public override ProblemCollection Check(TypeNode typeNode) { if (typeNode.Interfaces.Any()) { InterfaceNode foundServiceInterface = typeNode.Interfaces.First(i => i.FullName.EndsWith(".IBaseService")); if (foundServiceInterface!=null) { bool foundUsage = false; TypeNode serviceManagerTypeNode = foundServiceInterface.DeclaringModule.Types.First(t => t.FullName.EndsWith(".ServiceManager")); if (serviceManagerTypeNode != null) { Member member = serviceManagerTypeNode.Members.First(t => t.FullName.EndsWith(".RegisterAllServices")); var method = member as Method; if (method != null) { foundUsage = method.Instructions.Any(opcode => opcode.Value != null && opcode.Value.ToString().Contains(typeNode.FullName + "(")); } } if (!foundUsage) { Resolution resolution = GetResolution(typeNode.FullName); var problem = new Problem(resolution); Problems.Add(problem); } } } return Problems; }
public void Process(TypeNode node) { foreach (var propertyDefinition in node.TypeDefinition.Properties) { Read(propertyDefinition, node); } }
public override ProblemCollection Check(TypeNode type) { Type runtimeType = type.GetRuntimeType(); if ( IsTestFixture( runtimeType ) ) { System.Reflection.MethodInfo[] methods = runtimeType.GetMethods( BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly ); // Note that if an method with an invalid signature is marked as a setup method, then // it will be considered as not marked and hence setupMethod will be null. // Same applies for tearDownMethod. System.Reflection.MethodInfo setupMethod = Reflect.GetSetUpMethod( runtimeType ); System.Reflection.MethodInfo tearDownMethod = Reflect.GetTearDownMethod( runtimeType ); System.Reflection.MethodInfo fixtureSetupMethod = Reflect.GetFixtureSetUpMethod( runtimeType ); System.Reflection.MethodInfo fixtureTearDownMethod = Reflect.GetFixtureTearDownMethod( runtimeType ); foreach( System.Reflection.MethodInfo methodInfo in methods ) { if ( !IsTestCaseMethod( methodInfo ) && ( methodInfo != setupMethod ) && ( methodInfo != tearDownMethod ) && ( methodInfo != fixtureSetupMethod ) && ( methodInfo != fixtureTearDownMethod ) ) { Resolution resolution = GetResolution( methodInfo.Name ); Problem problem = new Problem( resolution ); base.Problems.Add( problem ); } } if ( base.Problems.Count > 0 ) return base.Problems; } return base.Check (type); }
/// <summary> /// Numeric, bool, DateTime, etc. types are safe from SQL/XSS injection. User-defined types composed entirely of safe types are also safe. /// </summary> protected bool IsTypeSafe(TypeNode t, HashSet<string> checkedTypes = null) { if (t == null) return true; if (checkedTypes == null) checkedTypes = new HashSet<string>(); else if (checkedTypes.Contains(t.FullName)) //don't recurse infinitely into self-referencing types return true; checkedTypes.Add(t.FullName); if (IsStringIsh(t) || (t.TemplateArguments != null && t.TemplateArguments.Any(a => IsStringIsh(a)))) return false; if (t.IsPrimitiveNumeric || t is EnumNode) return true; if (_maybeSafeGenericTypes.Any(a => t.IsDerivedFrom(a)) && t.TemplateArguments != null && t.TemplateArguments.All(a => IsTypeSafe(a, checkedTypes))) return true; if (_safeTypes.Contains(t.FullName)) return true; return t.Members.Where(w => w.Name.Name != "ToString").All(a => IsTypeSafe(a, checkedTypes)); }
void ProcessChildNode(TypeNode node, EventInvokerMethod eventInvoker) { var childEventInvoker = FindEventInvokerMethod(node.TypeDefinition); if (childEventInvoker == null) { if (node.TypeDefinition.BaseType.IsGenericInstance) { var methodReference = MakeGeneric(node.TypeDefinition.BaseType, eventInvoker.MethodReference); eventInvoker = new EventInvokerMethod { InvokerType = eventInvoker.InvokerType, MethodReference = methodReference, }; } } else { eventInvoker = childEventInvoker; } node.EventInvoker = eventInvoker; foreach (var childNode in node.Nodes) { ProcessChildNode(childNode, eventInvoker); } }
private static AssemblyNode GetTaskAssembly(TypeNode type) { AssemblyNode taskAssembly = null; // Check if the type's located in mscorlib TypeNode taskTypeNode = GetTypeNode(FrameworkAssemblies.Mscorlib, TaskNamespace, TaskGenericType); if (taskTypeNode != null) { taskAssembly = FrameworkAssemblies.Mscorlib; } else if (type.DeclaringModule.Name.Equals(TaskPortableAssembly)) { // If the type is a type in the portable assembly, no need to loop through the assembly references taskAssembly = type.DeclaringModule.ContainingAssembly; } else { AssemblyReference assemblyReference = type.DeclaringModule .AssemblyReferences .FirstOrDefault(reference => reference.Name.Equals(TaskPortableAssembly, StringComparison.Ordinal)); Contract.Assert(assemblyReference != null); taskAssembly = assemblyReference.Assembly; } Contract.Assert(taskAssembly != null); return taskAssembly; }
IEnumerable<OnChangedMethod> GetOnChangedMethods(TypeNode notifyNode) { var methods = notifyNode.TypeDefinition.Methods; var onChangedMethods = methods.Where(x => !x.IsStatic && !x.IsAbstract && //(IsNoArgOnChangedMethod(x) || //IsBeforeAfterOnChangedMethod(x)) && x.Name.StartsWith("On") && x.Name.EndsWith("Changed")); foreach (var methodDefinition in onChangedMethods) { var typeDefinitions = new Stack<TypeDefinition>(); typeDefinitions.Push(notifyNode.TypeDefinition); if (IsNoArgOnChangedMethod(methodDefinition)) { yield return new OnChangedMethod { OnChangedType = OnChangedTypes.NoArg, MethodReference = GetMethodReference(typeDefinitions, methodDefinition) }; } else if (IsBeforeAfterOnChangedMethod(methodDefinition)) { yield return new OnChangedMethod { OnChangedType = OnChangedTypes.BeforeAfter, MethodReference = GetMethodReference(typeDefinitions, methodDefinition) }; } } }
/// <param name="module">The module into which the duplicate IR will be grafted.</param> /// <param name="type">The type into which the duplicate Member will be grafted. Ignored if entire type, or larger unit is duplicated.</param> public Duplicator(Module/*!*/ module, TypeNode type) { this.TargetModule = module; this.TargetType = this.OriginalTargetType = type; this.DuplicateFor = new TrivialHashtable(); this.TypesToBeDuplicated = new TrivialHashtable(); //^ base(); }
public PropertyWeaver(MsCoreReferenceFinder msCoreReferenceFinder, Logger logger, PropertyData propertyData, TypeNode typeNode) { this.msCoreReferenceFinder = msCoreReferenceFinder; this.logger = logger; this.propertyData = propertyData; this.typeNode = typeNode; }
void ProcessChildNode(TypeNode node, MethodReference changedInvokerMethod) { var childEventInvoker = FindEventInvokerMethodRef(node.TypeDefinition); if (childEventInvoker == null) { if (changedInvokerMethod != null) { if (node.TypeDefinition.BaseType.IsGenericInstance) { var methodReference = MakeGeneric(node.TypeDefinition.BaseType, changedInvokerMethod); changedInvokerMethod = methodReference; } } } else { changedInvokerMethod = childEventInvoker; } node.IsChangedInvoker = changedInvokerMethod; foreach (var childNode in node.Nodes) { ProcessChildNode(childNode, changedInvokerMethod); } }
public override ProblemCollection Check(TypeNode type) { Type runtimeType = type.GetRuntimeType(); if ( IsTestFixture( runtimeType ) ) { System.Reflection.MethodInfo[] methods = runtimeType.GetMethods( BindingFlags.Instance | BindingFlags.Public ); foreach( MethodInfo method in methods ) { if ( !Reflect.HasTestAttribute( method ) && ( Reflect.HasExpectedExceptionAttribute( method ) || Reflect.HasIgnoreAttribute( method ) || Reflect.HasCategoryAttribute( method ) || Reflect.HasExplicitAttribute( method ) ) ) { Resolution resolution = GetResolution( method.Name ); Problem problem = new Problem( resolution ); base.Problems.Add( problem ); } } if ( base.Problems.Count > 0 ) return base.Problems; } return base.Check (type); }
void ProcessChildNode(TypeNode node, EventInvokerMethod eventInvoker) { var childEventInvoker = FindEventInvokerMethod(node.TypeDefinition); if (childEventInvoker == null) { if (node.TypeDefinition.BaseType.IsGenericInstance) { var methodReference = MakeGeneric(node.TypeDefinition.BaseType, eventInvoker.MethodReference); eventInvoker = new EventInvokerMethod { InvokerType = eventInvoker.InvokerType, MethodReference = methodReference, IsVisibleFromChildren = eventInvoker.IsVisibleFromChildren }; } } else { eventInvoker = childEventInvoker; } if (!eventInvoker.IsVisibleFromChildren) { var error = $"Cannot use '{eventInvoker.MethodReference.FullName}' in '{node.TypeDefinition.FullName}' since that method is not visible from the child class."; throw new WeavingException(error); } node.EventInvoker = eventInvoker; foreach (var childNode in node.Nodes) { ProcessChildNode(childNode, eventInvoker); } }
public static AttributeList GetCustomAttributes( Member member, TypeNode attrType ) { AttributeList result = null; if (member == null) return null; AttributeList attrs = member.Attributes; if( attrs != null ) { for( int i = 0; i < attrs.Count; i++ ) { AttributeNode an = attrs[i]; if (an == null) continue; MemberBinding mb = an.Constructor as MemberBinding; if( mb != null && mb.BoundMember != null && mb.BoundMember.DeclaringType == attrType ) { if( result == null ) { result = new AttributeList(); } result.Add(an); } } } if (result == null) { TypeNode tn = member as TypeNode; if (tn != null) return MetadataHelper.GetCustomAttributes(tn.BaseType, attrType); Property p = MetadataHelper.GetPropertyForMethod(member); if (p != null) return MetadataHelper.GetCustomAttributes(p, attrType); } return result; }
public PropertyWeaver(ModuleWeaver moduleWeaver, PropertyData propertyData, TypeNode typeNode, TypeSystem typeSystem ) { this.moduleWeaver = moduleWeaver; this.propertyData = propertyData; this.typeNode = typeNode; this.typeSystem = typeSystem; }
public override ProblemCollection Check(TypeNode type) { Type runtimeType = type.GetRuntimeType(); if ( IsTestFixture( runtimeType ) ) { string ignoreReason = Reflect.GetIgnoreReason( runtimeType ); if ( ignoreReason.Trim().Length == 0 ) { Resolution resolution = GetNamedResolution( "TestFixture", type.Name.Name ); Problem problem = new Problem( resolution ); base.Problems.Add( problem ); } System.Reflection.MethodInfo[] methods = runtimeType.GetMethods( BindingFlags.Instance | BindingFlags.Public ); foreach( MethodInfo method in methods ) { string methodIgnoreReason = Reflect.GetIgnoreReason( method ); if ( methodIgnoreReason.Trim().Length == 0 ) { string[] parameters = new string[] { type.Name.Name, method.Name }; Resolution resolution = GetNamedResolution( "TestCase", parameters ); Problem problem = new Problem( resolution ); base.Problems.Add( problem ); } } if ( base.Problems.Count > 0 ) return base.Problems; } return base.Check (type); }
public override ProblemCollection Check(TypeNode type) { Type runtimeType = type.GetRuntimeType(); if ( IsTestFixture( runtimeType ) ) { PropertyInfo[] properties; // check for instance public properties properties = runtimeType.GetProperties( BindingFlags.Instance | BindingFlags.Public ); foreach( PropertyInfo instanceProperty in properties ) { Resolution resolution = GetResolution( instanceProperty.DeclaringType.Name, instanceProperty.Name ); Problem problem = new Problem( resolution ); base.Problems.Add( problem ); } // check for static public properties, whether declared in the class // or one of its base classes. properties = runtimeType.GetProperties( BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy ); foreach( PropertyInfo staticProperty in properties ) { Resolution resolution = GetResolution( staticProperty.DeclaringType.Name, staticProperty.Name ); Problem problem = new Problem( resolution ); base.Problems.Add( problem ); } } if ( base.Problems.Count > 0 ) return base.Problems; return base.Check (type); }
public void ProcessDependsOnAttributes(TypeNode node) { foreach (var propertyDefinition in node.TypeDefinition.Properties) { ReadDependsOnData(propertyDefinition, node); } }
public override ProblemCollection Check(TypeNode type) { Type runtimeType = type.GetRuntimeType(); if ( IsTestFixture( runtimeType ) ) { // if more than one setup, trigger error. if ( GetTestSetupMethodsCount( runtimeType ) > 1 ) { Resolution resolution = GetNamedResolution( "SetUp", type.Name.Name ); Problem problem = new Problem( resolution ); base.Problems.Add( problem ); return base.Problems; } // if more than one setup, trigger error. if ( GetFixtureSetupMethodsCount( runtimeType ) > 1 ) { Resolution resolution = GetNamedResolution( "TestFixtureSetUp", type.Name.Name ); Problem problem = new Problem( resolution ); base.Problems.Add( problem ); return base.Problems; } } return base.Check (type); }
public TypeCache (string fullName) { this.cache_is_valid = false; this.have_type = false; this.cache = default(TypeNode); this.full_name = fullName; }
void ProcessField(TypeNode node, FieldDefinition field) { var name = field.Name; if (!field.IsPublic || field.IsStatic || !char.IsUpper(name, 0)) { return; } if (node.TypeDefinition.HasGenericParameters) { var message = string.Format("Skipped converting public field '{0}.{1}' to a property because generic types are not currently supported. You should make this a public property instead.", node.TypeDefinition.Name, field.Name); logger.LogWarning(message); return; } field.Name = string.Format("<{0}>k__BackingField", name); field.IsPublic = false; field.IsPrivate = true; var get = GetGet(field, name); node.TypeDefinition.Methods.Add(get); var set = GetSet(field, name); node.TypeDefinition.Methods.Add(set); var propertyDefinition = new PropertyDefinition(name, PropertyAttributes.None, field.FieldType) { GetMethod = get, SetMethod = set }; foreach (var customAttribute in field.CustomAttributes) { propertyDefinition.CustomAttributes.Add(customAttribute); } node.TypeDefinition.Properties.Add(propertyDefinition); ForwardedFields.Add(field, propertyDefinition); }
public override ProblemCollection Check(TypeNode type) { if (type == null) return Problems; if (!IsPresenterImplementation(type)) return Problems; var basePresenter = GetBasePresenterTypeNode(type); if (basePresenter == null) throw new InvalidOperationException("Failed to find WebFormsMvp.Presenter`1 even though we found WebFormsMvp.IPresenter."); var baseType = type; // We have an extra level of base type checking here so that we skip System.Object while (baseType.BaseType != null && baseType.BaseType.BaseType != null) { baseType = baseType.BaseType; } if (baseType.Template != basePresenter) { Problems.Add(new Problem( GetResolution(type.FullName)) { Certainty = 100, FixCategory = FixCategories.NonBreaking, MessageLevel = MessageLevel.Warning }); } return Problems; }
public override ProblemCollection Check(TypeNode type) { Type runtimeType = type.GetRuntimeType(); if ( IsTestFixture( runtimeType ) && !runtimeType.IsAbstract && type.IsVisibleOutsideAssembly ) { MemberList constructors = type.GetConstructors(); for ( int i = 0; i < constructors.Length; ++i ) { Member constructor = constructors[i]; // only examine non-static constructors Microsoft.Cci.InstanceInitializer instanceConstructor = constructor as Microsoft.Cci.InstanceInitializer; if ( instanceConstructor == null ) continue; // trigger errors for non-default constructors. if ( ( instanceConstructor.Parameters.Length != 0 ) && ( !instanceConstructor.IsPrivate ) ) { Resolution resolution = GetResolution( runtimeType.Name ); Problem problem = new Problem( resolution ); base.Problems.Add( problem ); } } if ( base.Problems.Count > 0 ) return base.Problems; } return base.Check (type); }
public override ProblemCollection Check(TypeNode type) { Type runtimeType = type.GetRuntimeType(); if ( IsTestFixture( runtimeType ) ) { System.Reflection.MethodInfo[] methods = runtimeType.GetMethods(); foreach( System.Reflection.MethodInfo methodInfo in methods ) { // if method starts with "test" and is not marked as [Test], // then an explicit [Test] should be added since NUnit will // treat it as a test case. if ( IsTestCaseMethod( methodInfo ) && !Reflect.HasTestAttribute( methodInfo ) ) { Resolution resolution = GetResolution( methodInfo.Name ); Problem problem = new Problem( resolution ); base.Problems.Add( problem ); } } if ( base.Problems.Count > 0 ) return base.Problems; } return base.Check (type); }
public ExistingTypeNodeUpdater(Lazy<IMethodAnnotations> methodAnnotations, ModuleDocumentNode modNode, MergedImportedType type) { targetType = type.TargetType; ownerModule = targetType.Module; origTypeDefOptions = new TypeDefOptions(targetType); newTypeDefOptions = type.NewTypeDefOptions; typeNode = modNode.Context.DocumentTreeView.FindNode(targetType); if (typeNode == null) throw new InvalidOperationException(); nestedTypes1 = type.NewOrExistingNestedTypes.OfType<MergedImportedType>().Select(a => new ExistingTypeNodeUpdater(methodAnnotations, modNode, a)).ToArray(); nestedTypes2 = type.NewOrExistingNestedTypes.OfType<NewImportedType>().Select(a => new NestedTypeNodeCreator(modNode, typeNode, a.TargetType)).ToArray(); if (nestedTypes1.Length + nestedTypes2.Length != type.NewOrExistingNestedTypes.Count) throw new InvalidOperationException(); fields = type.NewFields.Select(a => new FieldNodeCreator(modNode, typeNode, a)).ToArray(); var specialMethods = GetSpecialMethods(type); methods = type.NewMethods.Where(a => !specialMethods.Contains(a)).Select(a => new MethodNodeCreator(modNode, typeNode, a)).ToArray(); events = type.NewEvents.Select(a => new EventNodeCreator(modNode, typeNode, a)).ToArray(); properties = type.NewProperties.Select(a => new PropertyNodeCreator(modNode, typeNode, a)).ToArray(); editedFields = type.EditedFields.Select(a => new EditedFieldUpdater(modNode, a.OriginalField, a.FieldDefOptions)).ToArray(); editedMethods = type.EditedMethods.Select(a => new EditedMethodUpdater(methodAnnotations, modNode, a.OriginalMethod, a.NewBody, a.MethodDefOptions)).ToArray(); editedProperties = type.EditedProperties.Select(a => new EditedPropertyUpdater(modNode, a.OriginalProperty, a.PropertyDefOptions)).ToArray(); editedEvents = type.EditedEvents.Select(a => new EditedEventUpdater(modNode, a.OriginalEvent, a.EventDefOptions)).ToArray(); deletedTypes = type.DeletedNestedTypes.Select(a => new DeletedTypeUpdater(modNode, a)).ToArray(); deletedFields = type.DeletedFields.Select(a => new DeletedFieldUpdater(modNode, a)).ToArray(); deletedMethods = type.DeletedMethods.Select(a => new DeletedMethodUpdater(modNode, a)).ToArray(); deletedProperties = type.DeletedProperties.Select(a => new DeletedPropertyUpdater(modNode, a)).ToArray(); deletedEvents = type.DeletedEvents.Select(a => new DeletedEventUpdater(modNode, a)).ToArray(); }
/// <summary> /// Checks the specified type. /// </summary> /// <param name="type">The type.</param> /// <returns></returns> public override ProblemCollection Check(TypeNode type) { AttributeNode attribute = SemanticRulesUtilities.GetAttribute(type, ServiceContractAttribute); if (SemanticRulesUtilities.HasAttribute<ServiceContractAttribute>(attribute)) { List<string> duplicated = new List<string>(); foreach (Member member in type.Members) { if (SemanticRulesUtilities.GetAttribute(member, OperationContractAttribute) != null) { if (duplicated.Contains(member.Name.Name)) { Resolution resolution = base.GetResolution(member.FullName); Problem problem = new Problem(resolution, type.SourceContext); base.Problems.Add(problem); } else { duplicated.Add(member.Name.Name); } } } } return base.Problems; }
public override TypeNode VisitTypeNode(TypeNode typeNode) { TypeNode savedCurrentType = this.currentType; this.currentType = typeNode; TypeNode result = base.VisitTypeNode(typeNode); this.currentType = savedCurrentType; return result; }
public void Test() { var gen = new XmlResultsGenerator(null,null,null, null, null); var muSession = new MutationTestingSession(); var mutar = new MutationTarget(new MutationVariant()); var ass = new AssemblyNode("Assembly"); muSession.MutantsGrouped.Add(ass); var nodeNamespace = new TypeNamespaceNode(ass, "Namespace"); ass.Children.Add(nodeNamespace); var nodeType = new TypeNode(nodeNamespace, "Type"); nodeNamespace.Children.Add(nodeType); var nodeMethod = new MethodNode(nodeType, "Method", null, true); nodeType.Children.Add(nodeMethod); var nodeGroup = new MutantGroup("Gr1", nodeMethod); nodeMethod.Children.Add(nodeGroup); var nodeMutant = new Mutant("m1", nodeGroup, mutar); nodeGroup.Children.Add(nodeMutant); XDocument generateResults = gen.GenerateResults(muSession, false, false, ProgressCounter.Inactive(), CancellationToken.None).Result; Console.WriteLine(generateResults.ToString()); //gen. }
/// <summary> /// Checks the specified type. /// </summary> /// <param name="type">The type.</param> /// <returns></returns> public override ProblemCollection Check(TypeNode type) { AttributeNode attribute = SemanticRulesUtilities.GetAttribute(type, ServiceContractAttribute) ?? SemanticRulesUtilities.GetAttribute(type, OperationContractAttribute); return CheckForProblems(attribute); }
public static bool IsDataContractNesscery(TypeNode typeNode) { return !Helper.IsPrimitive(typeNode) && typeNode.FullName != typeof(void).FullName && !Helper.IsNullablePrimitive(typeNode) && !(typeNode.Template != null && typeNode.Template.FullName == typeof(List<>).FullName) ; }
public static PropertyNode GetPropertyFromParent(Identifier id, TypeNode typeNode) { if (typeNode == null) { return null; } return typeNode.GetProperty(id) ?? GetPropertyFromParent(id, typeNode.BaseType); }
internal static IndexerNode Indexer(ListNode attributes, ModifiersNode modifiers, TypeNode type, IdentNode name, ListNode formal_params, ListNode accessors, Symbol s) { IndexerNode res = new IndexerNode(); res.kind = Kind.Indexer; res.start = s.pos; res.end = s.endpos; res.attributes = attributes; res.modifiers = modifiers; res.type = type; res.name = name; res.formal_params = formal_params; res.accessors = accessors; return(res); }
internal static NodeInfo Create(TypeNode node) { return(new NodeInfo(NodeType.Type, node.FilterType.Name)); }
public ExpressionOperator LoadConst(TExpr pc, TypeNode type, object constant, TVar dest, TExpr data) { return(ExpressionOperator.Constant); }
public ExpressionOperator Isinst(TExpr pc, TypeNode type, TVar dest, TExpr obj, TExpr data) { return(ExpressionOperator.Unknown); }
public ExpressionType Isinst(TExpr pc, TypeNode type, TVar dest, TExpr obj, Dummy data) { return(ExpressionType.Unknown); }
private static void AppendTextForTypeNode([NotNull] WriteContext context, [NotNull] TypeNode type) { switch (type.NodeType) { case NodeType.Class: case NodeType.Interface: case NodeType.Struct: case NodeType.EnumNode: case NodeType.DelegateNode: WriteOrdinaryType(context, type, false); break; case NodeType.Reference: WriteReferenceType(context, type); break; case NodeType.Pointer: WritePointerType(context, type); break; case NodeType.ClassParameter: case NodeType.TypeParameter: WriteGenericParameter(context, type); break; case NodeType.ArrayType: WriteArray(context, type); break; case NodeType.FunctionPointer: WriteCppCliTypes(context, type); break; case NodeType.RequiredModifier: WriteRequiredModifier(context, type); break; case NodeType.OptionalModifier: WriteOptionalModifier(context, type); break; default: throw new NotSupportedException(string.Format("Unsupported NodeType '{0}'.", type.NodeType)); } if (type.IsGeneric && type.TemplateArguments != null && type.TemplateArguments.Count != 0) { // Undocumented: based on output from MS compilers. context.TextBuilder.Append('{'); bool comma = false; foreach (TypeNode templateArgumentType in type.TemplateArguments) { if (comma) { context.TextBuilder.Append(','); } AppendTextForTypeNode(context, templateArgumentType); comma = true; } context.TextBuilder.Append('}'); } }
public static bool HasCustomAttribute(Member member, TypeNode attrType) { return(GetCustomAttribute(member, attrType) != null); }
internal static MethodDecl Method(Kind k, ListNode attributes, ModifiersNode modifiers, IdentNode name, TypeNode return_type, ListNode parameters, StatementNode body, ConstructorInitializerNode base_init, Symbol s) { MethodDecl res = new MethodDecl(); res.kind = k; res.start = s.pos; res.end = s.endpos; res.attributes = attributes; res.modifiers = modifiers; res.name = name; res.return_type = return_type; res.parameters = parameters; res.body = body; res.base_init = base_init; return(res); }
internal static DelegateNode Delegate(ListNode attributes, ModifiersNode modifiers, IdentNode name, TypeNode return_type, ListNode parameters, Symbol s) { DelegateNode res = new DelegateNode(); res.kind = Kind.Delegate; res.start = s.pos; res.end = s.endpos; res.attributes = attributes; res.modifiers = modifiers; res.name = name; res.return_type = return_type; res.parameters = parameters; return(res); }
internal static FieldsDecl Fields(Kind k, ListNode attributes, ModifiersNode modifiers, TypeNode type, ListNode declarators, Symbol s) { FieldsDecl res = new FieldsDecl(); res.kind = k; res.start = s.pos; res.end = s.endpos; res.attributes = attributes; res.modifiers = modifiers; res.type = type; res.declarators = declarators; return(res); }
internal static ParameterNode Parameter(ListNode attributes, ModifiersNode modifiers, TypeNode type, IdentNode name, Symbol s) { ParameterNode res = new ParameterNode(); res.kind = Kind.Param; res.start = s.pos; res.end = s.endpos; res.attributes = attributes; res.modifiers = modifiers; res.type = type; res.name = name; return(res); }
/// <summary> /// Creates a convert operation. /// </summary> /// <param name="location">The current location.</param> /// <param name="node">The operand.</param> /// <param name="targetType">The target type.</param> /// <param name="flags">Operation flags.</param> /// <returns>A node that represents the convert operation.</returns> public ValueReference CreateConvert( Location location, Value node, TypeNode targetType, ConvertFlags flags) { // Check for identity conversions if (node.Type == targetType) { return(node); } // Check for int to pointer casts if (targetType is PointerType pointerType && pointerType.ElementType.IsVoidType) { return(CreateIntAsPointerCast( location, node)); } location.Assert(targetType.BasicValueType != BasicValueType.None); if (!(targetType is PrimitiveType targetPrimitiveType)) { throw location.GetNotSupportedException( ErrorMessages.NotSupportedConversion, node.Type, targetType); } bool isSourceUnsigned = (flags & ConvertFlags.SourceUnsigned) == ConvertFlags.SourceUnsigned; bool isTargetUnsigned = (flags & ConvertFlags.TargetUnsigned) == ConvertFlags.TargetUnsigned; // Match nested conversions if (node is ConvertValue convert) { var targetBasicType = targetPrimitiveType.BasicValueType; if (targetBasicType.IsInt() && convert.SourceType == targetBasicType.GetArithmeticBasicValueType( isTargetUnsigned)) { return(convert.Value); } var sourceBasicType = convert.BasicValueType; if (sourceBasicType.IsInt() && convert.Value.BasicValueType < sourceBasicType) { ConvertFlags newFlags = (convert.Flags & ~ConvertFlags.TargetUnsigned) | flags & ~(ConvertFlags.SourceUnsigned | ConvertFlags.OverflowSourceUnsigned); return(CreateConvert( location, convert.Value, targetType, newFlags)); } } // Match X to bool if (targetPrimitiveType.IsBool) { return(CreateCompare( location, node, CreatePrimitiveValue( location, node.BasicValueType, 0), CompareKind.NotEqual)); } // Match bool to X else if (node.BasicValueType == BasicValueType.Int1) { return(CreatePredicate( location, node, CreatePrimitiveValue( location, targetPrimitiveType.BasicValueType, 1), CreatePrimitiveValue( location, targetPrimitiveType.BasicValueType, 0))); } // Match primitive types if (node is PrimitiveValue value) { var targetBasicValueType = targetType.BasicValueType; switch (value.BasicValueType) { case BasicValueType.Int1: return(targetBasicValueType switch { BasicValueType.Float16 => CreatePrimitiveValue( location, value.Int1Value ? Half.One : Half.Zero), BasicValueType.Float32 => CreatePrimitiveValue( location, Convert.ToSingle(value.Int1Value)), BasicValueType.Float64 => CreatePrimitiveValue( location, Convert.ToDouble(value.Int1Value)), _ => CreatePrimitiveValue( location, targetBasicValueType, value.Int1Value ? 1 : 0), });
internal static PropertyNode Property(ListNode attributes, ModifiersNode modifiers, TypeNode type, IdentNode name, ListNode accessors, Symbol s) { PropertyNode res = new PropertyNode(); res.kind = Kind.Property; res.start = s.pos; res.end = s.endpos; res.attributes = attributes; res.modifiers = modifiers; res.type = type; res.name = name; res.accessors = accessors; return(res); }
private static void WritePointerType([NotNull] WriteContext context, [NotNull] TypeNode type) { AppendTextForTypeNode(context, ((Pointer)type).ElementType); context.TextBuilder.Append('*'); }
private static void WriteReferenceType([NotNull] WriteContext context, [NotNull] TypeNode type) { AppendTextForTypeNode(context, ((Reference)type).ElementType); context.TextBuilder.Append('@'); }
/// <summary> /// Creates a new array type. /// </summary> /// <param name="elementType">The element type.</param> /// <param name="dimensions">The number of array dimensions.</param> /// <returns>The created array type.</returns> public TypeNode CreateArrayType(TypeNode elementType, int dimensions) => TypeContext.CreateArrayType(elementType, dimensions);
public StreamValueNode(ValueNode parent, string name, TypeNode typeNode) : base(parent, name, typeNode) { }
/// <summary> /// Creates a view type. /// </summary> /// <param name="elementType">The view element type.</param> /// <param name="addressSpace">The address space.</param> /// <returns>The created view type.</returns> public ViewType CreateViewType( TypeNode elementType, MemoryAddressSpace addressSpace) => TypeContext.CreateViewType(elementType, addressSpace);
/// <summary> /// Creates a pointer type. /// </summary> /// <param name="elementType">The pointer element type.</param> /// <param name="addressSpace">The address space.</param> /// <returns>The created pointer type.</returns> public PointerType CreatePointerType( TypeNode elementType, MemoryAddressSpace addressSpace) => TypeContext.CreatePointerType(elementType, addressSpace);
private static void SplitIRAndState(ControlInfoJson.Item control, string topParentName, int index, EditorStateStore stateStore, TemplateStore templateStore, Entropy entropy, out BlockNode controlIR) { // Bottom up, recursively process children var children = new List <BlockNode>(); var childIndex = 0; foreach (var child in control.Children) { SplitIRAndState(child, topParentName, childIndex, stateStore, templateStore, entropy, out var childBlock); children.Add(childBlock); ++childIndex; } var isComponentDef = control.Template.IsComponentDefinition ?? false; var customPropsToHide = new HashSet <string>(); var functions = new List <FunctionNode>(); if (control.Template.CustomProperties?.Any() ?? false) { if (!isComponentDef) { // Skip component property params on instances customPropsToHide = new HashSet <string>(control.Template.CustomProperties .Where(customProp => customProp.IsFunctionProperty) .SelectMany(customProp => customProp.PropertyScopeKey.PropertyScopeRulesKey .Select(propertyScopeRule => propertyScopeRule.Name) )); } else { // Create FunctionNodes on def foreach (var customProp in control.Template.CustomProperties.Where(prop => prop.IsFunctionProperty)) { var name = customProp.Name; customPropsToHide.Add(name); var expression = control.Rules.First(rule => rule.Property == name).InvariantScript; var expressionNode = new ExpressionNode() { Expression = expression }; var resultType = new TypeNode() { TypeName = customProp.PropertyDataTypeKey }; var args = new List <TypedNameNode>(); var argMetadata = new List <ArgMetadataBlockNode>(); foreach (var arg in customProp.PropertyScopeKey.PropertyScopeRulesKey) { customPropsToHide.Add(arg.Name); args.Add(new TypedNameNode() { Identifier = arg.ScopeVariableInfo.ScopeVariableName, Kind = new TypeNode() { TypeName = ((PropertyDataType)arg.ScopeVariableInfo.ScopePropertyDataType).ToString() } }); argMetadata.Add(new ArgMetadataBlockNode() { Identifier = arg.ScopeVariableInfo.ScopeVariableName, Default = new ExpressionNode() { Expression = arg.ScopeVariableInfo.DefaultRule.Replace("\r\n", "\n").Replace("\r", "\n").TrimStart() }, }); arg.ScopeVariableInfo.DefaultRule = null; arg.ScopeVariableInfo.ScopePropertyDataType = null; arg.ScopeVariableInfo.ParameterIndex = null; arg.ScopeVariableInfo.ParentPropertyName = null; } argMetadata.Add(new ArgMetadataBlockNode() { Identifier = PAConstants.ThisPropertyIdentifier, Default = new ExpressionNode() { Expression = expression.Replace("\r\n", "\n").Replace("\r", "\n").TrimStart(), }, }); functions.Add(new FunctionNode() { Args = args, Metadata = argMetadata, Identifier = name }); } } } var properties = new List <PropertyNode>(); var propStates = new List <PropertyState>(); foreach (var property in control.Rules) { var(prop, state) = SplitProperty(property); propStates.Add(state); if (customPropsToHide.Contains(property.Property)) { continue; } properties.Add(prop); } controlIR = new BlockNode() { Name = new TypedNameNode() { Identifier = control.Name, Kind = new TypeNode() { TypeName = control.Template.TemplateDisplayName ?? control.Template.Name, OptionalVariant = string.IsNullOrEmpty(control.VariantName) ? null : control.VariantName } }, Children = children, Properties = properties, Functions = functions, }; if (templateStore.TryGetTemplate(control.Template.Name, out var templateState)) { if (isComponentDef) { templateState.IsComponentTemplate = true; templateState.CustomProperties = control.Template.CustomProperties; } } else { templateState = new CombinedTemplateState(control.Template); templateState.ComponentDefinitionInfo = null; var templateName = templateState.TemplateDisplayName ?? templateState.Name; templateStore.AddTemplate(templateName, templateState); } entropy.ControlUniqueIds.Add(control.Name, int.Parse(control.ControlUniqueId)); var controlState = new ControlState() { Name = control.Name, PublishOrderIndex = control.PublishOrderIndex, TopParentName = topParentName, Properties = propStates, StyleName = control.StyleName, ExtensionData = control.ExtensionData, ParentIndex = index, IsComponentDefinition = control.Template.IsComponentDefinition, }; stateStore.TryAddControl(controlState); }
public ExpressionType Sizeof(TExpr pc, TypeNode type, TVar dest, Dummy data) { return(ExpressionType.Int32); }
public ValueValueNode(Node parent, string name, TypeNode typeNode) : base(parent, name, typeNode) { }
public ExpressionOperator Sizeof(TExpr pc, TypeNode type, TVar dest, TExpr data) { return(ExpressionOperator.SizeOf); }
internal override void SerializeOverride(BoundedStream stream, EventShuttle eventShuttle) { Serialize(stream, BoundValue, TypeNode.GetSerializedType()); }
/// <summary> /// Creates a node that represents an undefined value of /// the given type. /// </summary> /// <param name="type">The type.</param> /// <returns>A reference to the requested value.</returns> public ValueReference CreateUndefined(TypeNode type) { Debug.Assert(type != null, "Invalid type node"); return(new UndefinedValue(BasicBlock, type)); }
public static Parameter[] GetParameters(this ConstructorDeclarationSyntax syntax, TypeNode parent) { var hierachy = parent.GetTypeParameterHierachy(); var typeConverter = new TypeSyntaxConverter(hierachy); return(syntax?.ParameterList.Parameters.Select(x => ToParameter(x, typeConverter)).ToArray()); }
public ObjectValueNode(ValueNode parent, string name, TypeNode typeNode) : base(parent, name, typeNode) { }
internal static EventNode Event(Kind k, ListNode attributes, ModifiersNode modifiers, TypeNode type, IdentNode name, ListNode accessors, ListNode vars, Symbol s) { EventNode res = new EventNode(); res.kind = k; res.start = s.pos; res.end = s.endpos; res.attributes = attributes; res.modifiers = modifiers; res.type = type; res.name = name; res.accessors = accessors; res.vars = vars; return(res); }
public FieldNode(string name, TypeNode type, string jsonPropertyName = null) { Name = name; Type = type; JsonPropertyName = jsonPropertyName; }
/// <summary> /// Creates alignment information for global pointer and view types. /// </summary> protected override AnalysisValue <int>?TryProvide(TypeNode typeNode) => typeNode is IAddressSpaceType ? Create(InitialValue, typeNode) : (AnalysisValue <int>?)null;