// // See if the method is a default constructor – constructor that does nothing // except call the constructor in its base class, usually inserted into your // assemblies by the compiler. // private bool IsDefaultCtor(Method method) { InstructionCollection ops = method.Instructions; if (ops.Count.Equals(4)) { // // Filter out default ctor generated by the compiler. // LocalCollection localList = ops[0].Value as LocalCollection; if (localList != null && localList.Count != 0) { return(false); } if (ops[1].OpCode != OpCode.Ldarg_0) { return(false); } if (ops[2].OpCode != OpCode.Call) { return(false); } InstanceInitializer init = ops[2].Value as InstanceInitializer; if (init == null) { return(false); } if (ops[3].OpCode != OpCode.Ret) { return(false); } return(true); } return(false); }
private void CopyMissingMembers() { Contract.Ensures(this.duplicatedMembers != null); this.duplicatedMembers = new TrivialHashtable(this.toBeDuplicatedMembers.Count * 2); foreach (var missing in this.toBeDuplicatedMembers) { Contract.Assume(missing.Value != null); Contract.Assume(missing.Key != null); InstanceInitializer ctor = missing.Key as InstanceInitializer; if (ctor != null && ctor.ParameterCount == 0) { continue; } var targetType = missing.Value; Trace("COPYOOB: copying {0} to {1}", missing.Key.FullName, targetType.FullName); this.Duplicator.TargetType = targetType; var dup = (Member)this.Duplicator.Visit(missing.Key); targetType.Members.Add(dup); duplicatedMembers[missing.Key.UniqueKey] = missing; } }
public TDefinition Instantiate <TDefinition>(Action <IGeneratorScope, TDefinition> init, string name = null, bool propertyOnly = false) where TDefinition : class { if (name == null) { name = Util.Utility.GenerateVariableName(); } using (var newScope = new InstanceInitializerScope(Generator, typeof(TDefinition), name, this, propertyOnly)) { Codes.Add(newScope); var nameAttr = typeof(TDefinition).GetCustomAttribute <NameAttribute>(); string entryCode = nameAttr?.Name ?? "{ }"; ICodeConstruct target = null; if (propertyOnly) { target = new InstancePropertyInitializer(newScope, typeof(TDefinition), name); } else { target = new InstanceInitializer(newScope, typeof(TDefinition), name, entryCode, new object[] { }); } var definition = new Interceptor <TDefinition>(Generator, target).GetProxy(newScope); init(newScope, definition); return(definition); } }
public override Expression VisitMemberBinding(MemberBinding memberBinding) { Expression e = base.VisitMemberBinding(memberBinding); if (memberBinding.TargetObject == null && memberBinding.BoundMember is InstanceInitializer) { // This is seen if there is a call to new T(...) within an expression if (e.Type == null) { InstanceInitializer ctor = memberBinding.BoundMember as InstanceInitializer; e.Type = ctor.DeclaringType; } } return(e); }
internal static void Initialize() { RuntimeAssembly = Runtime.GetRuntimeAssembly(); PostCompilationPluginAttributeType = RuntimeAssembly.GetType(Identifier.For("Microsoft.SpecSharp"), Identifier.For("PostCompilationPluginAttribute")); ObjectConstructor = SystemTypes.Object.GetConstructor(); IListAdd = SystemTypes.IList.GetMethod(StandardIds.Add, SystemTypes.Object); #if CCINamespace const string ContractsNs = "Microsoft.Contracts"; #else const string ContractsNs = "Microsoft.Contracts"; #endif MustOverrideAttribute = (Class)GetCompilerRuntimeTypeNodeFor(ContractsNs, "MustOverrideAttribute"); }
private static InstanceInitializer CreateConstructor(Class closureClass) { var ctor = new InstanceInitializer(closureClass, null, null, null); ctor.CallingConvention = CallingConventionFlags.HasThis; ctor.Flags |= MethodFlags.Public | MethodFlags.HideBySig; // Regular block that calls base class constructor ctor.Body = new Block( new StatementList( new ExpressionStatement( new MethodCall(new MemberBinding(ctor.ThisParameter, SystemTypes.Object.GetConstructor()), new ExpressionList())), new Return())); return(ctor); }
/// <summary>Visits a constructor invocation.</summary> /// <param name="cons">Construction.</param> /// <returns>Resulting expression to visit.</returns> public override void VisitConstruct(Construct cons) { InstanceInitializer init = ConstructAsInstanceInitializer(cons); if (init != null) { CheckMethod(init, x => x.DeclaringType.FullName == "System.CodeDom.CodeTypeReference" && !HasParameterType(x, "System.CodeDom.CodeTypeReferenceOptions"), methodUnderCheck.FullName); CheckMethod(init, x => x.DeclaringType.FullName == "System.CodeDom.CodeTypeReferenceExpression" && !HasParameterType(x, "System.CodeDom.CodeTypeReference"), methodUnderCheck.FullName); CheckMethod(init, x => x.DeclaringType.FullName == "System.CodeDom.CodeParameterDeclaration" && !HasParameterType(x, "System.CodeDom.CodeTypeReference"), methodUnderCheck.FullName); CheckMethod(init, x => x.DeclaringType.FullName == "System.CodeDom.CodeMemberField" && !HasParameterType(x, "System.CodeDom.CodeTypeReference"), methodUnderCheck.FullName); CheckMethod(init, x => x.DeclaringType.FullName == "System.CodeDom.CodeArrayCreateExpression" && !HasParameterType(x, "System.CodeDom.CodeTypeReference"), methodUnderCheck.FullName); CheckMethod(init, x => x.DeclaringType.FullName == "System.CodeDom.CodeCastExpression" && !HasParameterType(x, "System.CodeDom.CodeTypeReference"), methodUnderCheck.FullName); CheckMethod(init, x => x.DeclaringType.FullName == "System.CodeDom.CodeObjectCreateExpression" && !HasParameterType(x, "System.CodeDom.CodeTypeReference"), methodUnderCheck.FullName); } base.VisitConstruct(cons); }
private void WriteContentPropertyData(XmlWriter writer, object info) { TypeNode type = (TypeNode)info; if (contentProperties.ContainsKey(type)) { // get default constructors InstanceInitializer constructor = type.GetConstructor(new TypeNode[0]); if ((constructor != null) && (!constructor.IsPublic)) { constructor = null; } if (constructor != null) { writer.WriteAttributeString("defaultConstructor", mrw.ApiNamer.GetMemberName(constructor)); } } }
public override InstanceInitializer InjectDefaultConstructor(TypeNode typeNode) { if (this.DontInjectDefaultConstructors || typeNode.IsNormalized) { return(null); } Class Class = typeNode as Class; if (Class != null && Class.Name != null && !(Class is ClassParameter) && ClassHasNoExplicitConstructors(typeNode)) { if (Class.IsAbstractSealedContainerForStatics) { return(null); } if (Class.PartiallyDefines != null) { this.InjectDefaultConstructor(Class.PartiallyDefines); InstanceInitializer defCons = Class.PartiallyDefines.GetConstructor(); if (defCons != null && !defCons.HasCompilerGeneratedSignature) { defCons = null; //Not an orphan } if (defCons != null) { //This is an injected default constructor that is an orphan, adopt it defCons.HasCompilerGeneratedSignature = false; //abuse this flag to stop other partial types from adopting it Class.Members.Add(defCons); Class.BaseClass = ((Class)Class.PartiallyDefines).BaseClass; } return(defCons); //Ok if defCons null, this type should not show up in inheritance chains } else { //Inject a default constructor This thisParameter = new This(Class); Class baseClass = Class.BaseClass; StatementList statements = new StatementList(2); statements.Add(new FieldInitializerBlock(typeNode, false)); if (baseClass != null) { MethodCall mcall = new MethodCall(new QualifiedIdentifier(new Base(), StandardIds.Ctor, typeNode.Name.SourceContext), null); mcall.SourceContext = typeNode.Name.SourceContext; ExpressionStatement callSupCons = new ExpressionStatement(mcall); callSupCons.SourceContext = typeNode.Name.SourceContext; statements.Add(callSupCons); } InstanceInitializer defCons = new InstanceInitializer(typeNode, null, null, new Block(statements)); defCons.Name = new Identifier(".ctor", typeNode.Name.SourceContext); defCons.SourceContext = typeNode.Name.SourceContext; defCons.ThisParameter = thisParameter; if (typeNode.IsAbstract) { defCons.Flags |= MethodFlags.Family | MethodFlags.HideBySig; } else { defCons.Flags |= MethodFlags.Public | MethodFlags.HideBySig; } defCons.CallingConvention = CallingConventionFlags.HasThis; defCons.IsCompilerGenerated = true; typeNode.Members.Add(defCons); return(defCons); } } return(null); }
private void ProcessType(StatementList setupInteropStatements, Set<DelegateNode> accumDelegateTypes, TypeNode type) { try { var style = env.InteropManager.Style(null, type); if (style == InteropStyle.Delegate) { var delType = (DelegateNode)type; var di = env.InteropManager.DelegateInfo(null, delType); env.Log(new InteropInfoMessage(RewriterMsgContext.Type(type), "Registering type as: " + style)); setupInteropStatements.Add (new ExpressionStatement (new MethodCall (new MemberBinding (DatabaseExpression(), env.InteropDatabase_RegisterTypeMethod), new ExpressionList (TypeOfExpression(type), new Literal((int)style, env.IntType), new Literal(null, env.StringType), new Literal(null, env.StringType), new Literal(0, env.IntType), new Literal(di.CaptureThis, env.BooleanType), new Literal(di.InlineParamsArray, env.BooleanType), new Literal(false, env.BooleanType))))); } else if (style == InteropStyle.Proxied || style == InteropStyle.Keyed) { // Append to <Module>::SetupInterop(): // InteropContextManager.Database.RegisterType( // <index of type>, // Keyed or Proxied, // <JavaScript fragment for key field, or null>, // <JavaScript type classifier function, or null>, // <steps to root type>, // false); var rootTypeSteps = env.InteropManager.RootTypeSteps(null, type); var undefinedIsNotNull = false; var keyFieldStr = default(string); var classifierStr = default(string); if (rootTypeSteps == 0) { if (style == InteropStyle.Keyed) keyFieldStr = env.InteropManager.KeyField(null, type).ToString(false); var classifierJS = env.InteropManager.TypeClassifier(null, type); classifierStr = classifierJS == null ? null : classifierJS.ToString(false); } if (style == InteropStyle.Proxied) undefinedIsNotNull = env.InteropManager.UndefinedIsNotNull(null, type); env.Log(new InteropInfoMessage(RewriterMsgContext.Type(type), "Registering type as: " + style.ToString())); setupInteropStatements.Add (new ExpressionStatement (new MethodCall (new MemberBinding (DatabaseExpression(), env.InteropDatabase_RegisterTypeMethod), new ExpressionList (TypeOfExpression(type), new Literal((int)style, env.IntType), new Literal(keyFieldStr, env.StringType), new Literal(classifierStr, env.StringType), new Literal(rootTypeSteps, env.IntType), new Literal(false, env.BooleanType), new Literal(false, env.BooleanType), new Literal(undefinedIsNotNull, env.BooleanType))))); // Create default importing constructor if none supplied by user // - If derive from base with default importing constructor, invoke that. // - If derive from 'Normal' base with default constructor, invoke that. // - Otherwise error var importingCtor = DefaultImportingConstructor(type); if (importingCtor == null) { var thisExpr = new ThisBinding(ThisExpression(type), type.SourceContext); var parameters = new ParameterList(1); parameters.Add(new Parameter(Identifier.For("ctxt"), env.JSContextType)); var statements = new StatementList(1); var baseType = type.BaseType; if (baseType == null) // Object is 'Normal', so this is never possible throw new InvalidOperationException("no base type"); var baseDefaultImportingCtor = DefaultImportingConstructor(baseType); if (baseDefaultImportingCtor != null) { env.Log(new InteropInfoMessage(RewriterMsgContext.Type(type), "Created default importing constructor chained from base type's default importing constructor")); statements.Add (new ExpressionStatement (new MethodCall (new MemberBinding(thisExpr, baseDefaultImportingCtor), new ExpressionList (new ParameterBinding(parameters[0], type.SourceContext))))); } else { if (env.InteropManager.Style(null, baseType) == InteropStyle.Normal) { var baseDefaultCtor = baseType.GetConstructor(); if (baseDefaultCtor == null) { env.Log(new InteropInfoMessage (RewriterMsgContext.Type(type), "Cannot create a default importing constructor for type, since it derives from a type with state 'ManagedOnly' which does not contain a default constructor")); throw new DefinitionException(); } env.Log(new InteropInfoMessage(RewriterMsgContext.Type(type), "Created default importing constructor chained from base type's default constructor")); statements.Add (new ExpressionStatement (new MethodCall (new MemberBinding(thisExpr, baseDefaultCtor), new ExpressionList(0)))); } else { var hkType = default(TypeNode); var classTypeArguments = default(Seq<TypeNode>); ExplodeTypeApplication(baseType, out hkType, out classTypeArguments); if (classTypeArguments != null && classTypeArguments.Count > 0) { env.Log(new InteropInfoMessage (RewriterMsgContext.Type(type), "Cannot create a default importing constructor for type, since it derives from an instance of a higher-kinded type without an explicit default importing constructor. (This limitation will be removed in the future.)")); } else { env.Log(new InteropInfoMessage (RewriterMsgContext.Type(type), "Cannot create a default importing constructor for type, since it derives from a type with state 'ManagedAndJavaScript' or 'JavaScriptOnly', and that type does not contain a default importing constructor")); } throw new DefinitionException(); } } statements.Add(new Return()); importingCtor = new InstanceInitializer (type, new AttributeList(0), parameters, new Block(statements)); importingCtor.Flags |= MethodFlags.Public; importingCtor.DeclaringType = type; TagAsCompilerGenerated(importingCtor); // il2jsc can compile this importing ctor as if it were written by the user, // so no need for any 'InteropGenerated' attribute. type.Members.Add(importingCtor); } } // Remember: a type containing only static imports/exports may appear 'Normal' if (style == InteropStyle.Normal || style == InteropStyle.Primitive || style == InteropStyle.Proxied || style == InteropStyle.Keyed) { foreach (var member in type.Members) { var nestedType = member as TypeNode; if (nestedType != null) ProcessType(setupInteropStatements, accumDelegateTypes, nestedType); else { var method = member as Method; if (method != null) ProcessMethod(setupInteropStatements, accumDelegateTypes, method); } } } } catch (DefinitionException) { env.Log(new InvalidInteropMessage(RewriterMsgContext.Type(type), "Type contains interop specification errors")); } }
/// <summary> /// Returns the namespace of an object /// </summary> /// <param name="value"></param> /// <returns></returns> protected void TestObjectNamespaces(object value, Action <string> namespaceActionTest) { if (value is Expression) { //Expression type is in Type.Fullname Expression expressionValue = value as Expression; TestObjectNamespaces(expressionValue.Type, namespaceActionTest); } else if (value is TypeNode) { //Typenodes use Fullname TypeNode typeNodeValue = value as TypeNode; if (typeNodeValue.IsGeneric) { if (typeNodeValue.Template != null) { namespaceActionTest(typeNodeValue.Template.FullName); } if (typeNodeValue.StructuralElementTypes != null) { foreach (TypeNode structuralElementType in typeNodeValue.StructuralElementTypes) { TestObjectNamespaces(structuralElementType, namespaceActionTest); } } } else { namespaceActionTest(typeNodeValue.FullName); } } else if (value is InstanceInitializer) { InstanceInitializer instanceInitializerValue = value as InstanceInitializer; TestObjectNamespaces(instanceInitializerValue.DeclaringType, namespaceActionTest); } else if (value is Method) { Method methodValue = value as Method; TestObjectNamespaces(methodValue.DeclaringType, namespaceActionTest); foreach (Parameter parameter in methodValue.Parameters) { TestObjectNamespaces(parameter.Type, namespaceActionTest); } if (methodValue.IsGeneric) { if (methodValue.TemplateArguments != null) { foreach (TypeNode genericType in methodValue.TemplateArguments) { TestObjectNamespaces(genericType, namespaceActionTest); } } if (methodValue.TemplateParameters != null) { foreach (TypeNode genericType in methodValue.TemplateParameters) { TestObjectNamespaces(genericType, namespaceActionTest); } } } } else if (value is Node) { //Everything else returns the type from ToString() namespaceActionTest(value.ToString()); } else { //non-FxCop objects return the value of their type namespaceActionTest(value.GetType().FullName); } }
private void FixupNewlyConstructedObjectDelay(InitializedVariables iv, Variable receiver, InstanceInitializer ctor) { if (receiver == null) return; if (ctor == null) return; }
/// <summary> /// Write out a constructor name /// </summary> /// <param name="constructor">The constructor for which to write out the name</param> /// <param name="sb">The string builder to which the name is written</param> private static void WriteConstructor(InstanceInitializer constructor, StringBuilder sb) { WriteType(constructor.DeclaringType, sb); sb.Append(".#ctor"); WriteParameters(constructor.Parameters, sb); }
/// <summary> /// <para> /// Serializes the expressions in toSerialize to an attribute determined by ctor, as if they come from module containingModule. /// Uses the SourceContext information of <param name="sc">sc</param> for the source context for the attribute. /// </para> /// <para><code> /// requires ctor != null && sc != null; /// </code></para> /// <para><code> /// requires ctor.DeclaringType <: Microsoft.Contracts.AttributeWithContext; /// </code></para> /// </summary> /// <returns></returns> public static AttributeNode SerializeExpressions(InstanceInitializer/*!*/ ctor, ExpressionList dontSerialize, ExpressionList toSerialize, SourceContext/*!*/ sc, Module containingModule) { MemberBinding attrBinding = new MemberBinding(null, ctor); ExpressionList args = new ExpressionList(); if (dontSerialize != null) { foreach (Expression e in dontSerialize) { args.Add(e); } } if (toSerialize != null) { foreach (Expression e in toSerialize) { ContractSerializer cs = new ContractSerializer(containingModule); cs.Visit(e); string val = cs.SerializedContract; args.Add(new Literal(val, SystemTypes.String)); } } if (sc.SourceText != null) { args.Add(new NamedArgument(Identifier.For("Filename"), new Literal(sc.Document.Name, SystemTypes.String))); args.Add(new NamedArgument(Identifier.For("StartLine"), new Literal(sc.StartLine, SystemTypes.Int32))); args.Add(new NamedArgument(Identifier.For("StartColumn"), new Literal(sc.StartColumn, SystemTypes.Int32))); args.Add(new NamedArgument(Identifier.For("EndLine"), new Literal(sc.EndLine, SystemTypes.Int32))); args.Add(new NamedArgument(Identifier.For("EndColumn"), new Literal(sc.EndColumn, SystemTypes.Int32))); args.Add(new NamedArgument(Identifier.For("SourceText"), new Literal(sc.SourceText, SystemTypes.String))); } return new AttributeNode(attrBinding, args, (AttributeTargets)0); }
/// <summary> /// <para> /// Seralizes the expressions in toSerialize to an attribute determined by ctor. /// </para> /// <para><code> /// requires ctor.DeclaringType <: Microsoft.Contracts.AttributeWithContext; /// </code></para> /// <para><code> /// requires ctor != null && toSerialize != null && toSerialize.SourceContext != null; /// </code></para> /// </summary> public static AttributeNode SerializeExpression(InstanceInitializer/*!*/ ctor, Expression/*!*/ toSerialize, Module containingModule) { return Checker.SerializeExpressions(ctor, null, new ExpressionList(toSerialize), toSerialize.SourceContext, containingModule); }
public static Block createElementInitializerInternal(TYPE type, Expression indexer, int level, List <Expression> nonConstantDimensions, bool skipFirstLevel, SourceContext sourceContext) { // Generates internal part of array initializer: // either object constructor or, again, array initializer. // Check if the type is ARRAY. if (!(type is ARRAY_TYPE) && !(type is OBJECT_TYPE)) { return(null); } if (type is ARRAY_TYPE) { EXPRESSION_LIST declaredDimensions = ((ARRAY_TYPE)type).dimensions; int Rank = declaredDimensions.Length; List <Expression> dimensions = new List <Expression>(); // Check if all dimensions are constants or there is an expression available. for (int i = 0, n = Rank; i < n; i++) { if (declaredDimensions[i] == null || declaredDimensions[i].calculate() == null) { if (nonConstantDimensions == null) { return(null); } if (nonConstantDimensions.Count > 0) { dimensions.Add(nonConstantDimensions[0]); nonConstantDimensions.RemoveAt(0); } else { ERROR.MissingParameters(Rank, type.sourceContext); return(null); } } else { long d = (long)declaredDimensions[i].calculate(); Literal dim = new Literal((int)d, SystemTypes.Int32); dimensions.Add(dim); } } Block block = new Block(new StatementList()); // Generate array initializer: // x = new object[n]; if (skipFirstLevel && level == 0) { goto Bypass; } AssignmentStatement array_initializer = new AssignmentStatement(); array_initializer.NodeType = NodeType.AssignmentStatement; array_initializer.Operator = NodeType.Nop; // this means "normal" assignment, but not += etc. // Generate 'new object[n]' ConstructArray array_construct = new ConstructArray(); Node elem_type = ((ARRAY_TYPE)type).base_type.convert(); if (elem_type is ArrayTypeExpression) { ArrayTypeExpression arr_type = (elem_type.Clone()) as ArrayTypeExpression; // for ( int i=0, n=arr_type.Rank; i<n; i++ ) // arr_type.Sizes[i] = -1; elem_type = arr_type; } array_construct.ElementType = (TypeNode)elem_type; array_construct.Rank = Rank; array_construct.SourceContext = sourceContext; array_construct.Type = (TypeNode)type.convert(); array_construct.Operands = new ExpressionList(); for (int i = 0; i < Rank; i++) { array_construct.Operands.Add(dimensions[i]); } array_initializer.Source = array_construct; array_initializer.Target = indexer; array_initializer.SourceContext = sourceContext; block.Statements.Add(array_initializer); Bypass: // Generate x[i0,i1,...] for passing to the recursive call. Indexer new_indexer = new Indexer(); new_indexer.Object = indexer; new_indexer.Type = type.convert() as TypeNode; new_indexer.ElementType = ((ARRAY_TYPE)type).base_type.convert() as TypeNode; new_indexer.Operands = new ExpressionList(); for (int i = 0; i < Rank; i++) { Identifier index = Identifier.For("_i" + (level + i).ToString()); new_indexer.Operands.Add(index); } // Generate the last part (see comment, part 4, below). Block elem_initializers = createElementInitializerInternal(((ARRAY_TYPE)type).base_type, new_indexer, level + Rank, nonConstantDimensions, true, sourceContext); if (elem_initializers == null) { return(block); } // We do not need loops to initialize elements... // Return just array initializer. // Otherwise go generate initializers. // Generate // 1) int i0, i1, ...; // 2) for (int i1=0; i1<n; i1++) // for (int i2=0; i2<m; i2++) // ... // // Generate recursively: // 3) Initializers for array elements: x[i1,i2,...] = new object[n]; // 4) Initializers for every element (the similar loop(s)). // Generate int i0, i1, ...; for (int i = 0; i < Rank; i++) { VariableDeclaration locali = new VariableDeclaration(Identifier.For("_i" + (level + i).ToString()), SystemTypes.Int32, null); block.Statements.Add(locali); } // Generate loop headers: // for (int i1=0; i1<n; i1++) // for (int i2=0; i2<m; i2++) // ... Block owner = block; // where to put generated for-node for (int i = 0; i < Rank; i++) { For forStatement = new For(); // forStatement.NodeType; forStatement.SourceContext = sourceContext; // Making for-statement's body forStatement.Body = new Block(); forStatement.Body.Checked = true; forStatement.Body.HasLocals = false; // forStatement.Body.NodeType; // forStatement.Body.Scope; forStatement.Body.SourceContext = sourceContext; forStatement.Body.SuppressCheck = false; forStatement.Body.Statements = new StatementList(); // Now leave the body empty... // Making condition: i<n BinaryExpression condition = new BinaryExpression(); condition.NodeType = NodeType.Lt; condition.Operand1 = Identifier.For("_i" + (level + i).ToString()); condition.Operand2 = dimensions[i]; condition.SourceContext = sourceContext; forStatement.Condition = condition; // Making incrementer: i+=1 forStatement.Incrementer = new StatementList(); AssignmentStatement assignment = new AssignmentStatement(); assignment.NodeType = NodeType.AssignmentStatement; assignment.Operator = NodeType.Add; // Hope this means += // assignment.OperatorOverload assignment.Source = new Literal((int)1, SystemTypes.Int32); assignment.SourceContext = sourceContext; assignment.Target = Identifier.For("_i" + (level + i).ToString()); forStatement.Incrementer.Add(assignment); // Making initializer: i=0 forStatement.Initializer = new StatementList(); AssignmentStatement initializer = new AssignmentStatement(); initializer.NodeType = NodeType.AssignmentStatement; initializer.Operator = NodeType.Nop; // this means "normal" assignment, but not += etc. initializer.Source = new Literal(0, SystemTypes.Int32); initializer.Target = Identifier.For("_i" + (level + i).ToString()); initializer.SourceContext = sourceContext; forStatement.Initializer.Add(initializer); owner.Statements.Add(forStatement); owner = forStatement.Body; // for next iteration } // Adding element initializers generated in advance. owner.Statements.Add(elem_initializers); return(block); } else if (type is OBJECT_TYPE) { // Check if the type is VAL-object. if (!((OBJECT_TYPE)type).ObjectUnit.modifiers.Value) { return(null); } Block block = new Block(new StatementList()); // Generate 'new obj' DECLARATION objct = ((OBJECT_TYPE)type).ObjectUnit; // We do it for only own value types. They have // extra constcutor that takes ont fictive intgere. Might have // Chtck and call it Construct construct = new Construct(); // Strange thing: CCI expects _class_ in Construst.Constructor, // but not a constructor itself!.. // construct.Constructor = new MemberBinding(null,((TypeNode)objct.convert()).GetConstructors()[0]); // NODE.convertTypeName(objct); construct.Constructor = new MemberBinding(null, (TypeNode)objct.convert()); construct.Constructor.Type = SystemTypes.Type; construct.Operands = new ExpressionList(); construct.SourceContext = sourceContext; construct.Type = (TypeNode)objct.convert(); construct.Operands.Add(new Literal(1, SystemTypes.Int32)); // Generate x[i0,i1,...] = new obj; AssignmentStatement main_initializer = new AssignmentStatement(); main_initializer.NodeType = NodeType.AssignmentStatement; main_initializer.Operator = NodeType.Nop; // this means "normal" assignment, but not += etc. main_initializer.Source = construct; main_initializer.Target = indexer; main_initializer.SourceContext = sourceContext; block.Statements.Add(main_initializer); return(block); } else if (type is EXTERNAL_TYPE) { // Only value types might need extra calls Struct str = ((EXTERNAL_TYPE)type).entity as Struct; InstanceInitializer ctr = str.GetConstructor(new TypeNode[] { SystemTypes.Int32 }); bool possibly_was_our_structure = (ctr != null); if (ctr == null) { ctr = str.GetConstructor(new TypeNode[0] { }); } // TO_DO: When metadata is available replace this with // more consistent check Block block = new Block(new StatementList()); // Generate 'new obj' Construct construct = new Construct(); construct.Constructor = new MemberBinding(null, ctr); construct.Operands = new ExpressionList(); construct.Type = str; // We do it for only own value types. They have // extra constcutor that takes ont fictive intgere. Might have // Chtck and call it if (possibly_was_our_structure) { construct.Operands.Add(Literal.Int32MinusOne); } // Generate x[i0,i1,...] = new obj; AssignmentStatement main_initializer = new AssignmentStatement(); main_initializer.NodeType = NodeType.AssignmentStatement; main_initializer.Operator = NodeType.Nop; // this means "normal" assignment, but not += etc. main_initializer.Source = construct; main_initializer.Target = indexer; main_initializer.SourceContext = sourceContext; indexer.Type = construct.Type; block.Statements.Add(main_initializer); return(block); } else { return(null); } }
public override InstanceInitializer VisitInstanceInitializer(InstanceInitializer cons) { throw new ApplicationException("unimplemented"); }
private void EmitDelegateShim(StatementList setupInteropStatements, AssemblyNode inputAssembly, DelegateNode type) { // For each referential use in an imported or exported method signature of a delegate type definition D such as: // delegate R D<T, U>(A1 a1, A2 a2) // declare: // class D_Shim_<unique id><T, U> { // private UniversalDelegate u; // public D_Shim_<unique id>(UniversalDelegate u) { this.u = u; } // public R Invoke(A1 a1, A2 a2) { // return (R)u(new object[] {a1, a2}); // } // } // and append to <Module>::SetupInterop(): // InteropContextManager.Data.RegisterDelegateShim(typeof(D_Shim_<unique id>)) var shim = new Class (inputAssembly, null, new AttributeList(0), TypeFlags.Public | TypeFlags.Class, Identifier.For(""), Identifier.For(ShimFullName(type.FullName)), (Class)env.ObjectType, new InterfaceList(), new MemberList()); TransferTypeParameters(type, shim); var uField = new Field (shim, new AttributeList(0), FieldFlags.Private, Identifier.For("u"), env.UniversalDelegateType, null); uField.Flags |= FieldFlags.Private; shim.Members.Add(uField); var ctorParam = new Parameter(Identifier.For("u"), env.UniversalDelegateType); var ctorBlock = new Block (new StatementList (new ExpressionStatement (new MethodCall (new MemberBinding(ThisExpression(shim), env.ObjectType.GetConstructor()), new ExpressionList())), new AssignmentStatement (new MemberBinding(ThisExpression(shim), uField), new ParameterBinding(ctorParam, ctorParam.SourceContext)), new Return())); var ctor = new InstanceInitializer(shim, new AttributeList(0), new ParameterList(ctorParam), ctorBlock); ctor.Flags |= MethodFlags.Public | MethodFlags.SpecialName | MethodFlags.RTSpecialName; TagAsCompilerGenerated(ctor); shim.Members.Add(ctor); var invokeParams = CopyParameters(type.Parameters); var args = new ExpressionList(); foreach (var p in invokeParams) args.Add(BoxExpression(new ParameterBinding(p, p.SourceContext), env.ObjectType)); var argsAsObjectArray = ArrayExpression(args, env.ObjectType); var callExpr = new MethodCall (new MemberBinding (new MemberBinding(ThisExpression(shim), uField), env.UniversalDelegate_InvokeMethod), new ExpressionList(argsAsObjectArray)); var statements = new StatementList(); if (type.ReturnType == env.VoidType) { statements.Add(new ExpressionStatement(callExpr)); statements.Add(new ExpressionStatement(new UnaryExpression(null, NodeType.Pop))); statements.Add(new Return()); } else { statements.Add(new Return(CastExpression(callExpr, type.ReturnType))); } var invoke = new Method (shim, new AttributeList(0), Identifier.For("Invoke"), invokeParams, type.ReturnType, new Block(statements)); invoke.Flags |= MethodFlags.Public; invoke.CallingConvention |= CallingConventionFlags.HasThis; TagAsCompilerGenerated(invoke); shim.Members.Add(invoke); TagAsCompilerGenerated(shim); TagAsInteropGenerated(shim); TagAsIgnore(shim); inputAssembly.Types.Add(shim); shim.DeclaringModule = inputAssembly; env.Log(new InteropInfoMessage(RewriterMsgContext.Type(type), "Created shim type: " + shim.FullName)); setupInteropStatements.Add (new ExpressionStatement (new MethodCall (new MemberBinding (DatabaseExpression(), env.InteropDatabase_RegisterDelegateShimMethod), new ExpressionList(TypeOfExpression(shim))))); }
public void Setup(AssemblyNode mscorlib, AssemblyNode jsTypes, AssemblyNode rewriteAssembly) { NumWarnings = 0; NumErrors = 0; MsCorLib = mscorlib; AssemblyDelaySignAttributeType = GetType(mscorlib, "System.Reflection", "AssemblyDelaySignAttribute"); VoidType = GetType(mscorlib, "System", "Void"); ObjectType = GetType(mscorlib, "System", "Object"); StringType = GetType(mscorlib, "System", "String"); IntType = GetType(mscorlib, "System", "Int32"); BooleanType = GetType(mscorlib, "System", "Boolean"); MethodBaseType = GetType(mscorlib, "System.Reflection", "MethodBase"); RuntimeTypeHandleType = GetType(mscorlib, "System", "RuntimeTypeHandle"); NullableTypeConstructor = GetType(mscorlib, "System", "Nullable`1"); CompilerGeneratedAttributeType = GetType (mscorlib, "System.Runtime.CompilerServices", "CompilerGeneratedAttribute"); DllImportAttributeType = GetType(mscorlib, "System.Runtime.InteropServices", "DllImportAttribute"); TypeType = GetType(mscorlib, "System", "Type"); Type_GetMethodMethod = GetMethod(TypeType, "GetMethod", StringType, TypeType.GetArrayType(1)); Type_GetMemberMethod = GetMethod(TypeType, "GetMember", StringType); Type_GetConstructorMethod = GetMethod(TypeType, "GetConstructor", TypeType.GetArrayType(1)); Type_GetTypeFromHandleMethod = GetMethod(TypeType, "GetTypeFromHandle", RuntimeTypeHandleType); Type_GetGenericArgumentsMethod = GetMethod(TypeType, "GetGenericArguments"); Type_MakeArrayTypeMethod = GetMethod(TypeType, "MakeArrayType"); Type_MakeGenericTypeMethod = GetMethod(TypeType, "MakeGenericType", TypeType.GetArrayType(1)); InteropTypes = new InteropTypes(this); InteropManager = new InteropManager(this); IgnoreAttributeType = GetType(jsTypes, Constants.JSTypesIL2JSNS, "IgnoreAttribute"); InteropAttributeType = GetType(jsTypes, Constants.JSTypesInteropNS, "InteropAttribute"); NamingAttributeType = GetType(jsTypes, Constants.JSTypesInteropNS, "NamingAttribute"); ImportAttributeType = GetType(jsTypes, Constants.JSTypesInteropNS, "ImportAttribute"); ImportKeyAttributeType = GetType(jsTypes, Constants.JSTypesInteropNS, "ImportKeyAttribute"); ExportAttributeType = GetType(jsTypes, Constants.JSTypesInteropNS, "ExportAttribute"); NotExportedAttributeType = GetType(jsTypes, Constants.JSTypesInteropNS, "NotExportedAttribute"); InteropGeneratedAttributeType = GetType(jsTypes, Constants.JSTypesIL2JSNS, "InteropGeneratedAttribute"); JSTypes = jsTypes; JSContextType = GetType(jsTypes, Constants.JSTypesInteropNS, "JSContext"); InteropContextManagerType = GetType(jsTypes, Constants.JSTypesManagedInteropNS, "InteropContextManager"); InteropContextManager_GetDatabaseMethod = GetMethod(InteropContextManagerType, "get_Database"); InteropContextManager_GetCurrentRuntimeMethod = GetMethod(InteropContextManagerType, "get_CurrentRuntime"); InteropContextManager_GetRuntimeForObjectMethod = GetMethod (InteropContextManagerType, "GetRuntimeForObject", ObjectType); InteropDatabaseType = GetType(jsTypes, Constants.JSTypesManagedInteropNS, "InteropDatabase"); InteropDatabase_RegisterRootExpression = GetMethod(InteropDatabaseType, "RegisterRootExpression", StringType); InteropDatabase_RegisterDelegateShimMethod = GetMethod (InteropDatabaseType, "RegisterDelegateShim", TypeType); InteropDatabase_RegisterTypeMethod = GetMethod (InteropDatabaseType, "RegisterType", TypeType, IntType, StringType, StringType, IntType, BooleanType, BooleanType, BooleanType); InteropDatabase_RegisterExportMethod = GetMethod (InteropDatabaseType, "RegisterExport", MethodBaseType, BooleanType, StringType); SimpleMethodBaseType = GetType(jsTypes, Constants.JSTypesManagedInteropNS, "SimpleMethodBase"); SimpleMethodInfoType = GetType(jsTypes, Constants.JSTypesManagedInteropNS, "SimpleMethodInfo"); SimpleMethodInfo_Ctor = GetConstructor (SimpleMethodInfoType, BooleanType, StringType, TypeType, TypeType.GetArrayType(1), TypeType); SimpleConstructorInfoType = GetType(jsTypes, Constants.JSTypesManagedInteropNS, "SimpleConstructorInfo"); SimpleConstructorInfo_Ctor = GetConstructor(SimpleConstructorInfoType, TypeType, TypeType.GetArrayType(1)); RuntimeType = GetType(jsTypes, Constants.JSTypesManagedInteropNS, "Runtime"); Runtime_CompleteConstructionMethod = GetMethod (RuntimeType, "CompleteConstruction", SimpleMethodBaseType, ObjectType, JSContextType); Runtime_CallImportedMethodMethod = GetMethod (RuntimeType, "CallImportedMethod", SimpleMethodBaseType, StringType, ObjectType.GetArrayType(1)); UniversalDelegateType = GetType(jsTypes, Constants.JSTypesManagedInteropNS, "UniversalDelegate"); UniversalDelegate_InvokeMethod = GetUniqueMethod(UniversalDelegateType, "Invoke"); MethodBase_GetGenericArgumentsMethod = GetMethod(MethodBaseType, "GetGenericArguments"); ModuleType = GetType(rewriteAssembly, "", "<Module>"); foreach (var member in ModuleType.Members) { var cctor = member as StaticInitializer; if (cctor != null) { ModuleCCtorMethod = cctor; } } }
public InstanceInitializer BestImportingConstructor(InstanceInitializer importingCtor) { var bestCtor = default(InstanceInitializer); var bestRank = -1; foreach (var thisMember in importingCtor.DeclaringType.Members) { var thisCtor = thisMember as InstanceInitializer; if (thisCtor != null) { var thisRank = -1; var ps = thisCtor.Parameters; if (ps.Count == 1 && ps[0].Type == env.JSContextType) thisRank = 0; else if (ps.Count == 1 + importingCtor.Parameters.Count && ps[0].Type == env.JSContextType) { var match = true; for (var i = 0; i < importingCtor.Parameters.Count; i++) { if (!(ps[1 + i].Type == importingCtor.Parameters[i].Type)) { match = false; break; } } if (match) thisRank = 1; } if (thisRank > bestRank) { bestRank = thisRank; bestCtor = thisCtor; } } } if (bestCtor == null) { env.Log (new InvalidInteropMessage (RewriterMsgContext.Method(importingCtor), "No importing constructor found to match imported constructor")); throw new DefinitionException(); } else if ((bestCtor.Flags & MethodFlags.Public) == 0) { env.Log (new InvalidInteropMessage (RewriterMsgContext.Method(bestCtor), "Importing constructors must be public")); throw new DefinitionException(); } return bestCtor; }
public static void Initialize() { TypeNode RuntimeHelpers = SystemTypes.SystemAssembly.GetType(Identifier.For("System.Runtime.CompilerServices"), Identifier.For("RuntimeHelpers")); if (RuntimeHelpers != null) { Runtime.GetOffsetToStringData = RuntimeHelpers.GetMethod(Identifier.For("get_OffsetToStringData")); } Runtime.Combine = SystemTypes.Delegate.GetMethod(StandardIds.Combine, SystemTypes.Delegate, SystemTypes.Delegate); Runtime.CreateInstance = SystemTypes.Activator.GetMethod(StandardIds.CreateInstance, SystemTypes.Type); Runtime.GenericCreateInstance = SystemTypes.Activator.GetMethod(StandardIds.CreateInstance); Runtime.GetCurrent = SystemTypes.IEnumerator.GetMethod(StandardIds.getCurrent); Runtime.GetEnumerator = SystemTypes.IEnumerable.GetMethod(StandardIds.GetEnumerator); Runtime.GetType = SystemTypes.Object.GetMethod(Identifier.For("GetType")); Runtime.GetTypeFromHandle = SystemTypes.Type.GetMethod(Identifier.For("GetTypeFromHandle"), SystemTypes.RuntimeTypeHandle); Runtime.IDisposableDispose = SystemTypes.IDisposable.GetMethod(StandardIds.Dispose); Runtime.IsInterned = SystemTypes.String.GetMethod(StandardIds.IsInterned, SystemTypes.String); Runtime.MemberwiseClone = SystemTypes.Object.GetMethod(StandardIds.MemberwiseClone); Runtime.MonitorEnter = SystemTypes.Monitor.GetMethod(StandardIds.Enter, SystemTypes.Object); Runtime.MonitorExit = SystemTypes.Monitor.GetMethod(StandardIds.Exit, SystemTypes.Object); Runtime.MoveNext = SystemTypes.IEnumerator.GetMethod(StandardIds.MoveNext); Runtime.ObjectToString = SystemTypes.Object.GetMethod(StandardIds.ToString); Runtime.Reset = SystemTypes.IEnumerator.GetMethod(StandardIds.Reset); Runtime.Remove = SystemTypes.Delegate.GetMethod(StandardIds.Remove, SystemTypes.Delegate, SystemTypes.Delegate); Runtime.StringConcatObjects = SystemTypes.String.GetMethod(StandardIds.Concat, SystemTypes.Object, SystemTypes.Object); Runtime.StringConcatStrings = SystemTypes.String.GetMethod(StandardIds.Concat, SystemTypes.String, SystemTypes.String); Runtime.StringEquals = SystemTypes.String.GetMethod(StandardIds.Equals, SystemTypes.String, SystemTypes.String); InstanceInitializer dbgConstr = null; if (SystemTypes.DebuggableAttribute != null) { if (SystemTypes.DebuggingModes != null) { dbgConstr = SystemTypes.DebuggableAttribute.GetConstructor(SystemTypes.DebuggingModes); } else { dbgConstr = SystemTypes.DebuggableAttribute.GetConstructor(SystemTypes.Boolean, SystemTypes.Boolean); } } MemberBinding debuggableAttributeCtor = null; if (dbgConstr != null) { debuggableAttributeCtor = new MemberBinding(null, dbgConstr); } if (debuggableAttributeCtor != null) { Literal trueLit = new Literal(true, SystemTypes.Boolean); Literal falseLit = new Literal(false, SystemTypes.Boolean); Runtime.Debuggable = new AttributeNode(); Runtime.Debuggable.Constructor = debuggableAttributeCtor; //TODO: will need to fix this up in the case where the type is compiled from source Runtime.Debuggable.Expressions = new ExpressionList(2); if (SystemTypes.DebuggingModes != null) { Runtime.Debuggable.Expressions.Add(new Literal(0x107, SystemTypes.DebuggingModes)); } else { Runtime.Debuggable.Expressions.Add(trueLit); Runtime.Debuggable.Expressions.Add(trueLit); } Runtime.OptimizedButDebuggable = new AttributeNode(); Runtime.OptimizedButDebuggable.Constructor = debuggableAttributeCtor; Runtime.OptimizedButDebuggable.Expressions = new ExpressionList(2); if (SystemTypes.DebuggingModes != null) { Runtime.OptimizedButDebuggable.Expressions.Add(new Literal(0x007, SystemTypes.DebuggingModes)); } else { Runtime.OptimizedButDebuggable.Expressions.Add(trueLit); Runtime.OptimizedButDebuggable.Expressions.Add(falseLit); } Runtime.OptimizedWithPDBOnly = new AttributeNode(); Runtime.OptimizedWithPDBOnly.Constructor = debuggableAttributeCtor; Runtime.OptimizedWithPDBOnly.Expressions = new ExpressionList(2); if (SystemTypes.DebuggingModes != null) { Runtime.OptimizedWithPDBOnly.Expressions.Add(new Literal(0x006, SystemTypes.DebuggingModes)); } else { Runtime.OptimizedWithPDBOnly.Expressions.Add(falseLit); Runtime.OptimizedWithPDBOnly.Expressions.Add(falseLit); } } }
public void Setup(AssemblyNode mscorlib, AssemblyNode jsTypes, AssemblyNode rewriteAssembly) { NumWarnings = 0; NumErrors = 0; MsCorLib = mscorlib; AssemblyDelaySignAttributeType = GetType(mscorlib, "System.Reflection", "AssemblyDelaySignAttribute"); VoidType = GetType(mscorlib, "System", "Void"); ObjectType = GetType(mscorlib, "System", "Object"); StringType = GetType(mscorlib, "System", "String"); IntType = GetType(mscorlib, "System", "Int32"); BooleanType = GetType(mscorlib, "System", "Boolean"); MethodBaseType = GetType(mscorlib, "System.Reflection", "MethodBase"); RuntimeTypeHandleType = GetType(mscorlib, "System", "RuntimeTypeHandle"); NullableTypeConstructor = GetType(mscorlib, "System", "Nullable`1"); CompilerGeneratedAttributeType = GetType (mscorlib, "System.Runtime.CompilerServices", "CompilerGeneratedAttribute"); DllImportAttributeType = GetType(mscorlib, "System.Runtime.InteropServices", "DllImportAttribute"); TypeType = GetType(mscorlib, "System", "Type"); Type_GetMethodMethod = GetMethod(TypeType, "GetMethod", StringType, TypeType.GetArrayType(1)); Type_GetMemberMethod = GetMethod(TypeType, "GetMember", StringType); Type_GetConstructorMethod = GetMethod(TypeType, "GetConstructor", TypeType.GetArrayType(1)); Type_GetTypeFromHandleMethod = GetMethod(TypeType, "GetTypeFromHandle", RuntimeTypeHandleType); Type_GetGenericArgumentsMethod = GetMethod(TypeType, "GetGenericArguments"); Type_MakeArrayTypeMethod = GetMethod(TypeType, "MakeArrayType"); Type_MakeGenericTypeMethod = GetMethod(TypeType, "MakeGenericType", TypeType.GetArrayType(1)); InteropTypes = new InteropTypes(this); InteropManager = new InteropManager(this); IgnoreAttributeType = GetType(jsTypes, Constants.JSTypesIL2JSNS, "IgnoreAttribute"); InteropAttributeType = GetType(jsTypes, Constants.JSTypesInteropNS, "InteropAttribute"); NamingAttributeType = GetType(jsTypes, Constants.JSTypesInteropNS, "NamingAttribute"); ImportAttributeType = GetType(jsTypes, Constants.JSTypesInteropNS, "ImportAttribute"); ImportKeyAttributeType = GetType(jsTypes, Constants.JSTypesInteropNS, "ImportKeyAttribute"); ExportAttributeType = GetType(jsTypes, Constants.JSTypesInteropNS, "ExportAttribute"); NotExportedAttributeType = GetType(jsTypes, Constants.JSTypesInteropNS, "NotExportedAttribute"); InteropGeneratedAttributeType = GetType(jsTypes, Constants.JSTypesIL2JSNS, "InteropGeneratedAttribute"); JSTypes = jsTypes; JSContextType = GetType(jsTypes, Constants.JSTypesInteropNS, "JSContext"); InteropContextManagerType = GetType(jsTypes, Constants.JSTypesManagedInteropNS, "InteropContextManager"); InteropContextManager_GetDatabaseMethod = GetMethod(InteropContextManagerType, "get_Database"); InteropContextManager_GetCurrentRuntimeMethod = GetMethod(InteropContextManagerType, "get_CurrentRuntime"); InteropContextManager_GetRuntimeForObjectMethod = GetMethod (InteropContextManagerType, "GetRuntimeForObject", ObjectType); InteropDatabaseType = GetType(jsTypes, Constants.JSTypesManagedInteropNS, "InteropDatabase"); InteropDatabase_RegisterRootExpression = GetMethod(InteropDatabaseType, "RegisterRootExpression", StringType); InteropDatabase_RegisterDelegateShimMethod = GetMethod (InteropDatabaseType, "RegisterDelegateShim", TypeType); InteropDatabase_RegisterTypeMethod = GetMethod (InteropDatabaseType, "RegisterType", TypeType, IntType, StringType, StringType, IntType, BooleanType, BooleanType, BooleanType); InteropDatabase_RegisterExportMethod = GetMethod (InteropDatabaseType, "RegisterExport", MethodBaseType, BooleanType, StringType); SimpleMethodBaseType = GetType(jsTypes, Constants.JSTypesManagedInteropNS, "SimpleMethodBase"); SimpleMethodInfoType = GetType(jsTypes, Constants.JSTypesManagedInteropNS, "SimpleMethodInfo"); SimpleMethodInfo_Ctor = GetConstructor (SimpleMethodInfoType, BooleanType, StringType, TypeType, TypeType.GetArrayType(1), TypeType); SimpleConstructorInfoType = GetType(jsTypes, Constants.JSTypesManagedInteropNS, "SimpleConstructorInfo"); SimpleConstructorInfo_Ctor = GetConstructor(SimpleConstructorInfoType, TypeType, TypeType.GetArrayType(1)); RuntimeType = GetType(jsTypes, Constants.JSTypesManagedInteropNS, "Runtime"); Runtime_CompleteConstructionMethod = GetMethod (RuntimeType, "CompleteConstruction", SimpleMethodBaseType, ObjectType, JSContextType); Runtime_CallImportedMethodMethod = GetMethod (RuntimeType, "CallImportedMethod", SimpleMethodBaseType, StringType, ObjectType.GetArrayType(1)); UniversalDelegateType = GetType(jsTypes, Constants.JSTypesManagedInteropNS, "UniversalDelegate"); UniversalDelegate_InvokeMethod = GetUniqueMethod(UniversalDelegateType, "Invoke"); MethodBase_GetGenericArgumentsMethod = GetMethod(MethodBaseType, "GetGenericArguments"); ModuleType = GetType(rewriteAssembly, "", "<Module>"); foreach (var member in ModuleType.Members) { var cctor = member as StaticInitializer; if (cctor != null) ModuleCCtorMethod = cctor; } }
private Class TranslateToClass(CodeTypeDeclaration typeDec, Identifier nameSpace, TypeNode declaringType){ Debug.Assert(typeDec != null); Class c = new Class(); c.Attributes = this.Translate(typeDec.CustomAttributes, null); c.DeclaringModule = this.targetModule; if (declaringType == null) this.targetModule.Types.Add(c); c.DeclaringType = declaringType; c.Members = new MemberList(); this.Translate(typeDec.Members, c); c.Name = Identifier.For(typeDec.Name); c.Namespace = nameSpace; this.SetTypeFlags(c, typeDec.TypeAttributes); c.Interfaces = this.TranslateToInterfaceList(typeDec.BaseTypes); MemberList constructors = c.GetConstructors(); if (constructors.Count == 0){ //Add default constructor QualifiedIdentifier supCons = new QualifiedIdentifier(new Base(), StandardIds.Ctor); MethodCall superConstructorCall = new MethodCall(supCons, new ExpressionList(0), NodeType.Call); StatementList body = new StatementList(2); body.Add(new ExpressionStatement(superConstructorCall)); InstanceInitializer cons = new InstanceInitializer(c, null, new ParameterList(0), new Block(body)); cons.CallingConvention = CallingConventionFlags.HasThis; cons.Flags |= MethodFlags.Public; c.Members.Add(cons); } if (declaringType != null) declaringType.Members.Add(c); return c; }
public virtual void VisitInstanceInitializer(InstanceInitializer cons) { this.VisitMethod(cons); }
private void Translate(CodeConstructor cons, TypeNode declaringType){ InstanceInitializer c = new InstanceInitializer(); c.Attributes = this.Translate(cons.CustomAttributes, null); c.DeclaringType = declaringType; this.SetMethodFlags(cons.Attributes, c); c.Flags |= MethodFlags.SpecialName|MethodFlags.RTSpecialName; c.Parameters = this.Translate(cons.Parameters); StatementList statements = this.Translate(cons.Statements); int n = statements.Count; StatementList stats = new StatementList(n+1); if (cons.ChainedConstructorArgs != null && cons.ChainedConstructorArgs.Count > 0) stats.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(new This(), StandardIds.Ctor), this.Translate(cons.ChainedConstructorArgs), NodeType.Call))); else if (cons.BaseConstructorArgs != null && cons.BaseConstructorArgs.Count > 0) stats.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(new Base(), StandardIds.Ctor), this.Translate(cons.BaseConstructorArgs), NodeType.Call))); else stats.Add(new ExpressionStatement(new MethodCall(new QualifiedIdentifier(new Base(), StandardIds.Ctor), new ExpressionList(0), NodeType.Call))); for (int i = 0; i < n; i++) stats.Add(statements[i]); statements = stats; c.Body = new Block(statements); declaringType.Members.Add(c); }
public override InstanceInitializer VisitInstanceInitializer(InstanceInitializer cons) { if (cons == null) return null; if (cons.Parameters == null || cons.Parameters.Count == 0) { if (cons.DeclaringType != null && cons.DeclaringType.IsValueType) this.HandleError(cons.Name, Error.ExplicitDefaultConstructorForValueType); } if (!cons.HasCompilerGeneratedSignature && cons.DeclaringType is Class && cons.DeclaringType.IsSealed && cons.DeclaringType.IsAbstract) this.HandleError(cons.Name, Error.ConstructorInAbstractSealedClass); else if (cons.DeclaringType is Interface) { this.HandleError(cons.Name, Error.InterfaceHasConstructor); return null; } return (InstanceInitializer)this.VisitMethod(cons); }
public void SetUpClosureClass(Method method){ Class closureClass = method.Scope.ClosureClass; if (this.CodeMightBeVerified) { // Closure classes contain user-written code, but it doesn't get verified. closureClass.Attributes.Add( new AttributeNode(new MemberBinding(null, SystemTypes.VerifyAttribute.GetConstructor(SystemTypes.Boolean)), new ExpressionList(Literal.False), AttributeTargets.Class) ); } this.currentType.Members.Add(closureClass); MemberList members = closureClass.Members; ParameterList parameters = new ParameterList(); StatementList statements = new StatementList(); TypeNode thisType = method.Scope.ThisTypeInstance; This thisParameter = new This(closureClass); if (thisType != null && !method.IsStatic) { if (!thisType.IsValueType) thisType = OptionalModifier.For(SystemTypes.NonNullType, thisType); Field f = (Field)closureClass.Members[0]; f.Type = thisType; Parameter p = new Parameter(f.Name, f.Type); // The captured class object parameters to closure class constructors are delayed p.Attributes.Add(new AttributeNode(new MemberBinding(null, ExtendedRuntimeTypes.DelayedAttribute.GetConstructor()), null, AttributeTargets.Parameter)); method.Scope.ThisField = f; parameters.Add(p); Expression pval = p; if (p.Type.IsValueType) pval = new AddressDereference(p, p.Type); statements.Add(new AssignmentStatement(new MemberBinding(thisParameter, f), p)); } MemberList scopeMembers = method.Scope.Members; for (int i = 0, n = scopeMembers.Count; i < n; i++){ Member m = scopeMembers[i]; Field f = m as Field; if (f == null || f.Type is Reference) continue; f.Type = method.Scope.FixTypeReference(f.Type); members.Add(f); if (!(f is ParameterField)) continue; Parameter p = new Parameter(f.Name, f.Type); parameters.Add(p); statements.Add(new AssignmentStatement(new MemberBinding(thisParameter, f), p)); } InstanceInitializer cons = new InstanceInitializer(); cons.ThisParameter = thisParameter; cons.DeclaringType = closureClass; cons.Flags |= MethodFlags.CompilerControlled; cons.Parameters = parameters; cons.Scope = new MethodScope(closureClass, new UsedNamespaceList(0)); cons.Body = new Block(statements); MethodCall mcall = new MethodCall(new MemberBinding(thisParameter, CoreSystemTypes.Object.GetConstructor()), new ExpressionList(0), NodeType.Call, CoreSystemTypes.Void); statements.Add(new ExpressionStatement(mcall)); statements.Add(new Return()); closureClass.Members.Add(cons); }
/// <summary> /// Serializes the expressions in toSerialize to an attribute determined by ctor, as if they come from module containingModule. /// Uses the SourceContext information of <param name="sc">sc</param> for the source context for the attribute. /// <para><code> /// requires ctor != null && toSerialize != null && 0 < toSerialize.Count && sc != null;; /// </code></para> /// <para><code> /// requires ctor.DeclaringType <: Microsoft.Contracts.AttributeWithContext; /// </code></para> /// </summary> /// <returns></returns> public static AttributeNode SerializeExpressions (InstanceInitializer/*!*/ ctor, ExpressionList/*!*/ toSerialize, SourceContext/*!*/ sc, Module containingModule) { return Checker.SerializeExpressions(ctor, null, toSerialize, sc, containingModule); }
public override InstanceInitializer VisitInstanceInitializer(InstanceInitializer cons) { if (cons == null) return null; MethodCall savedCurrentCtorCall = this.currentBaseCtorCall; if (cons.ContainsBaseMarkerBecauseOfNonNullFields) { if (cons.BaseOrDefferingCallBlock == null) goto ActualVisit; if (cons.BaseOrDefferingCallBlock.Statements == null) goto ActualVisit; if (cons.BaseOrDefferingCallBlock.Statements.Count != 1) goto ActualVisit; ExpressionStatement es = cons.BaseOrDefferingCallBlock.Statements[0] as ExpressionStatement; if (es == null) goto ActualVisit; MethodCall mc = (MethodCall) es.Expression; if (mc == null) goto ActualVisit; ExpressionList el = mc.Operands; if (el == null) goto ActualVisit; int n = el.Count; ExpressionList localList = new ExpressionList(n); StatementList xs = new StatementList(n); if (n > 0) cons.Body.HasLocals = true; for (int i = 0; i < n; i++) { Expression operand = el[i]; if (operand == null) continue; Local l = new Local(Identifier.For("l" + i.ToString()), el[i].Type, cons.Body); localList.Add(l); xs.Add(new AssignmentStatement(l, el[i], mc.SourceContext)); } this.currentBaseCtorCall = new MethodCall(mc.Callee, localList, NodeType.Call, SystemTypes.Void); cons.BaseOrDefferingCallBlock.Statements = xs; cons.BaseOrDefferingCallBlock.HasLocals = true; } ActualVisit: InstanceInitializer res = base.VisitInstanceInitializer(cons); this.currentBaseCtorCall = savedCurrentCtorCall; return res; }
public virtual InstanceInitializer VisitInstanceInitializer(InstanceInitializer cons){ return (InstanceInitializer)this.VisitMethod(cons); }
private TypeNode BuildComparer(TypeNode type, MemberList members, QueryOrderType[] orders, int n) { Debug.Assert(members != null && n > 0 && n <= members.Count); Identifier name = Identifier.For("comparer"+type.UniqueKey); Class cc = new Class(); cc.DeclaringModule = this.currentModule; cc.DeclaringType = this.currentType; cc.Flags = TypeFlags.NestedPublic; cc.Namespace = Identifier.Empty; cc.Name = name; cc.BaseClass = SystemTypes.Object; cc.Interfaces = new InterfaceList(2); cc.Interfaces.Add(SystemTypes.IComparer); cc.Interfaces.Add(SystemTypes.IHashCodeProvider); // constructor Method init = new InstanceInitializer(cc, null, new ParameterList(), new Block(new StatementList(1))); init.Flags |= MethodFlags.Public; cc.Members.Add(init); Method mthBaseCons = SystemTypes.Object.GetMethod(StandardIds.Ctor); MethodCall mcBase = new MethodCall(new MemberBinding(init.ThisParameter, mthBaseCons), null); mcBase.Type = SystemTypes.Void; init.Body.Statements.Add(new ExpressionStatement(mcBase)); // CompareTo Method mcomp = new Method(cc, null, Identifier.For("Compare"), new ParameterList(2), SystemTypes.Int32, new Block(new StatementList())); mcomp.Flags = MethodFlags.Public|MethodFlags.Virtual|MethodFlags.Final; mcomp.CallingConvention = CallingConventionFlags.HasThis; mcomp.Parameters.Add(new Parameter(null, ParameterFlags.In, Identifier.For("p1"), SystemTypes.Object, null, null)); mcomp.Parameters.Add(new Parameter(null, ParameterFlags.In, Identifier.For("p2"), SystemTypes.Object, null, null)); cc.Members.Add(mcomp); // GetHashCode(obj) Method mhash = new Method(cc, null, Identifier.For("GetHashCode"), new ParameterList(1), SystemTypes.Int32, new Block(new StatementList())); mhash.Flags = MethodFlags.Public|MethodFlags.Virtual|MethodFlags.Final; mhash.CallingConvention = CallingConventionFlags.HasThis; mhash.Parameters.Add(new Parameter(null, ParameterFlags.In, Identifier.For("p1"), SystemTypes.Object, null, null)); cc.Members.Add(mhash); // call type specific comparison Method mcomptype = this.BuildComparisonMethod(cc, type, members, orders, n); MethodCall mccomptype = new MethodCall( new MemberBinding(null, mcomptype), new ExpressionList(this.Unbox(mcomp.Parameters[0], type), this.Unbox(mcomp.Parameters[1], type)) ); mccomptype.Type = mcomptype.ReturnType; Block brNotEqual = new Block(); mcomp.Body.Statements.Add(new Branch(new BinaryExpression(mcomp.Parameters[0], mcomp.Parameters[1], NodeType.Ne), brNotEqual)); mcomp.Body.Statements.Add(new Return(Literal.Int32Zero)); mcomp.Body.Statements.Add(brNotEqual); mcomp.Body.Statements.Add(new Return(mccomptype)); this.BuildGetHashCodeBody(mhash, type, members, n); return cc; }
public virtual Differences VisitInstanceInitializer(InstanceInitializer cons1, InstanceInitializer cons2){ return this.VisitMethod(cons1, cons2); }
protected virtual Overloads GetConstructors(int line, int col, TypeNode type){ Node node; Scope scope; int identContext; this.languageService.SearchForNodeAtPosition(line+1, col+1, out node, out scope, out identContext); TypeNode referringType = null; Module referringModule = null; while (scope != null){ TypeScope tScope = scope as TypeScope; if (tScope != null){ referringType = tScope.Type; if (referringType != null){ referringModule = referringType.DeclaringModule; break; } } NamespaceScope nScope = scope as NamespaceScope; if (nScope != null){ referringModule = nScope.AssociatedModule; break; } scope = scope.OuterScope; } bool showPrivate = referringType == type; bool showFamily = referringType != null && referringType.IsAssignableTo(type); bool showInternal = this.MayAccessInternals(referringType, type) || this.MayAccessInternals(referringModule, type); Member selectedMember = this.GetMember(line, col); MemberList members = type == null ? null : type.GetConstructors(); int positionOfSelectedMember = 0; MemberList filteredMembers = new MemberList(); if (type != null && type.IsValueType){ //Add dummy default constructor InstanceInitializer cons = new InstanceInitializer(type, null, null, null); cons.Flags |= MethodFlags.Public; filteredMembers.Add(cons); } for (int i = 0, n = members == null ? 0 : members.Count; i < n; i++){ Method meth = members[i] as Method; if (meth == null) continue; if (meth.IsCompilerControlled) continue; if (meth.IsPrivate && !showPrivate) continue; if ((meth.IsFamily || meth.IsFamilyAndAssembly) && !showFamily) continue; if ((meth.IsAssembly || meth.IsFamilyOrAssembly) && !showInternal) continue; if (meth == selectedMember) positionOfSelectedMember = filteredMembers.Count; filteredMembers.Add(meth); } if (filteredMembers.Count == 0) return null; return new Overloads(filteredMembers, scope, positionOfSelectedMember, this.helper, OverloadKind.Constructors); }
public virtual InstanceInitializer VisitInstanceInitializer(InstanceInitializer cons, InstanceInitializer changes, InstanceInitializer deletions, InstanceInitializer insertions){ return (InstanceInitializer)this.VisitMethod(cons, changes, deletions, insertions); }
private static void WriteConstructor(InstanceInitializer constructor, TextWriter writer) { WriteType(constructor.DeclaringType, writer); writer.Write(".#ctor"); WriteParameters(constructor.Parameters, writer); }