Example #1
0
        public void JsonAttributePropertyDeclaration()
        {
            //public int CategoryID {get;set;} //PrimaryKey not null
            PropertyTemplate property = new PropertyTemplate
            {
                PropName = "CategoryID",
                PropType = "int",
                IsKey    = true
            };
            var pg = new PropertyGenerator(property, new PocoSetting
            {
                AddJsonAttribute = true
            });
            //  Debug.WriteLine(pg);
            var expected = "[JsonProperty(PropertyName = \"CategoryID\")]";

            Assert.IsTrue(pg.ToString().Contains(expected));
        }
Example #2
0
        //products
        public void EagerVirtualPropertyDeclaration()
        {
            PropertyTemplate property = new PropertyTemplate
            {
                PropName    = "Products",
                PropType    = "List<Product>",
                PropComment = "// not null",
                IsNavigate  = true
            };

            PropertyGenerator pg = new PropertyGenerator(property, new PocoSetting
            {
                AddEager      = true,
                AddNavigation = true
            });

            //   Debug.WriteLine(pg);
            Assert.IsTrue(pg.Declaration.Contains("public List<Product> Products {get;set;}"));
        }
        public string ObterTextoEmHTML(Stream stream)
        {
            DocX doc = DocX.Load(stream);
            IList <Paragraph> Paragrafos = doc.Paragraphs;
            StringBuilder     Texto      = new StringBuilder();

            foreach (Paragraph p in Paragrafos)
            {
                IEnumerable <Bookmark> Bookmarks = p.GetBookmarks();
                foreach (Bookmark b in Bookmarks)
                {
                    string propriedade = PropertyGenerator.CreateHTMLProperty("class", "text-primary");
                    string text        = AninharEmElemento("p", b.Name, propriedade);
                    b.Paragraph.InsertAtBookmark($" {text} ", b.Name);
                }
                Texto.AppendLine($" {p.Text}");
            }
            return(Texto.ToString());
        }
Example #4
0
    public void PreClassesHook()
    {
        IDictionary <string, string> documentation = Documentation.Get(Data.Docs);

        foreach (CodeTypeDeclaration type in from smokeType in this.Data.SmokeTypeMap
                 where string.IsNullOrEmpty((string)smokeType.Value.UserData["parent"])
                 select smokeType.Value)
        {
            foreach (CodeTypeDeclaration nestedType in type.Members.OfType <CodeTypeDeclaration>().Where(t => !t.IsEnum))
            {
                this.GetClassDocs(nestedType, string.Format("{0}::{1}", type.Name, nestedType.Name),
                                  string.Format("{0}-{1}", type.Name, nestedType.Name), documentation);
            }
            this.GetClassDocs(type, type.Name, type.Name, documentation);
        }
        PropertyGenerator pg = new PropertyGenerator(Data, Translator, this.memberDocumentation);

        pg.Run();
    }
Example #5
0
        public static HtmlString MensagemDePropriedadesEmHTML <T>(this T entity, string divClass, string OuterDivClass = null, string OuterDivId = null) where T : ModeloBase
        {
            OuterDivClass = OuterDivClass ?? string.Empty;
            OuterDivId    = OuterDivId ?? string.Empty;

            StringBuilder Sb = new StringBuilder();

            foreach (var prop in entity.GetType().GetProperties())
            {
                try
                {
                    if (!prop.IsADEDominio(entity) && !prop.IsByteArray())
                    {
                        if (!prop.IsKey())
                        {
                            string NomeAtributo      = ObterNomePropriedade(prop);
                            string ValorAtributo     = ObterValorPropriedade(prop, entity);
                            string DescricaoAtributo = PropertyGenerator.CreateHTMLProperty("title", ObterDescricaoPropriedade(prop));
                            string LabelFor          = CreateHTMLProperty("for", prop.Name);
                            string Div = AninharEmDiv(string.Format(" {0}{1} ", AninharEmLabel(NomeAtributo, LabelFor) + "</br>", AninharEmParagrafo(ValorAtributo, DescricaoAtributo + CreateHTMLProperty("id", prop.Name)), CreateHTMLProperty("class", divClass)));
                            Sb.AppendLine(Div);
                        }
                    }
                }
                catch (Exception) { continue; }
            }
            string texto = Sb.ToString();
            string OuterDivProperties = string.Empty;

            if (OuterDivClass != null)
            {
                OuterDivProperties += CreateHTMLProperty("class", OuterDivClass);
            }
            if (OuterDivId != null)
            {
                OuterDivProperties += CreateHTMLProperty("id", OuterDivId);
            }
            AninharEmDiv(ref texto, OuterDivProperties);
            HtmlString textoHtml = new HtmlString(texto);

            return(textoHtml);
        }
        public void Property_has_type_without_prefix_namespac_test()
        {
            // Arrange
            var setting = new PocoSetting
            {
                AddEager = false,
            };
            var property = new PropertyTemplate
            {
                PropName       = "Table",
                PropType       = "SimpleDataTable",
                ClassNameSpace = "SP",
            };
            var expected = "public SimpleDataTable Table {get;set;}";
            // Act
            string sut = new PropertyGenerator(property, setting);

            // Assert
            Assert.IsTrue(sut.Contains(expected));
        }
Example #7
0
        public void KeyAttributePropertyDeclaration()
        {
            PropertyTemplate property = new PropertyTemplate
            {
                PropName = "CategoryID",
                PropType = "int",
                IsKey    = true
            };
            var pg = new PropertyGenerator(property, new PocoSetting
            {
                AddKeyAttribute = true
            });
            //  Debug.WriteLine(pg);
            var expected = @"
[Key]
public int CategoryID {get;set;} ";

            //Assert.IsTrue(CompareStringIgnoringSpaceCr(pg.ToString(), expected));
            Assert.AreEqual(pg.ToString().TrimAllSpace(), expected.TrimAllSpace());
        }
        public void NoneCasePropertyDeclaration_test()
        {
            // Arrange
            var setting = new PocoSetting
            {
                NameCase = CaseEnum.None
            };

            _attributeManager.Init(setting);
            var property = new PropertyTemplate
            {
                PropName = "Category_ID",
                PropType = "int",
                IsKey    = true
            };
            // Act
            var sut = new PropertyGenerator(property, setting);

            // Assert
            Assert.IsTrue(sut.Declaration.Contains("public int Category_ID {get;set;}"));
        }
Example #9
0
        public void AllAttributesPropertyDeclaration()
        {
            PropertyTemplate property = new PropertyTemplate
            {
                PropName = "CategoryID",
                PropType = "int",
                IsKey    = true
            };
            var pg = new PropertyGenerator(property, new PocoSetting
            {
                AddKeyAttribute      = true,
                AddRequiredAttribute = true,
                AddJsonAttribute     = true
            });

            //Debug.WriteLine(pg);

            Assert.IsTrue(pg.ToString().Contains("[Key]") &&
                          pg.ToString().Contains("[Required]") &&
                          pg.ToString().Contains("[JsonProperty(PropertyName = \"CategoryID\")]"));
        }
Example #10
0
        public void Test1()
        {
            var expected = @"#region byte A
byte _a;
public byte A
{
    get{ return _a; }
    set
	{
		if ( _a != value )
		{
			_a = value;
			OnPropertyChanged(""A"");

        }
    }
}
#endregion";
            var result   = new PropertyGenerator().Generate("byte", "A");

            Assert.IsTrue(Compare(expected, result));
        }
Example #11
0
        public void JsonAttributeWithCamelCasePropertyDeclaration()
        {
            //public int CategoryID {get;set;} //PrimaryKey not null
            PropertyTemplate property = new PropertyTemplate
            {
                PropName = "CategoryID",
                PropType = "int",
                IsKey    = true
            };
            var pg = new PropertyGenerator(property, new PocoSetting
            {
                AddJsonAttribute = true,
                NameCase         = CaseEnum.Camel
            });
            //  Debug.WriteLine(pg);
            var expected = "[JsonProperty(PropertyName = \"CategoryID\")] " + Environment.NewLine +
                           "public int categoryID {get;set;} ";

            //   Debug.WriteLine("Expected: " + expected);
            //Assert.IsTrue(Helper.CompareStringIgnoringSpaceCr(pg.ToString(), expected));
            Assert.AreEqual(pg.ToString().TrimAllSpace(), expected.TrimAllSpace());
        }
Example #12
0
        public void VerfiyInitializationOfPropertyGenerator()
        {
            CodeElement[] codeElements = new CodeElement[]
            {
                new MockedCodeVariable2("variable2", vsCMAccess.vsCMAccessPrivate),
                new MockedCodeElement("testElement"),
                new MockedCodeVariable2("variable1", vsCMAccess.vsCMAccessPrivate),
                new MockedCodeVariable2("_variable3", vsCMAccess.vsCMAccessPrivate),
                new MockedCodeVariable2("m_aprefixedvariable", vsCMAccess.vsCMAccessPrivate),
            };

            MockedCodeClass2  mockedCodeClass   = new MockedCodeClass2(codeElements);
            PropertyGenerator propertyGenerator = new PropertyGenerator(mockedCodeClass);

            Assert.IsFalse(propertyGenerator.GenerateComments);
            Assert.AreSame(mockedCodeClass, propertyGenerator.CodeClass);
            Assert.AreEqual(4, propertyGenerator.Properties.Length);
            Assert.AreEqual("Aprefixedvariable", propertyGenerator.Properties[0].Name);
            Assert.AreEqual("Variable1", propertyGenerator.Properties[1].Name);
            Assert.AreEqual("Variable2", propertyGenerator.Properties[2].Name);
            Assert.AreEqual("Variable3", propertyGenerator.Properties[3].Name);
        }
        public void LazyirtualPropertyDeclaration_test()
        {
            // Arrange
            var setting = new PocoSetting
            {
                AddEager      = false,
                AddNavigation = true
            };

            _attributeManager.Init(setting);
            var property = new PropertyTemplate
            {
                PropName    = "Products",
                PropType    = "List<Product>",
                PropComment = "// not null",
                IsNavigate  = true
            };
            // Act
            var sut = new PropertyGenerator(property, setting);

            // Assert
            Assert.IsTrue(sut.Declaration.Contains("public virtual List<Product> Products {get;set;}"));
        }
        public void JsonAttributePropertyDeclaration_test()
        {
            // Arrange
            var setting = new PocoSetting
            {
                AddJsonAttribute = true
            };

            _attributeManager.Init(setting);
            PropertyTemplate property = new PropertyTemplate
            {
                PropName = "CategoryID",
                PropType = "int",
                IsKey    = true
            };
            // Act
            var sut = new PropertyGenerator(property, setting);

            // Assert
            var expected = "[JsonProperty(PropertyName = \"CategoryID\")]";

            Assert.IsTrue(sut.ToString().Contains(expected));
        }
        public void IsNullablePropertyDeclaration_test()
        {
            // Arrange
            var setting = new PocoSetting
            {
                AddNullableDataType = true
            };

            _attributeManager.Init(setting);
            PropertyTemplate property = new PropertyTemplate
            {
                IsKey      = false,
                IsNullable = true,
                PropName   = "dummy1",
                PropType   = "int"
            };
            // Act
            var sut = new PropertyGenerator(property, setting);

            // Assert

            Assert.IsTrue(sut.Declaration.Contains("public int? dummy1 {get;set;}"));
        }
        public void Test_CreateModelClass()
        {
            var classBuilder = new ClassBuilder("Cat", "Models");
            var @class = classBuilder
                .WithUsings("System")
                .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 })))
                .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();

            Assert.AreEqual(
                "usingSystem;namespaceModels{publicclassCat{publicCat(stringname,intage){Name=name;Age=age;}publicstringName{get;set;}publicintAge{get;set;}}}",
                @class.ToString());
        }
Example #17
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());
        }
        private string GenerateMemberAccessExpression(MemberAccessExpressionSyntax memberAccessExpressionSyntax, SemanticModel semanticModel)
        {
            string memberOwnerExpression = GenerateExpression(memberAccessExpressionSyntax.Expression, semanticModel);

            var symbolInfo = ModelExtensions.GetSymbolInfo(semanticModel, memberAccessExpressionSyntax);

            if (symbolInfo.Symbol.Kind == SymbolKind.Property)
            {
                string propertyName = memberAccessExpressionSyntax.Name.Identifier.ValueText;
                var    type         = (INamedTypeSymbol)ModelExtensions.GetTypeInfo(semanticModel, memberAccessExpressionSyntax).Type;
                var    ownerType    = (INamedTypeSymbol)ModelExtensions.GetTypeInfo(semanticModel, memberAccessExpressionSyntax.Expression).Type;
                if (CustomPropertyAccessHelper.IsCustom(ownerType, propertyName))
                {
                    return(CustomPropertyAccessHelper.Generate(ownerType, memberOwnerExpression, propertyName));
                }
                else
                {
                    var    typeReference = TypeReferenceGenerator.GenerateTypeReference(type, semanticModel);
                    string methodName    = PropertyGenerator.GenerateGetterMethodName(typeReference, propertyName);
                    return(memberOwnerExpression + "." + GenerateMethodCallExpression(methodName, new List <string>()));
                }
            }
            throw new NotImplementedException();
        }
        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 }))
                .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 })))
                .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();

            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());
        }
Example #20
0
 public void Create_WhenCreatingPropertyWithSetModifiers_ShouldHaveGetModifiers()
 {
     Assert.AreEqual("intMyProperty{get;privateinternalset;}", PropertyGenerator.Create(new AutoProperty("MyProperty", typeof(int), PropertyTypes.GetAndSet, setModifiers: new List <Modifiers> {
         Modifiers.Private, Modifiers.Internal
     })).ToString());
 }
Example #21
0
 public void Create_WhenCreatingPropertyWithGetModifiers_ShouldHaveGetModifiers()
 {
     Assert.AreEqual("intMyProperty{protectedget;set;}", PropertyGenerator.Create(new AutoProperty("MyProperty", typeof(int), PropertyTypes.GetAndSet, getModifiers: new List <Modifiers> {
         Modifiers.Protected
     })).ToString());
 }
Example #22
0
 public void Create_WhenCreatingAutoPropertyWithGetAndSet_ShouldHaveBothGetAndSet()
 {
     Assert.AreEqual("intMyProperty{get;set;}", PropertyGenerator.Create(new AutoProperty("MyProperty", typeof(int), PropertyTypes.GetAndSet)).ToString());
 }
        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);
        }
 public PropertyGeneratorTests()
 {
     _propertyGenerator = new PropertyGenerator(new Property("TestName", DefaultPropertyType.Instance));
 }
        private string GenerateInvocationExpression(InvocationExpressionSyntax invocationExpressionSyntax, SemanticModel semanticModel)
        {
            var parameterExpressions = new List <string>();

            foreach (var argument in invocationExpressionSyntax.ArgumentList.Arguments)
            {
                string parameterExpression = GenerateExpression(argument.Expression, semanticModel);
                parameterExpressions.Add(parameterExpression);
            }
            var expression = invocationExpressionSyntax.Expression;
            var symbolInfo = ModelExtensions.GetSymbolInfo(semanticModel, expression);

            if (expression is IdentifierNameSyntax)
            {
                var identifierNameExpression = expression as IdentifierNameSyntax;
                var namedTypeSymbol          = (INamedTypeSymbol)ModelExtensions.GetTypeInfo(semanticModel, expression).Type;
                if (namedTypeSymbol != null && TypeReferenceGenerator.IsDelegateType(namedTypeSymbol))
                {
                    return(identifierNameExpression.Identifier.ValueText + "." + GenerateMethodCallExpression("invoke", parameterExpressions));
                }
                string containingTypeFullName = SyntaxTreeHelper.GetFullyQualifiedName(symbolInfo.Symbol.ContainingType);
                string methodName             = invocationExpressionSyntax.Expression.GetText()
                                                .ToString().Trim();
                return(GenerateMethodCallExpression(methodName, parameterExpressions));
            }
            if (expression is MemberAccessExpressionSyntax)
            {
                var    memberAccessExpression = expression as MemberAccessExpressionSyntax;
                string memberName             = memberAccessExpression.Name.Identifier.ValueText;

                string ownerExpression = GenerateExpression(memberAccessExpression.Expression, semanticModel);
                if (symbolInfo.Symbol is IMethodSymbol && (symbolInfo.Symbol as IMethodSymbol).IsExtensionMethod)
                {
                    var    containingType          = (symbolInfo.Symbol as IMethodSymbol).ContainingType;
                    string containingTypeReference = TypeReferenceGenerator.GenerateTypeReference(containingType, semanticModel).Text;
                    parameterExpressions.Insert(0, ownerExpression);
                    return(containingTypeReference + "." + GenerateMethodCallExpression(memberName, parameterExpressions));
                }
                if (symbolInfo.Symbol.Kind == SymbolKind.Method)
                {
                    string containingTypeFullName = SyntaxTreeHelper.GetFullyQualifiedName(symbolInfo.Symbol.ContainingType);
                    string methodName             = memberName;
                    if (CustomMethodInvocationHelper.IsCustom(containingTypeFullName, methodName))
                    {
                        return(CustomMethodInvocationHelper.Generate(containingTypeFullName,
                                                                     ownerExpression, methodName, parameterExpressions));
                    }
                    else
                    {
                        return(ownerExpression + "." + GenerateMethodCallExpression(methodName, parameterExpressions));
                    }
                }
                if (symbolInfo.Symbol.Kind == SymbolKind.Property && symbolInfo.Symbol is IPropertySymbol)
                {
                    var propertyType = (symbolInfo.Symbol as IPropertySymbol).Type as INamedTypeSymbol;
                    if (TypeReferenceGenerator.IsDelegateType(propertyType))
                    {
                        string propertyName  = memberAccessExpression.Name.Identifier.ValueText;
                        var    type          = (INamedTypeSymbol)ModelExtensions.GetTypeInfo(semanticModel, memberAccessExpression).Type;
                        var    typeReference = TypeReferenceGenerator.GenerateTypeReference(type, semanticModel);
                        string methodName    = PropertyGenerator.GenerateGetterMethodName(typeReference, propertyName);
                        return(ownerExpression + "." + GenerateMethodCallExpression(methodName, new List <string>()) + "." +
                               GenerateMethodCallExpression("invoke", parameterExpressions));
                    }
                    throw new NotImplementedException();
                }
                throw new NotImplementedException();
            }
            throw new NotImplementedException();
        }
Example #26
0
        private SourceCode GetProperties(SemanticModel semanticModel, HashSet <string> typeReferences,
                                         IEnumerable <PropertyDeclarationSyntax> propertyDeclarations, bool isFromInterface)
        {
            var generatedProperties = new SourceCode {
                MainPart = ""
            };

            foreach (var propertyDeclaration in propertyDeclarations)
            {
                string identifier    = propertyDeclaration.Identifier.ValueText;
                var    propertyType  = propertyDeclaration.Type;
                var    typeReference = TypeReferenceGenerator.GenerateTypeReference(propertyType, semanticModel);
                if (!typeReference.IsPredefined)
                {
                    typeReferences.Add(typeReference.Text);
                }

                bool isStatic  = HasStaticModifier(propertyDeclaration.Modifiers.ToList());
                bool isVirtual = isFromInterface || HasVirtualModifier(propertyDeclaration.Modifiers.ToList());

                var propertyAccessModifier = GetAccessModifier(propertyDeclaration.Modifiers.ToList());
                var accessors   = propertyDeclaration.AccessorList.Accessors;
                var getAccessor = accessors.FirstOrDefault(syntax => syntax.Keyword.Text == "get");
                var setAccessor = accessors.FirstOrDefault(syntax => syntax.Keyword.Text == "set");

                if (propertyDeclaration.AccessorList.Accessors.Any(syntax => syntax.Body != null))
                {
                    var complexPropertyDescription = new ComplexPropertyDescription
                    {
                        PropertyName      = identifier,
                        PropertyType      = typeReference,
                        GetAccessModifier = new Optional <AccessModifier>(),
                        SetAccessModifier = new Optional <AccessModifier>(),
                        IsStatic          = isStatic,
                        IsVirtual         = isVirtual
                    };
                    if (getAccessor != null)
                    {
                        var getAccessModifier = GetAccessModifier(getAccessor.Modifiers);
                        var getModifier       = MaxRestrictionAccessModifier(propertyAccessModifier, getAccessModifier);
                        complexPropertyDescription.GetAccessModifier = getModifier;
                        if (getAccessor.Body != null)
                        {
                            var statements = new List <string>();
                            foreach (var statement in getAccessor.Body.Statements)
                            {
                                string generatedStatement = StatementGenerator.Generate(statement, semanticModel);
                                statements.Add(generatedStatement);
                            }
                            complexPropertyDescription.GetStatements = statements;
                        }
                    }
                    if (setAccessor != null)
                    {
                        var setAccessModifier = GetAccessModifier(setAccessor.Modifiers);
                        var setModifier       = MaxRestrictionAccessModifier(propertyAccessModifier, setAccessModifier);
                        complexPropertyDescription.SetAccessModifier = setModifier;
                        if (setAccessor.Body != null)
                        {
                            var statements = new List <string>();
                            foreach (var statement in setAccessor.Body.Statements)
                            {
                                string generatedStatement = StatementGenerator.Generate(statement, semanticModel);
                                statements.Add(generatedStatement);
                            }
                            complexPropertyDescription.SetStatements = statements;
                        }
                    }

                    SourceCode generatedProperty = PropertyGenerator.GenerateComplexProperty(complexPropertyDescription, semanticModel);
                    generatedProperties.MainPart += "\n" + generatedProperty.MainPart;
                }
                else
                {
                    var simplePropertyDescription = new SimplePropertyDescription
                    {
                        PropertyName      = identifier,
                        PropertyType      = typeReference,
                        GetAccessModifier = new Optional <AccessModifier>(),
                        SetAccessModifier = new Optional <AccessModifier>(),
                        IsStatic          = isStatic,
                        IsVirtual         = isVirtual,
                        IsFromInterface   = isFromInterface
                    };
                    if (getAccessor != null)
                    {
                        var getAccessModifier = GetAccessModifier(getAccessor.Modifiers);
                        var getModifier       = MaxRestrictionAccessModifier(propertyAccessModifier, getAccessModifier);
                        simplePropertyDescription.GetAccessModifier = getModifier;
                    }
                    if (setAccessor != null)
                    {
                        var setAccessModifier = GetAccessModifier(setAccessor.Modifiers);
                        var setModifier       = MaxRestrictionAccessModifier(propertyAccessModifier, setAccessModifier);
                        simplePropertyDescription.SetAccessModifier = setModifier;
                    }

                    SourceCode generatedProperty = PropertyGenerator
                                                   .GenerateSimpleProperty(simplePropertyDescription, semanticModel, isFromInterface);
                    generatedProperties.MainPart += "\n" + generatedProperty.MainPart;
                }
            }
            return(generatedProperties);
        }
Example #27
0
 public void PreClassesHook(List<IntPtr> excludedMethods)
 {
     PropertyGenerator pg = new PropertyGenerator(Data, Translator, this.Documentation);
     pg.Run();
     excludedMethods.AddRange(pg.PropertyMethods);
 }
Example #28
0
 public void Create_WhenCreatingAutoPropertyWithAttribute_ShouldHaveAttribute()
 {
     Assert.AreEqual("[Test]intMyProperty{get;set;}", PropertyGenerator.Create(new AutoProperty("MyProperty", typeof(int), PropertyTypes.GetAndSet, new List <Modifiers>(), new List <Attribute> {
         new Attribute("Test")
     })).ToString());
 }
Example #29
0
 public void Create_WhenCreatingBodyPropertyWithGetAndSet_ShouldHaveBothGetAndSet()
 {
     Assert.AreEqual("intMyProperty{get{return1;}}", PropertyGenerator.Create(new BodyProperty("MyProperty", typeof(int), BodyGenerator.Create(Statement.Jump.Return(new ConstantReference(1))))).ToString());
 }
        private string GenerateIdentifierExpression(IdentifierNameSyntax identifierNameSyntax, SemanticModel semanticModel)
        {
            var symbolInfo = ModelExtensions.GetSymbolInfo(semanticModel, identifierNameSyntax);

            if (symbolInfo.Symbol.Kind == SymbolKind.Property)
            {
                string propertyName  = identifierNameSyntax.Identifier.ValueText;
                var    type          = (INamedTypeSymbol)ModelExtensions.GetTypeInfo(semanticModel, identifierNameSyntax).Type;
                var    typeReference = TypeReferenceGenerator.GenerateTypeReference(type, semanticModel);
                string methodName    = PropertyGenerator.GenerateGetterMethodName(typeReference, propertyName);
                return(GenerateMethodCallExpression(methodName, new List <string> {
                }));
            }
            if (symbolInfo.Symbol.Kind == SymbolKind.Field)
            {
                return(identifierNameSyntax.Identifier.ValueText);
            }
            if (symbolInfo.Symbol.Kind == SymbolKind.Parameter)
            {
                return(identifierNameSyntax.Identifier.ValueText);
            }
            if (symbolInfo.Symbol.Kind == SymbolKind.Local)
            {
                return(identifierNameSyntax.Identifier.ValueText);
            }
            if (symbolInfo.Symbol.Kind == SymbolKind.NamedType)
            {
                return(TypeReferenceGenerator.GenerateTypeReference((ITypeSymbol)symbolInfo.Symbol, semanticModel).Text);
            }
            if (symbolInfo.Symbol.Kind == SymbolKind.Method)
            {
                var methodSymbol           = symbolInfo.Symbol as IMethodSymbol;
                var typeSymbol             = ModelExtensions.GetTypeInfo(semanticModel, identifierNameSyntax).ConvertedType as INamedTypeSymbol;
                var delegateInfo           = GetDelegateInfo(typeSymbol, semanticModel);
                var delegateTypeParameters = delegateInfo.TypeParameters;

                var generatedParameters = new List <Var>();
                if (delegateInfo.IsFunc)
                {
                    delegateTypeParameters.RemoveAt(delegateTypeParameters.Count - 1);
                }
                for (int i = 0; i < delegateTypeParameters.Count; i++)
                {
                    generatedParameters.Add(new Var
                    {
                        Name = "arg" + i,
                        Type = delegateTypeParameters[i]
                    });
                }
                string statement = delegateInfo.IsFunc ? "return " : "";
                statement += methodSymbol.Name.ToLowerFirstChar() + "(";
                for (int i = 0; i < generatedParameters.Count - 1; i++)
                {
                    statement += generatedParameters[i].Name + ", ";
                }
                if (generatedParameters.Count > 0)
                {
                    statement += generatedParameters[generatedParameters.Count - 1].Name;
                }
                statement += ");";
                var statements = new List <string>
                {
                    statement
                };
                return(BuildLambdaExpression(delegateInfo.JavaDelegateType, generatedParameters, delegateInfo.ReturnType, statements, semanticModel));
            }
            throw new NotImplementedException();
        }
Example #31
0
 public void PreClassesHook()
 {
     IDictionary<string, string> documentation = Documentation.Get(Data.Docs);
     foreach (CodeTypeDeclaration type in from smokeType in this.Data.SmokeTypeMap
                                          where string.IsNullOrEmpty((string) smokeType.Value.UserData["parent"])
                                          select smokeType.Value)
     {
         foreach (CodeTypeDeclaration nestedType in type.Members.OfType<CodeTypeDeclaration>().Where(t => !t.IsEnum))
         {
             this.GetClassDocs(nestedType, string.Format("{0}::{1}", type.Name, nestedType.Name),
                               string.Format("{0}-{1}", type.Name, nestedType.Name), documentation);
         }
         this.GetClassDocs(type, type.Name, type.Name, documentation);
     }
     PropertyGenerator pg = new PropertyGenerator(Data, Translator, this.memberDocumentation);
     pg.Run();
 }
Example #32
0
        public override string Generate(int indent)
        {
            NamespaceGenerator @namespace = NamespaceGenerator.Namespace("Unity.VisualScripting.Community.Generated");

            if (Data != null)
            {
                var title        = GetCompoundTitle();
                var delegateType = DelegateType;

                Data.title = title;

                if (!string.IsNullOrEmpty(Data.category))
                {
                    @namespace = NamespaceGenerator.Namespace(Data.category);
                }

                var @class          = ClassGenerator.Class(RootAccessModifier.Public, ClassModifier.None, title, typeof(object)).ImplementInterface(delegateType);
                var properties      = string.Empty;
                var method          = Data.type.type.GetMethod("Invoke");
                var parameterUsings = new List <string>();
                var parameters      = method.GetParameters();
                var parameterNames  = new List <string>();
                var something       = new Dictionary <ParameterInfo, string>();

                for (int i = 0; i < parameters.Length; i++)
                {
                    properties += " new".ConstructHighlight() + " TypeParam".TypeHighlight() + "() { name = " + $@"""{parameters[i].Name}""".StringHighlight() + ", type = " + "typeof".ConstructHighlight() + "(" + (parameters[i].ParameterType.IsGenericParameter ? Data.generics[i].type.type.As().CSharpName() : parameters[i].ParameterType.As().CSharpName()) + ") }";
                    if (!parameterUsings.Contains(parameters[i].ParameterType.Namespace))
                    {
                        parameterUsings.Add(parameters[i].ParameterType.Namespace);
                    }
                    if (i < parameters.Length - 1)
                    {
                        properties += ", ";
                    }
                }

                @class.AddUsings(parameterUsings);

                if (string.IsNullOrEmpty(properties))
                {
                    properties += " ";
                }
                else
                {
                    properties = " " + properties + " ";
                }

                var displayName                 = string.IsNullOrEmpty(Data.displayName) ? Data.type.type.As().CSharpName().RemoveHighlights().RemoveMarkdown() : Data.displayName;
                var constructors                = Data.type.type.GetConstructors();
                var constructorParameters       = constructors[constructors.Length - 1 > 0 ? 1 : 0];
                var stringConstructorParameters = new List <string>();
                var constParams                 = parameters.ToListPooled();
                var assignParams                = string.Empty;

                if (constParams.Count <= 0)
                {
                }

                var constParamsLength = constParams.Count;
                var invokeString      = string.Empty;

                for (int i = constParamsLength - 1; i >= 0; i--)
                {
                    if (constParams[i].Name == "object" || constParams[i].Name == "method")
                    {
                        constParams.Remove(constParams[i]);
                    }
                }


                for (int i = 0; i < constParams.Count; i++)
                {
                    assignParams += constParams[i].Name.EnsureNonConstructName().Replace("&", string.Empty);
                    stringConstructorParameters.Add(constParams[i].Name.EnsureNonConstructName().Replace("&", string.Empty));
                    if (i < constParams.Count - 1)
                    {
                        assignParams += ", ";
                    }
                }

                var remappedGenerics = string.Empty;
                var remappedGeneric  = Data.type.type.Name.EnsureNonConstructName();

                for (int i = 0; i < Data.generics.Count; i++)
                {
                    remappedGenerics += Data.generics[i].type.type.As().CSharpName().Replace("&", string.Empty);
                    if (i < Data.generics.Count - 1)
                    {
                        remappedGenerics += ", ";
                    }
                }

                if (Data.generics.Count - 1 >= 0 || IsAction)
                {
                    for (int i = 0; i < (IsAction ? Data.generics.Count : Mathf.Clamp(Data.generics.Count - 1, 0, Data.generics.Count)); i++)
                    {
                        if (i < Data.generics.Count - 1 || IsAction)
                        {
                            invokeString += $"({ Data.generics[i].type.type.As().CSharpName().Replace("&", string.Empty)})parameters[{i.ToString()}]";
                            if (i < Data.generics.Count - (IsAction ? 1 : 2))
                            {
                                invokeString += ", ";
                            }
                        }
                    }
                }

                if (Data.generics.Count > 0)
                {
                    remappedGeneric = remappedGeneric.Contains("`") ? remappedGeneric.Remove(remappedGeneric.IndexOf("`"), remappedGeneric.Length - remappedGeneric.IndexOf("`")) : remappedGeneric;
                    remappedGeneric = remappedGeneric.TypeHighlight() + "<" + remappedGenerics + ">";
                }
                else
                {
                    remappedGeneric.TypeHighlight();
                }

                @class.AddField(FieldGenerator.Field(AccessModifier.Public, FieldModifier.None, remappedGeneric, Data.type.type.Namespace, "callback"));
                @class.AddField(FieldGenerator.Field(AccessModifier.Public, FieldModifier.None, remappedGeneric, Data.type.type.Namespace, "instance"));

                @class.AddField(FieldGenerator.Field(AccessModifier.Private, FieldModifier.None, typeof(bool), "_initialized"));

                @class.AddProperty(PropertyGenerator.Property(AccessModifier.Public, PropertyModifier.None, typeof(TypeParam), "parameters", false).SingleStatementGetter(AccessModifier.Public, "new".ConstructHighlight() + " TypeParam".TypeHighlight() + "[] {" + properties.Replace("&", string.Empty) + "}").AddTypeIndexer(""));

                @class.AddProperty(PropertyGenerator.Property(AccessModifier.Public, PropertyModifier.None, typeof(string), "DisplayName", false).SingleStatementGetter(AccessModifier.Public, $@"""{remappedGeneric.RemoveHighlights().RemoveMarkdown().Replace("<", " (").Replace(">", ")")}""".StringHighlight()));

                @class.AddProperty(PropertyGenerator.Property(AccessModifier.Public, PropertyModifier.None, typeof(bool), "initialized", false).SingleStatementGetter(AccessModifier.Public, "_initialized").SingleStatementSetter(AccessModifier.Public, "_initialized = value"));

                if (IsFunc)
                {
                    @class.AddProperty(PropertyGenerator.Property(AccessModifier.Public, PropertyModifier.None, typeof(Type), "ReturnType", false).SingleStatementGetter(AccessModifier.Public, "typeof".ConstructHighlight() + "(" + Data.generics[Data.generics.Count - 1].type.type.As().CSharpName() + ")"));
                }

                @class.AddMethod(MethodGenerator.Method(AccessModifier.Public, MethodModifier.None, typeof(Type), "GetDelegateType").Body("return typeof".ConstructHighlight() + "(" + remappedGeneric + ");"));

                @class.AddMethod(MethodGenerator.Method(AccessModifier.Public, MethodModifier.None, typeof(object), "GetDelegate").Body("return".ConstructHighlight() + " callback;"));

                @class.AddMethod(MethodGenerator.Method(AccessModifier.Public, MethodModifier.None, IsAction ? typeof(void) : typeof(object), IsAction ? "Invoke" : "DynamicInvoke").AddParameter(ParameterGenerator.Parameter("parameters", typeof(object[]), Libraries.CSharp.ParameterModifier.None, isParameters: true)).Body($"{(IsAction ? string.Empty : "return").ConstructHighlight()} callback({invokeString});"));

                if (!IsAction)
                {
                    @class.AddMethod(MethodGenerator.Method(AccessModifier.Public, MethodModifier.None, Data.generics[Mathf.Clamp(Data.generics.Count - 1, 0, Data.generics.Count - 1)].type.type, "Invoke").AddParameter(ParameterGenerator.Parameter("parameters", typeof(object[]), Libraries.CSharp.ParameterModifier.None, isParameters: true)).Body($"{(IsAction ? string.Empty : "return").ConstructHighlight()} callback({invokeString});"));
                }

                @class.AddMethod(MethodGenerator.Method(AccessModifier.Public, MethodModifier.None, typeof(void), "Initialize").
                                 AddParameter(ParameterGenerator.Parameter("flow", typeof(Flow), Libraries.CSharp.ParameterModifier.None)).
                                 AddParameter(ParameterGenerator.Parameter("unit", IsAction ? typeof(ActionNode) : typeof(FuncNode), Libraries.CSharp.ParameterModifier.None)).
                                 AddParameter(ParameterGenerator.Parameter(IsAction ? "flowAction" : "flowFunc", IsAction ? typeof(Action) : typeof(Func <object>), Libraries.CSharp.ParameterModifier.None)).
                                 Body("SetInstance(flow, unit, " + (IsAction ? "flowAction" : "flowFunc") + "); \n" + "callback = " + "new ".ConstructHighlight() + remappedGeneric + "(" + LambdaGenerator.SingleLine(stringConstructorParameters, (!IsAction ? "return".ConstructHighlight() + " " : string.Empty) + $"instance({assignParams});").Generate(0) + ");\n" + "initialized = " + "true".ConstructHighlight() + ";"));

                @class.AddMethod(MethodGenerator.Method(AccessModifier.Public, MethodModifier.None, typeof(void), "SetInstance").
                                 AddParameter(ParameterGenerator.Parameter("flow", typeof(Flow), Libraries.CSharp.ParameterModifier.None)).
                                 AddParameter(ParameterGenerator.Parameter("unit", IsAction ? typeof(ActionNode) : typeof(FuncNode), Libraries.CSharp.ParameterModifier.None)).
                                 AddParameter(ParameterGenerator.Parameter(IsAction ? "flowAction" : "flowFunc", IsAction ? typeof(Action) : typeof(Func <object>), Libraries.CSharp.ParameterModifier.None)).
                                 Body("instance = " + "new ".ConstructHighlight() + remappedGeneric + "(" + LambdaGenerator.SingleLine(stringConstructorParameters, (stringConstructorParameters.Count > 0 ? "unit.AssignParameters(flow, " + assignParams + "); " + (IsAction ? "flowAction();" : "return ".ConstructHighlight() + "(" + Data.generics[Data.generics.Count - 1].type.type.As().CSharpName() + ")" + "flowFunc();") : (IsAction ? "flowAction();" : "return ".ConstructHighlight() + "(" + Data.generics[Data.generics.Count - 1].type.type.As().CSharpName() + ")" + "flowFunc();"))).Generate(0) + ");"));

                @class.AddMethod(MethodGenerator.Method(AccessModifier.Public, MethodModifier.None, typeof(void), "Bind").
                                 AddParameter(ParameterGenerator.Parameter("other", typeof(IDelegate), Libraries.CSharp.ParameterModifier.None))
                                 .Body(
                                     "callback += (" + remappedGeneric + ")other.GetDelegate();"
                                     ));

                @class.AddMethod(MethodGenerator.Method(AccessModifier.Public, MethodModifier.None, typeof(void), "Unbind").
                                 AddParameter(ParameterGenerator.Parameter("other", typeof(IDelegate), Libraries.CSharp.ParameterModifier.None))
                                 .Body(
                                     "callback -= (" + remappedGeneric + ")other.GetDelegate();"
                                     ));

                @class.AddUsings(new List <string>()
                {
                    Data.type.type.Namespace, "System"
                });

                @class.AddAttribute(AttributeGenerator.Attribute <IncludeInSettingsAttribute>().AddParameter(true));

                if (Data.lastCompiledName != Data.GetFullTypeName())
                {
                    @class.AddAttribute(AttributeGenerator.Attribute <RenamedFromAttribute>().AddParameter(Data.lastCompiledName));
                }

                var genericNamespace = new List <string>();

                for (int i = 0; i < Data.generics.Count; i++)
                {
                    if (!genericNamespace.Contains(Data.generics[i].type.type.Namespace))
                    {
                        genericNamespace.Add(Data.generics[i].type.type.Namespace);
                    }
                }

                @class.AddUsings(genericNamespace);

                @namespace.AddClass(@class);

                return(@namespace.Generate(indent));
            }

            return(string.Empty);
        }