示例#1
0
        public override Object Visit(ConstructorDefinition node, Object obj)
        {
            // Scope to store the auxiliar local variables for each field
            this.map.SetScope();
            //Dictionary<string, FieldDeclaration>.KeyCollection keys = this.fieldsInfo.Keys;
            //foreach (string tmpName in keys)
            //{
            //   if (!fieldsInfo[tmpName].TypeInfo.EndsWith("[]"))
            //      this.map.AddNewField("this__" + tmpName, fieldsInfo[tmpName].TypeInfo, node.FileName, fieldsInfo[tmpName].Line, fieldsInfo[tmpName].Column);
            //}

            this.map.SetScope();
            for (int i = 0; i < node.ParametersInfo.Count; i++)
            {
                if (!node.ParametersInfo[i].ParamType.EndsWith("[]"))
                {
                    this.map.AddNewVariable(node.ParametersInfo[i].Identifier, node.ParametersInfo[i].ParamType, node.Location);
                }
            }

            if (node.Initialization != null)
            {
                node.Initialization.Accept(this, obj);
            }

            node.Body.Accept(this, obj);
            this.addLocalVariable(this.map.ResetScope(), node.Body);
            // Add local variable for each field in use.
            //this.addLocalVariable(this.map.GetFieldScope(), node.Body);
            this.map.ResetScope(); //this.addAssignmentStatements(this.map.ResetScope(), node.Body);
            return(null);
        }
示例#2
0
        public object Create(Type type)
        {
            ConstructorDefinition ctorDefinition;

            lock (readWriteLock)
            {
                if (!objectActivatorMap.TryGetValue(type, out ctorDefinition))
                {
                    var largestConstructor = type.GetConstructors()
                                             .OrderByDescending(x => x.GetParameters().Length).First();

                    var ctorValues = new List <object>();
                    foreach (var parameterInfo in largestConstructor.GetParameters())
                    {
                        var ctorValue = factoryProvider.Resolve(parameterInfo.ParameterType)
                                        ?? ReflectionUtils.GetDefaultValue(parameterInfo.ParameterType);

                        ctorValues.Add(ctorValue);
                    }

                    ctorDefinition = new ConstructorDefinition(
                        ctorValues.ToArray(), GetActivator(largestConstructor));

                    objectActivatorMap[type] = ctorDefinition;
                }
            }

            return(ctorDefinition.Create());
        }
		public object Create(Type type)
		{
			ConstructorDefinition ctorDefinition;
			lock (readWriteLock)
			{
				if (!objectActivatorMap.TryGetValue(type, out ctorDefinition))
				{
					var largestConstructor = type.GetConstructors()
						.OrderByDescending(x => x.GetParameters().Length).First();

					var ctorValues = new List<object>();
					foreach (var parameterInfo in largestConstructor.GetParameters())
					{
						var ctorValue = factoryProvider.Resolve(parameterInfo.ParameterType)
						                ?? ReflectionUtils.GetDefaultValue(parameterInfo.ParameterType);

						ctorValues.Add(ctorValue);
					}

					ctorDefinition = new ConstructorDefinition(
						ctorValues.ToArray(), GetActivator(largestConstructor));

					objectActivatorMap[type] = ctorDefinition;
				}
			}

			return ctorDefinition.Create();
		}
示例#4
0
        public void ImportOnConstructorWithFunc()
        {
            var id = TypeIdentity.CreateDefinition(typeof(ImportOnConstructorWithFunc));

            Assert.IsTrue(s_Types.Exists(s => s.Identity.Equals(id)));

            var plugins = s_Parts.Where(p => p.Identity.Equals(id));

            Assert.IsTrue(plugins.Count() == 1);

            var plugin = plugins.First();

            Assert.AreEqual(1, plugin.Imports.Count());

            var import = plugin.Imports.First() as ConstructorBasedImportDefinition;

            Assert.IsNotNull(import);
            Assert.AreEqual("ContractName", import.ContractName);
            Assert.AreEqual(id, import.DeclaringType);
            Assert.AreEqual(TypeIdentity.CreateDefinition(typeof(Func <IExportingInterface>)), import.RequiredTypeIdentity);
            Assert.AreEqual(
                ConstructorDefinition.CreateDefinition(
                    typeof(ImportOnConstructorWithFunc).GetConstructor(new[] { typeof(Func <IExportingInterface>) })),
                import.Constructor);
            Assert.AreEqual(
                ParameterDefinition.CreateDefinition(
                    typeof(ImportOnConstructorWithFunc).GetConstructor(new[] { typeof(Func <IExportingInterface>) }).GetParameters().First()),
                import.Parameter);
        }
        public override Object Visit(ConstructorDefinition node, Object obj)
        {
            Object modifiers = builtMethod(node);

            base.Visit(node, obj);
            return(modifiers);
        }
        public override Object Visit(ConstructorDefinition node, Object obj)
        {
            if (node.Location == ((AstNode)obj).Location || found)
            {
                found = true;
                return(this.table);
            }
            //this.blockList = new List<int>();
            //this.indexBlockList = 0;

            this.table.Set();
            //this.currentMethod = node.Identifier;
            this.parameterSymbol(node);

            if (node.Initialization != null)
            {
                node.Initialization.Accept(this, obj);
            }

            if (found)
            {
                return(this.table);
            }

            node.Body.Accept(this, obj);
            if (found)
            {
                return(this.table);
            }
            //this.currentMethod = "";
            this.table.Reset();
            return(this.table);
        }
        protected override void DefineUnpackingContextCore(
            IList <KeyValuePair <string, TypeDefinition> > fields,
            out TypeDefinition type,
            out ConstructorDefinition constructor,
            out ILConstruct parameterInUnpackValueMethods,
            out ILConstruct parameterInSetValueMethods,
            out ILConstruct parameterInCreateObjectFromContext
            )
        {
            Type            runtimeType;
            ConstructorInfo runtimeConstructor;

            this.Emitter.DefineUnpackingContext(
                SerializerBuilderHelper.UnpackingContextTypeName,
                fields.Select(kv => new KeyValuePair <string, Type>(kv.Key, kv.Value.ResolveRuntimeType())).ToArray(),
                out runtimeType,
                out runtimeConstructor
                );
            type        = runtimeType;
            constructor =
                new ConstructorDefinition(
                    runtimeConstructor,
                    fields.Select(kv => TypeDefinition.Object(kv.Value.ResolveRuntimeType()))
                    );
            DefineUnpackValueMethodArguments(type, out parameterInUnpackValueMethods, out parameterInSetValueMethods, out parameterInCreateObjectFromContext);
        }
        public ConstructorSetting AddConstructor(Action <ConstructorDefinition> predicate)
        {
            var constructor = new ConstructorDefinition();

            constructors.Add(constructor);
            predicate(constructor);
            return(this);
        }
        public void Default()
        {
            ConstructorDefinition definition = ConstructorDefinition.Default;

            Assert.Equal(Visibility.Public, definition.AccessModifier);
            Assert.Equal(Type.EmptyTypes, definition.ParameterTypes);
            Assert.Null(definition.ImplementBaseClassConstructorCallCallback);             // null => call parameterless constructor of base class, if any
        }
        public void Create_CallingParameterlessBaseClassConstructor(Visibility visibility, Type[] parameterTypes)
        {
            ConstructorDefinition definition = new ConstructorDefinition(visibility, parameterTypes, null);             // null = call parameterless base class constructor

            Assert.Equal(visibility, definition.AccessModifier);
            Assert.Equal(parameterTypes, definition.ParameterTypes);
            Assert.Null(definition.ImplementBaseClassConstructorCallCallback);
        }
示例#11
0
        public override Object Visit(ConstructorDefinition node, Object obj)
        {
            if (node.Initialization != null)
            {
                node.Initialization.Accept(this, obj);
            }

            return(node.Body.Accept(this, obj));
        }
示例#12
0
        public void AddConstructorDefinition_CallingParameterlessBaseClassConstructor(Visibility visibility, Type[] parameterTypes)
        {
            ClassDefinition       definition  = new ClassDefinition();                                       // no base class, dynamic type name
            ConstructorDefinition constructor = new ConstructorDefinition(visibility, parameterTypes, null); // null => call parameterless base class constructor

            definition.AddConstructorDefinition(constructor);
            Assert.Single(definition.Constructors);
            Assert.Same(constructor, definition.Constructors.First());
        }
示例#13
0
        public override void GenerateCodeForClass(TranspilerContext sb, ClassDefinition classDef)
        {
            sb.Append(sb.CurrentTab);
            sb.Append("function ");
            sb.Append(classDef.NameToken.Value);
            sb.Append("(");
            ConstructorDefinition ctor = classDef.Constructor;

            for (int i = 0; i < ctor.ArgNames.Length; ++i)
            {
                if (i > 0)
                {
                    sb.Append(", ");
                }
                sb.Append(ctor.ArgNames[i].Value);
            }
            sb.Append(") {\n");
            sb.TabDepth++;
            sb.Append(sb.CurrentTab);
            sb.Append("let _PST_this = this;\n");
            foreach (FieldDefinition fd in classDef.Fields)
            {
                sb.Append(sb.CurrentTab);
                sb.Append("this.");
                sb.Append(fd.NameToken.Value);
                sb.Append(" = ");
                this.TranslateExpression(sb, fd.Value);
                sb.Append(";\n");
            }
            this.TranslateExecutables(sb, ctor.Code);
            foreach (FunctionDefinition func in classDef.Methods)
            {
                sb.Append(sb.CurrentTab);
                sb.Append(classDef.NameToken.Value);
                sb.Append(".prototype.");
                sb.Append(func.Name);
                sb.Append(" = function(");
                for (int i = 0; i < func.ArgNames.Length; ++i)
                {
                    if (i > 0)
                    {
                        sb.Append(", ");
                    }
                    sb.Append(func.ArgNames[i].Value);
                }
                sb.Append(") {\n");
                sb.TabDepth++;
                this.TranslateExecutables(sb, func.Code);
                sb.TabDepth--;
                sb.Append(sb.CurrentTab);
                sb.Append("};\n");
            }
            sb.TabDepth--;
            sb.Append("}\n");
        }
        public void EqualityAndHashCode_Default(Visibility visibility1, Type[] parameters1, Visibility visibility2, Type[] parameters2, bool equal)
        {
            ConstructorDefinition definition1 = new ConstructorDefinition(visibility1, parameters1, null);
            ConstructorDefinition definition2 = new ConstructorDefinition(visibility2, parameters2, null);

            Assert.Equal(equal, definition1.Equals(definition2));                        // IEquatable<T>.Equals()
            Assert.Equal(equal, definition2.Equals(definition1));                        // IEquatable<T>.Equals()
            Assert.Equal(equal, (definition1 as object).Equals(definition2));            // object.Equals()
            Assert.Equal(equal, (definition2 as object).Equals(definition1));            // object.Equals()
            Assert.Equal(equal, definition1.GetHashCode() == definition2.GetHashCode()); // different definitions CAN have the same hash code, but it is unlikely...
        }
        public void Create_CallingParameterizedBaseClassConstructor(Visibility visibility, Type[] parameterTypes)
        {
            // pass a callback method to call when it comes to implementing the call of a base class constructor
            // (empty implementation, as it is not significant for this test...)
            ImplementBaseClassConstructorCallCallback callback = (constructorDefinition, typeBuilder, msil) => { };
            ConstructorDefinition definition = new ConstructorDefinition(visibility, parameterTypes, callback);

            Assert.Equal(visibility, definition.AccessModifier);
            Assert.Equal(parameterTypes, definition.ParameterTypes);
            Assert.Same(callback, definition.ImplementBaseClassConstructorCallCallback);
        }
示例#16
0
        public static void Compile(ByteCodeCompiler bcc, ParserContext parser, ByteBuffer buffer, Instantiate instantiate, bool outputUsed)
        {
            ClassDefinition       cd          = instantiate.Class;
            ConstructorDefinition constructor = cd.Constructor;

            bcc.CompileExpressionList(parser, buffer, instantiate.Args, true);
            buffer.Add(instantiate.NameToken,
                       OpCode.CALL_FUNCTION,
                       (int)FunctionInvocationType.CONSTRUCTOR,
                       instantiate.Args.Length,
                       constructor.FunctionID,
                       outputUsed ? 1 : 0,
                       cd.ClassID);
        }
示例#17
0
        private static PropertyDefinition ParseMemberMemberBinding(
            PropertyInfo property,
            MemberMemberBinding memberMemberBinding)
        {
            var defaultConstructor = property.PropertyType.GetConstructor(new Type[0]);
            var constructor        = new ConstructorDefinition(defaultConstructor, new IGenerator[0]);
            var botConfiguration   = new BotConfiguration(property.PropertyType, constructor);

            foreach (var nestedBinding in memberMemberBinding.Bindings)
            {
                botConfiguration.Properties.Add(ParseMemberBinding(nestedBinding));
            }
            return(new PropertyDefinition(property, botConfiguration));
        }
        public void EqualityAndHashCode_UsingSignatureEqualityComparer(Visibility visibility1, Type[] parameters1, Visibility visibility2, Type[] parameters2, bool equal)
        {
            ConstructorDefinition definition1 = new ConstructorDefinition(visibility1, parameters1, null);
            ConstructorDefinition definition2 = new ConstructorDefinition(visibility2, parameters2, null);
            var comparer  = ConstructorDefinition.SignatureEquality as IEqualityComparer;
            var icomparer = ConstructorDefinition.SignatureEquality as IEqualityComparer;

            Assert.Equal(equal, comparer.Equals(definition1, definition2));
            Assert.Equal(equal, comparer.Equals(definition2, definition1));
            Assert.Equal(equal, icomparer.Equals(definition1, definition2));
            Assert.Equal(equal, icomparer.Equals(definition2, definition1));
            Assert.Equal(equal, comparer.GetHashCode(definition1) == comparer.GetHashCode(definition2));             // different definitions CAN have the same hash code, but it is unlikely...
            Assert.Equal(equal, icomparer.GetHashCode(definition1) == icomparer.GetHashCode(definition2));           // different definitions CAN have the same hash code, but it is unlikely...
        }
示例#19
0
        private static TopLevelEntity ParseClassConstructor(
            ParserContext context,
            ClassLikeDefinition classDef,
            Token firstToken,
            Dictionary <string, Token> modifiers,
            CSharpType type,
            TokenStream tokens)
        {
            List <CSharpType> argTypes     = new List <CSharpType>();
            List <Token>      argNames     = new List <Token>();
            List <Token>      argModifiers = new List <Token>();

            ParseArgList(argTypes, argNames, argModifiers, tokens);

            ConstructorDefinition constructorDef = new ConstructorDefinition(
                firstToken,
                modifiers,
                argTypes,
                argNames,
                argModifiers,
                classDef);

            if (tokens.PopIfPresent(":"))
            {
                if (!tokens.IsNext("base") && !tokens.IsNext("this"))
                {
                    tokens.PopExpected("base"); // intentionally throw
                }
                constructorDef.BaseConstructorInvocation = tokens.Pop();

                tokens.PopExpected("(");
                List <Expression> baseConstructorArgs = new List <Expression>();
                while (!tokens.PopIfPresent(")"))
                {
                    if (baseConstructorArgs.Count > 0)
                    {
                        tokens.PopExpected(",");
                    }
                    baseConstructorArgs.Add(ExpressionParser.Parse(context, tokens, constructorDef));
                }
                constructorDef.BaseConstructorArgs = baseConstructorArgs.ToArray();
            }

            constructorDef.Code = ExecutableParser.ParseCodeBlock(context, tokens, constructorDef, true);

            return(constructorDef);
        }
示例#20
0
        public override Object Visit(ConstructorDefinition node, Object obj)
        {
            int indent = Convert.ToInt32(obj);

            this.printIndentation(indent);
            this.output.WriteLine("Constructor: {0} [{1}:{2}]", node.Identifier, node.Location.Line, node.Location.Column);

            this.printIndentation(indent + 1);
            this.output.Write("Type: ");
            this.output.WriteLine(printType(node.TypeExpr));

            if (node.Initialization != null)
            {
                node.Initialization.Accept(this, indent + 1);
            }
            return(node.Body.Accept(this, indent + 1));
        }
示例#21
0
        protected override void DefineUnpackingContextCore(
            IList <KeyValuePair <string, TypeDefinition> > fields,
            out TypeDefinition type,
            out ConstructorDefinition constructor,
            out CodeDomConstruct parameterInUnpackValueMethods,
            out CodeDomConstruct parameterInSetValueMethods,
            out CodeDomConstruct parameterInCreateObjectFromContext
            )
        {
            var codeType = new CodeTypeDeclaration(SerializerBuilderHelper.UnpackingContextTypeName);
            var ctor     =
                new CodeConstructor
            {
                Attributes = MemberAttributes.Public
            };

            foreach (var kv in fields)
            {
                var field =
                    new CodeMemberField(CodeDomSerializerBuilder.ToCodeTypeReference(kv.Value), kv.Key)
                {
                    Attributes = MemberAttributes.Public
                };
                codeType.Members.Add(field);

                var param = new CodeParameterDeclarationExpression(CodeDomSerializerBuilder.ToCodeTypeReference(kv.Value), kv.Key);

                ctor.Parameters.Add(param);
                ctor.Statements.Add(
                    new CodeAssignStatement(
                        new CodeFieldReferenceExpression(
                            new CodeThisReferenceExpression(),
                            kv.Key
                            ),
                        new CodeArgumentReferenceExpression(kv.Key)
                        )
                    );
            }

            codeType.Members.Add(ctor);
            this._buildingType.Members.Add(codeType);
            type        = TypeDefinition.Object(codeType.Name);
            constructor = new ConstructorDefinition(type, fields.Select(kv => kv.Value).ToArray());
            DefineUnpackValueMethodArguments(type, out parameterInUnpackValueMethods, out parameterInSetValueMethods, out parameterInCreateObjectFromContext);
        }
示例#22
0
        public override Object Visit(ConstructorDefinition node, Object obj)
        {
            this.blockList      = new List <int>();
            this.indexBlockList = 0;

            this.table.Set();
            this.currentMethod = node.Identifier;
            this.parameterSymbol(node);

            if (node.Initialization != null)
            {
                node.Initialization.Accept(this, obj);
            }

            node.Body.Accept(this, node);
            this.currentMethod = "";
            this.table.Reset();
            return(null);
        }
示例#23
0
        protected virtual ConstructorDefinition ParseConstructor(
            TokenStream tokens,
            ClassDefinition owner,
            ModifierCollection modifiers,
            AnnotationCollection annotations)
        {
            Token constructorToken     = tokens.PopExpected(this.parser.Keywords.CONSTRUCTOR);
            ConstructorDefinition ctor = new ConstructorDefinition(constructorToken, modifiers, annotations, owner);

            tokens.PopExpected("(");

            List <AType>      argTypes  = new List <AType>();
            List <Token>      argNames  = new List <Token>();
            List <Expression> argValues = new List <Expression>();

            this.ParseArgumentListDeclaration(tokens, ctor, argTypes, argNames, argValues);

            List <Expression> baseArgs  = new List <Expression>();
            Token             baseToken = null;

            if (tokens.PopIfPresent(":"))
            {
                baseToken = tokens.PopExpected(this.parser.Keywords.BASE);
                tokens.PopExpected("(");
                while (!tokens.PopIfPresent(")"))
                {
                    if (baseArgs.Count > 0)
                    {
                        tokens.PopExpected(",");
                    }

                    baseArgs.Add(this.parser.ExpressionParser.Parse(tokens, ctor));
                }
            }

            IList <Executable> code = this.parser.ExecutableParser.ParseBlock(tokens, true, ctor);

            ctor.SetArgs(argNames, argValues, argTypes);
            ctor.SetBaseArgs(baseArgs);
            ctor.SetCode(code);
            ctor.BaseToken = baseToken;
            return(ctor);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ConstructorBasedImportDefinition"/> class.
        /// </summary>
        /// <param name="contractName">The contract name that is used to identify the current import.</param>
        /// <param name="requiredTypeIdentity">The type identity of the export type expected.</param>
        /// <param name="cardinality">
        ///     One of the enumeration values that indicates the cardinality of the export object required by the import definition.
        /// </param>
        /// <param name="creationPolicy">
        ///     A value that indicates that the importer requires a specific creation policy for the exports used to satisfy this import.
        /// </param>
        /// <param name="declaringType">The type that declares the constructor on which the import is placed.</param>
        /// <param name="constructor">The constructor that declares the import.</param>
        /// <param name="parameter">The parameter on which the import is defined.</param>
        private ConstructorBasedImportDefinition(
            string contractName,
            TypeIdentity requiredTypeIdentity,
            ImportCardinality cardinality,
            CreationPolicy creationPolicy,
            TypeIdentity declaringType,
            ConstructorDefinition constructor,
            ParameterDefinition parameter)
            : base(contractName, 
                requiredTypeIdentity, 
                cardinality,
                false,
                true,
                creationPolicy,
                declaringType)
        {
            {
                Lokad.Enforce.Argument(() => parameter);
            }

            m_Constructor = constructor;
            m_Parameter = parameter;
        }
 public override Object Visit(ConstructorDefinition node, Object obj)
 {
     this.CurrentAuxiliarSuffix = 0;
     node.Body.Accept(this, obj);
     return(this.decls);
 }
 /**
  * Call back method that must be called as soon as the given <code>
  * ConstructorDefinition</code> object has been traversed.
  *
  * @param pConstructorDefinition  The <code>ConstructorDefinition</code>
  *                                object that has just been traversed.
  */
 public void actionPerformed(
      
     ConstructorDefinition pConstructorDefinition)
 {
     // Nothing to do.
 }
 /**
  * Call back method that must be called when the given <code>
  * ConstructorDefinition</code> will become the next <i>traverse
  * candidate</i>.
  *
  * @param pConstructorDefinition  The <code>ConstructorDefinition</code>
  *                                object that will become the next <i>
  *                                traverse candidate</i>.
  */
 public void performAction(
      
     ConstructorDefinition pConstructorDefinition)
 {
     // Nothing to do.
 }
示例#28
0
        private ClassDefinition ParseClassDefinition(TokenStream tokens, TopLevelConstruct owner, Token staticToken, Token finalToken, FileScope fileScope)
        {
            Token classToken     = tokens.PopExpected(this.parser.Keywords.CLASS);
            Token classNameToken = tokens.Pop();

            this.parser.VerifyIdentifier(classNameToken);
            List <Token>  baseClassTokens  = new List <Token>();
            List <string> baseClassStrings = new List <string>();

            if (tokens.PopIfPresent(":"))
            {
                if (baseClassTokens.Count > 0)
                {
                    tokens.PopExpected(",");
                }

                Token  baseClassToken = tokens.Pop();
                string baseClassName  = baseClassToken.Value;

                this.parser.VerifyIdentifier(baseClassToken);
                while (tokens.PopIfPresent("."))
                {
                    Token baseClassTokenNext = tokens.Pop();
                    this.parser.VerifyIdentifier(baseClassTokenNext);
                    baseClassName += "." + baseClassTokenNext.Value;
                }

                baseClassTokens.Add(baseClassToken);
                baseClassStrings.Add(baseClassName);
            }

            ClassDefinition cd = new ClassDefinition(
                classToken,
                classNameToken,
                baseClassTokens,
                baseClassStrings,
                parser.CurrentNamespace,
                owner,
                parser.CurrentLibrary,
                staticToken,
                finalToken,
                fileScope);

            tokens.PopExpected("{");
            List <FunctionDefinition> methods              = new List <FunctionDefinition>();
            List <FieldDeclaration>   fields               = new List <FieldDeclaration>();
            ConstructorDefinition     constructorDef       = null;
            ConstructorDefinition     staticConstructorDef = null;

            while (!tokens.PopIfPresent("}"))
            {
                Dictionary <string, List <Annotation> > annotations = null;

                while (tokens.IsNext("@"))
                {
                    annotations = annotations ?? new Dictionary <string, List <Annotation> >();
                    Annotation annotation = this.parser.AnnotationParser.ParseAnnotation(tokens);
                    if (!annotations.ContainsKey(annotation.Type))
                    {
                        annotations[annotation.Type] = new List <Annotation>();
                    }

                    annotations[annotation.Type].Add(annotation);
                }

                if (tokens.IsNext(this.parser.Keywords.FUNCTION) ||
                    tokens.AreNext(this.parser.Keywords.STATIC, this.parser.Keywords.FUNCTION))
                {
                    methods.Add((FunctionDefinition)this.parser.ExecutableParser.ParseFunction(tokens, cd, fileScope));
                }
                else if (tokens.IsNext(this.parser.Keywords.CONSTRUCTOR))
                {
                    if (constructorDef != null)
                    {
                        throw new ParserException(tokens.Pop(), "Multiple constructors are not allowed. Use optional arguments.");
                    }

                    constructorDef = (ConstructorDefinition)this.parser.ExecutableParser.ParseConstructor(tokens, cd);

                    if (annotations != null && annotations.ContainsKey(this.parser.Keywords.PRIVATE))
                    {
                        constructorDef.PrivateAnnotation = annotations[this.parser.Keywords.PRIVATE][0];
                        annotations[this.parser.Keywords.PRIVATE].RemoveAt(0);
                    }
                }
                else if (tokens.AreNext(this.parser.Keywords.STATIC, this.parser.Keywords.CONSTRUCTOR))
                {
                    tokens.Pop(); // static token
                    if (staticConstructorDef != null)
                    {
                        throw new ParserException(tokens.Pop(), "Multiple static constructors are not allowed.");
                    }

                    staticConstructorDef = (ConstructorDefinition)this.parser.ExecutableParser.ParseConstructor(tokens, cd);
                }
                else if (tokens.IsNext(this.parser.Keywords.FIELD) ||
                         tokens.AreNext(this.parser.Keywords.STATIC, this.parser.Keywords.FIELD))
                {
                    fields.Add(this.parser.ExecutableParser.ParseField(tokens, cd));
                }
                else
                {
                    tokens.PopExpected("}");
                }

                if (annotations != null)
                {
                    foreach (List <Annotation> annotationsOfType in annotations.Values)
                    {
                        if (annotationsOfType.Count > 0)
                        {
                            throw new ParserException(annotationsOfType[0].FirstToken, "Unused or extra annotation.");
                        }
                    }
                }
            }

            cd.Methods           = methods.ToArray();
            cd.Constructor       = constructorDef;
            cd.StaticConstructor = staticConstructorDef;
            cd.Fields            = fields.ToArray();

            return(cd);
        }
示例#29
0
 public override Object Visit(ConstructorDefinition node, Object obj)
 {
     node.FullName      = getClassIdentifier();
     node.SetReturnType = getClassIdentifier();
     return(null);
 }
示例#30
0
        public override void GenerateCodeForClass(TranspilerContext sb, ClassDefinition classDef)
        {
            string name = classDef.NameToken.Value;

            sb.Append("public class " + name);
            if (classDef.ParentClass != null)
            {
                sb.Append(" : " + classDef.ParentClass.NameToken.Value);
            }
            sb.Append(this.NewLine);

            sb.Append("{");
            sb.Append(this.NewLine);
            sb.TabDepth++;
            foreach (FieldDefinition fd in classDef.Fields)
            {
                System.Text.StringBuilder line = new System.Text.StringBuilder();
                sb.Append(sb.CurrentTab);
                sb.Append("public ");
                sb.Append(this.TranslateType(fd.FieldType));
                sb.Append(' ');
                sb.Append(fd.NameToken.Value);
                sb.Append(" = ");
                this.TranslateExpression(sb, fd.Value);
                sb.Append(";");
                sb.Append(this.NewLine);
                sb.Append(this.NewLine);
            }

            ConstructorDefinition constructorDef = classDef.Constructor;

            sb.Append("    public ");
            sb.Append(name);
            sb.Append('(');
            for (int i = 0; i < constructorDef.ArgNames.Length; ++i)
            {
                if (i > 0)
                {
                    sb.Append(", ");
                }
                sb.Append(this.TranslateType(constructorDef.ArgTypes[i]));
                sb.Append(' ');
                sb.Append(constructorDef.ArgNames[i].Value);
            }
            sb.Append(")");
            sb.Append(this.NewLine);
            sb.Append(sb.CurrentTab);
            sb.Append("{");
            sb.Append(this.NewLine);
            sb.TabDepth++;
            this.TranslateExecutables(sb, constructorDef.Code);
            sb.TabDepth--;
            sb.Append(sb.CurrentTab);
            sb.Append("}");
            sb.Append(this.NewLine);
            sb.Append(this.NewLine);

            foreach (FunctionDefinition fd in classDef.Methods)
            {
                this.GenerateCodeForFunction(sb, fd, false);
                sb.Append(this.NewLine);
            }

            sb.TabDepth--;
            sb.Append(this.NewLine);
            sb.Append("}");
            sb.Append(this.NewLine);
        }
示例#31
0
        public static void Compile(ByteCodeCompiler bcc, ParserContext parser, ByteBuffer buffer, ConstructorDefinition constructor, ByteBuffer complexFieldInitializers)
        {
            ByteBuffer tBuffer = new ByteBuffer();

            ClassDefinition cd = (ClassDefinition)constructor.Owner;

            List <int> offsetsForOptionalArgs = new List <int>();

            FunctionDefinitionEncoder.CompileFunctionArgs(bcc, parser, tBuffer, constructor.ArgNames, constructor.DefaultValues, offsetsForOptionalArgs, constructor.ArgLocalIds);

            int minArgs = 0;
            int maxArgs = constructor.ArgNames.Length;

            for (int i = 0; i < constructor.ArgNames.Length; ++i)
            {
                if (constructor.DefaultValues[i] == null)
                {
                    minArgs++;
                }
                else
                {
                    break;
                }
            }

            if (constructor.BaseToken != null)
            {
                bcc.CompileExpressionList(parser, tBuffer, constructor.BaseArgs, true);
                tBuffer.Add(
                    constructor.BaseToken,
                    OpCode.CALL_FUNCTION,
                    (int)FunctionInvocationType.BASE_CONSTRUCTOR,
                    constructor.BaseArgs.Length,
                    cd.BaseClass.Constructor.FunctionID,
                    0,
                    cd.BaseClass.ClassID);
            }

            if (complexFieldInitializers != null)
            {
                tBuffer.Concat(complexFieldInitializers);
            }

            bcc.Compile(parser, tBuffer, constructor.Code);
            tBuffer.Add(null, OpCode.RETURN, 0);

            List <int> args = new List <int>()
            {
                constructor.FunctionID,
                -1,
                minArgs,
                maxArgs,
                constructor.Modifiers.HasStatic ? 4 : 3,
                cd.ClassID,
                constructor.LocalScopeSize,
                tBuffer.Size,
                offsetsForOptionalArgs.Count,
            };

            args.AddRange(offsetsForOptionalArgs);

            buffer.Add(constructor.FirstToken, OpCode.FUNCTION_DEFINITION, "<constructor>", args.ToArray());
            buffer.Concat(tBuffer);
        }
示例#32
0
        /// <summary>
        /// 要素の集合を文字列に変換
        /// </summary>
        private string ItemsToStringForBaseLayer(IEnumerable <object> items, List <string> baseClassNameList, List <List <LayerdMethodDefinition> > baseMethodLists, List <int> superClassIDs, int indent, string ns)
        {
            StringBuilder stringBuilder = new StringBuilder();
            bool          indentFlag    = true;
            Action <int>  addIndent     = (indentCount) =>
            {
                for (int i = 0; i < indentCount; ++i)
                {
                    stringBuilder.Append("\t");
                }
            };

            foreach (var item in items)
            {
                if (item is LayerDefinition)
                {
                    var ld = (LayerDefinition)item;
                    addIndent(indent);
                    stringBuilder.Append(@"namespace ");
                    stringBuilder.AppendLine(ld.Name);
                    addIndent(indent);
                    stringBuilder.AppendLine(@"{");
                    stringBuilder.AppendLine(ItemsToStringForBaseLayer(ld.Contents, baseClassNameList, baseMethodLists, superClassIDs, indent, "baselayer"));
                    addIndent(indent);
                    stringBuilder.AppendLine(@"}");
                    indentFlag = true;
                }
                else if (item is NamespaceDefinition)
                {
                    var    nd    = (NamespaceDefinition)item;
                    string newns = "";
                    if (ns == "")
                    {
                        newns = nd.Name;
                    }
                    else
                    {
                        newns = ns + "::" + nd.Name;
                    }
                    addIndent(indent);
                    if (nd.IsInline)
                    {
                        stringBuilder.Append(@"inline ");
                    }
                    stringBuilder.Append(@"namespace ");
                    stringBuilder.AppendLine(nd.Name);
                    addIndent(indent);
                    stringBuilder.AppendLine(@"{");
                    stringBuilder.AppendLine(ItemsToStringForBaseLayer(nd.Contents, baseClassNameList, baseMethodLists, superClassIDs, indent, newns));
                    addIndent(indent);
                    stringBuilder.AppendLine(@"}");
                    indentFlag = true;
                }
                else if (item is LayerdClassDefinition)
                {
                    var    lcd   = (LayerdClassDefinition)item;
                    string newns = "";
                    if (ns == "")
                    {
                        newns = lcd.Name;
                    }
                    else
                    {
                        newns = ns + "::" + lcd.Name;
                    }
                    addIndent(indent);
                    stringBuilder.Append(lcd.ClassKey);
                    stringBuilder.Append(" ");
                    stringBuilder.Append(lcd.Name);
                    if (lcd.SuperClasses.Count > 0)
                    {
                        stringBuilder.Append(" : ");
                        stringBuilder.Append(string.Join(", ", lcd.SuperClasses));
                    }
                    stringBuilder.AppendLine();
                    addIndent(indent);
                    stringBuilder.AppendLine(@"{");
                    if (!lcd.Contents.Exists((obj) => obj is ConstructorDefinition))
                    {
                        ConstructorDefinition constructor = new ConstructorDefinition(lcd.Name, new VariableDeclaration[] { }, new IgnoreObjectBlock("{", "}", new object[] { }), new string[] { }, false);
                        lcd.Contents.Add(constructor);
                    }
                    stringBuilder.AppendLine(ItemsToStringForBaseLayer(lcd.Contents, baseClassNameList, baseMethodLists, superClassIDs, indent + 1, newns));
                    addIndent(indent);
                    stringBuilder.AppendLine(@"};");
                    indentFlag = true;
                }
                else if (item is LayerdMethodDefinition)
                {
                    if (item is EventHandlerDefinition)
                    {
                    }
                    var lmd = (LayerdMethodDefinition)item;
                    addIndent(indent);
                    if (lmd.IsBase != null && !lmd.IsVirtual)
                    {
                        stringBuilder.Append(@"virtual ");
                    }
                    foreach (string modifier in lmd.Modifiers)
                    {
                        stringBuilder.Append(modifier);
                        stringBuilder.Append(@" ");
                    }
                    stringBuilder.Append(lmd.ReturnType);
                    stringBuilder.Append(@" ");
                    stringBuilder.Append(lmd.Name);
                    stringBuilder.Append(@" (");
                    stringBuilder.Append(string.Join(", ", lmd.Parameters));
                    stringBuilder.Append(@")");
                    foreach (string modifier in lmd.ThisModifiers)
                    {
                        stringBuilder.Append(@" ");
                        stringBuilder.Append(modifier);
                    }
                    if (lmd.IsNoexcept)
                    {
                        stringBuilder.Append(@" noexcept");
                    }
                    if (lmd.Contents is IgnoreObjectBlock)
                    {
                        stringBuilder.AppendLine();
                        stringBuilder.AppendLine(ItemsToStringForBaseLayer(((IgnoreObjectBlock)lmd.Contents).Contents, baseClassNameList, baseMethodLists, superClassIDs, indent, ns));
                    }
                    else
                    {
                        stringBuilder.AppendLine(lmd.Contents.ToString());
                    }
                    indentFlag = true;
                }
                else if (item is MethodImplementation)
                {
                    var mi = (MethodImplementation)item;
                    addIndent(indent);
                    stringBuilder.Append(mi.ReturnType);
                    stringBuilder.Append(@" ");
                    stringBuilder.Append(mi.FullName);
                    stringBuilder.Append(@" (");
                    stringBuilder.Append(string.Join(@", ", mi.Parameters));
                    stringBuilder.Append(@")");
                    foreach (string modifier in mi.ThisModifiers)
                    {
                        stringBuilder.Append(@" ");
                        stringBuilder.Append(modifier);
                    }
                    if (mi.IsNoexcept)
                    {
                        stringBuilder.Append(@" noexcept");
                    }
                    stringBuilder.AppendLine();
                    addIndent(indent);
                    stringBuilder.AppendLine(@"{");
                    // supercall
                    string newns = "";
                    if (ns == "")
                    {
                        newns = mi.ClassName;
                    }
                    else
                    {
                        newns = ns + "::" + mi.ClassName;
                    }
                    int classId = -1;
                    classId = baseClassNameList.IndexOf(newns);
                    if (classId == -1)
                    {
                        classId = baseClassNameList.IndexOf("baselayer::" + newns);
                    }
                    int superId = superClassIDs[classId];
                    if (superId != -1)
                    {
                        int methodId = baseMethodLists[classId].FindIndex((obj) => obj != null && obj.CompareMethod(mi.ToLayerdMethodDefinition()));
                        if (methodId != -1)
                        {
                            int methodOffset = 0;
                            if (Environment != DevelopmentEnvironment.VisualStudio)
                            {
                                for (int i = methodId - 1; i >= 0; --i)
                                {
                                    if (baseMethodLists[classId][i] == null)
                                    {
                                        methodOffset = 1;
                                        break;
                                    }
                                }
                            }
                            addIndent(indent + 1);
                            stringBuilder.Append(@"volatile void** _RTCOP_vft = RTCOP::Framework::Instance->GetRTCOPManager()->GetVirtualFunctionTable(");
                            stringBuilder.Append(superId);
                            stringBuilder.AppendLine(@");");
                            addIndent(indent + 1);
                            stringBuilder.Append(@"auto supercall = [this, _RTCOP_vft](");
                            int n = mi.Parameters.Count;
                            if (n > 0)
                            {
                                stringBuilder.Append(mi.Parameters[0].Type);
                                stringBuilder.Append(" ");
                                stringBuilder.Append(mi.Parameters[0].Name);
                                for (int i = 1; i < n; ++i)
                                {
                                    stringBuilder.Append(", ");
                                    stringBuilder.Append(mi.Parameters[i].Type);
                                    stringBuilder.Append(" ");
                                    stringBuilder.Append(mi.Parameters[i].Name);
                                }
                            }
                            stringBuilder.Append(@") { RTCOP::Generated::DependentCode::");
                            stringBuilder.Append(baseClassNameList[classId]);
                            stringBuilder.Append(@"::ExecuteProceed_");
                            stringBuilder.Append(mi.MethodName);
                            stringBuilder.Append(@"(this, _RTCOP_vft[");
                            stringBuilder.Append(methodId + methodOffset);
                            stringBuilder.Append(@"]");
                            foreach (var param in mi.Parameters)
                            {
                                stringBuilder.Append(@", ");
                                stringBuilder.Append(param.Name);
                            }
                            stringBuilder.AppendLine(@"); };");
                        }
                    }
                    // 中身
                    List <object> contents = mi.Contents.Contents.ToList();
                    contents.Remove(contents.Last());
                    contents.Remove(contents.First());
                    stringBuilder.AppendLine(ItemsToStringForBaseLayer(contents, baseClassNameList, baseMethodLists, superClassIDs, indent + 1, ns));
                    addIndent(indent);
                    stringBuilder.AppendLine(@"}");
                    stringBuilder.AppendLine();
                    indentFlag = true;
                }
                else if (item is VariableDeclaration)
                {
                    addIndent(indent);
                    stringBuilder.Append(item.ToString());
                    stringBuilder.AppendLine(";");
                    indentFlag = true;
                }
                else if (item is IgnoreObjectBlock)
                {
                    var           iob      = (IgnoreObjectBlock)item;
                    List <object> contents = iob.Contents.ToList();
                    if (contents.First().ToString() == "{")
                    {
                        stringBuilder.AppendLine();
                        contents.Remove(contents.Last());
                        contents.Remove(contents.First());
                        addIndent(indent);
                        stringBuilder.AppendLine(@"{");
                        stringBuilder.AppendLine(ItemsToStringForBaseLayer(contents, baseClassNameList, baseMethodLists, superClassIDs, indent, ns));
                        addIndent(indent);
                        stringBuilder.AppendLine(@"}");
                    }
                    else
                    {
                        stringBuilder.AppendLine(ItemsToStringForBaseLayer(iob.Contents, baseClassNameList, baseMethodLists, superClassIDs, indent, ns));
                    }
                    stringBuilder.AppendLine();
                    indentFlag = true;
                }
                else if (item is IgnoreObject)
                {
                    var io = (IgnoreObject)item;
                    if (indentFlag)
                    {
                        addIndent(indent);
                    }
                    if (io.Content is PreprocessDirective)
                    {
                        var directive = io.Content as PreprocessDirective;
                        if (directive.Kind == DirectiveKind.ImportBaseClassHeader || directive.Kind == DirectiveKind.ImportLayerHeader)
                        {
                            // 読み飛ばす
                        }
                        else
                        {
                            stringBuilder.AppendLine(io.Content.ToString());
                            indentFlag = true;
                        }
                    }
                    else
                    {
                        string text = io.Content.ToString();
                        if (text == "{")
                        {
                            stringBuilder.AppendLine(text);
                            indent    += 1;
                            indentFlag = true;
                        }
                        else if (text == "}")
                        {
                            stringBuilder.AppendLine(text);
                            indent    -= 1;
                            indentFlag = true;
                        }
                        else if ((text == ";") || (text == ":"))
                        {
                            stringBuilder.AppendLine(text);
                            indentFlag = true;
                        }
                        else
                        {
                            stringBuilder.Append(text);
                            stringBuilder.Append(" ");
                            indentFlag = false;
                        }
                    }
                }
                else
                {
                    addIndent(indent);
                    stringBuilder.AppendLine(item.ToString());
                }
            }
            return(stringBuilder.ToString());
        }
示例#33
0
 public abstract Object Visit(ConstructorDefinition node, Object obj);
示例#34
0
        private ClassDefinition ParseClassDefinition(TokenStream tokens, TopLevelConstruct owner, Token staticToken, Token finalToken, FileScope fileScope, AnnotationCollection classAnnotations)
        {
            Token classToken     = tokens.PopExpected(this.parser.Keywords.CLASS);
            Token classNameToken = tokens.Pop();

            this.parser.VerifyIdentifier(classNameToken);
            List <Token>  baseClassTokens  = new List <Token>();
            List <string> baseClassStrings = new List <string>();

            if (tokens.PopIfPresent(":"))
            {
                if (baseClassTokens.Count > 0)
                {
                    tokens.PopExpected(",");
                }

                Token  baseClassToken = tokens.Pop();
                string baseClassName  = baseClassToken.Value;

                this.parser.VerifyIdentifier(baseClassToken);
                while (tokens.PopIfPresent("."))
                {
                    Token baseClassTokenNext = tokens.Pop();
                    this.parser.VerifyIdentifier(baseClassTokenNext);
                    baseClassName += "." + baseClassTokenNext.Value;
                }

                baseClassTokens.Add(baseClassToken);
                baseClassStrings.Add(baseClassName);
            }

            ClassDefinition cd = new ClassDefinition(
                classToken,
                classNameToken,
                baseClassTokens,
                baseClassStrings,
                owner,
                parser.CurrentLibrary,
                staticToken,
                finalToken,
                fileScope,
                classAnnotations);

            tokens.PopExpected("{");
            List <FunctionDefinition> methods              = new List <FunctionDefinition>();
            List <FieldDeclaration>   fields               = new List <FieldDeclaration>();
            ConstructorDefinition     constructorDef       = null;
            ConstructorDefinition     staticConstructorDef = null;

            while (!tokens.PopIfPresent("}"))
            {
                AnnotationCollection annotations = this.parser.AnnotationParser.ParseAnnotations(tokens);

                if (tokens.IsNext(this.parser.Keywords.FUNCTION) ||
                    tokens.AreNext(this.parser.Keywords.STATIC, this.parser.Keywords.FUNCTION))
                {
                    methods.Add(this.parser.ExecutableParser.ParseFunction(tokens, cd, fileScope, annotations));
                }
                else if (tokens.IsNext(this.parser.Keywords.CONSTRUCTOR))
                {
                    if (constructorDef != null)
                    {
                        throw this.parser.GenerateParseError(
                                  ErrorMessages.CLASS_CANNOT_HAVE_MULTIPLE_CONSTRUCTORS,
                                  tokens.Pop());
                    }

                    constructorDef = this.parser.ExecutableParser.ParseConstructor(tokens, cd, annotations);
                }
                else if (tokens.AreNext(this.parser.Keywords.STATIC, this.parser.Keywords.CONSTRUCTOR))
                {
                    tokens.Pop(); // static token
                    if (staticConstructorDef != null)
                    {
                        throw new ParserException(tokens.Pop(), "Multiple static constructors are not allowed.");
                    }

                    staticConstructorDef = this.parser.ExecutableParser.ParseConstructor(tokens, cd, annotations);
                }
                else if (tokens.IsNext(this.parser.Keywords.FIELD) ||
                         tokens.AreNext(this.parser.Keywords.STATIC, this.parser.Keywords.FIELD))
                {
                    fields.Add(this.parser.ExecutableParser.ParseField(tokens, cd, annotations));
                }
                else
                {
                    tokens.PopExpected("}");
                }

                TODO.CheckForUnusedAnnotations();
            }

            cd.Methods           = methods.ToArray();
            cd.Constructor       = constructorDef;
            cd.StaticConstructor = staticConstructorDef;
            cd.Fields            = fields.ToArray();

            return(cd);
        }