コード例 #1
0
 public void Constructor_WhenCreatingConstructorWithModifiers_ShouldGenerateCorrectCode()
 {
     Assert.AreEqual("publicMyClass(){}", ConstructorGenerator.Create("MyClass", BodyGenerator.Create(), modifiers: new List <Modifiers>()
     {
         Modifiers.Public
     }).ToString());
 }
コード例 #2
0
ファイル: Linker.cs プロジェクト: TurpIF/verse
        private static bool LinkDecoderAsArray <TEntity>(IDecoderDescriptor <TEntity> descriptor, BindingFlags bindings,
                                                         Type type, object setter, IDictionary <Type, object> parents)
        {
            var constructor = MethodResolver
                              .Create <Func <object> >(() => ConstructorGenerator.CreateConstructor <object>())
                              .SetGenericArguments(type)
                              .Invoke(null);

            if (parents.TryGetValue(type, out var recurse))
            {
                MethodResolver
                .Create <Func <IDecoderDescriptor <TEntity>, Func <object>, Setter <TEntity, IEnumerable <object> >,
                               IDecoderDescriptor <object>, IDecoderDescriptor <object> > >((d, c, s, p) => d.HasElements(c, s, p))
                .SetGenericArguments(type)
                .Invoke(descriptor, constructor, setter, recurse);

                return(true);
            }

            var itemDescriptor = MethodResolver
                                 .Create <Func <IDecoderDescriptor <TEntity>, Func <object>, Setter <TEntity, IEnumerable <object> >,
                                                IDecoderDescriptor <object> > >((d, c, s) => d.HasElements(c, s))
                                 .SetGenericArguments(type)
                                 .Invoke(descriptor, constructor, setter);

            var result = MethodResolver
                         .Create <Func <IDecoderDescriptor <object>, BindingFlags, Dictionary <Type, object>, bool> >((d, f, p) =>
                                                                                                                      Linker.LinkDecoder(d, f, p))
                         .SetGenericArguments(type)
                         .Invoke(null, itemDescriptor, bindings, parents);

            return(result is bool success && success);
        }
コード例 #3
0
    public void TestGenerateDelegateEvents()
    {
        var gen         = new CodeUnitGenerator("TestCodeGen");
        var classGen    = new ClassGenerator("TestClass");
        var delegateGen = new DelegateGenerator("MyEventHandler")
                          .AddParameter("TestClass", "myRef")
                          .AddReturnType(typeof(bool));

        var eventGen = new EventGenerator("OnSomeTrigger", delegateGen.delegateType);

        classGen.AddEvent(eventGen);
        var fireEventMethod = new MethodGenerator("FireEvent")
                              .AddStatement(new StatementBuilder()
                                            //.AddSnippetExpression("Debug.Log();DoMoreStuff();"));
                                            .InvokeEvent(eventGen, new ParamBuilder()
                                                         .AddPrimitiveExpression("new TestClass()")));

        classGen.AddMethod(fireEventMethod);

        gen.AddType(delegateGen);
        gen.AddType(classGen);

        var classSubscriber = new ClassGenerator("MySubscribeClass");
        var field           = new FieldGenerator("TestClass", "eventSource");

        classSubscriber.AddField(field);

        var constructor = new ConstructorGenerator(classSubscriber.classType);

        classSubscriber.AddMethod(constructor);

        var eventHandler = new MethodGenerator("OnSomeTrigger", delegateGen)
                           .AddStatement(new StatementBuilder()
                                         .AddSnippet("Debug.Log(\"Expression1\");")
                                         .AddSnippet("Debug.Log(\"Expression2\");"));

        var subscribeMethod = new MethodGenerator("AddListener")
                              .AddStatement(new StatementBuilder()
                                            .AttachEvent(eventHandler, new FieldTarget(field), eventGen));

        classSubscriber.AddMethod(
            new MethodGenerator("Unsubscribe").AddStatement(
                new StatementBuilder()
                .DetachEvent(eventHandler, new FieldTarget(field), eventGen)));
        classSubscriber.AddMethod(eventHandler);
        classSubscriber.AddMethod(subscribeMethod);
        gen.AddType(classSubscriber);

        var ccu = gen.GenerateCompileUnit();

        var output = StringCompiler.CompileToString(ccu);

        //Debug.Log(output);
        Assert.IsTrue(output.Contains("OnSomeTrigger"));
        Assert.IsTrue(output.Contains("FireEvent"));
        Assert.IsTrue(output.Contains("+="));
        Assert.IsTrue(output.Contains("-="));
        Assert.IsTrue(output.Contains("delegate"));
        Assert.IsTrue(output.Contains("event"));
    }
コード例 #4
0
ファイル: AbstractGenerator.cs プロジェクト: Artan1s/misharp
        private SourceCode GetConstructors(SemanticModel semanticModel, HashSet <string> typeReferences, IEnumerable <ConstructorDeclarationSyntax> constructorDeclarations)
        {
            var generatedConstructors = new SourceCode {
                MainPart = ""
            };

            foreach (var constructorDeclaration in constructorDeclarations)
            {
                string identifier = constructorDeclaration.Identifier.ValueText;
                var    parameters = new List <Var>();
                foreach (var parameter in constructorDeclaration.ParameterList.Parameters)
                {
                    var typeReference = TypeReferenceGenerator.GenerateTypeReference(parameter.Type, semanticModel);
                    parameters.Add(new Var
                    {
                        Name = parameter.Identifier.ValueText,
                        Type = typeReference
                    });
                }
                var constructorAccessModifier = GetAccessModifier(constructorDeclaration.Modifiers.ToList());
                var statements = new List <string>();
                foreach (var statement in constructorDeclaration.Body.Statements)
                {
                    string generatedStatement = StatementGenerator.Generate(statement, semanticModel);
                    statements.Add(generatedStatement);
                }
                var generatedConstructor = ConstructorGenerator.Generate(identifier, constructorAccessModifier, parameters,
                                                                         statements, semanticModel);
                generatedConstructors.MainPart += "\n" + generatedConstructor.MainPart;
            }
            return(generatedConstructors);
        }
コード例 #5
0
    public void TestGenerateClassImplementation()
    {
        var gen      = new CodeUnitGenerator("TestCodeGen");
        var classGen = new ClassGenerator("TestClass")
                       .SetIsPartial(true)
                       .SetIsAbstract(true)
                       .AddBaseType("IComponent");
        var field       = new FieldGenerator(typeof(int), "MyField");
        var property    = new AutoPropertyGenerator("TestClass", "MyProp");
        var constructor = new ConstructorGenerator()
                          .AddBaseCall("BaseArg")
                          .AddParameter(field.FieldType, field.Name)
                          .AddParameter(property.Name, property.PropertyType)
                          .AddStatement(new StatementBuilder()
                                        .AddConstructorFieldAssignement(field.Name, field.Name)
                                        .AddConstructorPropertyAssignement(property.Name, property.Name));

        classGen.AddAutoProperty(property);
        classGen.AddField(field);
        classGen.AddMethod(constructor);
        gen.AddType(classGen);
        var ccu = gen.GenerateCompileUnit();

        var output = StringCompiler.CompileToString(ccu);

        Debug.Log(output);
        Assert.IsTrue(output.Contains("base("));
        Assert.IsTrue(output.Contains("BaseArg"));
    }
コード例 #6
0
        public void Test_CreateModelClass()
        {
            var classBuilder = new ClassBuilder("Cat", "Models");
            var @class       = classBuilder
                               .WithUsings("System")
                               .WithConstructor(
                ConstructorGenerator.Create(
                    "Cat",
                    BodyGenerator.Create(
                        Statement.Declaration.Assign("Name", ReferenceGenerator.Create(new VariableReference("name"))),
                        Statement.Declaration.Assign("Age", ReferenceGenerator.Create(new VariableReference("age")))),
                    new List <Parameter> {
                new Parameter("name", typeof(string)), new Parameter("age", typeof(int))
            },
                    new List <Modifiers> {
                Modifiers.Public
            }))
                               .WithProperties(
                PropertyGenerator.Create(new AutoProperty("Name", typeof(string), PropertyTypes.GetAndSet, new List <Modifiers> {
                Modifiers.Public
            })),
                PropertyGenerator.Create(new AutoProperty("Age", typeof(int), PropertyTypes.GetAndSet, new List <Modifiers> {
                Modifiers.Public
            })))
                               .Build();

            Assert.AreEqual(
                "usingSystem;namespaceModels{publicclassCat{publicCat(stringname,intage){Name=name;Age=age;}publicstringName{get;set;}publicintAge{get;set;}}}",
                @class.ToString());
        }
コード例 #7
0
        public ConstructorGenerator AddConstructor()
        {
            var c = new ConstructorGenerator(_declaration);

            _constructors.Add(c);
            return(c);
        }
コード例 #8
0
        /// <summary>
        /// Generate the class, fields and constructor for a page object
        /// </summary>
        /// <param name="pageObejctName">Name of the new page object</param>
        /// <param name="namespace">Name of the namespace to generate</param>
        /// <param name="uiObjects">UiObject inside the class</param>
        /// <param name="useAttributes">If we should generate ui objects as attributes</param>
        /// <returns>The generated code as a string</returns>
        public string GeneratePageObject(string pageObejctName, string @namespace, IEnumerable <UiObjectInfo> uiObjects, bool useAttributes)
        {
            var fields     = new List <Field>();
            var statements = new List <StatementSyntax>();

            fields.Add(new Field(DeviceName, typeof(IAndroidDevice), new[] { Modifiers.Private }));
            statements.Add(Statement.Declaration.Assign(new VariableReference("this", new MemberReference(DeviceName)), new VariableReference("device")));

            foreach (var pageObjectUiNode in uiObjects)
            {
                var generatedUiObject = GenerateUiObject(pageObjectUiNode, useAttributes);
                fields.Add(generatedUiObject.field);
                if (generatedUiObject.statement != null)
                {
                    statements.Add(generatedUiObject.statement);
                }
            }

            var classBuilder = new ClassBuilder(pageObejctName, @namespace)
                               .WithUsings("Testura.Android.Device", "Testura.Android.Device.Ui.Objects", "Testura.Android.Device.Ui.Search")
                               .WithFields(fields.ToArray())
                               .WithConstructor(ConstructorGenerator.Create(
                                                    pageObejctName,
                                                    BodyGenerator.Create(statements.ToArray()),
                                                    modifiers: new[] { Modifiers.Public },
                                                    parameters: new List <Parameter> {
                new Parameter("device", typeof(IAndroidDevice))
            }))
                               .Build();

            return(_codeSaver.SaveCodeAsString(classBuilder));
        }
コード例 #9
0
ファイル: Linker.cs プロジェクト: TurpIF/verse
        private static bool LinkDecoderAsObject <TEntity>(IDecoderDescriptor <TEntity> descriptor, BindingFlags bindings,
                                                          Type type, string name, object setter, IDictionary <Type, object> parents)
        {
            var constructor = MethodResolver
                              .Create <Func <object> >(() => ConstructorGenerator.CreateConstructor <object>())
                              .SetGenericArguments(type)
                              .Invoke(null);

            if (parents.TryGetValue(type, out var parent))
            {
                MethodResolver
                .Create <Func <IDecoderDescriptor <TEntity>, string, Func <object>, Setter <TEntity, object>,
                               IDecoderDescriptor <object>, IDecoderDescriptor <object> > >((d, n, c, s, p) =>
                                                                                            d.HasField(n, c, s, p))
                .SetGenericArguments(type)
                .Invoke(descriptor, name, constructor, setter, parent);

                return(true);
            }

            var fieldDescriptor = MethodResolver
                                  .Create <Func <IDecoderDescriptor <TEntity>, string, Func <object>, Setter <TEntity, object>,
                                                 IDecoderDescriptor <object> > >((d, n, c, s) => d.HasField(n, c, s))
                                  .SetGenericArguments(type)
                                  .Invoke(descriptor, name, constructor, setter);

            var result = MethodResolver
                         .Create <Func <IDecoderDescriptor <object>, BindingFlags, Dictionary <Type, object>, bool> >((d, f, p) =>
                                                                                                                      Linker.LinkDecoder(d, f, p))
                         .SetGenericArguments(type)
                         .Invoke(null, fieldDescriptor, bindings, parents);

            return(result is bool success && success);
        }
コード例 #10
0
            public ParameterGenerator(ConstructorGenerator constructor, SourceType type, TypeSyntax actualType, string name)
            {
                Name       = IdentifierName(name);
                SourceType = type;
                ActualType = actualType;

                _constructor = constructor;
                _constructor.Parameters.Add(CreateParameter());
            }
コード例 #11
0
ファイル: Linker.cs プロジェクト: TurpIF/verse
        /// <summary>
        /// Describe and create decoder for given schema using reflection on target entity and provided binding flags.
        /// </summary>
        /// <typeparam name="TEntity">Entity type</typeparam>
        /// <param name="schema">Entity schema</param>
        /// <param name="bindings">Binding flags used to filter bound fields and properties</param>
        /// <returns>Entity decoder</returns>
        public static IDecoder <TEntity> CreateDecoder <TEntity>(ISchema <TEntity> schema, BindingFlags bindings)
        {
            if (!Linker.LinkDecoder(schema.DecoderDescriptor, bindings, new Dictionary <Type, object>()))
            {
                throw new ArgumentException($"can't link decoder for type '{typeof(TEntity)}'", nameof(schema));
            }

            return(schema.CreateDecoder(ConstructorGenerator.CreateConstructor <TEntity>()));
        }
コード例 #12
0
 public ClassGenerator(MemberInfoList memberInfoList, Type interfaceType, NameDefinition nameDefinition, IDefinition[] definitions)
 {
     this.interfaceType   = interfaceType;
     this.nameDefinition  = nameDefinition;
     this.definitions     = definitions;
     constructorGenerator = new ConstructorGenerator(nameDefinition.ClassName);
     propertiesGenerator  = new PropertyGenerators(memberInfoList.PropertyInfos, definitions);
     methodGenerators     = new MethodGenerators(
         memberInfoList.MethodInfos, memberInfoList.MethodIndexes, definitions);
     eventGenerators = new EventGenerators(memberInfoList.EventInfos, definitions);
 }
コード例 #13
0
        public override void CreateMember(TypeGenerator generator)
        {
            var parameters     = Parameters.Map(para => para.GetParameterInfo(generator.Context));
            var parameterTypes = parameters.Map(para => para.Type);
            var ctor           = generator.Builder.DefineConstructor(GetAttributes(), System.Reflection.CallingConventions.Standard, parameterTypes);
            var ctorGen        = new ConstructorGenerator(ctor, parameters, generator)
            {
                SyntaxBody = Body
            };

            generator.Add(ctorGen);
        }
コード例 #14
0
 public void Constructor_WhenCreatingConstructorWithParamterAndModifierAndAttribute_ShouldGenerateCorrectCode()
 {
     Assert.AreEqual("[Test]publicMyClass(inti){}",
                     ConstructorGenerator.Create("MyClass", BodyGenerator.Create(),
                                                 new List <Parameter> {
         new Parameter("i", typeof(int))
     }, new List <Modifiers>()
     {
         Modifiers.Public
     },
                                                 new List <Attribute> {
         new Attribute("Test")
     }).ToString());
 }
コード例 #15
0
        public void Test_CreateModelClassWithBodyProperties()
        {
            var classBuilder = new ClassBuilder("Cat", "Models");
            var @class       = classBuilder
                               .WithUsings("System")
                               .WithFields(
                new Field("_name", typeof(string), new List <Modifiers>()
            {
                Modifiers.Private
            }),
                new Field("_age", typeof(int), new List <Modifiers>()
            {
                Modifiers.Private
            }))
                               .WithConstructor(
                ConstructorGenerator.Create(
                    "Cat",
                    BodyGenerator.Create(
                        Statement.Declaration.Assign("Name", ReferenceGenerator.Create(new VariableReference("name"))),
                        Statement.Declaration.Assign("Age", ReferenceGenerator.Create(new VariableReference("age")))),
                    new List <Parameter> {
                new Parameter("name", typeof(string)), new Parameter("age", typeof(int))
            },
                    new List <Modifiers> {
                Modifiers.Public
            }))
                               .WithProperties(
                PropertyGenerator.Create(
                    new BodyProperty(
                        "Name",
                        typeof(string),
                        BodyGenerator.Create(Statement.Jump.Return(new VariableReference("_name"))), BodyGenerator.Create(Statement.Declaration.Assign("_name", new ValueKeywordReference())),
                        new List <Modifiers> {
                Modifiers.Public
            })),
                PropertyGenerator.Create(
                    new BodyProperty(
                        "Age",
                        typeof(int),
                        BodyGenerator.Create(Statement.Jump.Return(new VariableReference("_age"))), BodyGenerator.Create(Statement.Declaration.Assign("_age", new ValueKeywordReference())),
                        new List <Modifiers> {
                Modifiers.Public
            })))
                               .Build();

            Assert.AreEqual(
                "usingSystem;namespaceModels{publicclassCat{privatestring_name;privateint_age;publicCat(stringname,intage){Name=name;Age=age;}publicstringName{get{return_name;}set{_name=value;}}publicintAge{get{return_age;}set{_age=value;}}}}",
                @class.ToString());
        }
コード例 #16
0
ファイル: IoCConfig.cs プロジェクト: tukayam/autosetup
        public IXUnitSetupGenerator GetInstance(IClassUnderTestFinder classUnderTestFinder)
        {
            var classUnderTestNameFinder       = new ClassUnderTestNameFinder();
            var constructorParametersExtractor = new ConstructorParametersExtractor();
            var fieldFinder                  = new FieldFinder();
            var memberFinder                 = new MemberFinder();
            var constructorGenerator         = new ConstructorGenerator();
            var expressionStatementGenerator = new ExpressionStatementGenerator();
            var fieldNameGenerator           = new FieldNameGenerator();
            var fieldDeclarationGenerator    = new FieldDeclarationGenerator(fieldNameGenerator);
            var methodGenerator              = new MethodGenerator();
            var usingDirectivesGenerator     = new UsingDirectivesGenerator();

            var setupMethodBodyBuilder = new SetupMethodBodyBuilder(constructorParametersExtractor, expressionStatementGenerator, fieldNameGenerator);

            return(new XUnitSetupGenerator(classUnderTestNameFinder, classUnderTestFinder, constructorParametersExtractor, fieldDeclarationGenerator, setupMethodBodyBuilder, constructorGenerator, usingDirectivesGenerator, memberFinder, fieldFinder));
        }
コード例 #17
0
        internal void Start()
        {
            assembly.Context.Register("Console", typeof(Console));
            // code.Compile(assembly);
            valueField = typeGen.DefineField("value", typeof(object), FieldAttributes.Private);
            valueField.SetCustomAttribute(typeof(DebuggerBrowsableAttribute), typeof(DebuggerBrowsableAttribute).GetInstanceCtor(typeof(DebuggerBrowsableState)), DebuggerBrowsableState.Never);
            // ctor
            var ctorParams = new ParameterInfo[] { new ParameterInfo("val", 0, typeof(object)) };
            ConstructorGenerator ctorGen = typeGen.DefineCtor(ctorParams, MethodAttributes.Public);

            ctorGen.SyntaxBody = new BlockStatement(new NodeList <Statement>
            {
                Expression.Assign(Expression.Member("value"), Expression.Parameter(ctorParams[0]))
            });

            EmitOpImplicit(typeGen);
            EmitOpAddition(typeGen);
            EmitToStringMethod();
            typeGen.CreateType();
            assembly.Save("FluidScript.Runtime.dll");
        }
コード例 #18
0
        public void Test_CreateClassWithMethodThatHaveMultipleSUmmarysAndSingleLineComments()
        {
            var classBuilder = new ClassBuilder("Cat", "Models");
            var @class       = classBuilder
                               .WithUsings("System")
                               .WithSummary("My class summary")
                               .WithConstructor(ConstructorGenerator.Create(
                                                    "Cat",
                                                    BodyGenerator.Create(
                                                        Statement.Declaration.Assign("Name", ReferenceGenerator.Create(new VariableReference("name"))),
                                                        Statement.Declaration.Assign("Age", ReferenceGenerator.Create(new VariableReference("age")))),
                                                    new List <Parameter> {
                new Parameter("name", typeof(string)), new Parameter("age", typeof(int), xmlDocumentation: "My parameter")
            },
                                                    new List <Modifiers> {
                Modifiers.Public
            },
                                                    summary: "MyConstructor summary"))
                               .WithProperties(new AutoProperty("MyProperty", typeof(int), PropertyTypes.GetAndSet, summary: "MyPropertySummary"))
                               .WithFields(
                new Field("_name", typeof(string), new List <Modifiers>()
            {
                Modifiers.Private
            }, summary: "My field summary"))
                               .WithMethods(new MethodBuilder("MyMethod")
                                            .WithParameters(new Parameter("MyParameter", typeof(string)))
                                            .WithBody(
                                                BodyGenerator.Create(
                                                    Statement.Declaration.Declare("hello", typeof(int)).WithComment("My comment above").WithComment("hej"),
                                                    Statement.Declaration.Declare("hello", typeof(int)).WithComment("My comment to the side", CommentPosition.Right)
                                                    ))
                                            .Build())
                               .Build();

            Assert.AreEqual(
                "usingSystem;namespaceModels{/// <summary>\n/// My class summary\n/// </summary>\npublicclassCat{/// <summary>\n/// MyConstructor summary\n/// </summary>\n/// <param name=\"age\">My parameter</param>\npublicCat(stringname,intage){Name=name;Age=age;}/// <summary>\n/// MyPropertySummary\n/// </summary>\nintMyProperty{get;set;}/// <summary>\n/// My field summary\n/// </summary>\nprivatestring_name;voidMyMethod(stringMyParameter){//hej\ninthello;inthello; //My comment to the side\n}}}",
                @class.ToString());
        }
コード例 #19
0
        public void Test_CreateClassWithRegionWithMultipleMembers()
        {
            var classBuilder = new ClassBuilder("Cat", "Models");
            var @class       = classBuilder
                               .WithUsings("System")
                               .WithRegions(new RegionBuilder("MyRegion")
                                            .WithFields(
                                                new Field("_name", typeof(string), new List <Modifiers>()
            {
                Modifiers.Private
            }),
                                                new Field("_age", typeof(int), new List <Modifiers>()
            {
                Modifiers.Private
            }))
                                            .WithProperties(PropertyGenerator.Create(new AutoProperty("Name", typeof(string), PropertyTypes.GetAndSet, new List <Modifiers> {
                Modifiers.Public
            })))
                                            .WithConstructor(
                                                ConstructorGenerator.Create(
                                                    "Cat",
                                                    BodyGenerator.Create(
                                                        Statement.Declaration.Assign("Name", ReferenceGenerator.Create(new VariableReference("name"))),
                                                        Statement.Declaration.Assign("Age", ReferenceGenerator.Create(new VariableReference("age")))),
                                                    new List <Parameter> {
                new Parameter("name", typeof(string)), new Parameter("age", typeof(int))
            },
                                                    new List <Modifiers> {
                Modifiers.Public
            }))
                                            .Build())
                               .Build();

            Assert.AreEqual(
                "usingSystem;namespaceModels{publicclassCat{#region MyRegion \nprivatestring_name;privateint_age;publicstringName{get;set;}publicCat(stringname,intage){Name=name;Age=age;}#endregion}}",
                @class.ToString());
        }
コード例 #20
0
 public void Constructor_WhenCreatingConstructorWithAttribute_ShouldGenerateCorrectCode()
 {
     Assert.AreEqual("[Test]MyClass(){}", ConstructorGenerator.Create("MyClass", BodyGenerator.Create(), attributes: new List <Attribute> {
         new Attribute("Test")
     }).ToString());
 }
コード例 #21
0
 public ConstructorGeneratorTests()
 {
     _target = new ConstructorGenerator();
 }
コード例 #22
0
        protected override TypeGenerator OnGenerateType(ref string output, NamespaceGenerator @namespace)
        {
            var @class = ClassGenerator.Class(RootAccessModifier.Public, ClassModifier.None, Data.title.LegalMemberName(), Data.scriptableObject ? typeof(ScriptableObject) : typeof(object));

            if (Data.definedEvent)
            {
                @class.ImplementInterface(typeof(IDefinedEvent));
            }
            if (Data.inspectable)
            {
                @class.AddAttribute(AttributeGenerator.Attribute <InspectableAttribute>());
            }
            if (Data.serialized)
            {
                @class.AddAttribute(AttributeGenerator.Attribute <SerializableAttribute>());
            }
            if (Data.includeInSettings)
            {
                @class.AddAttribute(AttributeGenerator.Attribute <IncludeInSettingsAttribute>().AddParameter(true));
            }
            if (Data.scriptableObject)
            {
                @class.AddAttribute(AttributeGenerator.Attribute <CreateAssetMenuAttribute>().AddParameter("menuName", Data.menuName).AddParameter("fileName", Data.fileName).AddParameter("order", Data.order));
            }

            for (int i = 0; i < Data.constructors.Count; i++)
            {
                var constructor = ConstructorGenerator.Constructor(Data.constructors[i].scope, Data.constructors[i].modifier, Data.title.LegalMemberName());
                if (Data.constructors[i].graph.units.Count > 0)
                {
                    var unit = Data.constructors[i].graph.units[0] as FunctionNode;
                    constructor.Body(FunctionNodeGenerator.GetSingleDecorator(unit, unit).GenerateControl(null, new ControlGenerationData(), 0));

                    for (int pIndex = 0; pIndex < Data.constructors[i].parameters.Count; pIndex++)
                    {
                        if (!string.IsNullOrEmpty(Data.constructors[i].parameters[pIndex].name))
                        {
                            constructor.AddParameter(false, ParameterGenerator.Parameter(Data.constructors[i].parameters[pIndex].name, Data.constructors[i].parameters[pIndex].type, ParameterModifier.None));
                        }
                    }
                }

                @class.AddConstructor(constructor);
            }

            for (int i = 0; i < Data.variables.Count; i++)
            {
                if (!string.IsNullOrEmpty(Data.variables[i].name) && Data.variables[i].type != null)
                {
                    var attributes = Data.variables[i].attributes;

                    if (Data.variables[i].isProperty)
                    {
                        var property = PropertyGenerator.Property(Data.variables[i].scope, Data.variables[i].propertyModifier, Data.variables[i].type, Data.variables[i].name, false);

                        for (int attrIndex = 0; attrIndex < attributes.Count; attrIndex++)
                        {
                            AttributeGenerator attrGenerator = AttributeGenerator.Attribute(attributes[attrIndex].GetAttributeType());
                            property.AddAttribute(attrGenerator);
                        }

                        if (Data.variables[i].get)
                        {
                            property.MultiStatementGetter(AccessModifier.Public, NodeGenerator.GetSingleDecorator(Data.variables[i].getter.graph.units[0] as Unit, Data.variables[i].getter.graph.units[0] as Unit)
                                                          .GenerateControl(null, new ControlGenerationData()
                            {
                                returns = Data.variables[i].type
                            }, 0));
                        }

                        if (Data.variables[i].set)
                        {
                            property.MultiStatementSetter(AccessModifier.Public, NodeGenerator.GetSingleDecorator(Data.variables[i].setter.graph.units[0] as Unit, Data.variables[i].setter.graph.units[0] as Unit)
                                                          .GenerateControl(null, new ControlGenerationData(), 0));
                        }

                        @class.AddProperty(property);
                    }
                    else
                    {
                        var field = FieldGenerator.Field(Data.variables[i].scope, Data.variables[i].fieldModifier, Data.variables[i].type, Data.variables[i].name);


                        for (int attrIndex = 0; attrIndex < attributes.Count; attrIndex++)
                        {
                            AttributeGenerator attrGenerator = AttributeGenerator.Attribute(attributes[attrIndex].GetAttributeType());
                            field.AddAttribute(attrGenerator);
                        }

                        @class.AddField(field);
                    }
                }
            }

            for (int i = 0; i < Data.methods.Count; i++)
            {
                if (!string.IsNullOrEmpty(Data.methods[i].name) && Data.methods[i].returnType != null)
                {
                    var method = MethodGenerator.Method(Data.methods[i].scope, Data.methods[i].modifier, Data.methods[i].returnType, Data.methods[i].name);
                    if (Data.methods[i].graph.units.Count > 0)
                    {
                        var unit = Data.methods[i].graph.units[0] as FunctionNode;
                        method.Body(FunctionNodeGenerator.GetSingleDecorator(unit, unit).GenerateControl(null, new ControlGenerationData(), 0));

                        for (int pIndex = 0; pIndex < Data.methods[i].parameters.Count; pIndex++)
                        {
                            if (!string.IsNullOrEmpty(Data.methods[i].parameters[pIndex].name))
                            {
                                method.AddParameter(ParameterGenerator.Parameter(Data.methods[i].parameters[pIndex].name, Data.methods[i].parameters[pIndex].type, ParameterModifier.None));
                            }
                        }
                    }

                    @class.AddMethod(method);
                }
            }

            @namespace.AddClass(@class);

            return(@class);
        }
コード例 #23
0
 public void Constructor_WhenCreatingConstructorWithBaseInitializerWithArgument_ShouldGenerateCorrectCode()
 {
     Assert.AreEqual("MyClass():base(\"myText\"){}", ConstructorGenerator.Create("MyClass", BodyGenerator.Create(), constructorInitializer: new ConstructorInitializer(ConstructorInitializerTypes.Base, new List <Argument> {
         new ValueArgument("myText")
     })).ToString());
 }
コード例 #24
0
 public RequiredParameterGenerator(ConstructorGenerator constructor, SourceType type, TypeSyntax actualType, string name)
     : base(constructor, type, actualType, name)
 {
 }
コード例 #25
0
 public OptionalParameterGenerator(ConstructorGenerator constructor, SourceType type, TypeSyntax actualType, string name)
     : base(constructor, type, NullableType(actualType), name)
 {
 }
コード例 #26
0
 public void Constructor_WhenCreatingConstructorWithBaseInitializer_ShouldGenerateCorrectCode()
 {
     Assert.AreEqual("MyClass():base(){}", ConstructorGenerator.Create("MyClass", BodyGenerator.Create(), constructorInitializer: new ConstructorInitializer(ConstructorInitializerTypes.Base, null)).ToString());
 }
コード例 #27
0
 public void Constructor_WhenCreatingConstructor_ShouldGenerateCorrectCode()
 {
     Assert.AreEqual("MyClass(){}", ConstructorGenerator.Create("MyClass", BodyGenerator.Create()).ToString());
 }
コード例 #28
0
 public void Constructor_WhenCreatingConstructorWithParameters_ShouldGenerateCorrectCode()
 {
     Assert.AreEqual("MyClass(inttest){}", ConstructorGenerator.Create("MyClass", BodyGenerator.Create(), new List <Parameter> {
         new Parameter("test", typeof(int))
     }).ToString());
 }