public override void Emit() { Module.Append($@" RT_ENUM! {{ enum { DefinitionName }: { UnderlyingTypeName } {{ { String.Join(", ", Type.Fields.Where(f => f.Name != "value__").Select(f => $"{ NameHelpers.PreventKeywords(f.Name) } ({ Type.Name }_{ f.Name }) = { f.Constant }")) }, }}}}"); }
public IEnumerable <Opinion> FindOpinionsByExpert(string expert) { var connection = GetConnection(); connection.Open(); string sql = String.Format("select * from opinion where expert like '%{0}%' order by date desc", expert); SQLiteCommand command = new SQLiteCommand(sql, connection); SQLiteDataReader reader = command.ExecuteReader(); //date, signal, company, expert, opinion, price, symbol var opinions = new List <Opinion>(); while (reader.Read()) { var dateTime = new DateTime().AddTicks((long)reader["date"]); var o = new Opinion(dateTime, reader["signal"].ToString(), reader["company"].ToString(), reader["expert"].ToString(), reader["opinion"].ToString(), decimal.Parse(reader["price"].ToString()), reader["symbol"].ToString() ); opinions.Add(o); } connection.Close(); return(NameHelpers.RemoveWeakNameMatches(opinions, expert)); }
internal Track CreateAthameTrack(TidalServiceSettings settings) { // Always put main artists in the artist field var t = new Track { DiscNumber = VolumeNumber, TrackNumber = TrackNumber, Title = NameHelpers.CreateTrackTitle(settings, this), Id = Id.ToString(), IsDownloadable = AllowStreaming, // Only use first artist name and picture for now Artist = NameHelpers.CreateMainArtist(Artists, Artist), CustomMetadata = new[] { MetadataHelpers.ExplicitMetadata(Explicit), MetadataHelpers.MasterMetadata(AudioQuality) } }; // If the featured artists aren't already in the title, append them there if (!EnglishArtistNameJoiner.DoesTitleContainArtistString(this)) { var nonMainArtists = (from artist in Artists where artist.Type != ArtistRole.Main select artist.Name).ToArray(); if (nonMainArtists.Length > 0) { t.Title += " " + EnglishArtistNameJoiner.JoinFeaturingArtists(nonMainArtists); } } t.Album = Album.CreateAthameAlbum(settings); return(t); }
public virtual void Generate(TextGenerator writer) { CSharpServiceOptions options = Descriptor.Options.GetExtension(CSharpOptions.CsharpServiceOptions); if (options != null && options.HasInterfaceId) { writer.WriteLine("[global::System.Runtime.InteropServices.GuidAttribute(\"{0}\")]", new Guid(options.InterfaceId)); } WriteGeneratedCodeAttributes(writer); writer.WriteLine("{0} partial interface I{1} {{", ClassAccessLevel, Descriptor.Name); writer.Indent(); foreach (MethodDescriptor method in Descriptor.Methods) { CSharpMethodOptions mth = method.Options.GetExtension(CSharpOptions.CsharpMethodOptions); if (mth.HasDispatchId) { writer.WriteLine("[global::System.Runtime.InteropServices.DispId({0})]", mth.DispatchId); } writer.WriteLine("{0} {1}({2} {3});", GetClassName(method.OutputType), NameHelpers.UnderscoresToPascalCase(method.Name), GetClassName(method.InputType), NameHelpers.UnderscoresToCamelCase(method.InputType.Name)); } writer.Outdent(); writer.WriteLine("}"); }
private CSharpFieldOptions BuildOrFakeCSharpOptions() { // TODO(jonskeet): Check if we could use FileDescriptorProto.Descriptor.Name - interesting bootstrap issues if (File.Proto.Name == "google/protobuf/csharp_options.proto") { if (Name == "csharp_field_options") { return(new CSharpFieldOptions.Builder { PropertyName = "CSharpFieldOptions" }.Build()); } if (Name == "csharp_file_options") { return(new CSharpFieldOptions.Builder { PropertyName = "CSharpFileOptions" }.Build()); } } CSharpFieldOptions.Builder builder = CSharpFieldOptions.CreateBuilder(); if (Proto.Options.HasExtension(DescriptorProtos.CSharpOptions.CSharpFieldOptions)) { builder.MergeFrom(Proto.Options.GetExtension(DescriptorProtos.CSharpOptions.CSharpFieldOptions)); } if (!builder.HasPropertyName) { string fieldName = FieldType == FieldType.Group ? MessageType.Name : Name; string propertyName = NameHelpers.UnderscoresToPascalCase(fieldName); if (propertyName == ContainingType.Name) { propertyName += "_"; } builder.PropertyName = propertyName; } return(builder.Build()); }
public void Generate(TextGenerator writer) { //writer.WriteLine("[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]"); WriteGeneratedCodeAttributes(writer); writer.WriteLine("{0} abstract class {1} : pb::IService {{", ClassAccessLevel, Descriptor.Name); writer.Indent(); foreach (MethodDescriptor method in Descriptor.Methods) { writer.WriteLine("{0} abstract void {1}(", ClassAccessLevel, NameHelpers.UnderscoresToPascalCase(method.Name)); writer.WriteLine(" pb::IRpcController controller,"); writer.WriteLine(" {0} request,", GetClassName(method.InputType)); writer.WriteLine(" global::System.Action<{0}> done);", GetClassName(method.OutputType)); } // Generate Descriptor and DescriptorForType. writer.WriteLine(); writer.WriteLine("{0} static pbd::ServiceDescriptor Descriptor {{", ClassAccessLevel); writer.WriteLine(" get {{ return {0}.Descriptor.Services[{1}]; }}", DescriptorUtil.GetQualifiedUmbrellaClassName(Descriptor.File.CSharpOptions), Descriptor.Index); writer.WriteLine("}"); writer.WriteLine("public pbd::ServiceDescriptor DescriptorForType {"); writer.WriteLine(" get { return Descriptor; }"); writer.WriteLine("}"); GenerateCallMethod(writer); GenerateGetPrototype(RequestOrResponse.Request, writer); GenerateGetPrototype(RequestOrResponse.Response, writer); GenerateStub(writer); writer.Outdent(); writer.WriteLine("}"); }
internal Album CreateAthameAlbum(TidalServiceSettings settings) { var cmAlbum = new Album { Id = Id.ToString(), Title = Title, CoverPicture = new TidalPicture(Cover), Type = (AlbumType)TidalAlbumType, CustomMetadata = new[] { MetadataHelpers.ExplicitMetadata(Explicit), MetadataHelpers.MasterMetadata(AudioQuality) } }; // On most calls the Album returned is a "lite" version, with only the properties above // available. if (Artist != null) { // Need only main artists cmAlbum.Artist = NameHelpers.CreateMainArtist(Artists, Artist); } if (TidalTracks != null) { cmAlbum.Tracks = (from track in TidalTracks select track.CreateAthameTrack(settings)).ToList(); } return(cmAlbum); }
private void GenerateCallMethod(TextGenerator writer) { writer.WriteLine(); writer.WriteLine("public void CallMethod("); writer.WriteLine(" pbd::MethodDescriptor method,"); writer.WriteLine(" pb::IRpcController controller,"); writer.WriteLine(" pb::IMessage request,"); writer.WriteLine(" global::System.Action<pb::IMessage> done) {"); writer.Indent(); writer.WriteLine("if (method.Service != Descriptor) {"); writer.WriteLine(" throw new global::System.ArgumentException("); writer.WriteLine(" \"Service.CallMethod() given method descriptor for wrong service type.\");"); writer.WriteLine("}"); writer.WriteLine("switch(method.Index) {"); writer.Indent(); foreach (MethodDescriptor method in Descriptor.Methods) { writer.WriteLine("case {0}:", method.Index); writer.WriteLine(" this.{0}(controller, ({1}) request,", NameHelpers.UnderscoresToPascalCase(method.Name), GetClassName(method.InputType)); writer.WriteLine(" pb::RpcUtil.SpecializeCallback<{0}>(", GetClassName(method.OutputType)); writer.WriteLine(" done));"); writer.WriteLine(" return;"); } writer.WriteLine("default:"); writer.WriteLine(" throw new global::System.InvalidOperationException(\"Can't get here.\");"); writer.Outdent(); writer.WriteLine("}"); writer.Outdent(); writer.WriteLine("}"); writer.WriteLine(); }
private void GenerateIsInitialized(TextGenerator writer) { writer.WriteLine("#if UNITY_EDITOR\n [pb.FieldNumber] \n #endif//"); writer.WriteLine("public override bool IsInitialized {"); writer.Indent(); writer.WriteLine("get {"); writer.Indent(); // Check that all required fields in this message are set. // TODO(kenton): We can optimize this when we switch to putting all the // "has" fields into a single bitfield. foreach (FieldDescriptor field in Descriptor.Fields) { if (field.IsRequired) { writer.WriteLine("if (!has{0}) return false;", field.CSharpOptions.PropertyName); } } // Now check that all embedded messages are initialized. foreach (FieldDescriptor field in Descriptor.Fields) { if (field.FieldType != FieldType.Message || !HasRequiredFields(field.MessageType, new Dictionary <MessageDescriptor, object>())) { continue; } string propertyName = NameHelpers.UnderscoresToPascalCase(GetFieldName(field)); if (field.IsRepeated) { writer.WriteLine("foreach ({0} element in {1}List) {{", GetClassName(field.MessageType), propertyName); writer.WriteLine(" if (!element.IsInitialized) return false;"); writer.WriteLine("}"); } else if (field.IsOptional) { writer.WriteLine("if (Has{0}) {{", propertyName); writer.WriteLine(" if (!{0}.IsInitialized) return false;", propertyName); writer.WriteLine("}"); } else { writer.WriteLine("if (!{0}.IsInitialized) return false;", propertyName); } } if (Descriptor.Proto.ExtensionRangeCount > 0) { writer.WriteLine("if (!ExtensionsAreInitialized) return false;"); } writer.WriteLine("return true;"); writer.Outdent(); writer.WriteLine("}"); writer.Outdent(); writer.WriteLine("}"); writer.WriteLine(); }
public Opinion(DateTime date, string signal, string company, string expert, string opinionString, decimal price, string symbol) { Date = date; Signal = signal; Company = company; Expert = NameHelpers.Normalize(expert); OpinionString = opinionString; Price = price; Symbol = symbol; }
public string GetWrapperName(string rawName) { string name = NameHelpers.PreventKeywords(NameHelpers.CamelToSnakeCase(rawName.StartsWith("put_") ? "set_" + rawName.Substring(4) : rawName)); if (rawName.Contains("_")) // name already contains '_' -> might result in a name clash after renaming, e.g. caused by original names `get_Name` (property getter) and `GetName` (method) { if (DeclaringType.Methods.Select(mm => Tuple.Create(mm, mm.GetRawName())).Where(mm => !mm.Item2.Contains("_")).Any(mm => mm.Item1.GetWrapperName(mm.Item2) == name)) { name += "_"; } } return(name); }
private CSharpFileOptions BuildOrFakeCSharpOptions() { // TODO(jonskeet): Check if we could use FileDescriptorProto.Descriptor.Name - interesting bootstrap issues if (proto.Name == "google/protobuf/descriptor.proto") { return(new CSharpFileOptions.Builder { Namespace = "Google.ProtocolBuffers.DescriptorProtos", UmbrellaClassname = "DescriptorProtoFile", NestClasses = false, MultipleFiles = false, PublicClasses = true }.Build()); } if (proto.Name == "google/protobuf/csharp_options.proto") { return(new CSharpFileOptions.Builder { Namespace = "Google.ProtocolBuffers.DescriptorProtos", UmbrellaClassname = "CSharpOptions", NestClasses = false, MultipleFiles = false, PublicClasses = true }.Build()); } CSharpFileOptions.Builder builder = CSharpFileOptions.CreateBuilder(); if (proto.Options.HasExtension(DescriptorProtos.CSharpOptions.CSharpFileOptions)) { builder.MergeFrom(proto.Options.GetExtension(DescriptorProtos.CSharpOptions.CSharpFileOptions)); } if (!builder.HasNamespace) { builder.Namespace = Package; } if (!builder.HasMultipleFiles) { builder.MultipleFiles = false; } if (!builder.HasNestClasses) { builder.NestClasses = false; } if (!builder.HasPublicClasses) { builder.PublicClasses = true; } if (!builder.HasUmbrellaClassname) { int lastSlash = Name.LastIndexOf('/'); string baseName = Name.Substring(lastSlash + 1); builder.UmbrellaClassname = NameHelpers.UnderscoresToPascalCase(NameHelpers.StripProto(baseName)); } return(builder.Build()); }
public string this[string name] { get { if (name == "Name") { if (string.IsNullOrEmpty(Name.Trim())) { return("The name is empty."); } // Validate the invalid characters try { string toValidate = _package.Name; if (Path.IsPathRooted(_package.Name)) { // Skip the root toValidate = toValidate.Substring(Path.GetPathRoot(_package.Name).Length); } if (toValidate.IndexOfAny(Path.GetInvalidFileNameChars().Where(c => c != '\\').ToArray <char>()) != -1) { return("The name contains invalid characters."); } } catch (Exception e) { return(e.Message); } // Check for name duplicates if (NameHelpers.IsDuplicated( _package.Name, ProjectViewModel.Current.ManualPackagingInfo.Packages.Select(p => p.Name), StringComparison.OrdinalIgnoreCase)) { return("Package name is duplicated."); } } return(null); } }
private void GenerateStub(TextGenerator writer) { writer.WriteLine("public static Stub CreateStub(pb::IRpcChannel channel) {"); writer.WriteLine(" return new Stub(channel);"); writer.WriteLine("}"); writer.WriteLine(); writer.WriteLine("[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]"); writer.WriteLine("[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]"); writer.WriteLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"{0}\", \"{1}\")]", GetType().Assembly.GetName().Name, GetType().Assembly.GetName().Version); writer.WriteLine("{0} class Stub : {1} {{", ClassAccessLevel, GetClassName(Descriptor)); writer.Indent(); writer.WriteLine("internal Stub(pb::IRpcChannel channel) {"); writer.WriteLine(" this.channel = channel;"); writer.WriteLine("}"); writer.WriteLine(); writer.WriteLine("private readonly pb::IRpcChannel channel;"); writer.WriteLine(); writer.WriteLine("public pb::IRpcChannel Channel {"); writer.WriteLine(" get { return channel; }"); writer.WriteLine("}"); foreach (MethodDescriptor method in Descriptor.Methods) { writer.WriteLine(); writer.WriteLine("{0} override void {1}(", ClassAccessLevel, NameHelpers.UnderscoresToPascalCase(method.Name)); writer.WriteLine(" pb::IRpcController controller,"); writer.WriteLine(" {0} request,", GetClassName(method.InputType)); writer.WriteLine(" global::System.Action<{0}> done) {{", GetClassName(method.OutputType)); writer.Indent(); writer.WriteLine("channel.CallMethod(Descriptor.Methods[{0}],", method.Index); writer.WriteLine(" controller, request, {0}.DefaultInstance,", GetClassName(method.OutputType)); writer.WriteLine(" pb::RpcUtil.GeneralizeCallback<{0}, {0}.Builder>(done, {0}.DefaultInstance));", GetClassName(method.OutputType)); writer.Outdent(); writer.WriteLine("}"); } writer.Outdent(); writer.WriteLine("}"); }
private void AddPackage() { // Find a unique name string name = NameHelpers.FindUniqueName( Packages.Select(p => p.Name), Properties.Resources.NewPackageName, StringComparison.OrdinalIgnoreCase); Package package = new Package() { Name = name }; _manualPackagingInfo.Packages.Add(package); // Trigger the rename, but let the UI item to be loaded and data-bound Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Loaded, (Action) delegate { _packagesPerId[package.Id].Rename(); }); }
public IEnumerable <string> GetParameterDeclarations() { yield return("&self"); foreach (var p in Method.Parameters) { Assert(!p.IsReturnValue); int?lengthIs = null; var lengthIsAttribute = p.CustomAttributes.SingleOrDefault(a => a.AttributeType.Name == "LengthIsAttribute"); if (lengthIsAttribute != null) { lengthIs = (int)lengthIsAttribute.ConstructorArguments[0].Value; } if (p.ParameterType.IsArray) { // need additional input size parameter (even if parameter is marked as [Out]) yield return(NameHelpers.FirstToLower(p.Name) + "Size: u32"); } else if (p.ParameterType.IsByReference && (p.ParameterType as ByReferenceType).ElementType.IsArray) { Assert(!lengthIs.HasValue); // need additional output size parameter yield return(NameHelpers.FirstToLower(p.Name) + "Size: *mut u32"); } yield return(NameHelpers.PreventKeywords(NameHelpers.FirstToLower(p.Name)) + ": " + TypeHelpers.GetTypeName(DeclaringType.Generator, this, p.ParameterType, TypeUsage.Raw)); } if (Method.ReturnType.FullName != "System.Void") { if (Method.ReturnType.IsArray) { yield return("outSize: *mut u32"); } yield return("out: *mut " + TypeHelpers.GetTypeName(DeclaringType.Generator, this, Method.ReturnType, TypeUsage.Raw)); } }
private void GenerateStub(TextGenerator writer) { writer.WriteLine("public static Stub CreateStub(pb::IRpcChannel channel) {"); writer.WriteLine(" return new Stub(channel);"); writer.WriteLine("}"); writer.WriteLine(); writer.WriteLine("{0} class Stub : {1} {{", ClassAccessLevel, GetClassName(Descriptor)); writer.Indent(); writer.WriteLine("internal Stub(pb::IRpcChannel channel) {"); writer.WriteLine(" this.channel = channel;"); writer.WriteLine("}"); writer.WriteLine(); writer.WriteLine("private readonly pb::IRpcChannel channel;"); writer.WriteLine(); writer.WriteLine("public pb::IRpcChannel Channel {"); writer.WriteLine(" get { return channel; }"); writer.WriteLine("}"); foreach (MethodDescriptor method in Descriptor.Methods) { writer.WriteLine(); writer.WriteLine("public override void {0}(", NameHelpers.UnderscoresToPascalCase(method.Name)); writer.WriteLine(" pb::IRpcController controller,"); writer.WriteLine(" {0} request,", GetClassName(method.InputType)); writer.WriteLine(" global::System.Action<{0}> done) {{", GetClassName(method.OutputType)); writer.Indent(); writer.WriteLine("channel.CallMethod(Descriptor.Methods[{0}],", method.Index); writer.WriteLine(" controller, request, {0}.DefaultInstance,", GetClassName(method.OutputType)); writer.WriteLine(" pb::RpcUtil.GeneralizeCallback<{0}, {0}.Builder>(done, {0}.DefaultInstance));", GetClassName(method.OutputType)); writer.Outdent(); writer.WriteLine("}"); } writer.Outdent(); writer.WriteLine("}"); }
public override void Emit() { var classType = DefinitionName; bool needClassID = false; if (Type.Interfaces.Count > 0) { var dependsOnAssemblies = new List <string>(ForeignAssemblyDependencies.GroupBy(t => t.Module.Assembly.Name.Name).Select(g => g.Key)); var features = new FeatureConditions(dependsOnAssemblies); Module.Append($@" { features.GetAttribute() }RT_CLASS!{{class { DefinitionName }: { aliasedType }}}"); if (!features.IsEmpty) { // if the aliased type is from a different assembly that is not included, just use IInspectable instead // otherwise types depending on this class would transitively depend on the aliased type Module.Append($@" { features.GetInvertedAttribute() }RT_CLASS!{{class { DefinitionName }: IInspectable}}"); } foreach (var factory in factories.OrderBy(f => f)) { needClassID = true; Module.Append($@" impl RtActivatable<{ factory }> for { classType } {{}}"); } } else { Assert(!factories.Any()); Module.Append($@" RT_CLASS!{{static class { DefinitionName }}}"); } foreach (var staticType in statics.OrderBy(t => t.FullName)) { var staticName = Generator.GetTypeDefinition(staticType).DefinitionName; needClassID = true; Module.Append($@" impl RtActivatable<{ staticName }> for { classType } {{}}"); } if (IsDefaultActivatable()) { needClassID = true; Module.Append($@" impl RtActivatable<IActivationFactory> for { classType } {{}}"); } if (methodWrappers.Any()) { Module.Append($@" impl { DefinitionName } {{ { String.Join("\r\n ", methodWrappers.Select(m => m.Emit())) } }}"); } if (needClassID) { Module.Append($@" DEFINE_CLSID!({ classType }(&[{ NameHelpers.StringToUTF16WithZero(Type.FullName) }]) [CLSID_{ classType }]);"); } }
public override void Generate(TextGenerator writer) { base.Generate(writer); writer.WriteLine(); // CLIENT Proxy { if (Descriptor.File.CSharpOptions.ClsCompliance) { writer.WriteLine("[global::System.CLSCompliant(false)]"); } writer.WriteLine("[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]"); WriteGeneratedCodeAttributes(writer); writer.WriteLine("{0} partial class {1} : I{1}, pb::IRpcDispatch, global::System.IDisposable {{", ClassAccessLevel, Descriptor.Name); writer.Indent(); writer.WriteLine("private readonly bool dispose;"); writer.WriteLine("private readonly pb::IRpcDispatch dispatch;"); writer.WriteLine("public {0}(pb::IRpcDispatch dispatch) : this(dispatch, true) {{", Descriptor.Name); writer.WriteLine("}"); writer.WriteLine("public {0}(pb::IRpcDispatch dispatch, bool dispose) {{", Descriptor.Name); writer.WriteLine(" pb::ThrowHelper.ThrowIfNull(this.dispatch = dispatch, \"dispatch\");"); writer.WriteLine(" this.dispose = dispose && dispatch is global::System.IDisposable;"); writer.WriteLine("}"); writer.WriteLine(); writer.WriteLine("public void Dispose() {"); writer.WriteLine(" if (dispose) ((global::System.IDisposable)dispatch).Dispose();"); writer.WriteLine("}"); writer.WriteLine(); writer.WriteLine( "TMessage pb::IRpcDispatch.CallMethod<TMessage, TBuilder>(string method, pb::IMessageLite request, pb::IBuilderLite<TMessage, TBuilder> response) {"); writer.WriteLine(" return dispatch.CallMethod(method, request, response);"); writer.WriteLine("}"); writer.WriteLine(); foreach (MethodDescriptor method in Descriptor.Methods) { writer.WriteLine("public {0} {1}({2} {3}) {{", GetClassName(method.OutputType), NameHelpers.UnderscoresToPascalCase(method.Name), GetClassName(method.InputType), NameHelpers.UnderscoresToCamelCase(method.InputType.Name)); writer.WriteLine(" return dispatch.CallMethod(\"{0}\", {1}, {2}.CreateBuilder());", method.Name, NameHelpers.UnderscoresToCamelCase(method.InputType.Name), GetClassName(method.OutputType) ); writer.WriteLine("}"); writer.WriteLine(); } } // SERVER - DISPATCH { if (Descriptor.File.CSharpOptions.ClsCompliance) { writer.WriteLine("[global::System.CLSCompliant(false)]"); } writer.WriteLine("[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]"); WriteGeneratedCodeAttributes(writer); writer.WriteLine("public partial class Dispatch : pb::IRpcDispatch, global::System.IDisposable {"); writer.Indent(); writer.WriteLine("private readonly bool dispose;"); writer.WriteLine("private readonly I{0} implementation;", Descriptor.Name); writer.WriteLine("public Dispatch(I{0} implementation) : this(implementation, true) {{", Descriptor.Name); writer.WriteLine("}"); writer.WriteLine("public Dispatch(I{0} implementation, bool dispose) {{", Descriptor.Name); writer.WriteLine(" pb::ThrowHelper.ThrowIfNull(this.implementation = implementation, \"implementation\");"); writer.WriteLine(" this.dispose = dispose && implementation is global::System.IDisposable;"); writer.WriteLine("}"); writer.WriteLine(); writer.WriteLine("public void Dispose() {"); writer.WriteLine(" if (dispose) ((global::System.IDisposable)implementation).Dispose();"); writer.WriteLine("}"); writer.WriteLine(); writer.WriteLine( "public TMessage CallMethod<TMessage, TBuilder>(string methodName, pb::IMessageLite request, pb::IBuilderLite<TMessage, TBuilder> response)"); writer.WriteLine(" where TMessage : pb::IMessageLite<TMessage, TBuilder>"); writer.WriteLine(" where TBuilder : pb::IBuilderLite<TMessage, TBuilder> {"); writer.Indent(); writer.WriteLine("switch(methodName) {"); writer.Indent(); foreach (MethodDescriptor method in Descriptor.Methods) { writer.WriteLine( "case \"{0}\": return response.MergeFrom(implementation.{1}(({2})request)).Build();", method.Name, NameHelpers.UnderscoresToPascalCase(method.Name), GetClassName(method.InputType)); } writer.WriteLine("default: throw pb::ThrowHelper.CreateMissingMethod(typeof(I{0}), methodName);", Descriptor.Name); writer.Outdent(); writer.WriteLine("}"); //end switch writer.Outdent(); writer.WriteLine("}"); //end invoke writer.Outdent(); writer.WriteLine("}"); //end server } // SERVER - STUB { if (Descriptor.File.CSharpOptions.ClsCompliance) { writer.WriteLine("[global::System.CLSCompliant(false)]"); } writer.WriteLine("[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]"); WriteGeneratedCodeAttributes(writer); writer.WriteLine( "public partial class ServerStub : pb::IRpcServerStub, global::System.IDisposable {"); writer.Indent(); writer.WriteLine("private readonly bool dispose;"); writer.WriteLine("private readonly pb::IRpcDispatch implementation;", Descriptor.Name); writer.WriteLine("public ServerStub(I{0} implementation) : this(implementation, true) {{", Descriptor.Name); writer.WriteLine("}"); writer.WriteLine( "public ServerStub(I{0} implementation, bool dispose) : this(new Dispatch(implementation, dispose), dispose) {{", Descriptor.Name); writer.WriteLine("}"); writer.WriteLine("public ServerStub(pb::IRpcDispatch implementation) : this(implementation, true) {"); writer.WriteLine("}"); writer.WriteLine("public ServerStub(pb::IRpcDispatch implementation, bool dispose) {"); writer.WriteLine(" pb::ThrowHelper.ThrowIfNull(this.implementation = implementation, \"implementation\");"); writer.WriteLine(" this.dispose = dispose && implementation is global::System.IDisposable;"); writer.WriteLine("}"); writer.WriteLine(); writer.WriteLine("public void Dispose() {"); writer.WriteLine(" if (dispose) ((global::System.IDisposable)implementation).Dispose();"); writer.WriteLine("}"); writer.WriteLine(); writer.WriteLine( "public pb::IMessageLite CallMethod(string methodName, pb::ICodedInputStream input, pb::ExtensionRegistry registry) {{", Descriptor.Name); writer.Indent(); writer.WriteLine("switch(methodName) {"); writer.Indent(); foreach (MethodDescriptor method in Descriptor.Methods) { writer.WriteLine( "case \"{0}\": return implementation.CallMethod(methodName, {1}.ParseFrom(input, registry), {2}.CreateBuilder());", method.Name, GetClassName(method.InputType), GetClassName(method.OutputType)); } writer.WriteLine("default: throw pb::ThrowHelper.CreateMissingMethod(typeof(I{0}), methodName);", Descriptor.Name); writer.Outdent(); writer.WriteLine("}"); //end switch writer.Outdent(); writer.WriteLine("}"); //end invoke writer.Outdent(); writer.WriteLine("}"); //end server } writer.Outdent(); writer.WriteLine("}"); }
public override void CollectDependencies() { fields = Type.Fields.Select(f => NameHelpers.PreventKeywords(f.Name) + ": " + TypeHelpers.GetTypeName(Generator, this, f.FieldType, TypeUsage.Raw)).ToList(); }
private CSharpFileOptions BuildOrFakeWithDefaultOptions(CSharpFileOptions defaultOptions) { // Fix for being able to relocate these files to any directory structure if (proto.Package == "google.protobuf") { string filename = Path.GetFileName(proto.Name); // TODO(jonskeet): Check if we could use FileDescriptorProto.Descriptor.Name - interesting bootstrap issues) if (filename == "descriptor.proto") { return(new CSharpFileOptions.Builder { Namespace = "Google.ProtocolBuffers.DescriptorProtos", UmbrellaClassname = "DescriptorProtoFile", NestClasses = false, MultipleFiles = false, PublicClasses = true, OutputDirectory = defaultOptions.OutputDirectory, IgnoreGoogleProtobuf = defaultOptions.IgnoreGoogleProtobuf }.Build()); } if (filename == "csharp_options.proto") { return(new CSharpFileOptions.Builder { Namespace = "Google.ProtocolBuffers.DescriptorProtos", UmbrellaClassname = "CSharpOptions", NestClasses = false, MultipleFiles = false, PublicClasses = true, OutputDirectory = defaultOptions.OutputDirectory, IgnoreGoogleProtobuf = defaultOptions.IgnoreGoogleProtobuf }.Build()); } } CSharpFileOptions.Builder builder = defaultOptions.ToBuilder(); if (proto.Options.HasExtension(DescriptorProtos.CSharpOptions.CSharpFileOptions)) { builder.MergeFrom(proto.Options.GetExtension(DescriptorProtos.CSharpOptions.CSharpFileOptions)); } if (!builder.HasNamespace) { builder.Namespace = Package; } if (!builder.HasUmbrellaClassname) { int lastSlash = Name.LastIndexOf('/'); string baseName = Name.Substring(lastSlash + 1); builder.UmbrellaClassname = NameHelpers.UnderscoresToPascalCase(NameHelpers.StripProto(baseName)); } // Auto-fix for name collision by placing umbrella class into a new namespace. This // still won't fix the collisions with nesting enabled; however, you have to turn that on explicitly anyway. if (!builder.NestClasses && !builder.HasUmbrellaNamespace) { bool collision = false; foreach (IDescriptor d in MessageTypes) { collision |= d.Name == builder.UmbrellaClassname; } foreach (IDescriptor d in Services) { collision |= d.Name == builder.UmbrellaClassname; } foreach (IDescriptor d in EnumTypes) { collision |= d.Name == builder.UmbrellaClassname; } if (collision) { builder.UmbrellaNamespace = "Proto"; } } return(builder.Build()); }
private void GenerateBuilderParsingMethods(TextGenerator writer) { List <FieldDescriptor> sortedFields = new List <FieldDescriptor>(Descriptor.Fields); sortedFields.Sort((f1, f2) => f1.FieldNumber.CompareTo(f2.FieldNumber)); writer.WriteLine("public override Builder MergeFrom(pb::ICodedInputStream input) {"); writer.WriteLine(" return MergeFrom(input, pb::ExtensionRegistry.Empty);"); writer.WriteLine("}"); writer.WriteLine(); writer.WriteLine( "public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) {"); writer.Indent(); writer.WriteLine("PrepareBuilder();"); if (!UseLiteRuntime) { writer.WriteLine("pb::UnknownFieldSet.Builder unknownFields = null;"); } writer.WriteLine("uint tag;"); writer.WriteLine("string field_name;"); writer.WriteLine("while (input.ReadTag(out tag, out field_name)) {"); writer.Indent(); writer.WriteLine("if(tag == 0 && field_name != null) {"); writer.Indent(); //if you change from StringComparer.Ordinal, the array sort in FieldNames { get; } must also change writer.WriteLine( "int field_ordinal = global::System.Array.BinarySearch(_{0}FieldNames, field_name, global::System.StringComparer.Ordinal);", NameHelpers.UnderscoresToCamelCase(ClassName)); writer.WriteLine("if(field_ordinal >= 0)"); writer.WriteLine(" tag = _{0}FieldTags[field_ordinal];", NameHelpers.UnderscoresToCamelCase(ClassName)); writer.WriteLine("else {"); if (!UseLiteRuntime) { writer.WriteLine(" if (unknownFields == null) {"); // First unknown field - create builder now writer.WriteLine(" unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);"); writer.WriteLine(" }"); } writer.WriteLine(" ParseUnknownField(input, {0}extensionRegistry, tag, field_name);", UseLiteRuntime ? "" : "unknownFields, "); writer.WriteLine(" continue;"); writer.WriteLine("}"); writer.Outdent(); writer.WriteLine("}"); writer.WriteLine("switch (tag) {"); writer.Indent(); writer.WriteLine("case 0: {"); // 0 signals EOF / limit reached writer.WriteLine(" throw pb::InvalidProtocolBufferException.InvalidTag();"); writer.WriteLine("}"); writer.WriteLine("default: {"); writer.WriteLine(" if (pb::WireFormat.IsEndGroupTag(tag)) {"); if (!UseLiteRuntime) { writer.WriteLine(" if (unknownFields != null) {"); writer.WriteLine(" this.UnknownFields = unknownFields.Build();"); writer.WriteLine(" }"); } writer.WriteLine(" return this;"); // it's an endgroup tag writer.WriteLine(" }"); if (!UseLiteRuntime) { writer.WriteLine(" if (unknownFields == null) {"); // First unknown field - create builder now writer.WriteLine(" unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields);"); writer.WriteLine(" }"); } writer.WriteLine(" ParseUnknownField(input, {0}extensionRegistry, tag, field_name);", UseLiteRuntime ? "" : "unknownFields, "); writer.WriteLine(" break;"); writer.WriteLine("}"); foreach (FieldDescriptor field in sortedFields) { WireFormat.WireType wt = WireFormat.GetWireType(field.FieldType); uint tag = WireFormat.MakeTag(field.FieldNumber, wt); if (field.IsRepeated && (wt == WireFormat.WireType.Varint || wt == WireFormat.WireType.Fixed32 || wt == WireFormat.WireType.Fixed64)) { writer.WriteLine("case {0}:", WireFormat.MakeTag(field.FieldNumber, WireFormat.WireType.LengthDelimited)); } writer.WriteLine("case {0}: {{", tag); writer.Indent(); CreateFieldGenerator(field).GenerateParsingCode(writer); writer.WriteLine("break;"); writer.Outdent(); writer.WriteLine("}"); } writer.Outdent(); writer.WriteLine("}"); writer.Outdent(); writer.WriteLine("}"); writer.WriteLine(); if (!UseLiteRuntime) { writer.WriteLine("if (unknownFields != null) {"); writer.WriteLine(" this.UnknownFields = unknownFields.Build();"); writer.WriteLine("}"); } writer.WriteLine("return this;"); writer.Outdent(); writer.WriteLine("}"); writer.WriteLine(); }
private void GenerateMessageSerializationMethods(TextGenerator writer) { List <FieldDescriptor> sortedFields = new List <FieldDescriptor>(Descriptor.Fields); sortedFields.Sort((f1, f2) => f1.FieldNumber.CompareTo(f2.FieldNumber)); List <DescriptorProto.Types.ExtensionRange> sortedExtensions = new List <DescriptorProto.Types.ExtensionRange>(Descriptor.Proto.ExtensionRangeList); sortedExtensions.Sort((r1, r2) => (r1.Start.CompareTo(r2.Start))); writer.WriteLine("public override void WriteTo(pb::ICodedOutputStream output) {"); writer.Indent(); // Make sure we've computed the serialized length, so that packed fields are generated correctly. writer.WriteLine("CalcSerializedSize();"); writer.WriteLine("string[] field_names = _{0}FieldNames;", NameHelpers.UnderscoresToCamelCase(ClassName)); if (Descriptor.Proto.ExtensionRangeList.Count > 0) { writer.WriteLine( "pb::ExtendableMessage{1}<{0}, {0}.Builder>.ExtensionWriter extensionWriter = CreateExtensionWriter(this);", ClassName, RuntimeSuffix); } // Merge the fields and the extension ranges, both sorted by field number. for (int i = 0, j = 0; i < Descriptor.Fields.Count || j < sortedExtensions.Count;) { if (i == Descriptor.Fields.Count) { GenerateSerializeOneExtensionRange(writer, sortedExtensions[j++]); } else if (j == sortedExtensions.Count) { GenerateSerializeOneField(writer, sortedFields[i++]); } else if (sortedFields[i].FieldNumber < sortedExtensions[j].Start) { GenerateSerializeOneField(writer, sortedFields[i++]); } else { GenerateSerializeOneExtensionRange(writer, sortedExtensions[j++]); } } if (!UseLiteRuntime) { if (Descriptor.Proto.Options.MessageSetWireFormat) { writer.WriteLine("UnknownFields.WriteAsMessageSetTo(output);"); } else { writer.WriteLine("UnknownFields.WriteTo(output);"); } } writer.Outdent(); writer.WriteLine("}"); writer.WriteLine(); writer.WriteLine("private int memoizedSerializedSize = -1;"); writer.WriteLine("public override int SerializedSize {"); writer.Indent(); writer.WriteLine("get {"); writer.Indent(); writer.WriteLine("int size = memoizedSerializedSize;"); writer.WriteLine("if (size != -1) return size;"); writer.WriteLine("return CalcSerializedSize();"); writer.Outdent(); writer.WriteLine("}"); writer.Outdent(); writer.WriteLine("}"); writer.WriteLine(); writer.WriteLine("private int CalcSerializedSize() {"); writer.Indent(); writer.WriteLine("int size = memoizedSerializedSize;"); writer.WriteLine("if (size != -1) return size;"); writer.WriteLine(); writer.WriteLine("size = 0;"); foreach (FieldDescriptor field in Descriptor.Fields) { CreateFieldGenerator(field).GenerateSerializedSizeCode(writer); } if (Descriptor.Proto.ExtensionRangeCount > 0) { writer.WriteLine("size += ExtensionsSerializedSize;"); } if (!UseLiteRuntime) { if (Descriptor.Options.MessageSetWireFormat) { writer.WriteLine("size += UnknownFields.SerializedSizeAsMessageSet;"); } else { writer.WriteLine("size += UnknownFields.SerializedSize;"); } } writer.WriteLine("memoizedSerializedSize = size;"); writer.WriteLine("return size;"); writer.Outdent(); writer.WriteLine("}"); }
public void Generate(TextGenerator writer) { if (Descriptor.File.CSharpOptions.AddSerializable) { writer.WriteLine("[global::System.SerializableAttribute()]"); } writer.WriteLine("[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]"); WriteGeneratedCodeAttributes(writer); writer.WriteLine("{0} sealed partial class {1} : pb::{2}Message{3}<{1}, {1}.Builder> {{", ClassAccessLevel, ClassName, Descriptor.Proto.ExtensionRangeCount > 0 ? "Extendable" : "Generated", RuntimeSuffix); writer.Indent(); if (Descriptor.File.CSharpOptions.GeneratePrivateCtor) { writer.WriteLine("private {0}() {{ }}", ClassName); } // Must call MakeReadOnly() to make sure all lists are made read-only writer.WriteLine("private static readonly {0} defaultInstance = new {0}().MakeReadOnly();", ClassName); if (OptimizeSpeed) { writer.WriteLine("private static readonly string[] _{0}FieldNames = new string[] {{ {2}{1}{2} }};", NameHelpers.UnderscoresToCamelCase(ClassName), String.Join("\", \"", FieldNames), FieldNames.Length > 0 ? "\"" : ""); List <string> tags = new List <string>(); foreach (string name in FieldNames) { tags.Add(WireFormat.MakeTag(Descriptor.FindFieldByName(name)).ToString()); } writer.WriteLine("private static readonly uint[] _{0}FieldTags = new uint[] {{ {1} }};", NameHelpers.UnderscoresToCamelCase(ClassName), String.Join(", ", tags.ToArray())); } writer.WriteLine("public static {0} DefaultInstance {{", ClassName); writer.WriteLine(" get { return defaultInstance; }"); writer.WriteLine("}"); writer.WriteLine(); writer.WriteLine("public override {0} DefaultInstanceForType {{", ClassName); writer.WriteLine(" get { return DefaultInstance; }"); writer.WriteLine("}"); writer.WriteLine(); writer.WriteLine("protected override {0} ThisMessage {{", ClassName); writer.WriteLine(" get { return this; }"); writer.WriteLine("}"); writer.WriteLine(); if (!UseLiteRuntime) { writer.WriteLine("public static pbd::MessageDescriptor Descriptor {"); writer.WriteLine(" get {{ return {0}.internal__{1}__Descriptor; }}", DescriptorUtil.GetFullUmbrellaClassName(Descriptor), GetUniqueFileScopeIdentifier(Descriptor)); writer.WriteLine("}"); writer.WriteLine(); writer.WriteLine( "protected override pb::FieldAccess.FieldAccessorTable<{0}, {0}.Builder> InternalFieldAccessors {{", ClassName); writer.WriteLine(" get {{ return {0}.internal__{1}__FieldAccessorTable; }}", DescriptorUtil.GetFullUmbrellaClassName(Descriptor), GetUniqueFileScopeIdentifier(Descriptor)); writer.WriteLine("}"); writer.WriteLine(); } // Extensions don't need to go in an extra nested type WriteChildren(writer, null, Descriptor.Extensions); if (Descriptor.EnumTypes.Count + Descriptor.NestedTypes.Count > 0) { writer.WriteLine("#region Nested types"); writer.WriteLine("[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]"); WriteGeneratedCodeAttributes(writer); writer.WriteLine("public static partial class Types {"); writer.Indent(); WriteChildren(writer, null, Descriptor.EnumTypes); WriteChildren(writer, null, Descriptor.NestedTypes); writer.Outdent(); writer.WriteLine("}"); writer.WriteLine("#endregion"); writer.WriteLine(); } foreach (FieldDescriptor fieldDescriptor in Descriptor.Fields) { if (Descriptor.File.CSharpOptions.ClsCompliance && GetFieldConstantName(fieldDescriptor).StartsWith("_")) { writer.WriteLine("[global::System.CLSCompliant(false)]"); } // Rats: we lose the debug comment here :( writer.WriteLine("public const int {0} = {1};", GetFieldConstantName(fieldDescriptor), fieldDescriptor.FieldNumber); CreateFieldGenerator(fieldDescriptor).GenerateMembers(writer); writer.WriteLine(); } if (OptimizeSpeed) { GenerateIsInitialized(writer); GenerateMessageSerializationMethods(writer); } if (UseLiteRuntime) { GenerateLiteRuntimeMethods(writer); } GenerateParseFromMethods(writer); GenerateBuilder(writer); // Force the static initialization code for the file to run, since it may // initialize static variables declared in this class. writer.WriteLine("static {0}() {{", ClassName); // We call object.ReferenceEquals() just to make it a valid statement on its own. // Another option would be GetType(), but that causes problems in DescriptorProtoFile, // where the bootstrapping is somewhat recursive - type initializers call // each other, effectively. We temporarily see Descriptor as null. writer.WriteLine(" object.ReferenceEquals({0}.Descriptor, null);", DescriptorUtil.GetFullUmbrellaClassName(Descriptor)); writer.WriteLine("}"); writer.Outdent(); writer.WriteLine("}"); writer.WriteLine(); }
public string MakeWrapperBody(MethodDefinition def, bool isFactoryMethod) { var rawName = RawName; bool isGetMany = GetManyParameterName != null; var getManyPname = GetManyParameterName; var output = Output; var rawParams = new List <string> { "self.get_abi() as *const _ as *mut _" }; foreach (var p in def.Parameters) { var pname = NameHelpers.PreventKeywords(NameHelpers.FirstToLower(p.Name)); if (p.ParameterType.IsByReference) { if (((ByReferenceType)p.ParameterType).ElementType.IsArray) { rawParams.Add("&mut " + pname + "Size"); } // output parameter rawParams.Add("&mut " + pname); } else { // input parameter if (p.ParameterType.IsArray) { if (p.IsOut) { if (isGetMany) { rawParams.Add(pname + ".capacity() as u32"); rawParams.Add(pname + ".as_mut_ptr() as *mut T::Abi"); } else { rawParams.Add(pname + ".len() as u32"); rawParams.Add(pname + ".as_mut_ptr() as *mut _"); } } else { rawParams.Add(pname + ".len() as u32"); rawParams.Add(pname + ".as_ptr() as *mut _"); } } else { rawParams.Add(TypeHelpers.UnwrapInputParameter(pname, p.ParameterType)); } } } if (def.ReturnType.FullName != "System.Void") { if (def.ReturnType.IsArray) { rawParams.Add("&mut outSize"); } rawParams.Add("&mut out"); } var outInit = String.Join(" ", output.SelectMany(o => TypeHelpers.CreateUninitializedOutputs(o.Item1, o.Item2))); if (outInit != "") { outInit = "\r\n " + outInit; } var outWrap = String.Join(", ", output.Zip(GeneratedOutTypes, (a, b) => Tuple.Create(a.Item1, a.Item2, a.Item3, b)).Select(o => TypeHelpers.WrapOutputParameter(o.Item1, o.Item2, isFactoryMethod || o.Item3, o.Item4))); if (output.Count != 1) { outWrap = "(" + outWrap + ")"; // also works for count == 0 (empty tuple) } outWrap = "Ok(" + outWrap + ")"; if (isGetMany) { outInit = $"\r\n debug_assert!({ getManyPname }.capacity() > 0, \"capacity of `{ getManyPname }` must not be 0 (use Vec::with_capacity)\"); { getManyPname }.clear();{ outInit }"; outWrap = $"{ getManyPname }.set_len(out as usize); Ok(())"; } return(outInit + $@" let hr = (self.get_vtbl().{ rawName })({ String.Join(", ", rawParams) }); if hr == S_OK {{ { outWrap } }} else {{ err(hr) }}"); }
private MethodDetailsCache InitializeDetailsCache() { string rawName = GetRawName(); string name = GetWrapperName(rawName); bool isGetMany = (rawName == "GetMany" && DeclaringType.Namespace == "Windows.Foundation.Collections" && (DeclaringType.Name == "IVectorView`1" || DeclaringType.Name == "IIterator`1" || DeclaringType.Name == "IVector`1")); string getManyPname = null; // These `GetMany` methods have special semantics, since it takes an array and returns the number of elements that were filled // It uses the __RPC__out_ecount_part(capacity, *actual) annotation in the C headers. For the wrapper we use a &mut Vec<> buffer. var input = new List <Tuple <string, TypeReference, InputKind> >(); var output = new List <Tuple <string, TypeReference, bool> >(); foreach (var p in Method.Parameters) { string pname = NameHelpers.PreventKeywords(NameHelpers.FirstToLower(p.Name)); if (p.ParameterType.IsByReference) { Assert(p.IsOut); var realType = ((ByReferenceType)p.ParameterType).ElementType; output.Add(Tuple.Create(pname, realType, false)); } else { if (p.ParameterType.IsArray) { if (p.IsOut) { if (isGetMany) { Assert(getManyPname == null); // there should only be one out-array parameter for GetMany getManyPname = pname; input.Add(Tuple.Create(pname, ((ArrayType)p.ParameterType).ElementType, InputKind.VecBuffer)); } else { input.Add(Tuple.Create(pname, ((ArrayType)p.ParameterType).ElementType, InputKind.MutSlice)); } } else { input.Add(Tuple.Create(pname, ((ArrayType)p.ParameterType).ElementType, InputKind.Slice)); } } else { input.Add(Tuple.Create(pname, p.ParameterType, InputKind.Default)); } } } if (Method.ReturnType.FullName != "System.Void") { // this makes the actual return value the last in the tuple (if multiple) output.Add(Tuple.Create("out", Method.ReturnType, TypeHelpers.IsReturnTypeNonNull(Method.ReturnType, DeclaringType.Generator))); } // TODO: second tuple element should be true for some method's return value var outTypes = output.Select(o => Tuple.Create(o.Item2, o.Item3)).ToArray(); if (isGetMany) { outTypes = new Tuple <TypeReference, bool>[] { }; // GetMany has no return value } return(new MethodDetailsCache { WrappedName = name, RawName = rawName, InputParameterNames = input.Select(i => i.Item1).ToArray(), InputParameterTypes = input.Select(i => Tuple.Create(i.Item2, i.Item3)).ToArray(), OutTypes = outTypes.ToArray(), GetManyParameterName = isGetMany ? getManyPname : null, Output = output }); }
public Guest(string name, DateTime date) { Name = NameHelpers.Normalize(name); Date = date; }