3 '''Generate header file for nanopb from a ProtoBuf FileDescriptorSet.'''
4 nanopb_version = "nanopb-0.2.4-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, encoded size)
42 FieldD = descriptor.FieldDescriptorProto
44 FieldD.TYPE_BOOL: ('bool', 'BOOL', 1),
45 FieldD.TYPE_DOUBLE: ('double', 'DOUBLE', 8),
46 FieldD.TYPE_FIXED32: ('uint32_t', 'FIXED32', 4),
47 FieldD.TYPE_FIXED64: ('uint64_t', 'FIXED64', 8),
48 FieldD.TYPE_FLOAT: ('float', 'FLOAT', 4),
49 FieldD.TYPE_INT32: ('int32_t', 'INT32', 5),
50 FieldD.TYPE_INT64: ('int64_t', 'INT64', 10),
51 FieldD.TYPE_SFIXED32: ('int32_t', 'SFIXED32', 4),
52 FieldD.TYPE_SFIXED64: ('int64_t', 'SFIXED64', 8),
53 FieldD.TYPE_SINT32: ('int32_t', 'SINT32', 5),
54 FieldD.TYPE_SINT64: ('int64_t', 'SINT64', 10),
55 FieldD.TYPE_UINT32: ('uint32_t', 'UINT32', 5),
56 FieldD.TYPE_UINT64: ('uint64_t', 'UINT64', 10)
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('.'))
86 def varint_max_size(max_value):
87 '''Returns the maximum number of bytes a varint can take when encoded.'''
88 for i in range(1, 11):
89 if (max_value >> (i * 7)) == 0:
91 raise ValueError("Value too large for varint: " + str(max_value))
93 assert varint_max_size(0) == 1
94 assert varint_max_size(127) == 1
95 assert varint_max_size(128) == 2
98 def __init__(self, names, desc, enum_options):
99 '''desc is EnumDescriptorProto'''
101 self.options = enum_options
102 self.names = names + desc.name
104 if enum_options.long_names:
105 self.values = [(self.names + x.name, x.number) for x in desc.value]
107 self.values = [(names + x.name, x.number) for x in desc.value]
109 self.value_longnames = [self.names + x.name for x in desc.value]
112 result = 'typedef enum _%s {\n' % self.names
113 result += ',\n'.join([" %s = %d" % x for x in self.values])
114 result += '\n} %s;' % self.names
118 def __init__(self, struct_name, desc, field_options):
119 '''desc is FieldDescriptorProto'''
120 self.tag = desc.number
121 self.struct_name = struct_name
122 self.name = desc.name
125 self.max_count = None
129 # Parse field options
130 if field_options.HasField("max_size"):
131 self.max_size = field_options.max_size
133 if field_options.HasField("max_count"):
134 self.max_count = field_options.max_count
136 if desc.HasField('default_value'):
137 self.default = desc.default_value
139 # Check field rules, i.e. required/optional/repeated.
141 if desc.label == FieldD.LABEL_REQUIRED:
142 self.rules = 'REQUIRED'
143 elif desc.label == FieldD.LABEL_OPTIONAL:
144 self.rules = 'OPTIONAL'
145 elif desc.label == FieldD.LABEL_REPEATED:
146 self.rules = 'REPEATED'
147 if self.max_count is None:
148 can_be_static = False
150 self.array_decl = '[%d]' % self.max_count
152 raise NotImplementedError(desc.label)
154 # Decide the C data type to use in the struct.
155 if datatypes.has_key(desc.type):
156 self.ctype, self.pbtype, self.enc_size = datatypes[desc.type]
157 elif desc.type == FieldD.TYPE_ENUM:
159 self.ctype = names_from_type_name(desc.type_name)
160 if self.default is not None:
161 self.default = self.ctype + self.default
162 self.enc_size = 5 # protoc rejects enum values > 32 bits
163 elif desc.type == FieldD.TYPE_STRING:
164 self.pbtype = 'STRING'
165 if self.max_size is None:
166 can_be_static = False
169 self.array_decl += '[%d]' % self.max_size
170 self.enc_size = varint_max_size(self.max_size) + self.max_size
171 elif desc.type == FieldD.TYPE_BYTES:
172 self.pbtype = 'BYTES'
173 if self.max_size is None:
174 can_be_static = False
176 self.ctype = self.struct_name + self.name + 't'
177 self.enc_size = varint_max_size(self.max_size) + self.max_size
178 elif desc.type == FieldD.TYPE_MESSAGE:
179 self.pbtype = 'MESSAGE'
180 self.ctype = self.submsgname = names_from_type_name(desc.type_name)
181 self.enc_size = None # Needs to be filled in after the message type is available
183 raise NotImplementedError(desc.type)
185 if field_options.type == nanopb_pb2.FT_DEFAULT:
187 field_options.type = nanopb_pb2.FT_STATIC
189 field_options.type = nanopb_pb2.FT_CALLBACK
191 if field_options.type == nanopb_pb2.FT_STATIC and not can_be_static:
192 raise Exception("Field %s is defined as static, but max_size or max_count is not given." % self.name)
194 if field_options.type == nanopb_pb2.FT_STATIC:
195 self.allocation = 'STATIC'
196 elif field_options.type == nanopb_pb2.FT_CALLBACK:
197 self.allocation = 'CALLBACK'
198 self.ctype = 'pb_callback_t'
201 raise NotImplementedError(field_options.type)
203 def __cmp__(self, other):
204 return cmp(self.tag, other.tag)
207 if self.rules == 'OPTIONAL' and self.allocation == 'STATIC':
208 result = ' bool has_' + self.name + ';\n'
209 elif self.rules == 'REPEATED' and self.allocation == 'STATIC':
210 result = ' size_t ' + self.name + '_count;\n'
213 result += ' %s %s%s;' % (self.ctype, self.name, self.array_decl)
217 '''Return definitions for any special types this field might need.'''
218 if self.pbtype == 'BYTES' and self.allocation == 'STATIC':
219 result = 'typedef struct {\n'
220 result += ' size_t size;\n'
221 result += ' uint8_t bytes[%d];\n' % self.max_size
222 result += '} %s;\n' % self.ctype
227 def default_decl(self, declaration_only = False):
228 '''Return definition for this field's default value.'''
229 if self.default is None:
232 ctype, default = self.ctype, self.default
235 if self.pbtype == 'STRING':
236 if self.allocation != 'STATIC':
237 return None # Not implemented
239 array_decl = '[%d]' % self.max_size
240 default = str(self.default).encode('string_escape')
241 default = default.replace('"', '\\"')
242 default = '"' + default + '"'
243 elif self.pbtype == 'BYTES':
244 if self.allocation != 'STATIC':
245 return None # Not implemented
247 data = self.default.decode('string_escape')
248 data = ['0x%02x' % ord(c) for c in data]
249 default = '{%d, {%s}}' % (len(data), ','.join(data))
252 return 'extern const %s %s_default%s;' % (ctype, self.struct_name + self.name, array_decl)
254 return 'const %s %s_default%s = %s;' % (ctype, self.struct_name + self.name, array_decl, default)
257 '''Return the #define for the tag number of this field.'''
258 identifier = '%s_%s_tag' % (self.struct_name, self.name)
259 return '#define %-40s %d\n' % (identifier, self.tag)
261 def pb_field_t(self, prev_field_name):
262 '''Return the pb_field_t initializer to use in the constant array.
263 prev_field_name is the name of the previous field or None.
265 result = ' PB_FIELD2(%3d, ' % self.tag
266 result += '%-8s, ' % self.pbtype
267 result += '%s, ' % self.rules
268 result += '%s, ' % self.allocation
269 result += '%s, ' % ("FIRST" if not prev_field_name else "OTHER")
270 result += '%s, ' % self.struct_name
271 result += '%s, ' % self.name
272 result += '%s, ' % (prev_field_name or self.name)
274 if self.pbtype == 'MESSAGE':
275 result += '&%s_fields)' % self.submsgname
276 elif self.default is None:
278 elif self.pbtype in ['BYTES', 'STRING'] and self.allocation != 'STATIC':
279 result += '0)' # Arbitrary size default values not implemented
281 result += '&%s_default)' % (self.struct_name + self.name)
285 def largest_field_value(self):
286 '''Determine if this field needs 16bit or 32bit pb_field_t structure to compile properly.
287 Returns numeric value or a C-expression for assert.'''
288 if self.pbtype == 'MESSAGE':
289 if self.rules == 'REPEATED' and self.allocation == 'STATIC':
290 return 'pb_membersize(%s, %s[0])' % (self.struct_name, self.name)
292 return 'pb_membersize(%s, %s)' % (self.struct_name, self.name)
294 return max(self.tag, self.max_size, self.max_count)
296 def encoded_size(self, allmsgs):
297 '''Return the maximum size that this field can take when encoded,
298 including the field tag. If the size cannot be determined, returns
301 if self.allocation != 'STATIC':
304 encsize = self.enc_size
305 if self.pbtype == 'MESSAGE':
307 if msg.name == self.submsgname:
308 encsize = msg.encoded_size(allmsgs)
310 return None # Submessage size is indeterminate
311 encsize += varint_max_size(encsize) # submsg length is encoded also
314 # Submessage cannot be found, this currently occurs when
315 # the submessage type is defined in a different file.
319 raise RuntimeError("Could not determine encoded size for %s.%s"
320 % (self.struct_name, self.name))
322 encsize += varint_max_size(self.tag << 3) # Tag + wire type
324 if self.rules == 'REPEATED':
325 # Decoders must be always able to handle unpacked arrays.
326 # Therefore we have to reserve space for it, even though
327 # we emit packed arrays ourselves.
328 encsize *= self.max_count
333 class ExtensionRange(Field):
334 def __init__(self, struct_name, range_start, field_options):
335 '''Implements a special pb_extension_t* field in an extensible message
336 structure. The range_start signifies the index at which the extensions
337 start. Not necessarily all tags above this are extensions, it is merely
338 a speed optimization.
340 self.tag = range_start
341 self.struct_name = struct_name
342 self.name = 'extensions'
343 self.pbtype = 'EXTENSION'
344 self.rules = 'OPTIONAL'
345 self.allocation = 'CALLBACK'
346 self.ctype = 'pb_extension_t'
353 return ' pb_extension_t *extensions;'
361 def encoded_size(self, allmsgs):
362 # We exclude extensions from the count, because they cannot be known
363 # until runtime. Other option would be to return None here, but this
364 # way the value remains useful if extensions are not used.
367 class ExtensionField(Field):
368 def __init__(self, struct_name, desc, field_options):
369 self.fullname = struct_name + desc.name
370 self.extendee_name = names_from_type_name(desc.extendee)
371 Field.__init__(self, self.fullname + 'struct', desc, field_options)
373 if self.rules != 'OPTIONAL':
377 self.rules = 'OPTEXT'
379 def extension_decl(self):
380 '''Declaration of the extension type in the .pb.h file'''
382 msg = '/* Extension field %s was skipped because only "optional"\n' % self.fullname
383 msg +=' type of extension fields is currently supported. */\n'
386 return 'extern const pb_extension_type_t %s;\n' % self.fullname
388 def extension_def(self):
389 '''Definition of the extension type in the .pb.c file'''
394 result = 'typedef struct {\n'
396 result += '\n} %s;\n\n' % self.struct_name
397 result += ('static const pb_field_t %s_field = \n %s;\n\n' %
398 (self.fullname, self.pb_field_t(None)))
399 result += 'const pb_extension_type_t %s = {\n' % self.fullname
402 result += ' &%s_field\n' % self.fullname
407 # ---------------------------------------------------------------------------
408 # Generation of messages (structures)
409 # ---------------------------------------------------------------------------
413 def __init__(self, names, desc, message_options):
418 field_options = get_nanopb_suboptions(f, message_options, self.name + f.name)
419 if field_options.type != nanopb_pb2.FT_IGNORE:
420 self.fields.append(Field(self.name, f, field_options))
422 if len(desc.extension_range) > 0:
423 field_options = get_nanopb_suboptions(desc, message_options, self.name + 'extensions')
424 range_start = min([r.start for r in desc.extension_range])
425 if field_options.type != nanopb_pb2.FT_IGNORE:
426 self.fields.append(ExtensionRange(self.name, range_start, field_options))
428 self.packed = message_options.packed_struct
429 self.ordered_fields = self.fields[:]
430 self.ordered_fields.sort()
432 def get_dependencies(self):
433 '''Get list of type names that this structure refers to.'''
434 return [str(field.ctype) for field in self.fields]
437 result = 'typedef struct _%s {\n' % self.name
439 if not self.ordered_fields:
440 # Empty structs are not allowed in C standard.
441 # Therefore add a dummy field if an empty message occurs.
442 result += ' uint8_t dummy_field;'
444 result += '\n'.join([str(f) for f in self.ordered_fields])
448 result += ' pb_packed'
450 result += ' %s;' % self.name
453 result = 'PB_PACKED_STRUCT_START\n' + result
454 result += '\nPB_PACKED_STRUCT_END'
460 for field in self.fields:
461 types = field.types()
462 if types is not None:
463 result += types + '\n'
466 def default_decl(self, declaration_only = False):
468 for field in self.fields:
469 default = field.default_decl(declaration_only)
470 if default is not None:
471 result += default + '\n'
474 def fields_declaration(self):
475 result = 'extern const pb_field_t %s_fields[%d];' % (self.name, len(self.fields) + 1)
478 def fields_definition(self):
479 result = 'const pb_field_t %s_fields[%d] = {\n' % (self.name, len(self.fields) + 1)
482 for field in self.ordered_fields:
483 result += field.pb_field_t(prev)
487 result += ' PB_LAST_FIELD\n};'
490 def encoded_size(self, allmsgs):
491 '''Return the maximum size that this message can take when encoded.
492 If the size cannot be determined, returns None.
495 for field in self.fields:
496 fsize = field.encoded_size(allmsgs)
504 # ---------------------------------------------------------------------------
505 # Processing of entire .proto files
506 # ---------------------------------------------------------------------------
509 def iterate_messages(desc, names = Names()):
510 '''Recursively find all messages. For each, yield name, DescriptorProto.'''
511 if hasattr(desc, 'message_type'):
512 submsgs = desc.message_type
514 submsgs = desc.nested_type
516 for submsg in submsgs:
517 sub_names = names + submsg.name
518 yield sub_names, submsg
520 for x in iterate_messages(submsg, sub_names):
523 def iterate_extensions(desc, names = Names()):
524 '''Recursively find all extensions.
525 For each, yield name, FieldDescriptorProto.
527 for extension in desc.extension:
528 yield names, extension
530 for subname, subdesc in iterate_messages(desc, names):
531 for extension in subdesc.extension:
532 yield subname, extension
534 def parse_file(fdesc, file_options):
535 '''Takes a FileDescriptorProto and returns tuple (enums, messages, extensions).'''
542 base_name = Names(fdesc.package.split('.'))
546 for enum in fdesc.enum_type:
547 enum_options = get_nanopb_suboptions(enum, file_options, base_name + enum.name)
548 enums.append(Enum(base_name, enum, enum_options))
550 for names, message in iterate_messages(fdesc, base_name):
551 message_options = get_nanopb_suboptions(message, file_options, names)
552 messages.append(Message(names, message, message_options))
553 for enum in message.enum_type:
554 enum_options = get_nanopb_suboptions(enum, message_options, names + enum.name)
555 enums.append(Enum(names, enum, enum_options))
557 for names, extension in iterate_extensions(fdesc, base_name):
558 field_options = get_nanopb_suboptions(extension, file_options, names)
559 if field_options.type != nanopb_pb2.FT_IGNORE:
560 extensions.append(ExtensionField(names, extension, field_options))
562 # Fix field default values where enum short names are used.
564 if not enum.options.long_names:
565 for message in messages:
566 for field in message.fields:
567 if field.default in enum.value_longnames:
568 idx = enum.value_longnames.index(field.default)
569 field.default = enum.values[idx][0]
571 return enums, messages, extensions
575 From http://code.activestate.com/recipes/577413-topological-sort/
576 This function is under the MIT license.
578 for k, v in data.items():
579 v.discard(k) # Ignore self dependencies
580 extra_items_in_deps = reduce(set.union, data.values(), set()) - set(data.keys())
581 data.update(dict([(item, set()) for item in extra_items_in_deps]))
583 ordered = set(item for item,dep in data.items() if not dep)
586 for item in sorted(ordered):
588 data = dict([(item, (dep - ordered)) for item,dep in data.items()
589 if item not in ordered])
590 assert not data, "A cyclic dependency exists amongst %r" % data
592 def sort_dependencies(messages):
593 '''Sort a list of Messages based on dependencies.'''
596 for message in messages:
597 dependencies[str(message.name)] = set(message.get_dependencies())
598 message_by_name[str(message.name)] = message
600 for msgname in toposort2(dependencies):
601 if msgname in message_by_name:
602 yield message_by_name[msgname]
604 def make_identifier(headername):
605 '''Make #ifndef identifier that contains uppercase A-Z and digits 0-9'''
607 for c in headername.upper():
614 def generate_header(dependencies, headername, enums, messages, extensions, options):
615 '''Generate content for a header file.
616 Generates strings, which should be concatenated and stored to file.
619 yield '/* Automatically generated nanopb header */\n'
620 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
622 symbol = make_identifier(headername)
623 yield '#ifndef _PB_%s_\n' % symbol
624 yield '#define _PB_%s_\n' % symbol
626 yield options.libformat % ('pb.h')
628 # no %s specified - use whatever was passed in as options.libformat
629 yield options.libformat
632 for dependency in dependencies:
633 noext = os.path.splitext(dependency)[0]
634 yield options.genformat % (noext + '.' + options.extension + '.h')
637 yield '#ifdef __cplusplus\n'
638 yield 'extern "C" {\n'
641 yield '/* Enum definitions */\n'
643 yield str(enum) + '\n\n'
645 yield '/* Struct definitions */\n'
646 for msg in sort_dependencies(messages):
648 yield str(msg) + '\n\n'
651 yield '/* Extensions */\n'
652 for extension in extensions:
653 yield extension.extension_decl()
656 yield '/* Default values for struct fields */\n'
658 yield msg.default_decl(True)
661 yield '/* Field tags (for use in manual encoding/decoding) */\n'
662 for msg in sort_dependencies(messages):
663 for field in msg.fields:
667 yield '/* Struct field encoding specification for nanopb */\n'
669 yield msg.fields_declaration() + '\n'
672 yield '/* Maximum encoded size of messages (where known) */\n'
674 msize = msg.encoded_size(messages)
675 if msize is not None:
676 identifier = '%s_size' % msg.name
677 yield '#define %-40s %d\n' % (identifier, msize)
680 yield '#ifdef __cplusplus\n'
681 yield '} /* extern "C" */\n'
687 def generate_source(headername, enums, messages, extensions, options):
688 '''Generate content for a source file.'''
690 yield '/* Automatically generated nanopb constant definitions */\n'
691 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
692 yield options.genformat % (headername)
696 yield msg.default_decl(False)
701 yield msg.fields_definition() + '\n\n'
703 for ext in extensions:
704 yield ext.extension_def() + '\n'
706 # Add checks for numeric limits
708 count_required_fields = lambda m: len([f for f in msg.fields if f.rules == 'REQUIRED'])
709 largest_msg = max(messages, key = count_required_fields)
710 largest_count = count_required_fields(largest_msg)
711 if largest_count > 64:
712 yield '\n/* Check that missing required fields will be properly detected */\n'
713 yield '#if PB_MAX_REQUIRED_FIELDS < %d\n' % largest_count
714 yield '#error Properly detecting missing required fields in %s requires \\\n' % largest_msg.name
715 yield ' setting PB_MAX_REQUIRED_FIELDS to %d or more.\n' % largest_count
723 checks_msgnames.append(msg.name)
724 for field in msg.fields:
725 status = field.largest_field_value()
726 if isinstance(status, (str, unicode)):
727 checks.append(status)
730 worst_field = str(field.struct_name) + '.' + str(field.name)
732 if worst > 255 or checks:
733 yield '\n/* Check that field information fits in pb_field_t */\n'
736 yield '#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT)\n'
738 yield '#error Field descriptor for %s is too large. Define PB_FIELD_16BIT to fix this.\n' % worst_field
740 assertion = ' && '.join(str(c) + ' < 256' for c in checks)
741 msgs = '_'.join(str(n) for n in checks_msgnames)
742 yield 'STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
745 if worst > 65535 or checks:
746 yield '#if !defined(PB_FIELD_32BIT)\n'
748 yield '#error Field descriptor for %s is too large. Define PB_FIELD_32BIT to fix this.\n' % worst_field
750 assertion = ' && '.join(str(c) + ' < 65536' for c in checks)
751 msgs = '_'.join(str(n) for n in checks_msgnames)
752 yield 'STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
755 # Add check for sizeof(double)
758 for field in msg.fields:
759 if field.ctype == 'double':
764 yield '/* On some platforms (such as AVR), double is really float.\n'
765 yield ' * These are not directly supported by nanopb, but see example_avr_double.\n'
766 yield ' * To get rid of this error, remove any double fields from your .proto.\n'
768 yield 'STATIC_ASSERT(sizeof(double) == 8, DOUBLE_MUST_BE_8_BYTES)\n'
772 # ---------------------------------------------------------------------------
773 # Options parsing for the .proto files
774 # ---------------------------------------------------------------------------
776 from fnmatch import fnmatch
778 def read_options_file(infile):
779 '''Parse a separate options file to list:
780 [(namemask, options), ...]
785 if not line or line.startswith('//') or line.startswith('#'):
788 parts = line.split(None, 1)
789 opts = nanopb_pb2.NanoPBOptions()
790 text_format.Merge(parts[1], opts)
791 results.append((parts[0], opts))
796 '''Ugly global variables, should find a good way to pass these.'''
797 verbose_options = False
798 separate_options = []
800 def get_nanopb_suboptions(subdesc, options, name):
801 '''Get copy of options, and merge information from subdesc.'''
802 new_options = nanopb_pb2.NanoPBOptions()
803 new_options.CopyFrom(options)
805 # Handle options defined in a separate file
806 dotname = '.'.join(name.parts)
807 for namemask, options in Globals.separate_options:
808 if fnmatch(dotname, namemask):
809 new_options.MergeFrom(options)
811 # Handle options defined in .proto
812 if isinstance(subdesc.options, descriptor.FieldOptions):
813 ext_type = nanopb_pb2.nanopb
814 elif isinstance(subdesc.options, descriptor.FileOptions):
815 ext_type = nanopb_pb2.nanopb_fileopt
816 elif isinstance(subdesc.options, descriptor.MessageOptions):
817 ext_type = nanopb_pb2.nanopb_msgopt
818 elif isinstance(subdesc.options, descriptor.EnumOptions):
819 ext_type = nanopb_pb2.nanopb_enumopt
821 raise Exception("Unknown options type")
823 if subdesc.options.HasExtension(ext_type):
824 ext = subdesc.options.Extensions[ext_type]
825 new_options.MergeFrom(ext)
827 if Globals.verbose_options:
828 print "Options for " + dotname + ":"
829 print text_format.MessageToString(new_options)
834 # ---------------------------------------------------------------------------
835 # Command line interface
836 # ---------------------------------------------------------------------------
840 from optparse import OptionParser
842 optparser = OptionParser(
843 usage = "Usage: nanopb_generator.py [options] file.pb ...",
844 epilog = "Compile file.pb from file.proto by: 'protoc -ofile.pb file.proto'. " +
845 "Output will be written to file.pb.h and file.pb.c.")
846 optparser.add_option("-x", dest="exclude", metavar="FILE", action="append", default=[],
847 help="Exclude file from generated #include list.")
848 optparser.add_option("-e", "--extension", dest="extension", metavar="EXTENSION", default="pb",
849 help="Set extension to use instead of 'pb' for generated files. [default: %default]")
850 optparser.add_option("-f", "--options-file", dest="options_file", metavar="FILE", default="%s.options",
851 help="Set name of a separate generator options file.")
852 optparser.add_option("-Q", "--generated-include-format", dest="genformat",
853 metavar="FORMAT", default='#include "%s"\n',
854 help="Set format string to use for including other .pb.h files. [default: %default]")
855 optparser.add_option("-L", "--library-include-format", dest="libformat",
856 metavar="FORMAT", default='#include <%s>\n',
857 help="Set format string to use for including the nanopb pb.h header. [default: %default]")
858 optparser.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False,
859 help="Don't print anything except errors.")
860 optparser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
861 help="Print more information.")
862 optparser.add_option("-s", dest="settings", metavar="OPTION:VALUE", action="append", default=[],
863 help="Set generator option (max_size, max_count etc.).")
865 def process_file(filename, fdesc, options):
866 '''Process a single file.
867 filename: The full path to the .proto or .pb source file, as string.
868 fdesc: The loaded FileDescriptorSet, or None to read from the input file.
869 options: Command line options as they come from OptionsParser.
872 {'headername': Name of header file,
873 'headerdata': Data for the .h header file,
874 'sourcename': Name of the source code file,
875 'sourcedata': Data for the .c source code file
878 toplevel_options = nanopb_pb2.NanoPBOptions()
879 for s in options.settings:
880 text_format.Merge(s, toplevel_options)
883 data = open(filename, 'rb').read()
884 fdesc = descriptor.FileDescriptorSet.FromString(data).file[0]
886 # Check if there is a separate .options file
888 optfilename = options.options_file % os.path.splitext(filename)[0]
890 # No %s specified, use the filename as-is
891 optfilename = options.options_file
894 print 'Reading options from ' + optfilename
896 if os.path.isfile(optfilename):
897 Globals.separate_options = read_options_file(open(optfilename, "rU"))
899 Globals.separate_options = []
902 file_options = get_nanopb_suboptions(fdesc, toplevel_options, Names([filename]))
903 enums, messages, extensions = parse_file(fdesc, file_options)
905 # Decide the file names
906 noext = os.path.splitext(filename)[0]
907 headername = noext + '.' + options.extension + '.h'
908 sourcename = noext + '.' + options.extension + '.c'
909 headerbasename = os.path.basename(headername)
911 # List of .proto files that should not be included in the C header file
912 # even if they are mentioned in the source .proto.
913 excludes = ['nanopb.proto', 'google/protobuf/descriptor.proto'] + options.exclude
914 dependencies = [d for d in fdesc.dependency if d not in excludes]
916 headerdata = ''.join(generate_header(dependencies, headerbasename, enums,
917 messages, extensions, options))
919 sourcedata = ''.join(generate_source(headerbasename, enums,
920 messages, extensions, options))
922 return {'headername': headername, 'headerdata': headerdata,
923 'sourcename': sourcename, 'sourcedata': sourcedata}
926 '''Main function when invoked directly from the command line.'''
928 options, filenames = optparser.parse_args()
931 optparser.print_help()
935 options.verbose = False
937 Globals.verbose_options = options.verbose
939 for filename in filenames:
940 results = process_file(filename, None, options)
942 if not options.quiet:
943 print "Writing to " + results['headername'] + " and " + results['sourcename']
945 open(results['headername'], 'w').write(results['headerdata'])
946 open(results['sourcename'], 'w').write(results['sourcedata'])
949 '''Main function when invoked as a protoc plugin.'''
952 data = sys.stdin.read()
953 request = plugin_pb2.CodeGeneratorRequest.FromString(data)
956 args = shlex.split(request.parameter)
957 options, dummy = optparser.parse_args(args)
959 # We can't go printing stuff to stdout
960 Globals.verbose_options = False
961 options.verbose = False
964 response = plugin_pb2.CodeGeneratorResponse()
966 for filename in request.file_to_generate:
967 for fdesc in request.proto_file:
968 if fdesc.name == filename:
969 results = process_file(filename, fdesc, options)
971 f = response.file.add()
972 f.name = results['headername']
973 f.content = results['headerdata']
975 f = response.file.add()
976 f.name = results['sourcename']
977 f.content = results['sourcedata']
979 sys.stdout.write(response.SerializeToString())
981 if __name__ == '__main__':
982 # Check if we are running as a plugin under protoc
983 if 'protoc-gen-' in sys.argv[0]: