1 '''Generate header file for nanopb from a ProtoBuf FileDescriptorSet.'''
4 import google.protobuf.descriptor_pb2 as descriptor
7 print "*************************************************************"
8 print "*** Could not import the Google protobuf Python libraries ***"
9 print "*** Try installing package 'python-protobuf' or similar. ***"
10 print "*************************************************************"
18 print "***************************************************************"
19 print "*** Could not import the precompiled nanopb_pb2.py. ***"
20 print "*** Run 'make' in the 'generator' folder to update the file.***"
21 print "***************************************************************"
30 # ---------------------------------------------------------------------------
31 # Generation of single fields
32 # ---------------------------------------------------------------------------
37 # Values are tuple (c type, pb ltype)
38 FieldD = descriptor.FieldDescriptorProto
40 FieldD.TYPE_BOOL: ('bool', 'PB_LTYPE_VARINT'),
41 FieldD.TYPE_DOUBLE: ('double', 'PB_LTYPE_FIXED64'),
42 FieldD.TYPE_FIXED32: ('uint32_t', 'PB_LTYPE_FIXED32'),
43 FieldD.TYPE_FIXED64: ('uint64_t', 'PB_LTYPE_FIXED64'),
44 FieldD.TYPE_FLOAT: ('float', 'PB_LTYPE_FIXED32'),
45 FieldD.TYPE_INT32: ('int32_t', 'PB_LTYPE_VARINT'),
46 FieldD.TYPE_INT64: ('int64_t', 'PB_LTYPE_VARINT'),
47 FieldD.TYPE_SFIXED32: ('int32_t', 'PB_LTYPE_FIXED32'),
48 FieldD.TYPE_SFIXED64: ('int64_t', 'PB_LTYPE_FIXED64'),
49 FieldD.TYPE_SINT32: ('int32_t', 'PB_LTYPE_SVARINT'),
50 FieldD.TYPE_SINT64: ('int64_t', 'PB_LTYPE_SVARINT'),
51 FieldD.TYPE_UINT32: ('uint32_t', 'PB_LTYPE_VARINT'),
52 FieldD.TYPE_UINT64: ('uint64_t', 'PB_LTYPE_VARINT')
56 '''Keeps a set of nested names and formats them to C identifier.
57 You can subclass this with your own implementation.
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 names_from_type_name(type_name):
76 '''Parse Names() from FieldDescriptorProto type_name'''
77 if type_name[0] != '.':
78 raise NotImplementedError("Lookup of non-absolute type names is not supported")
79 return Names(type_name[1:].split('.'))
82 def __init__(self, names, desc, enum_options):
83 '''desc is EnumDescriptorProto'''
84 self.names = names + desc.name
85 self.values = [(self.names + x.name, x.number) for x in desc.value]
88 result = 'typedef enum _%s {\n' % self.names
89 result += ',\n'.join([" %s = %d" % x for x in self.values])
90 result += '\n} %s;' % self.names
94 def __init__(self, struct_name, desc, field_options):
95 '''desc is FieldDescriptorProto'''
96 self.tag = desc.number
97 self.struct_name = struct_name
101 self.max_count = None
104 # Parse field options
105 if field_options.HasField("max_size"):
106 self.max_size = field_options.max_size
108 if field_options.HasField("max_count"):
109 self.max_count = field_options.max_count
111 if desc.HasField('default_value'):
112 self.default = desc.default_value
115 # HTYPE is the high-order nibble of nanopb field description,
116 # defining whether value is required/optional/repeated.
118 if desc.label == FieldD.LABEL_REQUIRED:
119 self.htype = 'PB_HTYPE_REQUIRED'
120 elif desc.label == FieldD.LABEL_OPTIONAL:
121 self.htype = 'PB_HTYPE_OPTIONAL'
122 elif desc.label == FieldD.LABEL_REPEATED:
123 if self.max_count is None:
124 can_be_static = False
126 self.htype = 'PB_HTYPE_ARRAY'
127 self.array_decl = '[%d]' % self.max_count
129 raise NotImplementedError(desc.label)
131 # Decide LTYPE and CTYPE
132 # LTYPE is the low-order nibble of nanopb field description,
133 # defining how to decode an individual value.
134 # CTYPE is the name of the c type to use in the struct.
135 if datatypes.has_key(desc.type):
136 self.ctype, self.ltype = datatypes[desc.type]
137 elif desc.type == FieldD.TYPE_ENUM:
138 self.ltype = 'PB_LTYPE_VARINT'
139 self.ctype = names_from_type_name(desc.type_name)
140 if self.default is not None:
141 self.default = self.ctype + self.default
142 elif desc.type == FieldD.TYPE_STRING:
143 self.ltype = 'PB_LTYPE_STRING'
144 if self.max_size is None:
145 can_be_static = False
148 self.array_decl += '[%d]' % self.max_size
149 elif desc.type == FieldD.TYPE_BYTES:
150 self.ltype = 'PB_LTYPE_BYTES'
151 if self.max_size is None:
152 can_be_static = False
154 self.ctype = self.struct_name + self.name + 't'
155 elif desc.type == FieldD.TYPE_MESSAGE:
156 self.ltype = 'PB_LTYPE_SUBMESSAGE'
157 self.ctype = self.submsgname = names_from_type_name(desc.type_name)
159 raise NotImplementedError(desc.type)
161 if field_options.type == nanopb_pb2.FT_DEFAULT:
163 field_options.type = nanopb_pb2.FT_STATIC
165 field_options.type = nanopb_pb2.FT_CALLBACK
167 if field_options.type == nanopb_pb2.FT_STATIC and not can_be_static:
168 raise Exception("Field %s is defined as static, but max_size or max_count is not given." % self.name)
170 if field_options.type == nanopb_pb2.FT_CALLBACK:
171 self.htype = 'PB_HTYPE_CALLBACK'
172 self.ctype = 'pb_callback_t'
175 def __cmp__(self, other):
176 return cmp(self.tag, other.tag)
179 if self.htype == 'PB_HTYPE_OPTIONAL':
180 result = ' bool has_' + self.name + ';\n'
181 elif self.htype == 'PB_HTYPE_ARRAY':
182 result = ' size_t ' + self.name + '_count;\n'
185 result += ' %s %s%s;' % (self.ctype, self.name, self.array_decl)
189 '''Return definitions for any special types this field might need.'''
190 if self.ltype == 'PB_LTYPE_BYTES' and self.max_size is not None:
191 result = 'typedef struct {\n'
192 result += ' size_t size;\n'
193 result += ' uint8_t bytes[%d];\n' % self.max_size
194 result += '} %s;\n' % self.ctype
199 def default_decl(self, declaration_only = False):
200 '''Return definition for this field's default value.'''
201 if self.default is None:
204 if self.ltype == 'PB_LTYPE_STRING':
206 if self.max_size is None:
207 return None # Not implemented
209 array_decl = '[%d]' % (self.max_size + 1)
210 default = str(self.default).encode('string_escape')
211 default = default.replace('"', '\\"')
212 default = '"' + default + '"'
213 elif self.ltype == 'PB_LTYPE_BYTES':
214 data = self.default.decode('string_escape')
215 data = ['0x%02x' % ord(c) for c in data]
217 if self.max_size is None:
218 return None # Not implemented
222 default = '{%d, {%s}}' % (len(data), ','.join(data))
225 ctype, default = self.ctype, self.default
229 return 'extern const %s %s_default%s;' % (ctype, self.struct_name + self.name, array_decl)
231 return 'const %s %s_default%s = %s;' % (ctype, self.struct_name + self.name, array_decl, default)
233 def pb_field_t(self, prev_field_name):
234 '''Return the pb_field_t initializer to use in the constant array.
235 prev_field_name is the name of the previous field or None.
237 result = ' {%d, ' % self.tag
238 result += '(pb_type_t) ((int) ' + self.htype
239 if self.ltype is not None:
240 result += ' | (int) ' + self.ltype
243 if prev_field_name is None:
244 result += ' offsetof(%s, %s),' % (self.struct_name, self.name)
246 result += ' pb_delta_end(%s, %s, %s),' % (self.struct_name, self.name, prev_field_name)
248 if self.htype == 'PB_HTYPE_OPTIONAL':
249 result += '\n pb_delta(%s, has_%s, %s),' % (self.struct_name, self.name, self.name)
250 elif self.htype == 'PB_HTYPE_ARRAY':
251 result += '\n pb_delta(%s, %s_count, %s),' % (self.struct_name, self.name, self.name)
256 if self.htype == 'PB_HTYPE_ARRAY':
257 result += '\n pb_membersize(%s, %s[0]),' % (self.struct_name, self.name)
258 result += ('\n pb_membersize(%s, %s) / pb_membersize(%s, %s[0]),'
259 % (self.struct_name, self.name, self.struct_name, self.name))
261 result += '\n pb_membersize(%s, %s),' % (self.struct_name, self.name)
264 if self.ltype == 'PB_LTYPE_SUBMESSAGE':
265 result += '\n &%s_fields}' % self.submsgname
266 elif self.default is None or self.htype == 'PB_HTYPE_CALLBACK':
269 result += '\n &%s_default}' % (self.struct_name + self.name)
273 def largest_field_value(self):
274 '''Determine if this field needs 16bit or 32bit pb_field_t structure to compile properly.
275 Returns numeric value or a C-expression for assert.'''
276 if self.ltype == 'PB_LTYPE_SUBMESSAGE':
277 if self.htype == 'PB_HTYPE_ARRAY':
278 return 'pb_membersize(%s, %s[0])' % (self.struct_name, self.name)
280 return 'pb_membersize(%s, %s)' % (self.struct_name, self.name)
282 return max(self.tag, self.max_size, self.max_count)
289 # ---------------------------------------------------------------------------
290 # Generation of messages (structures)
291 # ---------------------------------------------------------------------------
295 def __init__(self, names, desc, message_options):
297 self.fields = [Field(self.name, f, get_nanopb_suboptions(f, message_options)) for f in desc.field]
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
307 result += '\n'.join([str(f) for f in self.ordered_fields])
308 result += '\n} %s;' % self.name
313 for field in self.fields:
314 types = field.types()
315 if types is not None:
316 result += types + '\n'
319 def default_decl(self, declaration_only = False):
321 for field in self.fields:
322 default = field.default_decl(declaration_only)
323 if default is not None:
324 result += default + '\n'
327 def fields_declaration(self):
328 result = 'extern const pb_field_t %s_fields[%d];' % (self.name, len(self.fields) + 1)
331 def fields_definition(self):
332 result = 'const pb_field_t %s_fields[%d] = {\n' % (self.name, len(self.fields) + 1)
335 for field in self.ordered_fields:
336 result += field.pb_field_t(prev)
340 result += ' PB_LAST_FIELD\n};'
348 # ---------------------------------------------------------------------------
349 # Processing of entire .proto files
350 # ---------------------------------------------------------------------------
353 def iterate_messages(desc, names = Names()):
354 '''Recursively find all messages. For each, yield name, DescriptorProto.'''
355 if hasattr(desc, 'message_type'):
356 submsgs = desc.message_type
358 submsgs = desc.nested_type
360 for submsg in submsgs:
361 sub_names = names + submsg.name
362 yield sub_names, submsg
364 for x in iterate_messages(submsg, sub_names):
367 def parse_file(fdesc, file_options):
368 '''Takes a FileDescriptorProto and returns tuple (enum, messages).'''
374 base_name = Names(fdesc.package.split('.'))
378 for enum in fdesc.enum_type:
379 enums.append(Enum(base_name, enum, file_options))
381 for names, message in iterate_messages(fdesc, base_name):
382 message_options = get_nanopb_suboptions(message, file_options)
383 messages.append(Message(names, message, message_options))
384 for enum in message.enum_type:
385 enums.append(Enum(names, enum, message_options))
387 return enums, messages
391 From http://code.activestate.com/recipes/577413-topological-sort/
392 This function is under the MIT license.
394 for k, v in data.items():
395 v.discard(k) # Ignore self dependencies
396 extra_items_in_deps = reduce(set.union, data.values(), set()) - set(data.keys())
397 data.update(dict([(item, set()) for item in extra_items_in_deps]))
399 ordered = set(item for item,dep in data.items() if not dep)
402 for item in sorted(ordered):
404 data = dict([(item, (dep - ordered)) for item,dep in data.items()
405 if item not in ordered])
406 assert not data, "A cyclic dependency exists amongst %r" % data
408 def sort_dependencies(messages):
409 '''Sort a list of Messages based on dependencies.'''
412 for message in messages:
413 dependencies[str(message.name)] = set(message.get_dependencies())
414 message_by_name[str(message.name)] = message
416 for msgname in toposort2(dependencies):
417 if msgname in message_by_name:
418 yield message_by_name[msgname]
420 def generate_header(dependencies, headername, enums, messages):
421 '''Generate content for a header file.
422 Generates strings, which should be concatenated and stored to file.
425 yield '/* Automatically generated nanopb header */\n'
427 symbol = headername.replace('.', '_').upper()
428 yield '#ifndef _PB_%s_\n' % symbol
429 yield '#define _PB_%s_\n' % symbol
430 yield '#include <pb.h>\n\n'
432 for dependency in dependencies:
433 noext = os.path.splitext(dependency)[0]
434 yield '#include "%s.pb.h"\n' % noext
437 yield '/* Enum definitions */\n'
439 yield str(enum) + '\n\n'
441 yield '/* Struct definitions */\n'
442 for msg in sort_dependencies(messages):
444 yield str(msg) + '\n\n'
446 yield '/* Default values for struct fields */\n'
448 yield msg.default_decl(True)
451 yield '/* Struct field encoding specification for nanopb */\n'
453 yield msg.fields_declaration() + '\n'
456 count_required_fields = lambda m: len([f for f in msg.fields if f.htype == 'PB_HTYPE_REQUIRED'])
457 largest_msg = max(messages, key = count_required_fields)
458 largest_count = count_required_fields(largest_msg)
459 if largest_count > 64:
460 yield '\n/* Check that missing required fields will be properly detected */\n'
461 yield '#if PB_MAX_REQUIRED_FIELDS < %d\n' % largest_count
462 yield '#error Properly detecting missing required fields in %s requires \\\n' % largest_msg.name
463 yield ' setting PB_MAX_REQUIRED_FIELDS to %d or more.\n' % largest_count
470 for field in msg.fields:
471 status = field.largest_field_value()
472 if isinstance(status, (str, unicode)):
473 checks.append(status)
476 worst_field = str(field.struct_name) + '.' + str(field.name)
478 if worst > 255 or checks:
479 yield '\n/* Check that field information fits in pb_field_t */\n'
482 yield '#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT)\n'
484 yield '#error Field descriptor for %s is too large. Define PB_FIELD_16BIT to fix this.\n' % worst_field
486 assertion = ' && '.join(str(c) + ' < 256' for c in checks)
487 yield 'STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_16BIT)\n' % assertion
490 if worst > 65535 or checks:
491 yield '#if !defined(PB_FIELD_32BIT)\n'
493 yield '#error Field descriptor for %s is too large. Define PB_FIELD_32BIT to fix this.\n' % worst_field
495 assertion = ' && '.join(str(c) + ' < 65536' for c in checks)
496 yield 'STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_32BIT)\n' % assertion
502 def generate_source(headername, enums, messages):
503 '''Generate content for a source file.'''
505 yield '/* Automatically generated nanopb constant definitions */\n'
506 yield '#include "%s"\n\n' % headername
509 yield msg.default_decl(False)
514 yield msg.fields_definition() + '\n\n'
518 # ---------------------------------------------------------------------------
519 # Command line interface
520 # ---------------------------------------------------------------------------
524 from optparse import OptionParser
525 import google.protobuf.text_format as text_format
527 optparser = OptionParser(
528 usage = "Usage: nanopb_generator.py [options] file.pb ...",
529 epilog = "Compile file.pb from file.proto by: 'protoc -ofile.pb file.proto'. " +
530 "Output will be written to file.pb.h and file.pb.c.")
531 optparser.add_option("-x", dest="exclude", metavar="FILE", action="append", default=[],
532 help="Exclude file from generated #include list.")
533 optparser.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False,
534 help="Don't print anything except errors.")
535 optparser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
536 help="Print more information.")
537 optparser.add_option("-s", dest="settings", metavar="OPTION:VALUE", action="append", default=[],
538 help="Set generator option (max_size, max_count etc.).")
540 def get_nanopb_suboptions(subdesc, options):
541 '''Get copy of options, and merge information from subdesc.'''
542 new_options = nanopb_pb2.NanoPBOptions()
543 new_options.CopyFrom(options)
545 if isinstance(subdesc.options, descriptor.FieldOptions):
546 ext_type = nanopb_pb2.nanopb
547 elif isinstance(subdesc.options, descriptor.FileOptions):
548 ext_type = nanopb_pb2.nanopb_fileopt
549 elif isinstance(subdesc.options, descriptor.MessageOptions):
550 ext_type = nanopb_pb2.nanopb_msgopt
552 raise Exception("Unknown options type")
554 if subdesc.options.HasExtension(ext_type):
555 ext = subdesc.options.Extensions[ext_type]
556 new_options.MergeFrom(ext)
560 def process(filenames, options):
561 '''Process the files given on the command line.'''
564 optparser.print_help()
568 options.verbose = False
570 toplevel_options = nanopb_pb2.NanoPBOptions()
571 for s in options.settings:
572 text_format.Merge(s, toplevel_options)
574 for filename in filenames:
575 data = open(filename, 'rb').read()
576 fdesc = descriptor.FileDescriptorSet.FromString(data)
578 file_options = get_nanopb_suboptions(fdesc.file[0], toplevel_options)
581 print "Options for " + filename + ":"
582 print text_format.MessageToString(file_options)
584 enums, messages = parse_file(fdesc.file[0], file_options)
586 noext = os.path.splitext(filename)[0]
587 headername = noext + '.pb.h'
588 sourcename = noext + '.pb.c'
589 headerbasename = os.path.basename(headername)
591 if not options.quiet:
592 print "Writing to " + headername + " and " + sourcename
594 # List of .proto files that should not be included in the C header file
595 # even if they are mentioned in the source .proto.
596 excludes = ['nanopb.proto', 'google/protobuf/descriptor.proto'] + options.exclude
597 dependencies = [d for d in fdesc.file[0].dependency if d not in excludes]
599 header = open(headername, 'w')
600 for part in generate_header(dependencies, headerbasename, enums, messages):
603 source = open(sourcename, 'w')
604 for part in generate_source(headerbasename, enums, messages):
609 if __name__ == '__main__':
610 options, filenames = optparser.parse_args()
611 status = process(filenames, options)