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
304 if not self.ordered_fields:
305 # Empty structs are not allowed in C standard.
306 # Therefore add a dummy field if an empty message occurs.
307 result += ' uint8_t dummy_field;'
309 result += '\n'.join([str(f) for f in self.ordered_fields])
313 result += ' pb_packed'
315 result += ' %s;' % self.name
320 for field in self.fields:
321 types = field.types()
322 if types is not None:
323 result += types + '\n'
326 def default_decl(self, declaration_only = False):
328 for field in self.fields:
329 default = field.default_decl(declaration_only)
330 if default is not None:
331 result += default + '\n'
334 def fields_declaration(self):
335 result = 'extern const pb_field_t %s_fields[%d];' % (self.name, len(self.fields) + 1)
338 def fields_definition(self):
339 result = 'const pb_field_t %s_fields[%d] = {\n' % (self.name, len(self.fields) + 1)
342 for field in self.ordered_fields:
343 result += field.pb_field_t(prev)
347 result += ' PB_LAST_FIELD\n};'
355 # ---------------------------------------------------------------------------
356 # Processing of entire .proto files
357 # ---------------------------------------------------------------------------
360 def iterate_messages(desc, names = Names()):
361 '''Recursively find all messages. For each, yield name, DescriptorProto.'''
362 if hasattr(desc, 'message_type'):
363 submsgs = desc.message_type
365 submsgs = desc.nested_type
367 for submsg in submsgs:
368 sub_names = names + submsg.name
369 yield sub_names, submsg
371 for x in iterate_messages(submsg, sub_names):
374 def parse_file(fdesc, file_options):
375 '''Takes a FileDescriptorProto and returns tuple (enum, messages).'''
381 base_name = Names(fdesc.package.split('.'))
385 for enum in fdesc.enum_type:
386 enum_options = get_nanopb_suboptions(enum, file_options)
387 enums.append(Enum(base_name, enum, enum_options))
389 for names, message in iterate_messages(fdesc, base_name):
390 message_options = get_nanopb_suboptions(message, file_options)
391 messages.append(Message(names, message, message_options))
392 for enum in message.enum_type:
393 enum_options = get_nanopb_suboptions(enum, message_options)
394 enums.append(Enum(names, enum, enum_options))
396 # Fix field default values where enum short names are used.
398 if not enum.options.long_names:
399 for message in messages:
400 for field in message.fields:
401 if field.default in enum.value_longnames:
402 idx = enum.value_longnames.index(field.default)
403 field.default = enum.values[idx][0]
405 return enums, messages
409 From http://code.activestate.com/recipes/577413-topological-sort/
410 This function is under the MIT license.
412 for k, v in data.items():
413 v.discard(k) # Ignore self dependencies
414 extra_items_in_deps = reduce(set.union, data.values(), set()) - set(data.keys())
415 data.update(dict([(item, set()) for item in extra_items_in_deps]))
417 ordered = set(item for item,dep in data.items() if not dep)
420 for item in sorted(ordered):
422 data = dict([(item, (dep - ordered)) for item,dep in data.items()
423 if item not in ordered])
424 assert not data, "A cyclic dependency exists amongst %r" % data
426 def sort_dependencies(messages):
427 '''Sort a list of Messages based on dependencies.'''
430 for message in messages:
431 dependencies[str(message.name)] = set(message.get_dependencies())
432 message_by_name[str(message.name)] = message
434 for msgname in toposort2(dependencies):
435 if msgname in message_by_name:
436 yield message_by_name[msgname]
438 def make_identifier(headername):
439 '''Make #ifndef identifier that contains uppercase A-Z and digits 0-9'''
441 for c in headername.upper():
448 def generate_header(dependencies, headername, enums, messages, options):
449 '''Generate content for a header file.
450 Generates strings, which should be concatenated and stored to file.
453 yield '/* Automatically generated nanopb header */\n'
454 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
456 symbol = make_identifier(headername)
457 yield '#ifndef _PB_%s_\n' % symbol
458 yield '#define _PB_%s_\n' % symbol
459 yield options.libformat % ('pb.h')
462 for dependency in dependencies:
463 noext = os.path.splitext(dependency)[0]
464 yield options.genformat % (noext + '.' + options.extension + '.h')
467 yield '#ifdef __cplusplus\n'
468 yield 'extern "C" {\n'
471 yield '/* Enum definitions */\n'
473 yield str(enum) + '\n\n'
475 yield '/* Struct definitions */\n'
476 for msg in sort_dependencies(messages):
478 yield str(msg) + '\n\n'
480 yield '/* Default values for struct fields */\n'
482 yield msg.default_decl(True)
485 yield '/* Struct field encoding specification for nanopb */\n'
487 yield msg.fields_declaration() + '\n'
489 yield '\n#ifdef __cplusplus\n'
490 yield '} /* extern "C" */\n'
496 def generate_source(headername, enums, messages):
497 '''Generate content for a source file.'''
499 yield '/* Automatically generated nanopb constant definitions */\n'
500 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
501 yield options.genformat % (headername)
505 yield msg.default_decl(False)
510 yield msg.fields_definition() + '\n\n'
513 count_required_fields = lambda m: len([f for f in msg.fields if f.rules == 'REQUIRED'])
514 largest_msg = max(messages, key = count_required_fields)
515 largest_count = count_required_fields(largest_msg)
516 if largest_count > 64:
517 yield '\n/* Check that missing required fields will be properly detected */\n'
518 yield '#if PB_MAX_REQUIRED_FIELDS < %d\n' % largest_count
519 yield '#error Properly detecting missing required fields in %s requires \\\n' % largest_msg.name
520 yield ' setting PB_MAX_REQUIRED_FIELDS to %d or more.\n' % largest_count
523 # Add checks for numeric limits
529 checks_msgnames.append(msg.name)
530 for field in msg.fields:
531 status = field.largest_field_value()
532 if isinstance(status, (str, unicode)):
533 checks.append(status)
536 worst_field = str(field.struct_name) + '.' + str(field.name)
538 if worst > 255 or checks:
539 yield '\n/* Check that field information fits in pb_field_t */\n'
542 yield '#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT)\n'
544 yield '#error Field descriptor for %s is too large. Define PB_FIELD_16BIT to fix this.\n' % worst_field
546 assertion = ' && '.join(str(c) + ' < 256' for c in checks)
547 msgs = '_'.join(str(n) for n in checks_msgnames)
548 yield 'STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
551 if worst > 65535 or checks:
552 yield '#if !defined(PB_FIELD_32BIT)\n'
554 yield '#error Field descriptor for %s is too large. Define PB_FIELD_32BIT to fix this.\n' % worst_field
556 assertion = ' && '.join(str(c) + ' < 65536' for c in checks)
557 msgs = '_'.join(str(n) for n in checks_msgnames)
558 yield 'STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
561 # Add check for sizeof(double)
564 for field in msg.fields:
565 if field.ctype == 'double':
570 yield '/* On some platforms (such as AVR), double is really float.\n'
571 yield ' * These are not directly supported by nanopb, but see example_avr_double.\n'
572 yield ' * To get rid of this error, remove any double fields from your .proto.\n'
574 yield 'STATIC_ASSERT(sizeof(double) == 8, DOUBLE_MUST_BE_8_BYTES)\n'
579 # ---------------------------------------------------------------------------
580 # Command line interface
581 # ---------------------------------------------------------------------------
585 from optparse import OptionParser
586 import google.protobuf.text_format as text_format
588 optparser = OptionParser(
589 usage = "Usage: nanopb_generator.py [options] file.pb ...",
590 epilog = "Compile file.pb from file.proto by: 'protoc -ofile.pb file.proto'. " +
591 "Output will be written to file.pb.h and file.pb.c.")
592 optparser.add_option("-x", dest="exclude", metavar="FILE", action="append", default=[],
593 help="Exclude file from generated #include list.")
594 optparser.add_option("-e", "--extension", dest="extension", metavar="EXTENSION", default="pb",
595 help="Set extension to use instead of 'pb' for generated files. [default: %default]")
596 optparser.add_option("-Q", "--generated-include-format", dest="genformat",
597 metavar="FORMAT", default='#include "%s"\n',
598 help="Set format string to use for including other .pb.h files. [default: %default]")
599 optparser.add_option("-L", "--library-include-format", dest="libformat",
600 metavar="FORMAT", default='#include <%s>\n',
601 help="Set format string to use for including the nanopb pb.h header. [default: %default]")
602 optparser.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False,
603 help="Don't print anything except errors.")
604 optparser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
605 help="Print more information.")
606 optparser.add_option("-s", dest="settings", metavar="OPTION:VALUE", action="append", default=[],
607 help="Set generator option (max_size, max_count etc.).")
609 def get_nanopb_suboptions(subdesc, options):
610 '''Get copy of options, and merge information from subdesc.'''
611 new_options = nanopb_pb2.NanoPBOptions()
612 new_options.CopyFrom(options)
614 if isinstance(subdesc.options, descriptor.FieldOptions):
615 ext_type = nanopb_pb2.nanopb
616 elif isinstance(subdesc.options, descriptor.FileOptions):
617 ext_type = nanopb_pb2.nanopb_fileopt
618 elif isinstance(subdesc.options, descriptor.MessageOptions):
619 ext_type = nanopb_pb2.nanopb_msgopt
620 elif isinstance(subdesc.options, descriptor.EnumOptions):
621 ext_type = nanopb_pb2.nanopb_enumopt
623 raise Exception("Unknown options type")
625 if subdesc.options.HasExtension(ext_type):
626 ext = subdesc.options.Extensions[ext_type]
627 new_options.MergeFrom(ext)
631 def process(filenames, options):
632 '''Process the files given on the command line.'''
635 optparser.print_help()
639 options.verbose = False
641 toplevel_options = nanopb_pb2.NanoPBOptions()
642 for s in options.settings:
643 text_format.Merge(s, toplevel_options)
645 for filename in filenames:
646 data = open(filename, 'rb').read()
647 fdesc = descriptor.FileDescriptorSet.FromString(data)
649 file_options = get_nanopb_suboptions(fdesc.file[0], toplevel_options)
652 print "Options for " + filename + ":"
653 print text_format.MessageToString(file_options)
655 enums, messages = parse_file(fdesc.file[0], file_options)
657 noext = os.path.splitext(filename)[0]
658 headername = noext + '.' + options.extension + '.h'
659 sourcename = noext + '.' + options.extension + '.c'
660 headerbasename = os.path.basename(headername)
662 if not options.quiet:
663 print "Writing to " + headername + " and " + sourcename
665 # List of .proto files that should not be included in the C header file
666 # even if they are mentioned in the source .proto.
667 excludes = ['nanopb.proto', 'google/protobuf/descriptor.proto'] + options.exclude
668 dependencies = [d for d in fdesc.file[0].dependency if d not in excludes]
670 header = open(headername, 'w')
671 for part in generate_header(dependencies, headerbasename, enums, messages, options):
674 source = open(sourcename, 'w')
675 for part in generate_source(headerbasename, enums, messages):
680 if __name__ == '__main__':
681 options, filenames = optparser.parse_args()
682 status = process(filenames, options)