blob: 1604f11caba95040e71ceb1e752a058b7736a8c5 [file] [log] [blame]
Jon Skeetd6343be2008-11-12 23:39:44 +00001using System;
Jon Skeet60c059b2008-10-23 21:17:56 +01002using System.Collections.Generic;
Jon Skeet68036862008-10-22 13:30:34 +01003using Google.ProtocolBuffers.Descriptors;
4
5namespace Google.ProtocolBuffers.ProtoGen {
6 internal abstract class SourceGeneratorBase<T> where T : IDescriptor {
7
8 private readonly T descriptor;
9
10 protected SourceGeneratorBase(T descriptor) {
11 this.descriptor = descriptor;
12 }
13
14 protected T Descriptor {
15 get { return descriptor; }
16 }
17
Jon Skeetd6343be2008-11-12 23:39:44 +000018 internal static string GetClassName(IDescriptor descriptor) {
19 return ToCSharpName(descriptor.FullName, descriptor.File);
20 }
21
22 // Groups are hacky: The name of the field is just the lower-cased name
23 // of the group type. In C#, though, we would like to retain the original
24 // capitalization of the type name.
25 internal static string GetFieldName(FieldDescriptor descriptor) {
26 if (descriptor.FieldType == FieldType.Group) {
27 return descriptor.MessageType.Name;
28 } else {
29 return descriptor.Name;
Jon Skeet68036862008-10-22 13:30:34 +010030 }
31 }
32
Jon Skeet7ee85c42009-05-28 21:11:15 +010033 internal static string GetFieldConstantName(FieldDescriptor field) {
Jon Skeetdf67f142009-06-05 19:29:36 +010034 return field.CSharpOptions.PropertyName + "FieldNumber";
Jon Skeet7ee85c42009-05-28 21:11:15 +010035 }
36
Jon Skeetd6343be2008-11-12 23:39:44 +000037 private static string ToCSharpName(string name, FileDescriptor file) {
38 string result = file.CSharpOptions.Namespace;
39 if (file.CSharpOptions.NestClasses) {
40 if (result != "") {
41 result += ".";
42 }
43 result += file.CSharpOptions.UmbrellaClassname;
44 }
45 if (result != "") {
46 result += '.';
47 }
48 string classname;
49 if (file.Package == "") {
50 classname = name;
51 } else {
52 // Strip the proto package from full_name since we've replaced it with
53 // the C# namespace.
54 classname = name.Substring(file.Package.Length + 1);
55 }
56 result += classname.Replace(".", ".Types.");
57 return "global::" + result;
Jon Skeet68036862008-10-22 13:30:34 +010058 }
59
Jon Skeetd6343be2008-11-12 23:39:44 +000060 protected string ClassAccessLevel {
61 get {
62 return descriptor.File.CSharpOptions.PublicClasses ? "public" : "internal";
63 }
64 }
65
66 protected void WriteChildren<TChild>(TextGenerator writer, string region, IEnumerable<TChild> children)
Jon Skeet68036862008-10-22 13:30:34 +010067 where TChild : IDescriptor {
68 // Copy the set of children; makes access easier
69 List<TChild> copy = new List<TChild>(children);
70 if (copy.Count == 0) {
71 return;
72 }
73
74 if (region != null) {
75 writer.WriteLine("#region {0}", region);
76 }
77 foreach (TChild child in children) {
78 SourceGenerators.CreateGenerator(child).Generate(writer);
79 }
80 if (region != null) {
81 writer.WriteLine("#endregion");
82 writer.WriteLine();
83 }
84 }
85 }
86}