3 from __future__ import unicode_literals
5 '''Generate header file for nanopb from a ProtoBuf FileDescriptorSet.'''
6 nanopb_version = "nanopb-0.3.8-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 *** Failed to import the protocol definitions for generator. ***
39 *** You have to run 'make' in the nanopb/generator/proto folder. ***
40 ********************************************************************
44 # ---------------------------------------------------------------------------
45 # Generation of single fields
46 # ---------------------------------------------------------------------------
51 # Values are tuple (c type, pb type, encoded size, int_size_allowed)
52 FieldD = descriptor.FieldDescriptorProto
54 FieldD.TYPE_BOOL: ('bool', 'BOOL', 1, False),
55 FieldD.TYPE_DOUBLE: ('double', 'DOUBLE', 8, False),
56 FieldD.TYPE_FIXED32: ('uint32_t', 'FIXED32', 4, False),
57 FieldD.TYPE_FIXED64: ('uint64_t', 'FIXED64', 8, False),
58 FieldD.TYPE_FLOAT: ('float', 'FLOAT', 4, False),
59 FieldD.TYPE_INT32: ('int32_t', 'INT32', 10, True),
60 FieldD.TYPE_INT64: ('int64_t', 'INT64', 10, True),
61 FieldD.TYPE_SFIXED32: ('int32_t', 'SFIXED32', 4, False),
62 FieldD.TYPE_SFIXED64: ('int64_t', 'SFIXED64', 8, False),
63 FieldD.TYPE_SINT32: ('int32_t', 'SINT32', 5, True),
64 FieldD.TYPE_SINT64: ('int64_t', 'SINT64', 10, True),
65 FieldD.TYPE_UINT32: ('uint32_t', 'UINT32', 5, True),
66 FieldD.TYPE_UINT64: ('uint64_t', 'UINT64', 10, True)
69 # Integer size overrides (from .proto settings)
71 nanopb_pb2.IS_8: 'int8_t',
72 nanopb_pb2.IS_16: 'int16_t',
73 nanopb_pb2.IS_32: 'int32_t',
74 nanopb_pb2.IS_64: 'int64_t',
77 # String types (for python 2 / python 3 compatibility)
79 strtypes = (unicode, str)
84 '''Keeps a set of nested names and formats them to C identifier.'''
85 def __init__(self, parts = ()):
86 if isinstance(parts, Names):
88 self.parts = tuple(parts)
91 return '_'.join(self.parts)
93 def __add__(self, other):
94 if isinstance(other, strtypes):
95 return Names(self.parts + (other,))
96 elif isinstance(other, tuple):
97 return Names(self.parts + other)
99 raise ValueError("Name parts should be of type str")
101 def __eq__(self, other):
102 return isinstance(other, Names) and self.parts == other.parts
104 def names_from_type_name(type_name):
105 '''Parse Names() from FieldDescriptorProto type_name'''
106 if type_name[0] != '.':
107 raise NotImplementedError("Lookup of non-absolute type names is not supported")
108 return Names(type_name[1:].split('.'))
110 def varint_max_size(max_value):
111 '''Returns the maximum number of bytes a varint can take when encoded.'''
113 max_value = 2**64 - max_value
114 for i in range(1, 11):
115 if (max_value >> (i * 7)) == 0:
117 raise ValueError("Value too large for varint: " + str(max_value))
119 assert varint_max_size(-1) == 10
120 assert varint_max_size(0) == 1
121 assert varint_max_size(127) == 1
122 assert varint_max_size(128) == 2
125 '''Class used to represent the encoded size of a field or a message.
126 Consists of a combination of symbolic sizes and integer sizes.'''
127 def __init__(self, value = 0, symbols = []):
128 if isinstance(value, EncodedSize):
129 self.value = value.value
130 self.symbols = value.symbols
131 elif isinstance(value, strtypes + (Names,)):
132 self.symbols = [str(value)]
136 self.symbols = symbols
138 def __add__(self, other):
139 if isinstance(other, int):
140 return EncodedSize(self.value + other, self.symbols)
141 elif isinstance(other, strtypes + (Names,)):
142 return EncodedSize(self.value, self.symbols + [str(other)])
143 elif isinstance(other, EncodedSize):
144 return EncodedSize(self.value + other.value, self.symbols + other.symbols)
146 raise ValueError("Cannot add size: " + repr(other))
148 def __mul__(self, other):
149 if isinstance(other, int):
150 return EncodedSize(self.value * other, [str(other) + '*' + s for s in self.symbols])
152 raise ValueError("Cannot multiply size: " + repr(other))
156 return str(self.value)
158 return '(' + str(self.value) + ' + ' + ' + '.join(self.symbols) + ')'
160 def upperlimit(self):
167 def __init__(self, names, desc, enum_options):
168 '''desc is EnumDescriptorProto'''
170 self.options = enum_options
171 self.names = names + desc.name
173 if enum_options.long_names:
174 self.values = [(self.names + x.name, x.number) for x in desc.value]
176 self.values = [(names + x.name, x.number) for x in desc.value]
178 self.value_longnames = [self.names + x.name for x in desc.value]
179 self.packed = enum_options.packed_enum
181 def has_negative(self):
182 for n, v in self.values:
187 def encoded_size(self):
188 return max([varint_max_size(v) for n,v in self.values])
191 result = 'typedef enum _%s {\n' % self.names
192 result += ',\n'.join([" %s = %d" % x for x in self.values])
196 result += ' pb_packed'
198 result += ' %s;' % self.names
200 result += '\n#define _%s_MIN %s' % (self.names, self.values[0][0])
201 result += '\n#define _%s_MAX %s' % (self.names, self.values[-1][0])
202 result += '\n#define _%s_ARRAYSIZE ((%s)(%s+1))' % (self.names, self.names, self.values[-1][0])
204 if not self.options.long_names:
205 # Define the long names always so that enum value references
206 # from other files work properly.
207 for i, x in enumerate(self.values):
208 result += '\n#define %s %s' % (self.value_longnames[i], x[0])
210 if self.options.enum_to_string:
211 result += '\nconst char *%s_name(%s v);\n' % (self.names, self.names)
215 def enum_to_string_definition(self):
216 if not self.options.enum_to_string:
219 result = 'const char *%s_name(%s v) {\n' % (self.names, self.names)
220 result += ' switch (v) {\n'
222 for ((enumname, _), strname) in zip(self.values, self.value_longnames):
223 # Strip off the leading type name from the string value.
224 strval = str(strname)[len(str(self.names)) + 1:]
225 result += ' case %s: return "%s";\n' % (enumname, strval)
228 result += ' return "unknown";\n'
234 def __init__(self, worst = 0, checks = [], field_name = 'undefined'):
235 if isinstance(worst, list):
236 self.worst = max(i for i in worst if i is not None)
240 self.worst_field = field_name
241 self.checks = list(checks)
243 def extend(self, extend, field_name = None):
244 self.worst = max(self.worst, extend.worst)
246 if self.worst == extend.worst:
247 self.worst_field = extend.worst_field
249 self.checks.extend(extend.checks)
252 def __init__(self, struct_name, desc, field_options):
253 '''desc is FieldDescriptorProto'''
254 self.tag = desc.number
255 self.struct_name = struct_name
256 self.union_name = None
257 self.name = desc.name
260 self.max_count = None
265 if field_options.type == nanopb_pb2.FT_INLINE:
266 # Before nanopb-0.3.8, fixed length bytes arrays were specified
267 # by setting type to FT_INLINE. But to handle pointer typed fields,
268 # it makes sense to have it as a separate option.
269 field_options.type = nanopb_pb2.FT_STATIC
270 field_options.fixed_length = True
272 # Parse field options
273 if field_options.HasField("max_size"):
274 self.max_size = field_options.max_size
276 if desc.type == FieldD.TYPE_STRING and field_options.HasField("max_length"):
277 # max_length overrides max_size for strings
278 self.max_size = field_options.max_length + 1
280 if field_options.HasField("max_count"):
281 self.max_count = field_options.max_count
283 if desc.HasField('default_value'):
284 self.default = desc.default_value
286 # Check field rules, i.e. required/optional/repeated.
288 if desc.label == FieldD.LABEL_REPEATED:
289 self.rules = 'REPEATED'
290 if self.max_count is None:
291 can_be_static = False
293 self.array_decl = '[%d]' % self.max_count
294 elif field_options.proto3:
295 self.rules = 'SINGULAR'
296 elif desc.label == FieldD.LABEL_REQUIRED:
297 self.rules = 'REQUIRED'
298 elif desc.label == FieldD.LABEL_OPTIONAL:
299 self.rules = 'OPTIONAL'
301 raise NotImplementedError(desc.label)
303 # Check if the field can be implemented with static allocation
304 # i.e. whether the data size is known.
305 if desc.type == FieldD.TYPE_STRING and self.max_size is None:
306 can_be_static = False
308 if desc.type == FieldD.TYPE_BYTES and self.max_size is None:
309 can_be_static = False
311 # Decide how the field data will be allocated
312 if field_options.type == nanopb_pb2.FT_DEFAULT:
314 field_options.type = nanopb_pb2.FT_STATIC
316 field_options.type = nanopb_pb2.FT_CALLBACK
318 if field_options.type == nanopb_pb2.FT_STATIC and not can_be_static:
319 raise Exception("Field %s is defined as static, but max_size or "
320 "max_count is not given." % self.name)
322 if field_options.type == nanopb_pb2.FT_STATIC:
323 self.allocation = 'STATIC'
324 elif field_options.type == nanopb_pb2.FT_POINTER:
325 self.allocation = 'POINTER'
326 elif field_options.type == nanopb_pb2.FT_CALLBACK:
327 self.allocation = 'CALLBACK'
329 raise NotImplementedError(field_options.type)
331 # Decide the C data type to use in the struct.
332 if desc.type in datatypes:
333 self.ctype, self.pbtype, self.enc_size, isa = datatypes[desc.type]
335 # Override the field size if user wants to use smaller integers
336 if isa and field_options.int_size != nanopb_pb2.IS_DEFAULT:
337 self.ctype = intsizes[field_options.int_size]
338 if desc.type == FieldD.TYPE_UINT32 or desc.type == FieldD.TYPE_UINT64:
339 self.ctype = 'u' + self.ctype;
340 elif desc.type == FieldD.TYPE_ENUM:
342 self.ctype = names_from_type_name(desc.type_name)
343 if self.default is not None:
344 self.default = self.ctype + self.default
345 self.enc_size = None # Needs to be filled in when enum values are known
346 elif desc.type == FieldD.TYPE_STRING:
347 self.pbtype = 'STRING'
349 if self.allocation == 'STATIC':
351 self.array_decl += '[%d]' % self.max_size
352 self.enc_size = varint_max_size(self.max_size) + self.max_size
353 elif desc.type == FieldD.TYPE_BYTES:
354 if field_options.fixed_length:
355 self.pbtype = 'FIXED_LENGTH_BYTES'
356 self.enc_size = varint_max_size(self.max_size) + self.max_size
357 self.ctype = 'pb_byte_t'
358 self.array_decl += '[%d]' % self.max_size
360 self.pbtype = 'BYTES'
361 self.ctype = 'pb_bytes_array_t'
362 if self.allocation == 'STATIC':
363 self.ctype = self.struct_name + self.name + 't'
364 self.enc_size = varint_max_size(self.max_size) + self.max_size
365 elif desc.type == FieldD.TYPE_MESSAGE:
366 self.pbtype = 'MESSAGE'
367 self.ctype = self.submsgname = names_from_type_name(desc.type_name)
368 self.enc_size = None # Needs to be filled in after the message type is available
370 raise NotImplementedError(desc.type)
372 def __lt__(self, other):
373 return self.tag < other.tag
377 if self.allocation == 'POINTER':
378 if self.rules == 'REPEATED':
379 result += ' pb_size_t ' + self.name + '_count;\n'
381 if self.pbtype == 'MESSAGE':
382 # Use struct definition, so recursive submessages are possible
383 result += ' struct _%s *%s;' % (self.ctype, self.name)
384 elif self.pbtype == 'FIXED_LENGTH_BYTES':
385 # Pointer to fixed size array
386 result += ' %s (*%s)%s;' % (self.ctype, self.name, self.array_decl)
387 elif self.rules == 'REPEATED' and self.pbtype in ['STRING', 'BYTES']:
388 # String/bytes arrays need to be defined as pointers to pointers
389 result += ' %s **%s;' % (self.ctype, self.name)
391 result += ' %s *%s;' % (self.ctype, self.name)
392 elif self.allocation == 'CALLBACK':
393 result += ' pb_callback_t %s;' % self.name
395 if self.rules == 'OPTIONAL' and self.allocation == 'STATIC':
396 result += ' bool has_' + self.name + ';\n'
397 elif self.rules == 'REPEATED' and self.allocation == 'STATIC':
398 result += ' pb_size_t ' + self.name + '_count;\n'
399 result += ' %s %s%s;' % (self.ctype, self.name, self.array_decl)
403 '''Return definitions for any special types this field might need.'''
404 if self.pbtype == 'BYTES' and self.allocation == 'STATIC':
405 result = 'typedef PB_BYTES_ARRAY_T(%d) %s;\n' % (self.max_size, self.ctype)
410 def get_dependencies(self):
411 '''Get list of type names used by this field.'''
412 if self.allocation == 'STATIC':
413 return [str(self.ctype)]
417 def get_initializer(self, null_init, inner_init_only = False):
418 '''Return literal expression for this field's default value.
419 null_init: If True, initialize to a 0 value instead of default from .proto
420 inner_init_only: If True, exclude initialization for any count/has fields
424 if self.pbtype == 'MESSAGE':
426 inner_init = '%s_init_zero' % self.ctype
428 inner_init = '%s_init_default' % self.ctype
429 elif self.default is None or null_init:
430 if self.pbtype == 'STRING':
432 elif self.pbtype == 'BYTES':
433 inner_init = '{0, {0}}'
434 elif self.pbtype == 'FIXED_LENGTH_BYTES':
436 elif self.pbtype in ('ENUM', 'UENUM'):
437 inner_init = '(%s)0' % self.ctype
441 if self.pbtype == 'STRING':
442 inner_init = self.default.replace('"', '\\"')
443 inner_init = '"' + inner_init + '"'
444 elif self.pbtype == 'BYTES':
445 data = ['0x%02x' % ord(c) for c in self.default]
447 inner_init = '{0, {0}}'
449 inner_init = '{%d, {%s}}' % (len(data), ','.join(data))
450 elif self.pbtype == 'FIXED_LENGTH_BYTES':
451 data = ['0x%02x' % ord(c) for c in self.default]
455 inner_init = '{%s}' % ','.join(data)
456 elif self.pbtype in ['FIXED32', 'UINT32']:
457 inner_init = str(self.default) + 'u'
458 elif self.pbtype in ['FIXED64', 'UINT64']:
459 inner_init = str(self.default) + 'ull'
460 elif self.pbtype in ['SFIXED64', 'INT64']:
461 inner_init = str(self.default) + 'll'
463 inner_init = str(self.default)
469 if self.allocation == 'STATIC':
470 if self.rules == 'REPEATED':
472 outer_init += ', '.join([inner_init] * self.max_count)
474 elif self.rules == 'OPTIONAL':
475 outer_init = 'false, ' + inner_init
477 outer_init = inner_init
478 elif self.allocation == 'POINTER':
479 if self.rules == 'REPEATED':
480 outer_init = '0, NULL'
483 elif self.allocation == 'CALLBACK':
484 if self.pbtype == 'EXTENSION':
487 outer_init = '{{NULL}, NULL}'
491 def default_decl(self, declaration_only = False):
492 '''Return definition for this field's default value.'''
493 if self.default is None:
497 default = self.get_initializer(False, True)
500 if self.pbtype == 'STRING':
501 if self.allocation != 'STATIC':
502 return None # Not implemented
503 array_decl = '[%d]' % self.max_size
504 elif self.pbtype == 'BYTES':
505 if self.allocation != 'STATIC':
506 return None # Not implemented
507 elif self.pbtype == 'FIXED_LENGTH_BYTES':
508 if self.allocation != 'STATIC':
509 return None # Not implemented
510 array_decl = '[%d]' % self.max_size
513 return 'extern const %s %s_default%s;' % (ctype, self.struct_name + self.name, array_decl)
515 return 'const %s %s_default%s = %s;' % (ctype, self.struct_name + self.name, array_decl, default)
518 '''Return the #define for the tag number of this field.'''
519 identifier = '%s_%s_tag' % (self.struct_name, self.name)
520 return '#define %-40s %d\n' % (identifier, self.tag)
522 def pb_field_t(self, prev_field_name, union_index = None):
523 '''Return the pb_field_t initializer to use in the constant array.
524 prev_field_name is the name of the previous field or None. For OneOf
525 unions, union_index is the index of this field inside the OneOf.
528 if self.rules == 'ONEOF':
530 result = ' PB_ANONYMOUS_ONEOF_FIELD(%s, ' % self.union_name
532 result = ' PB_ONEOF_FIELD(%s, ' % self.union_name
534 result = ' PB_FIELD('
536 result += '%3d, ' % self.tag
537 result += '%-8s, ' % self.pbtype
538 result += '%s, ' % self.rules
539 result += '%-8s, ' % self.allocation
541 if union_index is not None and union_index > 0:
543 elif prev_field_name is None:
548 result += '%s, ' % self.struct_name
549 result += '%s, ' % self.name
550 result += '%s, ' % (prev_field_name or self.name)
552 if self.pbtype == 'MESSAGE':
553 result += '&%s_fields)' % self.submsgname
554 elif self.default is None:
556 elif self.pbtype in ['BYTES', 'STRING', 'FIXED_LENGTH_BYTES'] and self.allocation != 'STATIC':
557 result += '0)' # Arbitrary size default values not implemented
558 elif self.rules == 'OPTEXT':
559 result += '0)' # Default value for extensions is not implemented
561 result += '&%s_default)' % (self.struct_name + self.name)
565 def get_last_field_name(self):
568 def largest_field_value(self):
569 '''Determine if this field needs 16bit or 32bit pb_field_t structure to compile properly.
570 Returns numeric value or a C-expression for assert.'''
572 if self.pbtype == 'MESSAGE' and self.allocation == 'STATIC':
573 if self.rules == 'REPEATED':
574 check.append('pb_membersize(%s, %s[0])' % (self.struct_name, self.name))
575 elif self.rules == 'ONEOF':
577 check.append('pb_membersize(%s, %s)' % (self.struct_name, self.name))
579 check.append('pb_membersize(%s, %s.%s)' % (self.struct_name, self.union_name, self.name))
581 check.append('pb_membersize(%s, %s)' % (self.struct_name, self.name))
582 elif self.pbtype == 'BYTES' and self.allocation == 'STATIC':
583 if self.max_size > 251:
584 check.append('pb_membersize(%s, %s)' % (self.struct_name, self.name))
586 return FieldMaxSize([self.tag, self.max_size, self.max_count],
588 ('%s.%s' % (self.struct_name, self.name)))
590 def encoded_size(self, dependencies):
591 '''Return the maximum size that this field can take when encoded,
592 including the field tag. If the size cannot be determined, returns
595 if self.allocation != 'STATIC':
598 if self.pbtype == 'MESSAGE':
600 if str(self.submsgname) in dependencies:
601 submsg = dependencies[str(self.submsgname)]
602 encsize = submsg.encoded_size(dependencies)
603 if encsize is not None:
604 # Include submessage length prefix
605 encsize += varint_max_size(encsize.upperlimit())
608 # Submessage or its size cannot be found.
609 # This can occur if submessage is defined in different
610 # file, and it or its .options could not be found.
611 # Instead of direct numeric value, reference the size that
612 # has been #defined in the other file.
613 encsize = EncodedSize(self.submsgname + 'size')
615 # We will have to make a conservative assumption on the length
616 # prefix size, though.
619 elif self.pbtype in ['ENUM', 'UENUM']:
620 if str(self.ctype) in dependencies:
621 enumtype = dependencies[str(self.ctype)]
622 encsize = enumtype.encoded_size()
624 # Conservative assumption
627 elif self.enc_size is None:
628 raise RuntimeError("Could not determine encoded size for %s.%s"
629 % (self.struct_name, self.name))
631 encsize = EncodedSize(self.enc_size)
633 encsize += varint_max_size(self.tag << 3) # Tag + wire type
635 if self.rules == 'REPEATED':
636 # Decoders must be always able to handle unpacked arrays.
637 # Therefore we have to reserve space for it, even though
638 # we emit packed arrays ourselves.
639 encsize *= self.max_count
644 class ExtensionRange(Field):
645 def __init__(self, struct_name, range_start, field_options):
646 '''Implements a special pb_extension_t* field in an extensible message
647 structure. The range_start signifies the index at which the extensions
648 start. Not necessarily all tags above this are extensions, it is merely
649 a speed optimization.
651 self.tag = range_start
652 self.struct_name = struct_name
653 self.name = 'extensions'
654 self.pbtype = 'EXTENSION'
655 self.rules = 'OPTIONAL'
656 self.allocation = 'CALLBACK'
657 self.ctype = 'pb_extension_t'
664 return ' pb_extension_t *extensions;'
672 def encoded_size(self, dependencies):
673 # We exclude extensions from the count, because they cannot be known
674 # until runtime. Other option would be to return None here, but this
675 # way the value remains useful if extensions are not used.
676 return EncodedSize(0)
678 class ExtensionField(Field):
679 def __init__(self, struct_name, desc, field_options):
680 self.fullname = struct_name + desc.name
681 self.extendee_name = names_from_type_name(desc.extendee)
682 Field.__init__(self, self.fullname + 'struct', desc, field_options)
684 if self.rules != 'OPTIONAL':
688 self.rules = 'OPTEXT'
691 '''Return the #define for the tag number of this field.'''
692 identifier = '%s_tag' % self.fullname
693 return '#define %-40s %d\n' % (identifier, self.tag)
695 def extension_decl(self):
696 '''Declaration of the extension type in the .pb.h file'''
698 msg = '/* Extension field %s was skipped because only "optional"\n' % self.fullname
699 msg +=' type of extension fields is currently supported. */\n'
702 return ('extern const pb_extension_type_t %s; /* field type: %s */\n' %
703 (self.fullname, str(self).strip()))
705 def extension_def(self):
706 '''Definition of the extension type in the .pb.c file'''
711 result = 'typedef struct {\n'
713 result += '\n} %s;\n\n' % self.struct_name
714 result += ('static const pb_field_t %s_field = \n %s;\n\n' %
715 (self.fullname, self.pb_field_t(None)))
716 result += 'const pb_extension_type_t %s = {\n' % self.fullname
719 result += ' &%s_field\n' % self.fullname
724 # ---------------------------------------------------------------------------
725 # Generation of oneofs (unions)
726 # ---------------------------------------------------------------------------
729 def __init__(self, struct_name, oneof_desc):
730 self.struct_name = struct_name
731 self.name = oneof_desc.name
733 self.pbtype = 'oneof'
735 self.allocation = 'ONEOF'
738 self.anonymous = False
740 def add_field(self, field):
741 if field.allocation == 'CALLBACK':
742 raise Exception("Callback fields inside of oneof are not supported"
743 + " (field %s)" % field.name)
745 field.union_name = self.name
746 field.rules = 'ONEOF'
747 field.anonymous = self.anonymous
748 self.fields.append(field)
749 self.fields.sort(key = lambda f: f.tag)
751 # Sort by the lowest tag number inside union
752 self.tag = min([f.tag for f in self.fields])
757 result += ' pb_size_t which_' + self.name + ";\n"
758 result += ' union {\n'
759 for f in self.fields:
760 result += ' ' + str(f).replace('\n', '\n ') + '\n'
764 result += ' } ' + self.name + ';'
768 return ''.join([f.types() for f in self.fields])
770 def get_dependencies(self):
772 for f in self.fields:
773 deps += f.get_dependencies()
776 def get_initializer(self, null_init):
777 return '0, {' + self.fields[0].get_initializer(null_init) + '}'
779 def default_decl(self, declaration_only = False):
783 return ''.join([f.tags() for f in self.fields])
785 def pb_field_t(self, prev_field_name):
787 for union_index, field in enumerate(self.fields):
788 parts.append(field.pb_field_t(prev_field_name, union_index))
789 return ',\n'.join(parts)
791 def get_last_field_name(self):
793 return self.fields[-1].name
795 return self.name + '.' + self.fields[-1].name
797 def largest_field_value(self):
798 largest = FieldMaxSize()
799 for f in self.fields:
800 largest.extend(f.largest_field_value())
803 def encoded_size(self, dependencies):
804 '''Returns the size of the largest oneof field.'''
805 largest = EncodedSize(0)
806 for f in self.fields:
807 size = EncodedSize(f.encoded_size(dependencies))
808 if size.value is None:
811 return None # Cannot resolve maximum of symbols
812 elif size.value > largest.value:
817 # ---------------------------------------------------------------------------
818 # Generation of messages (structures)
819 # ---------------------------------------------------------------------------
823 def __init__(self, names, desc, message_options):
829 if message_options.msgid:
830 self.msgid = message_options.msgid
832 if hasattr(desc, 'oneof_decl'):
833 for i, f in enumerate(desc.oneof_decl):
834 oneof_options = get_nanopb_suboptions(desc, message_options, self.name + f.name)
835 if oneof_options.no_unions:
836 no_unions.append(i) # No union, but add fields normally
837 elif oneof_options.type == nanopb_pb2.FT_IGNORE:
838 pass # No union and skip fields also
840 oneof = OneOf(self.name, f)
841 if oneof_options.anonymous_oneof:
842 oneof.anonymous = True
843 self.oneofs[i] = oneof
844 self.fields.append(oneof)
847 field_options = get_nanopb_suboptions(f, message_options, self.name + f.name)
848 if field_options.type == nanopb_pb2.FT_IGNORE:
851 field = Field(self.name, f, field_options)
852 if (hasattr(f, 'oneof_index') and
853 f.HasField('oneof_index') and
854 f.oneof_index not in no_unions):
855 if f.oneof_index in self.oneofs:
856 self.oneofs[f.oneof_index].add_field(field)
858 self.fields.append(field)
860 if len(desc.extension_range) > 0:
861 field_options = get_nanopb_suboptions(desc, message_options, self.name + 'extensions')
862 range_start = min([r.start for r in desc.extension_range])
863 if field_options.type != nanopb_pb2.FT_IGNORE:
864 self.fields.append(ExtensionRange(self.name, range_start, field_options))
866 self.packed = message_options.packed_struct
867 self.ordered_fields = self.fields[:]
868 self.ordered_fields.sort()
870 def get_dependencies(self):
871 '''Get list of type names that this structure refers to.'''
873 for f in self.fields:
874 deps += f.get_dependencies()
878 result = 'typedef struct _%s {\n' % self.name
880 if not self.ordered_fields:
881 # Empty structs are not allowed in C standard.
882 # Therefore add a dummy field if an empty message occurs.
883 result += ' char dummy_field;'
885 result += '\n'.join([str(f) for f in self.ordered_fields])
886 result += '\n/* @@protoc_insertion_point(struct:%s) */' % self.name
890 result += ' pb_packed'
892 result += ' %s;' % self.name
895 result = 'PB_PACKED_STRUCT_START\n' + result
896 result += '\nPB_PACKED_STRUCT_END'
901 return ''.join([f.types() for f in self.fields])
903 def get_initializer(self, null_init):
904 if not self.ordered_fields:
908 for field in self.ordered_fields:
909 parts.append(field.get_initializer(null_init))
910 return '{' + ', '.join(parts) + '}'
912 def default_decl(self, declaration_only = False):
914 for field in self.fields:
915 default = field.default_decl(declaration_only)
916 if default is not None:
917 result += default + '\n'
920 def count_required_fields(self):
921 '''Returns number of required fields inside this message'''
923 for f in self.fields:
924 if not isinstance(f, OneOf):
925 if f.rules == 'REQUIRED':
929 def count_all_fields(self):
931 for f in self.fields:
932 if isinstance(f, OneOf):
933 count += len(f.fields)
938 def fields_declaration(self):
939 result = 'extern const pb_field_t %s_fields[%d];' % (self.name, self.count_all_fields() + 1)
942 def fields_definition(self):
943 result = 'const pb_field_t %s_fields[%d] = {\n' % (self.name, self.count_all_fields() + 1)
946 for field in self.ordered_fields:
947 result += field.pb_field_t(prev)
949 prev = field.get_last_field_name()
951 result += ' PB_LAST_FIELD\n};'
954 def encoded_size(self, dependencies):
955 '''Return the maximum size that this message can take when encoded.
956 If the size cannot be determined, returns None.
958 size = EncodedSize(0)
959 for field in self.fields:
960 fsize = field.encoded_size(dependencies)
968 # ---------------------------------------------------------------------------
969 # Processing of entire .proto files
970 # ---------------------------------------------------------------------------
972 def iterate_messages(desc, names = Names()):
973 '''Recursively find all messages. For each, yield name, DescriptorProto.'''
974 if hasattr(desc, 'message_type'):
975 submsgs = desc.message_type
977 submsgs = desc.nested_type
979 for submsg in submsgs:
980 sub_names = names + submsg.name
981 yield sub_names, submsg
983 for x in iterate_messages(submsg, sub_names):
986 def iterate_extensions(desc, names = Names()):
987 '''Recursively find all extensions.
988 For each, yield name, FieldDescriptorProto.
990 for extension in desc.extension:
991 yield names, extension
993 for subname, subdesc in iterate_messages(desc, names):
994 for extension in subdesc.extension:
995 yield subname, extension
999 From http://code.activestate.com/recipes/577413-topological-sort/
1000 This function is under the MIT license.
1002 for k, v in list(data.items()):
1003 v.discard(k) # Ignore self dependencies
1004 extra_items_in_deps = reduce(set.union, list(data.values()), set()) - set(data.keys())
1005 data.update(dict([(item, set()) for item in extra_items_in_deps]))
1007 ordered = set(item for item,dep in list(data.items()) if not dep)
1010 for item in sorted(ordered):
1012 data = dict([(item, (dep - ordered)) for item,dep in list(data.items())
1013 if item not in ordered])
1014 assert not data, "A cyclic dependency exists amongst %r" % data
1016 def sort_dependencies(messages):
1017 '''Sort a list of Messages based on dependencies.'''
1019 message_by_name = {}
1020 for message in messages:
1021 dependencies[str(message.name)] = set(message.get_dependencies())
1022 message_by_name[str(message.name)] = message
1024 for msgname in toposort2(dependencies):
1025 if msgname in message_by_name:
1026 yield message_by_name[msgname]
1028 def make_identifier(headername):
1029 '''Make #ifndef identifier that contains uppercase A-Z and digits 0-9'''
1031 for c in headername.upper():
1039 def __init__(self, fdesc, file_options):
1040 '''Takes a FileDescriptorProto and parses it.'''
1042 self.file_options = file_options
1043 self.dependencies = {}
1046 # Some of types used in this file probably come from the file itself.
1047 # Thus it has implicit dependency on itself.
1048 self.add_dependency(self)
1053 self.extensions = []
1055 if self.fdesc.package:
1056 base_name = Names(self.fdesc.package.split('.'))
1060 for enum in self.fdesc.enum_type:
1061 enum_options = get_nanopb_suboptions(enum, self.file_options, base_name + enum.name)
1062 self.enums.append(Enum(base_name, enum, enum_options))
1064 for names, message in iterate_messages(self.fdesc, base_name):
1065 message_options = get_nanopb_suboptions(message, self.file_options, names)
1067 if message_options.skip_message:
1070 self.messages.append(Message(names, message, message_options))
1071 for enum in message.enum_type:
1072 enum_options = get_nanopb_suboptions(enum, message_options, names + enum.name)
1073 self.enums.append(Enum(names, enum, enum_options))
1075 for names, extension in iterate_extensions(self.fdesc, base_name):
1076 field_options = get_nanopb_suboptions(extension, self.file_options, names + extension.name)
1077 if field_options.type != nanopb_pb2.FT_IGNORE:
1078 self.extensions.append(ExtensionField(names, extension, field_options))
1080 def add_dependency(self, other):
1081 for enum in other.enums:
1082 self.dependencies[str(enum.names)] = enum
1084 for msg in other.messages:
1085 self.dependencies[str(msg.name)] = msg
1087 # Fix field default values where enum short names are used.
1088 for enum in other.enums:
1089 if not enum.options.long_names:
1090 for message in self.messages:
1091 for field in message.fields:
1092 if field.default in enum.value_longnames:
1093 idx = enum.value_longnames.index(field.default)
1094 field.default = enum.values[idx][0]
1096 # Fix field data types where enums have negative values.
1097 for enum in other.enums:
1098 if not enum.has_negative():
1099 for message in self.messages:
1100 for field in message.fields:
1101 if field.pbtype == 'ENUM' and field.ctype == enum.names:
1102 field.pbtype = 'UENUM'
1104 def generate_header(self, includes, headername, options):
1105 '''Generate content for a header file.
1106 Generates strings, which should be concatenated and stored to file.
1109 yield '/* Automatically generated nanopb header */\n'
1110 if options.notimestamp:
1111 yield '/* Generated by %s */\n\n' % (nanopb_version)
1113 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
1115 if self.fdesc.package:
1116 symbol = make_identifier(self.fdesc.package + '_' + headername)
1118 symbol = make_identifier(headername)
1119 yield '#ifndef PB_%s_INCLUDED\n' % symbol
1120 yield '#define PB_%s_INCLUDED\n' % symbol
1122 yield options.libformat % ('pb.h')
1124 # no %s specified - use whatever was passed in as options.libformat
1125 yield options.libformat
1128 for incfile in includes:
1129 noext = os.path.splitext(incfile)[0]
1130 yield options.genformat % (noext + options.extension + '.h')
1133 yield '/* @@protoc_insertion_point(includes) */\n'
1135 yield '#if PB_PROTO_HEADER_VERSION != 30\n'
1136 yield '#error Regenerate this file with the current version of nanopb generator.\n'
1140 yield '#ifdef __cplusplus\n'
1141 yield 'extern "C" {\n'
1145 yield '/* Enum definitions */\n'
1146 for enum in self.enums:
1147 yield str(enum) + '\n\n'
1150 yield '/* Struct definitions */\n'
1151 for msg in sort_dependencies(self.messages):
1153 yield str(msg) + '\n\n'
1156 yield '/* Extensions */\n'
1157 for extension in self.extensions:
1158 yield extension.extension_decl()
1162 yield '/* Default values for struct fields */\n'
1163 for msg in self.messages:
1164 yield msg.default_decl(True)
1167 yield '/* Initializer values for message structs */\n'
1168 for msg in self.messages:
1169 identifier = '%s_init_default' % msg.name
1170 yield '#define %-40s %s\n' % (identifier, msg.get_initializer(False))
1171 for msg in self.messages:
1172 identifier = '%s_init_zero' % msg.name
1173 yield '#define %-40s %s\n' % (identifier, msg.get_initializer(True))
1176 yield '/* Field tags (for use in manual encoding/decoding) */\n'
1177 for msg in sort_dependencies(self.messages):
1178 for field in msg.fields:
1180 for extension in self.extensions:
1181 yield extension.tags()
1184 yield '/* Struct field encoding specification for nanopb */\n'
1185 for msg in self.messages:
1186 yield msg.fields_declaration() + '\n'
1189 yield '/* Maximum encoded size of messages (where known) */\n'
1190 for msg in self.messages:
1191 msize = msg.encoded_size(self.dependencies)
1192 identifier = '%s_size' % msg.name
1193 if msize is not None:
1194 yield '#define %-40s %s\n' % (identifier, msize)
1196 yield '/* %s depends on runtime parameters */\n' % identifier
1199 yield '/* Message IDs (where set with "msgid" option) */\n'
1201 yield '#ifdef PB_MSGID\n'
1202 for msg in self.messages:
1203 if hasattr(msg,'msgid'):
1204 yield '#define PB_MSG_%d %s\n' % (msg.msgid, msg.name)
1207 symbol = make_identifier(headername.split('.')[0])
1208 yield '#define %s_MESSAGES \\\n' % symbol
1210 for msg in self.messages:
1212 msize = msg.encoded_size(self.dependencies)
1213 if msize is not None:
1215 if hasattr(msg,'msgid'):
1216 yield '\tPB_MSG(%d,%s,%s) \\\n' % (msg.msgid, m, msg.name)
1219 for msg in self.messages:
1220 if hasattr(msg,'msgid'):
1221 yield '#define %s_msgid %d\n' % (msg.name, msg.msgid)
1226 yield '#ifdef __cplusplus\n'
1227 yield '} /* extern "C" */\n'
1231 yield '/* @@protoc_insertion_point(eof) */\n'
1234 def generate_source(self, headername, options):
1235 '''Generate content for a source file.'''
1237 yield '/* Automatically generated nanopb constant definitions */\n'
1238 if options.notimestamp:
1239 yield '/* Generated by %s */\n\n' % (nanopb_version)
1241 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
1242 yield options.genformat % (headername)
1244 yield '/* @@protoc_insertion_point(includes) */\n'
1246 yield '#if PB_PROTO_HEADER_VERSION != 30\n'
1247 yield '#error Regenerate this file with the current version of nanopb generator.\n'
1251 for msg in self.messages:
1252 yield msg.default_decl(False)
1256 for msg in self.messages:
1257 yield msg.fields_definition() + '\n\n'
1259 for ext in self.extensions:
1260 yield ext.extension_def() + '\n'
1262 for enum in self.enums:
1263 yield enum.enum_to_string_definition() + '\n'
1265 # Add checks for numeric limits
1267 largest_msg = max(self.messages, key = lambda m: m.count_required_fields())
1268 largest_count = largest_msg.count_required_fields()
1269 if largest_count > 64:
1270 yield '\n/* Check that missing required fields will be properly detected */\n'
1271 yield '#if PB_MAX_REQUIRED_FIELDS < %d\n' % largest_count
1272 yield '#error Properly detecting missing required fields in %s requires \\\n' % largest_msg.name
1273 yield ' setting PB_MAX_REQUIRED_FIELDS to %d or more.\n' % largest_count
1276 max_field = FieldMaxSize()
1277 checks_msgnames = []
1278 for msg in self.messages:
1279 checks_msgnames.append(msg.name)
1280 for field in msg.fields:
1281 max_field.extend(field.largest_field_value())
1283 worst = max_field.worst
1284 worst_field = max_field.worst_field
1285 checks = max_field.checks
1287 if worst > 255 or checks:
1288 yield '\n/* Check that field information fits in pb_field_t */\n'
1290 if worst > 65535 or checks:
1291 yield '#if !defined(PB_FIELD_32BIT)\n'
1293 yield '#error Field descriptor for %s is too large. Define PB_FIELD_32BIT to fix this.\n' % worst_field
1295 assertion = ' && '.join(str(c) + ' < 65536' for c in checks)
1296 msgs = '_'.join(str(n) for n in checks_msgnames)
1297 yield '/* If you get an error here, it means that you need to define PB_FIELD_32BIT\n'
1298 yield ' * compile-time option. You can do that in pb.h or on compiler command line.\n'
1300 yield ' * The reason you need to do this is that some of your messages contain tag\n'
1301 yield ' * numbers or field sizes that are larger than what can fit in 8 or 16 bit\n'
1302 yield ' * field descriptors.\n'
1304 yield 'PB_STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
1308 yield '#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT)\n'
1310 yield '#error Field descriptor for %s is too large. Define PB_FIELD_16BIT to fix this.\n' % worst_field
1312 assertion = ' && '.join(str(c) + ' < 256' for c in checks)
1313 msgs = '_'.join(str(n) for n in checks_msgnames)
1314 yield '/* If you get an error here, it means that you need to define PB_FIELD_16BIT\n'
1315 yield ' * compile-time option. You can do that in pb.h or on compiler command line.\n'
1317 yield ' * The reason you need to do this is that some of your messages contain tag\n'
1318 yield ' * numbers or field sizes that are larger than what can fit in the default\n'
1319 yield ' * 8 bit descriptors.\n'
1321 yield 'PB_STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
1324 # Add check for sizeof(double)
1326 for msg in self.messages:
1327 for field in msg.fields:
1328 if field.ctype == 'double':
1333 yield '/* On some platforms (such as AVR), double is really float.\n'
1334 yield ' * These are not directly supported by nanopb, but see example_avr_double.\n'
1335 yield ' * To get rid of this error, remove any double fields from your .proto.\n'
1337 yield 'PB_STATIC_ASSERT(sizeof(double) == 8, DOUBLE_MUST_BE_8_BYTES)\n'
1340 yield '/* @@protoc_insertion_point(eof) */\n'
1342 # ---------------------------------------------------------------------------
1343 # Options parsing for the .proto files
1344 # ---------------------------------------------------------------------------
1346 from fnmatch import fnmatch
1348 def read_options_file(infile):
1349 '''Parse a separate options file to list:
1350 [(namemask, options), ...]
1353 data = infile.read()
1354 data = re.sub('/\*.*?\*/', '', data, flags = re.MULTILINE)
1355 data = re.sub('//.*?$', '', data, flags = re.MULTILINE)
1356 data = re.sub('#.*?$', '', data, flags = re.MULTILINE)
1357 for i, line in enumerate(data.split('\n')):
1362 parts = line.split(None, 1)
1365 sys.stderr.write("%s:%d: " % (infile.name, i + 1) +
1366 "Option lines should have space between field name and options. " +
1367 "Skipping line: '%s'\n" % line)
1370 opts = nanopb_pb2.NanoPBOptions()
1373 text_format.Merge(parts[1], opts)
1374 except Exception as e:
1375 sys.stderr.write("%s:%d: " % (infile.name, i + 1) +
1376 "Unparseable option line: '%s'. " % line +
1377 "Error: %s\n" % str(e))
1379 results.append((parts[0], opts))
1384 '''Ugly global variables, should find a good way to pass these.'''
1385 verbose_options = False
1386 separate_options = []
1387 matched_namemasks = set()
1389 def get_nanopb_suboptions(subdesc, options, name):
1390 '''Get copy of options, and merge information from subdesc.'''
1391 new_options = nanopb_pb2.NanoPBOptions()
1392 new_options.CopyFrom(options)
1394 if hasattr(subdesc, 'syntax') and subdesc.syntax == "proto3":
1395 new_options.proto3 = True
1397 # Handle options defined in a separate file
1398 dotname = '.'.join(name.parts)
1399 for namemask, options in Globals.separate_options:
1400 if fnmatch(dotname, namemask):
1401 Globals.matched_namemasks.add(namemask)
1402 new_options.MergeFrom(options)
1404 # Handle options defined in .proto
1405 if isinstance(subdesc.options, descriptor.FieldOptions):
1406 ext_type = nanopb_pb2.nanopb
1407 elif isinstance(subdesc.options, descriptor.FileOptions):
1408 ext_type = nanopb_pb2.nanopb_fileopt
1409 elif isinstance(subdesc.options, descriptor.MessageOptions):
1410 ext_type = nanopb_pb2.nanopb_msgopt
1411 elif isinstance(subdesc.options, descriptor.EnumOptions):
1412 ext_type = nanopb_pb2.nanopb_enumopt
1414 raise Exception("Unknown options type")
1416 if subdesc.options.HasExtension(ext_type):
1417 ext = subdesc.options.Extensions[ext_type]
1418 new_options.MergeFrom(ext)
1420 if Globals.verbose_options:
1421 sys.stderr.write("Options for " + dotname + ": ")
1422 sys.stderr.write(text_format.MessageToString(new_options) + "\n")
1427 # ---------------------------------------------------------------------------
1428 # Command line interface
1429 # ---------------------------------------------------------------------------
1433 from optparse import OptionParser
1435 optparser = OptionParser(
1436 usage = "Usage: nanopb_generator.py [options] file.pb ...",
1437 epilog = "Compile file.pb from file.proto by: 'protoc -ofile.pb file.proto'. " +
1438 "Output will be written to file.pb.h and file.pb.c.")
1439 optparser.add_option("-x", dest="exclude", metavar="FILE", action="append", default=[],
1440 help="Exclude file from generated #include list.")
1441 optparser.add_option("-e", "--extension", dest="extension", metavar="EXTENSION", default=".pb",
1442 help="Set extension to use instead of '.pb' for generated files. [default: %default]")
1443 optparser.add_option("-f", "--options-file", dest="options_file", metavar="FILE", default="%s.options",
1444 help="Set name of a separate generator options file.")
1445 optparser.add_option("-I", "--options-path", dest="options_path", metavar="DIR",
1446 action="append", default = [],
1447 help="Search for .options files additionally in this path")
1448 optparser.add_option("-D", "--output-dir", dest="output_dir",
1449 metavar="OUTPUTDIR", default=None,
1450 help="Output directory of .pb.h and .pb.c files")
1451 optparser.add_option("-Q", "--generated-include-format", dest="genformat",
1452 metavar="FORMAT", default='#include "%s"\n',
1453 help="Set format string to use for including other .pb.h files. [default: %default]")
1454 optparser.add_option("-L", "--library-include-format", dest="libformat",
1455 metavar="FORMAT", default='#include <%s>\n',
1456 help="Set format string to use for including the nanopb pb.h header. [default: %default]")
1457 optparser.add_option("-T", "--no-timestamp", dest="notimestamp", action="store_true", default=False,
1458 help="Don't add timestamp to .pb.h and .pb.c preambles")
1459 optparser.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False,
1460 help="Don't print anything except errors.")
1461 optparser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
1462 help="Print more information.")
1463 optparser.add_option("-s", dest="settings", metavar="OPTION:VALUE", action="append", default=[],
1464 help="Set generator option (max_size, max_count etc.).")
1466 def parse_file(filename, fdesc, options):
1467 '''Parse a single file. Returns a ProtoFile instance.'''
1468 toplevel_options = nanopb_pb2.NanoPBOptions()
1469 for s in options.settings:
1470 text_format.Merge(s, toplevel_options)
1473 data = open(filename, 'rb').read()
1474 fdesc = descriptor.FileDescriptorSet.FromString(data).file[0]
1476 # Check if there is a separate .options file
1479 optfilename = options.options_file % os.path.splitext(filename)[0]
1481 # No %s specified, use the filename as-is
1482 optfilename = options.options_file
1485 paths = ['.'] + options.options_path
1487 if os.path.isfile(os.path.join(p, optfilename)):
1488 optfilename = os.path.join(p, optfilename)
1490 sys.stderr.write('Reading options from ' + optfilename + '\n')
1491 Globals.separate_options = read_options_file(open(optfilename, "rU"))
1494 # If we are given a full filename and it does not exist, give an error.
1495 # However, don't give error when we automatically look for .options file
1496 # with the same name as .proto.
1497 if options.verbose or had_abspath:
1498 sys.stderr.write('Options file not found: ' + optfilename + '\n')
1499 Globals.separate_options = []
1501 Globals.matched_namemasks = set()
1504 file_options = get_nanopb_suboptions(fdesc, toplevel_options, Names([filename]))
1505 f = ProtoFile(fdesc, file_options)
1506 f.optfilename = optfilename
1510 def process_file(filename, fdesc, options, other_files = {}):
1511 '''Process a single file.
1512 filename: The full path to the .proto or .pb source file, as string.
1513 fdesc: The loaded FileDescriptorSet, or None to read from the input file.
1514 options: Command line options as they come from OptionsParser.
1517 {'headername': Name of header file,
1518 'headerdata': Data for the .h header file,
1519 'sourcename': Name of the source code file,
1520 'sourcedata': Data for the .c source code file
1523 f = parse_file(filename, fdesc, options)
1525 # Provide dependencies if available
1526 for dep in f.fdesc.dependency:
1527 if dep in other_files:
1528 f.add_dependency(other_files[dep])
1530 # Decide the file names
1531 noext = os.path.splitext(filename)[0]
1532 headername = noext + options.extension + '.h'
1533 sourcename = noext + options.extension + '.c'
1534 headerbasename = os.path.basename(headername)
1536 # List of .proto files that should not be included in the C header file
1537 # even if they are mentioned in the source .proto.
1538 excludes = ['nanopb.proto', 'google/protobuf/descriptor.proto'] + options.exclude
1539 includes = [d for d in f.fdesc.dependency if d not in excludes]
1541 headerdata = ''.join(f.generate_header(includes, headerbasename, options))
1542 sourcedata = ''.join(f.generate_source(headerbasename, options))
1544 # Check if there were any lines in .options that did not match a member
1545 unmatched = [n for n,o in Globals.separate_options if n not in Globals.matched_namemasks]
1546 if unmatched and not options.quiet:
1547 sys.stderr.write("Following patterns in " + f.optfilename + " did not match any fields: "
1548 + ', '.join(unmatched) + "\n")
1549 if not Globals.verbose_options:
1550 sys.stderr.write("Use protoc --nanopb-out=-v:. to see a list of the field names.\n")
1552 return {'headername': headername, 'headerdata': headerdata,
1553 'sourcename': sourcename, 'sourcedata': sourcedata}
1556 '''Main function when invoked directly from the command line.'''
1558 options, filenames = optparser.parse_args()
1561 optparser.print_help()
1565 options.verbose = False
1567 if options.output_dir and not os.path.exists(options.output_dir):
1568 optparser.print_help()
1569 sys.stderr.write("\noutput_dir does not exist: %s\n" % options.output_dir)
1573 Globals.verbose_options = options.verbose
1574 for filename in filenames:
1575 results = process_file(filename, None, options)
1577 base_dir = options.output_dir or ''
1579 (os.path.join(base_dir, results['headername']), results['headerdata']),
1580 (os.path.join(base_dir, results['sourcename']), results['sourcedata']),
1583 if not options.quiet:
1584 paths = " and ".join([x[0] for x in to_write])
1585 sys.stderr.write("Writing to %s\n" % paths)
1587 for path, data in to_write:
1588 with open(path, 'w') as f:
1592 '''Main function when invoked as a protoc plugin.'''
1595 if sys.platform == "win32":
1597 # Set stdin and stdout to binary mode
1598 msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
1599 msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
1601 data = io.open(sys.stdin.fileno(), "rb").read()
1603 request = plugin_pb2.CodeGeneratorRequest.FromString(data)
1606 # Versions of Python prior to 2.7.3 do not support unicode
1607 # input to shlex.split(). Try to convert to str if possible.
1608 params = str(request.parameter)
1609 except UnicodeEncodeError:
1610 params = request.parameter
1613 args = shlex.split(params)
1614 options, dummy = optparser.parse_args(args)
1616 Globals.verbose_options = options.verbose
1618 response = plugin_pb2.CodeGeneratorResponse()
1620 # Google's protoc does not currently indicate the full path of proto files.
1621 # Instead always add the main file path to the search dirs, that works for
1624 options.options_path.append(os.path.dirname(request.file_to_generate[0]))
1626 # Process any include files first, in order to have them
1627 # available as dependencies
1629 for fdesc in request.proto_file:
1630 other_files[fdesc.name] = parse_file(fdesc.name, fdesc, options)
1632 for filename in request.file_to_generate:
1633 for fdesc in request.proto_file:
1634 if fdesc.name == filename:
1635 results = process_file(filename, fdesc, options, other_files)
1637 f = response.file.add()
1638 f.name = results['headername']
1639 f.content = results['headerdata']
1641 f = response.file.add()
1642 f.name = results['sourcename']
1643 f.content = results['sourcedata']
1645 io.open(sys.stdout.fileno(), "wb").write(response.SerializeToString())
1647 if __name__ == '__main__':
1648 # Check if we are running as a plugin under protoc
1649 if 'protoc-gen-' in sys.argv[0] or '--protoc-plugin' in sys.argv: