3 '''Generate header file for nanopb from a ProtoBuf FileDescriptorSet.'''
4 nanopb_version = "nanopb-0.2.3-dev"
7 import google.protobuf.descriptor_pb2 as descriptor
8 import google.protobuf.text_format as text_format
11 print "*************************************************************"
12 print "*** Could not import the Google protobuf Python libraries ***"
13 print "*** Try installing package 'python-protobuf' or similar. ***"
14 print "*************************************************************"
22 print "***************************************************************"
23 print "*** Could not import the precompiled nanopb_pb2.py. ***"
24 print "*** Run 'make' in the 'generator' folder to update the file.***"
25 print "***************************************************************"
34 # ---------------------------------------------------------------------------
35 # Generation of single fields
36 # ---------------------------------------------------------------------------
41 # Values are tuple (c type, pb type)
42 FieldD = descriptor.FieldDescriptorProto
44 FieldD.TYPE_BOOL: ('bool', 'BOOL'),
45 FieldD.TYPE_DOUBLE: ('double', 'DOUBLE'),
46 FieldD.TYPE_FIXED32: ('uint32_t', 'FIXED32'),
47 FieldD.TYPE_FIXED64: ('uint64_t', 'FIXED64'),
48 FieldD.TYPE_FLOAT: ('float', 'FLOAT'),
49 FieldD.TYPE_INT32: ('int32_t', 'INT32'),
50 FieldD.TYPE_INT64: ('int64_t', 'INT64'),
51 FieldD.TYPE_SFIXED32: ('int32_t', 'SFIXED32'),
52 FieldD.TYPE_SFIXED64: ('int64_t', 'SFIXED64'),
53 FieldD.TYPE_SINT32: ('int32_t', 'SINT32'),
54 FieldD.TYPE_SINT64: ('int64_t', 'SINT64'),
55 FieldD.TYPE_UINT32: ('uint32_t', 'UINT32'),
56 FieldD.TYPE_UINT64: ('uint64_t', 'UINT64')
60 '''Keeps a set of nested names and formats them to C identifier.'''
61 def __init__(self, parts = ()):
62 if isinstance(parts, Names):
64 self.parts = tuple(parts)
67 return '_'.join(self.parts)
69 def __add__(self, other):
70 if isinstance(other, (str, unicode)):
71 return Names(self.parts + (other,))
72 elif isinstance(other, tuple):
73 return Names(self.parts + other)
75 raise ValueError("Name parts should be of type str")
77 def __eq__(self, other):
78 return isinstance(other, Names) and self.parts == other.parts
80 def names_from_type_name(type_name):
81 '''Parse Names() from FieldDescriptorProto type_name'''
82 if type_name[0] != '.':
83 raise NotImplementedError("Lookup of non-absolute type names is not supported")
84 return Names(type_name[1:].split('.'))
87 def __init__(self, names, desc, enum_options):
88 '''desc is EnumDescriptorProto'''
90 self.options = enum_options
91 self.names = names + desc.name
93 if enum_options.long_names:
94 self.values = [(self.names + x.name, x.number) for x in desc.value]
96 self.values = [(names + x.name, x.number) for x in desc.value]
98 self.value_longnames = [self.names + x.name for x in desc.value]
101 result = 'typedef enum _%s {\n' % self.names
102 result += ',\n'.join([" %s = %d" % x for x in self.values])
103 result += '\n} %s;' % self.names
107 def __init__(self, struct_name, desc, field_options):
108 '''desc is FieldDescriptorProto'''
109 self.tag = desc.number
110 self.struct_name = struct_name
111 self.name = desc.name
114 self.max_count = None
117 # Parse field options
118 if field_options.HasField("max_size"):
119 self.max_size = field_options.max_size
121 if field_options.HasField("max_count"):
122 self.max_count = field_options.max_count
124 if desc.HasField('default_value'):
125 self.default = desc.default_value
127 # Check field rules, i.e. required/optional/repeated.
129 if desc.label == FieldD.LABEL_REQUIRED:
130 self.rules = 'REQUIRED'
131 elif desc.label == FieldD.LABEL_OPTIONAL:
132 self.rules = 'OPTIONAL'
133 elif desc.label == FieldD.LABEL_REPEATED:
134 self.rules = 'REPEATED'
135 if self.max_count is None:
136 can_be_static = False
138 self.array_decl = '[%d]' % self.max_count
140 raise NotImplementedError(desc.label)
142 # Decide the C data type to use in the struct.
143 if datatypes.has_key(desc.type):
144 self.ctype, self.pbtype = datatypes[desc.type]
145 elif desc.type == FieldD.TYPE_ENUM:
147 self.ctype = names_from_type_name(desc.type_name)
148 if self.default is not None:
149 self.default = self.ctype + self.default
150 elif desc.type == FieldD.TYPE_STRING:
151 self.pbtype = 'STRING'
152 if self.max_size is None:
153 can_be_static = False
156 self.array_decl += '[%d]' % self.max_size
157 elif desc.type == FieldD.TYPE_BYTES:
158 self.pbtype = 'BYTES'
159 if self.max_size is None:
160 can_be_static = False
162 self.ctype = self.struct_name + self.name + 't'
163 elif desc.type == FieldD.TYPE_MESSAGE:
164 self.pbtype = 'MESSAGE'
165 self.ctype = self.submsgname = names_from_type_name(desc.type_name)
167 raise NotImplementedError(desc.type)
169 if field_options.type == nanopb_pb2.FT_DEFAULT:
171 field_options.type = nanopb_pb2.FT_STATIC
173 field_options.type = nanopb_pb2.FT_CALLBACK
175 if field_options.type == nanopb_pb2.FT_STATIC and not can_be_static:
176 raise Exception("Field %s is defined as static, but max_size or max_count is not given." % self.name)
178 if field_options.type == nanopb_pb2.FT_STATIC:
179 self.allocation = 'STATIC'
180 elif field_options.type == nanopb_pb2.FT_CALLBACK:
181 self.allocation = 'CALLBACK'
182 self.ctype = 'pb_callback_t'
185 raise NotImplementedError(field_options.type)
187 def __cmp__(self, other):
188 return cmp(self.tag, other.tag)
191 if self.rules == 'OPTIONAL' and self.allocation == 'STATIC':
192 result = ' bool has_' + self.name + ';\n'
193 elif self.rules == 'REPEATED' and self.allocation == 'STATIC':
194 result = ' size_t ' + self.name + '_count;\n'
197 result += ' %s %s%s;' % (self.ctype, self.name, self.array_decl)
201 '''Return definitions for any special types this field might need.'''
202 if self.pbtype == 'BYTES' and self.allocation == 'STATIC':
203 result = 'typedef struct {\n'
204 result += ' size_t size;\n'
205 result += ' uint8_t bytes[%d];\n' % self.max_size
206 result += '} %s;\n' % self.ctype
211 def default_decl(self, declaration_only = False):
212 '''Return definition for this field's default value.'''
213 if self.default is None:
216 ctype, default = self.ctype, self.default
219 if self.pbtype == 'STRING':
220 if self.allocation != 'STATIC':
221 return None # Not implemented
223 array_decl = '[%d]' % self.max_size
224 default = str(self.default).encode('string_escape')
225 default = default.replace('"', '\\"')
226 default = '"' + default + '"'
227 elif self.pbtype == 'BYTES':
228 if self.allocation != 'STATIC':
229 return None # Not implemented
231 data = self.default.decode('string_escape')
232 data = ['0x%02x' % ord(c) for c in data]
233 default = '{%d, {%s}}' % (len(data), ','.join(data))
236 return 'extern const %s %s_default%s;' % (ctype, self.struct_name + self.name, array_decl)
238 return 'const %s %s_default%s = %s;' % (ctype, self.struct_name + self.name, array_decl, default)
241 '''Return the #define for the tag number of this field.'''
242 identifier = '%s_%s_tag' % (self.struct_name, self.name)
243 return '#define %-40s %d\n' % (identifier, self.tag)
245 def pb_field_t(self, prev_field_name):
246 '''Return the pb_field_t initializer to use in the constant array.
247 prev_field_name is the name of the previous field or None.
249 result = ' PB_FIELD(%3d, ' % self.tag
250 result += '%-8s, ' % self.pbtype
251 result += '%s, ' % self.rules
252 result += '%s, ' % self.allocation
253 result += '%s, ' % self.struct_name
254 result += '%s, ' % self.name
255 result += '%s, ' % (prev_field_name or self.name)
257 if self.pbtype == 'MESSAGE':
258 result += '&%s_fields)' % self.submsgname
259 elif self.default is None:
261 elif self.pbtype in ['BYTES', 'STRING'] and self.allocation != 'STATIC':
262 result += '0)' # Arbitrary size default values not implemented
264 result += '&%s_default)' % (self.struct_name + self.name)
268 def largest_field_value(self):
269 '''Determine if this field needs 16bit or 32bit pb_field_t structure to compile properly.
270 Returns numeric value or a C-expression for assert.'''
271 if self.pbtype == 'MESSAGE':
272 if self.rules == 'REPEATED' and self.allocation == 'STATIC':
273 return 'pb_membersize(%s, %s[0])' % (self.struct_name, self.name)
275 return 'pb_membersize(%s, %s)' % (self.struct_name, self.name)
277 return max(self.tag, self.max_size, self.max_count)
280 class ExtensionRange(Field):
281 def __init__(self, struct_name, range_start, field_options):
282 '''Implements a special pb_extension_t* field in an extensible message
283 structure. The range_start signifies the index at which the extensions
284 start. Not necessarily all tags above this are extensions, it is merely
285 a speed optimization.
287 self.tag = range_start
288 self.struct_name = struct_name
289 self.name = 'extensions'
290 self.pbtype = 'EXTENSION'
291 self.rules = 'OPTIONAL'
292 self.allocation = 'CALLBACK'
293 self.ctype = 'pb_extension_t'
300 return ' pb_extension_t *extensions;'
308 class ExtensionField(Field):
309 def __init__(self, struct_name, desc, field_options):
310 self.fullname = struct_name + desc.name
311 self.extendee_name = names_from_type_name(desc.extendee)
312 Field.__init__(self, self.fullname + 'struct', desc, field_options)
314 if self.rules != 'OPTIONAL':
318 self.rules = 'OPTEXT'
320 def extension_decl(self):
321 '''Declaration of the extension type in the .pb.h file'''
323 msg = '/* Extension field %s was skipped because only "optional"\n' % self.fullname
324 msg +=' type of extension fields is currently supported. */\n'
327 return 'extern const pb_extension_type_t %s;\n' % self.fullname
329 def extension_def(self):
330 '''Definition of the extension type in the .pb.c file'''
335 result = 'typedef struct {\n'
337 result += '\n} %s;\n\n' % self.struct_name
338 result += ('static const pb_field_t %s_field = \n %s;\n\n' %
339 (self.fullname, self.pb_field_t(None)))
340 result += 'const pb_extension_type_t %s = {\n' % self.fullname
343 result += ' &%s_field\n' % self.fullname
348 # ---------------------------------------------------------------------------
349 # Generation of messages (structures)
350 # ---------------------------------------------------------------------------
354 def __init__(self, names, desc, message_options):
359 field_options = get_nanopb_suboptions(f, message_options, self.name + f.name)
360 if field_options.type != nanopb_pb2.FT_IGNORE:
361 self.fields.append(Field(self.name, f, field_options))
363 if len(desc.extension_range) > 0:
364 field_options = get_nanopb_suboptions(desc, message_options, self.name + 'extensions')
365 range_start = min([r.start for r in desc.extension_range])
366 if field_options.type != nanopb_pb2.FT_IGNORE:
367 self.fields.append(ExtensionRange(self.name, range_start, field_options))
369 self.packed = message_options.packed_struct
370 self.ordered_fields = self.fields[:]
371 self.ordered_fields.sort()
373 def get_dependencies(self):
374 '''Get list of type names that this structure refers to.'''
375 return [str(field.ctype) for field in self.fields]
378 result = 'typedef struct _%s {\n' % self.name
380 if not self.ordered_fields:
381 # Empty structs are not allowed in C standard.
382 # Therefore add a dummy field if an empty message occurs.
383 result += ' uint8_t dummy_field;'
385 result += '\n'.join([str(f) for f in self.ordered_fields])
389 result += ' pb_packed'
391 result += ' %s;' % self.name
394 result = 'PB_PACKED_STRUCT_START\n' + result
395 result += '\nPB_PACKED_STRUCT_END'
401 for field in self.fields:
402 types = field.types()
403 if types is not None:
404 result += types + '\n'
407 def default_decl(self, declaration_only = False):
409 for field in self.fields:
410 default = field.default_decl(declaration_only)
411 if default is not None:
412 result += default + '\n'
415 def fields_declaration(self):
416 result = 'extern const pb_field_t %s_fields[%d];' % (self.name, len(self.fields) + 1)
419 def fields_definition(self):
420 result = 'const pb_field_t %s_fields[%d] = {\n' % (self.name, len(self.fields) + 1)
423 for field in self.ordered_fields:
424 result += field.pb_field_t(prev)
428 result += ' PB_LAST_FIELD\n};'
433 # ---------------------------------------------------------------------------
434 # Processing of entire .proto files
435 # ---------------------------------------------------------------------------
438 def iterate_messages(desc, names = Names()):
439 '''Recursively find all messages. For each, yield name, DescriptorProto.'''
440 if hasattr(desc, 'message_type'):
441 submsgs = desc.message_type
443 submsgs = desc.nested_type
445 for submsg in submsgs:
446 sub_names = names + submsg.name
447 yield sub_names, submsg
449 for x in iterate_messages(submsg, sub_names):
452 def iterate_extensions(desc, names = Names()):
453 '''Recursively find all extensions.
454 For each, yield name, FieldDescriptorProto.
456 for extension in desc.extension:
457 yield names, extension
459 for subname, subdesc in iterate_messages(desc, names):
460 for extension in subdesc.extension:
461 yield subname, extension
463 def parse_file(fdesc, file_options):
464 '''Takes a FileDescriptorProto and returns tuple (enums, messages, extensions).'''
471 base_name = Names(fdesc.package.split('.'))
475 for enum in fdesc.enum_type:
476 enum_options = get_nanopb_suboptions(enum, file_options, base_name + enum.name)
477 enums.append(Enum(base_name, enum, enum_options))
479 for names, message in iterate_messages(fdesc, base_name):
480 message_options = get_nanopb_suboptions(message, file_options, names)
481 messages.append(Message(names, message, message_options))
482 for enum in message.enum_type:
483 enum_options = get_nanopb_suboptions(enum, message_options, names + enum.name)
484 enums.append(Enum(names, enum, enum_options))
486 for names, extension in iterate_extensions(fdesc, base_name):
487 field_options = get_nanopb_suboptions(extension, file_options, names)
488 if field_options.type != nanopb_pb2.FT_IGNORE:
489 extensions.append(ExtensionField(names, extension, field_options))
491 # Fix field default values where enum short names are used.
493 if not enum.options.long_names:
494 for message in messages:
495 for field in message.fields:
496 if field.default in enum.value_longnames:
497 idx = enum.value_longnames.index(field.default)
498 field.default = enum.values[idx][0]
500 return enums, messages, extensions
504 From http://code.activestate.com/recipes/577413-topological-sort/
505 This function is under the MIT license.
507 for k, v in data.items():
508 v.discard(k) # Ignore self dependencies
509 extra_items_in_deps = reduce(set.union, data.values(), set()) - set(data.keys())
510 data.update(dict([(item, set()) for item in extra_items_in_deps]))
512 ordered = set(item for item,dep in data.items() if not dep)
515 for item in sorted(ordered):
517 data = dict([(item, (dep - ordered)) for item,dep in data.items()
518 if item not in ordered])
519 assert not data, "A cyclic dependency exists amongst %r" % data
521 def sort_dependencies(messages):
522 '''Sort a list of Messages based on dependencies.'''
525 for message in messages:
526 dependencies[str(message.name)] = set(message.get_dependencies())
527 message_by_name[str(message.name)] = message
529 for msgname in toposort2(dependencies):
530 if msgname in message_by_name:
531 yield message_by_name[msgname]
533 def make_identifier(headername):
534 '''Make #ifndef identifier that contains uppercase A-Z and digits 0-9'''
536 for c in headername.upper():
543 def generate_header(dependencies, headername, enums, messages, extensions, options):
544 '''Generate content for a header file.
545 Generates strings, which should be concatenated and stored to file.
548 yield '/* Automatically generated nanopb header */\n'
549 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
551 symbol = make_identifier(headername)
552 yield '#ifndef _PB_%s_\n' % symbol
553 yield '#define _PB_%s_\n' % symbol
555 yield options.libformat % ('pb.h')
557 # no %s specified - use whatever was passed in as options.libformat
558 yield options.libformat
561 for dependency in dependencies:
562 noext = os.path.splitext(dependency)[0]
563 yield options.genformat % (noext + '.' + options.extension + '.h')
566 yield '#ifdef __cplusplus\n'
567 yield 'extern "C" {\n'
570 yield '/* Enum definitions */\n'
572 yield str(enum) + '\n\n'
574 yield '/* Struct definitions */\n'
575 for msg in sort_dependencies(messages):
577 yield str(msg) + '\n\n'
580 yield '/* Extensions */\n'
581 for extension in extensions:
582 yield extension.extension_decl()
585 yield '/* Default values for struct fields */\n'
587 yield msg.default_decl(True)
590 yield '/* Field tags (for use in manual encoding/decoding) */\n'
591 for msg in sort_dependencies(messages):
592 for field in msg.fields:
596 yield '/* Struct field encoding specification for nanopb */\n'
598 yield msg.fields_declaration() + '\n'
600 yield '\n#ifdef __cplusplus\n'
601 yield '} /* extern "C" */\n'
607 def generate_source(headername, enums, messages, extensions, options):
608 '''Generate content for a source file.'''
610 yield '/* Automatically generated nanopb constant definitions */\n'
611 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
612 yield options.genformat % (headername)
616 yield msg.default_decl(False)
621 yield msg.fields_definition() + '\n\n'
623 for ext in extensions:
624 yield ext.extension_def() + '\n'
626 # Add checks for numeric limits
628 count_required_fields = lambda m: len([f for f in msg.fields if f.rules == 'REQUIRED'])
629 largest_msg = max(messages, key = count_required_fields)
630 largest_count = count_required_fields(largest_msg)
631 if largest_count > 64:
632 yield '\n/* Check that missing required fields will be properly detected */\n'
633 yield '#if PB_MAX_REQUIRED_FIELDS < %d\n' % largest_count
634 yield '#error Properly detecting missing required fields in %s requires \\\n' % largest_msg.name
635 yield ' setting PB_MAX_REQUIRED_FIELDS to %d or more.\n' % largest_count
643 checks_msgnames.append(msg.name)
644 for field in msg.fields:
645 status = field.largest_field_value()
646 if isinstance(status, (str, unicode)):
647 checks.append(status)
650 worst_field = str(field.struct_name) + '.' + str(field.name)
652 if worst > 255 or checks:
653 yield '\n/* Check that field information fits in pb_field_t */\n'
656 yield '#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT)\n'
658 yield '#error Field descriptor for %s is too large. Define PB_FIELD_16BIT to fix this.\n' % worst_field
660 assertion = ' && '.join(str(c) + ' < 256' for c in checks)
661 msgs = '_'.join(str(n) for n in checks_msgnames)
662 yield 'STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
665 if worst > 65535 or checks:
666 yield '#if !defined(PB_FIELD_32BIT)\n'
668 yield '#error Field descriptor for %s is too large. Define PB_FIELD_32BIT to fix this.\n' % worst_field
670 assertion = ' && '.join(str(c) + ' < 65536' for c in checks)
671 msgs = '_'.join(str(n) for n in checks_msgnames)
672 yield 'STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
675 # Add check for sizeof(double)
678 for field in msg.fields:
679 if field.ctype == 'double':
684 yield '/* On some platforms (such as AVR), double is really float.\n'
685 yield ' * These are not directly supported by nanopb, but see example_avr_double.\n'
686 yield ' * To get rid of this error, remove any double fields from your .proto.\n'
688 yield 'STATIC_ASSERT(sizeof(double) == 8, DOUBLE_MUST_BE_8_BYTES)\n'
692 # ---------------------------------------------------------------------------
693 # Options parsing for the .proto files
694 # ---------------------------------------------------------------------------
696 from fnmatch import fnmatch
698 def read_options_file(infile):
699 '''Parse a separate options file to list:
700 [(namemask, options), ...]
705 if not line or line.startswith('//') or line.startswith('#'):
708 parts = line.split(None, 1)
709 opts = nanopb_pb2.NanoPBOptions()
710 text_format.Merge(parts[1], opts)
711 results.append((parts[0], opts))
716 '''Ugly global variables, should find a good way to pass these.'''
717 verbose_options = False
718 separate_options = []
720 def get_nanopb_suboptions(subdesc, options, name):
721 '''Get copy of options, and merge information from subdesc.'''
722 new_options = nanopb_pb2.NanoPBOptions()
723 new_options.CopyFrom(options)
725 # Handle options defined in a separate file
726 dotname = '.'.join(name.parts)
727 for namemask, options in Globals.separate_options:
728 if fnmatch(dotname, namemask):
729 new_options.MergeFrom(options)
731 # Handle options defined in .proto
732 if isinstance(subdesc.options, descriptor.FieldOptions):
733 ext_type = nanopb_pb2.nanopb
734 elif isinstance(subdesc.options, descriptor.FileOptions):
735 ext_type = nanopb_pb2.nanopb_fileopt
736 elif isinstance(subdesc.options, descriptor.MessageOptions):
737 ext_type = nanopb_pb2.nanopb_msgopt
738 elif isinstance(subdesc.options, descriptor.EnumOptions):
739 ext_type = nanopb_pb2.nanopb_enumopt
741 raise Exception("Unknown options type")
743 if subdesc.options.HasExtension(ext_type):
744 ext = subdesc.options.Extensions[ext_type]
745 new_options.MergeFrom(ext)
747 if Globals.verbose_options:
748 print "Options for " + dotname + ":"
749 print text_format.MessageToString(new_options)
754 # ---------------------------------------------------------------------------
755 # Command line interface
756 # ---------------------------------------------------------------------------
760 from optparse import OptionParser
762 optparser = OptionParser(
763 usage = "Usage: nanopb_generator.py [options] file.pb ...",
764 epilog = "Compile file.pb from file.proto by: 'protoc -ofile.pb file.proto'. " +
765 "Output will be written to file.pb.h and file.pb.c.")
766 optparser.add_option("-x", dest="exclude", metavar="FILE", action="append", default=[],
767 help="Exclude file from generated #include list.")
768 optparser.add_option("-e", "--extension", dest="extension", metavar="EXTENSION", default="pb",
769 help="Set extension to use instead of 'pb' for generated files. [default: %default]")
770 optparser.add_option("-f", "--options-file", dest="options_file", metavar="FILE", default="%s.options",
771 help="Set name of a separate generator options file.")
772 optparser.add_option("-Q", "--generated-include-format", dest="genformat",
773 metavar="FORMAT", default='#include "%s"\n',
774 help="Set format string to use for including other .pb.h files. [default: %default]")
775 optparser.add_option("-L", "--library-include-format", dest="libformat",
776 metavar="FORMAT", default='#include <%s>\n',
777 help="Set format string to use for including the nanopb pb.h header. [default: %default]")
778 optparser.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False,
779 help="Don't print anything except errors.")
780 optparser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
781 help="Print more information.")
782 optparser.add_option("-s", dest="settings", metavar="OPTION:VALUE", action="append", default=[],
783 help="Set generator option (max_size, max_count etc.).")
785 def process_file(filename, fdesc, options):
786 '''Process a single file.
787 filename: The full path to the .proto or .pb source file, as string.
788 fdesc: The loaded FileDescriptorSet, or None to read from the input file.
789 options: Command line options as they come from OptionsParser.
792 {'headername': Name of header file,
793 'headerdata': Data for the .h header file,
794 'sourcename': Name of the source code file,
795 'sourcedata': Data for the .c source code file
798 toplevel_options = nanopb_pb2.NanoPBOptions()
799 for s in options.settings:
800 text_format.Merge(s, toplevel_options)
803 data = open(filename, 'rb').read()
804 fdesc = descriptor.FileDescriptorSet.FromString(data).file[0]
806 # Check if there is a separate .options file
808 optfilename = options.options_file % os.path.splitext(filename)[0]
810 # No %s specified, use the filename as-is
811 optfilename = options.options_file
814 print 'Reading options from ' + optfilename
816 if os.path.isfile(optfilename):
817 Globals.separate_options = read_options_file(open(optfilename, "rU"))
819 Globals.separate_options = []
822 file_options = get_nanopb_suboptions(fdesc, toplevel_options, Names([filename]))
823 enums, messages, extensions = parse_file(fdesc, file_options)
825 # Decide the file names
826 noext = os.path.splitext(filename)[0]
827 headername = noext + '.' + options.extension + '.h'
828 sourcename = noext + '.' + options.extension + '.c'
829 headerbasename = os.path.basename(headername)
831 # List of .proto files that should not be included in the C header file
832 # even if they are mentioned in the source .proto.
833 excludes = ['nanopb.proto', 'google/protobuf/descriptor.proto'] + options.exclude
834 dependencies = [d for d in fdesc.dependency if d not in excludes]
836 headerdata = ''.join(generate_header(dependencies, headerbasename, enums,
837 messages, extensions, options))
839 sourcedata = ''.join(generate_source(headerbasename, enums,
840 messages, extensions, options))
842 return {'headername': headername, 'headerdata': headerdata,
843 'sourcename': sourcename, 'sourcedata': sourcedata}
846 '''Main function when invoked directly from the command line.'''
848 options, filenames = optparser.parse_args()
851 optparser.print_help()
855 options.verbose = False
857 Globals.verbose_options = options.verbose
859 for filename in filenames:
860 results = process_file(filename, None, options)
862 if not options.quiet:
863 print "Writing to " + results['headername'] + " and " + results['sourcename']
865 open(results['headername'], 'w').write(results['headerdata'])
866 open(results['sourcename'], 'w').write(results['sourcedata'])
869 '''Main function when invoked as a protoc plugin.'''
872 data = sys.stdin.read()
873 request = plugin_pb2.CodeGeneratorRequest.FromString(data)
876 args = shlex.split(request.parameter)
877 options, dummy = optparser.parse_args(args)
879 # We can't go printing stuff to stdout
880 Globals.verbose_options = False
881 options.verbose = False
884 response = plugin_pb2.CodeGeneratorResponse()
886 for filename in request.file_to_generate:
887 for fdesc in request.proto_file:
888 if fdesc.name == filename:
889 results = process_file(filename, fdesc, options)
891 f = response.file.add()
892 f.name = results['headername']
893 f.content = results['headerdata']
895 f = response.file.add()
896 f.name = results['sourcename']
897 f.content = results['sourcedata']
899 sys.stdout.write(response.SerializeToString())
901 if __name__ == '__main__':
902 # Check if we are running as a plugin under protoc
903 if 'protoc-gen-' in sys.argv[0]: