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_FIELD2(%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)
256 result += '%s, ' % ("first" if not prev_field_name else "other")
258 if self.pbtype == 'MESSAGE':
259 result += '&%s_fields)' % self.submsgname
260 elif self.default is None:
262 elif self.pbtype in ['BYTES', 'STRING'] and self.allocation != 'STATIC':
263 result += '0)' # Arbitrary size default values not implemented
265 result += '&%s_default)' % (self.struct_name + self.name)
269 def largest_field_value(self):
270 '''Determine if this field needs 16bit or 32bit pb_field_t structure to compile properly.
271 Returns numeric value or a C-expression for assert.'''
272 if self.pbtype == 'MESSAGE':
273 if self.rules == 'REPEATED' and self.allocation == 'STATIC':
274 return 'pb_membersize(%s, %s[0])' % (self.struct_name, self.name)
276 return 'pb_membersize(%s, %s)' % (self.struct_name, self.name)
278 return max(self.tag, self.max_size, self.max_count)
281 class ExtensionRange(Field):
282 def __init__(self, struct_name, range_start, field_options):
283 '''Implements a special pb_extension_t* field in an extensible message
284 structure. The range_start signifies the index at which the extensions
285 start. Not necessarily all tags above this are extensions, it is merely
286 a speed optimization.
288 self.tag = range_start
289 self.struct_name = struct_name
290 self.name = 'extensions'
291 self.pbtype = 'EXTENSION'
292 self.rules = 'OPTIONAL'
293 self.allocation = 'CALLBACK'
294 self.ctype = 'pb_extension_t'
301 return ' pb_extension_t *extensions;'
309 class ExtensionField(Field):
310 def __init__(self, struct_name, desc, field_options):
311 self.fullname = struct_name + desc.name
312 self.extendee_name = names_from_type_name(desc.extendee)
313 Field.__init__(self, self.fullname + 'struct', desc, field_options)
315 if self.rules != 'OPTIONAL':
319 self.rules = 'OPTEXT'
321 def extension_decl(self):
322 '''Declaration of the extension type in the .pb.h file'''
324 msg = '/* Extension field %s was skipped because only "optional"\n' % self.fullname
325 msg +=' type of extension fields is currently supported. */\n'
328 return 'extern const pb_extension_type_t %s;\n' % self.fullname
330 def extension_def(self):
331 '''Definition of the extension type in the .pb.c file'''
336 result = 'typedef struct {\n'
338 result += '\n} %s;\n\n' % self.struct_name
339 result += ('static const pb_field_t %s_field = \n %s;\n\n' %
340 (self.fullname, self.pb_field_t(None)))
341 result += 'const pb_extension_type_t %s = {\n' % self.fullname
344 result += ' &%s_field\n' % self.fullname
349 # ---------------------------------------------------------------------------
350 # Generation of messages (structures)
351 # ---------------------------------------------------------------------------
355 def __init__(self, names, desc, message_options):
360 field_options = get_nanopb_suboptions(f, message_options, self.name + f.name)
361 if field_options.type != nanopb_pb2.FT_IGNORE:
362 self.fields.append(Field(self.name, f, field_options))
364 if len(desc.extension_range) > 0:
365 field_options = get_nanopb_suboptions(desc, message_options, self.name + 'extensions')
366 range_start = min([r.start for r in desc.extension_range])
367 if field_options.type != nanopb_pb2.FT_IGNORE:
368 self.fields.append(ExtensionRange(self.name, range_start, field_options))
370 self.packed = message_options.packed_struct
371 self.ordered_fields = self.fields[:]
372 self.ordered_fields.sort()
374 def get_dependencies(self):
375 '''Get list of type names that this structure refers to.'''
376 return [str(field.ctype) for field in self.fields]
379 result = 'typedef struct _%s {\n' % self.name
381 if not self.ordered_fields:
382 # Empty structs are not allowed in C standard.
383 # Therefore add a dummy field if an empty message occurs.
384 result += ' uint8_t dummy_field;'
386 result += '\n'.join([str(f) for f in self.ordered_fields])
390 result += ' pb_packed'
392 result += ' %s;' % self.name
395 result = 'PB_PACKED_STRUCT_START\n' + result
396 result += '\nPB_PACKED_STRUCT_END'
402 for field in self.fields:
403 types = field.types()
404 if types is not None:
405 result += types + '\n'
408 def default_decl(self, declaration_only = False):
410 for field in self.fields:
411 default = field.default_decl(declaration_only)
412 if default is not None:
413 result += default + '\n'
416 def fields_declaration(self):
417 result = 'extern const pb_field_t %s_fields[%d];' % (self.name, len(self.fields) + 1)
420 def fields_definition(self):
421 result = 'const pb_field_t %s_fields[%d] = {\n' % (self.name, len(self.fields) + 1)
424 for field in self.ordered_fields:
425 result += field.pb_field_t(prev)
429 result += ' PB_LAST_FIELD\n};'
434 # ---------------------------------------------------------------------------
435 # Processing of entire .proto files
436 # ---------------------------------------------------------------------------
439 def iterate_messages(desc, names = Names()):
440 '''Recursively find all messages. For each, yield name, DescriptorProto.'''
441 if hasattr(desc, 'message_type'):
442 submsgs = desc.message_type
444 submsgs = desc.nested_type
446 for submsg in submsgs:
447 sub_names = names + submsg.name
448 yield sub_names, submsg
450 for x in iterate_messages(submsg, sub_names):
453 def iterate_extensions(desc, names = Names()):
454 '''Recursively find all extensions.
455 For each, yield name, FieldDescriptorProto.
457 for extension in desc.extension:
458 yield names, extension
460 for subname, subdesc in iterate_messages(desc, names):
461 for extension in subdesc.extension:
462 yield subname, extension
464 def parse_file(fdesc, file_options):
465 '''Takes a FileDescriptorProto and returns tuple (enums, messages, extensions).'''
472 base_name = Names(fdesc.package.split('.'))
476 for enum in fdesc.enum_type:
477 enum_options = get_nanopb_suboptions(enum, file_options, base_name + enum.name)
478 enums.append(Enum(base_name, enum, enum_options))
480 for names, message in iterate_messages(fdesc, base_name):
481 message_options = get_nanopb_suboptions(message, file_options, names)
482 messages.append(Message(names, message, message_options))
483 for enum in message.enum_type:
484 enum_options = get_nanopb_suboptions(enum, message_options, names + enum.name)
485 enums.append(Enum(names, enum, enum_options))
487 for names, extension in iterate_extensions(fdesc, base_name):
488 field_options = get_nanopb_suboptions(extension, file_options, names)
489 if field_options.type != nanopb_pb2.FT_IGNORE:
490 extensions.append(ExtensionField(names, extension, field_options))
492 # Fix field default values where enum short names are used.
494 if not enum.options.long_names:
495 for message in messages:
496 for field in message.fields:
497 if field.default in enum.value_longnames:
498 idx = enum.value_longnames.index(field.default)
499 field.default = enum.values[idx][0]
501 return enums, messages, extensions
505 From http://code.activestate.com/recipes/577413-topological-sort/
506 This function is under the MIT license.
508 for k, v in data.items():
509 v.discard(k) # Ignore self dependencies
510 extra_items_in_deps = reduce(set.union, data.values(), set()) - set(data.keys())
511 data.update(dict([(item, set()) for item in extra_items_in_deps]))
513 ordered = set(item for item,dep in data.items() if not dep)
516 for item in sorted(ordered):
518 data = dict([(item, (dep - ordered)) for item,dep in data.items()
519 if item not in ordered])
520 assert not data, "A cyclic dependency exists amongst %r" % data
522 def sort_dependencies(messages):
523 '''Sort a list of Messages based on dependencies.'''
526 for message in messages:
527 dependencies[str(message.name)] = set(message.get_dependencies())
528 message_by_name[str(message.name)] = message
530 for msgname in toposort2(dependencies):
531 if msgname in message_by_name:
532 yield message_by_name[msgname]
534 def make_identifier(headername):
535 '''Make #ifndef identifier that contains uppercase A-Z and digits 0-9'''
537 for c in headername.upper():
544 def generate_header(dependencies, headername, enums, messages, extensions, options):
545 '''Generate content for a header file.
546 Generates strings, which should be concatenated and stored to file.
549 yield '/* Automatically generated nanopb header */\n'
550 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
552 symbol = make_identifier(headername)
553 yield '#ifndef _PB_%s_\n' % symbol
554 yield '#define _PB_%s_\n' % symbol
556 yield options.libformat % ('pb.h')
558 # no %s specified - use whatever was passed in as options.libformat
559 yield options.libformat
562 for dependency in dependencies:
563 noext = os.path.splitext(dependency)[0]
564 yield options.genformat % (noext + '.' + options.extension + '.h')
567 yield '#ifdef __cplusplus\n'
568 yield 'extern "C" {\n'
571 yield '/* Enum definitions */\n'
573 yield str(enum) + '\n\n'
575 yield '/* Struct definitions */\n'
576 for msg in sort_dependencies(messages):
578 yield str(msg) + '\n\n'
581 yield '/* Extensions */\n'
582 for extension in extensions:
583 yield extension.extension_decl()
586 yield '/* Default values for struct fields */\n'
588 yield msg.default_decl(True)
591 yield '/* Field tags (for use in manual encoding/decoding) */\n'
592 for msg in sort_dependencies(messages):
593 for field in msg.fields:
597 yield '/* Struct field encoding specification for nanopb */\n'
599 yield msg.fields_declaration() + '\n'
601 yield '\n#ifdef __cplusplus\n'
602 yield '} /* extern "C" */\n'
608 def generate_source(headername, enums, messages, extensions, options):
609 '''Generate content for a source file.'''
611 yield '/* Automatically generated nanopb constant definitions */\n'
612 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
613 yield options.genformat % (headername)
617 yield msg.default_decl(False)
622 yield msg.fields_definition() + '\n\n'
624 for ext in extensions:
625 yield ext.extension_def() + '\n'
627 # Add checks for numeric limits
629 count_required_fields = lambda m: len([f for f in msg.fields if f.rules == 'REQUIRED'])
630 largest_msg = max(messages, key = count_required_fields)
631 largest_count = count_required_fields(largest_msg)
632 if largest_count > 64:
633 yield '\n/* Check that missing required fields will be properly detected */\n'
634 yield '#if PB_MAX_REQUIRED_FIELDS < %d\n' % largest_count
635 yield '#error Properly detecting missing required fields in %s requires \\\n' % largest_msg.name
636 yield ' setting PB_MAX_REQUIRED_FIELDS to %d or more.\n' % largest_count
644 checks_msgnames.append(msg.name)
645 for field in msg.fields:
646 status = field.largest_field_value()
647 if isinstance(status, (str, unicode)):
648 checks.append(status)
651 worst_field = str(field.struct_name) + '.' + str(field.name)
653 if worst > 255 or checks:
654 yield '\n/* Check that field information fits in pb_field_t */\n'
657 yield '#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT)\n'
659 yield '#error Field descriptor for %s is too large. Define PB_FIELD_16BIT to fix this.\n' % worst_field
661 assertion = ' && '.join(str(c) + ' < 256' for c in checks)
662 msgs = '_'.join(str(n) for n in checks_msgnames)
663 yield 'STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
666 if worst > 65535 or checks:
667 yield '#if !defined(PB_FIELD_32BIT)\n'
669 yield '#error Field descriptor for %s is too large. Define PB_FIELD_32BIT to fix this.\n' % worst_field
671 assertion = ' && '.join(str(c) + ' < 65536' for c in checks)
672 msgs = '_'.join(str(n) for n in checks_msgnames)
673 yield 'STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
676 # Add check for sizeof(double)
679 for field in msg.fields:
680 if field.ctype == 'double':
685 yield '/* On some platforms (such as AVR), double is really float.\n'
686 yield ' * These are not directly supported by nanopb, but see example_avr_double.\n'
687 yield ' * To get rid of this error, remove any double fields from your .proto.\n'
689 yield 'STATIC_ASSERT(sizeof(double) == 8, DOUBLE_MUST_BE_8_BYTES)\n'
693 # ---------------------------------------------------------------------------
694 # Options parsing for the .proto files
695 # ---------------------------------------------------------------------------
697 from fnmatch import fnmatch
699 def read_options_file(infile):
700 '''Parse a separate options file to list:
701 [(namemask, options), ...]
706 if not line or line.startswith('//') or line.startswith('#'):
709 parts = line.split(None, 1)
710 opts = nanopb_pb2.NanoPBOptions()
711 text_format.Merge(parts[1], opts)
712 results.append((parts[0], opts))
717 '''Ugly global variables, should find a good way to pass these.'''
718 verbose_options = False
719 separate_options = []
721 def get_nanopb_suboptions(subdesc, options, name):
722 '''Get copy of options, and merge information from subdesc.'''
723 new_options = nanopb_pb2.NanoPBOptions()
724 new_options.CopyFrom(options)
726 # Handle options defined in a separate file
727 dotname = '.'.join(name.parts)
728 for namemask, options in Globals.separate_options:
729 if fnmatch(dotname, namemask):
730 new_options.MergeFrom(options)
732 # Handle options defined in .proto
733 if isinstance(subdesc.options, descriptor.FieldOptions):
734 ext_type = nanopb_pb2.nanopb
735 elif isinstance(subdesc.options, descriptor.FileOptions):
736 ext_type = nanopb_pb2.nanopb_fileopt
737 elif isinstance(subdesc.options, descriptor.MessageOptions):
738 ext_type = nanopb_pb2.nanopb_msgopt
739 elif isinstance(subdesc.options, descriptor.EnumOptions):
740 ext_type = nanopb_pb2.nanopb_enumopt
742 raise Exception("Unknown options type")
744 if subdesc.options.HasExtension(ext_type):
745 ext = subdesc.options.Extensions[ext_type]
746 new_options.MergeFrom(ext)
748 if Globals.verbose_options:
749 print "Options for " + dotname + ":"
750 print text_format.MessageToString(new_options)
755 # ---------------------------------------------------------------------------
756 # Command line interface
757 # ---------------------------------------------------------------------------
761 from optparse import OptionParser
763 optparser = OptionParser(
764 usage = "Usage: nanopb_generator.py [options] file.pb ...",
765 epilog = "Compile file.pb from file.proto by: 'protoc -ofile.pb file.proto'. " +
766 "Output will be written to file.pb.h and file.pb.c.")
767 optparser.add_option("-x", dest="exclude", metavar="FILE", action="append", default=[],
768 help="Exclude file from generated #include list.")
769 optparser.add_option("-e", "--extension", dest="extension", metavar="EXTENSION", default="pb",
770 help="Set extension to use instead of 'pb' for generated files. [default: %default]")
771 optparser.add_option("-f", "--options-file", dest="options_file", metavar="FILE", default="%s.options",
772 help="Set name of a separate generator options file.")
773 optparser.add_option("-Q", "--generated-include-format", dest="genformat",
774 metavar="FORMAT", default='#include "%s"\n',
775 help="Set format string to use for including other .pb.h files. [default: %default]")
776 optparser.add_option("-L", "--library-include-format", dest="libformat",
777 metavar="FORMAT", default='#include <%s>\n',
778 help="Set format string to use for including the nanopb pb.h header. [default: %default]")
779 optparser.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False,
780 help="Don't print anything except errors.")
781 optparser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
782 help="Print more information.")
783 optparser.add_option("-s", dest="settings", metavar="OPTION:VALUE", action="append", default=[],
784 help="Set generator option (max_size, max_count etc.).")
786 def process_file(filename, fdesc, options):
787 '''Process a single file.
788 filename: The full path to the .proto or .pb source file, as string.
789 fdesc: The loaded FileDescriptorSet, or None to read from the input file.
790 options: Command line options as they come from OptionsParser.
793 {'headername': Name of header file,
794 'headerdata': Data for the .h header file,
795 'sourcename': Name of the source code file,
796 'sourcedata': Data for the .c source code file
799 toplevel_options = nanopb_pb2.NanoPBOptions()
800 for s in options.settings:
801 text_format.Merge(s, toplevel_options)
804 data = open(filename, 'rb').read()
805 fdesc = descriptor.FileDescriptorSet.FromString(data).file[0]
807 # Check if there is a separate .options file
809 optfilename = options.options_file % os.path.splitext(filename)[0]
811 # No %s specified, use the filename as-is
812 optfilename = options.options_file
815 print 'Reading options from ' + optfilename
817 if os.path.isfile(optfilename):
818 Globals.separate_options = read_options_file(open(optfilename, "rU"))
820 Globals.separate_options = []
823 file_options = get_nanopb_suboptions(fdesc, toplevel_options, Names([filename]))
824 enums, messages, extensions = parse_file(fdesc, file_options)
826 # Decide the file names
827 noext = os.path.splitext(filename)[0]
828 headername = noext + '.' + options.extension + '.h'
829 sourcename = noext + '.' + options.extension + '.c'
830 headerbasename = os.path.basename(headername)
832 # List of .proto files that should not be included in the C header file
833 # even if they are mentioned in the source .proto.
834 excludes = ['nanopb.proto', 'google/protobuf/descriptor.proto'] + options.exclude
835 dependencies = [d for d in fdesc.dependency if d not in excludes]
837 headerdata = ''.join(generate_header(dependencies, headerbasename, enums,
838 messages, extensions, options))
840 sourcedata = ''.join(generate_source(headerbasename, enums,
841 messages, extensions, options))
843 return {'headername': headername, 'headerdata': headerdata,
844 'sourcename': sourcename, 'sourcedata': sourcedata}
847 '''Main function when invoked directly from the command line.'''
849 options, filenames = optparser.parse_args()
852 optparser.print_help()
856 options.verbose = False
858 Globals.verbose_options = options.verbose
860 for filename in filenames:
861 results = process_file(filename, None, options)
863 if not options.quiet:
864 print "Writing to " + results['headername'] + " and " + results['sourcename']
866 open(results['headername'], 'w').write(results['headerdata'])
867 open(results['sourcename'], 'w').write(results['sourcedata'])
870 '''Main function when invoked as a protoc plugin.'''
873 data = sys.stdin.read()
874 request = plugin_pb2.CodeGeneratorRequest.FromString(data)
877 args = shlex.split(request.parameter)
878 options, dummy = optparser.parse_args(args)
880 # We can't go printing stuff to stdout
881 Globals.verbose_options = False
882 options.verbose = False
885 response = plugin_pb2.CodeGeneratorResponse()
887 for filename in request.file_to_generate:
888 for fdesc in request.proto_file:
889 if fdesc.name == filename:
890 results = process_file(filename, fdesc, options)
892 f = response.file.add()
893 f.name = results['headername']
894 f.content = results['headerdata']
896 f = response.file.add()
897 f.name = results['sourcename']
898 f.content = results['sourcedata']
900 sys.stdout.write(response.SerializeToString())
902 if __name__ == '__main__':
903 # Check if we are running as a plugin under protoc
904 if 'protoc-gen-' in sys.argv[0]: