示例#1
0
 /// <summary>
 /// End a file
 /// </summary>
 protected override void WriteFileFooter(GeneratorContext ctx, FileDescriptorProto file, ref object state)
 {
     if (ctx.Supports(VB14))
     {
         ctx.WriteLine($"#Enable Warning BC40008, BC40055, IDE1006").WriteLine();
     }
 }
示例#2
0
            internal void AddFile(FileDescriptorProto fileDescriptor)
            {
                if (_filesByName.ContainsKey(fileDescriptor.Name))
                {
                    return;
                }
                _filesByName.Add(fileDescriptor.Name, fileDescriptor);

                foreach (var dependency in fileDescriptor.GetDependencies())
                {
                    AddFile(dependency);
                }
                foreach (var enumeration in fileDescriptor.EnumTypes)
                {
                    AddEnum(enumeration);
                }
                foreach (var message in fileDescriptor.MessageTypes)
                {
                    AddMessage(message);
                }
                foreach (var service in fileDescriptor.Services)
                {
                    AddService(service);
                }
            }
示例#3
0
        ProtoTypeNode GetOrCreateTypeNode(string name, FileDescriptorProto proto = null, object source = null)
        {
            if (!protobufTypeMap.TryGetValue(name, out var node))
            {
                node = new ProtoTypeNode()
                {
                    Name    = name,
                    Proto   = proto,
                    Source  = source,
                    Defined = source != null
                };

                protobufTypeMap.Add(name, node);
            }
            else if (source != null)
            {
                Debug.Assert(node.Defined == false);

                node.Proto   = proto;
                node.Source  = source;
                node.Defined = true;
            }

            return(node);
        }
示例#4
0
 /// <summary>
 /// Create a new GeneratorContext instance
 /// </summary>
 internal GeneratorContext(FileDescriptorProto file, NameNormalizer nameNormalizer, TextWriter output, string indentToken)
 {
     File           = file;
     NameNormalizer = nameNormalizer;
     Output         = output;
     IndentToken    = indentToken;
 }
示例#5
0
        Dictionary <string, string> DumpOptions(FileDescriptorProto source, MessageOptions options)
        {
            var optionsKv = new Dictionary <string, string>();

            if (options == null)
            {
                return(optionsKv);
            }

            if (options.message_set_wire_formatSpecified)
            {
                optionsKv.Add("message_set_wire_format", options.message_set_wire_format ? "true" : "false");
            }
            if (options.no_standard_descriptor_accessorSpecified)
            {
                optionsKv.Add("no_standard_descriptor_accessor", options.no_standard_descriptor_accessor ? "true" : "false");
            }
            if (options.deprecatedSpecified)
            {
                optionsKv.Add("deprecated", options.deprecated ? "true" : "false");
            }

            DumpOptionsMatching(source, ".google.protobuf.MessageOptions", options, optionsKv);

            return(optionsKv);
        }
示例#6
0
        public void AddMessagesToReset(DescriptorProto proto_msg, FileDescriptorProto fileDescriptor)
        {
            var key         = GetMessageCSharpName(proto_msg.Name, fileDescriptor.Package);
            var fields_list = proto_msg.Fields;

            foreach (var field in fields_list)
            {
                if (field.type == FieldDescriptorProto.Type.TypeMessage)//todo
                {
                    //var key_nested = GetMessageCSharpName(origin_typename, ns);
                    //DescriptorProto depend_proto_msg;
                    //if(MessagesReceive.TryGetValue(key_nested, out depend_proto_msg))
                    //{
                    //    continue;
                    //}
                    //else
                    //{
                    //    Messages.TryGetValue(key_nested, out depend_proto_msg);
                    //    Console.WriteLine("key_nested " + key_nested);
                    //    AddMessagesToReset(depend_proto_msg, ns);
                    //}
                }
            }
            MessagesReceive.Add(key, proto_msg);
        }
示例#7
0
        private void DoParseFile(FileDescriptorProto set)
        {
            StringBuilder sb = new StringBuilder();

            DumpFileDescriptor(set, sb);

            FinalProtoDefinition.Add(new ProtoData {
                file = set, buffer = sb
            });
            ProtoList.Add(set.name);

            List <FileDescriptorProto> protosToRender = new List <FileDescriptorProto>();

            do
            {
                protosToRender.Clear();

                foreach (var proto in deferredProtos)
                {
                    if (!ShouldDeferProto(proto))
                    {
                        protosToRender.Add(proto);
                    }
                }

                foreach (var proto in protosToRender)
                {
                    deferredProtos.Remove(proto);
                    DoParseFile(proto);
                }
            }while (protosToRender.Count != 0);
        }
示例#8
0
        /// <summary>
        /// End a file
        /// </summary>
        protected override void WriteFileFooter(GeneratorContext ctx, FileDescriptorProto file, ref object state)
        {
            var @namespace = (string)state;

            if (!string.IsNullOrWhiteSpace(@namespace))
            {
                ctx.Outdent().WriteLine("}").WriteLine();
            }
            var @filename = file.Name.Substring(0, file.Name.IndexOf("."));

            ctx.WriteLine($"public class ILRuntime_{@filename}");
            ctx.WriteLine("{").Indent();
            ctx.WriteLine($"static ILRuntime_{@filename}()");
            ctx.WriteLine("{");
            ctx.WriteLine().Indent();
            ctx.WriteLine($"//Initlize();");
            ctx.WriteLine().Outdent();
            ctx.WriteLine("}");
            ctx.WriteLine($"public static void Initlize()");
            ctx.WriteLine("{");
            ctx.WriteLine().Indent();
            foreach (var T in TypeNames2)
            {
                ctx.WriteLine($@"ProtoBuf.PType.RegisterType(""{T}"", typeof({T}));");
            }
            ctx.WriteLine().Outdent();
            ctx.WriteLine("}").Outdent();
            ctx.WriteLine("}").WriteLine();
            ctx.WriteLine("#pragma warning restore CS1591, CS0612, CS3021");
        }
示例#9
0
 private void CheckByEachFile(FileDescriptorProto protofile)
 {
     foreach (ServiceDescriptorProto service in protofile.Service)
     {
         CheckEachService(service);
     }
 }
示例#10
0
        /// <summary>
        /// Start a file
        /// </summary>
        protected override void WriteFileHeader(GeneratorContext ctx, FileDescriptorProto file, ref object state)
        {
            var prefix = ctx.Supports(CSharp6) ? "CS" : "";
            var tw     = ctx.WriteLine("// <auto-generated>")
                         .WriteLine("//   This file was generated by a tool; you should avoid making direct changes.")
                         .WriteLine("//   Consider using 'partial classes' to extend these types")
                         .WriteLine($"//   Input: {Path.GetFileName(ctx.File.Name)}")
                         .WriteLine("// </auto-generated>")
                         .WriteLine()
                         .WriteLine("#region Designer generated code")
                         .Write($"#pragma warning disable {prefix}0612, {prefix}1591, {prefix}3021");

            if (ctx.Supports(CSharp6))
            {
                tw.Write(AdditionalSuppressionCodes);
            }
            tw.WriteLine();

            var @namespace = ctx.NameNormalizer.GetName(file);

            if (!string.IsNullOrWhiteSpace(@namespace))
            {
                state = @namespace;
                ctx.WriteLine($"namespace {@namespace}");
                ctx.WriteLine("{").Indent().WriteLine();
            }
        }
示例#11
0
        void DumpService(FileDescriptorProto source, ServiceDescriptorProto service, StringBuilder sb)
        {
            sb.AppendLine($"service {service.name} {{");

            foreach (var option in DumpOptions(source, service.options))
            {
                sb.AppendLine($"\toption {option.Key} = {option.Value};");
            }

            foreach (var method in service.method)
            {
                var declaration = $"\trpc {method.name} ({method.input_type}) returns ({method.output_type})";

                var options = DumpOptions(source, method.options);

                if (options.Count == 0)
                {
                    sb.AppendLine($"{declaration};");
                }
                else
                {
                    sb.AppendLine($"{declaration} {{");

                    foreach (var option in options)
                    {
                        sb.AppendLine($"\t\toption {option.Key} = {option.Value};");
                    }

                    sb.AppendLine("\t}");
                }
            }

            sb.AppendLine("}");
            sb.AppendLine();
        }
示例#12
0
        /// <summary>
        /// Builds a FileDescriptor from its protocol buffer representation.
        /// </summary>
        /// <param name="descriptorData">The original serialized descriptor data.
        /// We have only limited proto2 support, so serializing FileDescriptorProto
        /// would not necessarily give us this.</param>
        /// <param name="proto">The protocol message form of the FileDescriptor.</param>
        /// <param name="dependencies">FileDescriptors corresponding to all of the
        /// file's dependencies, in the exact order listed in the .proto file. May be null,
        /// in which case it is treated as an empty array.</param>
        /// <param name="allowUnknownDependencies">Whether unknown dependencies are ignored (true) or cause an exception to be thrown (false).</param>
        /// <param name="generatedCodeInfo">Details about generated code, for the purposes of reflection.</param>
        /// <exception cref="DescriptorValidationException">If <paramref name="proto"/> is not
        /// a valid descriptor. This can occur for a number of reasons, such as a field
        /// having an undefined type or because two messages were defined with the same name.</exception>
        private static FileDescriptor BuildFrom(ByteString descriptorData, FileDescriptorProto proto, FileDescriptor[] dependencies, bool allowUnknownDependencies, GeneratedClrTypeInfo generatedCodeInfo)
        {
            // Building descriptors involves two steps: translating and linking.
            // In the translation step (implemented by FileDescriptor's
            // constructor), we build an object tree mirroring the
            // FileDescriptorProto's tree and put all of the descriptors into the
            // DescriptorPool's lookup tables.  In the linking step, we look up all
            // type references in the DescriptorPool, so that, for example, a
            // FieldDescriptor for an embedded message contains a pointer directly
            // to the Descriptor for that message's type.  We also detect undefined
            // types in the linking step.
            if (dependencies == null)
            {
                dependencies = new FileDescriptor[0];
            }

            DescriptorPool pool   = new DescriptorPool(dependencies);
            FileDescriptor result = new FileDescriptor(descriptorData, proto, dependencies, pool, allowUnknownDependencies, generatedCodeInfo);

            // Validate that the dependencies we've been passed (as FileDescriptors) are actually the ones we
            // need.
            if (dependencies.Length != proto.Dependency.Count)
            {
                throw new DescriptorValidationException(
                          result,
                          "Dependencies passed to FileDescriptor.BuildFrom() don't match " +
                          "those listed in the FileDescriptorProto.");
            }

            result.CrossLink();
            return(result);
        }
示例#13
0
        protected override void WriteFile(GeneratorContext ctx, FileDescriptorProto obj)
        {
            var file = ctx.File;
            var ast  = new ProtoFile
            {
                PackageName = file.Package,
                CsNamespace = file.Options?.CsharpNamespace ?? file.Package,
                Messages    = file
                              .MessageTypes
                              .ToArray()
                              .Select(mt => new ProtoMessage {
                    Name = mt.Name
                })
                              .ToArray(),
                Services = file
                           .Services
                           .ToArray()
                           .Select(s => new ProtoService
                {
                    Name    = s.Name,
                    Methods = s.Methods.ToArray().Select(m => new ProtoMethod
                    {
                        Name       = m.Name,
                        InputName  = RemovePackageName(m.InputType),
                        OutputName = RemovePackageName(m.OutputType),
                    }).ToArray()
                })
                           .ToArray()
            };
            var f = Handlebars.Compile(Template.Code);

            var result = f(ast);

            ctx.WriteLine(result);
        }
示例#14
0
        public void ExampleImport()
        {
            using (var stream = File.OpenRead(@"protobuf/example.import"))
            {
                FileDescriptorSet descriptorSet = FileDescriptorSet.Parser.ParseFrom(stream);
                Google.Protobuf.Collections.RepeatedField <FileDescriptorProto> descriptorsProto = descriptorSet.File;
                FileDescriptorProto a  = descriptorsProto[0];
                FileDescriptorProto b  = descriptorsProto[1];
                FileDescriptorProto bb = descriptorsProto[2];
                FileDescriptorProto c  = descriptorsProto[3];
                FileDescriptorProto cc = descriptorsProto[4];

                Assert.That(b.Dependency.Count, Is.EqualTo(1));
                Assert.That(b.Dependency[0], Contains.Substring("A.proto"));
                Assert.That(b.PublicDependency.Count, Is.EqualTo(0));

                Assert.That(bb.Dependency.Count, Is.EqualTo(1));
                Assert.That(bb.Dependency[0], Contains.Substring("B.proto"));
                Assert.That(bb.PublicDependency.Count, Is.EqualTo(0));

                Assert.That(c.Dependency.Count, Is.EqualTo(1));
                Assert.That(c.Dependency[0], Contains.Substring("A.proto"));
                Assert.That(c.PublicDependency.Count, Is.EqualTo(1));

                Assert.That(cc.Dependency.Count, Is.EqualTo(1));
                Assert.That(cc.Dependency[0], Contains.Substring("C.proto"));
                Assert.That(cc.PublicDependency.Count, Is.EqualTo(1));
            }
        }
示例#15
0
        public void Test1()
        {
            using (var stream = File.OpenRead(@"mymodel"))
            {
                FileDescriptorSet descriptorSet = FileDescriptorSet.Parser.ParseFrom(stream);
                Google.Protobuf.Collections.RepeatedField <FileDescriptorProto> descriptorsProto = descriptorSet.File;
                FileDescriptorProto info = descriptorsProto[0];

                var service = info.Service[0];
                Console.WriteLine("---------------");
                Console.WriteLine("| <<Service>> |");
                Console.WriteLine($"| {service.Name} |");
                Console.WriteLine("---------------");
                foreach (MethodDescriptorProto method in service.Method)
                {
                    Console.WriteLine($"| + {method.OutputType} {method.Name}({method.InputType}) |");
                }
                Console.WriteLine("---------------");

                foreach (DescriptorProto message in info.MessageType)
                {
                    Console.WriteLine("---------------");
                    Console.WriteLine($"| {message.Name} |");
                    Console.WriteLine("---------------");
                    foreach (var field in message.Field)
                    {
                        Console.WriteLine($"| + {field.TypeName} {field.Name} |");
                    }
                    Console.WriteLine("---------------");
                }
            }
        }
示例#16
0
        void DumpEnumDescriptor(FileDescriptorProto source, EnumDescriptorProto field, StringBuilder sb, int level, ref bool marker)
        {
            var levelspace = new string( '\t', level );

            AppendHeadingSpace(sb, ref marker);
            sb.AppendLine($"{levelspace}enum {field.name} {{");

            foreach (var option in DumpOptions(source, field.options))
            {
                sb.AppendLine($"{levelspace}\toption {option.Key} = {option.Value};");
            }

            foreach (var enumValue in field.value)
            {
                var options = DumpOptions(source, enumValue.options);

                var parameters = string.Empty;
                if (options.Count > 0)
                {
                    parameters = $" [{string.Join( ", ", options.Select( kvp => $"{kvp.Key} = {kvp.Value}" ) )}]";
                }

                sb.AppendLine($"{levelspace}\t{enumValue.name} = {enumValue.number}{parameters};");
            }

            sb.AppendLine($"{levelspace}}}");
            marker = true;
        }
示例#17
0
        /// <summary>
        /// Emits the code for a file in a descriptor-set
        /// </summary>
        protected virtual void WriteFile(GeneratorContext ctx, FileDescriptorProto obj)
        {
            var    file  = ctx.File;
            object state = null;

            WriteFileHeader(ctx, obj, ref state);

            foreach (var inner in file.MessageTypes)
            {
                WriteMessage(ctx, inner);
            }
            foreach (var inner in file.EnumTypes)
            {
                WriteEnum(ctx, inner);
            }
            foreach (var inner in file.Services)
            {
                WriteService(ctx, inner);
            }
            if (file.Extensions.Count != 0)
            {
                object extState = null;
                WriteExtensionsHeader(ctx, file, ref extState);
                foreach (var ext in file.Extensions)
                {
                    WriteExtension(ctx, ext);
                }
                WriteExtensionsFooter(ctx, file, ref extState);
            }
            WriteFileFooter(ctx, obj, ref state);
        }
示例#18
0
        void DumpFileDescriptor(FileDescriptorProto proto, StringBuilder sb)
        {
            if (!string.IsNullOrEmpty(proto.package))
            {
                PushDescriptorName(proto);
            }

            var marker = false;

            for (var i = 0; i < proto.dependency.Count; i++)
            {
                var dependency = proto.dependency[i];
                var modifier   = proto.public_dependency.Contains(i) ? "public " : "";
                sb.AppendLine($"import {modifier}\"{dependency}\";");
                marker = true;
            }

            if (!string.IsNullOrEmpty(proto.package))
            {
                AppendHeadingSpace(sb, ref marker);
                sb.AppendLine($"package {proto.package};");
                marker = true;
            }

            var options = DumpOptions(proto, proto.options);

            foreach (var option in options)
            {
                AppendHeadingSpace(sb, ref marker);
                sb.AppendLine($"option {option.Key} = {option.Value};");
            }

            if (options.Count > 0)
            {
                marker = true;
            }

            DumpExtensionDescriptors(proto, proto.extension, sb, 0, ref marker);

            foreach (var field in proto.enum_type)
            {
                DumpEnumDescriptor(proto, field, sb, 0, ref marker);
            }

            foreach (var message in proto.message_type)
            {
                DumpDescriptor(proto, message, sb, 0, ref marker);
            }

            foreach (var service in proto.service)
            {
                DumpService(proto, service, sb, ref marker);
            }

            if (!string.IsNullOrEmpty(proto.package))
            {
                PopDescriptorName();
            }
        }
示例#19
0
        private Dictionary <string, string> DumpOptions(FileDescriptorProto source, FileOptions options)
        {
            var optionsKv = new Dictionary <string, string>();

            if (options == null)
            {
                return(optionsKv);
            }

            if (options.deprecatedSpecified)
            {
                optionsKv.Add("deprecated", options.deprecated ? "true" : "false");
            }
            if (options.optimize_forSpecified)
            {
                optionsKv.Add("optimize_for", $"{options.optimize_for}");
            }
            if (options.cc_generic_servicesSpecified)
            {
                optionsKv.Add("cc_generic_services", options.cc_generic_services ? "true" : "false");
            }
            if (options.go_packageSpecified)
            {
                optionsKv.Add("go_package", $"\"{options.go_package}\"");
            }
            if (options.java_packageSpecified)
            {
                optionsKv.Add("java_package", $"\"{options.java_package}\"");
            }
            if (options.java_outer_classnameSpecified)
            {
                optionsKv.Add("java_outer_classname", $"\"{options.java_outer_classname}\"");
            }
            if (options.java_generate_equals_and_hashSpecified)
            {
                optionsKv.Add("java_generate_equals_and_hash",
                              options.java_generate_equals_and_hash ? "true" : "false");
            }
            if (options.java_generic_servicesSpecified)
            {
                optionsKv.Add("java_generic_services", options.java_generic_services ? "true" : "false");
            }
            if (options.java_multiple_filesSpecified)
            {
                optionsKv.Add("java_multiple_files", options.java_multiple_files ? "true" : "false");
            }
            if (options.java_string_check_utf8Specified)
            {
                optionsKv.Add("java_string_check_utf8", options.java_string_check_utf8 ? "true" : "false");
            }
            if (options.py_generic_servicesSpecified)
            {
                optionsKv.Add("py_generic_services", options.py_generic_services ? "true" : "false");
            }

            DumpOptionsMatching(source, ".google.protobuf.FileOptions", options, optionsKv);

            return(optionsKv);
        }
示例#20
0
        protected override void GenerateByEachFile(FileDescriptorProto protofile, CodeGeneratorResponse response)
        {
            bool genericClient;

            protofile.Options.CustomOptions.TryGetBool(DotBPEOptions.DISABLE_GENERIC_SERVICES_CLIENT, out genericClient);
            if (genericClient)
            {
                return;
            }
            if (protofile.Service == null || protofile.Service.Count <= 0)
            {
                return;
            }
            //生成文件头
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("// Generated by the protocol buffer compiler.  DO NOT EDIT!");
            sb.AppendLine($"// source: {protofile.Name}");
            //还可以生成注释

            sb.AppendLine("#region Designer generated code");
            sb.AppendLine("");
            sb.AppendLine("using System; ");
            sb.AppendLine("using System.Threading.Tasks; ");
            sb.AppendLine("using DotBPE.Rpc; ");
            sb.AppendLine("using DotBPE.Protocol.Amp; ");
            sb.AppendLine("using DotBPE.Rpc.Exceptions; ");
            sb.AppendLine("using Google.Protobuf; ");
            sb.AppendLine("");

            string ns = Utils.GetFileNamespace(protofile);

            sb.AppendLine("namespace " + ns + " {");
            //生成代码

            foreach (ServiceDescriptorProto t in protofile.Service)
            {
                t.Options.CustomOptions.TryGetBool(DotBPEOptions.DISABLE_GENERIC_SERVICES_CLIENT, out genericClient);
                if (genericClient)
                {
                    continue;
                }
                sb.AppendLine("");
                sb.AppendLine("//start for class " + t.Name + "Client");
                GenerateServiceForClient(t, sb);
                sb.AppendLine("//end for class " + t.Name + "Client");
            }
            sb.AppendLine("}");
            sb.AppendLine("#endregion");

            //生成文件
            var nfile = new CodeGeneratorResponse.Types.File
            {
                Name    = Utils.GetFileName(protofile.Name) + "Client.cs",
                Content = sb.ToString()
            };

            response.File.Add(nfile);
        }
 static byte[] SerializeFileDescriptor(FileDescriptorProto descriptor)
 {
     using (var stream = new MemoryStream(4096))
     {
         Serializer.Serialize(stream, descriptor);
         return(stream.ToArray());
     }
 }
示例#22
0
        private string BuildDescriptorDeclaration(FileDescriptorProto source, FieldDescriptorProto field,
                                                  bool emitFieldLabel = true)
        {
            PushDescriptorName(field);

            var type    = ResolveType(field);
            var options = new Dictionary <string, string>();

            if (!string.IsNullOrEmpty(field.default_value))
            {
                var defaultValue = field.default_value;

                if (field.type == FieldDescriptorProto.Type.TYPE_STRING)
                {
                    defaultValue = $"\"{defaultValue}\"";
                }

                options.Add("default", defaultValue);
            }
            else if (field.type == FieldDescriptorProto.Type.TYPE_ENUM &&
                     field.label != FieldDescriptorProto.Label.LABEL_REPEATED)
            {
                var lookup = _protobufTypeMap[field.type_name];

                if (lookup.Source is EnumDescriptorProto enumDescriptor && enumDescriptor.value.Count > 0)
                {
                    options.Add("default", enumDescriptor.value[0].name);
                }
            }

            var fieldOptions = DumpOptions(source, field.options);

            foreach (var(key, value) in fieldOptions)
            {
                options[key] = value;
            }

            var parameters = string.Empty;

            if (options.Count > 0)
            {
                parameters = $" [{string.Join(", ", options.Select(kvp => $"{kvp.Key} = {kvp.Value}"))}]";
            }

            PopDescriptorName();

            var descriptorDeclarationBuilder = new StringBuilder();

            if (emitFieldLabel)
            {
                descriptorDeclarationBuilder.Append(GetLabel(field.label));
                descriptorDeclarationBuilder.Append(" ");
            }

            descriptorDeclarationBuilder.Append($"{type} {field.name} = {field.number}{parameters};");

            return(descriptorDeclarationBuilder.ToString());
        }
示例#23
0
        private bool HandleProto(string name, byte[] data)
        {
            //if (name == "google/protobuf/descriptor.proto")
            //    return true;

            Console.WriteLine("Found protobuf candidate '{0}'!", name);

            FileDescriptorProto set = null;

            if (Environment.GetCommandLineArgs().Contains("-dump", StringComparer.OrdinalIgnoreCase))
            {
                string fileName = Path.Combine(OutputDir, name + ".dump");
                Directory.CreateDirectory(Path.GetDirectoryName(fileName));

                Console.WriteLine("  ! Dumping to '{0}'!", fileName);

                try
                {
                    File.WriteAllBytes(fileName, data);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Unable to dump: {0}", ex.Message);
                    return(true);
                }
            }

            try
            {
                using (MemoryStream ms = new MemoryStream(data))
                    set = Serializer.Deserialize <FileDescriptorProto>(ms);
            }
            catch (Exception ex)
            {
                if (ex.GetType() == typeof(EndOfStreamException))
                {
                    Console.WriteLine("'{0}' needs rescan: {1}\n", name, ex.Message);
                    return(false);
                }

                Console.WriteLine("'{0}' was invalid: {1}\n", name, ex.Message);
                return(true);
            }

            if (ShouldDeferProto(set))
            {
                Console.WriteLine("  ! Deferring parsing proto '{0}'\n", set.name);

                deferredProtos.Add(set);
            }
            else
            {
                DoParseFile(set);
            }

            return(true);
        }
            public override Writer <T> AddWriter <T>(string topic)
            {
                var    msgType                 = typeof(T).ToString();
                string descriptorName          = NameByMsgType[msgType];
                FileDescriptorProto descriptor = DescriptorByName[descriptorName].Item2;

                var descriptors = new List <byte[]>();

                GetDescriptors(descriptors, descriptor);

                int count = descriptors.Count;

                var data = new List <byte>(4096);

                data.Add((byte)Op.RegisterDesc);
                data.Add((byte)(count >> 0));
                data.Add((byte)(count >> 8));
                data.Add((byte)(count >> 16));
                data.Add((byte)(count >> 24));
                foreach (var s in descriptors)
                {
                    int bytes = s.Length;
                    data.Add((byte)(bytes >> 0));
                    data.Add((byte)(bytes >> 8));
                    data.Add((byte)(bytes >> 16));
                    data.Add((byte)(bytes >> 24));
                    data.AddRange(s);
                }

                var channel = System.Text.Encoding.ASCII.GetBytes(topic);

                byte[] descriptorData = DescriptorByName[descriptorName].Item1;
                var    typeb          = System.Text.Encoding.ASCII.GetBytes(msgType);

                data.Add((byte)Op.AddWriter);
                data.Add((byte)(channel.Length >> 0));
                data.Add((byte)(channel.Length >> 8));
                data.Add((byte)(channel.Length >> 16));
                data.Add((byte)(channel.Length >> 24));
                data.AddRange(channel);
                data.Add((byte)(typeb.Length >> 0));
                data.Add((byte)(typeb.Length >> 8));
                data.Add((byte)(typeb.Length >> 16));
                data.Add((byte)(typeb.Length >> 24));
                data.AddRange(typeb);

                TopicPublishers.Add(new Topic()
                {
                    Name = topic,
                    Type = typeof(T).ToString(),
                });

                SendAsync(data.ToArray());

                return(new CyberWriter <T>(this, topic));
            }
示例#25
0
        static void WorkSingleEntry(Docs.ServiceDocFactory docs, FileDescriptorProto filedesc, ServiceDescriptorProto service, List <NameInfo> names, string sourceFile)
        {
            var targetName = filedesc.Options?.CsharpNamespace ?? "";

            if (targetName.StartsWith(settings.NamespaceBase))
            {
                targetName = targetName.Substring(settings.NamespaceBase.Length);
            }
            else
            {
                log.WriteWarning(text: $"the c# namespace {targetName} has not the base {settings.NamespaceBase}. The namespace will not be shortened.",
                                 file: filedesc.Name);
            }
            if (targetName != null)
            {
                targetName += '.';
            }
            targetName = (targetName + service.Name).Replace('.', '/');
            if (targetName.StartsWith("/"))
            {
                targetName = targetName.Substring(1);
            }
            targetName = Path.Combine(settings.OutputDir + "/", targetName + settings.FileExtension);
            if (settings.Verbose)
            {
                Console.WriteLine($" Generate service for {service.Name} at {targetName}...");
            }
            var fi = new FileInfo(targetName);

            if (!fi.Directory.Exists)
            {
                try { fi.Directory.Create(); }
                catch (IOException e)
                {
                    log.WriteError(text: $"Couldn't create directory for output file {targetName}: {e}",
                                   file: filedesc.Name);
                    return;
                }
            }
            using var writer = new StreamWriter(new FileStream(targetName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite));
            writer.BaseStream.SetLength(0);
            Generator generator = settings.OutputFormat switch
            {
                "1" => new Generator(docs, settings, log),
                "2" => new Generator2(docs, settings, log),
                _ => new Generator(docs, settings, log),
            };

            generator.GenerateServiceFile(filedesc, service, writer, names);
            writer.Flush();

            if (report != null)
            {
                if (settings.BuildProtoc)
                {
                    sourceFile = sourceFile[0..^ 4];
示例#26
0
        public static string GetFileNamespace(FileDescriptorProto protofile)
        {
            string ns = protofile.Options.CsharpNamespace;

            if (string.IsNullOrEmpty(ns))
            {
                throw new Exception("" + protofile.Name + ".proto did not set csharp_namespace");
            }
            return(ConvertCamelCase(ns));
        }
        public void ToJsonRequiringBufferExpansion()
        {
            string s    = new string('.', 4086);
            var    opts = FileDescriptorProto.CreateBuilder()
                          .SetName(s)
                          .SetPackage("package")
                          .BuildPartial();

            Assert.NotNull(Extensions.ToJson(opts));
        }
        /// <summary>
        /// Starts an extgensions block
        /// </summary>
        protected override void WriteExtensionsHeader(GeneratorContext ctx, FileDescriptorProto file, ref object state)
        {
            var name = file?.Options?.GetOptions()?.ExtensionTypeName;

            if (string.IsNullOrWhiteSpace(name))
            {
                name = "Extensions";
            }
            ctx.WriteLine($"{GetAccess(GetAccess(file))} static class {Escape(name)}").WriteLine("{").Indent();
        }
 public virtual UmlPackage CreateUmlPackage(FileDescriptorProto fileDescriptorProto)
 {
     /*
      * UmlPackage umlPackage = new UmlPackage(fileDescriptorProto.Package);
      * UmlModel umlModel = CreateUmlModel(fileDescriptorProto);
      * umlPackage.UmlModel = umlModel;
      * return umlPackage;
      */
     return(null);
 }
示例#30
0
        /// <summary>
        /// End a file
        /// </summary>
        protected override void WriteFileFooter(GeneratorContext ctx, FileDescriptorProto file, ref object state)
        {
            var @namespace = (string)state;

            if (!string.IsNullOrEmpty(@namespace))
            {
                ctx.Outdent().WriteLine("}").WriteLine();
            }
            //ctx.WriteLine("#pragma warning restore CS1591, CS0612, CS3021");
        }
示例#31
0
 /// <summary>Helper: create a new instance to deserializing into</summary>
 public static FileDescriptorProto DeserializeLength(Stream stream, int length)
 {
     FileDescriptorProto instance = new FileDescriptorProto();
     DeserializeLength(stream, length, instance);
     return instance;
 }
        /// <summary>Serialize the instance into the stream</summary>
        public static void Serialize(Stream stream, FileDescriptorProto instance)
        {
            var msField = global::SilentOrbit.ProtocolBuffers.ProtocolParser.Stack.Pop();
            if (instance.Name != null)
            {
                // Key for field: 1, LengthDelimited
                stream.WriteByte(10);
                global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.Name));
            }
            if (instance.Package != null)
            {
                // Key for field: 2, LengthDelimited
                stream.WriteByte(18);
                global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.Package));
            }
            if (instance.Dependency != null)
            {
                foreach (var i3 in instance.Dependency)
                {
                    // Key for field: 3, LengthDelimited
                    stream.WriteByte(26);
                    global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(i3));
                }
            }
            if (instance.PublicDependency != null)
            {
                foreach (var i10 in instance.PublicDependency)
                {
                    // Key for field: 10, Varint
                    stream.WriteByte(80);
                    global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(stream,(ulong)i10);
                }
            }
            if (instance.WeakDependency != null)
            {
                foreach (var i11 in instance.WeakDependency)
                {
                    // Key for field: 11, Varint
                    stream.WriteByte(88);
                    global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(stream,(ulong)i11);
                }
            }
            if (instance.MessageType != null)
            {
                foreach (var i4 in instance.MessageType)
                {
                    // Key for field: 4, LengthDelimited
                    stream.WriteByte(34);
                    msField.SetLength(0);
                    Google.Protobuf.DescriptorProto.Serialize(msField, i4);
                    // Length delimited byte array
                    uint length4 = (uint)msField.Length;
                    global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, length4);
                    msField.WriteTo(stream);

                }
            }
            if (instance.EnumType != null)
            {
                foreach (var i5 in instance.EnumType)
                {
                    // Key for field: 5, LengthDelimited
                    stream.WriteByte(42);
                    msField.SetLength(0);
                    Google.Protobuf.EnumDescriptorProto.Serialize(msField, i5);
                    // Length delimited byte array
                    uint length5 = (uint)msField.Length;
                    global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, length5);
                    msField.WriteTo(stream);

                }
            }
            if (instance.Service != null)
            {
                foreach (var i6 in instance.Service)
                {
                    // Key for field: 6, LengthDelimited
                    stream.WriteByte(50);
                    msField.SetLength(0);
                    Google.Protobuf.ServiceDescriptorProto.Serialize(msField, i6);
                    // Length delimited byte array
                    uint length6 = (uint)msField.Length;
                    global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, length6);
                    msField.WriteTo(stream);

                }
            }
            if (instance.Extension != null)
            {
                foreach (var i7 in instance.Extension)
                {
                    // Key for field: 7, LengthDelimited
                    stream.WriteByte(58);
                    msField.SetLength(0);
                    Google.Protobuf.FieldDescriptorProto.Serialize(msField, i7);
                    // Length delimited byte array
                    uint length7 = (uint)msField.Length;
                    global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, length7);
                    msField.WriteTo(stream);

                }
            }
            if (instance.Options != null)
            {
                // Key for field: 8, LengthDelimited
                stream.WriteByte(66);
                msField.SetLength(0);
                Google.Protobuf.FileOptions.Serialize(msField, instance.Options);
                // Length delimited byte array
                uint length8 = (uint)msField.Length;
                global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, length8);
                msField.WriteTo(stream);

            }
            if (instance.SourceCodeInfo != null)
            {
                // Key for field: 9, LengthDelimited
                stream.WriteByte(74);
                msField.SetLength(0);
                Google.Protobuf.SourceCodeInfo.Serialize(msField, instance.SourceCodeInfo);
                // Length delimited byte array
                uint length9 = (uint)msField.Length;
                global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, length9);
                msField.WriteTo(stream);

            }
            global::SilentOrbit.ProtocolBuffers.ProtocolParser.Stack.Push(msField);
        }
 /// <summary>Helper: create a new instance to deserializing into</summary>
 public static FileDescriptorProto Deserialize(Stream stream)
 {
     var instance = new FileDescriptorProto();
     Deserialize(stream, instance);
     return instance;
 }
示例#34
0
 /// <summary>Helper: put the buffer into a MemoryStream and create a new instance to deserializing into</summary>
 public static FileDescriptorProto Deserialize(byte[] buffer)
 {
     FileDescriptorProto instance = new FileDescriptorProto();
     using (var ms = new MemoryStream(buffer))
         Deserialize(ms, instance);
     return instance;
 }
示例#35
0
 /// <summary>Helper: Serialize into a MemoryStream and return its byte array</summary>
 public static byte[] SerializeToBytes(FileDescriptorProto instance)
 {
     using (var ms = new MemoryStream())
     {
         Serialize(ms, instance);
         return ms.ToArray();
     }
 }
示例#36
0
 /// <summary>Helper: Serialize with a varint length prefix</summary>
 public static void SerializeLengthDelimited(Stream stream, FileDescriptorProto instance)
 {
     var data = SerializeToBytes(instance);
     global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, (uint)data.Length);
     stream.Write(data, 0, data.Length);
 }
示例#37
0
        /// <summary>Serialize the instance into the stream</summary>
        public static void Serialize(Stream stream, FileDescriptorProto instance)
        {
            if (instance.Name != null)
            {
                // Key for field: 1, LengthDelimited
                stream.WriteByte(10);
                global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.Name));
            }
            if (instance.Package != null)
            {
                // Key for field: 2, LengthDelimited
                stream.WriteByte(18);
                global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.Package));
            }
            if (instance.Dependency != null)
            {
                foreach (var i3 in instance.Dependency)
                {
                    // Key for field: 3, LengthDelimited
                    stream.WriteByte(26);
                    global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(i3));
                }
            }
            if (instance.PublicDependency != null)
            {
                foreach (var i10 in instance.PublicDependency)
                {
                    // Key for field: 10, Varint
                    stream.WriteByte(80);
                    global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(stream,(ulong)i10);
                }
            }
            if (instance.WeakDependency != null)
            {
                foreach (var i11 in instance.WeakDependency)
                {
                    // Key for field: 11, Varint
                    stream.WriteByte(88);
                    global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(stream,(ulong)i11);
                }
            }
            if (instance.MessageType != null)
            {
                foreach (var i4 in instance.MessageType)
                {
                    // Key for field: 4, LengthDelimited
                    stream.WriteByte(34);
                    using (var ms4 = new MemoryStream())
                    {
                        Google.protobuf.DescriptorProto.Serialize(ms4, i4);
                        // Length delimited byte array
                        uint ms4Length = (uint)ms4.Length;
                        global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms4Length);
                        stream.Write(ms4.GetBuffer(), 0, (int)ms4Length);
                    }

                }
            }
            if (instance.EnumType != null)
            {
                foreach (var i5 in instance.EnumType)
                {
                    // Key for field: 5, LengthDelimited
                    stream.WriteByte(42);
                    using (var ms5 = new MemoryStream())
                    {
                        Google.protobuf.EnumDescriptorProto.Serialize(ms5, i5);
                        // Length delimited byte array
                        uint ms5Length = (uint)ms5.Length;
                        global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms5Length);
                        stream.Write(ms5.GetBuffer(), 0, (int)ms5Length);
                    }

                }
            }
            if (instance.Service != null)
            {
                foreach (var i6 in instance.Service)
                {
                    // Key for field: 6, LengthDelimited
                    stream.WriteByte(50);
                    using (var ms6 = new MemoryStream())
                    {
                        Google.protobuf.ServiceDescriptorProto.Serialize(ms6, i6);
                        // Length delimited byte array
                        uint ms6Length = (uint)ms6.Length;
                        global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms6Length);
                        stream.Write(ms6.GetBuffer(), 0, (int)ms6Length);
                    }

                }
            }
            if (instance.Extension != null)
            {
                foreach (var i7 in instance.Extension)
                {
                    // Key for field: 7, LengthDelimited
                    stream.WriteByte(58);
                    using (var ms7 = new MemoryStream())
                    {
                        Google.protobuf.FieldDescriptorProto.Serialize(ms7, i7);
                        // Length delimited byte array
                        uint ms7Length = (uint)ms7.Length;
                        global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms7Length);
                        stream.Write(ms7.GetBuffer(), 0, (int)ms7Length);
                    }

                }
            }
            if (instance.Options != null)
            {
                // Key for field: 8, LengthDelimited
                stream.WriteByte(66);
                using (var ms8 = new MemoryStream())
                {
                    Google.protobuf.FileOptions.Serialize(ms8, instance.Options);
                    // Length delimited byte array
                    uint ms8Length = (uint)ms8.Length;
                    global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms8Length);
                    stream.Write(ms8.GetBuffer(), 0, (int)ms8Length);
                }

            }
            if (instance.SourceCodeInfo != null)
            {
                // Key for field: 9, LengthDelimited
                stream.WriteByte(74);
                using (var ms9 = new MemoryStream())
                {
                    Google.protobuf.SourceCodeInfo.Serialize(ms9, instance.SourceCodeInfo);
                    // Length delimited byte array
                    uint ms9Length = (uint)ms9.Length;
                    global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms9Length);
                    stream.Write(ms9.GetBuffer(), 0, (int)ms9Length);
                }

            }
        }
示例#38
0
 /// <summary>Helper: create a new instance to deserializing into</summary>
 public static FileDescriptorProto DeserializeLengthDelimited(Stream stream)
 {
     FileDescriptorProto instance = new FileDescriptorProto();
     DeserializeLengthDelimited(stream, instance);
     return instance;
 }