1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc. All rights reserved.
3 //
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file or at
6 // https://developers.google.com/open-source/licenses/bsd
7
8 // Author: kenton@google.com (Kenton Varda)
9 // Based on original Protocol Buffers design by
10 // Sanjay Ghemawat, Jeff Dean, and others.
11 //
12 // Defines the abstract interface implemented by each of the language-specific
13 // code generators.
14
15 #ifndef GOOGLE_PROTOBUF_COMPILER_CODE_GENERATOR_H__
16 #define GOOGLE_PROTOBUF_COMPILER_CODE_GENERATOR_H__
17
18 #include <cstdint>
19 #include <string>
20 #include <utility>
21 #include <vector>
22
23 #include "absl/status/statusor.h"
24 #include "absl/strings/string_view.h"
25 #include "google/protobuf/compiler/code_generator_lite.h" // IWYU pragma: export
26 #include "google/protobuf/descriptor.h"
27 #include "google/protobuf/descriptor.pb.h"
28
29 // Must be included last.
30 #include "google/protobuf/port_def.inc"
31
32 namespace google {
33 namespace protobuf {
34
35 namespace io {
36 class ZeroCopyOutputStream;
37 }
38 class FileDescriptor;
39 class GeneratedCodeInfo;
40
41 namespace compiler {
42 class AccessInfoMap;
43
44 class Version;
45
46 // Defined in this file.
47 class CodeGenerator;
48 class GeneratorContext;
49
50 // The abstract interface to a class which generates code implementing a
51 // particular proto file in a particular language. A number of these may
52 // be registered with CommandLineInterface to support various languages.
53 class PROTOC_EXPORT CodeGenerator {
54 public:
55 CodeGenerator() = default;
56 CodeGenerator(const CodeGenerator&) = delete;
57 CodeGenerator& operator=(const CodeGenerator&) = delete;
58 virtual ~CodeGenerator();
59
60 // Generates code for the given proto file, generating one or more files in
61 // the given output directory.
62 //
63 // A parameter to be passed to the generator can be specified on the command
64 // line. This is intended to be used to pass generator specific parameters.
65 // It is empty if no parameter was given. ParseGeneratorParameter (below),
66 // can be used to accept multiple parameters within the single parameter
67 // command line flag.
68 //
69 // Returns true if successful. Otherwise, sets *error to a description of
70 // the problem (e.g. "invalid parameter") and returns false.
71 virtual bool Generate(const FileDescriptor* file,
72 const std::string& parameter,
73 GeneratorContext* generator_context,
74 std::string* error) const = 0;
75
76 // Generates code for all given proto files.
77 //
78 // WARNING: The canonical code generator design produces one or two output
79 // files per input .proto file, and we do not wish to encourage alternate
80 // designs.
81 //
82 // A parameter is given as passed on the command line, as in |Generate()|
83 // above.
84 //
85 // Returns true if successful. Otherwise, sets *error to a description of
86 // the problem (e.g. "invalid parameter") and returns false.
87 virtual bool GenerateAll(const std::vector<const FileDescriptor*>& files,
88 const std::string& parameter,
89 GeneratorContext* generator_context,
90 std::string* error) const;
91
92 // This must be kept in sync with plugin.proto. See that file for
93 // documentation on each value.
94 // TODO Use CodeGeneratorResponse.Feature here.
95 enum Feature {
96 FEATURE_PROTO3_OPTIONAL = 1,
97 FEATURE_SUPPORTS_EDITIONS = 2,
98 };
99
100 // Implement this to indicate what features this code generator supports.
101 //
102 // This must be a bitwise OR of values from the Feature enum above (or zero).
GetSupportedFeatures()103 virtual uint64_t GetSupportedFeatures() const { return 0; }
104
105 // This is no longer used, but this class is part of the opensource protobuf
106 // library, so it has to remain to keep vtables the same for the current
107 // version of the library. When protobufs does a api breaking change, the
108 // method can be removed.
HasGenerateAll()109 virtual bool HasGenerateAll() const { return true; }
110
111 // Returns all the feature extensions used by this generator. This must be in
112 // the generated pool, meaning that the extensions should be linked into this
113 // binary. Any generator features not included here will not get properly
114 // resolved and GetResolvedSourceFeatures will not provide useful values.
GetFeatureExtensions()115 virtual std::vector<const FieldDescriptor*> GetFeatureExtensions() const {
116 return {};
117 }
118
119 // Returns the minimum edition (inclusive) supported by this generator. Any
120 // proto files with an edition before this will result in an error.
GetMinimumEdition()121 virtual Edition GetMinimumEdition() const { return Edition::EDITION_UNKNOWN; }
122
123 // Returns the maximum edition (inclusive) supported by this generator. Any
124 // proto files with an edition after this will result in an error.
GetMaximumEdition()125 virtual Edition GetMaximumEdition() const { return Edition::EDITION_UNKNOWN; }
126
127 // Builds a default feature set mapping for this generator.
128 //
129 // This will use the extensions specified by GetFeatureExtensions(), with the
130 // supported edition range [GetMinimumEdition(), GetMaximumEdition]. It has
131 // no side-effects, and code generators only need to call this if they want to
132 // embed the defaults into the generated code.
133 absl::StatusOr<FeatureSetDefaults> BuildFeatureSetDefaults() const;
134
135 protected:
136 // Retrieves the resolved source features for a given descriptor. All the
137 // global features and language features returned by GetFeatureExtensions will
138 // be fully resolved. These should be used to make any feature-based decisions
139 // during code generation.
140 template <typename DescriptorT>
GetResolvedSourceFeatures(const DescriptorT & desc)141 static const FeatureSet& GetResolvedSourceFeatures(const DescriptorT& desc) {
142 return ::google::protobuf::internal::InternalFeatureHelper::GetFeatures(desc);
143 }
144
145 // Retrieves the unresolved source features for a given descriptor. These
146 // should be used to validate the original .proto file. These represent the
147 // original proto files from generated code, but should be stripped of
148 // source-retention features before sending to a runtime.
149 template <typename DescriptorT, typename TypeTraitsT, uint8_t field_type,
150 bool is_packed>
GetUnresolvedSourceFeatures(const DescriptorT & descriptor,const google::protobuf::internal::ExtensionIdentifier<FeatureSet,TypeTraitsT,field_type,is_packed> & extension)151 static typename TypeTraitsT::ConstType GetUnresolvedSourceFeatures(
152 const DescriptorT& descriptor,
153 const google::protobuf::internal::ExtensionIdentifier<
154 FeatureSet, TypeTraitsT, field_type, is_packed>& extension) {
155 return ::google::protobuf::internal::InternalFeatureHelper::GetUnresolvedFeatures(
156 descriptor, extension);
157 }
158
159 // Retrieves the edition of a built file descriptor.
GetEdition(const FileDescriptor & file)160 static Edition GetEdition(const FileDescriptor& file) {
161 return ::google::protobuf::internal::InternalFeatureHelper::GetEdition(file);
162 }
163 };
164
MinimumAllowedEdition()165 constexpr auto MinimumAllowedEdition() { return Edition::EDITION_PROTO2; }
MaximumAllowedEdition()166 constexpr auto MaximumAllowedEdition() { return Edition::EDITION_2023; }
167
168 // CodeGenerators generate one or more files in a given directory. This
169 // abstract interface represents the directory to which the CodeGenerator is
170 // to write and other information about the context in which the Generator
171 // runs.
172 class PROTOC_EXPORT GeneratorContext {
173 public:
GeneratorContext()174 GeneratorContext() {
175 }
176 GeneratorContext(const GeneratorContext&) = delete;
177 GeneratorContext& operator=(const GeneratorContext&) = delete;
178 virtual ~GeneratorContext();
179
180 // Opens the given file, truncating it if it exists, and returns a
181 // ZeroCopyOutputStream that writes to the file. The caller takes ownership
182 // of the returned object. This method never fails (a dummy stream will be
183 // returned instead).
184 //
185 // The filename given should be relative to the root of the source tree.
186 // E.g. the C++ generator, when generating code for "foo/bar.proto", will
187 // generate the files "foo/bar.pb.h" and "foo/bar.pb.cc"; note that
188 // "foo/" is included in these filenames. The filename is not allowed to
189 // contain "." or ".." components.
190 virtual io::ZeroCopyOutputStream* Open(const std::string& filename) = 0;
191
192 // Similar to Open() but the output will be appended to the file if exists
193 virtual io::ZeroCopyOutputStream* OpenForAppend(const std::string& filename);
194
195 // Creates a ZeroCopyOutputStream which will insert code into the given file
196 // at the given insertion point. See plugin.proto (plugin.pb.h) for more
197 // information on insertion points. The default implementation
198 // assert-fails -- it exists only for backwards-compatibility.
199 //
200 // WARNING: This feature is currently EXPERIMENTAL and is subject to change.
201 virtual io::ZeroCopyOutputStream* OpenForInsert(
202 const std::string& filename, const std::string& insertion_point);
203
204 // Similar to OpenForInsert, but if `info` is non-empty, will open (or create)
205 // filename.pb.meta and insert info at the appropriate place with the
206 // necessary shifts. The default implementation ignores `info`.
207 //
208 // WARNING: This feature will be REMOVED in the near future.
209 virtual io::ZeroCopyOutputStream* OpenForInsertWithGeneratedCodeInfo(
210 const std::string& filename, const std::string& insertion_point,
211 const google::protobuf::GeneratedCodeInfo& info);
212
213 // Returns a vector of FileDescriptors for all the files being compiled
214 // in this run. Useful for languages, such as Go, that treat files
215 // differently when compiled as a set rather than individually.
216 virtual void ListParsedFiles(std::vector<const FileDescriptor*>* output);
217
218 // Retrieves the version number of the protocol compiler associated with
219 // this GeneratorContext.
220 virtual void GetCompilerVersion(Version* version) const;
221
222 };
223
224 // The type GeneratorContext was once called OutputDirectory. This typedef
225 // provides backward compatibility.
226 typedef GeneratorContext OutputDirectory;
227
228 // Returns true if the proto path can skip edition check.
229 PROTOC_EXPORT bool CanSkipEditionCheck(absl::string_view filename);
230
231 } // namespace compiler
232 } // namespace protobuf
233 } // namespace google
234
235 #include "google/protobuf/port_undef.inc"
236
237 #endif // GOOGLE_PROTOBUF_COMPILER_CODE_GENERATOR_H__
238