Пример #1
0
        public void TestNamespaceGenerationWithManyTypes()
        {
            // arrange
            var blog = new CSharpClass {
                Name = "Blog"
            };
            var post = new CSharpClass {
                Name = "Post"
            };
            var csharpNamespace = new CSharpNamespace {
                Name = "SuperBlogger", Types = new List <CSharpType> {
                    blog, post
                }
            };
            var output = new StringWriter();
            var expectedOutputWriter = new StringWriter();

            expectedOutputWriter.WriteLine("namespace SuperBlogger");
            expectedOutputWriter.WriteLine("{");
            blog.Generate(expectedOutputWriter);
            expectedOutputWriter.WriteLine();
            post.Generate(expectedOutputWriter);
            expectedOutputWriter.WriteLine("}");

            // act
            csharpNamespace.Generate(output);

            // assert
            Assert.Equal(expectedOutputWriter.ToString(), output.ToString());
        }
Пример #2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ClassGenerator"/> class for the specified <see cref="IndentedStreamWriter"/>
 /// </summary>
 /// <param name="class"><see cref="CSharpClass"/> to generate</param>
 /// <param name="writer"><see cref="IndentedStreamWriter"/> used to write to</param>
 public ClassGenerator(CSharpClass @class, IndentedStreamWriter writer) : base(writer)
 {
     _class                    = @class;
     _usingGenerator           = new UsingGenerator(_class.Usings, writer);
     _namespaceGenerator       = new NamespaceGenerator(_class.Namespace, writer);
     _classDefinitionGenerator = new ClassDefinitionGenerator(_class, writer);
 }
Пример #3
0
        public async Task <CSharpClass> GenerateClassCode(Table table = null)
        {
            Table tableToUse = null;

            try {
                if ((string.IsNullOrEmpty(SelectedTable?.TableName) && table == null) || StaticElements.DB == null)
                {
                    return(null);
                }
                else if (table != null)
                {
                    tableToUse = table;
                }
                else
                {
                    tableToUse = SelectedTable;
                }

                var columns = await Column.GetAsync(StaticElements.DB, tableToUse.TableSchema, tableToUse.TableName);

                var classBuilder = new CSharpClass(tableToUse, columns, FullyAsyncReading);
                ClassCode = classBuilder.ToString(Namespace);
                return(classBuilder);
            } catch (Exception ex) {
                Console.WriteLine(ex);
            }
            return(null);
        }
Пример #4
0
        public void TestGenerateClassWithMembers()
        {
            // arrange
            var idMember = new CSharpClassMember {
                Name = "Id", Type = "int"
            };
            var descriptionMembers = new CSharpClassMember {
                Name = "Description", Type = "string"
            };
            var csharpClass = new CSharpClass {
                Name = "Blog", Members = new List <CSharpClassMember> {
                    idMember, descriptionMembers
                }
            };
            var output = new StringWriter();
            var expectedOutputWriter = new StringWriter();

            expectedOutputWriter.Write("  public class Blog" + Environment.NewLine);
            expectedOutputWriter.Write("  {" + Environment.NewLine);
            idMember.Generate(expectedOutputWriter);
            expectedOutputWriter.WriteLine();
            descriptionMembers.Generate(expectedOutputWriter);
            expectedOutputWriter.Write("  }" + Environment.NewLine);

            // act
            csharpClass.Generate(output);

            // assert
            var generatedOutput = output.GetStringBuilder().ToString();

            Assert.Equal(expectedOutputWriter.GetStringBuilder().ToString(), generatedOutput);
        }
        public void ShouldEvaluateDecorationWithAttributesForAllMethodsThatMatchInclusionPattern()
        {
            //GIVEN
            var report = Any.Instance <IAnalysisReportInProgress>();
            var methodNameInclusionPattern = Any.Pattern();
            var description = Any.Instance <RuleDescription>();
            var method1     = Substitute.For <ICSharpMethod>();
            var method2     = Substitute.For <ICSharpMethod>();
            var method3     = Substitute.For <ICSharpMethod>();
            var methods     = new [] { method1, method2, method3 };
            var declaration = Any.Instance <ClassDeclarationInfo>();
            var @class      = new CSharpClass(declaration, methods);

            method1.NameMatches(methodNameInclusionPattern).Returns(true);
            method2.NameMatches(methodNameInclusionPattern).Returns(false);
            method3.NameMatches(methodNameInclusionPattern).Returns(true);

            //WHEN
            @class.EvaluateDecorationWithAttributes(report, methodNameInclusionPattern, description);

            //THEN
            method1.Received(1).EvaluateMethodsHavingCorrectAttributes(report, declaration.Name, description);
            method2.DidNotReceive().EvaluateMethodsHavingCorrectAttributes(
                Arg.Any <IAnalysisReportInProgress>(),
                Arg.Any <string>(),
                Arg.Any <RuleDescription>());
            method3.Received(1).EvaluateMethodsHavingCorrectAttributes(report, declaration.Name, description);
        }
Пример #6
0
        public void GeneratesCorrectDom()
        {
            var generator = new Generator(new NamingConvention("MyNamespace"));
            var generated = generator.Generate(Sample.Endpoints, Sample.Doc.Components.Schemas);

            var noteDto      = Dto("Note");
            var noteEndpoint = ElementEndpoint(noteDto);

            var contactDto = Dto("Contact");
            var contactEndpointInterface = new CSharpInterface(new CSharpIdentifier("MyNamespace", "IContactEndpoint"))
            {
                Interfaces = { ElementEndpoint(contactDto).ToInterface() },
                Properties =
                {
                    Property("Note",    "./note",    noteEndpoint,   description: "The note for a specific contact."),
                    Property("Poke",    "./poke",    ActionEndpoint, description: "Pokes a contact."),
                    Property("Picture", "./picture", BlobEndpoint,   description: "A picture of a specific contact.")
                },
                Description = "A specific contact."
            };
            var contactEndpoint = new CSharpClass(new CSharpIdentifier("MyNamespace", "ContactEndpoint"))
            {
                BaseClass = new CSharpClassConstruction(ElementEndpoint(contactDto))
                {
                    Parameters =
                    {
                        Referrer,
                        new CSharpParameter(CSharpIdentifier.Uri, "relativeUri")
                    }
                },
                Interfaces  = { contactEndpointInterface.Identifier },
                Description = contactEndpointInterface.Description
            };

            contactEndpoint.Properties.AddRange(contactEndpointInterface.Properties);

            var collectionEndpoint = CollectionEndpoint(contactDto, contactEndpoint.Identifier);

            var entryEndpoint = new CSharpClass(new CSharpIdentifier("MyNamespace", "MyEntryEndpoint"))
            {
                BaseClass = new CSharpClassConstruction(new CSharpIdentifier("TypedRest.Endpoints", "EntryEndpoint"))
                {
                    Parameters =
                    {
                        new CSharpParameter(CSharpIdentifier.Uri, "uri")
                    }
                },
                Properties =
                {
                    Property("Contacts",                    "./contacts",                                       collectionEndpoint,
                             CollectionEndpoint(contactDto, contactEndpointInterface.Identifier).ToInterface(),
                             description: "Collection of contacts.")
                }
            };

            generated.Should().BeEquivalentTo(
                contactDto, noteDto,
                entryEndpoint, contactEndpointInterface, contactEndpoint);
        }
Пример #7
0
        private static Member GetForeignKeyMember(CSharpClass type, string otherTypeName)
        {
            // give preference to Property over Field
            var fk = type.Operations.OfType <CSharpProperty>().SingleOrDefault(op => op.Name.ToLowerInvariant() == $"{otherTypeName.ToLowerInvariant()}id") as Member ??
                     type.Fields.OfType <CSharpField>().SingleOrDefault(field => field.Name.ToLowerInvariant() == $"{otherTypeName.ToLowerInvariant()}id");

            return(fk);
        }
Пример #8
0
    int ParseArguments(String[] args)
    {
        bool help = false;

        var p = new OptionSet {
            { "h|?|help", "Show this help message", v => help = v != null },
            { "o=|out=", "Set the output directory", v => OutputDir = v },
            { "ns=|namespace=", "Set the namespace of the generated code", v => Lib.BaseNamespace = v },
            { "lib=", "The base name of the C++ library, i.e. 'qt' for libqt.so", v => Lib.BaseName = v },
            { "filters=", "A file containing filter directives for filtering classes", v => FilterFile = v },
            { "inline=", "Inline methods in lib are: notpresent (default), present, surrogatelib (present in %lib%-inline)", v => Lib.InlinePolicy = (InlineMethods)Enum.Parse(typeof(InlineMethods), v, true) }
        };

        try {
            args = p.Parse(args).ToArray();
        } catch (OptionException) {
            Console.WriteLine("Try `generator --help' for more information.");
            return(1);
        }

        if (help)
        {
            p.WriteOptionDescriptions(Console.Error);
            return(1);
        }

        if (args.Length != 1)
        {
            Console.WriteLine("Usage: generator <options> <input xml file>");
            return(1);
        }

        // Code templates
        LibsTemplate  = new CSharpLibs();
        ClassTemplate = new CSharpClass();
        EnumTemplate  = new CSharpEnum();

        InputFileName = args [0];

        if (Lib.BaseName == null)
        {
            Console.WriteLine("The --lib= option is required.");
            return(1);
        }

        if (Lib.BaseNamespace == null)
        {
            Lib.BaseNamespace = Path.GetFileNameWithoutExtension(Lib.BaseName);
        }

        if (OutputDir == null)
        {
            OutputDir = "output";
        }

        return(0);
    }
Пример #9
0
        private static void CreatePrimaryKey(StringBuilder sb, CSharpClass type)
        {
            var pk = GetPrimaryKeyMember(type);

            if (pk != null)
            {
                sb.AppendLine($"ALTER TABLE {type.Name} ADD CONSTRAINT {GetPrimaryKeyName(type)} PRIMARY KEY({pk.Name});");
            }
        }
Пример #10
0
        private static void DeleteLinkTable(StringBuilder sb, EntityRelationship link)
        {
            var linkTable = new CSharpClass
            {
                Name = $"{link.First.Name}_{link.Second.Name}"
            };

            DeleteTable(sb, linkTable);
        }
Пример #11
0
        /// <summary>
        /// Attach documentation to functions and create new functions from raw functions using Span&lt;T&gt; when possible.
        /// </summary>
        /// <param name="monocypher">The Monocypher static class containing all generated raw PInvoke functions.</param>
        private void ProcessInvokeFunctions(CSharpClass monocypher)
        {
            var sizeType    = monocypher.Members.OfType <CSharpStruct>().First(x => x.Name == "size_t");
            var indexOfSize = monocypher.Members.IndexOf(sizeType);

            // Embrace size_t only for NETSTANDARD_20, NET5.0 is using nint
            monocypher.Members.Insert(indexOfSize + 1, new CSharpFreeMember()
            {
                Text = "#endif"
            });
            monocypher.Members.Insert(indexOfSize, new CSharpFreeMember()
            {
                Text = "#if NETSTANDARD2_0"
            });

            var newMethods = new List <CSharpCustomMethod>();

            // Loop on all raw PInvoke functions
            foreach (var function in monocypher.Members.OfType <CSharpMethod>())
            {
                // Get the documentation
                _functionDocs.TryGetValue(function.Name, out var funcDoc);

                var fullComment = new CSharpFullComment();
                var textComment = funcDoc?.Summary ?? new CSharpXmlComment("summary")
                {
                    Children = { new CSharpTextComment($"Function {function.Name}") }
                };
                fullComment.Children.Add(textComment);
                if (funcDoc != null)
                {
                    foreach (var paramDesc in funcDoc.Parameters)
                    {
                        fullComment.Children.Add(paramDesc);
                    }
                }
                function.Comment = fullComment;

                // Detect if we need to create a version of the function using Span:
                // - In case there is a fixed array parameter (e.g unsigned char mac[16]) Span<byte> of size 16
                // - In case there is a tuple (void* ptr, intptr_t size) => Span<byte> of size length
                var  extraParameters = new List <ParameterExtra>();
                bool processFunction = false;
                foreach (var parameter in function.Parameters)
                {
                    var  kind       = ParameterKind.Default;
                    bool isReadOnly = false;

                    if (parameter.ParameterType is CSharpRefType refType && refType.ElementType is CSharpArrayLikeType)
                    {
                        kind            = ParameterKind.FixedBuffer;
                        isReadOnly      = refType.Kind == CSharpRefKind.In;
                        processFunction = true;
                    }
Пример #12
0
        private bool CreateClasses(out IDictionary <IClass, ICSharpClass> classTable)
        {
            classTable = null;

            if (!ClassSplitting.Create(Compiler.LoadedRoot.ClassList, ErrorList, out IClassSplitting Splitting))
            {
                return(false);
            }

            classTable = new Dictionary <IClass, ICSharpClass>();

            ICSharpClass ClassAny = CSharpClass.Create(Class.ClassAny);

            classTable.Add(Class.ClassAny, ClassAny);

            ICSharpClass ClassAnyReference = CSharpClass.Create(Class.ClassAnyReference);

            classTable.Add(Class.ClassAnyReference, ClassAnyReference);

            ICSharpClass ClassAnyValue = CSharpClass.Create(Class.ClassAnyValue);

            classTable.Add(Class.ClassAnyValue, ClassAnyValue);

            foreach (IClass Class in Compiler.LoadedRoot.ClassList)
            {
                ICSharpClass NewCSharpClass = CSharpClass.Create(Class);
                classTable.Add(Class, NewCSharpClass);
            }

            foreach (KeyValuePair <IClass, ICSharpClass> Entry in classTable)
            {
                ICSharpClass Class = Entry.Value;

                if (GetBaseClass(Class, Splitting, classTable, out ICSharpClass BaseClass))
                {
                    Class.SetBaseClass(BaseClass);
                }

                Class.SetAncestorClasses(classTable);
            }

            foreach (KeyValuePair <IClass, ICSharpClass> Entry in classTable)
            {
                ICSharpClass Class = Entry.Value;
                CheckRename(Class, ErrorList);
            }
            if (!ErrorList.IsEmpty)
            {
                return(false);
            }

            return(true);
        }
        public void ShouldBeAbleToSayWhetherItsNameMatchesAPattern(string pattern, string className, bool expectedResult)
        {
            //GIVEN
            var declaration = new ClassDeclarationInfo(className, Any.String());

            var @class = new CSharpClass(declaration, Any.Array <ICSharpMethod>());

            //WHEN
            var nameMatches = @class.NameMatches(Pattern.WithoutExclusion(pattern));

            //THEN
            nameMatches.Should().Be(expectedResult);
        }
Пример #14
0
        private CSharpClass GenerateEndpointImplementation(string key, IEndpoint endpoint, TypeList typeList, IList <CSharpProperty> children)
        {
            var builder = _builders[endpoint.GetType()];

            var endpointImplementation = new CSharpClass(_naming.EndpointType(key, endpoint))
            {
                BaseClass   = builder.GetConstruction(endpoint, typeList),
                Description = endpoint.Description
            };

            endpointImplementation.Properties.AddRange(children);

            typeList.Add(endpoint, endpointImplementation);
            return(endpointImplementation);
        }
Пример #15
0
 private void AddMethods(Document doc, CSharpClass @class)
 {
     foreach (var method in @class.Methods)
     {
         doc.Add(new Field(Fields.Method, method.MethodName, Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
         doc.Add(new Field(Fields.Return, method.ReturnType, Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
         foreach (var parameter in method.Parameters)
         {
             doc.Add(new Field(Fields.Parameter, parameter, Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
         }
         if (method.Body != null)
         {
             doc.Add(new Field(Fields.Code, method.Body, Field.Store.NO, Field.Index.ANALYZED));
         }
     }
 }
Пример #16
0
        private IEnumerable <CSharpClass> GetClasses(ContractDefinition contract, string implementationName, CSharpAccessModifier accessLevel)
        {
            Type baseClass = typeof(Receiver <>);

            CSharpClass @class = new CSharpClass(
                name: implementationName,
                accessModifier: accessLevel,
                properties: this.GetProperties(contract),
                constructors: this.GetConstructors(contract, implementationName),
                methods: this.GetMethods(contract),
                baseType: $"{baseClass.GetCSharpName(identifierOnly: true)}<{contract.FullName}>",
                documentationComment: !string.IsNullOrWhiteSpace(contract.Description)
                    ? new CSharpDocumentationComment(summary: null, rawNotes: contract.Description)
                    : null);

            yield return(@class);
        }
        private IEnumerable <CSharpClass> GetClasses(ContractDefinition contract, string implementationName, CSharpAccessModifier accessLevel)
        {
            Type baseClass = typeof(Transmitter);

            CSharpClass @class = new CSharpClass(
                name: implementationName,
                accessModifier: accessLevel,
                constructors: this.GetConstructors(implementationName),
                methods: this.GetMethods(contract.Operations),
                baseType: baseClass.GetCSharpName(),
                interfaces: contract.FullName.SingleObjectAsEnumerable(),
                documentationComment: !string.IsNullOrWhiteSpace(contract.Description)
                    ? new CSharpDocumentationComment(summary: null, rawNotes: contract.Description)
                    : null);

            yield return(@class);
        }
Пример #18
0
        public void GenerateBean(CSharpBeanConfig beanConfig)
        {
            initDefault();

            //IRazorEngineCompiledTemplate template = razorEngine.Compile(templateContent);// "Hello @Model.Name");

            beanConfig.DDLConfig.Prepare();



            string beanRootDir = CodeUtil.PrepareCodeRoot(beanConfig.CodeDiretory, beanConfig.NamespacePath);

            string result = String.Empty;

            beanConfig.DDLConfig.Tables.ForEach(t =>
            {
                result = beanTemplate.Run(instance =>
                {
                    beanConfig.Table = t;
                    t.CreatedClass   = CSharpClass.CreateEntityClass(t, beanConfig, true);
                    instance.Model   = t.CreatedClass as CSharpClass;
                });
                Console.WriteLine(result);
                string filePath = beanRootDir + Path.DirectorySeparatorChar + t.CreatedClass.ClassName + ".java";

                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }
                File.WriteAllText(filePath, result, new UTF8Encoding(false));


                //result = beanTemplate.Run(instance =>
                //{
                //    instance.Model = t.CreatedClass.JavaVoClass;
                //});
                //Console.WriteLine(result);
                //filePath = voRootDir + Path.DirectorySeparatorChar + t.CreatedClass.JavaVoClass.ClassName + ".java";
                //if (File.Exists(filePath))
                //{
                //    File.Delete(filePath);
                //}
                //File.WriteAllText(filePath, result, new UTF8Encoding(false));
            });
        }
        private static CSharpClass ToCSharpClass(this ObjectFactoryCmdlet cmdlet)
        {
            if (cmdlet == null)
            {
                throw new ArgumentNullException(nameof(cmdlet));
            }

            // Create the result object
            CSharpClass result = new CSharpClass($"{cmdlet.Name.Verb}_{cmdlet.Name.Noun}")
            {
                DocumentationComment = cmdlet.Documentation.ToCSharpDocumentationComment(),
                AccessModifier       = CSharpAccessModifier.Public,
                BaseType             = nameof(ObjectFactoryCmdletBase),
                Attributes           = cmdlet.CreateAttributes(),
                Properties           = cmdlet.CreateProperties(),
            };

            return(result);
        }
Пример #20
0
        public void TestGenerateClassWithNoMembers()
        {
            // arrange
            var csharpClass = new CSharpClass {
                Name = "Blog"
            };
            var output         = new StringWriter();
            var expectedOutput =
                "  public class Blog" + Environment.NewLine +
                "  {" + Environment.NewLine +
                "  }" + Environment.NewLine;

            // act
            csharpClass.Generate(output);

            // assert
            var generatedOutput = output.GetStringBuilder().ToString();

            Assert.Equal(expectedOutput, generatedOutput);
        }
Пример #21
0
        public void CSharpNamespaceCloneTest()
        {
            var parentPackage = new CSharpNamespace("parent");
            var childPackage  = new CSharpNamespace("child");
            var classType1    = new CSharpClass("class1");
            var classType2    = new CSharpClass("class2");

            childPackage.AddNestedChild(classType1);
            childPackage.AddNestedChild(classType2);
            parentPackage.AddNestedChild(childPackage);

            var otherParent = parentPackage.Clone(true);
            var otherChild  = (CSharpNamespace)parentPackage.NestedChilds.First();

            otherParent.NestedChilds.Count().ShouldBe(1);
            otherParent.Name.ShouldBe(parentPackage.Name);
            otherChild.NestedChilds.Count().ShouldBe(2);
            otherChild.Name.ShouldBe(childPackage.Name);
            otherChild.NestedChilds.First().Name.ShouldBe(classType1.Name);
            otherChild.NestedChilds.Last().Name.ShouldBe(classType2.Name);
        }
Пример #22
0
        private static void CreateTable(StringBuilder sb, CSharpClass type)
        {
            var pk = GetPrimaryKeyMember(type);

            sb.AppendLine($"CREATE TABLE {type.Name}");
            sb.AppendLine($"(");

            foreach (var field in type.Fields.OfType <CSharpField>())
            {
                var pkField = field.Name == pk?.Name ? "NOT NULL" : string.Empty;
                sb.AppendLine($"  {field.Name} {NetToSqlTypeMap[field.Type.ToLowerInvariant()]} {pkField},");
            }

            foreach (var op in type.Operations.OfType <CSharpProperty>())
            {
                var pkOp = op.Name == pk?.Name ? "NOT NULL" : string.Empty;
                sb.AppendLine($"  {op.Name} {NetToSqlTypeMap[op.Type.ToLowerInvariant()]} {pkOp},");
            }

            sb.AppendLine($");");
            sb.AppendLine();
        }
Пример #23
0
        protected override ICSharpType BuildTypeInner()
        {
            var type = new CSharpClass(Identifier);

            foreach ((string propKey, var propSchema) in Schema.Properties)
            {
                var property = BuildProperty(propKey, propSchema);

                if (Schema.Required.Contains(propKey))
                {
                    property.Attributes.Add(Attributes.Required);
                }

                if (propKey.Equals("id", StringComparison.InvariantCultureIgnoreCase))
                {
                    property.Attributes.Add(Attributes.Key);
                }

                type.Properties.Add(property);
            }

            return(type);
        }
Пример #24
0
        private static void CreateLinkTable(StringBuilder sb, EntityRelationship link)
        {
            var linkTable = new CSharpClass
            {
                Name = $"{link.First.Name}_{link.Second.Name}"
            };

            var pk1     = GetPrimaryKeyMember((CSharpClass)link.First);
            var firstId = linkTable.AddProperty();

            firstId.Name = $"{link.First.Name}Id";
            firstId.Type = pk1.Type;

            var pk2      = GetPrimaryKeyMember((CSharpClass)link.Second);
            var secondId = linkTable.AddProperty();

            secondId.Name = $"{link.Second.Name}Id";
            secondId.Type = pk2.Type;

            CreateTable(sb, linkTable);

            CreateForeignKey(sb, linkTable.Name, link.First, link.Second, firstId.Name, pk1.Name);
            CreateForeignKey(sb, linkTable.Name, link.Second, link.First, secondId.Name, pk2.Name);
        }
Пример #25
0
        /// <summary>
        /// Translates nodes from the compiler to the target language.
        /// </summary>
        public override void Translate()
        {
            ErrorList.ClearErrors();

            if (!CreateClasses(out IDictionary <IClass, ICSharpClass> ClassTable))
            {
                return;
            }

            if (!CreateFeatures(ClassTable, out IDictionary <ICompiledFeature, ICSharpFeature> FeatureTable))
            {
                return;
            }

            ICSharpContext Context = new CSharpContext(ClassTable, FeatureTable);

            foreach (KeyValuePair <IClass, ICSharpClass> ClassEntry in ClassTable)
            {
                ICSharpClass           Class                = ClassEntry.Value;
                IList <ICSharpFeature> ClassFeatureList     = new List <ICSharpFeature>();
                IList <ICSharpFeature> InheritedFeatureList = new List <ICSharpFeature>();

                foreach (KeyValuePair <ICompiledFeature, ICSharpFeature> FeatureEntry in FeatureTable)
                {
                    ICSharpFeature   Feature  = FeatureEntry.Value;
                    IFeatureInstance Instance = Feature.Instance;

                    if (Instance.IsDiscontinued)
                    {
                        continue;
                    }

                    if (FeatureEntry.Value.Owner == Class)
                    {
                        ClassFeatureList.Add(Feature);
                    }
                    else if (!IsDirectOrNotMainParentFeature(Instance, Class))
                    {
                        InheritedFeatureList.Add(Feature);
                    }
                }

                Class.SetFeatureList(Context, ClassFeatureList, InheritedFeatureList);
            }

            foreach (KeyValuePair <ICompiledFeature, ICSharpFeature> Entry in FeatureTable)
            {
                ICSharpFeature Feature = Entry.Value;
                Feature.InitOverloadsAndBodies(Context);
            }

            foreach (KeyValuePair <ICompiledFeature, ICSharpFeature> Entry in FeatureTable)
            {
                ICSharpFeature Feature = Entry.Value;
                Feature.InitHierarchy(Context);
            }

            foreach (KeyValuePair <IClass, ICSharpClass> Entry in ClassTable)
            {
                ICSharpClass Class = Entry.Value;
                CheckSharedName(Class, ClassTable);
            }

            foreach (KeyValuePair <IClass, ICSharpClass> Entry in ClassTable)
            {
                ICSharpClass Class = Entry.Value;
                Class.CheckOverrides();
            }

            foreach (KeyValuePair <IClass, ICSharpClass> Entry in ClassTable)
            {
                ICSharpClass Class = Entry.Value;
                Class.CheckOverrides();
            }

            bool Continue;

            do
            {
                Continue = false;

                foreach (KeyValuePair <IClass, ICSharpClass> Entry in ClassTable)
                {
                    ICSharpClass Class = Entry.Value;
                    Class.CheckForcedReadWrite(FeatureTable, ref Continue);
                }
            }while (Continue);

            foreach (KeyValuePair <IClass, ICSharpClass> Entry in ClassTable)
            {
                ICSharpClass Class = Entry.Value;
                Class.CheckSideBySideAttributes();
            }

            foreach (KeyValuePair <IClass, ICSharpClass> Entry in ClassTable)
            {
                ICSharpClass Class = Entry.Value;
                Class.CheckInheritSideBySideAttributes(FeatureTable);
            }

            foreach (KeyValuePair <IClass, ICSharpClass> Entry in ClassTable)
            {
                ICSharpClass Class = Entry.Value;
                Class.CreateDelegates();
            }

            ICSharpFeature SingledClassFeature = null;

            if (SingledGuid != Guid.Empty || SingledGuid == Guid.Empty)
            {
                foreach (KeyValuePair <IClass, ICSharpClass> Entry in ClassTable)
                {
                    ICSharpClass Class = Entry.Value;
                    if (Class.Source.ClassGuid == SingledGuid || SingledGuid == Guid.Empty || SingledGuid != Guid.Empty)
                    {
                        foreach (ICSharpFeature Feature in Class.FeatureList)
                        {
                            if (Feature is ICSharpFeatureWithName AsWithName && AsWithName.Name == SingledName)
                            {
                                SingledClassFeature = Feature;
                                break;
                            }
                        }
                    }

                    if (SingledClassFeature != null)
                    {
                        break;
                    }
                }
            }

            if (SingledClassFeature == null)
            {
                foreach (KeyValuePair <IClass, ICSharpClass> Entry in ClassTable)
                {
                    ICSharpClass Class = Entry.Value;
                    Class.SetWriteDown();

                    foreach (ICSharpFeature Feature in Class.FeatureList)
                    {
                        Feature.SetWriteDown();
                    }

                    foreach (ICSharpAssertion Invariant in Class.InvariantList)
                    {
                        Invariant.SetWriteDown();
                    }
                }
            }
            else
            {
                SingledClassFeature.SetWriteDown();
            }

            if (!Directory.Exists(OutputRootFolder))
            {
                Directory.CreateDirectory(OutputRootFolder);
            }

            foreach (KeyValuePair <IClass, ICSharpClass> Entry in ClassTable)
            {
                ICSharpClass Class = Entry.Value;
                if (!CSharpClass.IsLanguageClass(Class.Source) && !IsClassFromLibrary(Class.Source))
                {
                    if (Class.WriteDown)
                    {
                        Class.Write(OutputRootFolder, Namespace, SourceFileName, SingledClassFeature);
                    }
                }
            }
        }
Пример #26
0
 private static CSharpIdentifier CollectionEndpoint(CSharpClass dto, CSharpIdentifier elementEndpoint)
 => new CSharpIdentifier("TypedRest.Endpoints.Generic", "CollectionEndpoint")
 {
     TypeArguments = { dto.Identifier, elementEndpoint }
 };
Пример #27
0
 private static CSharpIdentifier ElementEndpoint(CSharpClass dto)
 => new CSharpIdentifier("TypedRest.Endpoints.Generic", "ElementEndpoint")
 {
     TypeArguments = { dto.Identifier }
 };
Пример #28
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ClassDefinitionGenerator"/> class for the specified <see cref="IndentedStreamWriter"/>
 /// </summary>
 /// <param name="class"><see cref="CSharpClass"/> to generate definition for</param>
 /// <param name="writer"><see cref="IndentedStreamWriter"/> used to write to</param>
 public ClassDefinitionGenerator(CSharpClass @class, IndentedStreamWriter writer) : base(writer) => _class = @class;
Пример #29
0
 public void Add(IEndpoint endpoint, CSharpClass type)
 {
     _types.Add(type);
     _endpointImplementations.Add(endpoint, type.Identifier);
 }
Пример #30
0
	int ParseArguments (String[] args) {
		bool help = false;

		var p = new OptionSet {
				{ "h|?|help", "Show this help message", v => help = v != null },
				{ "o=|out=", "Set the output directory", v => OutputDir = v },
				{ "ns=|namespace=", "Set the namespace of the generated code", v => Lib.BaseNamespace = v },
				{ "lib=", "The base name of the C++ library, i.e. 'qt' for libqt.so", v =>Lib.BaseName = v },
				{ "filters=", "A file containing filter directives for filtering classes", v => FilterFile = v },
				{ "inline=", "Inline methods in lib are: notpresent (default), present, surrogatelib (present in %lib%-inline)", v => Lib.InlinePolicy = (InlineMethods)Enum.Parse (typeof (InlineMethods), v, true) }
			};

		try {
			args = p.Parse (args).ToArray ();
		} catch (OptionException) {
			Console.WriteLine ("Try `generator --help' for more information.");
			return 1;
		}

		if (help) {
			p.WriteOptionDescriptions (Console.Error);
			return 1;
		}

		if (args.Length != 1) {
			Console.WriteLine ("Usage: generator <options> <input xml file>");
			return 1;
		}

		// Code templates
		LibsTemplate = new CSharpLibs ();
		ClassTemplate = new CSharpClass ();
		EnumTemplate = new CSharpEnum ();

		InputFileName = args [0];

		if (Lib.BaseName == null) {
			Console.WriteLine ("The --lib= option is required.");
			return 1;
		}

		if (Lib.BaseNamespace == null) {
			Lib.BaseNamespace = Path.GetFileNameWithoutExtension (Lib.BaseName);
		}

		if (OutputDir == null)
			OutputDir = "output";

		return 0;
	}
Пример #31
0
        private CSharpInterface GenerateEndpointInterface(IEndpoint endpoint, TypeList typeList, CSharpClass endpointImplementation)
        {
            var builder = _builders[endpoint.GetType()];

            var endpointInterface = new CSharpInterface(endpointImplementation.Identifier.ToInterface())
            {
                Interfaces  = { builder.GetInterface(endpoint, typeList) },
                Description = endpoint.Description
            };

            endpointInterface.Properties.AddRange(endpointImplementation.Properties);

            endpointImplementation.Interfaces.Add(endpointInterface.Identifier);

            typeList.Add(endpoint, endpointInterface);
            return(endpointInterface);
        }