blob: 6abe1dde2ded675d85891d3d8aa3ce93051e6b18 [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 Skeetd6343be2008-11-12 23:39:44 +000033 private static string ToCSharpName(string name, FileDescriptor file) {
34 string result = file.CSharpOptions.Namespace;
35 if (file.CSharpOptions.NestClasses) {
36 if (result != "") {
37 result += ".";
38 }
39 result += file.CSharpOptions.UmbrellaClassname;
40 }
41 if (result != "") {
42 result += '.';
43 }
44 string classname;
45 if (file.Package == "") {
46 classname = name;
47 } else {
48 // Strip the proto package from full_name since we've replaced it with
49 // the C# namespace.
50 classname = name.Substring(file.Package.Length + 1);
51 }
52 result += classname.Replace(".", ".Types.");
53 return "global::" + result;
Jon Skeet68036862008-10-22 13:30:34 +010054 }
55
Jon Skeetd6343be2008-11-12 23:39:44 +000056 protected string ClassAccessLevel {
57 get {
58 return descriptor.File.CSharpOptions.PublicClasses ? "public" : "internal";
59 }
60 }
61
62 protected void WriteChildren<TChild>(TextGenerator writer, string region, IEnumerable<TChild> children)
Jon Skeet68036862008-10-22 13:30:34 +010063 where TChild : IDescriptor {
64 // Copy the set of children; makes access easier
65 List<TChild> copy = new List<TChild>(children);
66 if (copy.Count == 0) {
67 return;
68 }
69
70 if (region != null) {
71 writer.WriteLine("#region {0}", region);
72 }
73 foreach (TChild child in children) {
74 SourceGenerators.CreateGenerator(child).Generate(writer);
75 }
76 if (region != null) {
77 writer.WriteLine("#endregion");
78 writer.WriteLine();
79 }
80 }
81 }
82}