3 '''Generate header file for nanopb from a ProtoBuf FileDescriptorSet.'''
4 nanopb_version = "nanopb-0.2.5-dev"
7 import google.protobuf.descriptor_pb2 as descriptor
8 import google.protobuf.text_format as text_format
11 print "*************************************************************"
12 print "*** Could not import the Google protobuf Python libraries ***"
13 print "*** Try installing package 'python-protobuf' or similar. ***"
14 print "*************************************************************"
22 print "***************************************************************"
23 print "*** Could not import the precompiled nanopb_pb2.py. ***"
24 print "*** Run 'make' in the 'generator' folder to update the file.***"
25 print "***************************************************************"
34 # ---------------------------------------------------------------------------
35 # Generation of single fields
36 # ---------------------------------------------------------------------------
41 # Values are tuple (c type, pb type, encoded size)
42 FieldD = descriptor.FieldDescriptorProto
44 FieldD.TYPE_BOOL: ('bool', 'BOOL', 1),
45 FieldD.TYPE_DOUBLE: ('double', 'DOUBLE', 8),
46 FieldD.TYPE_FIXED32: ('uint32_t', 'FIXED32', 4),
47 FieldD.TYPE_FIXED64: ('uint64_t', 'FIXED64', 8),
48 FieldD.TYPE_FLOAT: ('float', 'FLOAT', 4),
49 FieldD.TYPE_INT32: ('int32_t', 'INT32', 5),
50 FieldD.TYPE_INT64: ('int64_t', 'INT64', 10),
51 FieldD.TYPE_SFIXED32: ('int32_t', 'SFIXED32', 4),
52 FieldD.TYPE_SFIXED64: ('int64_t', 'SFIXED64', 8),
53 FieldD.TYPE_SINT32: ('int32_t', 'SINT32', 5),
54 FieldD.TYPE_SINT64: ('int64_t', 'SINT64', 10),
55 FieldD.TYPE_UINT32: ('uint32_t', 'UINT32', 5),
56 FieldD.TYPE_UINT64: ('uint64_t', 'UINT64', 10)
60 '''Keeps a set of nested names and formats them to C identifier.'''
61 def __init__(self, parts = ()):
62 if isinstance(parts, Names):
64 self.parts = tuple(parts)
67 return '_'.join(self.parts)
69 def __add__(self, other):
70 if isinstance(other, (str, unicode)):
71 return Names(self.parts + (other,))
72 elif isinstance(other, tuple):
73 return Names(self.parts + other)
75 raise ValueError("Name parts should be of type str")
77 def __eq__(self, other):
78 return isinstance(other, Names) and self.parts == other.parts
80 def names_from_type_name(type_name):
81 '''Parse Names() from FieldDescriptorProto type_name'''
82 if type_name[0] != '.':
83 raise NotImplementedError("Lookup of non-absolute type names is not supported")
84 return Names(type_name[1:].split('.'))
86 def varint_max_size(max_value):
87 '''Returns the maximum number of bytes a varint can take when encoded.'''
88 for i in range(1, 11):
89 if (max_value >> (i * 7)) == 0:
91 raise ValueError("Value too large for varint: " + str(max_value))
93 assert varint_max_size(0) == 1
94 assert varint_max_size(127) == 1
95 assert varint_max_size(128) == 2
98 '''Class used to represent the encoded size of a field or a message.
99 Consists of a combination of symbolic sizes and integer sizes.'''
100 def __init__(self, value = 0, symbols = []):
101 if isinstance(value, (str, Names)):
102 symbols = [str(value)]
105 self.symbols = symbols
107 def __add__(self, other):
108 if isinstance(other, (int, long)):
109 return EncodedSize(self.value + other, self.symbols)
110 elif isinstance(other, (str, Names)):
111 return EncodedSize(self.value, self.symbols + [str(other)])
112 elif isinstance(other, EncodedSize):
113 return EncodedSize(self.value + other.value, self.symbols + other.symbols)
115 raise ValueError("Cannot add size: " + repr(other))
117 def __mul__(self, other):
118 if isinstance(other, (int, long)):
119 return EncodedSize(self.value * other, [str(other) + '*' + s for s in self.symbols])
121 raise ValueError("Cannot multiply size: " + repr(other))
125 return str(self.value)
127 return '(' + str(self.value) + ' + ' + ' + '.join(self.symbols) + ')'
129 def upperlimit(self):
136 def __init__(self, names, desc, enum_options):
137 '''desc is EnumDescriptorProto'''
139 self.options = enum_options
140 self.names = names + desc.name
142 if enum_options.long_names:
143 self.values = [(self.names + x.name, x.number) for x in desc.value]
145 self.values = [(names + x.name, x.number) for x in desc.value]
147 self.value_longnames = [self.names + x.name for x in desc.value]
150 result = 'typedef enum _%s {\n' % self.names
151 result += ',\n'.join([" %s = %d" % x for x in self.values])
152 result += '\n} %s;' % self.names
156 def __init__(self, struct_name, desc, field_options):
157 '''desc is FieldDescriptorProto'''
158 self.tag = desc.number
159 self.struct_name = struct_name
160 self.name = desc.name
163 self.max_count = None
167 # Parse field options
168 if field_options.HasField("max_size"):
169 self.max_size = field_options.max_size
171 if field_options.HasField("max_count"):
172 self.max_count = field_options.max_count
174 if desc.HasField('default_value'):
175 self.default = desc.default_value
177 # Check field rules, i.e. required/optional/repeated.
179 if desc.label == FieldD.LABEL_REQUIRED:
180 self.rules = 'REQUIRED'
181 elif desc.label == FieldD.LABEL_OPTIONAL:
182 self.rules = 'OPTIONAL'
183 elif desc.label == FieldD.LABEL_REPEATED:
184 self.rules = 'REPEATED'
185 if self.max_count is None:
186 can_be_static = False
188 self.array_decl = '[%d]' % self.max_count
190 raise NotImplementedError(desc.label)
192 # Decide the C data type to use in the struct.
193 if datatypes.has_key(desc.type):
194 self.ctype, self.pbtype, self.enc_size = datatypes[desc.type]
195 elif desc.type == FieldD.TYPE_ENUM:
197 self.ctype = names_from_type_name(desc.type_name)
198 if self.default is not None:
199 self.default = self.ctype + self.default
200 self.enc_size = 5 # protoc rejects enum values > 32 bits
201 elif desc.type == FieldD.TYPE_STRING:
202 self.pbtype = 'STRING'
203 if self.max_size is None:
204 can_be_static = False
207 self.array_decl += '[%d]' % self.max_size
208 self.enc_size = varint_max_size(self.max_size) + self.max_size
209 elif desc.type == FieldD.TYPE_BYTES:
210 self.pbtype = 'BYTES'
211 if self.max_size is None:
212 can_be_static = False
214 self.ctype = self.struct_name + self.name + 't'
215 self.enc_size = varint_max_size(self.max_size) + self.max_size
216 elif desc.type == FieldD.TYPE_MESSAGE:
217 self.pbtype = 'MESSAGE'
218 self.ctype = self.submsgname = names_from_type_name(desc.type_name)
219 self.enc_size = None # Needs to be filled in after the message type is available
221 raise NotImplementedError(desc.type)
223 if field_options.type == nanopb_pb2.FT_DEFAULT:
225 field_options.type = nanopb_pb2.FT_STATIC
227 field_options.type = nanopb_pb2.FT_CALLBACK
229 if field_options.type == nanopb_pb2.FT_STATIC and not can_be_static:
230 raise Exception("Field %s is defined as static, but max_size or max_count is not given." % self.name)
232 if field_options.type == nanopb_pb2.FT_STATIC:
233 self.allocation = 'STATIC'
234 elif field_options.type == nanopb_pb2.FT_CALLBACK:
235 self.allocation = 'CALLBACK'
236 self.ctype = 'pb_callback_t'
239 raise NotImplementedError(field_options.type)
241 def __cmp__(self, other):
242 return cmp(self.tag, other.tag)
245 if self.rules == 'OPTIONAL' and self.allocation == 'STATIC':
246 result = ' bool has_' + self.name + ';\n'
247 elif self.rules == 'REPEATED' and self.allocation == 'STATIC':
248 result = ' size_t ' + self.name + '_count;\n'
251 result += ' %s %s%s;' % (self.ctype, self.name, self.array_decl)
255 '''Return definitions for any special types this field might need.'''
256 if self.pbtype == 'BYTES' and self.allocation == 'STATIC':
257 result = 'typedef struct {\n'
258 result += ' size_t size;\n'
259 result += ' uint8_t bytes[%d];\n' % self.max_size
260 result += '} %s;\n' % self.ctype
265 def default_decl(self, declaration_only = False):
266 '''Return definition for this field's default value.'''
267 if self.default is None:
270 ctype, default = self.ctype, self.default
273 if self.pbtype == 'STRING':
274 if self.allocation != 'STATIC':
275 return None # Not implemented
277 array_decl = '[%d]' % self.max_size
278 default = str(self.default).encode('string_escape')
279 default = default.replace('"', '\\"')
280 default = '"' + default + '"'
281 elif self.pbtype == 'BYTES':
282 if self.allocation != 'STATIC':
283 return None # Not implemented
285 data = self.default.decode('string_escape')
286 data = ['0x%02x' % ord(c) for c in data]
287 default = '{%d, {%s}}' % (len(data), ','.join(data))
290 return 'extern const %s %s_default%s;' % (ctype, self.struct_name + self.name, array_decl)
292 return 'const %s %s_default%s = %s;' % (ctype, self.struct_name + self.name, array_decl, default)
295 '''Return the #define for the tag number of this field.'''
296 identifier = '%s_%s_tag' % (self.struct_name, self.name)
297 return '#define %-40s %d\n' % (identifier, self.tag)
299 def pb_field_t(self, prev_field_name):
300 '''Return the pb_field_t initializer to use in the constant array.
301 prev_field_name is the name of the previous field or None.
303 result = ' PB_FIELD2(%3d, ' % self.tag
304 result += '%-8s, ' % self.pbtype
305 result += '%s, ' % self.rules
306 result += '%s, ' % self.allocation
307 result += '%s, ' % ("FIRST" if not prev_field_name else "OTHER")
308 result += '%s, ' % self.struct_name
309 result += '%s, ' % self.name
310 result += '%s, ' % (prev_field_name or self.name)
312 if self.pbtype == 'MESSAGE':
313 result += '&%s_fields)' % self.submsgname
314 elif self.default is None:
316 elif self.pbtype in ['BYTES', 'STRING'] and self.allocation != 'STATIC':
317 result += '0)' # Arbitrary size default values not implemented
319 result += '&%s_default)' % (self.struct_name + self.name)
323 def largest_field_value(self):
324 '''Determine if this field needs 16bit or 32bit pb_field_t structure to compile properly.
325 Returns numeric value or a C-expression for assert.'''
326 if self.pbtype == 'MESSAGE':
327 if self.rules == 'REPEATED' and self.allocation == 'STATIC':
328 return 'pb_membersize(%s, %s[0])' % (self.struct_name, self.name)
330 return 'pb_membersize(%s, %s)' % (self.struct_name, self.name)
332 return max(self.tag, self.max_size, self.max_count)
334 def encoded_size(self, allmsgs):
335 '''Return the maximum size that this field can take when encoded,
336 including the field tag. If the size cannot be determined, returns
339 if self.allocation != 'STATIC':
342 if self.pbtype == 'MESSAGE':
344 if msg.name == self.submsgname:
345 encsize = msg.encoded_size(allmsgs)
347 return None # Submessage size is indeterminate
349 # Include submessage length prefix
350 encsize += varint_max_size(encsize.upperlimit())
353 # Submessage cannot be found, this currently occurs when
354 # the submessage type is defined in a different file.
355 # Instead of direct numeric value, reference the size that
356 # has been #defined in the other file.
357 encsize = EncodedSize(self.submsgname + 'size')
359 # We will have to make a conservative assumption on the length
360 # prefix size, though.
363 elif self.enc_size is None:
364 raise RuntimeError("Could not determine encoded size for %s.%s"
365 % (self.struct_name, self.name))
367 encsize = EncodedSize(self.enc_size)
369 encsize += varint_max_size(self.tag << 3) # Tag + wire type
371 if self.rules == 'REPEATED':
372 # Decoders must be always able to handle unpacked arrays.
373 # Therefore we have to reserve space for it, even though
374 # we emit packed arrays ourselves.
375 encsize *= self.max_count
380 class ExtensionRange(Field):
381 def __init__(self, struct_name, range_start, field_options):
382 '''Implements a special pb_extension_t* field in an extensible message
383 structure. The range_start signifies the index at which the extensions
384 start. Not necessarily all tags above this are extensions, it is merely
385 a speed optimization.
387 self.tag = range_start
388 self.struct_name = struct_name
389 self.name = 'extensions'
390 self.pbtype = 'EXTENSION'
391 self.rules = 'OPTIONAL'
392 self.allocation = 'CALLBACK'
393 self.ctype = 'pb_extension_t'
400 return ' pb_extension_t *extensions;'
408 def encoded_size(self, allmsgs):
409 # We exclude extensions from the count, because they cannot be known
410 # until runtime. Other option would be to return None here, but this
411 # way the value remains useful if extensions are not used.
412 return EncodedSize(0)
414 class ExtensionField(Field):
415 def __init__(self, struct_name, desc, field_options):
416 self.fullname = struct_name + desc.name
417 self.extendee_name = names_from_type_name(desc.extendee)
418 Field.__init__(self, self.fullname + 'struct', desc, field_options)
420 if self.rules != 'OPTIONAL':
424 self.rules = 'OPTEXT'
427 '''Return the #define for the tag number of this field.'''
428 identifier = '%s_tag' % self.fullname
429 return '#define %-40s %d\n' % (identifier, self.tag)
431 def extension_decl(self):
432 '''Declaration of the extension type in the .pb.h file'''
434 msg = '/* Extension field %s was skipped because only "optional"\n' % self.fullname
435 msg +=' type of extension fields is currently supported. */\n'
438 return 'extern const pb_extension_type_t %s;\n' % self.fullname
440 def extension_def(self):
441 '''Definition of the extension type in the .pb.c file'''
446 result = 'typedef struct {\n'
448 result += '\n} %s;\n\n' % self.struct_name
449 result += ('static const pb_field_t %s_field = \n %s;\n\n' %
450 (self.fullname, self.pb_field_t(None)))
451 result += 'const pb_extension_type_t %s = {\n' % self.fullname
454 result += ' &%s_field\n' % self.fullname
459 # ---------------------------------------------------------------------------
460 # Generation of messages (structures)
461 # ---------------------------------------------------------------------------
465 def __init__(self, names, desc, message_options):
470 field_options = get_nanopb_suboptions(f, message_options, self.name + f.name)
471 if field_options.type != nanopb_pb2.FT_IGNORE:
472 self.fields.append(Field(self.name, f, field_options))
474 if len(desc.extension_range) > 0:
475 field_options = get_nanopb_suboptions(desc, message_options, self.name + 'extensions')
476 range_start = min([r.start for r in desc.extension_range])
477 if field_options.type != nanopb_pb2.FT_IGNORE:
478 self.fields.append(ExtensionRange(self.name, range_start, field_options))
480 self.packed = message_options.packed_struct
481 self.ordered_fields = self.fields[:]
482 self.ordered_fields.sort()
484 def get_dependencies(self):
485 '''Get list of type names that this structure refers to.'''
486 return [str(field.ctype) for field in self.fields]
489 result = 'typedef struct _%s {\n' % self.name
491 if not self.ordered_fields:
492 # Empty structs are not allowed in C standard.
493 # Therefore add a dummy field if an empty message occurs.
494 result += ' uint8_t dummy_field;'
496 result += '\n'.join([str(f) for f in self.ordered_fields])
500 result += ' pb_packed'
502 result += ' %s;' % self.name
505 result = 'PB_PACKED_STRUCT_START\n' + result
506 result += '\nPB_PACKED_STRUCT_END'
512 for field in self.fields:
513 types = field.types()
514 if types is not None:
515 result += types + '\n'
518 def default_decl(self, declaration_only = False):
520 for field in self.fields:
521 default = field.default_decl(declaration_only)
522 if default is not None:
523 result += default + '\n'
526 def fields_declaration(self):
527 result = 'extern const pb_field_t %s_fields[%d];' % (self.name, len(self.fields) + 1)
530 def fields_definition(self):
531 result = 'const pb_field_t %s_fields[%d] = {\n' % (self.name, len(self.fields) + 1)
534 for field in self.ordered_fields:
535 result += field.pb_field_t(prev)
539 result += ' PB_LAST_FIELD\n};'
542 def encoded_size(self, allmsgs):
543 '''Return the maximum size that this message can take when encoded.
544 If the size cannot be determined, returns None.
546 size = EncodedSize(0)
547 for field in self.fields:
548 fsize = field.encoded_size(allmsgs)
556 # ---------------------------------------------------------------------------
557 # Processing of entire .proto files
558 # ---------------------------------------------------------------------------
561 def iterate_messages(desc, names = Names()):
562 '''Recursively find all messages. For each, yield name, DescriptorProto.'''
563 if hasattr(desc, 'message_type'):
564 submsgs = desc.message_type
566 submsgs = desc.nested_type
568 for submsg in submsgs:
569 sub_names = names + submsg.name
570 yield sub_names, submsg
572 for x in iterate_messages(submsg, sub_names):
575 def iterate_extensions(desc, names = Names()):
576 '''Recursively find all extensions.
577 For each, yield name, FieldDescriptorProto.
579 for extension in desc.extension:
580 yield names, extension
582 for subname, subdesc in iterate_messages(desc, names):
583 for extension in subdesc.extension:
584 yield subname, extension
586 def parse_file(fdesc, file_options):
587 '''Takes a FileDescriptorProto and returns tuple (enums, messages, extensions).'''
594 base_name = Names(fdesc.package.split('.'))
598 for enum in fdesc.enum_type:
599 enum_options = get_nanopb_suboptions(enum, file_options, base_name + enum.name)
600 enums.append(Enum(base_name, enum, enum_options))
602 for names, message in iterate_messages(fdesc, base_name):
603 message_options = get_nanopb_suboptions(message, file_options, names)
604 messages.append(Message(names, message, message_options))
605 for enum in message.enum_type:
606 enum_options = get_nanopb_suboptions(enum, message_options, names + enum.name)
607 enums.append(Enum(names, enum, enum_options))
609 for names, extension in iterate_extensions(fdesc, base_name):
610 field_options = get_nanopb_suboptions(extension, file_options, names)
611 if field_options.type != nanopb_pb2.FT_IGNORE:
612 extensions.append(ExtensionField(names, extension, field_options))
614 # Fix field default values where enum short names are used.
616 if not enum.options.long_names:
617 for message in messages:
618 for field in message.fields:
619 if field.default in enum.value_longnames:
620 idx = enum.value_longnames.index(field.default)
621 field.default = enum.values[idx][0]
623 return enums, messages, extensions
627 From http://code.activestate.com/recipes/577413-topological-sort/
628 This function is under the MIT license.
630 for k, v in data.items():
631 v.discard(k) # Ignore self dependencies
632 extra_items_in_deps = reduce(set.union, data.values(), set()) - set(data.keys())
633 data.update(dict([(item, set()) for item in extra_items_in_deps]))
635 ordered = set(item for item,dep in data.items() if not dep)
638 for item in sorted(ordered):
640 data = dict([(item, (dep - ordered)) for item,dep in data.items()
641 if item not in ordered])
642 assert not data, "A cyclic dependency exists amongst %r" % data
644 def sort_dependencies(messages):
645 '''Sort a list of Messages based on dependencies.'''
648 for message in messages:
649 dependencies[str(message.name)] = set(message.get_dependencies())
650 message_by_name[str(message.name)] = message
652 for msgname in toposort2(dependencies):
653 if msgname in message_by_name:
654 yield message_by_name[msgname]
656 def make_identifier(headername):
657 '''Make #ifndef identifier that contains uppercase A-Z and digits 0-9'''
659 for c in headername.upper():
666 def generate_header(dependencies, headername, enums, messages, extensions, options):
667 '''Generate content for a header file.
668 Generates strings, which should be concatenated and stored to file.
671 yield '/* Automatically generated nanopb header */\n'
672 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
674 symbol = make_identifier(headername)
675 yield '#ifndef _PB_%s_\n' % symbol
676 yield '#define _PB_%s_\n' % symbol
678 yield options.libformat % ('pb.h')
680 # no %s specified - use whatever was passed in as options.libformat
681 yield options.libformat
684 for dependency in dependencies:
685 noext = os.path.splitext(dependency)[0]
686 yield options.genformat % (noext + '.' + options.extension + '.h')
689 yield '#ifdef __cplusplus\n'
690 yield 'extern "C" {\n'
693 yield '/* Enum definitions */\n'
695 yield str(enum) + '\n\n'
697 yield '/* Struct definitions */\n'
698 for msg in sort_dependencies(messages):
700 yield str(msg) + '\n\n'
703 yield '/* Extensions */\n'
704 for extension in extensions:
705 yield extension.extension_decl()
708 yield '/* Default values for struct fields */\n'
710 yield msg.default_decl(True)
713 yield '/* Field tags (for use in manual encoding/decoding) */\n'
714 for msg in sort_dependencies(messages):
715 for field in msg.fields:
717 for extension in extensions:
718 yield extension.tags()
721 yield '/* Struct field encoding specification for nanopb */\n'
723 yield msg.fields_declaration() + '\n'
726 yield '/* Maximum encoded size of messages (where known) */\n'
728 msize = msg.encoded_size(messages)
729 if msize is not None:
730 identifier = '%s_size' % msg.name
731 yield '#define %-40s %s\n' % (identifier, msize)
734 yield '#ifdef __cplusplus\n'
735 yield '} /* extern "C" */\n'
741 def generate_source(headername, enums, messages, extensions, options):
742 '''Generate content for a source file.'''
744 yield '/* Automatically generated nanopb constant definitions */\n'
745 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
746 yield options.genformat % (headername)
750 yield msg.default_decl(False)
755 yield msg.fields_definition() + '\n\n'
757 for ext in extensions:
758 yield ext.extension_def() + '\n'
760 # Add checks for numeric limits
762 count_required_fields = lambda m: len([f for f in msg.fields if f.rules == 'REQUIRED'])
763 largest_msg = max(messages, key = count_required_fields)
764 largest_count = count_required_fields(largest_msg)
765 if largest_count > 64:
766 yield '\n/* Check that missing required fields will be properly detected */\n'
767 yield '#if PB_MAX_REQUIRED_FIELDS < %d\n' % largest_count
768 yield '#error Properly detecting missing required fields in %s requires \\\n' % largest_msg.name
769 yield ' setting PB_MAX_REQUIRED_FIELDS to %d or more.\n' % largest_count
777 checks_msgnames.append(msg.name)
778 for field in msg.fields:
779 status = field.largest_field_value()
780 if isinstance(status, (str, unicode)):
781 checks.append(status)
784 worst_field = str(field.struct_name) + '.' + str(field.name)
786 if worst > 255 or checks:
787 yield '\n/* Check that field information fits in pb_field_t */\n'
790 yield '#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT)\n'
792 yield '#error Field descriptor for %s is too large. Define PB_FIELD_16BIT to fix this.\n' % worst_field
794 assertion = ' && '.join(str(c) + ' < 256' for c in checks)
795 msgs = '_'.join(str(n) for n in checks_msgnames)
796 yield 'STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
799 if worst > 65535 or checks:
800 yield '#if !defined(PB_FIELD_32BIT)\n'
802 yield '#error Field descriptor for %s is too large. Define PB_FIELD_32BIT to fix this.\n' % worst_field
804 assertion = ' && '.join(str(c) + ' < 65536' for c in checks)
805 msgs = '_'.join(str(n) for n in checks_msgnames)
806 yield 'STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
809 # Add check for sizeof(double)
812 for field in msg.fields:
813 if field.ctype == 'double':
818 yield '/* On some platforms (such as AVR), double is really float.\n'
819 yield ' * These are not directly supported by nanopb, but see example_avr_double.\n'
820 yield ' * To get rid of this error, remove any double fields from your .proto.\n'
822 yield 'STATIC_ASSERT(sizeof(double) == 8, DOUBLE_MUST_BE_8_BYTES)\n'
826 # ---------------------------------------------------------------------------
827 # Options parsing for the .proto files
828 # ---------------------------------------------------------------------------
830 from fnmatch import fnmatch
832 def read_options_file(infile):
833 '''Parse a separate options file to list:
834 [(namemask, options), ...]
839 if not line or line.startswith('//') or line.startswith('#'):
842 parts = line.split(None, 1)
843 opts = nanopb_pb2.NanoPBOptions()
844 text_format.Merge(parts[1], opts)
845 results.append((parts[0], opts))
850 '''Ugly global variables, should find a good way to pass these.'''
851 verbose_options = False
852 separate_options = []
854 def get_nanopb_suboptions(subdesc, options, name):
855 '''Get copy of options, and merge information from subdesc.'''
856 new_options = nanopb_pb2.NanoPBOptions()
857 new_options.CopyFrom(options)
859 # Handle options defined in a separate file
860 dotname = '.'.join(name.parts)
861 for namemask, options in Globals.separate_options:
862 if fnmatch(dotname, namemask):
863 new_options.MergeFrom(options)
865 # Handle options defined in .proto
866 if isinstance(subdesc.options, descriptor.FieldOptions):
867 ext_type = nanopb_pb2.nanopb
868 elif isinstance(subdesc.options, descriptor.FileOptions):
869 ext_type = nanopb_pb2.nanopb_fileopt
870 elif isinstance(subdesc.options, descriptor.MessageOptions):
871 ext_type = nanopb_pb2.nanopb_msgopt
872 elif isinstance(subdesc.options, descriptor.EnumOptions):
873 ext_type = nanopb_pb2.nanopb_enumopt
875 raise Exception("Unknown options type")
877 if subdesc.options.HasExtension(ext_type):
878 ext = subdesc.options.Extensions[ext_type]
879 new_options.MergeFrom(ext)
881 if Globals.verbose_options:
882 print "Options for " + dotname + ":"
883 print text_format.MessageToString(new_options)
888 # ---------------------------------------------------------------------------
889 # Command line interface
890 # ---------------------------------------------------------------------------
894 from optparse import OptionParser
896 optparser = OptionParser(
897 usage = "Usage: nanopb_generator.py [options] file.pb ...",
898 epilog = "Compile file.pb from file.proto by: 'protoc -ofile.pb file.proto'. " +
899 "Output will be written to file.pb.h and file.pb.c.")
900 optparser.add_option("-x", dest="exclude", metavar="FILE", action="append", default=[],
901 help="Exclude file from generated #include list.")
902 optparser.add_option("-e", "--extension", dest="extension", metavar="EXTENSION", default="pb",
903 help="Set extension to use instead of 'pb' for generated files. [default: %default]")
904 optparser.add_option("-f", "--options-file", dest="options_file", metavar="FILE", default="%s.options",
905 help="Set name of a separate generator options file.")
906 optparser.add_option("-Q", "--generated-include-format", dest="genformat",
907 metavar="FORMAT", default='#include "%s"\n',
908 help="Set format string to use for including other .pb.h files. [default: %default]")
909 optparser.add_option("-L", "--library-include-format", dest="libformat",
910 metavar="FORMAT", default='#include <%s>\n',
911 help="Set format string to use for including the nanopb pb.h header. [default: %default]")
912 optparser.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False,
913 help="Don't print anything except errors.")
914 optparser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
915 help="Print more information.")
916 optparser.add_option("-s", dest="settings", metavar="OPTION:VALUE", action="append", default=[],
917 help="Set generator option (max_size, max_count etc.).")
919 def process_file(filename, fdesc, options):
920 '''Process a single file.
921 filename: The full path to the .proto or .pb source file, as string.
922 fdesc: The loaded FileDescriptorSet, or None to read from the input file.
923 options: Command line options as they come from OptionsParser.
926 {'headername': Name of header file,
927 'headerdata': Data for the .h header file,
928 'sourcename': Name of the source code file,
929 'sourcedata': Data for the .c source code file
932 toplevel_options = nanopb_pb2.NanoPBOptions()
933 for s in options.settings:
934 text_format.Merge(s, toplevel_options)
937 data = open(filename, 'rb').read()
938 fdesc = descriptor.FileDescriptorSet.FromString(data).file[0]
940 # Check if there is a separate .options file
942 optfilename = options.options_file % os.path.splitext(filename)[0]
944 # No %s specified, use the filename as-is
945 optfilename = options.options_file
948 print 'Reading options from ' + optfilename
950 if os.path.isfile(optfilename):
951 Globals.separate_options = read_options_file(open(optfilename, "rU"))
953 Globals.separate_options = []
956 file_options = get_nanopb_suboptions(fdesc, toplevel_options, Names([filename]))
957 enums, messages, extensions = parse_file(fdesc, file_options)
959 # Decide the file names
960 noext = os.path.splitext(filename)[0]
961 headername = noext + '.' + options.extension + '.h'
962 sourcename = noext + '.' + options.extension + '.c'
963 headerbasename = os.path.basename(headername)
965 # List of .proto files that should not be included in the C header file
966 # even if they are mentioned in the source .proto.
967 excludes = ['nanopb.proto', 'google/protobuf/descriptor.proto'] + options.exclude
968 dependencies = [d for d in fdesc.dependency if d not in excludes]
970 headerdata = ''.join(generate_header(dependencies, headerbasename, enums,
971 messages, extensions, options))
973 sourcedata = ''.join(generate_source(headerbasename, enums,
974 messages, extensions, options))
976 return {'headername': headername, 'headerdata': headerdata,
977 'sourcename': sourcename, 'sourcedata': sourcedata}
980 '''Main function when invoked directly from the command line.'''
982 options, filenames = optparser.parse_args()
985 optparser.print_help()
989 options.verbose = False
991 Globals.verbose_options = options.verbose
993 for filename in filenames:
994 results = process_file(filename, None, options)
996 if not options.quiet:
997 print "Writing to " + results['headername'] + " and " + results['sourcename']
999 open(results['headername'], 'w').write(results['headerdata'])
1000 open(results['sourcename'], 'w').write(results['sourcedata'])
1003 '''Main function when invoked as a protoc plugin.'''
1006 data = sys.stdin.read()
1007 request = plugin_pb2.CodeGeneratorRequest.FromString(data)
1010 args = shlex.split(request.parameter)
1011 options, dummy = optparser.parse_args(args)
1013 # We can't go printing stuff to stdout
1014 Globals.verbose_options = False
1015 options.verbose = False
1016 options.quiet = True
1018 response = plugin_pb2.CodeGeneratorResponse()
1020 for filename in request.file_to_generate:
1021 for fdesc in request.proto_file:
1022 if fdesc.name == filename:
1023 results = process_file(filename, fdesc, options)
1025 f = response.file.add()
1026 f.name = results['headername']
1027 f.content = results['headerdata']
1029 f = response.file.add()
1030 f.name = results['sourcename']
1031 f.content = results['sourcedata']
1033 sys.stdout.write(response.SerializeToString())
1035 if __name__ == '__main__':
1036 # Check if we are running as a plugin under protoc
1037 if 'protoc-gen-' in sys.argv[0]: