示例#1
0
        /// <summary>
        /// Write an extension
        /// </summary>
        protected override void WriteExtension(GeneratorContext ctx, FieldDescriptorProto field)
        {
            string dataFormat;
            bool   isMap;
            var    type = GetTypeName(ctx, field, out dataFormat, out isMap);

            if (isMap)
            {
                ctx.WriteLine("#error map extensions not yet implemented");
            }
            else if (field.label == FieldDescriptorProto.Label.LabelRepeated)
            {
                ctx.WriteLine("#error repeated extensions not yet implemented");
            }
            else
            {
                var msg      = ctx.TryFind <DescriptorProto>(field.Extendee);
                var extendee = MakeRelativeName(field, msg, ctx.NameNormalizer);

                var    @this = field.Parent is FileDescriptorProto ? "this " : "";
                string name  = ctx.NameNormalizer.GetName(field);
                ctx.WriteLine($"{GetAccess(GetAccess(field))} static {type} Get{name}({@this}{extendee} obj)");

                TextWriter tw;
                if (ctx.Supports(CSharp6))
                {
                    tw = ctx.Indent().Write($"=> ");
                }
                else
                {
                    ctx.WriteLine("{").Indent();
                    tw = ctx.Write("return ");
                }
                tw.Write($"obj == null ? default({type}) : global::ProtoBuf.Extensible.GetValue<{type}>(obj, {field.Number}");
                if (!string.IsNullOrEmpty(dataFormat))
                {
                    tw.Write($", global::ProtoBuf.DataFormat.{dataFormat}");
                }
                tw.WriteLine(");");
                if (ctx.Supports(CSharp6))
                {
                    ctx.Outdent().WriteLine();
                }
                else
                {
                    ctx.Outdent().WriteLine("}").WriteLine();
                }

                //  GetValue<TValue>(IExtensible instance, int tag, DataFormat format)
            }
        }
示例#2
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");
        }
示例#3
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");
        }
        /// <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("End Namespace").WriteLine();
            }
            ctx.WriteLine($"#Enable Warning BC40008, IDE1006").WriteLine();
        }
示例#5
0
        /// <summary>
        /// End a file
        /// </summary>
        protected override void WriteFileFooter(GeneratorContext ctx, FileDescriptorProto file, ref object state)
        {
            var @namespace = (string)state;
            var prefix     = ctx.Supports(CSharp6) ? "CS" : "";

            if (!string.IsNullOrWhiteSpace(@namespace))
            {
                ctx.Outdent().WriteLine("}").WriteLine();
            }
            ctx.WriteLine($"#pragma warning restore {prefix}1591, {prefix}0612, {prefix}3021");
        }
示例#6
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("#pragma warning restore CS1591, CS0612, CS3021");
        }
        /// <summary>
        /// Emit code terminating a constructor, if one is required
        /// </summary>
        protected override void WriteConstructorFooter(GeneratorContext ctx, DescriptorProto message, ref object state)
        {
            if (ctx.Supports(CSharp3))
            {
                ctx.WriteLine("OnConstructor();");
            }
            ctx.Outdent().WriteLine("}").WriteLine();

            if (ctx.Supports(CSharp3))
            {
                ctx.WriteLine("partial void OnConstructor();")
                .WriteLine();
            }
        }
示例#8
0
        protected override void WriteReadFun(GeneratorContext ctx, DescriptorProto obj, OneOfStub[] oneOfs)
        {
            ctx.WriteLine($"public void MergeFrom(byte[] _bytes){"{"}").Indent();
            ctx.WriteLine("Google.Protobuf.CodedInputStream input = new Google.Protobuf.CodedInputStream(_bytes);");
            ctx.WriteLine("uint tag;");
            ctx.WriteLine("while ((tag = input.ReadTag()) != 0) {").Indent();
            ctx.WriteLine("switch(tag) {").Indent();
            ctx.WriteLine("default:").Indent();
            ctx.WriteLine("input.SkipLastField();");
            ctx.WriteLine("break;").Outdent();

            foreach (var inner in obj.Fields)
            {
                WriteFileRead(ctx, inner, oneOfs);
            }

            ctx.Outdent().WriteLine("}"); //switch

            ctx.Outdent().WriteLine("}"); //while

            ctx.WriteLine("input.Dispose();");

            ctx.Outdent().WriteLine("}");
        }
示例#9
0
 protected override void WriteWriteFun(GeneratorContext ctx, DescriptorProto obj, OneOfStub[] oneOfs)
 {
     ctx.WriteLine($"public byte[] GetBytes(){"{"}").Indent();
     ctx.WriteLine("System.IO.MemoryStream tmemsteam = new System.IO.MemoryStream();");
     ctx.WriteLine("Google.Protobuf.CodedOutputStream output = new Google.Protobuf.CodedOutputStream(tmemsteam,512,true);");
     foreach (var inner in obj.Fields)
     {
         WriteFieldWrite(ctx, inner, oneOfs);
     }
     ctx.WriteLine($"output.Flush();");
     ctx.WriteLine($"byte[] ret = tmemsteam.ToArray();");
     ctx.WriteLine($"output.Dispose();");
     ctx.WriteLine($"tmemsteam.Dispose();");
     ctx.WriteLine($"return ret;");
     ctx.Outdent();
     ctx.WriteLine($"{"}"}");
 }
        /// <summary>
        /// Write an extension
        /// </summary>
        protected override void WriteExtension(GeneratorContext ctx, FieldDescriptorProto field)
        {
            var type = GetTypeName(ctx, field, out string dataFormat, out bool isMap);

            if (isMap)
            {
                ctx.WriteLine("REM #error map extensions not yet implemented; please file an issue");
            }
            else if (field.label == FieldDescriptorProto.Label.LabelRepeated)
            {
                ctx.WriteLine("REM #error repeated extensions not yet implemented; please file an issue");
            }
            else
            {
                var msg      = ctx.TryFind <DescriptorProto>(field.Extendee);
                var extendee = MakeRelativeName(field, msg, ctx.NameNormalizer);

                string name   = ctx.NameNormalizer.GetName(field);
                string shared = "";
                if (field.Parent is FileDescriptorProto)
                {
                    ctx.WriteLine("<Global.System.Runtime.CompilerServices.Extension> _");
                }
                else
                {
                    shared = "Shared ";
                }
                ctx.WriteLine($"{GetAccess(GetAccess(field))} {shared}Function Get{name}(ByVal obj As {extendee}) As {type}");

                var tw = ctx.Indent().Write($"Return If(obj Is Nothing, CType(Nothing, {type}), Global.ProtoBuf.Extensible.GetValue(Of {type})(obj, {field.Number}");
                if (!string.IsNullOrEmpty(dataFormat))
                {
                    tw.Write($", Global.ProtoBuf.DataFormat.{dataFormat}");
                }
                tw.WriteLine("))");
                ctx.Outdent().WriteLine("End Function");
            }
        }
 /// <summary>
 /// Ends an extensions block
 /// </summary>
 protected override void WriteExtensionsFooter(GeneratorContext ctx, DescriptorProto message, ref object state)
 {
     ctx.Outdent().WriteLine("}");
 }
        /// <summary>
        /// End an enum
        /// </summary>

        protected override void WriteEnumFooter(GeneratorContext ctx, EnumDescriptorProto @enum, ref object state)
        {
            ctx.Outdent().WriteLine("}").WriteLine();
        }
示例#13
0
        protected void WriteFieldWrite(GeneratorContext ctx, FieldDescriptorProto obj, OneOfStub[] oneOfs)
        {
            bool isOptional = obj.label == FieldDescriptorProto.Label.LabelOptional;
            bool isRepeated = obj.label == FieldDescriptorProto.Label.LabelRepeated;

            Google.Protobuf.WireFormat.WireType ttwtype = ProtoTool.ILHelper.GetWireType(obj.type);
            uint   ttag   = Google.Protobuf.WireFormat.MakeTag(obj.Number, ttwtype);
            string tagstr = $"output.WriteTag({ttag});";

            var typeName = GetTypeName(ctx, obj, out var dataFormat, out var isMap);

            if (isOptional)
            {
                string tifvalue = "";
                if (obj.type == FieldDescriptorProto.Type.TypeString)
                {
                    tifvalue = $"if(!string.IsNullOrEmpty({obj.Name})){"{"}";
                }
                else
                {
                    tifvalue = $"if({obj.Name} != default({typeName})){"{"}";
                }
                ctx.WriteLine(tifvalue).Indent();
                //代码块
                ctx.WriteLine(tagstr);
                ctx.WriteLine(WriteString(obj.type, obj.Name));

                ctx.Outdent();
                ctx.WriteLine($"{"}"}");
            }
            else if (isRepeated)
            {
                var mapMsgType = isMap ? ctx.TryFind <DescriptorProto>(obj.TypeName) : null;
                if (mapMsgType != null)
                {
                    var keyTypeName = GetTypeName(ctx, mapMsgType.Fields.Single(x => x.Number == 1),
                                                  out var keyDataFormat, out var _);
                    var valueTypeName = GetTypeName(ctx, mapMsgType.Fields.Single(x => x.Number == 2),
                                                    out var valueDataFormat, out var _);
                    // System.Collections.Generic.Dictionary<int, int> ttt = new Dictionary<int, int>();
                    // System.Collections.Generic.KeyValuePair<int,int> ttt
                    ctx.WriteLine($"if({obj.Name}.Count > 0 ){"{"}").Indent();
                    ctx.WriteLine($"foreach (System.Collections.Generic.KeyValuePair<{keyTypeName}, {valueTypeName}> item in {obj.Name}){"{"}").Indent();

                    ctx.WriteLine(tagstr);
                    ctx.WriteLine(WriteString(mapMsgType.Fields[0].type, "item.Key"));
                    ctx.WriteLine(WriteString(mapMsgType.Fields[1].type, "item.Value"));

                    ctx.Outdent().WriteLine("}");
                    ctx.Outdent().WriteLine("}");
                }
                else
                {
                    ctx.WriteLine($"if({obj.Name}.Count > 0 ){"{"}").Indent();
                    ctx.WriteLine($"for (int i = 0; i < {obj.Name}.Count; i++){"{"}").Indent();

                    ctx.WriteLine(tagstr);
                    ctx.WriteLine(WriteString(obj.type, obj.Name + "[i]"));

                    ctx.Outdent().WriteLine("}");

                    ctx.Outdent().WriteLine("}");
                }
            }
            else
            {
                ctx.WriteLine(tagstr);
                ctx.WriteLine(WriteString(obj.type, obj.Name));
            }
        }
示例#14
0
 /// <summary>
 /// End a message
 /// </summary>
 protected override void WriteMessageFooter(GeneratorContext ctx, DescriptorProto obj, ref object state)
 {
     ctx.Outdent().WriteLine("}").WriteLine();
 }
        /// <summary>
        /// Write a field
        /// </summary>
        protected override void WriteField(GeneratorContext ctx, FieldDescriptorProto field, ref object state, OneOfStub[] oneOfs)
        {
            var name = ctx.NameNormalizer.GetName(field);

            var tw = ctx.Write($"<Global.ProtoBuf.ProtoMember({field.Number}");

            if (name != field.Name)
            {
                tw.Write($@", Name := ""{field.Name}""");
            }
            var options = field.Options?.GetOptions();

            if (options?.AsReference == true)
            {
                tw.Write(", AsReference := True");
            }
            if (options?.DynamicType == true)
            {
                tw.Write(", DynamicType := True");
            }

            bool isOptional = field.label == FieldDescriptorProto.Label.LabelOptional;
            bool isRepeated = field.label == FieldDescriptorProto.Label.LabelRepeated;

            OneOfStub oneOf = field.ShouldSerializeOneofIndex() ? oneOfs?[field.OneofIndex] : null;

            if (oneOf != null && !ctx.OneOfEnums && oneOf.CountTotal == 1)
            {
                oneOf = null; // not really a one-of, then!
            }
            bool explicitValues = isOptional && oneOf == null && ctx.Syntax == FileDescriptorProto.SyntaxProto2 &&
                                  field.type != FieldDescriptorProto.Type.TypeMessage &&
                                  field.type != FieldDescriptorProto.Type.TypeGroup;

            bool suppressDefaultAttribute = !isOptional;
            var  typeName = GetTypeName(ctx, field, out var dataFormat, out var isMap);

            string defaultValue = GetDefaultValue(ctx, field, typeName);

            if (!string.IsNullOrWhiteSpace(dataFormat))
            {
                tw.Write($", DataFormat := Global.ProtoBuf.DataFormat.{dataFormat}");
            }
            if (field.IsPacked(ctx.Syntax))
            {
                tw.Write($", IsPacked := True");
            }
            if (field.label == FieldDescriptorProto.Label.LabelRequired)
            {
                tw.Write($", IsRequired := True");
            }
            tw.WriteLine(")> _");
            if (!isRepeated && !string.IsNullOrWhiteSpace(defaultValue) && !suppressDefaultAttribute)
            {
                ctx.WriteLine($"<Global.System.ComponentModel.DefaultValue({defaultValue})> _");
            }
            WriteOptions(ctx, field.Options);
            if (isRepeated)
            {
                var mapMsgType = isMap ? ctx.TryFind <DescriptorProto>(field.TypeName) : null;
                if (mapMsgType != null)
                {
                    var keyTypeName = GetTypeName(ctx, mapMsgType.Fields.Single(x => x.Number == 1),
                                                  out var keyDataFormat, out var _);
                    var valueTypeName = GetTypeName(ctx, mapMsgType.Fields.Single(x => x.Number == 2),
                                                    out var valueDataFormat, out var _);

                    bool first = true;
                    tw = ctx.Write($"<Global.ProtoBuf.ProtoMap");
                    if (!string.IsNullOrWhiteSpace(keyDataFormat))
                    {
                        tw.Write($"{(first ? "(" : ", ")}KeyFormat := Global.ProtoBuf.DataFormat.{keyDataFormat}");
                        first = false;
                    }
                    if (!string.IsNullOrWhiteSpace(valueDataFormat))
                    {
                        tw.Write($"{(first ? "(" : ", ")}ValueFormat := Global.ProtoBuf.DataFormat.{valueDataFormat}");
                        first = false;
                    }
                    tw.WriteLine(first ? "> _" : ")> _");

                    if (ctx.Supports(VB14))
                    {
                        ctx.WriteLine($"{GetAccess(GetAccess(field))} Readonly Property {Escape(name)} As New Global.System.Collections.Generic.Dictionary(Of {keyTypeName}, {valueTypeName})");
                    }
                    else
                    {
                        var fieldName = FieldPrefix + name;
                        ctx.WriteLine($"{GetAccess(GetAccess(field))} Readonly Property {Escape(name)} As Global.System.Collections.Generic.Dictionary(Of {keyTypeName}, {valueTypeName})").Indent()
                        .WriteLine("Get").Indent()
                        .WriteLine($"Return {fieldName}")
                        .Outdent().WriteLine("End Get").Outdent().WriteLine("End Property").WriteLine()
                        .WriteLine($"Private ReadOnly {fieldName} As New Global.System.Collections.Generic.Dictionary(Of {keyTypeName}, {valueTypeName})").WriteLine();
                    }
                }
                else if (UseArray(field))
                {
                    if (ctx.Supports(VB11))
                    {
                        ctx.WriteLine($"{GetAccess(GetAccess(field))} Property {Escape(name)} As {typeName}()");
                    }
                    else
                    {
                        var fieldName = FieldPrefix + name;
                        ctx.WriteLine($"{GetAccess(GetAccess(field))} Property {Escape(name)} As {typeName}()")
                        .Indent().WriteLine("Get").Indent().WriteLine($"Return {fieldName}").Outdent().WriteLine("End Get").Outdent()
                        .Indent().WriteLine($"Set(ByVal value as {typeName}())").Indent().WriteLine($"{fieldName} = value").Outdent().WriteLine("End Set").Outdent()
                        .WriteLine("End Property").WriteLine()
                        .WriteLine($"Private {fieldName} As {typeName}()").WriteLine();
                    }
                }
                else
                {
                    if (ctx.Supports(VB14))
                    {
                        ctx.WriteLine($"{GetAccess(GetAccess(field))} Readonly Property {Escape(name)} As New Global.System.Collections.Generic.List(Of {typeName})");
                    }
                    else
                    {
                        var fieldName = FieldPrefix + name;
                        ctx.WriteLine($"{GetAccess(GetAccess(field))} Readonly Property {Escape(name)} As Global.System.Collections.Generic.List(Of {typeName})").Indent()
                        .WriteLine("Get").Indent()
                        .WriteLine($"Return {fieldName}")
                        .Outdent().WriteLine("End Get").Outdent().WriteLine("End Property").WriteLine()
                        .WriteLine($"Private ReadOnly {fieldName} As New Global.System.Collections.Generic.List(Of {typeName})").WriteLine();
                    }
                }
            }
            else if (oneOf != null)
            {
                var defValue  = string.IsNullOrWhiteSpace(defaultValue) ? $"CType(Nothing, {typeName})" : defaultValue;
                var fieldName = GetOneOfFieldName(oneOf.OneOf);
                var storage   = oneOf.GetStorage(field.type, field.TypeName);
                ctx.WriteLine($"{GetAccess(GetAccess(field))} Property {Escape(name)} As {typeName}").Indent().WriteLine("Get").Indent();
                switch (field.type)
                {
                case FieldDescriptorProto.Type.TypeMessage:
                case FieldDescriptorProto.Type.TypeGroup:
                case FieldDescriptorProto.Type.TypeEnum:
                case FieldDescriptorProto.Type.TypeBytes:
                case FieldDescriptorProto.Type.TypeString:
                    ctx.WriteLine($"Return If({fieldName}.Is({field.Number}), CType({fieldName}.{storage}, {typeName}), {defValue})");
                    break;

                default:
                    ctx.WriteLine($"Return If({fieldName}.Is({field.Number}), {fieldName}.{storage}, {defValue})");
                    break;
                }
                ctx.Outdent().WriteLine("End Get");

                var unionType = oneOf.GetUnionType();

                ctx.WriteLine($"Set(ByVal value As {typeName})").Indent()
                .WriteLine($"{fieldName} = New Global.ProtoBuf.{unionType}({field.Number}, value)").Outdent().WriteLine("End Set");

                ctx.Outdent().WriteLine("End Property").WriteLine();

                ctx.WriteLine($"{GetAccess(GetAccess(field))} Function ShouldSerialize{name}() As Boolean").Indent()
                .WriteLine($"Return {fieldName}.Is({field.Number})").Outdent()
                .WriteLine("End Function").WriteLine()
                .WriteLine($"{GetAccess(GetAccess(field))} Sub Reset{name}()").Indent()
                .WriteLine($"Global.ProtoBuf.{unionType}.Reset({fieldName}, {field.Number})")
                .Outdent().WriteLine("End Sub");

                if (oneOf.IsFirst())
                {
                    ctx.WriteLine().WriteLine($"Private {fieldName} As Global.ProtoBuf.{unionType}");
                }
            }
            else if (explicitValues)
            {
                string fieldName = FieldPrefix + name, fieldType;
                bool   isRef = false;
                switch (field.type)
                {
                case FieldDescriptorProto.Type.TypeString:
                case FieldDescriptorProto.Type.TypeBytes:
                    fieldType = typeName;
                    isRef     = true;
                    break;

                default:
                    fieldType = typeName + "?";
                    break;
                }

                ctx.WriteLine($"{GetAccess(GetAccess(field))} Property {Escape(name)} As {typeName}").Indent()
                .WriteLine("Get").Indent();

                if (!string.IsNullOrWhiteSpace(defaultValue))
                {
                    ctx.WriteLine($"Return If({fieldName}, {defaultValue})");
                }
                else if (!isRef)
                {
                    ctx.WriteLine($"Return {fieldName}.GetValueOrDefault()");
                }
                else
                {
                    ctx.WriteLine($"Return {fieldName}");
                }

                ctx.Outdent().WriteLine("End Get").WriteLine($"Set(ByVal value As {typeName})").Indent()
                .WriteLine($"{fieldName} = value").Outdent().WriteLine("End Set").
                Outdent().WriteLine("End Property");

                ctx.WriteLine($"{GetAccess(GetAccess(field))} Function ShouldSerialize{name}() As Boolean").Indent()
                .WriteLine($"Return Not ({fieldName} Is Nothing)").Outdent()
                .WriteLine("End Function")
                .WriteLine($"{GetAccess(GetAccess(field))} Sub Reset{name}()").Indent()
                .WriteLine($"{fieldName} = Nothing").Outdent().WriteLine("End Sub");

                ctx.WriteLine($"Private {fieldName} As {fieldType}");
            }
            else
            {
                if (ctx.Supports(VB11))
                {
                    tw = ctx.Write($"{GetAccess(GetAccess(field))} Property {Escape(name)} As {typeName}");
                    if (!string.IsNullOrWhiteSpace(defaultValue))
                    {
                        tw.Write($" = {defaultValue}");
                    }
                    tw.WriteLine();
                }
                else
                {
                    var fieldName = FieldPrefix + name;
                    tw = ctx.WriteLine($"{GetAccess(GetAccess(field))} Property {Escape(name)} As {typeName}")
                         .Indent().WriteLine("Get").Indent().WriteLine($"Return {fieldName}").Outdent().WriteLine("End Get").Outdent()
                         .Indent().WriteLine($"Set(ByVal value as {typeName})").Indent().WriteLine($"{fieldName} = value").Outdent().WriteLine("End Set").Outdent()
                         .WriteLine("End Property").WriteLine()
                         .Write($"Private {fieldName} As {typeName}");
                    if (!string.IsNullOrWhiteSpace(defaultValue))
                    {
                        tw.Write($" = {defaultValue}");
                    }
                    tw.WriteLine();
                }
            }
            ctx.WriteLine();
        }
示例#16
0
 /// <inheritdoc/>
 protected override void WriteNamespaceFooter(GeneratorContext ctx, string @namespace)
 {
     ctx.Outdent().WriteLine("}").WriteLine();
 }
 /// <summary>
 /// Emit code following a set of service methods
 /// </summary>
 protected override void WriteServiceFooter(GeneratorContext ctx, ServiceDescriptorProto service, ref object state)
 {
     ctx.Outdent().WriteLine("}").WriteLine();
 }
 /// <summary>
 /// Ends an extgensions block
 /// </summary>
 protected override void WriteExtensionsFooter(GeneratorContext ctx, FileDescriptorProto file, ref object state)
 {
     ctx.Outdent().WriteLine("End Module");
 }
        /// <summary>
        /// Write an extension
        /// </summary>
        protected override void WriteExtension(GeneratorContext ctx, FieldDescriptorProto field)
        {
            var type            = GetTypeName(ctx, field, out string dataFormat, out bool isMap, false);
            var nonNullableType = GetTypeName(ctx, field, out _, out _, true);
            var msg             = ctx.TryFind <DescriptorProto>(field.Extendee);
            var extendee        = MakeRelativeName(field, msg, ctx.NameNormalizer);

            var        @this = field.Parent is FileDescriptorProto ? "this " : "";
            string     name  = ctx.NameNormalizer.GetName(field);
            TextWriter tw;

            if (isMap)
            {
                ctx.WriteLine("#error map extensions not yet implemented; please file an issue");
            }
            else
            {
                bool isRepeated = field.label == FieldDescriptorProto.Label.LabelRepeated;

                var getMethodName = isRepeated ? nameof(Extensible.GetValues) : nameof(Extensible.GetValue);
                if (isRepeated)
                {
                    ctx.WriteLine($"{GetAccess(GetAccess(field))} static global::System.Collections.Generic.IEnumerable<{nonNullableType}> Get{name}({@this}{extendee} obj)");
                }
                else
                {
                    ctx.WriteLine($"{GetAccess(GetAccess(field))} static {type} Get{name}({@this}{extendee} obj)");
                }
                if (ctx.Supports(CSharp6))
                {
                    tw = ctx.Indent().Write($"=> ");
                }
                else
                {
                    ctx.WriteLine("{").Indent();
                    tw = ctx.Write("return ");
                }
                var defaultValue = isRepeated ? "null" : ctx.Supports(CSharp7_1) ? "default" : $"default({type})";
                tw.Write($"obj == null ? {defaultValue} : global::ProtoBuf.Extensible.{getMethodName}<{(isRepeated ? nonNullableType : type)}>(obj, {field.Number}");
                if (!string.IsNullOrEmpty(dataFormat))
                {
                    tw.Write($", global::ProtoBuf.DataFormat.{dataFormat}");
                }
                tw.WriteLine(");");
                if (ctx.Supports(CSharp6))
                {
                    ctx.Outdent().WriteLine();
                }
                else
                {
                    ctx.Outdent().WriteLine("}").WriteLine();
                }

                var setAccessorName = isRepeated ? "Add" : "Set";
                ctx.WriteLine($"{GetAccess(GetAccess(field))} static void {setAccessorName}{name}({@this}{extendee} obj, {nonNullableType} value)");
                if (ctx.Supports(CSharp6))
                {
                    tw = ctx.Indent().Write($"=> ");
                }
                else
                {
                    ctx.WriteLine("{").Indent();
                    tw = ctx.Write("");
                }
                tw.Write($"global::ProtoBuf.Extensible.AppendValue<{nonNullableType}>(obj, {field.Number}");
                if (!string.IsNullOrEmpty(dataFormat))
                {
                    tw.Write($", global::ProtoBuf.DataFormat.{dataFormat}");
                }
                tw.WriteLine(", value);");
                if (ctx.Supports(CSharp6))
                {
                    ctx.Outdent().WriteLine();
                }
                else
                {
                    ctx.Outdent().WriteLine("}").WriteLine();
                }
            }
        }
 /// <summary>
 /// Emit the end of an enum declaration for 'oneof' groups
 /// </summary>
 protected override void WriteOneOfEnumFooter(GeneratorContext ctx, OneofDescriptorProto oneof, ref object state)
 {
     ctx.Outdent().WriteLine("}").WriteLine();
 }
示例#21
0
        protected void ReaderString(GeneratorContext ctx, FieldDescriptorProto obj)
        {
            bool isRepeated = obj.label == FieldDescriptorProto.Label.LabelRepeated;
            var  typeName   = GetTypeName(ctx, obj, out var dataFormat, out var isMap);

            string tfirstvalue = obj.Name;

            if (isRepeated)
            {
                tfirstvalue = $"{typeName} tvalue";
                ctx.WriteLine("{").Indent();
            }

            ReadBaseDataStr(ctx, obj.type, tfirstvalue, typeName);

            if (isRepeated)
            {
                var mapMsgType = isMap ? ctx.TryFind <DescriptorProto>(obj.TypeName) : null;
                if (mapMsgType != null)
                {
                    var keyTypeName = GetTypeName(ctx, mapMsgType.Fields.Single(x => x.Number == 1),
                                                  out var keyDataFormat, out var _);
                    var valueTypeName = GetTypeName(ctx, mapMsgType.Fields.Single(x => x.Number == 2),
                                                    out var valueDataFormat, out var _);

                    string tkey = "tkey";
                    if (FieldDescriptorProto.Type.TypeMessage == mapMsgType.Fields[0].type)
                    {
                        ReadCreatObjectStr(ctx, keyTypeName, tkey);
                    }
                    else
                    {
                        ReadBaseDataStr(ctx, mapMsgType.Fields[0].type, $"{keyTypeName} {tkey}", keyTypeName);
                    }

                    string tvalue = "tvalue";
                    if (FieldDescriptorProto.Type.TypeMessage == mapMsgType.Fields[1].type)
                    {
                        ReadCreatObjectStr(ctx, valueTypeName, tvalue);
                    }
                    else
                    {
                        ReadBaseDataStr(ctx, mapMsgType.Fields[1].type, $"{valueTypeName} {tvalue}", valueTypeName);
                    }

                    ctx.WriteLine($"{obj.Name}.Add({tkey}, {tvalue});");
                }
                else
                {
                    if (FieldDescriptorProto.Type.TypeMessage == obj.type)
                    {
                        ReadCreatObjectStr(ctx, typeName, "tobj");
                        ctx.WriteLine($"{obj.Name}.Add(tobj);");
                    }
                    else
                    {
                        ctx.WriteLine($"{obj.Name}.Add(tvalue);");
                    }
                }
                ctx.Outdent().WriteLine("}");
            }
            else
            {
                switch (obj.type)
                {
                case FieldDescriptorProto.Type.TypeMessage:
                    ctx.WriteLine("{").Indent();
                    ctx.WriteLine($"byte[] tchildbuffer = input.ReadBytes().ToByteArray();");
                    ctx.WriteLine($"{tfirstvalue}.MergeFrom(tchildbuffer);");
                    ctx.Outdent().WriteLine("}");
                    break;
                }
            }
        }