3 '''Generate header file for nanopb from a ProtoBuf FileDescriptorSet.'''
4 nanopb_version = "nanopb-0.3.4-dev"
10 # Add some dummy imports to keep packaging tools happy.
11 import google, distutils.util # bbfreeze seems to need these
12 import pkg_resources # pyinstaller / protobuf 2.5 seem to need these
14 # Don't care, we will error out later if it is actually important.
18 import google.protobuf.text_format as text_format
19 import google.protobuf.descriptor_pb2 as descriptor
22 *************************************************************
23 *** Could not import the Google protobuf Python libraries ***
24 *** Try installing package 'python-protobuf' or similar. ***
25 *************************************************************
30 import proto.nanopb_pb2 as nanopb_pb2
31 import proto.plugin_pb2 as plugin_pb2
34 ********************************************************************
35 *** Failed to import the protocol definitions for generator. ***
36 *** You have to run 'make' in the nanopb/generator/proto folder. ***
37 ********************************************************************
41 # ---------------------------------------------------------------------------
42 # Generation of single fields
43 # ---------------------------------------------------------------------------
48 # Values are tuple (c type, pb type, encoded size, int_size_allowed)
49 FieldD = descriptor.FieldDescriptorProto
51 FieldD.TYPE_BOOL: ('bool', 'BOOL', 1, False),
52 FieldD.TYPE_DOUBLE: ('double', 'DOUBLE', 8, False),
53 FieldD.TYPE_FIXED32: ('uint32_t', 'FIXED32', 4, False),
54 FieldD.TYPE_FIXED64: ('uint64_t', 'FIXED64', 8, False),
55 FieldD.TYPE_FLOAT: ('float', 'FLOAT', 4, False),
56 FieldD.TYPE_INT32: ('int32_t', 'INT32', 10, True),
57 FieldD.TYPE_INT64: ('int64_t', 'INT64', 10, True),
58 FieldD.TYPE_SFIXED32: ('int32_t', 'SFIXED32', 4, False),
59 FieldD.TYPE_SFIXED64: ('int64_t', 'SFIXED64', 8, False),
60 FieldD.TYPE_SINT32: ('int32_t', 'SINT32', 5, True),
61 FieldD.TYPE_SINT64: ('int64_t', 'SINT64', 10, True),
62 FieldD.TYPE_UINT32: ('uint32_t', 'UINT32', 5, True),
63 FieldD.TYPE_UINT64: ('uint64_t', 'UINT64', 10, True)
66 # Integer size overrides (from .proto settings)
68 nanopb_pb2.IS_8: 'int8_t',
69 nanopb_pb2.IS_16: 'int16_t',
70 nanopb_pb2.IS_32: 'int32_t',
71 nanopb_pb2.IS_64: 'int64_t',
75 '''Keeps a set of nested names and formats them to C identifier.'''
76 def __init__(self, parts = ()):
77 if isinstance(parts, Names):
79 self.parts = tuple(parts)
82 return '_'.join(self.parts)
84 def __add__(self, other):
85 if isinstance(other, (str, unicode)):
86 return Names(self.parts + (other,))
87 elif isinstance(other, tuple):
88 return Names(self.parts + other)
90 raise ValueError("Name parts should be of type str")
92 def __eq__(self, other):
93 return isinstance(other, Names) and self.parts == other.parts
95 def names_from_type_name(type_name):
96 '''Parse Names() from FieldDescriptorProto type_name'''
97 if type_name[0] != '.':
98 raise NotImplementedError("Lookup of non-absolute type names is not supported")
99 return Names(type_name[1:].split('.'))
101 def varint_max_size(max_value):
102 '''Returns the maximum number of bytes a varint can take when encoded.'''
103 for i in range(1, 11):
104 if (max_value >> (i * 7)) == 0:
106 raise ValueError("Value too large for varint: " + str(max_value))
108 assert varint_max_size(0) == 1
109 assert varint_max_size(127) == 1
110 assert varint_max_size(128) == 2
113 '''Class used to represent the encoded size of a field or a message.
114 Consists of a combination of symbolic sizes and integer sizes.'''
115 def __init__(self, value = 0, symbols = []):
116 if isinstance(value, (str, Names)):
117 symbols = [str(value)]
120 self.symbols = symbols
122 def __add__(self, other):
123 if isinstance(other, (int, long)):
124 return EncodedSize(self.value + other, self.symbols)
125 elif isinstance(other, (str, Names)):
126 return EncodedSize(self.value, self.symbols + [str(other)])
127 elif isinstance(other, EncodedSize):
128 return EncodedSize(self.value + other.value, self.symbols + other.symbols)
130 raise ValueError("Cannot add size: " + repr(other))
132 def __mul__(self, other):
133 if isinstance(other, (int, long)):
134 return EncodedSize(self.value * other, [str(other) + '*' + s for s in self.symbols])
136 raise ValueError("Cannot multiply size: " + repr(other))
140 return str(self.value)
142 return '(' + str(self.value) + ' + ' + ' + '.join(self.symbols) + ')'
144 def upperlimit(self):
151 def __init__(self, names, desc, enum_options):
152 '''desc is EnumDescriptorProto'''
154 self.options = enum_options
155 self.names = names + desc.name
157 if enum_options.long_names:
158 self.values = [(self.names + x.name, x.number) for x in desc.value]
160 self.values = [(names + x.name, x.number) for x in desc.value]
162 self.value_longnames = [self.names + x.name for x in desc.value]
163 self.packed = enum_options.packed_enum
165 def has_negative(self):
166 for n, v in self.values:
172 result = 'typedef enum _%s {\n' % self.names
173 result += ',\n'.join([" %s = %d" % x for x in self.values])
177 result += ' pb_packed'
179 result += ' %s;' % self.names
181 if not self.options.long_names:
182 # Define the long names always so that enum value references
183 # from other files work properly.
184 for i, x in enumerate(self.values):
185 result += '\n#define %s %s' % (self.value_longnames[i], x[0])
190 def __init__(self, struct_name, desc, field_options):
191 '''desc is FieldDescriptorProto'''
192 self.tag = desc.number
193 self.struct_name = struct_name
194 self.union_name = None
195 self.name = desc.name
198 self.max_count = None
203 # Parse field options
204 if field_options.HasField("max_size"):
205 self.max_size = field_options.max_size
207 if field_options.HasField("max_count"):
208 self.max_count = field_options.max_count
210 if desc.HasField('default_value'):
211 self.default = desc.default_value
213 # Check field rules, i.e. required/optional/repeated.
215 if desc.label == FieldD.LABEL_REQUIRED:
216 self.rules = 'REQUIRED'
217 elif desc.label == FieldD.LABEL_OPTIONAL:
218 self.rules = 'OPTIONAL'
219 elif desc.label == FieldD.LABEL_REPEATED:
220 self.rules = 'REPEATED'
221 if self.max_count is None:
222 can_be_static = False
224 self.array_decl = '[%d]' % self.max_count
226 raise NotImplementedError(desc.label)
228 # Check if the field can be implemented with static allocation
229 # i.e. whether the data size is known.
230 if desc.type == FieldD.TYPE_STRING and self.max_size is None:
231 can_be_static = False
233 if desc.type == FieldD.TYPE_BYTES and self.max_size is None:
234 can_be_static = False
236 # Decide how the field data will be allocated
237 if field_options.type == nanopb_pb2.FT_DEFAULT:
239 field_options.type = nanopb_pb2.FT_STATIC
241 field_options.type = nanopb_pb2.FT_CALLBACK
243 if field_options.type == nanopb_pb2.FT_STATIC and not can_be_static:
244 raise Exception("Field %s is defined as static, but max_size or "
245 "max_count is not given." % self.name)
247 if field_options.type == nanopb_pb2.FT_STATIC:
248 self.allocation = 'STATIC'
249 elif field_options.type == nanopb_pb2.FT_POINTER:
250 self.allocation = 'POINTER'
251 elif field_options.type == nanopb_pb2.FT_CALLBACK:
252 self.allocation = 'CALLBACK'
254 raise NotImplementedError(field_options.type)
256 # Decide the C data type to use in the struct.
257 if datatypes.has_key(desc.type):
258 self.ctype, self.pbtype, self.enc_size, isa = datatypes[desc.type]
260 # Override the field size if user wants to use smaller integers
261 if isa and field_options.int_size != nanopb_pb2.IS_DEFAULT:
262 self.ctype = intsizes[field_options.int_size]
263 if desc.type == FieldD.TYPE_UINT32 or desc.type == FieldD.TYPE_UINT64:
264 self.ctype = 'u' + self.ctype;
265 elif desc.type == FieldD.TYPE_ENUM:
267 self.ctype = names_from_type_name(desc.type_name)
268 if self.default is not None:
269 self.default = self.ctype + self.default
270 self.enc_size = 5 # protoc rejects enum values > 32 bits
271 elif desc.type == FieldD.TYPE_STRING:
272 self.pbtype = 'STRING'
274 if self.allocation == 'STATIC':
276 self.array_decl += '[%d]' % self.max_size
277 self.enc_size = varint_max_size(self.max_size) + self.max_size
278 elif desc.type == FieldD.TYPE_BYTES:
279 self.pbtype = 'BYTES'
280 if self.allocation == 'STATIC':
281 self.ctype = self.struct_name + self.name + 't'
282 self.enc_size = varint_max_size(self.max_size) + self.max_size
283 elif self.allocation == 'POINTER':
284 self.ctype = 'pb_bytes_array_t'
285 elif desc.type == FieldD.TYPE_MESSAGE:
286 self.pbtype = 'MESSAGE'
287 self.ctype = self.submsgname = names_from_type_name(desc.type_name)
288 self.enc_size = None # Needs to be filled in after the message type is available
290 raise NotImplementedError(desc.type)
292 def __cmp__(self, other):
293 return cmp(self.tag, other.tag)
297 if self.allocation == 'POINTER':
298 if self.rules == 'REPEATED':
299 result += ' pb_size_t ' + self.name + '_count;\n'
301 if self.pbtype == 'MESSAGE':
302 # Use struct definition, so recursive submessages are possible
303 result += ' struct _%s *%s;' % (self.ctype, self.name)
304 elif self.rules == 'REPEATED' and self.pbtype in ['STRING', 'BYTES']:
305 # String/bytes arrays need to be defined as pointers to pointers
306 result += ' %s **%s;' % (self.ctype, self.name)
308 result += ' %s *%s;' % (self.ctype, self.name)
309 elif self.allocation == 'CALLBACK':
310 result += ' pb_callback_t %s;' % self.name
312 if self.rules == 'OPTIONAL' and self.allocation == 'STATIC':
313 result += ' bool has_' + self.name + ';\n'
314 elif self.rules == 'REPEATED' and self.allocation == 'STATIC':
315 result += ' pb_size_t ' + self.name + '_count;\n'
316 result += ' %s %s%s;' % (self.ctype, self.name, self.array_decl)
320 '''Return definitions for any special types this field might need.'''
321 if self.pbtype == 'BYTES' and self.allocation == 'STATIC':
322 result = 'typedef PB_BYTES_ARRAY_T(%d) %s;\n' % (self.max_size, self.ctype)
327 def get_dependencies(self):
328 '''Get list of type names used by this field.'''
329 if self.allocation == 'STATIC':
330 return [str(self.ctype)]
334 def get_initializer(self, null_init, inner_init_only = False):
335 '''Return literal expression for this field's default value.
336 null_init: If True, initialize to a 0 value instead of default from .proto
337 inner_init_only: If True, exclude initialization for any count/has fields
341 if self.pbtype == 'MESSAGE':
343 inner_init = '%s_init_zero' % self.ctype
345 inner_init = '%s_init_default' % self.ctype
346 elif self.default is None or null_init:
347 if self.pbtype == 'STRING':
349 elif self.pbtype == 'BYTES':
350 inner_init = '{0, {0}}'
351 elif self.pbtype in ('ENUM', 'UENUM'):
352 inner_init = '(%s)0' % self.ctype
356 if self.pbtype == 'STRING':
357 inner_init = self.default.encode('utf-8').encode('string_escape')
358 inner_init = inner_init.replace('"', '\\"')
359 inner_init = '"' + inner_init + '"'
360 elif self.pbtype == 'BYTES':
361 data = str(self.default).decode('string_escape')
362 data = ['0x%02x' % ord(c) for c in data]
364 inner_init = '{0, {0}}'
366 inner_init = '{%d, {%s}}' % (len(data), ','.join(data))
367 elif self.pbtype in ['FIXED32', 'UINT32']:
368 inner_init = str(self.default) + 'u'
369 elif self.pbtype in ['FIXED64', 'UINT64']:
370 inner_init = str(self.default) + 'ull'
371 elif self.pbtype in ['SFIXED64', 'INT64']:
372 inner_init = str(self.default) + 'll'
374 inner_init = str(self.default)
380 if self.allocation == 'STATIC':
381 if self.rules == 'REPEATED':
383 outer_init += ', '.join([inner_init] * self.max_count)
385 elif self.rules == 'OPTIONAL':
386 outer_init = 'false, ' + inner_init
388 outer_init = inner_init
389 elif self.allocation == 'POINTER':
390 if self.rules == 'REPEATED':
391 outer_init = '0, NULL'
394 elif self.allocation == 'CALLBACK':
395 if self.pbtype == 'EXTENSION':
398 outer_init = '{{NULL}, NULL}'
402 def default_decl(self, declaration_only = False):
403 '''Return definition for this field's default value.'''
404 if self.default is None:
408 default = self.get_initializer(False, True)
411 if self.pbtype == 'STRING':
412 if self.allocation != 'STATIC':
413 return None # Not implemented
414 array_decl = '[%d]' % self.max_size
415 elif self.pbtype == 'BYTES':
416 if self.allocation != 'STATIC':
417 return None # Not implemented
420 return 'extern const %s %s_default%s;' % (ctype, self.struct_name + self.name, array_decl)
422 return 'const %s %s_default%s = %s;' % (ctype, self.struct_name + self.name, array_decl, default)
425 '''Return the #define for the tag number of this field.'''
426 identifier = '%s_%s_tag' % (self.struct_name, self.name)
427 return '#define %-40s %d\n' % (identifier, self.tag)
429 def pb_field_t(self, prev_field_name):
430 '''Return the pb_field_t initializer to use in the constant array.
431 prev_field_name is the name of the previous field or None.
434 if self.rules == 'ONEOF':
435 result = ' PB_ONEOF_FIELD(%s, ' % self.union_name
437 result = ' PB_FIELD('
439 result += '%3d, ' % self.tag
440 result += '%-8s, ' % self.pbtype
441 result += '%s, ' % self.rules
442 result += '%-8s, ' % self.allocation
443 result += '%s, ' % ("FIRST" if not prev_field_name else "OTHER")
444 result += '%s, ' % self.struct_name
445 result += '%s, ' % self.name
446 result += '%s, ' % (prev_field_name or self.name)
448 if self.pbtype == 'MESSAGE':
449 result += '&%s_fields)' % self.submsgname
450 elif self.default is None:
452 elif self.pbtype in ['BYTES', 'STRING'] and self.allocation != 'STATIC':
453 result += '0)' # Arbitrary size default values not implemented
454 elif self.rules == 'OPTEXT':
455 result += '0)' # Default value for extensions is not implemented
457 result += '&%s_default)' % (self.struct_name + self.name)
461 def largest_field_value(self):
462 '''Determine if this field needs 16bit or 32bit pb_field_t structure to compile properly.
463 Returns numeric value or a C-expression for assert.'''
464 if self.pbtype == 'MESSAGE':
465 if self.rules == 'REPEATED' and self.allocation == 'STATIC':
466 return 'pb_membersize(%s, %s[0])' % (self.struct_name, self.name)
467 elif self.rules == 'ONEOF':
468 return 'pb_membersize(%s, %s.%s)' % (self.struct_name, self.union_name, self.name)
470 return 'pb_membersize(%s, %s)' % (self.struct_name, self.name)
472 return max(self.tag, self.max_size, self.max_count)
474 def encoded_size(self, dependencies):
475 '''Return the maximum size that this field can take when encoded,
476 including the field tag. If the size cannot be determined, returns
479 if self.allocation != 'STATIC':
482 if self.pbtype == 'MESSAGE':
483 if str(self.submsgname) in dependencies:
484 submsg = dependencies[str(self.submsgname)]
485 encsize = submsg.encoded_size(dependencies)
487 return None # Submessage size is indeterminate
489 # Include submessage length prefix
490 encsize += varint_max_size(encsize.upperlimit())
492 # Submessage cannot be found, this currently occurs when
493 # the submessage type is defined in a different file.
494 # Instead of direct numeric value, reference the size that
495 # has been #defined in the other file.
496 encsize = EncodedSize(self.submsgname + 'size')
498 # We will have to make a conservative assumption on the length
499 # prefix size, though.
502 elif self.enc_size is None:
503 raise RuntimeError("Could not determine encoded size for %s.%s"
504 % (self.struct_name, self.name))
506 encsize = EncodedSize(self.enc_size)
508 encsize += varint_max_size(self.tag << 3) # Tag + wire type
510 if self.rules == 'REPEATED':
511 # Decoders must be always able to handle unpacked arrays.
512 # Therefore we have to reserve space for it, even though
513 # we emit packed arrays ourselves.
514 encsize *= self.max_count
519 class ExtensionRange(Field):
520 def __init__(self, struct_name, range_start, field_options):
521 '''Implements a special pb_extension_t* field in an extensible message
522 structure. The range_start signifies the index at which the extensions
523 start. Not necessarily all tags above this are extensions, it is merely
524 a speed optimization.
526 self.tag = range_start
527 self.struct_name = struct_name
528 self.name = 'extensions'
529 self.pbtype = 'EXTENSION'
530 self.rules = 'OPTIONAL'
531 self.allocation = 'CALLBACK'
532 self.ctype = 'pb_extension_t'
539 return ' pb_extension_t *extensions;'
547 def encoded_size(self, allmsgs):
548 # We exclude extensions from the count, because they cannot be known
549 # until runtime. Other option would be to return None here, but this
550 # way the value remains useful if extensions are not used.
551 return EncodedSize(0)
553 class ExtensionField(Field):
554 def __init__(self, struct_name, desc, field_options):
555 self.fullname = struct_name + desc.name
556 self.extendee_name = names_from_type_name(desc.extendee)
557 Field.__init__(self, self.fullname + 'struct', desc, field_options)
559 if self.rules != 'OPTIONAL':
563 self.rules = 'OPTEXT'
566 '''Return the #define for the tag number of this field.'''
567 identifier = '%s_tag' % self.fullname
568 return '#define %-40s %d\n' % (identifier, self.tag)
570 def extension_decl(self):
571 '''Declaration of the extension type in the .pb.h file'''
573 msg = '/* Extension field %s was skipped because only "optional"\n' % self.fullname
574 msg +=' type of extension fields is currently supported. */\n'
577 return ('extern const pb_extension_type_t %s; /* field type: %s */\n' %
578 (self.fullname, str(self).strip()))
580 def extension_def(self):
581 '''Definition of the extension type in the .pb.c file'''
586 result = 'typedef struct {\n'
588 result += '\n} %s;\n\n' % self.struct_name
589 result += ('static const pb_field_t %s_field = \n %s;\n\n' %
590 (self.fullname, self.pb_field_t(None)))
591 result += 'const pb_extension_type_t %s = {\n' % self.fullname
594 result += ' &%s_field\n' % self.fullname
599 # ---------------------------------------------------------------------------
600 # Generation of oneofs (unions)
601 # ---------------------------------------------------------------------------
604 def __init__(self, struct_name, oneof_desc):
605 self.struct_name = struct_name
606 self.name = oneof_desc.name
608 self.pbtype = 'oneof'
610 self.allocation = 'ONEOF'
614 def add_field(self, field):
615 if field.allocation == 'CALLBACK':
616 raise Exception("Callback fields inside of oneof are not supported"
617 + " (field %s)" % field.name)
619 field.union_name = self.name
620 field.rules = 'ONEOF'
621 self.fields.append(field)
622 self.fields.sort(key = lambda f: f.tag)
624 # Sort by the lowest tag number inside union
625 self.tag = min([f.tag for f in self.fields])
627 def __cmp__(self, other):
628 return cmp(self.tag, other.tag)
633 result += ' pb_size_t which_' + self.name + ";\n"
634 result += ' union {\n'
635 for f in self.fields:
636 result += ' ' + str(f).replace('\n', '\n ') + '\n'
637 result += ' } ' + self.name + ';'
641 return ''.join([f.types() for f in self.fields])
643 def get_dependencies(self):
645 for f in self.fields:
646 deps += f.get_dependencies()
649 def get_initializer(self, null_init):
650 return '0, {' + self.fields[0].get_initializer(null_init) + '}'
652 def default_decl(self, declaration_only = False):
656 return '\n'.join([f.tags() for f in self.fields])
658 def pb_field_t(self, prev_field_name):
659 result = ',\n'.join([f.pb_field_t(prev_field_name) for f in self.fields])
662 def largest_field_value(self):
663 return max([f.largest_field_value() for f in self.fields])
665 def encoded_size(self, allmsgs):
666 largest = EncodedSize(0)
667 for f in self.fields:
668 size = f.encoded_size(allmsgs)
672 return None # Cannot resolve maximum of symbols
673 elif size.value > largest.value:
678 # ---------------------------------------------------------------------------
679 # Generation of messages (structures)
680 # ---------------------------------------------------------------------------
684 def __init__(self, names, desc, message_options):
690 if message_options.msgid:
691 self.msgid = message_options.msgid
693 if hasattr(desc, 'oneof_decl'):
694 for i, f in enumerate(desc.oneof_decl):
695 oneof_options = get_nanopb_suboptions(desc, message_options, self.name + f.name)
696 if oneof_options.no_unions:
697 no_unions.append(i) # No union, but add fields normally
698 elif oneof_options.type == nanopb_pb2.FT_IGNORE:
699 pass # No union and skip fields also
701 oneof = OneOf(self.name, f)
702 self.oneofs[i] = oneof
703 self.fields.append(oneof)
706 field_options = get_nanopb_suboptions(f, message_options, self.name + f.name)
707 if field_options.type == nanopb_pb2.FT_IGNORE:
710 field = Field(self.name, f, field_options)
711 if (hasattr(f, 'oneof_index') and
712 f.HasField('oneof_index') and
713 f.oneof_index not in no_unions):
714 if f.oneof_index in self.oneofs:
715 self.oneofs[f.oneof_index].add_field(field)
717 self.fields.append(field)
719 if len(desc.extension_range) > 0:
720 field_options = get_nanopb_suboptions(desc, message_options, self.name + 'extensions')
721 range_start = min([r.start for r in desc.extension_range])
722 if field_options.type != nanopb_pb2.FT_IGNORE:
723 self.fields.append(ExtensionRange(self.name, range_start, field_options))
725 self.packed = message_options.packed_struct
726 self.ordered_fields = self.fields[:]
727 self.ordered_fields.sort()
729 def get_dependencies(self):
730 '''Get list of type names that this structure refers to.'''
732 for f in self.fields:
733 deps += f.get_dependencies()
737 result = 'typedef struct _%s {\n' % self.name
739 if not self.ordered_fields:
740 # Empty structs are not allowed in C standard.
741 # Therefore add a dummy field if an empty message occurs.
742 result += ' uint8_t dummy_field;'
744 result += '\n'.join([str(f) for f in self.ordered_fields])
748 result += ' pb_packed'
750 result += ' %s;' % self.name
753 result = 'PB_PACKED_STRUCT_START\n' + result
754 result += '\nPB_PACKED_STRUCT_END'
759 return ''.join([f.types() for f in self.fields])
761 def get_initializer(self, null_init):
762 if not self.ordered_fields:
766 for field in self.ordered_fields:
767 parts.append(field.get_initializer(null_init))
768 return '{' + ', '.join(parts) + '}'
770 def default_decl(self, declaration_only = False):
772 for field in self.fields:
773 default = field.default_decl(declaration_only)
774 if default is not None:
775 result += default + '\n'
778 def count_required_fields(self):
779 '''Returns number of required fields inside this message'''
781 for f in self.fields:
782 if not isinstance(f, OneOf):
783 if f.rules == 'REQUIRED':
787 def count_all_fields(self):
789 for f in self.fields:
790 if isinstance(f, OneOf):
791 count += len(f.fields)
796 def fields_declaration(self):
797 result = 'extern const pb_field_t %s_fields[%d];' % (self.name, self.count_all_fields() + 1)
800 def fields_definition(self):
801 result = 'const pb_field_t %s_fields[%d] = {\n' % (self.name, self.count_all_fields() + 1)
804 for field in self.ordered_fields:
805 result += field.pb_field_t(prev)
807 if isinstance(field, OneOf):
808 prev = field.name + '.' + field.fields[-1].name
812 result += ' PB_LAST_FIELD\n};'
815 def encoded_size(self, allmsgs):
816 '''Return the maximum size that this message can take when encoded.
817 If the size cannot be determined, returns None.
819 size = EncodedSize(0)
820 for field in self.fields:
821 fsize = field.encoded_size(allmsgs)
829 # ---------------------------------------------------------------------------
830 # Processing of entire .proto files
831 # ---------------------------------------------------------------------------
833 def iterate_messages(desc, names = Names()):
834 '''Recursively find all messages. For each, yield name, DescriptorProto.'''
835 if hasattr(desc, 'message_type'):
836 submsgs = desc.message_type
838 submsgs = desc.nested_type
840 for submsg in submsgs:
841 sub_names = names + submsg.name
842 yield sub_names, submsg
844 for x in iterate_messages(submsg, sub_names):
847 def iterate_extensions(desc, names = Names()):
848 '''Recursively find all extensions.
849 For each, yield name, FieldDescriptorProto.
851 for extension in desc.extension:
852 yield names, extension
854 for subname, subdesc in iterate_messages(desc, names):
855 for extension in subdesc.extension:
856 yield subname, extension
860 From http://code.activestate.com/recipes/577413-topological-sort/
861 This function is under the MIT license.
863 for k, v in data.items():
864 v.discard(k) # Ignore self dependencies
865 extra_items_in_deps = reduce(set.union, data.values(), set()) - set(data.keys())
866 data.update(dict([(item, set()) for item in extra_items_in_deps]))
868 ordered = set(item for item,dep in data.items() if not dep)
871 for item in sorted(ordered):
873 data = dict([(item, (dep - ordered)) for item,dep in data.items()
874 if item not in ordered])
875 assert not data, "A cyclic dependency exists amongst %r" % data
877 def sort_dependencies(messages):
878 '''Sort a list of Messages based on dependencies.'''
881 for message in messages:
882 dependencies[str(message.name)] = set(message.get_dependencies())
883 message_by_name[str(message.name)] = message
885 for msgname in toposort2(dependencies):
886 if msgname in message_by_name:
887 yield message_by_name[msgname]
889 def make_identifier(headername):
890 '''Make #ifndef identifier that contains uppercase A-Z and digits 0-9'''
892 for c in headername.upper():
900 def __init__(self, fdesc, file_options):
901 '''Takes a FileDescriptorProto and parses it.'''
903 self.file_options = file_options
904 self.dependencies = {}
907 # Some of types used in this file probably come from the file itself.
908 # Thus it has implicit dependency on itself.
909 self.add_dependency(self)
916 if self.fdesc.package:
917 base_name = Names(self.fdesc.package.split('.'))
921 for enum in self.fdesc.enum_type:
922 enum_options = get_nanopb_suboptions(enum, self.file_options, base_name + enum.name)
923 self.enums.append(Enum(base_name, enum, enum_options))
925 for names, message in iterate_messages(self.fdesc, base_name):
926 message_options = get_nanopb_suboptions(message, self.file_options, names)
928 if message_options.skip_message:
931 self.messages.append(Message(names, message, message_options))
932 for enum in message.enum_type:
933 enum_options = get_nanopb_suboptions(enum, message_options, names + enum.name)
934 self.enums.append(Enum(names, enum, enum_options))
936 for names, extension in iterate_extensions(self.fdesc, base_name):
937 field_options = get_nanopb_suboptions(extension, self.file_options, names + extension.name)
938 if field_options.type != nanopb_pb2.FT_IGNORE:
939 self.extensions.append(ExtensionField(names, extension, field_options))
941 def add_dependency(self, other):
942 for enum in other.enums:
943 self.dependencies[str(enum.names)] = enum
945 for msg in other.messages:
946 self.dependencies[str(msg.name)] = msg
948 # Fix field default values where enum short names are used.
949 for enum in other.enums:
950 if not enum.options.long_names:
951 for message in self.messages:
952 for field in message.fields:
953 if field.default in enum.value_longnames:
954 idx = enum.value_longnames.index(field.default)
955 field.default = enum.values[idx][0]
957 # Fix field data types where enums have negative values.
958 for enum in other.enums:
959 if not enum.has_negative():
960 for message in self.messages:
961 for field in message.fields:
962 if field.pbtype == 'ENUM' and field.ctype == enum.names:
963 field.pbtype = 'UENUM'
965 def generate_header(self, includes, headername, options):
966 '''Generate content for a header file.
967 Generates strings, which should be concatenated and stored to file.
970 yield '/* Automatically generated nanopb header */\n'
971 if options.notimestamp:
972 yield '/* Generated by %s */\n\n' % (nanopb_version)
974 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
976 symbol = make_identifier(headername)
977 yield '#ifndef PB_%s_INCLUDED\n' % symbol
978 yield '#define PB_%s_INCLUDED\n' % symbol
980 yield options.libformat % ('pb.h')
982 # no %s specified - use whatever was passed in as options.libformat
983 yield options.libformat
986 for incfile in includes:
987 noext = os.path.splitext(incfile)[0]
988 yield options.genformat % (noext + options.extension + '.h')
991 yield '#if PB_PROTO_HEADER_VERSION != 30\n'
992 yield '#error Regenerate this file with the current version of nanopb generator.\n'
996 yield '#ifdef __cplusplus\n'
997 yield 'extern "C" {\n'
1001 yield '/* Enum definitions */\n'
1002 for enum in self.enums:
1003 yield str(enum) + '\n\n'
1006 yield '/* Struct definitions */\n'
1007 for msg in sort_dependencies(self.messages):
1009 yield str(msg) + '\n\n'
1012 yield '/* Extensions */\n'
1013 for extension in self.extensions:
1014 yield extension.extension_decl()
1018 yield '/* Default values for struct fields */\n'
1019 for msg in self.messages:
1020 yield msg.default_decl(True)
1023 yield '/* Initializer values for message structs */\n'
1024 for msg in self.messages:
1025 identifier = '%s_init_default' % msg.name
1026 yield '#define %-40s %s\n' % (identifier, msg.get_initializer(False))
1027 for msg in self.messages:
1028 identifier = '%s_init_zero' % msg.name
1029 yield '#define %-40s %s\n' % (identifier, msg.get_initializer(True))
1032 yield '/* Field tags (for use in manual encoding/decoding) */\n'
1033 for msg in sort_dependencies(self.messages):
1034 for field in msg.fields:
1036 for extension in self.extensions:
1037 yield extension.tags()
1040 yield '/* Struct field encoding specification for nanopb */\n'
1041 for msg in self.messages:
1042 yield msg.fields_declaration() + '\n'
1045 yield '/* Maximum encoded size of messages (where known) */\n'
1046 for msg in self.messages:
1047 msize = msg.encoded_size(self.dependencies)
1048 if msize is not None:
1049 identifier = '%s_size' % msg.name
1050 yield '#define %-40s %s\n' % (identifier, msize)
1053 yield '/* Message IDs (where set with "msgid" option) */\n'
1055 yield '#ifdef PB_MSGID\n'
1056 for msg in self.messages:
1057 if hasattr(msg,'msgid'):
1058 yield '#define PB_MSG_%d %s\n' % (msg.msgid, msg.name)
1061 symbol = make_identifier(headername.split('.')[0])
1062 yield '#define %s_MESSAGES \\\n' % symbol
1064 for msg in self.messages:
1066 msize = msg.encoded_size(self.dependencies)
1067 if msize is not None:
1069 if hasattr(msg,'msgid'):
1070 yield '\tPB_MSG(%d,%s,%s) \\\n' % (msg.msgid, m, msg.name)
1073 for msg in self.messages:
1074 if hasattr(msg,'msgid'):
1075 yield '#define %s_msgid %d\n' % (msg.name, msg.msgid)
1080 yield '#ifdef __cplusplus\n'
1081 yield '} /* extern "C" */\n'
1087 def generate_source(self, headername, options):
1088 '''Generate content for a source file.'''
1090 yield '/* Automatically generated nanopb constant definitions */\n'
1091 if options.notimestamp:
1092 yield '/* Generated by %s */\n\n' % (nanopb_version)
1094 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
1095 yield options.genformat % (headername)
1098 yield '#if PB_PROTO_HEADER_VERSION != 30\n'
1099 yield '#error Regenerate this file with the current version of nanopb generator.\n'
1103 for msg in self.messages:
1104 yield msg.default_decl(False)
1108 for msg in self.messages:
1109 yield msg.fields_definition() + '\n\n'
1111 for ext in self.extensions:
1112 yield ext.extension_def() + '\n'
1114 # Add checks for numeric limits
1116 largest_msg = max(self.messages, key = lambda m: m.count_required_fields())
1117 largest_count = largest_msg.count_required_fields()
1118 if largest_count > 64:
1119 yield '\n/* Check that missing required fields will be properly detected */\n'
1120 yield '#if PB_MAX_REQUIRED_FIELDS < %d\n' % largest_count
1121 yield '#error Properly detecting missing required fields in %s requires \\\n' % largest_msg.name
1122 yield ' setting PB_MAX_REQUIRED_FIELDS to %d or more.\n' % largest_count
1128 checks_msgnames = []
1129 for msg in self.messages:
1130 checks_msgnames.append(msg.name)
1131 for field in msg.fields:
1132 status = field.largest_field_value()
1133 if isinstance(status, (str, unicode)):
1134 checks.append(status)
1135 elif status > worst:
1137 worst_field = str(field.struct_name) + '.' + str(field.name)
1139 if worst > 255 or checks:
1140 yield '\n/* Check that field information fits in pb_field_t */\n'
1142 if worst > 65535 or checks:
1143 yield '#if !defined(PB_FIELD_32BIT)\n'
1145 yield '#error Field descriptor for %s is too large. Define PB_FIELD_32BIT to fix this.\n' % worst_field
1147 assertion = ' && '.join(str(c) + ' < 65536' for c in checks)
1148 msgs = '_'.join(str(n) for n in checks_msgnames)
1149 yield '/* If you get an error here, it means that you need to define PB_FIELD_32BIT\n'
1150 yield ' * compile-time option. You can do that in pb.h or on compiler command line.\n'
1152 yield ' * The reason you need to do this is that some of your messages contain tag\n'
1153 yield ' * numbers or field sizes that are larger than what can fit in 8 or 16 bit\n'
1154 yield ' * field descriptors.\n'
1156 yield 'PB_STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
1160 yield '#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT)\n'
1162 yield '#error Field descriptor for %s is too large. Define PB_FIELD_16BIT to fix this.\n' % worst_field
1164 assertion = ' && '.join(str(c) + ' < 256' for c in checks)
1165 msgs = '_'.join(str(n) for n in checks_msgnames)
1166 yield '/* If you get an error here, it means that you need to define PB_FIELD_16BIT\n'
1167 yield ' * compile-time option. You can do that in pb.h or on compiler command line.\n'
1169 yield ' * The reason you need to do this is that some of your messages contain tag\n'
1170 yield ' * numbers or field sizes that are larger than what can fit in the default\n'
1171 yield ' * 8 bit descriptors.\n'
1173 yield 'PB_STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
1176 # Add check for sizeof(double)
1178 for msg in self.messages:
1179 for field in msg.fields:
1180 if field.ctype == 'double':
1185 yield '/* On some platforms (such as AVR), double is really float.\n'
1186 yield ' * These are not directly supported by nanopb, but see example_avr_double.\n'
1187 yield ' * To get rid of this error, remove any double fields from your .proto.\n'
1189 yield 'PB_STATIC_ASSERT(sizeof(double) == 8, DOUBLE_MUST_BE_8_BYTES)\n'
1193 # ---------------------------------------------------------------------------
1194 # Options parsing for the .proto files
1195 # ---------------------------------------------------------------------------
1197 from fnmatch import fnmatch
1199 def read_options_file(infile):
1200 '''Parse a separate options file to list:
1201 [(namemask, options), ...]
1204 data = infile.read()
1205 data = re.sub('/\*.*?\*/', '', data, flags = re.MULTILINE)
1206 data = re.sub('//.*?$', '', data, flags = re.MULTILINE)
1207 data = re.sub('#.*?$', '', data, flags = re.MULTILINE)
1208 for i, line in enumerate(data.split('\n')):
1213 parts = line.split(None, 1)
1216 sys.stderr.write("%s:%d: " % (infile.name, i + 1) +
1217 "Option lines should have space between field name and options. " +
1218 "Skipping line: '%s'\n" % line)
1221 opts = nanopb_pb2.NanoPBOptions()
1224 text_format.Merge(parts[1], opts)
1225 except Exception, e:
1226 sys.stderr.write("%s:%d: " % (infile.name, i + 1) +
1227 "Unparseable option line: '%s'. " % line +
1228 "Error: %s\n" % str(e))
1230 results.append((parts[0], opts))
1235 '''Ugly global variables, should find a good way to pass these.'''
1236 verbose_options = False
1237 separate_options = []
1238 matched_namemasks = set()
1240 def get_nanopb_suboptions(subdesc, options, name):
1241 '''Get copy of options, and merge information from subdesc.'''
1242 new_options = nanopb_pb2.NanoPBOptions()
1243 new_options.CopyFrom(options)
1245 # Handle options defined in a separate file
1246 dotname = '.'.join(name.parts)
1247 for namemask, options in Globals.separate_options:
1248 if fnmatch(dotname, namemask):
1249 Globals.matched_namemasks.add(namemask)
1250 new_options.MergeFrom(options)
1252 # Handle options defined in .proto
1253 if isinstance(subdesc.options, descriptor.FieldOptions):
1254 ext_type = nanopb_pb2.nanopb
1255 elif isinstance(subdesc.options, descriptor.FileOptions):
1256 ext_type = nanopb_pb2.nanopb_fileopt
1257 elif isinstance(subdesc.options, descriptor.MessageOptions):
1258 ext_type = nanopb_pb2.nanopb_msgopt
1259 elif isinstance(subdesc.options, descriptor.EnumOptions):
1260 ext_type = nanopb_pb2.nanopb_enumopt
1262 raise Exception("Unknown options type")
1264 if subdesc.options.HasExtension(ext_type):
1265 ext = subdesc.options.Extensions[ext_type]
1266 new_options.MergeFrom(ext)
1268 if Globals.verbose_options:
1269 sys.stderr.write("Options for " + dotname + ": ")
1270 sys.stderr.write(text_format.MessageToString(new_options) + "\n")
1275 # ---------------------------------------------------------------------------
1276 # Command line interface
1277 # ---------------------------------------------------------------------------
1281 from optparse import OptionParser
1283 optparser = OptionParser(
1284 usage = "Usage: nanopb_generator.py [options] file.pb ...",
1285 epilog = "Compile file.pb from file.proto by: 'protoc -ofile.pb file.proto'. " +
1286 "Output will be written to file.pb.h and file.pb.c.")
1287 optparser.add_option("-x", dest="exclude", metavar="FILE", action="append", default=[],
1288 help="Exclude file from generated #include list.")
1289 optparser.add_option("-e", "--extension", dest="extension", metavar="EXTENSION", default=".pb",
1290 help="Set extension to use instead of '.pb' for generated files. [default: %default]")
1291 optparser.add_option("-f", "--options-file", dest="options_file", metavar="FILE", default="%s.options",
1292 help="Set name of a separate generator options file.")
1293 optparser.add_option("-Q", "--generated-include-format", dest="genformat",
1294 metavar="FORMAT", default='#include "%s"\n',
1295 help="Set format string to use for including other .pb.h files. [default: %default]")
1296 optparser.add_option("-L", "--library-include-format", dest="libformat",
1297 metavar="FORMAT", default='#include <%s>\n',
1298 help="Set format string to use for including the nanopb pb.h header. [default: %default]")
1299 optparser.add_option("-T", "--no-timestamp", dest="notimestamp", action="store_true", default=False,
1300 help="Don't add timestamp to .pb.h and .pb.c preambles")
1301 optparser.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False,
1302 help="Don't print anything except errors.")
1303 optparser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
1304 help="Print more information.")
1305 optparser.add_option("-s", dest="settings", metavar="OPTION:VALUE", action="append", default=[],
1306 help="Set generator option (max_size, max_count etc.).")
1308 def process_file(filename, fdesc, options):
1309 '''Process a single file.
1310 filename: The full path to the .proto or .pb source file, as string.
1311 fdesc: The loaded FileDescriptorSet, or None to read from the input file.
1312 options: Command line options as they come from OptionsParser.
1315 {'headername': Name of header file,
1316 'headerdata': Data for the .h header file,
1317 'sourcename': Name of the source code file,
1318 'sourcedata': Data for the .c source code file
1321 toplevel_options = nanopb_pb2.NanoPBOptions()
1322 for s in options.settings:
1323 text_format.Merge(s, toplevel_options)
1326 data = open(filename, 'rb').read()
1327 fdesc = descriptor.FileDescriptorSet.FromString(data).file[0]
1329 # Check if there is a separate .options file
1332 optfilename = options.options_file % os.path.splitext(filename)[0]
1334 # No %s specified, use the filename as-is
1335 optfilename = options.options_file
1338 if os.path.isfile(optfilename):
1340 sys.stderr.write('Reading options from ' + optfilename + '\n')
1342 Globals.separate_options = read_options_file(open(optfilename, "rU"))
1344 # If we are given a full filename and it does not exist, give an error.
1345 # However, don't give error when we automatically look for .options file
1346 # with the same name as .proto.
1347 if options.verbose or had_abspath:
1348 sys.stderr.write('Options file not found: ' + optfilename)
1350 Globals.separate_options = []
1352 Globals.matched_namemasks = set()
1355 file_options = get_nanopb_suboptions(fdesc, toplevel_options, Names([filename]))
1356 f = ProtoFile(fdesc, file_options)
1358 # Decide the file names
1359 noext = os.path.splitext(filename)[0]
1360 headername = noext + options.extension + '.h'
1361 sourcename = noext + options.extension + '.c'
1362 headerbasename = os.path.basename(headername)
1364 # List of .proto files that should not be included in the C header file
1365 # even if they are mentioned in the source .proto.
1366 excludes = ['nanopb.proto', 'google/protobuf/descriptor.proto'] + options.exclude
1367 includes = [d for d in fdesc.dependency if d not in excludes]
1369 headerdata = ''.join(f.generate_header(includes, headerbasename, options))
1370 sourcedata = ''.join(f.generate_source(headerbasename, options))
1372 # Check if there were any lines in .options that did not match a member
1373 unmatched = [n for n,o in Globals.separate_options if n not in Globals.matched_namemasks]
1374 if unmatched and not options.quiet:
1375 sys.stderr.write("Following patterns in " + optfilename + " did not match any fields: "
1376 + ', '.join(unmatched) + "\n")
1377 if not Globals.verbose_options:
1378 sys.stderr.write("Use protoc --nanopb-out=-v:. to see a list of the field names.\n")
1380 return {'headername': headername, 'headerdata': headerdata,
1381 'sourcename': sourcename, 'sourcedata': sourcedata}
1384 '''Main function when invoked directly from the command line.'''
1386 options, filenames = optparser.parse_args()
1389 optparser.print_help()
1393 options.verbose = False
1395 Globals.verbose_options = options.verbose
1397 for filename in filenames:
1398 results = process_file(filename, None, options)
1400 if not options.quiet:
1401 sys.stderr.write("Writing to " + results['headername'] + " and "
1402 + results['sourcename'] + "\n")
1404 open(results['headername'], 'w').write(results['headerdata'])
1405 open(results['sourcename'], 'w').write(results['sourcedata'])
1408 '''Main function when invoked as a protoc plugin.'''
1411 if sys.platform == "win32":
1413 # Set stdin and stdout to binary mode
1414 msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
1415 msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
1417 data = sys.stdin.read()
1418 request = plugin_pb2.CodeGeneratorRequest.FromString(data)
1421 # Versions of Python prior to 2.7.3 do not support unicode
1422 # input to shlex.split(). Try to convert to str if possible.
1423 params = str(request.parameter)
1424 except UnicodeEncodeError:
1425 params = request.parameter
1428 args = shlex.split(params)
1429 options, dummy = optparser.parse_args(args)
1431 Globals.verbose_options = options.verbose
1433 response = plugin_pb2.CodeGeneratorResponse()
1435 for filename in request.file_to_generate:
1436 for fdesc in request.proto_file:
1437 if fdesc.name == filename:
1438 results = process_file(filename, fdesc, options)
1440 f = response.file.add()
1441 f.name = results['headername']
1442 f.content = results['headerdata']
1444 f = response.file.add()
1445 f.name = results['sourcename']
1446 f.content = results['sourcedata']
1448 sys.stdout.write(response.SerializeToString())
1450 if __name__ == '__main__':
1451 # Check if we are running as a plugin under protoc
1452 if 'protoc-gen-' in sys.argv[0] or '--protoc-plugin' in sys.argv: