1 '''Generate header file for nanopb from a ProtoBuf FileDescriptorSet.'''
2 nanopb_version = "nanopb-0.2.2-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' and self.allocation == 'STATIC':
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)
239 '''Return the #define for the tag number of this field.'''
240 identifier = '%s_%s_tag' % (self.struct_name, self.name)
241 return '#define %-40s %d\n' % (identifier, self.tag)
243 def pb_field_t(self, prev_field_name):
244 '''Return the pb_field_t initializer to use in the constant array.
245 prev_field_name is the name of the previous field or None.
247 result = ' PB_FIELD(%3d, ' % self.tag
248 result += '%-8s, ' % self.pbtype
249 result += '%s, ' % self.rules
250 result += '%s, ' % self.allocation
251 result += '%s, ' % self.struct_name
252 result += '%s, ' % self.name
253 result += '%s, ' % (prev_field_name or self.name)
255 if self.pbtype == 'MESSAGE':
256 result += '&%s_fields)' % self.submsgname
257 elif self.default is None:
259 elif self.pbtype in ['BYTES', 'STRING'] and self.allocation != 'STATIC':
260 result += '0)' # Arbitrary size default values not implemented
262 result += '&%s_default)' % (self.struct_name + self.name)
266 def largest_field_value(self):
267 '''Determine if this field needs 16bit or 32bit pb_field_t structure to compile properly.
268 Returns numeric value or a C-expression for assert.'''
269 if self.pbtype == 'MESSAGE':
270 if self.rules == 'REPEATED' and self.allocation == 'STATIC':
271 return 'pb_membersize(%s, %s[0])' % (self.struct_name, self.name)
273 return 'pb_membersize(%s, %s)' % (self.struct_name, self.name)
275 return max(self.tag, self.max_size, self.max_count)
282 # ---------------------------------------------------------------------------
283 # Generation of messages (structures)
284 # ---------------------------------------------------------------------------
288 def __init__(self, names, desc, message_options):
293 field_options = get_nanopb_suboptions(f, message_options, self.name + f.name)
294 if field_options.type != nanopb_pb2.FT_IGNORE:
295 self.fields.append(Field(self.name, f, field_options))
297 self.packed = message_options.packed_struct
298 self.ordered_fields = self.fields[:]
299 self.ordered_fields.sort()
301 def get_dependencies(self):
302 '''Get list of type names that this structure refers to.'''
303 return [str(field.ctype) for field in self.fields]
306 result = 'typedef struct _%s {\n' % self.name
308 if not self.ordered_fields:
309 # Empty structs are not allowed in C standard.
310 # Therefore add a dummy field if an empty message occurs.
311 result += ' uint8_t dummy_field;'
313 result += '\n'.join([str(f) for f in self.ordered_fields])
317 result += ' pb_packed'
319 result += ' %s;' % self.name
322 result = 'PB_PACKED_STRUCT_START\n' + result
323 result += '\nPB_PACKED_STRUCT_END'
329 for field in self.fields:
330 types = field.types()
331 if types is not None:
332 result += types + '\n'
335 def default_decl(self, declaration_only = False):
337 for field in self.fields:
338 default = field.default_decl(declaration_only)
339 if default is not None:
340 result += default + '\n'
343 def fields_declaration(self):
344 result = 'extern const pb_field_t %s_fields[%d];' % (self.name, len(self.fields) + 1)
347 def fields_definition(self):
348 result = 'const pb_field_t %s_fields[%d] = {\n' % (self.name, len(self.fields) + 1)
351 for field in self.ordered_fields:
352 result += field.pb_field_t(prev)
356 result += ' PB_LAST_FIELD\n};'
364 # ---------------------------------------------------------------------------
365 # Processing of entire .proto files
366 # ---------------------------------------------------------------------------
369 def iterate_messages(desc, names = Names()):
370 '''Recursively find all messages. For each, yield name, DescriptorProto.'''
371 if hasattr(desc, 'message_type'):
372 submsgs = desc.message_type
374 submsgs = desc.nested_type
376 for submsg in submsgs:
377 sub_names = names + submsg.name
378 yield sub_names, submsg
380 for x in iterate_messages(submsg, sub_names):
383 def parse_file(fdesc, file_options):
384 '''Takes a FileDescriptorProto and returns tuple (enum, messages).'''
390 base_name = Names(fdesc.package.split('.'))
394 for enum in fdesc.enum_type:
395 enum_options = get_nanopb_suboptions(enum, file_options, base_name + enum.name)
396 enums.append(Enum(base_name, enum, enum_options))
398 for names, message in iterate_messages(fdesc, base_name):
399 message_options = get_nanopb_suboptions(message, file_options, names)
400 messages.append(Message(names, message, message_options))
401 for enum in message.enum_type:
402 enum_options = get_nanopb_suboptions(enum, message_options, names + enum.name)
403 enums.append(Enum(names, enum, enum_options))
405 # Fix field default values where enum short names are used.
407 if not enum.options.long_names:
408 for message in messages:
409 for field in message.fields:
410 if field.default in enum.value_longnames:
411 idx = enum.value_longnames.index(field.default)
412 field.default = enum.values[idx][0]
414 return enums, messages
418 From http://code.activestate.com/recipes/577413-topological-sort/
419 This function is under the MIT license.
421 for k, v in data.items():
422 v.discard(k) # Ignore self dependencies
423 extra_items_in_deps = reduce(set.union, data.values(), set()) - set(data.keys())
424 data.update(dict([(item, set()) for item in extra_items_in_deps]))
426 ordered = set(item for item,dep in data.items() if not dep)
429 for item in sorted(ordered):
431 data = dict([(item, (dep - ordered)) for item,dep in data.items()
432 if item not in ordered])
433 assert not data, "A cyclic dependency exists amongst %r" % data
435 def sort_dependencies(messages):
436 '''Sort a list of Messages based on dependencies.'''
439 for message in messages:
440 dependencies[str(message.name)] = set(message.get_dependencies())
441 message_by_name[str(message.name)] = message
443 for msgname in toposort2(dependencies):
444 if msgname in message_by_name:
445 yield message_by_name[msgname]
447 def make_identifier(headername):
448 '''Make #ifndef identifier that contains uppercase A-Z and digits 0-9'''
450 for c in headername.upper():
457 def generate_header(dependencies, headername, enums, messages, options):
458 '''Generate content for a header file.
459 Generates strings, which should be concatenated and stored to file.
462 yield '/* Automatically generated nanopb header */\n'
463 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
465 symbol = make_identifier(headername)
466 yield '#ifndef _PB_%s_\n' % symbol
467 yield '#define _PB_%s_\n' % symbol
469 yield options.libformat % ('pb.h')
471 # no %s specified - use whatever was passed in as options.libformat
472 yield options.libformat
475 for dependency in dependencies:
476 noext = os.path.splitext(dependency)[0]
477 yield options.genformat % (noext + '.' + options.extension + '.h')
480 yield '#ifdef __cplusplus\n'
481 yield 'extern "C" {\n'
484 yield '/* Enum definitions */\n'
486 yield str(enum) + '\n\n'
488 yield '/* Struct definitions */\n'
489 for msg in sort_dependencies(messages):
491 yield str(msg) + '\n\n'
493 yield '/* Default values for struct fields */\n'
495 yield msg.default_decl(True)
498 yield '/* Field tags (for use in manual encoding/decoding) */\n'
499 for msg in sort_dependencies(messages):
500 for field in msg.fields:
504 yield '/* Struct field encoding specification for nanopb */\n'
506 yield msg.fields_declaration() + '\n'
508 yield '\n#ifdef __cplusplus\n'
509 yield '} /* extern "C" */\n'
515 def generate_source(headername, enums, messages):
516 '''Generate content for a source file.'''
518 yield '/* Automatically generated nanopb constant definitions */\n'
519 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
520 yield options.genformat % (headername)
524 yield msg.default_decl(False)
529 yield msg.fields_definition() + '\n\n'
532 count_required_fields = lambda m: len([f for f in msg.fields if f.rules == 'REQUIRED'])
533 largest_msg = max(messages, key = count_required_fields)
534 largest_count = count_required_fields(largest_msg)
535 if largest_count > 64:
536 yield '\n/* Check that missing required fields will be properly detected */\n'
537 yield '#if PB_MAX_REQUIRED_FIELDS < %d\n' % largest_count
538 yield '#error Properly detecting missing required fields in %s requires \\\n' % largest_msg.name
539 yield ' setting PB_MAX_REQUIRED_FIELDS to %d or more.\n' % largest_count
542 # Add checks for numeric limits
548 checks_msgnames.append(msg.name)
549 for field in msg.fields:
550 status = field.largest_field_value()
551 if isinstance(status, (str, unicode)):
552 checks.append(status)
555 worst_field = str(field.struct_name) + '.' + str(field.name)
557 if worst > 255 or checks:
558 yield '\n/* Check that field information fits in pb_field_t */\n'
561 yield '#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT)\n'
563 yield '#error Field descriptor for %s is too large. Define PB_FIELD_16BIT to fix this.\n' % worst_field
565 assertion = ' && '.join(str(c) + ' < 256' for c in checks)
566 msgs = '_'.join(str(n) for n in checks_msgnames)
567 yield 'STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
570 if worst > 65535 or checks:
571 yield '#if !defined(PB_FIELD_32BIT)\n'
573 yield '#error Field descriptor for %s is too large. Define PB_FIELD_32BIT to fix this.\n' % worst_field
575 assertion = ' && '.join(str(c) + ' < 65536' for c in checks)
576 msgs = '_'.join(str(n) for n in checks_msgnames)
577 yield 'STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
580 # Add check for sizeof(double)
583 for field in msg.fields:
584 if field.ctype == 'double':
589 yield '/* On some platforms (such as AVR), double is really float.\n'
590 yield ' * These are not directly supported by nanopb, but see example_avr_double.\n'
591 yield ' * To get rid of this error, remove any double fields from your .proto.\n'
593 yield 'STATIC_ASSERT(sizeof(double) == 8, DOUBLE_MUST_BE_8_BYTES)\n'
597 # ---------------------------------------------------------------------------
598 # Options parsing for the .proto files
599 # ---------------------------------------------------------------------------
601 from fnmatch import fnmatch
603 def read_options_file(infile):
604 '''Parse a separate options file to list:
605 [(namemask, options), ...]
610 if not line or line.startswith('//') or line.startswith('#'):
613 parts = line.split(None, 1)
614 opts = nanopb_pb2.NanoPBOptions()
615 text_format.Merge(parts[1], opts)
616 results.append((parts[0], opts))
621 '''Ugly global variables, should find a good way to pass these.'''
622 verbose_options = False
623 separate_options = []
625 def get_nanopb_suboptions(subdesc, options, name):
626 '''Get copy of options, and merge information from subdesc.'''
627 new_options = nanopb_pb2.NanoPBOptions()
628 new_options.CopyFrom(options)
630 # Handle options defined in a separate file
631 dotname = '.'.join(name.parts)
632 for namemask, options in Globals.separate_options:
633 if fnmatch(dotname, namemask):
634 new_options.MergeFrom(options)
636 # Handle options defined in .proto
637 if isinstance(subdesc.options, descriptor.FieldOptions):
638 ext_type = nanopb_pb2.nanopb
639 elif isinstance(subdesc.options, descriptor.FileOptions):
640 ext_type = nanopb_pb2.nanopb_fileopt
641 elif isinstance(subdesc.options, descriptor.MessageOptions):
642 ext_type = nanopb_pb2.nanopb_msgopt
643 elif isinstance(subdesc.options, descriptor.EnumOptions):
644 ext_type = nanopb_pb2.nanopb_enumopt
646 raise Exception("Unknown options type")
648 if subdesc.options.HasExtension(ext_type):
649 ext = subdesc.options.Extensions[ext_type]
650 new_options.MergeFrom(ext)
652 if Globals.verbose_options:
653 print "Options for " + dotname + ":"
654 print text_format.MessageToString(new_options)
659 # ---------------------------------------------------------------------------
660 # Command line interface
661 # ---------------------------------------------------------------------------
665 from optparse import OptionParser
667 optparser = OptionParser(
668 usage = "Usage: nanopb_generator.py [options] file.pb ...",
669 epilog = "Compile file.pb from file.proto by: 'protoc -ofile.pb file.proto'. " +
670 "Output will be written to file.pb.h and file.pb.c.")
671 optparser.add_option("-x", dest="exclude", metavar="FILE", action="append", default=[],
672 help="Exclude file from generated #include list.")
673 optparser.add_option("-e", "--extension", dest="extension", metavar="EXTENSION", default="pb",
674 help="Set extension to use instead of 'pb' for generated files. [default: %default]")
675 optparser.add_option("-f", "--options-file", dest="options_file", metavar="FILE", default="%s.options",
676 help="Set name of a separate generator options file.")
677 optparser.add_option("-Q", "--generated-include-format", dest="genformat",
678 metavar="FORMAT", default='#include "%s"\n',
679 help="Set format string to use for including other .pb.h files. [default: %default]")
680 optparser.add_option("-L", "--library-include-format", dest="libformat",
681 metavar="FORMAT", default='#include <%s>\n',
682 help="Set format string to use for including the nanopb pb.h header. [default: %default]")
683 optparser.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False,
684 help="Don't print anything except errors.")
685 optparser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
686 help="Print more information.")
687 optparser.add_option("-s", dest="settings", metavar="OPTION:VALUE", action="append", default=[],
688 help="Set generator option (max_size, max_count etc.).")
690 def process(filenames, options):
691 '''Process the files given on the command line.'''
694 optparser.print_help()
698 options.verbose = False
700 Globals.verbose_options = options.verbose
702 toplevel_options = nanopb_pb2.NanoPBOptions()
703 for s in options.settings:
704 text_format.Merge(s, toplevel_options)
706 for filename in filenames:
707 data = open(filename, 'rb').read()
708 fdesc = descriptor.FileDescriptorSet.FromString(data)
710 # Check if any separate options are specified
712 optfilename = options.options_file % os.path.splitext(filename)[0]
714 # No %s specified, use the filename as-is
715 optfilename = options.options_file
718 print 'Reading options from ' + optfilename
720 if os.path.isfile(optfilename):
721 Globals.separate_options = read_options_file(open(optfilename, "rU"))
723 Globals.separate_options = []
726 file_options = get_nanopb_suboptions(fdesc.file[0], toplevel_options, Names([filename]))
727 enums, messages = parse_file(fdesc.file[0], file_options)
729 noext = os.path.splitext(filename)[0]
730 headername = noext + '.' + options.extension + '.h'
731 sourcename = noext + '.' + options.extension + '.c'
732 headerbasename = os.path.basename(headername)
734 if not options.quiet:
735 print "Writing to " + headername + " and " + sourcename
737 # List of .proto files that should not be included in the C header file
738 # even if they are mentioned in the source .proto.
739 excludes = ['nanopb.proto', 'google/protobuf/descriptor.proto'] + options.exclude
740 dependencies = [d for d in fdesc.file[0].dependency if d not in excludes]
742 header = open(headername, 'w')
743 for part in generate_header(dependencies, headerbasename, enums, messages, options):
746 source = open(sourcename, 'w')
747 for part in generate_source(headerbasename, enums, messages):
752 if __name__ == '__main__':
753 options, filenames = optparser.parse_args()
754 status = process(filenames, options)