コード例 #1
0
        public static async Task GenerateAsync(FullPath rootDirectory)
        {
            var unit = new CompilationUnit();
            var ns   = unit.AddNamespace("Meziantou.GitLab");

            var emojiClass = ns.AddType(new ClassDeclaration("Emoji")
            {
                Modifiers = Modifiers.Public | Modifiers.Partial | Modifiers.Static
            });

            using var httpClient = new HttpClient();

            using var result = await httpClient.GetAsync("https://raw.githubusercontent.com/jonathanwiesel/gemojione/master/config/index.json").ConfigureAwait(false);

            var str = await result.Content.ReadAsStringAsync().ConfigureAwait(false);

            var emojis = System.Text.Json.JsonSerializer.Deserialize <Dictionary <string, Emoji> >(str);

            if (emojis == null)
            {
                throw new InvalidOperationException("Emojis is null");
            }

            var named = new HashSet <string>(StringComparer.Ordinal);

            foreach (var kvp in emojis.OrderBy(entry => entry.Value.Moji).ThenBy(entry => entry.Key))
            {
                Debug.Assert(!string.IsNullOrEmpty(kvp.Value.Name));

                var name     = kvp.Key.StartsWith("flag_", StringComparison.Ordinal) ? kvp.Key : kvp.Value.Name;
                var constant = new FieldDeclaration("Emoji" + GetName(name), typeof(string), Modifiers.Public | Modifiers.Const)
                {
                    InitExpression = new LiteralExpression(kvp.Key),
                };

                var field = emojiClass.AddMember(constant);
                field.XmlComments.AddSummary($"Emoji {kvp.Value.Name} '{kvp.Value.Moji}' (U+{kvp.Value.Unicode}) in category {kvp.Value.Category}");
            }

            unit.WriteUnit(rootDirectory / "Emoji.cs");

            string GetName(string value)
            {
                for (var i = 0; i < 1000; i++)
                {
                    var name = value
                               .Replace("’", "", StringComparison.Ordinal)
                               .Replace("'", "", StringComparison.Ordinal)
                               .Split(new[] { '_', '-', ' ', ':', ',', '(', ')' }, StringSplitOptions.RemoveEmptyEntries)
                               .Select(s => char.ToUpperInvariant(s[0]) + s[1..])
                               .Aggregate(string.Empty, (s1, s2) => s1 + s2)
                               + (i == 0 ? "" : i.ToString(CultureInfo.InvariantCulture));

                    if (named.Add(name))
                    {
                        return(name);
                    }
                }
コード例 #2
0
        private static void GenerateEnumerationUrlBuilder(Enumeration enumeration, CompilationUnit unit, TypeReference enumType)
        {
            var ns         = unit.AddNamespace(InternalsNamespace);
            var urlBuilder = ns.AddType(new StructDeclaration("UrlBuilder"));

            urlBuilder.Modifiers = Modifiers.Partial | Modifiers.Internal;

            // not nullable
            foreach (var(appendMethodName, encode) in new[] { ("AppendParameter", encode: true), ("AppendRawParameter", encode: false) })
コード例 #3
0
        public void CSharpCodeGenerator_Factorial()
        {
            var unit   = new CompilationUnit();
            var ns     = unit.AddNamespace("Meziantou.Framework.CodeDom");
            var c      = ns.AddType(new ClassDeclaration("Sample"));
            var method = c.AddMember(new MethodDeclaration("Factorial"));

            method.ReturnType = typeof(int);
            var n = method.AddArgument("n", typeof(int));

            method.Modifiers = Modifiers.Public | Modifiers.Static;

            method.Statements = new ConditionStatement()
            {
                Condition       = new BinaryExpression(BinaryOperator.LessThanOrEqual, 1, n),
                TrueStatements  = new ReturnStatement(1),
                FalseStatements = new ReturnStatement(new BinaryExpression(
                                                          BinaryOperator.Multiply,
                                                          n,
                                                          new MethodInvokeExpression(method, new BinaryExpression(BinaryOperator.Substract, n, 1))))
            };

            var generator = new CSharpCodeGenerator();
            var result    = generator.Write(unit);

            Assert.That.StringEquals(@"namespace Meziantou.Framework.CodeDom
{
    class Sample
    {
        public static int Factorial(int n)
        {
            if ((1 <= n))
            {
                return 1;
            }
            else
            {
                return (n * this.Factorial((n - 1)));
            }
        }
    }
}
", result);
        }
コード例 #4
0
        public async Task Generate()
        {
            var unit = new CompilationUnit();
            var ns   = unit.AddNamespace("Meziantou.GitLab");

            var emojiClass = ns.AddType(new ClassDeclaration("Emoji")
            {
                Modifiers = Modifiers.Public | Modifiers.Partial | Modifiers.Static
            });

            using (var httpClient = new HttpClient())
            {
                using (var result = await httpClient.GetAsync("https://raw.githubusercontent.com/jonathanwiesel/gemojione/master/config/index.json"))
                {
                    var str = await result.Content.ReadAsStringAsync();

                    var emojis = JsonConvert.DeserializeObject <Dictionary <string, Emoji> >(str);
                    foreach (var kvp in emojis.OrderBy(entry => entry.Key))
                    {
                        var constant = new FieldDeclaration("Emoji" + GetName(kvp.Key), typeof(string), Modifiers.Public | Modifiers.Const)
                        {
                            InitExpression = new LiteralExpression(kvp.Key)
                        };

                        var field = emojiClass.AddMember(constant);
                        field.XmlComments.AddSummary($"Emoji {kvp.Value.Name} {kvp.Value.Moji}");
                    }
                }
            }

            using (var tw = new StreamWriter("../../../../Meziantou.GitLabClient/Emoji.cs"))
            {
                new CSharpCodeGenerator().Write(tw, unit);
            }

            string GetName(string value)
            {
                return(value.Split(new[] { '_', '-' }, StringSplitOptions.RemoveEmptyEntries)
                       .Select(s => char.ToUpperInvariant(s[0]) + s.Substring(1, s.Length - 1))
                       .Aggregate(string.Empty, (s1, s2) => s1 + s2));
            }
        }
コード例 #5
0
        private static void GenerateQueries(CompilationUnit unit, GraphqlType type)
        {
            // generate response types + Connection types + input types
            // e.g. User / UserConnection / UserWhere / UserSelect
            foreach (var field in type.Fields)
            {
                var ns = unit.AddNamespace("Meziantou.GitLabClient.Graphql");

                ns.AddType(new ClassDeclaration(field.Name + "QueryBuilder"));

                if (field.Args != null)
                {
                    var argsType = ns.AddType(new ClassDeclaration(field.Name + "Args"));

                    foreach (var arg in field.Args)
                    {
                        argsType.AddMember(new PropertyDeclaration(arg.Name, typeof(object)));
                    }
                }
            }
        }
コード例 #6
0
ファイル: Program.cs プロジェクト: NBSChain/ghost-chat
        static void Main(string[] args)
        {
            var freeIconFile = Path.GetFullPath(Path.Combine("../../../", "Free", "metadata", "icons.json"));

            if (!File.Exists(freeIconFile))
            {
                Console.Error.WriteLine($"File not found: {freeIconFile}");
                Console.ReadKey();
                return;
            }

            var freeIcons = JsonConvert.DeserializeObject <IDictionary <string, Icon> >(File.ReadAllText(freeIconFile));
            var unit      = new CompilationUnit();
            var ns        = unit.AddNamespace("Naruto.WPF2Icon");

            {
                var enumeration = ns.AddType(new EnumerationDeclaration($"FontAwesomeIcons")
                {
                    Modifiers = Modifiers.Public
                });
                enumeration.BaseType = typeof(ushort);

                foreach (var(key, value) in freeIcons)
                {
                    var identifier = ToCSharpIdentifier(PascalName(key));
                    var member     = new EnumerationMember(identifier, value.UnicodeIntValue);
                    enumeration.Members.Add(member);

                    member.XmlComments.Add(new XElement("summary", $"{value.Label} ({value.Unicode})"));
                }
            }

            var codeGenerator = new CSharpCodeGenerator();

            File.WriteAllText("../../../Free/genout/FontAweIcons.cs", codeGenerator.Write(unit));
            return;
        }
コード例 #7
0
        private static TypeDeclaration GenerateEnumerationJsonConverter(CompilationUnit unit, EnumerationDeclaration enumType)
        {
            var serializationNamespace = unit.AddNamespace(SerializationNamespace);

            // EnumMembers
            var enumMember = serializationNamespace.AddType(new ClassDeclaration("EnumMember"));

            enumMember.Modifiers = Modifiers.Partial | Modifiers.Internal;

            var enumMemberType = WellKnownTypes.EnumMemberTypeReference.MakeGeneric(enumType);
            var arrayType      = enumMemberType.Clone();

            arrayType.ArrayRank = 1;

            // EnumMember.Field
            var initArray = enumMember.AddMember(new MethodDeclaration("Create" + enumType.Name + "Members"));

            initArray.Modifiers  = Modifiers.Private | Modifiers.Static;
            initArray.ReturnType = arrayType;
            initArray.Statements = new StatementCollection();
            var result = new VariableDeclarationStatement(arrayType, "result", new NewArrayExpression(enumMemberType, enumType.Members.Count));

            initArray.Statements.Add(result);

            for (var i = 0; i < enumType.Members.Count; i++)
            {
                var enumerationMember = enumType.Members[i];
                var model             = (EnumerationMember)enumerationMember.Data["EnumerationMember"];
                if (model == null)
                {
                    continue;
                }

                initArray.Statements.Add(new AssignStatement(
                                             new ArrayIndexerExpression(result, i),
                                             new NewObjectExpression(enumMemberType,
                                                                     new MemberReferenceExpression(new TypeReferenceExpression(enumType), ToPropertyName(enumerationMember.Name)),
                                                                     model.FinalSerializationName)));
            }
            initArray.Statements.Add(new ReturnStatement(result));

            var membersField = enumMember.AddMember(new FieldDeclaration("s" + ToFieldName(enumType.Name) + "Members", arrayType));

            membersField.Modifiers      = Modifiers.Private | Modifiers.Static | Modifiers.ReadOnly;
            membersField.InitExpression = new MethodInvokeExpression(new MemberReferenceExpression(new TypeReferenceExpression(enumMember), initArray));

            // EnumMember.FromString
            var fromString    = enumMember.AddMember(new MethodDeclaration(enumType.Name + "FromString"));
            var fromStringArg = fromString.AddArgument("value", typeof(string));

            fromString.Modifiers  = Modifiers.Public | Modifiers.Static;
            fromString.ReturnType = enumType;
            fromString.Statements = new StatementCollection
            {
                new ReturnStatement(new MethodInvokeExpression(
                                        new MemberReferenceExpression(new TypeReferenceExpression(enumMember), "FromString"),
                                        fromStringArg,
                                        new MemberReferenceExpression(new TypeReferenceExpression(enumMember), membersField))),
            };

            // EnumMember.ToString
            var toString    = enumMember.AddMember(new MethodDeclaration("ToString"));
            var toStringArg = toString.AddArgument("value", enumType);

            toString.Modifiers  = Modifiers.Public | Modifiers.Static;
            toString.ReturnType = typeof(string);
            toString.Statements = new StatementCollection();
            foreach (var member in enumType.Members)
            {
                var model = (EnumerationMember)member.Data["EnumerationMember"];
                if (model == null)
                {
                    continue;
                }

                toString.Statements.Add(new ConditionStatement()
                {
                    Condition      = new BinaryExpression(BinaryOperator.Equals, toStringArg, new MemberReferenceExpression(new TypeReferenceExpression(enumType), ToPropertyName(member.Name))),
                    TrueStatements = new ReturnStatement(model.FinalSerializationName),
                });
            }

            toString.Statements.Add(new ThrowStatement(
                                        new NewObjectExpression(typeof(ArgumentOutOfRangeException),
                                                                new NameofExpression(toStringArg),
                                                                new MethodInvokeExpression(new MemberReferenceExpression(typeof(string), "Concat"), "Value '", new MethodInvokeExpression(new MemberReferenceExpression(toStringArg, "ToString")), "' is not valid"))));

            // Json converter
            var converterType = serializationNamespace.AddType(new ClassDeclaration(enumType.Name + "JsonConverter"));

            converterType.BaseType  = new TypeReference("Meziantou.GitLab.Serialization.EnumBaseJsonConverter").MakeGeneric(enumType);
            converterType.Modifiers = Modifiers.Partial | Modifiers.Sealed | Modifiers.Internal;

            // ToString
            var converterToString = converterType.AddMember(new MethodDeclaration("ToString"));

            converterToString.Modifiers  = Modifiers.Protected | Modifiers.Override;
            converterToString.ReturnType = typeof(string);
            var convertToStringArg = converterToString.AddArgument("value", enumType);

            converterToString.Statements =
                new ReturnStatement(
                    new MethodInvokeExpression(
                        new MemberReferenceExpression(new TypeReferenceExpression(enumMember), "ToString"),
                        convertToStringArg));

            // FromString
            var converterFromString = converterType.AddMember(new MethodDeclaration("FromString"));

            converterFromString.Modifiers  = Modifiers.Protected | Modifiers.Override;
            converterFromString.ReturnType = enumType;
            var convertFromStringArg = converterFromString.AddArgument("value", typeof(string));

            converterFromString.Statements =
                new ReturnStatement(
                    new MethodInvokeExpression(
                        new MemberReferenceExpression(new TypeReferenceExpression(enumMember), enumType.Name + "FromString"),
                        convertFromStringArg));

            return(converterType);
        }
コード例 #8
0
        private void GenerateCode()
        {
            var unit = new CompilationUnit();
            var ns   = unit.AddNamespace("Meziantou.GitLab");

            // Generate types
            foreach (var model in Project.Models.OfType <Enumeration>().OrderBy(m => m.Name))
            {
                GenerateEnumeration(ns, model);
            }

            foreach (var model in Project.Models.OfType <Entity>().OrderBy(m => m.Name))
            {
                GenerateEntity(ns, model);
            }

            foreach (var entity in Project.ParameterEntities.OrderBy(p => p.Name))
            {
                GenerateParameterEntities(ns, entity);
            }

            var clientInterface = ns.AddType(new InterfaceDeclaration("IGitLabClient")
            {
                Modifiers = Modifiers.Partial
            });

            var clientClass = ns.AddType(new ClassDeclaration("GitLabClient")
            {
                Modifiers  = Modifiers.Partial,
                Implements =
                {
                    clientInterface
                }
            });

            var clientExtensionsClass = ns.AddType(new ClassDeclaration("GitLabClientExtensions")
            {
                Modifiers = Modifiers.Partial | Modifiers.Public | Modifiers.Static
            });

            // Generate methods
            foreach (var methodGroup in Project.MethodGroups)
            {
                foreach (var method in methodGroup.Methods)
                {
                    GenerateInterfaceMethod(clientInterface, method);
                    var methodDeclaration = GenerateMethod(clientClass, method);

                    // Add extension methods on entities
                    //foreach (var param in method.Parameters.Where(p => p.Type.IsParameterEntity))
                    //{
                    //    foreach (var entity in param.Type.ParameterEntity.Refs.Where(r => r.ModelRef.IsModel))
                    //    {
                    //        var type = ns.Types.OfType<ClassDeclaration>().First(t => t.Name == entity.ModelRef.Model.Name);
                    //        GenerateExtensionMethod(clientExtensionsClass, method, param);
                    //    }
                    //}
                }
            }

            GenerateFileExtensionMethod(clientClass, clientExtensionsClass);

            // Write file
            new DefaultFormatterVisitor().Visit(unit);
            using (var tw = new StreamWriter("../../../../Meziantou.GitLabClient/GitLabClient.generated.cs"))
            {
                new CSharpCodeGenerator().Write(tw, unit);
            }
        }
コード例 #9
0
ファイル: DwarfReader.cs プロジェクト: baulig/debugger
            public DieNamespace(DwarfBinaryReader reader, CompilationUnit comp_unit,
					     long offset, AbbrevEntry abbrev)
                : base(reader, comp_unit, abbrev)
            {
                this.offset = offset;
                comp_unit.AddNamespace (offset, this);

                if (extension != null) {
                    if (extension.name != null) {
                        if (name != null)
                            name = extension.name + "::" + name;
                        else
                            name = extension.name;
                    }
                }
            }