1 '''Generate header file for nanopb from a ProtoBuf FileDescriptorSet.'''
2 nanopb_version = "nanopb-0.2.1-dev"
5 import google.protobuf.descriptor_pb2 as descriptor
6 import google.protobuf.text_format as text_format
9 print "*************************************************************"
10 print "*** Could not import the Google protobuf Python libraries ***"
11 print "*** Try installing package 'python-protobuf' or similar. ***"
12 print "*************************************************************"
20 print "***************************************************************"
21 print "*** Could not import the precompiled nanopb_pb2.py. ***"
22 print "*** Run 'make' in the 'generator' folder to update the file.***"
23 print "***************************************************************"
32 # ---------------------------------------------------------------------------
33 # Generation of single fields
34 # ---------------------------------------------------------------------------
39 # Values are tuple (c type, pb type)
40 FieldD = descriptor.FieldDescriptorProto
42 FieldD.TYPE_BOOL: ('bool', 'BOOL'),
43 FieldD.TYPE_DOUBLE: ('double', 'DOUBLE'),
44 FieldD.TYPE_FIXED32: ('uint32_t', 'FIXED32'),
45 FieldD.TYPE_FIXED64: ('uint64_t', 'FIXED64'),
46 FieldD.TYPE_FLOAT: ('float', 'FLOAT'),
47 FieldD.TYPE_INT32: ('int32_t', 'INT32'),
48 FieldD.TYPE_INT64: ('int64_t', 'INT64'),
49 FieldD.TYPE_SFIXED32: ('int32_t', 'SFIXED32'),
50 FieldD.TYPE_SFIXED64: ('int64_t', 'SFIXED64'),
51 FieldD.TYPE_SINT32: ('int32_t', 'SINT32'),
52 FieldD.TYPE_SINT64: ('int64_t', 'SINT64'),
53 FieldD.TYPE_UINT32: ('uint32_t', 'UINT32'),
54 FieldD.TYPE_UINT64: ('uint64_t', 'UINT64')
58 '''Keeps a set of nested names and formats them to C identifier.'''
59 def __init__(self, parts = ()):
60 if isinstance(parts, Names):
62 self.parts = tuple(parts)
65 return '_'.join(self.parts)
67 def __add__(self, other):
68 if isinstance(other, (str, unicode)):
69 return Names(self.parts + (other,))
70 elif isinstance(other, tuple):
71 return Names(self.parts + other)
73 raise ValueError("Name parts should be of type str")
75 def __eq__(self, other):
76 return isinstance(other, Names) and self.parts == other.parts
78 def names_from_type_name(type_name):
79 '''Parse Names() from FieldDescriptorProto type_name'''
80 if type_name[0] != '.':
81 raise NotImplementedError("Lookup of non-absolute type names is not supported")
82 return Names(type_name[1:].split('.'))
85 def __init__(self, names, desc, enum_options):
86 '''desc is EnumDescriptorProto'''
88 self.options = enum_options
89 self.names = names + desc.name
91 if enum_options.long_names:
92 self.values = [(self.names + x.name, x.number) for x in desc.value]
94 self.values = [(names + x.name, x.number) for x in desc.value]
96 self.value_longnames = [self.names + x.name for x in desc.value]
99 result = 'typedef enum _%s {\n' % self.names
100 result += ',\n'.join([" %s = %d" % x for x in self.values])
101 result += '\n} %s;' % self.names
105 def __init__(self, struct_name, desc, field_options):
106 '''desc is FieldDescriptorProto'''
107 self.tag = desc.number
108 self.struct_name = struct_name
109 self.name = desc.name
112 self.max_count = None
115 # Parse field options
116 if field_options.HasField("max_size"):
117 self.max_size = field_options.max_size
119 if field_options.HasField("max_count"):
120 self.max_count = field_options.max_count
122 if desc.HasField('default_value'):
123 self.default = desc.default_value
125 # Check field rules, i.e. required/optional/repeated.
127 if desc.label == FieldD.LABEL_REQUIRED:
128 self.rules = 'REQUIRED'
129 elif desc.label == FieldD.LABEL_OPTIONAL:
130 self.rules = 'OPTIONAL'
131 elif desc.label == FieldD.LABEL_REPEATED:
132 self.rules = 'REPEATED'
133 if self.max_count is None:
134 can_be_static = False
136 self.array_decl = '[%d]' % self.max_count
138 raise NotImplementedError(desc.label)
140 # Decide the C data type to use in the struct.
141 if datatypes.has_key(desc.type):
142 self.ctype, self.pbtype = datatypes[desc.type]
143 elif desc.type == FieldD.TYPE_ENUM:
145 self.ctype = names_from_type_name(desc.type_name)
146 if self.default is not None:
147 self.default = self.ctype + self.default
148 elif desc.type == FieldD.TYPE_STRING:
149 self.pbtype = 'STRING'
150 if self.max_size is None:
151 can_be_static = False
154 self.array_decl += '[%d]' % self.max_size
155 elif desc.type == FieldD.TYPE_BYTES:
156 self.pbtype = 'BYTES'
157 if self.max_size is None:
158 can_be_static = False
160 self.ctype = self.struct_name + self.name + 't'
161 elif desc.type == FieldD.TYPE_MESSAGE:
162 self.pbtype = 'MESSAGE'
163 self.ctype = self.submsgname = names_from_type_name(desc.type_name)
165 raise NotImplementedError(desc.type)
167 if field_options.type == nanopb_pb2.FT_DEFAULT:
169 field_options.type = nanopb_pb2.FT_STATIC
171 field_options.type = nanopb_pb2.FT_CALLBACK
173 if field_options.type == nanopb_pb2.FT_STATIC and not can_be_static:
174 raise Exception("Field %s is defined as static, but max_size or max_count is not given." % self.name)
176 if field_options.type == nanopb_pb2.FT_STATIC:
177 self.allocation = 'STATIC'
178 elif field_options.type == nanopb_pb2.FT_CALLBACK:
179 self.allocation = 'CALLBACK'
180 self.ctype = 'pb_callback_t'
183 raise NotImplementedError(field_options.type)
185 def __cmp__(self, other):
186 return cmp(self.tag, other.tag)
189 if self.rules == 'OPTIONAL':
190 result = ' bool has_' + self.name + ';\n'
191 elif self.rules == 'REPEATED' and self.allocation == 'STATIC':
192 result = ' size_t ' + self.name + '_count;\n'
195 result += ' %s %s%s;' % (self.ctype, self.name, self.array_decl)
199 '''Return definitions for any special types this field might need.'''
200 if self.pbtype == 'BYTES' and self.allocation == 'STATIC':
201 result = 'typedef struct {\n'
202 result += ' size_t size;\n'
203 result += ' uint8_t bytes[%d];\n' % self.max_size
204 result += '} %s;\n' % self.ctype
209 def default_decl(self, declaration_only = False):
210 '''Return definition for this field's default value.'''
211 if self.default is None:
214 ctype, default = self.ctype, self.default
217 if self.pbtype == 'STRING':
218 if self.allocation != 'STATIC':
219 return None # Not implemented
221 array_decl = '[%d]' % self.max_size
222 default = str(self.default).encode('string_escape')
223 default = default.replace('"', '\\"')
224 default = '"' + default + '"'
225 elif self.pbtype == 'BYTES':
226 if self.allocation != 'STATIC':
227 return None # Not implemented
229 data = self.default.decode('string_escape')
230 data = ['0x%02x' % ord(c) for c in data]
231 default = '{%d, {%s}}' % (len(data), ','.join(data))
234 return 'extern const %s %s_default%s;' % (ctype, self.struct_name + self.name, array_decl)
236 return 'const %s %s_default%s = %s;' % (ctype, self.struct_name + self.name, array_decl, default)
238 def pb_field_t(self, prev_field_name):
239 '''Return the pb_field_t initializer to use in the constant array.
240 prev_field_name is the name of the previous field or None.
242 result = ' PB_FIELD(%3d, ' % self.tag
243 result += '%-8s, ' % self.pbtype
244 result += '%s, ' % self.rules
245 result += '%s, ' % self.allocation
246 result += '%s, ' % self.struct_name
247 result += '%s, ' % self.name
248 result += '%s, ' % (prev_field_name or self.name)
250 if self.pbtype == 'MESSAGE':
251 result += '&%s_fields)' % self.submsgname
252 elif self.default is None:
254 elif self.pbtype in ['BYTES', 'STRING'] and self.allocation != 'STATIC':
255 result += '0)' # Arbitrary size default values not implemented
257 result += '&%s_default)' % (self.struct_name + self.name)
261 def largest_field_value(self):
262 '''Determine if this field needs 16bit or 32bit pb_field_t structure to compile properly.
263 Returns numeric value or a C-expression for assert.'''
264 if self.pbtype == 'MESSAGE':
265 if self.rules == 'REPEATED' and self.allocation == 'STATIC':
266 return 'pb_membersize(%s, %s[0])' % (self.struct_name, self.name)
268 return 'pb_membersize(%s, %s)' % (self.struct_name, self.name)
270 return max(self.tag, self.max_size, self.max_count)
277 # ---------------------------------------------------------------------------
278 # Generation of messages (structures)
279 # ---------------------------------------------------------------------------
283 def __init__(self, names, desc, message_options):
288 field_options = get_nanopb_suboptions(f, message_options, self.name + f.name)
289 if field_options.type != nanopb_pb2.FT_IGNORE:
290 self.fields.append(Field(self.name, f, field_options))
292 self.packed = message_options.packed_struct
293 self.ordered_fields = self.fields[:]
294 self.ordered_fields.sort()
296 def get_dependencies(self):
297 '''Get list of type names that this structure refers to.'''
298 return [str(field.ctype) for field in self.fields]
301 result = 'typedef struct _%s {\n' % self.name
303 if not self.ordered_fields:
304 # Empty structs are not allowed in C standard.
305 # Therefore add a dummy field if an empty message occurs.
306 result += ' uint8_t dummy_field;'
308 result += '\n'.join([str(f) for f in self.ordered_fields])
312 result += ' pb_packed'
314 result += ' %s;' % self.name
319 for field in self.fields:
320 types = field.types()
321 if types is not None:
322 result += types + '\n'
325 def default_decl(self, declaration_only = False):
327 for field in self.fields:
328 default = field.default_decl(declaration_only)
329 if default is not None:
330 result += default + '\n'
333 def fields_declaration(self):
334 result = 'extern const pb_field_t %s_fields[%d];' % (self.name, len(self.fields) + 1)
337 def fields_definition(self):
338 result = 'const pb_field_t %s_fields[%d] = {\n' % (self.name, len(self.fields) + 1)
341 for field in self.ordered_fields:
342 result += field.pb_field_t(prev)
346 result += ' PB_LAST_FIELD\n};'
354 # ---------------------------------------------------------------------------
355 # Processing of entire .proto files
356 # ---------------------------------------------------------------------------
359 def iterate_messages(desc, names = Names()):
360 '''Recursively find all messages. For each, yield name, DescriptorProto.'''
361 if hasattr(desc, 'message_type'):
362 submsgs = desc.message_type
364 submsgs = desc.nested_type
366 for submsg in submsgs:
367 sub_names = names + submsg.name
368 yield sub_names, submsg
370 for x in iterate_messages(submsg, sub_names):
373 def parse_file(fdesc, file_options):
374 '''Takes a FileDescriptorProto and returns tuple (enum, messages).'''
380 base_name = Names(fdesc.package.split('.'))
384 for enum in fdesc.enum_type:
385 enum_options = get_nanopb_suboptions(enum, file_options, base_name + enum.name)
386 enums.append(Enum(base_name, enum, enum_options))
388 for names, message in iterate_messages(fdesc, base_name):
389 message_options = get_nanopb_suboptions(message, file_options, names)
390 messages.append(Message(names, message, message_options))
391 for enum in message.enum_type:
392 enum_options = get_nanopb_suboptions(enum, message_options, names + enum.name)
393 enums.append(Enum(names, enum, enum_options))
395 # Fix field default values where enum short names are used.
397 if not enum.options.long_names:
398 for message in messages:
399 for field in message.fields:
400 if field.default in enum.value_longnames:
401 idx = enum.value_longnames.index(field.default)
402 field.default = enum.values[idx][0]
404 return enums, messages
408 From http://code.activestate.com/recipes/577413-topological-sort/
409 This function is under the MIT license.
411 for k, v in data.items():
412 v.discard(k) # Ignore self dependencies
413 extra_items_in_deps = reduce(set.union, data.values(), set()) - set(data.keys())
414 data.update(dict([(item, set()) for item in extra_items_in_deps]))
416 ordered = set(item for item,dep in data.items() if not dep)
419 for item in sorted(ordered):
421 data = dict([(item, (dep - ordered)) for item,dep in data.items()
422 if item not in ordered])
423 assert not data, "A cyclic dependency exists amongst %r" % data
425 def sort_dependencies(messages):
426 '''Sort a list of Messages based on dependencies.'''
429 for message in messages:
430 dependencies[str(message.name)] = set(message.get_dependencies())
431 message_by_name[str(message.name)] = message
433 for msgname in toposort2(dependencies):
434 if msgname in message_by_name:
435 yield message_by_name[msgname]
437 def make_identifier(headername):
438 '''Make #ifndef identifier that contains uppercase A-Z and digits 0-9'''
440 for c in headername.upper():
447 def generate_header(dependencies, headername, enums, messages, options):
448 '''Generate content for a header file.
449 Generates strings, which should be concatenated and stored to file.
452 yield '/* Automatically generated nanopb header */\n'
453 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
455 symbol = make_identifier(headername)
456 yield '#ifndef _PB_%s_\n' % symbol
457 yield '#define _PB_%s_\n' % symbol
459 yield options.libformat % ('pb.h')
461 # no %s specified - use whatever was passed in as options.libformat
462 yield options.libformat
465 for dependency in dependencies:
466 noext = os.path.splitext(dependency)[0]
467 yield options.genformat % (noext + '.' + options.extension + '.h')
470 yield '#ifdef __cplusplus\n'
471 yield 'extern "C" {\n'
474 yield '/* Enum definitions */\n'
476 yield str(enum) + '\n\n'
478 yield '/* Struct definitions */\n'
479 for msg in sort_dependencies(messages):
481 yield str(msg) + '\n\n'
483 yield '/* Default values for struct fields */\n'
485 yield msg.default_decl(True)
488 yield '/* Struct field encoding specification for nanopb */\n'
490 yield msg.fields_declaration() + '\n'
492 yield '\n#ifdef __cplusplus\n'
493 yield '} /* extern "C" */\n'
499 def generate_source(headername, enums, messages):
500 '''Generate content for a source file.'''
502 yield '/* Automatically generated nanopb constant definitions */\n'
503 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
504 yield options.genformat % (headername)
508 yield msg.default_decl(False)
513 yield msg.fields_definition() + '\n\n'
516 count_required_fields = lambda m: len([f for f in msg.fields if f.rules == 'REQUIRED'])
517 largest_msg = max(messages, key = count_required_fields)
518 largest_count = count_required_fields(largest_msg)
519 if largest_count > 64:
520 yield '\n/* Check that missing required fields will be properly detected */\n'
521 yield '#if PB_MAX_REQUIRED_FIELDS < %d\n' % largest_count
522 yield '#error Properly detecting missing required fields in %s requires \\\n' % largest_msg.name
523 yield ' setting PB_MAX_REQUIRED_FIELDS to %d or more.\n' % largest_count
526 # Add checks for numeric limits
532 checks_msgnames.append(msg.name)
533 for field in msg.fields:
534 status = field.largest_field_value()
535 if isinstance(status, (str, unicode)):
536 checks.append(status)
539 worst_field = str(field.struct_name) + '.' + str(field.name)
541 if worst > 255 or checks:
542 yield '\n/* Check that field information fits in pb_field_t */\n'
545 yield '#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT)\n'
547 yield '#error Field descriptor for %s is too large. Define PB_FIELD_16BIT to fix this.\n' % worst_field
549 assertion = ' && '.join(str(c) + ' < 256' for c in checks)
550 msgs = '_'.join(str(n) for n in checks_msgnames)
551 yield 'STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
554 if worst > 65535 or checks:
555 yield '#if !defined(PB_FIELD_32BIT)\n'
557 yield '#error Field descriptor for %s is too large. Define PB_FIELD_32BIT to fix this.\n' % worst_field
559 assertion = ' && '.join(str(c) + ' < 65536' for c in checks)
560 msgs = '_'.join(str(n) for n in checks_msgnames)
561 yield 'STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
564 # Add check for sizeof(double)
567 for field in msg.fields:
568 if field.ctype == 'double':
573 yield '/* On some platforms (such as AVR), double is really float.\n'
574 yield ' * These are not directly supported by nanopb, but see example_avr_double.\n'
575 yield ' * To get rid of this error, remove any double fields from your .proto.\n'
577 yield 'STATIC_ASSERT(sizeof(double) == 8, DOUBLE_MUST_BE_8_BYTES)\n'
581 # ---------------------------------------------------------------------------
582 # Options parsing for the .proto files
583 # ---------------------------------------------------------------------------
585 from fnmatch import fnmatch
587 def read_options_file(infile):
588 '''Parse a separate options file to list:
589 [(namemask, options), ...]
594 if not line or line.startswith('//') or line.startswith('#'):
597 parts = line.split(None, 1)
598 opts = nanopb_pb2.NanoPBOptions()
599 text_format.Merge(parts[1], opts)
600 results.append((parts[0], opts))
605 '''Ugly global variables, should find a good way to pass these.'''
606 verbose_options = False
607 separate_options = []
609 def get_nanopb_suboptions(subdesc, options, name):
610 '''Get copy of options, and merge information from subdesc.'''
611 new_options = nanopb_pb2.NanoPBOptions()
612 new_options.CopyFrom(options)
614 # Handle options defined in a separate file
615 dotname = '.'.join(name.parts)
616 for namemask, options in Globals.separate_options:
617 if fnmatch(dotname, namemask):
618 new_options.MergeFrom(options)
620 # Handle options defined in .proto
621 if isinstance(subdesc.options, descriptor.FieldOptions):
622 ext_type = nanopb_pb2.nanopb
623 elif isinstance(subdesc.options, descriptor.FileOptions):
624 ext_type = nanopb_pb2.nanopb_fileopt
625 elif isinstance(subdesc.options, descriptor.MessageOptions):
626 ext_type = nanopb_pb2.nanopb_msgopt
627 elif isinstance(subdesc.options, descriptor.EnumOptions):
628 ext_type = nanopb_pb2.nanopb_enumopt
630 raise Exception("Unknown options type")
632 if subdesc.options.HasExtension(ext_type):
633 ext = subdesc.options.Extensions[ext_type]
634 new_options.MergeFrom(ext)
636 if Globals.verbose_options:
637 print "Options for " + dotname + ":"
638 print text_format.MessageToString(new_options)
643 # ---------------------------------------------------------------------------
644 # Command line interface
645 # ---------------------------------------------------------------------------
649 from optparse import OptionParser
651 optparser = OptionParser(
652 usage = "Usage: nanopb_generator.py [options] file.pb ...",
653 epilog = "Compile file.pb from file.proto by: 'protoc -ofile.pb file.proto'. " +
654 "Output will be written to file.pb.h and file.pb.c.")
655 optparser.add_option("-x", dest="exclude", metavar="FILE", action="append", default=[],
656 help="Exclude file from generated #include list.")
657 optparser.add_option("-e", "--extension", dest="extension", metavar="EXTENSION", default="pb",
658 help="Set extension to use instead of 'pb' for generated files. [default: %default]")
659 optparser.add_option("-f", "--options-file", dest="options_file", metavar="FILE", default="%s.options",
660 help="Set name of a separate generator options file.")
661 optparser.add_option("-Q", "--generated-include-format", dest="genformat",
662 metavar="FORMAT", default='#include "%s"\n',
663 help="Set format string to use for including other .pb.h files. [default: %default]")
664 optparser.add_option("-L", "--library-include-format", dest="libformat",
665 metavar="FORMAT", default='#include <%s>\n',
666 help="Set format string to use for including the nanopb pb.h header. [default: %default]")
667 optparser.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False,
668 help="Don't print anything except errors.")
669 optparser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
670 help="Print more information.")
671 optparser.add_option("-s", dest="settings", metavar="OPTION:VALUE", action="append", default=[],
672 help="Set generator option (max_size, max_count etc.).")
674 def process(filenames, options):
675 '''Process the files given on the command line.'''
678 optparser.print_help()
682 options.verbose = False
684 Globals.verbose_options = options.verbose
686 toplevel_options = nanopb_pb2.NanoPBOptions()
687 for s in options.settings:
688 text_format.Merge(s, toplevel_options)
690 for filename in filenames:
691 data = open(filename, 'rb').read()
692 fdesc = descriptor.FileDescriptorSet.FromString(data)
694 # Check if any separate options are specified
696 optfilename = options.options_file % os.path.splitext(filename)[0]
698 # No %s specified, use the filename as-is
699 optfilename = options.options_file
702 print 'Reading options from ' + optfilename
704 if os.path.isfile(optfilename):
705 Globals.separate_options = read_options_file(open(optfilename, "rU"))
707 Globals.separate_options = []
710 file_options = get_nanopb_suboptions(fdesc.file[0], toplevel_options, Names([filename]))
711 enums, messages = parse_file(fdesc.file[0], file_options)
713 noext = os.path.splitext(filename)[0]
714 headername = noext + '.' + options.extension + '.h'
715 sourcename = noext + '.' + options.extension + '.c'
716 headerbasename = os.path.basename(headername)
718 if not options.quiet:
719 print "Writing to " + headername + " and " + sourcename
721 # List of .proto files that should not be included in the C header file
722 # even if they are mentioned in the source .proto.
723 excludes = ['nanopb.proto', 'google/protobuf/descriptor.proto'] + options.exclude
724 dependencies = [d for d in fdesc.file[0].dependency if d not in excludes]
726 header = open(headername, 'w')
727 for part in generate_header(dependencies, headerbasename, enums, messages, options):
730 source = open(sourcename, 'w')
731 for part in generate_source(headerbasename, enums, messages):
736 if __name__ == '__main__':
737 options, filenames = optparser.parse_args()
738 status = process(filenames, options)