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
266 if field_options.type == nanopb_pb2.FT_INLINE:
267 field_options.type = nanopb_pb2.FT_STATIC
268 self.inline = nanopb_pb2.FT_INLINE
270 # Parse field options
271 if field_options.HasField("max_size"):
272 self.max_size = field_options.max_size
274 if field_options.HasField("max_count"):
275 self.max_count = field_options.max_count
277 if desc.HasField('default_value'):
278 self.default = desc.default_value
280 # Check field rules, i.e. required/optional/repeated.
282 if desc.label == FieldD.LABEL_REPEATED:
283 self.rules = 'REPEATED'
284 if self.max_count is None:
285 can_be_static = False
287 self.array_decl = '[%d]' % self.max_count
288 elif field_options.proto3:
289 self.rules = 'SINGULAR'
290 elif desc.label == FieldD.LABEL_REQUIRED:
291 self.rules = 'REQUIRED'
292 elif desc.label == FieldD.LABEL_OPTIONAL:
293 self.rules = 'OPTIONAL'
295 raise NotImplementedError(desc.label)
297 # Check if the field can be implemented with static allocation
298 # i.e. whether the data size is known.
299 if desc.type == FieldD.TYPE_STRING and self.max_size is None:
300 can_be_static = False
302 if desc.type == FieldD.TYPE_BYTES and self.max_size is None:
303 can_be_static = False
305 # Decide how the field data will be allocated
306 if field_options.type == nanopb_pb2.FT_DEFAULT:
308 field_options.type = nanopb_pb2.FT_STATIC
310 field_options.type = nanopb_pb2.FT_CALLBACK
312 if field_options.type == nanopb_pb2.FT_STATIC and not can_be_static:
313 raise Exception("Field %s is defined as static, but max_size or "
314 "max_count is not given." % self.name)
316 if field_options.type == nanopb_pb2.FT_STATIC:
317 self.allocation = 'STATIC'
318 elif field_options.type == nanopb_pb2.FT_POINTER:
319 self.allocation = 'POINTER'
320 elif field_options.type == nanopb_pb2.FT_CALLBACK:
321 self.allocation = 'CALLBACK'
323 raise NotImplementedError(field_options.type)
325 # Decide the C data type to use in the struct.
326 if desc.type in datatypes:
327 self.ctype, self.pbtype, self.enc_size, isa = datatypes[desc.type]
329 # Override the field size if user wants to use smaller integers
330 if isa and field_options.int_size != nanopb_pb2.IS_DEFAULT:
331 self.ctype = intsizes[field_options.int_size]
332 if desc.type == FieldD.TYPE_UINT32 or desc.type == FieldD.TYPE_UINT64:
333 self.ctype = 'u' + self.ctype;
334 elif desc.type == FieldD.TYPE_ENUM:
336 self.ctype = names_from_type_name(desc.type_name)
337 if self.default is not None:
338 self.default = self.ctype + self.default
339 self.enc_size = None # Needs to be filled in when enum values are known
340 elif desc.type == FieldD.TYPE_STRING:
341 self.pbtype = 'STRING'
343 if self.allocation == 'STATIC':
345 self.array_decl += '[%d]' % self.max_size
346 self.enc_size = varint_max_size(self.max_size) + self.max_size
347 elif desc.type == FieldD.TYPE_BYTES:
348 self.pbtype = 'BYTES'
349 if self.allocation == 'STATIC':
350 # Inline STATIC for BYTES is like STATIC for STRING.
352 self.ctype = 'pb_byte_t'
353 self.array_decl += '[%d]' % self.max_size
355 self.ctype = self.struct_name + self.name + 't'
356 self.enc_size = varint_max_size(self.max_size) + self.max_size
357 elif self.allocation == 'POINTER':
358 self.ctype = 'pb_bytes_array_t'
359 elif desc.type == FieldD.TYPE_MESSAGE:
360 self.pbtype = 'MESSAGE'
361 self.ctype = self.submsgname = names_from_type_name(desc.type_name)
362 self.enc_size = None # Needs to be filled in after the message type is available
364 raise NotImplementedError(desc.type)
366 def __lt__(self, other):
367 return self.tag < other.tag
371 if self.allocation == 'POINTER':
372 if self.rules == 'REPEATED':
373 result += ' pb_size_t ' + self.name + '_count;\n'
375 if self.pbtype == 'MESSAGE':
376 # Use struct definition, so recursive submessages are possible
377 result += ' struct _%s *%s;' % (self.ctype, self.name)
378 elif self.rules == 'REPEATED' and self.pbtype in ['STRING', 'BYTES']:
379 # String/bytes arrays need to be defined as pointers to pointers
380 result += ' %s **%s;' % (self.ctype, self.name)
382 result += ' %s *%s;' % (self.ctype, self.name)
383 elif self.allocation == 'CALLBACK':
384 result += ' pb_callback_t %s;' % self.name
386 if self.rules == 'OPTIONAL' and self.allocation == 'STATIC':
387 result += ' bool has_' + self.name + ';\n'
388 elif self.rules == 'REPEATED' and self.allocation == 'STATIC':
389 result += ' pb_size_t ' + self.name + '_count;\n'
390 result += ' %s %s%s;' % (self.ctype, self.name, self.array_decl)
394 '''Return definitions for any special types this field might need.'''
395 if self.pbtype == 'BYTES' and self.allocation == 'STATIC' and not self.inline:
396 result = 'typedef PB_BYTES_ARRAY_T(%d) %s;\n' % (self.max_size, self.ctype)
401 def get_dependencies(self):
402 '''Get list of type names used by this field.'''
403 if self.allocation == 'STATIC':
404 return [str(self.ctype)]
408 def get_initializer(self, null_init, inner_init_only = False):
409 '''Return literal expression for this field's default value.
410 null_init: If True, initialize to a 0 value instead of default from .proto
411 inner_init_only: If True, exclude initialization for any count/has fields
415 if self.pbtype == 'MESSAGE':
417 inner_init = '%s_init_zero' % self.ctype
419 inner_init = '%s_init_default' % self.ctype
420 elif self.default is None or null_init:
421 if self.pbtype == 'STRING':
423 elif self.pbtype == 'BYTES':
427 inner_init = '{0, {0}}'
428 elif self.pbtype in ('ENUM', 'UENUM'):
429 inner_init = '(%s)0' % self.ctype
433 if self.pbtype == 'STRING':
434 inner_init = self.default.replace('"', '\\"')
435 inner_init = '"' + inner_init + '"'
436 elif self.pbtype == 'BYTES':
437 data = ['0x%02x' % ord(c) for c in self.default]
442 inner_init = '{0, {0}}'
445 inner_init = '{%s}' % ','.join(data)
447 inner_init = '{%d, {%s}}' % (len(data), ','.join(data))
448 elif self.pbtype in ['FIXED32', 'UINT32']:
449 inner_init = str(self.default) + 'u'
450 elif self.pbtype in ['FIXED64', 'UINT64']:
451 inner_init = str(self.default) + 'ull'
452 elif self.pbtype in ['SFIXED64', 'INT64']:
453 inner_init = str(self.default) + 'll'
455 inner_init = str(self.default)
461 if self.allocation == 'STATIC':
462 if self.rules == 'REPEATED':
464 outer_init += ', '.join([inner_init] * self.max_count)
466 elif self.rules == 'OPTIONAL':
467 outer_init = 'false, ' + inner_init
469 outer_init = inner_init
470 elif self.allocation == 'POINTER':
471 if self.rules == 'REPEATED':
472 outer_init = '0, NULL'
475 elif self.allocation == 'CALLBACK':
476 if self.pbtype == 'EXTENSION':
479 outer_init = '{{NULL}, NULL}'
483 def default_decl(self, declaration_only = False):
484 '''Return definition for this field's default value.'''
485 if self.default is None:
489 default = self.get_initializer(False, True)
492 if self.pbtype == 'STRING':
493 if self.allocation != 'STATIC':
494 return None # Not implemented
495 array_decl = '[%d]' % self.max_size
496 elif self.pbtype == 'BYTES':
497 if self.allocation != 'STATIC':
498 return None # Not implemented
500 array_decl = '[%d]' % self.max_size
503 return 'extern const %s %s_default%s;' % (ctype, self.struct_name + self.name, array_decl)
505 return 'const %s %s_default%s = %s;' % (ctype, self.struct_name + self.name, array_decl, default)
508 '''Return the #define for the tag number of this field.'''
509 identifier = '%s_%s_tag' % (self.struct_name, self.name)
510 return '#define %-40s %d\n' % (identifier, self.tag)
512 def pb_field_t(self, prev_field_name, union_index = None):
513 '''Return the pb_field_t initializer to use in the constant array.
514 prev_field_name is the name of the previous field or None. For OneOf
515 unions, union_index is the index of this field inside the OneOf.
518 if self.rules == 'ONEOF':
520 result = ' PB_ANONYMOUS_ONEOF_FIELD(%s, ' % self.union_name
522 result = ' PB_ONEOF_FIELD(%s, ' % self.union_name
524 result = ' PB_FIELD('
526 result += '%3d, ' % self.tag
527 result += '%-8s, ' % self.pbtype
528 result += '%s, ' % self.rules
529 result += '%-8s, ' % (self.allocation if not self.inline else "INLINE")
531 if union_index is not None and union_index > 0:
533 elif prev_field_name is None:
538 result += '%s, ' % self.struct_name
539 result += '%s, ' % self.name
540 result += '%s, ' % (prev_field_name or self.name)
542 if self.pbtype == 'MESSAGE':
543 result += '&%s_fields)' % self.submsgname
544 elif self.default is None:
546 elif self.pbtype in ['BYTES', 'STRING'] and self.allocation != 'STATIC':
547 result += '0)' # Arbitrary size default values not implemented
548 elif self.rules == 'OPTEXT':
549 result += '0)' # Default value for extensions is not implemented
551 result += '&%s_default)' % (self.struct_name + self.name)
555 def get_last_field_name(self):
558 def largest_field_value(self):
559 '''Determine if this field needs 16bit or 32bit pb_field_t structure to compile properly.
560 Returns numeric value or a C-expression for assert.'''
562 if self.pbtype == 'MESSAGE' and self.allocation == 'STATIC':
563 if self.rules == 'REPEATED':
564 check.append('pb_membersize(%s, %s[0])' % (self.struct_name, self.name))
565 elif self.rules == 'ONEOF':
567 check.append('pb_membersize(%s, %s)' % (self.struct_name, self.name))
569 check.append('pb_membersize(%s, %s.%s)' % (self.struct_name, self.union_name, self.name))
571 check.append('pb_membersize(%s, %s)' % (self.struct_name, self.name))
572 elif self.pbtype == 'BYTES' and self.allocation == 'STATIC':
573 if self.max_size > 251:
574 check.append('pb_membersize(%s, %s)' % (self.struct_name, self.name))
576 return FieldMaxSize([self.tag, self.max_size, self.max_count],
578 ('%s.%s' % (self.struct_name, self.name)))
580 def encoded_size(self, dependencies):
581 '''Return the maximum size that this field can take when encoded,
582 including the field tag. If the size cannot be determined, returns
585 if self.allocation != 'STATIC':
588 if self.pbtype == 'MESSAGE':
590 if str(self.submsgname) in dependencies:
591 submsg = dependencies[str(self.submsgname)]
592 encsize = submsg.encoded_size(dependencies)
593 if encsize is not None:
594 # Include submessage length prefix
595 encsize += varint_max_size(encsize.upperlimit())
598 # Submessage or its size cannot be found.
599 # This can occur if submessage is defined in different
600 # file, and it or its .options could not be found.
601 # Instead of direct numeric value, reference the size that
602 # has been #defined in the other file.
603 encsize = EncodedSize(self.submsgname + 'size')
605 # We will have to make a conservative assumption on the length
606 # prefix size, though.
609 elif self.pbtype in ['ENUM', 'UENUM']:
610 if str(self.ctype) in dependencies:
611 enumtype = dependencies[str(self.ctype)]
612 encsize = enumtype.encoded_size()
614 # Conservative assumption
617 elif self.enc_size is None:
618 raise RuntimeError("Could not determine encoded size for %s.%s"
619 % (self.struct_name, self.name))
621 encsize = EncodedSize(self.enc_size)
623 encsize += varint_max_size(self.tag << 3) # Tag + wire type
625 if self.rules == 'REPEATED':
626 # Decoders must be always able to handle unpacked arrays.
627 # Therefore we have to reserve space for it, even though
628 # we emit packed arrays ourselves.
629 encsize *= self.max_count
634 class ExtensionRange(Field):
635 def __init__(self, struct_name, range_start, field_options):
636 '''Implements a special pb_extension_t* field in an extensible message
637 structure. The range_start signifies the index at which the extensions
638 start. Not necessarily all tags above this are extensions, it is merely
639 a speed optimization.
641 self.tag = range_start
642 self.struct_name = struct_name
643 self.name = 'extensions'
644 self.pbtype = 'EXTENSION'
645 self.rules = 'OPTIONAL'
646 self.allocation = 'CALLBACK'
647 self.ctype = 'pb_extension_t'
655 return ' pb_extension_t *extensions;'
663 def encoded_size(self, dependencies):
664 # We exclude extensions from the count, because they cannot be known
665 # until runtime. Other option would be to return None here, but this
666 # way the value remains useful if extensions are not used.
667 return EncodedSize(0)
669 class ExtensionField(Field):
670 def __init__(self, struct_name, desc, field_options):
671 self.fullname = struct_name + desc.name
672 self.extendee_name = names_from_type_name(desc.extendee)
673 Field.__init__(self, self.fullname + 'struct', desc, field_options)
675 if self.rules != 'OPTIONAL':
679 self.rules = 'OPTEXT'
682 '''Return the #define for the tag number of this field.'''
683 identifier = '%s_tag' % self.fullname
684 return '#define %-40s %d\n' % (identifier, self.tag)
686 def extension_decl(self):
687 '''Declaration of the extension type in the .pb.h file'''
689 msg = '/* Extension field %s was skipped because only "optional"\n' % self.fullname
690 msg +=' type of extension fields is currently supported. */\n'
693 return ('extern const pb_extension_type_t %s; /* field type: %s */\n' %
694 (self.fullname, str(self).strip()))
696 def extension_def(self):
697 '''Definition of the extension type in the .pb.c file'''
702 result = 'typedef struct {\n'
704 result += '\n} %s;\n\n' % self.struct_name
705 result += ('static const pb_field_t %s_field = \n %s;\n\n' %
706 (self.fullname, self.pb_field_t(None)))
707 result += 'const pb_extension_type_t %s = {\n' % self.fullname
710 result += ' &%s_field\n' % self.fullname
715 # ---------------------------------------------------------------------------
716 # Generation of oneofs (unions)
717 # ---------------------------------------------------------------------------
720 def __init__(self, struct_name, oneof_desc):
721 self.struct_name = struct_name
722 self.name = oneof_desc.name
724 self.pbtype = 'oneof'
726 self.allocation = 'ONEOF'
729 self.anonymous = False
732 def add_field(self, field):
733 if field.allocation == 'CALLBACK':
734 raise Exception("Callback fields inside of oneof are not supported"
735 + " (field %s)" % field.name)
737 field.union_name = self.name
738 field.rules = 'ONEOF'
739 field.anonymous = self.anonymous
740 self.fields.append(field)
741 self.fields.sort(key = lambda f: f.tag)
743 # Sort by the lowest tag number inside union
744 self.tag = min([f.tag for f in self.fields])
749 result += ' pb_size_t which_' + self.name + ";\n"
750 result += ' union {\n'
751 for f in self.fields:
752 result += ' ' + str(f).replace('\n', '\n ') + '\n'
756 result += ' } ' + self.name + ';'
760 return ''.join([f.types() for f in self.fields])
762 def get_dependencies(self):
764 for f in self.fields:
765 deps += f.get_dependencies()
768 def get_initializer(self, null_init):
769 return '0, {' + self.fields[0].get_initializer(null_init) + '}'
771 def default_decl(self, declaration_only = False):
775 return ''.join([f.tags() for f in self.fields])
777 def pb_field_t(self, prev_field_name):
779 for union_index, field in enumerate(self.fields):
780 parts.append(field.pb_field_t(prev_field_name, union_index))
781 return ',\n'.join(parts)
783 def get_last_field_name(self):
785 return self.fields[-1].name
787 return self.name + '.' + self.fields[-1].name
789 def largest_field_value(self):
790 largest = FieldMaxSize()
791 for f in self.fields:
792 largest.extend(f.largest_field_value())
795 def encoded_size(self, dependencies):
796 '''Returns the size of the largest oneof field.'''
797 largest = EncodedSize(0)
798 for f in self.fields:
799 size = EncodedSize(f.encoded_size(dependencies))
800 if size.value is None:
803 return None # Cannot resolve maximum of symbols
804 elif size.value > largest.value:
809 # ---------------------------------------------------------------------------
810 # Generation of messages (structures)
811 # ---------------------------------------------------------------------------
815 def __init__(self, names, desc, message_options):
821 if message_options.msgid:
822 self.msgid = message_options.msgid
824 if hasattr(desc, 'oneof_decl'):
825 for i, f in enumerate(desc.oneof_decl):
826 oneof_options = get_nanopb_suboptions(desc, message_options, self.name + f.name)
827 if oneof_options.no_unions:
828 no_unions.append(i) # No union, but add fields normally
829 elif oneof_options.type == nanopb_pb2.FT_IGNORE:
830 pass # No union and skip fields also
832 oneof = OneOf(self.name, f)
833 if oneof_options.anonymous_oneof:
834 oneof.anonymous = True
835 self.oneofs[i] = oneof
836 self.fields.append(oneof)
839 field_options = get_nanopb_suboptions(f, message_options, self.name + f.name)
840 if field_options.type == nanopb_pb2.FT_IGNORE:
843 field = Field(self.name, f, field_options)
844 if (hasattr(f, 'oneof_index') and
845 f.HasField('oneof_index') and
846 f.oneof_index not in no_unions):
847 if f.oneof_index in self.oneofs:
848 self.oneofs[f.oneof_index].add_field(field)
850 self.fields.append(field)
852 if len(desc.extension_range) > 0:
853 field_options = get_nanopb_suboptions(desc, message_options, self.name + 'extensions')
854 range_start = min([r.start for r in desc.extension_range])
855 if field_options.type != nanopb_pb2.FT_IGNORE:
856 self.fields.append(ExtensionRange(self.name, range_start, field_options))
858 self.packed = message_options.packed_struct
859 self.ordered_fields = self.fields[:]
860 self.ordered_fields.sort()
862 def get_dependencies(self):
863 '''Get list of type names that this structure refers to.'''
865 for f in self.fields:
866 deps += f.get_dependencies()
870 result = 'typedef struct _%s {\n' % self.name
872 if not self.ordered_fields:
873 # Empty structs are not allowed in C standard.
874 # Therefore add a dummy field if an empty message occurs.
875 result += ' char dummy_field;'
877 result += '\n'.join([str(f) for f in self.ordered_fields])
878 result += '\n/* @@protoc_insertion_point(struct:%s) */' % self.name
882 result += ' pb_packed'
884 result += ' %s;' % self.name
887 result = 'PB_PACKED_STRUCT_START\n' + result
888 result += '\nPB_PACKED_STRUCT_END'
893 return ''.join([f.types() for f in self.fields])
895 def get_initializer(self, null_init):
896 if not self.ordered_fields:
900 for field in self.ordered_fields:
901 parts.append(field.get_initializer(null_init))
902 return '{' + ', '.join(parts) + '}'
904 def default_decl(self, declaration_only = False):
906 for field in self.fields:
907 default = field.default_decl(declaration_only)
908 if default is not None:
909 result += default + '\n'
912 def count_required_fields(self):
913 '''Returns number of required fields inside this message'''
915 for f in self.fields:
916 if not isinstance(f, OneOf):
917 if f.rules == 'REQUIRED':
921 def count_all_fields(self):
923 for f in self.fields:
924 if isinstance(f, OneOf):
925 count += len(f.fields)
930 def fields_declaration(self):
931 result = 'extern const pb_field_t %s_fields[%d];' % (self.name, self.count_all_fields() + 1)
934 def fields_definition(self):
935 result = 'const pb_field_t %s_fields[%d] = {\n' % (self.name, self.count_all_fields() + 1)
938 for field in self.ordered_fields:
939 result += field.pb_field_t(prev)
941 prev = field.get_last_field_name()
943 result += ' PB_LAST_FIELD\n};'
946 def encoded_size(self, dependencies):
947 '''Return the maximum size that this message can take when encoded.
948 If the size cannot be determined, returns None.
950 size = EncodedSize(0)
951 for field in self.fields:
952 fsize = field.encoded_size(dependencies)
960 # ---------------------------------------------------------------------------
961 # Processing of entire .proto files
962 # ---------------------------------------------------------------------------
964 def iterate_messages(desc, names = Names()):
965 '''Recursively find all messages. For each, yield name, DescriptorProto.'''
966 if hasattr(desc, 'message_type'):
967 submsgs = desc.message_type
969 submsgs = desc.nested_type
971 for submsg in submsgs:
972 sub_names = names + submsg.name
973 yield sub_names, submsg
975 for x in iterate_messages(submsg, sub_names):
978 def iterate_extensions(desc, names = Names()):
979 '''Recursively find all extensions.
980 For each, yield name, FieldDescriptorProto.
982 for extension in desc.extension:
983 yield names, extension
985 for subname, subdesc in iterate_messages(desc, names):
986 for extension in subdesc.extension:
987 yield subname, extension
991 From http://code.activestate.com/recipes/577413-topological-sort/
992 This function is under the MIT license.
994 for k, v in list(data.items()):
995 v.discard(k) # Ignore self dependencies
996 extra_items_in_deps = reduce(set.union, list(data.values()), set()) - set(data.keys())
997 data.update(dict([(item, set()) for item in extra_items_in_deps]))
999 ordered = set(item for item,dep in list(data.items()) if not dep)
1002 for item in sorted(ordered):
1004 data = dict([(item, (dep - ordered)) for item,dep in list(data.items())
1005 if item not in ordered])
1006 assert not data, "A cyclic dependency exists amongst %r" % data
1008 def sort_dependencies(messages):
1009 '''Sort a list of Messages based on dependencies.'''
1011 message_by_name = {}
1012 for message in messages:
1013 dependencies[str(message.name)] = set(message.get_dependencies())
1014 message_by_name[str(message.name)] = message
1016 for msgname in toposort2(dependencies):
1017 if msgname in message_by_name:
1018 yield message_by_name[msgname]
1020 def make_identifier(headername):
1021 '''Make #ifndef identifier that contains uppercase A-Z and digits 0-9'''
1023 for c in headername.upper():
1031 def __init__(self, fdesc, file_options):
1032 '''Takes a FileDescriptorProto and parses it.'''
1034 self.file_options = file_options
1035 self.dependencies = {}
1038 # Some of types used in this file probably come from the file itself.
1039 # Thus it has implicit dependency on itself.
1040 self.add_dependency(self)
1045 self.extensions = []
1047 if self.fdesc.package:
1048 base_name = Names(self.fdesc.package.split('.'))
1052 for enum in self.fdesc.enum_type:
1053 enum_options = get_nanopb_suboptions(enum, self.file_options, base_name + enum.name)
1054 self.enums.append(Enum(base_name, enum, enum_options))
1056 for names, message in iterate_messages(self.fdesc, base_name):
1057 message_options = get_nanopb_suboptions(message, self.file_options, names)
1059 if message_options.skip_message:
1062 self.messages.append(Message(names, message, message_options))
1063 for enum in message.enum_type:
1064 enum_options = get_nanopb_suboptions(enum, message_options, names + enum.name)
1065 self.enums.append(Enum(names, enum, enum_options))
1067 for names, extension in iterate_extensions(self.fdesc, base_name):
1068 field_options = get_nanopb_suboptions(extension, self.file_options, names + extension.name)
1069 if field_options.type != nanopb_pb2.FT_IGNORE:
1070 self.extensions.append(ExtensionField(names, extension, field_options))
1072 def add_dependency(self, other):
1073 for enum in other.enums:
1074 self.dependencies[str(enum.names)] = enum
1076 for msg in other.messages:
1077 self.dependencies[str(msg.name)] = msg
1079 # Fix field default values where enum short names are used.
1080 for enum in other.enums:
1081 if not enum.options.long_names:
1082 for message in self.messages:
1083 for field in message.fields:
1084 if field.default in enum.value_longnames:
1085 idx = enum.value_longnames.index(field.default)
1086 field.default = enum.values[idx][0]
1088 # Fix field data types where enums have negative values.
1089 for enum in other.enums:
1090 if not enum.has_negative():
1091 for message in self.messages:
1092 for field in message.fields:
1093 if field.pbtype == 'ENUM' and field.ctype == enum.names:
1094 field.pbtype = 'UENUM'
1096 def generate_header(self, includes, headername, options):
1097 '''Generate content for a header file.
1098 Generates strings, which should be concatenated and stored to file.
1101 yield '/* Automatically generated nanopb header */\n'
1102 if options.notimestamp:
1103 yield '/* Generated by %s */\n\n' % (nanopb_version)
1105 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
1107 if self.fdesc.package:
1108 symbol = make_identifier(self.fdesc.package + '_' + headername)
1110 symbol = make_identifier(headername)
1111 yield '#ifndef PB_%s_INCLUDED\n' % symbol
1112 yield '#define PB_%s_INCLUDED\n' % symbol
1114 yield options.libformat % ('pb.h')
1116 # no %s specified - use whatever was passed in as options.libformat
1117 yield options.libformat
1120 for incfile in includes:
1121 noext = os.path.splitext(incfile)[0]
1122 yield options.genformat % (noext + options.extension + '.h')
1125 yield '/* @@protoc_insertion_point(includes) */\n'
1127 yield '#if PB_PROTO_HEADER_VERSION != 30\n'
1128 yield '#error Regenerate this file with the current version of nanopb generator.\n'
1132 yield '#ifdef __cplusplus\n'
1133 yield 'extern "C" {\n'
1137 yield '/* Enum definitions */\n'
1138 for enum in self.enums:
1139 yield str(enum) + '\n\n'
1142 yield '/* Struct definitions */\n'
1143 for msg in sort_dependencies(self.messages):
1145 yield str(msg) + '\n\n'
1148 yield '/* Extensions */\n'
1149 for extension in self.extensions:
1150 yield extension.extension_decl()
1154 yield '/* Default values for struct fields */\n'
1155 for msg in self.messages:
1156 yield msg.default_decl(True)
1159 yield '/* Initializer values for message structs */\n'
1160 for msg in self.messages:
1161 identifier = '%s_init_default' % msg.name
1162 yield '#define %-40s %s\n' % (identifier, msg.get_initializer(False))
1163 for msg in self.messages:
1164 identifier = '%s_init_zero' % msg.name
1165 yield '#define %-40s %s\n' % (identifier, msg.get_initializer(True))
1168 yield '/* Field tags (for use in manual encoding/decoding) */\n'
1169 for msg in sort_dependencies(self.messages):
1170 for field in msg.fields:
1172 for extension in self.extensions:
1173 yield extension.tags()
1176 yield '/* Struct field encoding specification for nanopb */\n'
1177 for msg in self.messages:
1178 yield msg.fields_declaration() + '\n'
1181 yield '/* Maximum encoded size of messages (where known) */\n'
1182 for msg in self.messages:
1183 msize = msg.encoded_size(self.dependencies)
1184 identifier = '%s_size' % msg.name
1185 if msize is not None:
1186 yield '#define %-40s %s\n' % (identifier, msize)
1188 yield '/* %s depends on runtime parameters */\n' % identifier
1191 yield '/* Message IDs (where set with "msgid" option) */\n'
1193 yield '#ifdef PB_MSGID\n'
1194 for msg in self.messages:
1195 if hasattr(msg,'msgid'):
1196 yield '#define PB_MSG_%d %s\n' % (msg.msgid, msg.name)
1199 symbol = make_identifier(headername.split('.')[0])
1200 yield '#define %s_MESSAGES \\\n' % symbol
1202 for msg in self.messages:
1204 msize = msg.encoded_size(self.dependencies)
1205 if msize is not None:
1207 if hasattr(msg,'msgid'):
1208 yield '\tPB_MSG(%d,%s,%s) \\\n' % (msg.msgid, m, msg.name)
1211 for msg in self.messages:
1212 if hasattr(msg,'msgid'):
1213 yield '#define %s_msgid %d\n' % (msg.name, msg.msgid)
1218 yield '#ifdef __cplusplus\n'
1219 yield '} /* extern "C" */\n'
1223 yield '/* @@protoc_insertion_point(eof) */\n'
1226 def generate_source(self, headername, options):
1227 '''Generate content for a source file.'''
1229 yield '/* Automatically generated nanopb constant definitions */\n'
1230 if options.notimestamp:
1231 yield '/* Generated by %s */\n\n' % (nanopb_version)
1233 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
1234 yield options.genformat % (headername)
1236 yield '/* @@protoc_insertion_point(includes) */\n'
1238 yield '#if PB_PROTO_HEADER_VERSION != 30\n'
1239 yield '#error Regenerate this file with the current version of nanopb generator.\n'
1243 for msg in self.messages:
1244 yield msg.default_decl(False)
1248 for msg in self.messages:
1249 yield msg.fields_definition() + '\n\n'
1251 for ext in self.extensions:
1252 yield ext.extension_def() + '\n'
1254 for enum in self.enums:
1255 yield enum.enum_to_string_definition() + '\n'
1257 # Add checks for numeric limits
1259 largest_msg = max(self.messages, key = lambda m: m.count_required_fields())
1260 largest_count = largest_msg.count_required_fields()
1261 if largest_count > 64:
1262 yield '\n/* Check that missing required fields will be properly detected */\n'
1263 yield '#if PB_MAX_REQUIRED_FIELDS < %d\n' % largest_count
1264 yield '#error Properly detecting missing required fields in %s requires \\\n' % largest_msg.name
1265 yield ' setting PB_MAX_REQUIRED_FIELDS to %d or more.\n' % largest_count
1268 max_field = FieldMaxSize()
1269 checks_msgnames = []
1270 for msg in self.messages:
1271 checks_msgnames.append(msg.name)
1272 for field in msg.fields:
1273 max_field.extend(field.largest_field_value())
1275 worst = max_field.worst
1276 worst_field = max_field.worst_field
1277 checks = max_field.checks
1279 if worst > 255 or checks:
1280 yield '\n/* Check that field information fits in pb_field_t */\n'
1282 if worst > 65535 or checks:
1283 yield '#if !defined(PB_FIELD_32BIT)\n'
1285 yield '#error Field descriptor for %s is too large. Define PB_FIELD_32BIT to fix this.\n' % worst_field
1287 assertion = ' && '.join(str(c) + ' < 65536' for c in checks)
1288 msgs = '_'.join(str(n) for n in checks_msgnames)
1289 yield '/* If you get an error here, it means that you need to define PB_FIELD_32BIT\n'
1290 yield ' * compile-time option. You can do that in pb.h or on compiler command line.\n'
1292 yield ' * The reason you need to do this is that some of your messages contain tag\n'
1293 yield ' * numbers or field sizes that are larger than what can fit in 8 or 16 bit\n'
1294 yield ' * field descriptors.\n'
1296 yield 'PB_STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
1300 yield '#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT)\n'
1302 yield '#error Field descriptor for %s is too large. Define PB_FIELD_16BIT to fix this.\n' % worst_field
1304 assertion = ' && '.join(str(c) + ' < 256' for c in checks)
1305 msgs = '_'.join(str(n) for n in checks_msgnames)
1306 yield '/* If you get an error here, it means that you need to define PB_FIELD_16BIT\n'
1307 yield ' * compile-time option. You can do that in pb.h or on compiler command line.\n'
1309 yield ' * The reason you need to do this is that some of your messages contain tag\n'
1310 yield ' * numbers or field sizes that are larger than what can fit in the default\n'
1311 yield ' * 8 bit descriptors.\n'
1313 yield 'PB_STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
1316 # Add check for sizeof(double)
1318 for msg in self.messages:
1319 for field in msg.fields:
1320 if field.ctype == 'double':
1325 yield '/* On some platforms (such as AVR), double is really float.\n'
1326 yield ' * These are not directly supported by nanopb, but see example_avr_double.\n'
1327 yield ' * To get rid of this error, remove any double fields from your .proto.\n'
1329 yield 'PB_STATIC_ASSERT(sizeof(double) == 8, DOUBLE_MUST_BE_8_BYTES)\n'
1332 yield '/* @@protoc_insertion_point(eof) */\n'
1334 # ---------------------------------------------------------------------------
1335 # Options parsing for the .proto files
1336 # ---------------------------------------------------------------------------
1338 from fnmatch import fnmatch
1340 def read_options_file(infile):
1341 '''Parse a separate options file to list:
1342 [(namemask, options), ...]
1345 data = infile.read()
1346 data = re.sub('/\*.*?\*/', '', data, flags = re.MULTILINE)
1347 data = re.sub('//.*?$', '', data, flags = re.MULTILINE)
1348 data = re.sub('#.*?$', '', data, flags = re.MULTILINE)
1349 for i, line in enumerate(data.split('\n')):
1354 parts = line.split(None, 1)
1357 sys.stderr.write("%s:%d: " % (infile.name, i + 1) +
1358 "Option lines should have space between field name and options. " +
1359 "Skipping line: '%s'\n" % line)
1362 opts = nanopb_pb2.NanoPBOptions()
1365 text_format.Merge(parts[1], opts)
1366 except Exception as e:
1367 sys.stderr.write("%s:%d: " % (infile.name, i + 1) +
1368 "Unparseable option line: '%s'. " % line +
1369 "Error: %s\n" % str(e))
1371 results.append((parts[0], opts))
1376 '''Ugly global variables, should find a good way to pass these.'''
1377 verbose_options = False
1378 separate_options = []
1379 matched_namemasks = set()
1381 def get_nanopb_suboptions(subdesc, options, name):
1382 '''Get copy of options, and merge information from subdesc.'''
1383 new_options = nanopb_pb2.NanoPBOptions()
1384 new_options.CopyFrom(options)
1386 if hasattr(subdesc, 'syntax') and subdesc.syntax == "proto3":
1387 new_options.proto3 = True
1389 # Handle options defined in a separate file
1390 dotname = '.'.join(name.parts)
1391 for namemask, options in Globals.separate_options:
1392 if fnmatch(dotname, namemask):
1393 Globals.matched_namemasks.add(namemask)
1394 new_options.MergeFrom(options)
1396 # Handle options defined in .proto
1397 if isinstance(subdesc.options, descriptor.FieldOptions):
1398 ext_type = nanopb_pb2.nanopb
1399 elif isinstance(subdesc.options, descriptor.FileOptions):
1400 ext_type = nanopb_pb2.nanopb_fileopt
1401 elif isinstance(subdesc.options, descriptor.MessageOptions):
1402 ext_type = nanopb_pb2.nanopb_msgopt
1403 elif isinstance(subdesc.options, descriptor.EnumOptions):
1404 ext_type = nanopb_pb2.nanopb_enumopt
1406 raise Exception("Unknown options type")
1408 if subdesc.options.HasExtension(ext_type):
1409 ext = subdesc.options.Extensions[ext_type]
1410 new_options.MergeFrom(ext)
1412 if Globals.verbose_options:
1413 sys.stderr.write("Options for " + dotname + ": ")
1414 sys.stderr.write(text_format.MessageToString(new_options) + "\n")
1419 # ---------------------------------------------------------------------------
1420 # Command line interface
1421 # ---------------------------------------------------------------------------
1425 from optparse import OptionParser
1427 optparser = OptionParser(
1428 usage = "Usage: nanopb_generator.py [options] file.pb ...",
1429 epilog = "Compile file.pb from file.proto by: 'protoc -ofile.pb file.proto'. " +
1430 "Output will be written to file.pb.h and file.pb.c.")
1431 optparser.add_option("-x", dest="exclude", metavar="FILE", action="append", default=[],
1432 help="Exclude file from generated #include list.")
1433 optparser.add_option("-e", "--extension", dest="extension", metavar="EXTENSION", default=".pb",
1434 help="Set extension to use instead of '.pb' for generated files. [default: %default]")
1435 optparser.add_option("-f", "--options-file", dest="options_file", metavar="FILE", default="%s.options",
1436 help="Set name of a separate generator options file.")
1437 optparser.add_option("-I", "--options-path", dest="options_path", metavar="DIR",
1438 action="append", default = [],
1439 help="Search for .options files additionally in this path")
1440 optparser.add_option("-D", "--output-dir", dest="output_dir",
1441 metavar="OUTPUTDIR", default=None,
1442 help="Output directory of .pb.h and .pb.c files")
1443 optparser.add_option("-Q", "--generated-include-format", dest="genformat",
1444 metavar="FORMAT", default='#include "%s"\n',
1445 help="Set format string to use for including other .pb.h files. [default: %default]")
1446 optparser.add_option("-L", "--library-include-format", dest="libformat",
1447 metavar="FORMAT", default='#include <%s>\n',
1448 help="Set format string to use for including the nanopb pb.h header. [default: %default]")
1449 optparser.add_option("-T", "--no-timestamp", dest="notimestamp", action="store_true", default=False,
1450 help="Don't add timestamp to .pb.h and .pb.c preambles")
1451 optparser.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False,
1452 help="Don't print anything except errors.")
1453 optparser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
1454 help="Print more information.")
1455 optparser.add_option("-s", dest="settings", metavar="OPTION:VALUE", action="append", default=[],
1456 help="Set generator option (max_size, max_count etc.).")
1458 def parse_file(filename, fdesc, options):
1459 '''Parse a single file. Returns a ProtoFile instance.'''
1460 toplevel_options = nanopb_pb2.NanoPBOptions()
1461 for s in options.settings:
1462 text_format.Merge(s, toplevel_options)
1465 data = open(filename, 'rb').read()
1466 fdesc = descriptor.FileDescriptorSet.FromString(data).file[0]
1468 # Check if there is a separate .options file
1471 optfilename = options.options_file % os.path.splitext(filename)[0]
1473 # No %s specified, use the filename as-is
1474 optfilename = options.options_file
1477 paths = ['.'] + options.options_path
1479 if os.path.isfile(os.path.join(p, optfilename)):
1480 optfilename = os.path.join(p, optfilename)
1482 sys.stderr.write('Reading options from ' + optfilename + '\n')
1483 Globals.separate_options = read_options_file(open(optfilename, "rU"))
1486 # If we are given a full filename and it does not exist, give an error.
1487 # However, don't give error when we automatically look for .options file
1488 # with the same name as .proto.
1489 if options.verbose or had_abspath:
1490 sys.stderr.write('Options file not found: ' + optfilename + '\n')
1491 Globals.separate_options = []
1493 Globals.matched_namemasks = set()
1496 file_options = get_nanopb_suboptions(fdesc, toplevel_options, Names([filename]))
1497 f = ProtoFile(fdesc, file_options)
1498 f.optfilename = optfilename
1502 def process_file(filename, fdesc, options, other_files = {}):
1503 '''Process a single file.
1504 filename: The full path to the .proto or .pb source file, as string.
1505 fdesc: The loaded FileDescriptorSet, or None to read from the input file.
1506 options: Command line options as they come from OptionsParser.
1509 {'headername': Name of header file,
1510 'headerdata': Data for the .h header file,
1511 'sourcename': Name of the source code file,
1512 'sourcedata': Data for the .c source code file
1515 f = parse_file(filename, fdesc, options)
1517 # Provide dependencies if available
1518 for dep in f.fdesc.dependency:
1519 if dep in other_files:
1520 f.add_dependency(other_files[dep])
1522 # Decide the file names
1523 noext = os.path.splitext(filename)[0]
1524 headername = noext + options.extension + '.h'
1525 sourcename = noext + options.extension + '.c'
1526 headerbasename = os.path.basename(headername)
1528 # List of .proto files that should not be included in the C header file
1529 # even if they are mentioned in the source .proto.
1530 excludes = ['nanopb.proto', 'google/protobuf/descriptor.proto'] + options.exclude
1531 includes = [d for d in f.fdesc.dependency if d not in excludes]
1533 headerdata = ''.join(f.generate_header(includes, headerbasename, options))
1534 sourcedata = ''.join(f.generate_source(headerbasename, options))
1536 # Check if there were any lines in .options that did not match a member
1537 unmatched = [n for n,o in Globals.separate_options if n not in Globals.matched_namemasks]
1538 if unmatched and not options.quiet:
1539 sys.stderr.write("Following patterns in " + f.optfilename + " did not match any fields: "
1540 + ', '.join(unmatched) + "\n")
1541 if not Globals.verbose_options:
1542 sys.stderr.write("Use protoc --nanopb-out=-v:. to see a list of the field names.\n")
1544 return {'headername': headername, 'headerdata': headerdata,
1545 'sourcename': sourcename, 'sourcedata': sourcedata}
1548 '''Main function when invoked directly from the command line.'''
1550 options, filenames = optparser.parse_args()
1553 optparser.print_help()
1557 options.verbose = False
1559 if options.output_dir and not os.path.exists(options.output_dir):
1560 optparser.print_help()
1561 sys.stderr.write("\noutput_dir does not exist: %s\n" % options.output_dir)
1565 Globals.verbose_options = options.verbose
1566 for filename in filenames:
1567 results = process_file(filename, None, options)
1569 base_dir = options.output_dir or ''
1571 (os.path.join(base_dir, results['headername']), results['headerdata']),
1572 (os.path.join(base_dir, results['sourcename']), results['sourcedata']),
1575 if not options.quiet:
1576 paths = " and ".join([x[0] for x in to_write])
1577 sys.stderr.write("Writing to %s\n" % paths)
1579 for path, data in to_write:
1580 with open(path, 'w') as f:
1584 '''Main function when invoked as a protoc plugin.'''
1587 if sys.platform == "win32":
1589 # Set stdin and stdout to binary mode
1590 msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
1591 msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
1593 data = io.open(sys.stdin.fileno(), "rb").read()
1595 request = plugin_pb2.CodeGeneratorRequest.FromString(data)
1598 # Versions of Python prior to 2.7.3 do not support unicode
1599 # input to shlex.split(). Try to convert to str if possible.
1600 params = str(request.parameter)
1601 except UnicodeEncodeError:
1602 params = request.parameter
1605 args = shlex.split(params)
1606 options, dummy = optparser.parse_args(args)
1608 Globals.verbose_options = options.verbose
1610 response = plugin_pb2.CodeGeneratorResponse()
1612 # Google's protoc does not currently indicate the full path of proto files.
1613 # Instead always add the main file path to the search dirs, that works for
1616 options.options_path.append(os.path.dirname(request.file_to_generate[0]))
1618 # Process any include files first, in order to have them
1619 # available as dependencies
1621 for fdesc in request.proto_file:
1622 other_files[fdesc.name] = parse_file(fdesc.name, fdesc, options)
1624 for filename in request.file_to_generate:
1625 for fdesc in request.proto_file:
1626 if fdesc.name == filename:
1627 results = process_file(filename, fdesc, options, other_files)
1629 f = response.file.add()
1630 f.name = results['headername']
1631 f.content = results['headerdata']
1633 f = response.file.add()
1634 f.name = results['sourcename']
1635 f.content = results['sourcedata']
1637 io.open(sys.stdout.fileno(), "wb").write(response.SerializeToString())
1639 if __name__ == '__main__':
1640 # Check if we are running as a plugin under protoc
1641 if 'protoc-gen-' in sys.argv[0] or '--protoc-plugin' in sys.argv: