3 from __future__ import unicode_literals
5 '''Generate header file for nanopb from a ProtoBuf FileDescriptorSet.'''
6 nanopb_version = "nanopb-0.3.9-dev"
10 from functools import reduce
13 # Add some dummy imports to keep packaging tools happy.
14 import google, distutils.util # bbfreeze seems to need these
15 import pkg_resources # pyinstaller / protobuf 2.5 seem to need these
17 # Don't care, we will error out later if it is actually important.
21 import google.protobuf.text_format as text_format
22 import google.protobuf.descriptor_pb2 as descriptor
25 *************************************************************
26 *** Could not import the Google protobuf Python libraries ***
27 *** Try installing package 'python-protobuf' or similar. ***
28 *************************************************************
33 import proto.nanopb_pb2 as nanopb_pb2
34 import proto.plugin_pb2 as plugin_pb2
37 ****************************************************************************
38 *** Got TypeError when importing the protocol definitions for generator. ***
39 *** This usually means that the protoc in your path doesn't match the ***
40 *** Python protobuf library version. ***
42 *** Please check the output of the following commands: ***
44 *** protoc --version ***
45 *** python -c 'import google.protobuf; print(google.protobuf.__file__)' ***
46 ****************************************************************************
51 ********************************************************************
52 *** Failed to import the protocol definitions for generator. ***
53 *** You have to run 'make' in the nanopb/generator/proto folder. ***
54 ********************************************************************
58 # ---------------------------------------------------------------------------
59 # Generation of single fields
60 # ---------------------------------------------------------------------------
65 # Values are tuple (c type, pb type, encoded size, int_size_allowed)
66 FieldD = descriptor.FieldDescriptorProto
68 FieldD.TYPE_BOOL: ('bool', 'BOOL', 1, False),
69 FieldD.TYPE_DOUBLE: ('double', 'DOUBLE', 8, False),
70 FieldD.TYPE_FIXED32: ('uint32_t', 'FIXED32', 4, False),
71 FieldD.TYPE_FIXED64: ('uint64_t', 'FIXED64', 8, False),
72 FieldD.TYPE_FLOAT: ('float', 'FLOAT', 4, False),
73 FieldD.TYPE_INT32: ('int32_t', 'INT32', 10, True),
74 FieldD.TYPE_INT64: ('int64_t', 'INT64', 10, True),
75 FieldD.TYPE_SFIXED32: ('int32_t', 'SFIXED32', 4, False),
76 FieldD.TYPE_SFIXED64: ('int64_t', 'SFIXED64', 8, False),
77 FieldD.TYPE_SINT32: ('int32_t', 'SINT32', 5, True),
78 FieldD.TYPE_SINT64: ('int64_t', 'SINT64', 10, True),
79 FieldD.TYPE_UINT32: ('uint32_t', 'UINT32', 5, True),
80 FieldD.TYPE_UINT64: ('uint64_t', 'UINT64', 10, True)
83 # Integer size overrides (from .proto settings)
85 nanopb_pb2.IS_8: 'int8_t',
86 nanopb_pb2.IS_16: 'int16_t',
87 nanopb_pb2.IS_32: 'int32_t',
88 nanopb_pb2.IS_64: 'int64_t',
91 # String types (for python 2 / python 3 compatibility)
93 strtypes = (unicode, str)
98 '''Keeps a set of nested names and formats them to C identifier.'''
99 def __init__(self, parts = ()):
100 if isinstance(parts, Names):
102 self.parts = tuple(parts)
105 return '_'.join(self.parts)
107 def __add__(self, other):
108 if isinstance(other, strtypes):
109 return Names(self.parts + (other,))
110 elif isinstance(other, tuple):
111 return Names(self.parts + other)
113 raise ValueError("Name parts should be of type str")
115 def __eq__(self, other):
116 return isinstance(other, Names) and self.parts == other.parts
118 def names_from_type_name(type_name):
119 '''Parse Names() from FieldDescriptorProto type_name'''
120 if type_name[0] != '.':
121 raise NotImplementedError("Lookup of non-absolute type names is not supported")
122 return Names(type_name[1:].split('.'))
124 def varint_max_size(max_value):
125 '''Returns the maximum number of bytes a varint can take when encoded.'''
127 max_value = 2**64 - max_value
128 for i in range(1, 11):
129 if (max_value >> (i * 7)) == 0:
131 raise ValueError("Value too large for varint: " + str(max_value))
133 assert varint_max_size(-1) == 10
134 assert varint_max_size(0) == 1
135 assert varint_max_size(127) == 1
136 assert varint_max_size(128) == 2
139 '''Class used to represent the encoded size of a field or a message.
140 Consists of a combination of symbolic sizes and integer sizes.'''
141 def __init__(self, value = 0, symbols = []):
142 if isinstance(value, EncodedSize):
143 self.value = value.value
144 self.symbols = value.symbols
145 elif isinstance(value, strtypes + (Names,)):
146 self.symbols = [str(value)]
150 self.symbols = symbols
152 def __add__(self, other):
153 if isinstance(other, int):
154 return EncodedSize(self.value + other, self.symbols)
155 elif isinstance(other, strtypes + (Names,)):
156 return EncodedSize(self.value, self.symbols + [str(other)])
157 elif isinstance(other, EncodedSize):
158 return EncodedSize(self.value + other.value, self.symbols + other.symbols)
160 raise ValueError("Cannot add size: " + repr(other))
162 def __mul__(self, other):
163 if isinstance(other, int):
164 return EncodedSize(self.value * other, [str(other) + '*' + s for s in self.symbols])
166 raise ValueError("Cannot multiply size: " + repr(other))
170 return str(self.value)
172 return '(' + str(self.value) + ' + ' + ' + '.join(self.symbols) + ')'
174 def upperlimit(self):
181 def __init__(self, names, desc, enum_options):
182 '''desc is EnumDescriptorProto'''
184 self.options = enum_options
185 self.names = names + desc.name
187 if enum_options.long_names:
188 self.values = [(self.names + x.name, x.number) for x in desc.value]
190 self.values = [(names + x.name, x.number) for x in desc.value]
192 self.value_longnames = [self.names + x.name for x in desc.value]
193 self.packed = enum_options.packed_enum
195 def has_negative(self):
196 for n, v in self.values:
201 def encoded_size(self):
202 return max([varint_max_size(v) for n,v in self.values])
205 result = 'typedef enum _%s {\n' % self.names
206 result += ',\n'.join([" %s = %d" % x for x in self.values])
210 result += ' pb_packed'
212 result += ' %s;' % self.names
214 result += '\n#define _%s_MIN %s' % (self.names, self.values[0][0])
215 result += '\n#define _%s_MAX %s' % (self.names, self.values[-1][0])
216 result += '\n#define _%s_ARRAYSIZE ((%s)(%s+1))' % (self.names, self.names, self.values[-1][0])
218 if not self.options.long_names:
219 # Define the long names always so that enum value references
220 # from other files work properly.
221 for i, x in enumerate(self.values):
222 result += '\n#define %s %s' % (self.value_longnames[i], x[0])
224 if self.options.enum_to_string:
225 result += '\nconst char *%s_name(%s v);\n' % (self.names, self.names)
229 def enum_to_string_definition(self):
230 if not self.options.enum_to_string:
233 result = 'const char *%s_name(%s v) {\n' % (self.names, self.names)
234 result += ' switch (v) {\n'
236 for ((enumname, _), strname) in zip(self.values, self.value_longnames):
237 # Strip off the leading type name from the string value.
238 strval = str(strname)[len(str(self.names)) + 1:]
239 result += ' case %s: return "%s";\n' % (enumname, strval)
242 result += ' return "unknown";\n'
248 def __init__(self, worst = 0, checks = [], field_name = 'undefined'):
249 if isinstance(worst, list):
250 self.worst = max(i for i in worst if i is not None)
254 self.worst_field = field_name
255 self.checks = list(checks)
257 def extend(self, extend, field_name = None):
258 self.worst = max(self.worst, extend.worst)
260 if self.worst == extend.worst:
261 self.worst_field = extend.worst_field
263 self.checks.extend(extend.checks)
266 def __init__(self, struct_name, desc, field_options):
267 '''desc is FieldDescriptorProto'''
268 self.tag = desc.number
269 self.struct_name = struct_name
270 self.union_name = None
271 self.name = desc.name
274 self.max_count = None
279 if field_options.type == nanopb_pb2.FT_INLINE:
280 # Before nanopb-0.3.8, fixed length bytes arrays were specified
281 # by setting type to FT_INLINE. But to handle pointer typed fields,
282 # it makes sense to have it as a separate option.
283 field_options.type = nanopb_pb2.FT_STATIC
284 field_options.fixed_length = True
286 # Parse field options
287 if field_options.HasField("max_size"):
288 self.max_size = field_options.max_size
290 if desc.type == FieldD.TYPE_STRING and field_options.HasField("max_length"):
291 # max_length overrides max_size for strings
292 self.max_size = field_options.max_length + 1
294 if field_options.HasField("max_count"):
295 self.max_count = field_options.max_count
297 if desc.HasField('default_value'):
298 self.default = desc.default_value
300 # Check field rules, i.e. required/optional/repeated.
302 if desc.label == FieldD.LABEL_REPEATED:
303 self.rules = 'REPEATED'
304 if self.max_count is None:
305 can_be_static = False
307 self.array_decl = '[%d]' % self.max_count
308 elif field_options.proto3:
309 self.rules = 'SINGULAR'
310 elif desc.label == FieldD.LABEL_REQUIRED:
311 self.rules = 'REQUIRED'
312 elif desc.label == FieldD.LABEL_OPTIONAL:
313 self.rules = 'OPTIONAL'
315 raise NotImplementedError(desc.label)
317 # Check if the field can be implemented with static allocation
318 # i.e. whether the data size is known.
319 if desc.type == FieldD.TYPE_STRING and self.max_size is None:
320 can_be_static = False
322 if desc.type == FieldD.TYPE_BYTES and self.max_size is None:
323 can_be_static = False
325 # Decide how the field data will be allocated
326 if field_options.type == nanopb_pb2.FT_DEFAULT:
328 field_options.type = nanopb_pb2.FT_STATIC
330 field_options.type = nanopb_pb2.FT_CALLBACK
332 if field_options.type == nanopb_pb2.FT_STATIC and not can_be_static:
333 raise Exception("Field %s is defined as static, but max_size or "
334 "max_count is not given." % self.name)
336 if field_options.type == nanopb_pb2.FT_STATIC:
337 self.allocation = 'STATIC'
338 elif field_options.type == nanopb_pb2.FT_POINTER:
339 self.allocation = 'POINTER'
340 elif field_options.type == nanopb_pb2.FT_CALLBACK:
341 self.allocation = 'CALLBACK'
343 raise NotImplementedError(field_options.type)
345 # Decide the C data type to use in the struct.
346 if desc.type in datatypes:
347 self.ctype, self.pbtype, self.enc_size, isa = datatypes[desc.type]
349 # Override the field size if user wants to use smaller integers
350 if isa and field_options.int_size != nanopb_pb2.IS_DEFAULT:
351 self.ctype = intsizes[field_options.int_size]
352 if desc.type == FieldD.TYPE_UINT32 or desc.type == FieldD.TYPE_UINT64:
353 self.ctype = 'u' + self.ctype;
354 elif desc.type == FieldD.TYPE_ENUM:
356 self.ctype = names_from_type_name(desc.type_name)
357 if self.default is not None:
358 self.default = self.ctype + self.default
359 self.enc_size = None # Needs to be filled in when enum values are known
360 elif desc.type == FieldD.TYPE_STRING:
361 self.pbtype = 'STRING'
363 if self.allocation == 'STATIC':
365 self.array_decl += '[%d]' % self.max_size
366 self.enc_size = varint_max_size(self.max_size) + self.max_size
367 elif desc.type == FieldD.TYPE_BYTES:
368 if field_options.fixed_length:
369 self.pbtype = 'FIXED_LENGTH_BYTES'
370 self.enc_size = varint_max_size(self.max_size) + self.max_size
371 self.ctype = 'pb_byte_t'
372 self.array_decl += '[%d]' % self.max_size
374 self.pbtype = 'BYTES'
375 self.ctype = 'pb_bytes_array_t'
376 if self.allocation == 'STATIC':
377 self.ctype = self.struct_name + self.name + 't'
378 self.enc_size = varint_max_size(self.max_size) + self.max_size
379 elif desc.type == FieldD.TYPE_MESSAGE:
380 self.pbtype = 'MESSAGE'
381 self.ctype = self.submsgname = names_from_type_name(desc.type_name)
382 self.enc_size = None # Needs to be filled in after the message type is available
384 raise NotImplementedError(desc.type)
386 def __lt__(self, other):
387 return self.tag < other.tag
391 if self.allocation == 'POINTER':
392 if self.rules == 'REPEATED':
393 result += ' pb_size_t ' + self.name + '_count;\n'
395 if self.pbtype == 'MESSAGE':
396 # Use struct definition, so recursive submessages are possible
397 result += ' struct _%s *%s;' % (self.ctype, self.name)
398 elif self.pbtype == 'FIXED_LENGTH_BYTES':
399 # Pointer to fixed size array
400 result += ' %s (*%s)%s;' % (self.ctype, self.name, self.array_decl)
401 elif self.rules == 'REPEATED' and self.pbtype in ['STRING', 'BYTES']:
402 # String/bytes arrays need to be defined as pointers to pointers
403 result += ' %s **%s;' % (self.ctype, self.name)
405 result += ' %s *%s;' % (self.ctype, self.name)
406 elif self.allocation == 'CALLBACK':
407 result += ' pb_callback_t %s;' % self.name
409 if self.rules == 'OPTIONAL' and self.allocation == 'STATIC':
410 result += ' bool has_' + self.name + ';\n'
411 elif self.rules == 'REPEATED' and self.allocation == 'STATIC':
412 result += ' pb_size_t ' + self.name + '_count;\n'
413 result += ' %s %s%s;' % (self.ctype, self.name, self.array_decl)
417 '''Return definitions for any special types this field might need.'''
418 if self.pbtype == 'BYTES' and self.allocation == 'STATIC':
419 result = 'typedef PB_BYTES_ARRAY_T(%d) %s;\n' % (self.max_size, self.ctype)
424 def get_dependencies(self):
425 '''Get list of type names used by this field.'''
426 if self.allocation == 'STATIC':
427 return [str(self.ctype)]
431 def get_initializer(self, null_init, inner_init_only = False):
432 '''Return literal expression for this field's default value.
433 null_init: If True, initialize to a 0 value instead of default from .proto
434 inner_init_only: If True, exclude initialization for any count/has fields
438 if self.pbtype == 'MESSAGE':
440 inner_init = '%s_init_zero' % self.ctype
442 inner_init = '%s_init_default' % self.ctype
443 elif self.default is None or null_init:
444 if self.pbtype == 'STRING':
446 elif self.pbtype == 'BYTES':
447 inner_init = '{0, {0}}'
448 elif self.pbtype == 'FIXED_LENGTH_BYTES':
450 elif self.pbtype in ('ENUM', 'UENUM'):
451 inner_init = '(%s)0' % self.ctype
455 if self.pbtype == 'STRING':
456 inner_init = self.default.replace('"', '\\"')
457 inner_init = '"' + inner_init + '"'
458 elif self.pbtype == 'BYTES':
459 data = ['0x%02x' % ord(c) for c in self.default]
461 inner_init = '{0, {0}}'
463 inner_init = '{%d, {%s}}' % (len(data), ','.join(data))
464 elif self.pbtype == 'FIXED_LENGTH_BYTES':
465 data = ['0x%02x' % ord(c) for c in self.default]
469 inner_init = '{%s}' % ','.join(data)
470 elif self.pbtype in ['FIXED32', 'UINT32']:
471 inner_init = str(self.default) + 'u'
472 elif self.pbtype in ['FIXED64', 'UINT64']:
473 inner_init = str(self.default) + 'ull'
474 elif self.pbtype in ['SFIXED64', 'INT64']:
475 inner_init = str(self.default) + 'll'
477 inner_init = str(self.default)
483 if self.allocation == 'STATIC':
484 if self.rules == 'REPEATED':
486 outer_init += ', '.join([inner_init] * self.max_count)
488 elif self.rules == 'OPTIONAL':
489 outer_init = 'false, ' + inner_init
491 outer_init = inner_init
492 elif self.allocation == 'POINTER':
493 if self.rules == 'REPEATED':
494 outer_init = '0, NULL'
497 elif self.allocation == 'CALLBACK':
498 if self.pbtype == 'EXTENSION':
501 outer_init = '{{NULL}, NULL}'
505 def default_decl(self, declaration_only = False):
506 '''Return definition for this field's default value.'''
507 if self.default is None:
511 default = self.get_initializer(False, True)
514 if self.pbtype == 'STRING':
515 if self.allocation != 'STATIC':
516 return None # Not implemented
517 array_decl = '[%d]' % self.max_size
518 elif self.pbtype == 'BYTES':
519 if self.allocation != 'STATIC':
520 return None # Not implemented
521 elif self.pbtype == 'FIXED_LENGTH_BYTES':
522 if self.allocation != 'STATIC':
523 return None # Not implemented
524 array_decl = '[%d]' % self.max_size
527 return 'extern const %s %s_default%s;' % (ctype, self.struct_name + self.name, array_decl)
529 return 'const %s %s_default%s = %s;' % (ctype, self.struct_name + self.name, array_decl, default)
532 '''Return the #define for the tag number of this field.'''
533 identifier = '%s_%s_tag' % (self.struct_name, self.name)
534 return '#define %-40s %d\n' % (identifier, self.tag)
536 def pb_field_t(self, prev_field_name, union_index = None):
537 '''Return the pb_field_t initializer to use in the constant array.
538 prev_field_name is the name of the previous field or None. For OneOf
539 unions, union_index is the index of this field inside the OneOf.
542 if self.rules == 'ONEOF':
544 result = ' PB_ANONYMOUS_ONEOF_FIELD(%s, ' % self.union_name
546 result = ' PB_ONEOF_FIELD(%s, ' % self.union_name
548 result = ' PB_FIELD('
550 result += '%3d, ' % self.tag
551 result += '%-8s, ' % self.pbtype
552 result += '%s, ' % self.rules
553 result += '%-8s, ' % self.allocation
555 if union_index is not None and union_index > 0:
557 elif prev_field_name is None:
562 result += '%s, ' % self.struct_name
563 result += '%s, ' % self.name
564 result += '%s, ' % (prev_field_name or self.name)
566 if self.pbtype == 'MESSAGE':
567 result += '&%s_fields)' % self.submsgname
568 elif self.default is None:
570 elif self.pbtype in ['BYTES', 'STRING', 'FIXED_LENGTH_BYTES'] and self.allocation != 'STATIC':
571 result += '0)' # Arbitrary size default values not implemented
572 elif self.rules == 'OPTEXT':
573 result += '0)' # Default value for extensions is not implemented
575 result += '&%s_default)' % (self.struct_name + self.name)
579 def get_last_field_name(self):
582 def largest_field_value(self):
583 '''Determine if this field needs 16bit or 32bit pb_field_t structure to compile properly.
584 Returns numeric value or a C-expression for assert.'''
586 if self.pbtype == 'MESSAGE' and self.allocation == 'STATIC':
587 if self.rules == 'REPEATED':
588 check.append('pb_membersize(%s, %s[0])' % (self.struct_name, self.name))
589 elif self.rules == 'ONEOF':
591 check.append('pb_membersize(%s, %s)' % (self.struct_name, self.name))
593 check.append('pb_membersize(%s, %s.%s)' % (self.struct_name, self.union_name, self.name))
595 check.append('pb_membersize(%s, %s)' % (self.struct_name, self.name))
596 elif self.pbtype == 'BYTES' and self.allocation == 'STATIC':
597 if self.max_size > 251:
598 check.append('pb_membersize(%s, %s)' % (self.struct_name, self.name))
600 return FieldMaxSize([self.tag, self.max_size, self.max_count],
602 ('%s.%s' % (self.struct_name, self.name)))
604 def encoded_size(self, dependencies):
605 '''Return the maximum size that this field can take when encoded,
606 including the field tag. If the size cannot be determined, returns
609 if self.allocation != 'STATIC':
612 if self.pbtype == 'MESSAGE':
614 if str(self.submsgname) in dependencies:
615 submsg = dependencies[str(self.submsgname)]
616 encsize = submsg.encoded_size(dependencies)
617 if encsize is not None:
618 # Include submessage length prefix
619 encsize += varint_max_size(encsize.upperlimit())
622 # Submessage or its size cannot be found.
623 # This can occur if submessage is defined in different
624 # file, and it or its .options could not be found.
625 # Instead of direct numeric value, reference the size that
626 # has been #defined in the other file.
627 encsize = EncodedSize(self.submsgname + 'size')
629 # We will have to make a conservative assumption on the length
630 # prefix size, though.
633 elif self.pbtype in ['ENUM', 'UENUM']:
634 if str(self.ctype) in dependencies:
635 enumtype = dependencies[str(self.ctype)]
636 encsize = enumtype.encoded_size()
638 # Conservative assumption
641 elif self.enc_size is None:
642 raise RuntimeError("Could not determine encoded size for %s.%s"
643 % (self.struct_name, self.name))
645 encsize = EncodedSize(self.enc_size)
647 encsize += varint_max_size(self.tag << 3) # Tag + wire type
649 if self.rules == 'REPEATED':
650 # Decoders must be always able to handle unpacked arrays.
651 # Therefore we have to reserve space for it, even though
652 # we emit packed arrays ourselves. For length of 1, packed
653 # arrays are larger however so we need to add allowance
654 # for the length byte.
655 encsize *= self.max_count
657 if self.max_count == 1:
663 class ExtensionRange(Field):
664 def __init__(self, struct_name, range_start, field_options):
665 '''Implements a special pb_extension_t* field in an extensible message
666 structure. The range_start signifies the index at which the extensions
667 start. Not necessarily all tags above this are extensions, it is merely
668 a speed optimization.
670 self.tag = range_start
671 self.struct_name = struct_name
672 self.name = 'extensions'
673 self.pbtype = 'EXTENSION'
674 self.rules = 'OPTIONAL'
675 self.allocation = 'CALLBACK'
676 self.ctype = 'pb_extension_t'
683 return ' pb_extension_t *extensions;'
691 def encoded_size(self, dependencies):
692 # We exclude extensions from the count, because they cannot be known
693 # until runtime. Other option would be to return None here, but this
694 # way the value remains useful if extensions are not used.
695 return EncodedSize(0)
697 class ExtensionField(Field):
698 def __init__(self, struct_name, desc, field_options):
699 self.fullname = struct_name + desc.name
700 self.extendee_name = names_from_type_name(desc.extendee)
701 Field.__init__(self, self.fullname + 'struct', desc, field_options)
703 if self.rules != 'OPTIONAL':
707 self.rules = 'OPTEXT'
710 '''Return the #define for the tag number of this field.'''
711 identifier = '%s_tag' % self.fullname
712 return '#define %-40s %d\n' % (identifier, self.tag)
714 def extension_decl(self):
715 '''Declaration of the extension type in the .pb.h file'''
717 msg = '/* Extension field %s was skipped because only "optional"\n' % self.fullname
718 msg +=' type of extension fields is currently supported. */\n'
721 return ('extern const pb_extension_type_t %s; /* field type: %s */\n' %
722 (self.fullname, str(self).strip()))
724 def extension_def(self):
725 '''Definition of the extension type in the .pb.c file'''
730 result = 'typedef struct {\n'
732 result += '\n} %s;\n\n' % self.struct_name
733 result += ('static const pb_field_t %s_field = \n %s;\n\n' %
734 (self.fullname, self.pb_field_t(None)))
735 result += 'const pb_extension_type_t %s = {\n' % self.fullname
738 result += ' &%s_field\n' % self.fullname
743 # ---------------------------------------------------------------------------
744 # Generation of oneofs (unions)
745 # ---------------------------------------------------------------------------
748 def __init__(self, struct_name, oneof_desc):
749 self.struct_name = struct_name
750 self.name = oneof_desc.name
752 self.pbtype = 'oneof'
754 self.allocation = 'ONEOF'
757 self.anonymous = False
759 def add_field(self, field):
760 if field.allocation == 'CALLBACK':
761 raise Exception("Callback fields inside of oneof are not supported"
762 + " (field %s)" % field.name)
764 field.union_name = self.name
765 field.rules = 'ONEOF'
766 field.anonymous = self.anonymous
767 self.fields.append(field)
768 self.fields.sort(key = lambda f: f.tag)
770 # Sort by the lowest tag number inside union
771 self.tag = min([f.tag for f in self.fields])
776 result += ' pb_size_t which_' + self.name + ";\n"
777 result += ' union {\n'
778 for f in self.fields:
779 result += ' ' + str(f).replace('\n', '\n ') + '\n'
783 result += ' } ' + self.name + ';'
787 return ''.join([f.types() for f in self.fields])
789 def get_dependencies(self):
791 for f in self.fields:
792 deps += f.get_dependencies()
795 def get_initializer(self, null_init):
796 return '0, {' + self.fields[0].get_initializer(null_init) + '}'
798 def default_decl(self, declaration_only = False):
802 return ''.join([f.tags() for f in self.fields])
804 def pb_field_t(self, prev_field_name):
806 for union_index, field in enumerate(self.fields):
807 parts.append(field.pb_field_t(prev_field_name, union_index))
808 return ',\n'.join(parts)
810 def get_last_field_name(self):
812 return self.fields[-1].name
814 return self.name + '.' + self.fields[-1].name
816 def largest_field_value(self):
817 largest = FieldMaxSize()
818 for f in self.fields:
819 largest.extend(f.largest_field_value())
822 def encoded_size(self, dependencies):
823 '''Returns the size of the largest oneof field.'''
824 largest = EncodedSize(0)
825 for f in self.fields:
826 size = EncodedSize(f.encoded_size(dependencies))
827 if size.value is None:
830 return None # Cannot resolve maximum of symbols
831 elif size.value > largest.value:
836 # ---------------------------------------------------------------------------
837 # Generation of messages (structures)
838 # ---------------------------------------------------------------------------
842 def __init__(self, names, desc, message_options):
848 if message_options.msgid:
849 self.msgid = message_options.msgid
851 if hasattr(desc, 'oneof_decl'):
852 for i, f in enumerate(desc.oneof_decl):
853 oneof_options = get_nanopb_suboptions(desc, message_options, self.name + f.name)
854 if oneof_options.no_unions:
855 no_unions.append(i) # No union, but add fields normally
856 elif oneof_options.type == nanopb_pb2.FT_IGNORE:
857 pass # No union and skip fields also
859 oneof = OneOf(self.name, f)
860 if oneof_options.anonymous_oneof:
861 oneof.anonymous = True
862 self.oneofs[i] = oneof
863 self.fields.append(oneof)
866 field_options = get_nanopb_suboptions(f, message_options, self.name + f.name)
867 if field_options.type == nanopb_pb2.FT_IGNORE:
870 field = Field(self.name, f, field_options)
871 if (hasattr(f, 'oneof_index') and
872 f.HasField('oneof_index') and
873 f.oneof_index not in no_unions):
874 if f.oneof_index in self.oneofs:
875 self.oneofs[f.oneof_index].add_field(field)
877 self.fields.append(field)
879 if len(desc.extension_range) > 0:
880 field_options = get_nanopb_suboptions(desc, message_options, self.name + 'extensions')
881 range_start = min([r.start for r in desc.extension_range])
882 if field_options.type != nanopb_pb2.FT_IGNORE:
883 self.fields.append(ExtensionRange(self.name, range_start, field_options))
885 self.packed = message_options.packed_struct
886 self.ordered_fields = self.fields[:]
887 self.ordered_fields.sort()
889 def get_dependencies(self):
890 '''Get list of type names that this structure refers to.'''
892 for f in self.fields:
893 deps += f.get_dependencies()
897 result = 'typedef struct _%s {\n' % self.name
899 if not self.ordered_fields:
900 # Empty structs are not allowed in C standard.
901 # Therefore add a dummy field if an empty message occurs.
902 result += ' char dummy_field;'
904 result += '\n'.join([str(f) for f in self.ordered_fields])
905 result += '\n/* @@protoc_insertion_point(struct:%s) */' % self.name
909 result += ' pb_packed'
911 result += ' %s;' % self.name
914 result = 'PB_PACKED_STRUCT_START\n' + result
915 result += '\nPB_PACKED_STRUCT_END'
920 return ''.join([f.types() for f in self.fields])
922 def get_initializer(self, null_init):
923 if not self.ordered_fields:
927 for field in self.ordered_fields:
928 parts.append(field.get_initializer(null_init))
929 return '{' + ', '.join(parts) + '}'
931 def default_decl(self, declaration_only = False):
933 for field in self.fields:
934 default = field.default_decl(declaration_only)
935 if default is not None:
936 result += default + '\n'
939 def count_required_fields(self):
940 '''Returns number of required fields inside this message'''
942 for f in self.fields:
943 if not isinstance(f, OneOf):
944 if f.rules == 'REQUIRED':
948 def count_all_fields(self):
950 for f in self.fields:
951 if isinstance(f, OneOf):
952 count += len(f.fields)
957 def fields_declaration(self):
958 result = 'extern const pb_field_t %s_fields[%d];' % (self.name, self.count_all_fields() + 1)
961 def fields_definition(self):
962 result = 'const pb_field_t %s_fields[%d] = {\n' % (self.name, self.count_all_fields() + 1)
965 for field in self.ordered_fields:
966 result += field.pb_field_t(prev)
968 prev = field.get_last_field_name()
970 result += ' PB_LAST_FIELD\n};'
973 def encoded_size(self, dependencies):
974 '''Return the maximum size that this message can take when encoded.
975 If the size cannot be determined, returns None.
977 size = EncodedSize(0)
978 for field in self.fields:
979 fsize = field.encoded_size(dependencies)
987 # ---------------------------------------------------------------------------
988 # Processing of entire .proto files
989 # ---------------------------------------------------------------------------
991 def iterate_messages(desc, names = Names()):
992 '''Recursively find all messages. For each, yield name, DescriptorProto.'''
993 if hasattr(desc, 'message_type'):
994 submsgs = desc.message_type
996 submsgs = desc.nested_type
998 for submsg in submsgs:
999 sub_names = names + submsg.name
1000 yield sub_names, submsg
1002 for x in iterate_messages(submsg, sub_names):
1005 def iterate_extensions(desc, names = Names()):
1006 '''Recursively find all extensions.
1007 For each, yield name, FieldDescriptorProto.
1009 for extension in desc.extension:
1010 yield names, extension
1012 for subname, subdesc in iterate_messages(desc, names):
1013 for extension in subdesc.extension:
1014 yield subname, extension
1016 def toposort2(data):
1017 '''Topological sort.
1018 From http://code.activestate.com/recipes/577413-topological-sort/
1019 This function is under the MIT license.
1021 for k, v in list(data.items()):
1022 v.discard(k) # Ignore self dependencies
1023 extra_items_in_deps = reduce(set.union, list(data.values()), set()) - set(data.keys())
1024 data.update(dict([(item, set()) for item in extra_items_in_deps]))
1026 ordered = set(item for item,dep in list(data.items()) if not dep)
1029 for item in sorted(ordered):
1031 data = dict([(item, (dep - ordered)) for item,dep in list(data.items())
1032 if item not in ordered])
1033 assert not data, "A cyclic dependency exists amongst %r" % data
1035 def sort_dependencies(messages):
1036 '''Sort a list of Messages based on dependencies.'''
1038 message_by_name = {}
1039 for message in messages:
1040 dependencies[str(message.name)] = set(message.get_dependencies())
1041 message_by_name[str(message.name)] = message
1043 for msgname in toposort2(dependencies):
1044 if msgname in message_by_name:
1045 yield message_by_name[msgname]
1047 def make_identifier(headername):
1048 '''Make #ifndef identifier that contains uppercase A-Z and digits 0-9'''
1050 for c in headername.upper():
1058 def __init__(self, fdesc, file_options):
1059 '''Takes a FileDescriptorProto and parses it.'''
1061 self.file_options = file_options
1062 self.dependencies = {}
1065 # Some of types used in this file probably come from the file itself.
1066 # Thus it has implicit dependency on itself.
1067 self.add_dependency(self)
1072 self.extensions = []
1074 if self.fdesc.package:
1075 base_name = Names(self.fdesc.package.split('.'))
1079 for enum in self.fdesc.enum_type:
1080 enum_options = get_nanopb_suboptions(enum, self.file_options, base_name + enum.name)
1081 self.enums.append(Enum(base_name, enum, enum_options))
1083 for names, message in iterate_messages(self.fdesc, base_name):
1084 message_options = get_nanopb_suboptions(message, self.file_options, names)
1086 if message_options.skip_message:
1089 self.messages.append(Message(names, message, message_options))
1090 for enum in message.enum_type:
1091 enum_options = get_nanopb_suboptions(enum, message_options, names + enum.name)
1092 self.enums.append(Enum(names, enum, enum_options))
1094 for names, extension in iterate_extensions(self.fdesc, base_name):
1095 field_options = get_nanopb_suboptions(extension, self.file_options, names + extension.name)
1096 if field_options.type != nanopb_pb2.FT_IGNORE:
1097 self.extensions.append(ExtensionField(names, extension, field_options))
1099 def add_dependency(self, other):
1100 for enum in other.enums:
1101 self.dependencies[str(enum.names)] = enum
1103 for msg in other.messages:
1104 self.dependencies[str(msg.name)] = msg
1106 # Fix field default values where enum short names are used.
1107 for enum in other.enums:
1108 if not enum.options.long_names:
1109 for message in self.messages:
1110 for field in message.fields:
1111 if field.default in enum.value_longnames:
1112 idx = enum.value_longnames.index(field.default)
1113 field.default = enum.values[idx][0]
1115 # Fix field data types where enums have negative values.
1116 for enum in other.enums:
1117 if not enum.has_negative():
1118 for message in self.messages:
1119 for field in message.fields:
1120 if field.pbtype == 'ENUM' and field.ctype == enum.names:
1121 field.pbtype = 'UENUM'
1123 def generate_header(self, includes, headername, options):
1124 '''Generate content for a header file.
1125 Generates strings, which should be concatenated and stored to file.
1128 yield '/* Automatically generated nanopb header */\n'
1129 if options.notimestamp:
1130 yield '/* Generated by %s */\n\n' % (nanopb_version)
1132 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
1134 if self.fdesc.package:
1135 symbol = make_identifier(self.fdesc.package + '_' + headername)
1137 symbol = make_identifier(headername)
1138 yield '#ifndef PB_%s_INCLUDED\n' % symbol
1139 yield '#define PB_%s_INCLUDED\n' % symbol
1141 yield options.libformat % ('pb.h')
1143 # no %s specified - use whatever was passed in as options.libformat
1144 yield options.libformat
1147 for incfile in includes:
1148 noext = os.path.splitext(incfile)[0]
1149 yield options.genformat % (noext + options.extension + '.h')
1152 yield '/* @@protoc_insertion_point(includes) */\n'
1154 yield '#if PB_PROTO_HEADER_VERSION != 30\n'
1155 yield '#error Regenerate this file with the current version of nanopb generator.\n'
1159 yield '#ifdef __cplusplus\n'
1160 yield 'extern "C" {\n'
1164 yield '/* Enum definitions */\n'
1165 for enum in self.enums:
1166 yield str(enum) + '\n\n'
1169 yield '/* Struct definitions */\n'
1170 for msg in sort_dependencies(self.messages):
1172 yield str(msg) + '\n\n'
1175 yield '/* Extensions */\n'
1176 for extension in self.extensions:
1177 yield extension.extension_decl()
1181 yield '/* Default values for struct fields */\n'
1182 for msg in self.messages:
1183 yield msg.default_decl(True)
1186 yield '/* Initializer values for message structs */\n'
1187 for msg in self.messages:
1188 identifier = '%s_init_default' % msg.name
1189 yield '#define %-40s %s\n' % (identifier, msg.get_initializer(False))
1190 for msg in self.messages:
1191 identifier = '%s_init_zero' % msg.name
1192 yield '#define %-40s %s\n' % (identifier, msg.get_initializer(True))
1195 yield '/* Field tags (for use in manual encoding/decoding) */\n'
1196 for msg in sort_dependencies(self.messages):
1197 for field in msg.fields:
1199 for extension in self.extensions:
1200 yield extension.tags()
1203 yield '/* Struct field encoding specification for nanopb */\n'
1204 for msg in self.messages:
1205 yield msg.fields_declaration() + '\n'
1208 yield '/* Maximum encoded size of messages (where known) */\n'
1209 for msg in self.messages:
1210 msize = msg.encoded_size(self.dependencies)
1211 identifier = '%s_size' % msg.name
1212 if msize is not None:
1213 yield '#define %-40s %s\n' % (identifier, msize)
1215 yield '/* %s depends on runtime parameters */\n' % identifier
1218 yield '/* Message IDs (where set with "msgid" option) */\n'
1220 yield '#ifdef PB_MSGID\n'
1221 for msg in self.messages:
1222 if hasattr(msg,'msgid'):
1223 yield '#define PB_MSG_%d %s\n' % (msg.msgid, msg.name)
1226 symbol = make_identifier(headername.split('.')[0])
1227 yield '#define %s_MESSAGES \\\n' % symbol
1229 for msg in self.messages:
1231 msize = msg.encoded_size(self.dependencies)
1232 if msize is not None:
1234 if hasattr(msg,'msgid'):
1235 yield '\tPB_MSG(%d,%s,%s) \\\n' % (msg.msgid, m, msg.name)
1238 for msg in self.messages:
1239 if hasattr(msg,'msgid'):
1240 yield '#define %s_msgid %d\n' % (msg.name, msg.msgid)
1245 yield '#ifdef __cplusplus\n'
1246 yield '} /* extern "C" */\n'
1250 yield '/* @@protoc_insertion_point(eof) */\n'
1253 def generate_source(self, headername, options):
1254 '''Generate content for a source file.'''
1256 yield '/* Automatically generated nanopb constant definitions */\n'
1257 if options.notimestamp:
1258 yield '/* Generated by %s */\n\n' % (nanopb_version)
1260 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
1261 yield options.genformat % (headername)
1263 yield '/* @@protoc_insertion_point(includes) */\n'
1265 yield '#if PB_PROTO_HEADER_VERSION != 30\n'
1266 yield '#error Regenerate this file with the current version of nanopb generator.\n'
1270 for msg in self.messages:
1271 yield msg.default_decl(False)
1275 for msg in self.messages:
1276 yield msg.fields_definition() + '\n\n'
1278 for ext in self.extensions:
1279 yield ext.extension_def() + '\n'
1281 for enum in self.enums:
1282 yield enum.enum_to_string_definition() + '\n'
1284 # Add checks for numeric limits
1286 largest_msg = max(self.messages, key = lambda m: m.count_required_fields())
1287 largest_count = largest_msg.count_required_fields()
1288 if largest_count > 64:
1289 yield '\n/* Check that missing required fields will be properly detected */\n'
1290 yield '#if PB_MAX_REQUIRED_FIELDS < %d\n' % largest_count
1291 yield '#error Properly detecting missing required fields in %s requires \\\n' % largest_msg.name
1292 yield ' setting PB_MAX_REQUIRED_FIELDS to %d or more.\n' % largest_count
1295 max_field = FieldMaxSize()
1296 checks_msgnames = []
1297 for msg in self.messages:
1298 checks_msgnames.append(msg.name)
1299 for field in msg.fields:
1300 max_field.extend(field.largest_field_value())
1302 worst = max_field.worst
1303 worst_field = max_field.worst_field
1304 checks = max_field.checks
1306 if worst > 255 or checks:
1307 yield '\n/* Check that field information fits in pb_field_t */\n'
1309 if worst > 65535 or checks:
1310 yield '#if !defined(PB_FIELD_32BIT)\n'
1312 yield '#error Field descriptor for %s is too large. Define PB_FIELD_32BIT to fix this.\n' % worst_field
1314 assertion = ' && '.join(str(c) + ' < 65536' for c in checks)
1315 msgs = '_'.join(str(n) for n in checks_msgnames)
1316 yield '/* If you get an error here, it means that you need to define PB_FIELD_32BIT\n'
1317 yield ' * compile-time option. You can do that in pb.h or on compiler command line.\n'
1319 yield ' * The reason you need to do this is that some of your messages contain tag\n'
1320 yield ' * numbers or field sizes that are larger than what can fit in 8 or 16 bit\n'
1321 yield ' * field descriptors.\n'
1323 yield 'PB_STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
1327 yield '#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT)\n'
1329 yield '#error Field descriptor for %s is too large. Define PB_FIELD_16BIT to fix this.\n' % worst_field
1331 assertion = ' && '.join(str(c) + ' < 256' for c in checks)
1332 msgs = '_'.join(str(n) for n in checks_msgnames)
1333 yield '/* If you get an error here, it means that you need to define PB_FIELD_16BIT\n'
1334 yield ' * compile-time option. You can do that in pb.h or on compiler command line.\n'
1336 yield ' * The reason you need to do this is that some of your messages contain tag\n'
1337 yield ' * numbers or field sizes that are larger than what can fit in the default\n'
1338 yield ' * 8 bit descriptors.\n'
1340 yield 'PB_STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
1343 # Add check for sizeof(double)
1345 for msg in self.messages:
1346 for field in msg.fields:
1347 if field.ctype == 'double':
1352 yield '/* On some platforms (such as AVR), double is really float.\n'
1353 yield ' * These are not directly supported by nanopb, but see example_avr_double.\n'
1354 yield ' * To get rid of this error, remove any double fields from your .proto.\n'
1356 yield 'PB_STATIC_ASSERT(sizeof(double) == 8, DOUBLE_MUST_BE_8_BYTES)\n'
1359 yield '/* @@protoc_insertion_point(eof) */\n'
1361 # ---------------------------------------------------------------------------
1362 # Options parsing for the .proto files
1363 # ---------------------------------------------------------------------------
1365 from fnmatch import fnmatch
1367 def read_options_file(infile):
1368 '''Parse a separate options file to list:
1369 [(namemask, options), ...]
1372 data = infile.read()
1373 data = re.sub('/\*.*?\*/', '', data, flags = re.MULTILINE)
1374 data = re.sub('//.*?$', '', data, flags = re.MULTILINE)
1375 data = re.sub('#.*?$', '', data, flags = re.MULTILINE)
1376 for i, line in enumerate(data.split('\n')):
1381 parts = line.split(None, 1)
1384 sys.stderr.write("%s:%d: " % (infile.name, i + 1) +
1385 "Option lines should have space between field name and options. " +
1386 "Skipping line: '%s'\n" % line)
1389 opts = nanopb_pb2.NanoPBOptions()
1392 text_format.Merge(parts[1], opts)
1393 except Exception as e:
1394 sys.stderr.write("%s:%d: " % (infile.name, i + 1) +
1395 "Unparseable option line: '%s'. " % line +
1396 "Error: %s\n" % str(e))
1398 results.append((parts[0], opts))
1403 '''Ugly global variables, should find a good way to pass these.'''
1404 verbose_options = False
1405 separate_options = []
1406 matched_namemasks = set()
1408 def get_nanopb_suboptions(subdesc, options, name):
1409 '''Get copy of options, and merge information from subdesc.'''
1410 new_options = nanopb_pb2.NanoPBOptions()
1411 new_options.CopyFrom(options)
1413 if hasattr(subdesc, 'syntax') and subdesc.syntax == "proto3":
1414 new_options.proto3 = True
1416 # Handle options defined in a separate file
1417 dotname = '.'.join(name.parts)
1418 for namemask, options in Globals.separate_options:
1419 if fnmatch(dotname, namemask):
1420 Globals.matched_namemasks.add(namemask)
1421 new_options.MergeFrom(options)
1423 # Handle options defined in .proto
1424 if isinstance(subdesc.options, descriptor.FieldOptions):
1425 ext_type = nanopb_pb2.nanopb
1426 elif isinstance(subdesc.options, descriptor.FileOptions):
1427 ext_type = nanopb_pb2.nanopb_fileopt
1428 elif isinstance(subdesc.options, descriptor.MessageOptions):
1429 ext_type = nanopb_pb2.nanopb_msgopt
1430 elif isinstance(subdesc.options, descriptor.EnumOptions):
1431 ext_type = nanopb_pb2.nanopb_enumopt
1433 raise Exception("Unknown options type")
1435 if subdesc.options.HasExtension(ext_type):
1436 ext = subdesc.options.Extensions[ext_type]
1437 new_options.MergeFrom(ext)
1439 if Globals.verbose_options:
1440 sys.stderr.write("Options for " + dotname + ": ")
1441 sys.stderr.write(text_format.MessageToString(new_options) + "\n")
1446 # ---------------------------------------------------------------------------
1447 # Command line interface
1448 # ---------------------------------------------------------------------------
1452 from optparse import OptionParser
1454 optparser = OptionParser(
1455 usage = "Usage: nanopb_generator.py [options] file.pb ...",
1456 epilog = "Compile file.pb from file.proto by: 'protoc -ofile.pb file.proto'. " +
1457 "Output will be written to file.pb.h and file.pb.c.")
1458 optparser.add_option("-x", dest="exclude", metavar="FILE", action="append", default=[],
1459 help="Exclude file from generated #include list.")
1460 optparser.add_option("-e", "--extension", dest="extension", metavar="EXTENSION", default=".pb",
1461 help="Set extension to use instead of '.pb' for generated files. [default: %default]")
1462 optparser.add_option("-f", "--options-file", dest="options_file", metavar="FILE", default="%s.options",
1463 help="Set name of a separate generator options file.")
1464 optparser.add_option("-I", "--options-path", dest="options_path", metavar="DIR",
1465 action="append", default = [],
1466 help="Search for .options files additionally in this path")
1467 optparser.add_option("-D", "--output-dir", dest="output_dir",
1468 metavar="OUTPUTDIR", default=None,
1469 help="Output directory of .pb.h and .pb.c files")
1470 optparser.add_option("-Q", "--generated-include-format", dest="genformat",
1471 metavar="FORMAT", default='#include "%s"\n',
1472 help="Set format string to use for including other .pb.h files. [default: %default]")
1473 optparser.add_option("-L", "--library-include-format", dest="libformat",
1474 metavar="FORMAT", default='#include <%s>\n',
1475 help="Set format string to use for including the nanopb pb.h header. [default: %default]")
1476 optparser.add_option("-T", "--no-timestamp", dest="notimestamp", action="store_true", default=False,
1477 help="Don't add timestamp to .pb.h and .pb.c preambles")
1478 optparser.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False,
1479 help="Don't print anything except errors.")
1480 optparser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
1481 help="Print more information.")
1482 optparser.add_option("-s", dest="settings", metavar="OPTION:VALUE", action="append", default=[],
1483 help="Set generator option (max_size, max_count etc.).")
1485 def parse_file(filename, fdesc, options):
1486 '''Parse a single file. Returns a ProtoFile instance.'''
1487 toplevel_options = nanopb_pb2.NanoPBOptions()
1488 for s in options.settings:
1489 text_format.Merge(s, toplevel_options)
1492 data = open(filename, 'rb').read()
1493 fdesc = descriptor.FileDescriptorSet.FromString(data).file[0]
1495 # Check if there is a separate .options file
1498 optfilename = options.options_file % os.path.splitext(filename)[0]
1500 # No %s specified, use the filename as-is
1501 optfilename = options.options_file
1504 paths = ['.'] + options.options_path
1506 if os.path.isfile(os.path.join(p, optfilename)):
1507 optfilename = os.path.join(p, optfilename)
1509 sys.stderr.write('Reading options from ' + optfilename + '\n')
1510 Globals.separate_options = read_options_file(open(optfilename, "rU"))
1513 # If we are given a full filename and it does not exist, give an error.
1514 # However, don't give error when we automatically look for .options file
1515 # with the same name as .proto.
1516 if options.verbose or had_abspath:
1517 sys.stderr.write('Options file not found: ' + optfilename + '\n')
1518 Globals.separate_options = []
1520 Globals.matched_namemasks = set()
1523 file_options = get_nanopb_suboptions(fdesc, toplevel_options, Names([filename]))
1524 f = ProtoFile(fdesc, file_options)
1525 f.optfilename = optfilename
1529 def process_file(filename, fdesc, options, other_files = {}):
1530 '''Process a single file.
1531 filename: The full path to the .proto or .pb source file, as string.
1532 fdesc: The loaded FileDescriptorSet, or None to read from the input file.
1533 options: Command line options as they come from OptionsParser.
1536 {'headername': Name of header file,
1537 'headerdata': Data for the .h header file,
1538 'sourcename': Name of the source code file,
1539 'sourcedata': Data for the .c source code file
1542 f = parse_file(filename, fdesc, options)
1544 # Provide dependencies if available
1545 for dep in f.fdesc.dependency:
1546 if dep in other_files:
1547 f.add_dependency(other_files[dep])
1549 # Decide the file names
1550 noext = os.path.splitext(filename)[0]
1551 headername = noext + options.extension + '.h'
1552 sourcename = noext + options.extension + '.c'
1553 headerbasename = os.path.basename(headername)
1555 # List of .proto files that should not be included in the C header file
1556 # even if they are mentioned in the source .proto.
1557 excludes = ['nanopb.proto', 'google/protobuf/descriptor.proto'] + options.exclude
1558 includes = [d for d in f.fdesc.dependency if d not in excludes]
1560 headerdata = ''.join(f.generate_header(includes, headerbasename, options))
1561 sourcedata = ''.join(f.generate_source(headerbasename, options))
1563 # Check if there were any lines in .options that did not match a member
1564 unmatched = [n for n,o in Globals.separate_options if n not in Globals.matched_namemasks]
1565 if unmatched and not options.quiet:
1566 sys.stderr.write("Following patterns in " + f.optfilename + " did not match any fields: "
1567 + ', '.join(unmatched) + "\n")
1568 if not Globals.verbose_options:
1569 sys.stderr.write("Use protoc --nanopb-out=-v:. to see a list of the field names.\n")
1571 return {'headername': headername, 'headerdata': headerdata,
1572 'sourcename': sourcename, 'sourcedata': sourcedata}
1575 '''Main function when invoked directly from the command line.'''
1577 options, filenames = optparser.parse_args()
1580 optparser.print_help()
1584 options.verbose = False
1586 if options.output_dir and not os.path.exists(options.output_dir):
1587 optparser.print_help()
1588 sys.stderr.write("\noutput_dir does not exist: %s\n" % options.output_dir)
1592 Globals.verbose_options = options.verbose
1593 for filename in filenames:
1594 results = process_file(filename, None, options)
1596 base_dir = options.output_dir or ''
1598 (os.path.join(base_dir, results['headername']), results['headerdata']),
1599 (os.path.join(base_dir, results['sourcename']), results['sourcedata']),
1602 if not options.quiet:
1603 paths = " and ".join([x[0] for x in to_write])
1604 sys.stderr.write("Writing to %s\n" % paths)
1606 for path, data in to_write:
1607 with open(path, 'w') as f:
1611 '''Main function when invoked as a protoc plugin.'''
1614 if sys.platform == "win32":
1616 # Set stdin and stdout to binary mode
1617 msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
1618 msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
1620 data = io.open(sys.stdin.fileno(), "rb").read()
1622 request = plugin_pb2.CodeGeneratorRequest.FromString(data)
1625 # Versions of Python prior to 2.7.3 do not support unicode
1626 # input to shlex.split(). Try to convert to str if possible.
1627 params = str(request.parameter)
1628 except UnicodeEncodeError:
1629 params = request.parameter
1632 args = shlex.split(params)
1633 options, dummy = optparser.parse_args(args)
1635 Globals.verbose_options = options.verbose
1637 response = plugin_pb2.CodeGeneratorResponse()
1639 # Google's protoc does not currently indicate the full path of proto files.
1640 # Instead always add the main file path to the search dirs, that works for
1643 options.options_path.append(os.path.dirname(request.file_to_generate[0]))
1645 # Process any include files first, in order to have them
1646 # available as dependencies
1648 for fdesc in request.proto_file:
1649 other_files[fdesc.name] = parse_file(fdesc.name, fdesc, options)
1651 for filename in request.file_to_generate:
1652 for fdesc in request.proto_file:
1653 if fdesc.name == filename:
1654 results = process_file(filename, fdesc, options, other_files)
1656 f = response.file.add()
1657 f.name = results['headername']
1658 f.content = results['headerdata']
1660 f = response.file.add()
1661 f.name = results['sourcename']
1662 f.content = results['sourcedata']
1664 io.open(sys.stdout.fileno(), "wb").write(response.SerializeToString())
1666 if __name__ == '__main__':
1667 # Check if we are running as a plugin under protoc
1668 if 'protoc-gen-' in sys.argv[0] or '--protoc-plugin' in sys.argv: