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
8 print "*************************************************************"
9 print "*** Could not import the Google protobuf Python libraries ***"
10 print "*** Try installing package 'python-protobuf' or similar. ***"
11 print "*************************************************************"
19 print "***************************************************************"
20 print "*** Could not import the precompiled nanopb_pb2.py. ***"
21 print "*** Run 'make' in the 'generator' folder to update the file.***"
22 print "***************************************************************"
31 # ---------------------------------------------------------------------------
32 # Generation of single fields
33 # ---------------------------------------------------------------------------
38 # Values are tuple (c type, pb type)
39 FieldD = descriptor.FieldDescriptorProto
41 FieldD.TYPE_BOOL: ('bool', 'BOOL'),
42 FieldD.TYPE_DOUBLE: ('double', 'DOUBLE'),
43 FieldD.TYPE_FIXED32: ('uint32_t', 'FIXED32'),
44 FieldD.TYPE_FIXED64: ('uint64_t', 'FIXED64'),
45 FieldD.TYPE_FLOAT: ('float', 'FLOAT'),
46 FieldD.TYPE_INT32: ('int32_t', 'INT32'),
47 FieldD.TYPE_INT64: ('int64_t', 'INT64'),
48 FieldD.TYPE_SFIXED32: ('int32_t', 'SFIXED32'),
49 FieldD.TYPE_SFIXED64: ('int64_t', 'SFIXED64'),
50 FieldD.TYPE_SINT32: ('int32_t', 'SINT32'),
51 FieldD.TYPE_SINT64: ('int64_t', 'SINT64'),
52 FieldD.TYPE_UINT32: ('uint32_t', 'UINT32'),
53 FieldD.TYPE_UINT64: ('uint64_t', 'UINT64')
57 '''Keeps a set of nested names and formats them to C identifier.
58 You can subclass this with your own implementation.
60 def __init__(self, parts = ()):
61 if isinstance(parts, Names):
63 self.parts = tuple(parts)
66 return '_'.join(self.parts)
68 def __add__(self, other):
69 if isinstance(other, (str, unicode)):
70 return Names(self.parts + (other,))
71 elif isinstance(other, tuple):
72 return Names(self.parts + other)
74 raise ValueError("Name parts should be of type str")
76 def __eq__(self, other):
77 return isinstance(other, Names) and self.parts == other.parts
79 def names_from_type_name(type_name):
80 '''Parse Names() from FieldDescriptorProto type_name'''
81 if type_name[0] != '.':
82 raise NotImplementedError("Lookup of non-absolute type names is not supported")
83 return Names(type_name[1:].split('.'))
86 def __init__(self, names, desc, enum_options):
87 '''desc is EnumDescriptorProto'''
89 self.options = enum_options
90 self.names = names + desc.name
92 if enum_options.long_names:
93 self.values = [(self.names + x.name, x.number) for x in desc.value]
95 self.values = [(names + x.name, x.number) for x in desc.value]
97 self.value_longnames = [self.names + x.name for x in desc.value]
100 result = 'typedef enum _%s {\n' % self.names
101 result += ',\n'.join([" %s = %d" % x for x in self.values])
102 result += '\n} %s;' % self.names
106 def __init__(self, struct_name, desc, field_options):
107 '''desc is FieldDescriptorProto'''
108 self.tag = desc.number
109 self.struct_name = struct_name
110 self.name = desc.name
113 self.max_count = None
116 # Parse field options
117 if field_options.HasField("max_size"):
118 self.max_size = field_options.max_size
120 if field_options.HasField("max_count"):
121 self.max_count = field_options.max_count
123 if desc.HasField('default_value'):
124 self.default = desc.default_value
126 # Check field rules, i.e. required/optional/repeated.
128 if desc.label == FieldD.LABEL_REQUIRED:
129 self.rules = 'REQUIRED'
130 elif desc.label == FieldD.LABEL_OPTIONAL:
131 self.rules = 'OPTIONAL'
132 elif desc.label == FieldD.LABEL_REPEATED:
133 self.rules = 'REPEATED'
134 if self.max_count is None:
135 can_be_static = False
137 self.array_decl = '[%d]' % self.max_count
139 raise NotImplementedError(desc.label)
141 # Decide the C data type to use in the struct.
142 if datatypes.has_key(desc.type):
143 self.ctype, self.pbtype = datatypes[desc.type]
144 elif desc.type == FieldD.TYPE_ENUM:
146 self.ctype = names_from_type_name(desc.type_name)
147 if self.default is not None:
148 self.default = self.ctype + self.default
149 elif desc.type == FieldD.TYPE_STRING:
150 self.pbtype = 'STRING'
151 if self.max_size is None:
152 can_be_static = False
155 self.array_decl += '[%d]' % self.max_size
156 elif desc.type == FieldD.TYPE_BYTES:
157 self.pbtype = 'BYTES'
158 if self.max_size is None:
159 can_be_static = False
161 self.ctype = self.struct_name + self.name + 't'
162 elif desc.type == FieldD.TYPE_MESSAGE:
163 self.pbtype = 'MESSAGE'
164 self.ctype = self.submsgname = names_from_type_name(desc.type_name)
166 raise NotImplementedError(desc.type)
168 if field_options.type == nanopb_pb2.FT_DEFAULT:
170 field_options.type = nanopb_pb2.FT_STATIC
172 field_options.type = nanopb_pb2.FT_CALLBACK
174 if field_options.type == nanopb_pb2.FT_STATIC and not can_be_static:
175 raise Exception("Field %s is defined as static, but max_size or max_count is not given." % self.name)
177 if field_options.type == nanopb_pb2.FT_STATIC:
178 self.allocation = 'STATIC'
179 elif field_options.type == nanopb_pb2.FT_CALLBACK:
180 self.allocation = 'CALLBACK'
181 self.ctype = 'pb_callback_t'
184 raise NotImplementedError(field_options.type)
186 def __cmp__(self, other):
187 return cmp(self.tag, other.tag)
190 if self.rules == 'OPTIONAL':
191 result = ' bool has_' + self.name + ';\n'
192 elif self.rules == 'REPEATED' and self.allocation == 'STATIC':
193 result = ' size_t ' + self.name + '_count;\n'
196 result += ' %s %s%s;' % (self.ctype, self.name, self.array_decl)
200 '''Return definitions for any special types this field might need.'''
201 if self.pbtype == 'BYTES' and self.allocation == 'STATIC':
202 result = 'typedef struct {\n'
203 result += ' size_t size;\n'
204 result += ' uint8_t bytes[%d];\n' % self.max_size
205 result += '} %s;\n' % self.ctype
210 def default_decl(self, declaration_only = False):
211 '''Return definition for this field's default value.'''
212 if self.default is None:
215 ctype, default = self.ctype, self.default
218 if self.pbtype == 'STRING':
219 if self.allocation != 'STATIC':
220 return None # Not implemented
222 array_decl = '[%d]' % self.max_size
223 default = str(self.default).encode('string_escape')
224 default = default.replace('"', '\\"')
225 default = '"' + default + '"'
226 elif self.pbtype == 'BYTES':
227 if self.allocation != 'STATIC':
228 return None # Not implemented
230 data = self.default.decode('string_escape')
231 data = ['0x%02x' % ord(c) for c in data]
232 default = '{%d, {%s}}' % (len(data), ','.join(data))
235 return 'extern const %s %s_default%s;' % (ctype, self.struct_name + self.name, array_decl)
237 return 'const %s %s_default%s = %s;' % (ctype, self.struct_name + self.name, array_decl, default)
239 def pb_field_t(self, prev_field_name):
240 '''Return the pb_field_t initializer to use in the constant array.
241 prev_field_name is the name of the previous field or None.
243 result = ' PB_FIELD(%3d, ' % self.tag
244 result += '%-8s, ' % self.pbtype
245 result += '%s, ' % self.rules
246 result += '%s, ' % self.allocation
247 result += '%s, ' % self.struct_name
248 result += '%s, ' % self.name
249 result += '%s, ' % (prev_field_name or self.name)
251 if self.pbtype == 'MESSAGE':
252 result += '&%s_fields)' % self.submsgname
253 elif self.default is None:
255 elif self.pbtype in ['BYTES', 'STRING'] and self.allocation != 'STATIC':
256 result += '0)' # Arbitrary size default values not implemented
258 result += '&%s_default)' % (self.struct_name + self.name)
262 def largest_field_value(self):
263 '''Determine if this field needs 16bit or 32bit pb_field_t structure to compile properly.
264 Returns numeric value or a C-expression for assert.'''
265 if self.pbtype == 'MESSAGE':
266 if self.rules == 'REPEATED' and self.allocation == 'STATIC':
267 return 'pb_membersize(%s, %s[0])' % (self.struct_name, self.name)
269 return 'pb_membersize(%s, %s)' % (self.struct_name, self.name)
271 return max(self.tag, self.max_size, self.max_count)
278 # ---------------------------------------------------------------------------
279 # Generation of messages (structures)
280 # ---------------------------------------------------------------------------
284 def __init__(self, names, desc, message_options):
289 field_options = get_nanopb_suboptions(f, message_options)
290 if field_options.type != nanopb_pb2.FT_IGNORE:
291 self.fields.append(Field(self.name, f, field_options))
293 self.packed = message_options.packed_struct
294 self.ordered_fields = self.fields[:]
295 self.ordered_fields.sort()
297 def get_dependencies(self):
298 '''Get list of type names that this structure refers to.'''
299 return [str(field.ctype) for field in self.fields]
302 result = 'typedef struct _%s {\n' % self.name
303 result += '\n'.join([str(f) for f in self.ordered_fields])
307 result += ' pb_packed'
309 result += ' %s;' % self.name
314 for field in self.fields:
315 types = field.types()
316 if types is not None:
317 result += types + '\n'
320 def default_decl(self, declaration_only = False):
322 for field in self.fields:
323 default = field.default_decl(declaration_only)
324 if default is not None:
325 result += default + '\n'
328 def fields_declaration(self):
329 result = 'extern const pb_field_t %s_fields[%d];' % (self.name, len(self.fields) + 1)
332 def fields_definition(self):
333 result = 'const pb_field_t %s_fields[%d] = {\n' % (self.name, len(self.fields) + 1)
336 for field in self.ordered_fields:
337 result += field.pb_field_t(prev)
341 result += ' PB_LAST_FIELD\n};'
349 # ---------------------------------------------------------------------------
350 # Processing of entire .proto files
351 # ---------------------------------------------------------------------------
354 def iterate_messages(desc, names = Names()):
355 '''Recursively find all messages. For each, yield name, DescriptorProto.'''
356 if hasattr(desc, 'message_type'):
357 submsgs = desc.message_type
359 submsgs = desc.nested_type
361 for submsg in submsgs:
362 sub_names = names + submsg.name
363 yield sub_names, submsg
365 for x in iterate_messages(submsg, sub_names):
368 def parse_file(fdesc, file_options):
369 '''Takes a FileDescriptorProto and returns tuple (enum, messages).'''
375 base_name = Names(fdesc.package.split('.'))
379 for enum in fdesc.enum_type:
380 enum_options = get_nanopb_suboptions(enum, file_options)
381 enums.append(Enum(base_name, enum, enum_options))
383 for names, message in iterate_messages(fdesc, base_name):
384 message_options = get_nanopb_suboptions(message, file_options)
385 messages.append(Message(names, message, message_options))
386 for enum in message.enum_type:
387 enum_options = get_nanopb_suboptions(enum, message_options)
388 enums.append(Enum(names, enum, enum_options))
390 # Fix field default values where enum short names are used.
392 if not enum.options.long_names:
393 for message in messages:
394 for field in message.fields:
395 if field.default in enum.value_longnames:
396 idx = enum.value_longnames.index(field.default)
397 field.default = enum.values[idx][0]
399 return enums, messages
403 From http://code.activestate.com/recipes/577413-topological-sort/
404 This function is under the MIT license.
406 for k, v in data.items():
407 v.discard(k) # Ignore self dependencies
408 extra_items_in_deps = reduce(set.union, data.values(), set()) - set(data.keys())
409 data.update(dict([(item, set()) for item in extra_items_in_deps]))
411 ordered = set(item for item,dep in data.items() if not dep)
414 for item in sorted(ordered):
416 data = dict([(item, (dep - ordered)) for item,dep in data.items()
417 if item not in ordered])
418 assert not data, "A cyclic dependency exists amongst %r" % data
420 def sort_dependencies(messages):
421 '''Sort a list of Messages based on dependencies.'''
424 for message in messages:
425 dependencies[str(message.name)] = set(message.get_dependencies())
426 message_by_name[str(message.name)] = message
428 for msgname in toposort2(dependencies):
429 if msgname in message_by_name:
430 yield message_by_name[msgname]
432 def make_identifier(headername):
433 '''Make #ifndef identifier that contains uppercase A-Z and digits 0-9'''
435 for c in headername.upper():
442 def generate_header(dependencies, headername, enums, messages, options):
443 '''Generate content for a header file.
444 Generates strings, which should be concatenated and stored to file.
447 yield '/* Automatically generated nanopb header */\n'
448 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
450 symbol = make_identifier(headername)
451 yield '#ifndef _PB_%s_\n' % symbol
452 yield '#define _PB_%s_\n' % symbol
453 yield options.libformat % ('pb.h')
456 for dependency in dependencies:
457 noext = os.path.splitext(dependency)[0]
458 yield options.genformat % (noext + '.' + options.extension + '.h')
461 yield '#ifdef __cplusplus\n'
462 yield 'extern "C" {\n'
465 yield '/* Enum definitions */\n'
467 yield str(enum) + '\n\n'
469 yield '/* Struct definitions */\n'
470 for msg in sort_dependencies(messages):
472 yield str(msg) + '\n\n'
474 yield '/* Default values for struct fields */\n'
476 yield msg.default_decl(True)
479 yield '/* Struct field encoding specification for nanopb */\n'
481 yield msg.fields_declaration() + '\n'
483 yield '\n#ifdef __cplusplus\n'
484 yield '} /* extern "C" */\n'
490 def generate_source(headername, enums, messages):
491 '''Generate content for a source file.'''
493 yield '/* Automatically generated nanopb constant definitions */\n'
494 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
495 yield options.genformat % (headername)
499 yield msg.default_decl(False)
504 yield msg.fields_definition() + '\n\n'
507 count_required_fields = lambda m: len([f for f in msg.fields if f.rules == 'REQUIRED'])
508 largest_msg = max(messages, key = count_required_fields)
509 largest_count = count_required_fields(largest_msg)
510 if largest_count > 64:
511 yield '\n/* Check that missing required fields will be properly detected */\n'
512 yield '#if PB_MAX_REQUIRED_FIELDS < %d\n' % largest_count
513 yield '#error Properly detecting missing required fields in %s requires \\\n' % largest_msg.name
514 yield ' setting PB_MAX_REQUIRED_FIELDS to %d or more.\n' % largest_count
517 # Add checks for numeric limits
523 checks_msgnames.append(msg.name)
524 for field in msg.fields:
525 status = field.largest_field_value()
526 if isinstance(status, (str, unicode)):
527 checks.append(status)
530 worst_field = str(field.struct_name) + '.' + str(field.name)
532 if worst > 255 or checks:
533 yield '\n/* Check that field information fits in pb_field_t */\n'
536 yield '#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT)\n'
538 yield '#error Field descriptor for %s is too large. Define PB_FIELD_16BIT to fix this.\n' % worst_field
540 assertion = ' && '.join(str(c) + ' < 256' for c in checks)
541 msgs = '_'.join(str(n) for n in checks_msgnames)
542 yield 'STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
545 if worst > 65535 or checks:
546 yield '#if !defined(PB_FIELD_32BIT)\n'
548 yield '#error Field descriptor for %s is too large. Define PB_FIELD_32BIT to fix this.\n' % worst_field
550 assertion = ' && '.join(str(c) + ' < 65536' for c in checks)
551 msgs = '_'.join(str(n) for n in checks_msgnames)
552 yield 'STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
555 # Add check for sizeof(double)
558 for field in msg.fields:
559 if field.ctype == 'double':
564 yield '/* On some platforms (such as AVR), double is really float.\n'
565 yield ' * These are not directly supported by nanopb, but see example_avr_double.\n'
566 yield ' * To get rid of this error, remove any double fields from your .proto.\n'
568 yield 'STATIC_ASSERT(sizeof(double) == 8, DOUBLE_MUST_BE_8_BYTES)\n'
573 # ---------------------------------------------------------------------------
574 # Command line interface
575 # ---------------------------------------------------------------------------
579 from optparse import OptionParser
580 import google.protobuf.text_format as text_format
582 optparser = OptionParser(
583 usage = "Usage: nanopb_generator.py [options] file.pb ...",
584 epilog = "Compile file.pb from file.proto by: 'protoc -ofile.pb file.proto'. " +
585 "Output will be written to file.pb.h and file.pb.c.")
586 optparser.add_option("-x", dest="exclude", metavar="FILE", action="append", default=[],
587 help="Exclude file from generated #include list.")
588 optparser.add_option("-e", "--extension", dest="extension", metavar="EXTENSION", default="pb",
589 help="Set extension to use instead of 'pb' for generated files. [default: %default]")
590 optparser.add_option("-Q", "--generated-include-format", dest="genformat",
591 metavar="FORMAT", default='#include "%s"\n',
592 help="Set format string to use for including other .pb.h files. [default: %default]")
593 optparser.add_option("-L", "--library-include-format", dest="libformat",
594 metavar="FORMAT", default='#include <%s>\n',
595 help="Set format string to use for including the nanopb pb.h header. [default: %default]")
596 optparser.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False,
597 help="Don't print anything except errors.")
598 optparser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
599 help="Print more information.")
600 optparser.add_option("-s", dest="settings", metavar="OPTION:VALUE", action="append", default=[],
601 help="Set generator option (max_size, max_count etc.).")
603 def get_nanopb_suboptions(subdesc, options):
604 '''Get copy of options, and merge information from subdesc.'''
605 new_options = nanopb_pb2.NanoPBOptions()
606 new_options.CopyFrom(options)
608 if isinstance(subdesc.options, descriptor.FieldOptions):
609 ext_type = nanopb_pb2.nanopb
610 elif isinstance(subdesc.options, descriptor.FileOptions):
611 ext_type = nanopb_pb2.nanopb_fileopt
612 elif isinstance(subdesc.options, descriptor.MessageOptions):
613 ext_type = nanopb_pb2.nanopb_msgopt
614 elif isinstance(subdesc.options, descriptor.EnumOptions):
615 ext_type = nanopb_pb2.nanopb_enumopt
617 raise Exception("Unknown options type")
619 if subdesc.options.HasExtension(ext_type):
620 ext = subdesc.options.Extensions[ext_type]
621 new_options.MergeFrom(ext)
625 def process(filenames, options):
626 '''Process the files given on the command line.'''
629 optparser.print_help()
633 options.verbose = False
635 toplevel_options = nanopb_pb2.NanoPBOptions()
636 for s in options.settings:
637 text_format.Merge(s, toplevel_options)
639 for filename in filenames:
640 data = open(filename, 'rb').read()
641 fdesc = descriptor.FileDescriptorSet.FromString(data)
643 file_options = get_nanopb_suboptions(fdesc.file[0], toplevel_options)
646 print "Options for " + filename + ":"
647 print text_format.MessageToString(file_options)
649 enums, messages = parse_file(fdesc.file[0], file_options)
651 noext = os.path.splitext(filename)[0]
652 headername = noext + '.' + options.extension + '.h'
653 sourcename = noext + '.' + options.extension + '.c'
654 headerbasename = os.path.basename(headername)
656 if not options.quiet:
657 print "Writing to " + headername + " and " + sourcename
659 # List of .proto files that should not be included in the C header file
660 # even if they are mentioned in the source .proto.
661 excludes = ['nanopb.proto', 'google/protobuf/descriptor.proto'] + options.exclude
662 dependencies = [d for d in fdesc.file[0].dependency if d not in excludes]
664 header = open(headername, 'w')
665 for part in generate_header(dependencies, headerbasename, enums, messages, options):
668 source = open(sourcename, 'w')
669 for part in generate_source(headerbasename, enums, messages):
674 if __name__ == '__main__':
675 options, filenames = optparser.parse_args()
676 status = process(filenames, options)