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.HasField("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):
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.
517 if self.rules == 'ONEOF':
519 result = ' PB_ANONYMOUS_ONEOF_FIELD(%s, ' % self.union_name
521 result = ' PB_ONEOF_FIELD(%s, ' % self.union_name
523 result = ' PB_FIELD('
525 result += '%3d, ' % self.tag
526 result += '%-8s, ' % self.pbtype
527 result += '%s, ' % self.rules
528 result += '%-8s, ' % (self.allocation if not self.inline else "INLINE")
529 result += '%s, ' % ("FIRST" if not prev_field_name else "OTHER")
530 result += '%s, ' % self.struct_name
531 result += '%s, ' % self.name
532 result += '%s, ' % (prev_field_name or self.name)
534 if self.pbtype == 'MESSAGE':
535 result += '&%s_fields)' % self.submsgname
536 elif self.default is None:
538 elif self.pbtype in ['BYTES', 'STRING'] and self.allocation != 'STATIC':
539 result += '0)' # Arbitrary size default values not implemented
540 elif self.rules == 'OPTEXT':
541 result += '0)' # Default value for extensions is not implemented
543 result += '&%s_default)' % (self.struct_name + self.name)
547 def get_last_field_name(self):
550 def largest_field_value(self):
551 '''Determine if this field needs 16bit or 32bit pb_field_t structure to compile properly.
552 Returns numeric value or a C-expression for assert.'''
554 if self.pbtype == 'MESSAGE' and self.allocation == 'STATIC':
555 if self.rules == 'REPEATED':
556 check.append('pb_membersize(%s, %s[0])' % (self.struct_name, self.name))
557 elif self.rules == 'ONEOF':
559 check.append('pb_membersize(%s, %s)' % (self.struct_name, self.name))
561 check.append('pb_membersize(%s, %s.%s)' % (self.struct_name, self.union_name, self.name))
563 check.append('pb_membersize(%s, %s)' % (self.struct_name, self.name))
564 elif self.pbtype == 'BYTES' and self.allocation == 'STATIC':
565 if self.max_size > 251:
566 check.append('pb_membersize(%s, %s)' % (self.struct_name, self.name))
568 return FieldMaxSize([self.tag, self.max_size, self.max_count],
570 ('%s.%s' % (self.struct_name, self.name)))
572 def encoded_size(self, dependencies):
573 '''Return the maximum size that this field can take when encoded,
574 including the field tag. If the size cannot be determined, returns
577 if self.allocation != 'STATIC':
580 if self.pbtype == 'MESSAGE':
582 if str(self.submsgname) in dependencies:
583 submsg = dependencies[str(self.submsgname)]
584 encsize = submsg.encoded_size(dependencies)
585 if encsize is not None:
586 # Include submessage length prefix
587 encsize += varint_max_size(encsize.upperlimit())
590 # Submessage or its size cannot be found.
591 # This can occur if submessage is defined in different
592 # file, and it or its .options could not be found.
593 # Instead of direct numeric value, reference the size that
594 # has been #defined in the other file.
595 encsize = EncodedSize(self.submsgname + 'size')
597 # We will have to make a conservative assumption on the length
598 # prefix size, though.
601 elif self.pbtype in ['ENUM', 'UENUM']:
602 if str(self.ctype) in dependencies:
603 enumtype = dependencies[str(self.ctype)]
604 encsize = enumtype.encoded_size()
606 # Conservative assumption
609 elif self.enc_size is None:
610 raise RuntimeError("Could not determine encoded size for %s.%s"
611 % (self.struct_name, self.name))
613 encsize = EncodedSize(self.enc_size)
615 encsize += varint_max_size(self.tag << 3) # Tag + wire type
617 if self.rules == 'REPEATED':
618 # Decoders must be always able to handle unpacked arrays.
619 # Therefore we have to reserve space for it, even though
620 # we emit packed arrays ourselves.
621 encsize *= self.max_count
626 class ExtensionRange(Field):
627 def __init__(self, struct_name, range_start, field_options):
628 '''Implements a special pb_extension_t* field in an extensible message
629 structure. The range_start signifies the index at which the extensions
630 start. Not necessarily all tags above this are extensions, it is merely
631 a speed optimization.
633 self.tag = range_start
634 self.struct_name = struct_name
635 self.name = 'extensions'
636 self.pbtype = 'EXTENSION'
637 self.rules = 'OPTIONAL'
638 self.allocation = 'CALLBACK'
639 self.ctype = 'pb_extension_t'
647 return ' pb_extension_t *extensions;'
655 def encoded_size(self, dependencies):
656 # We exclude extensions from the count, because they cannot be known
657 # until runtime. Other option would be to return None here, but this
658 # way the value remains useful if extensions are not used.
659 return EncodedSize(0)
661 class ExtensionField(Field):
662 def __init__(self, struct_name, desc, field_options):
663 self.fullname = struct_name + desc.name
664 self.extendee_name = names_from_type_name(desc.extendee)
665 Field.__init__(self, self.fullname + 'struct', desc, field_options)
667 if self.rules != 'OPTIONAL':
671 self.rules = 'OPTEXT'
674 '''Return the #define for the tag number of this field.'''
675 identifier = '%s_tag' % self.fullname
676 return '#define %-40s %d\n' % (identifier, self.tag)
678 def extension_decl(self):
679 '''Declaration of the extension type in the .pb.h file'''
681 msg = '/* Extension field %s was skipped because only "optional"\n' % self.fullname
682 msg +=' type of extension fields is currently supported. */\n'
685 return ('extern const pb_extension_type_t %s; /* field type: %s */\n' %
686 (self.fullname, str(self).strip()))
688 def extension_def(self):
689 '''Definition of the extension type in the .pb.c file'''
694 result = 'typedef struct {\n'
696 result += '\n} %s;\n\n' % self.struct_name
697 result += ('static const pb_field_t %s_field = \n %s;\n\n' %
698 (self.fullname, self.pb_field_t(None)))
699 result += 'const pb_extension_type_t %s = {\n' % self.fullname
702 result += ' &%s_field\n' % self.fullname
707 # ---------------------------------------------------------------------------
708 # Generation of oneofs (unions)
709 # ---------------------------------------------------------------------------
712 def __init__(self, struct_name, oneof_desc):
713 self.struct_name = struct_name
714 self.name = oneof_desc.name
716 self.pbtype = 'oneof'
718 self.allocation = 'ONEOF'
721 self.anonymous = False
724 def add_field(self, field):
725 if field.allocation == 'CALLBACK':
726 raise Exception("Callback fields inside of oneof are not supported"
727 + " (field %s)" % field.name)
729 field.union_name = self.name
730 field.rules = 'ONEOF'
731 field.anonymous = self.anonymous
732 self.fields.append(field)
733 self.fields.sort(key = lambda f: f.tag)
735 # Sort by the lowest tag number inside union
736 self.tag = min([f.tag for f in self.fields])
741 result += ' pb_size_t which_' + self.name + ";\n"
742 result += ' union {\n'
743 for f in self.fields:
744 result += ' ' + str(f).replace('\n', '\n ') + '\n'
748 result += ' } ' + self.name + ';'
752 return ''.join([f.types() for f in self.fields])
754 def get_dependencies(self):
756 for f in self.fields:
757 deps += f.get_dependencies()
760 def get_initializer(self, null_init):
761 return '0, {' + self.fields[0].get_initializer(null_init) + '}'
763 def default_decl(self, declaration_only = False):
767 return ''.join([f.tags() for f in self.fields])
769 def pb_field_t(self, prev_field_name):
770 result = ',\n'.join([f.pb_field_t(prev_field_name) for f in self.fields])
773 def get_last_field_name(self):
775 return self.fields[-1].name
777 return self.name + '.' + self.fields[-1].name
779 def largest_field_value(self):
780 largest = FieldMaxSize()
781 for f in self.fields:
782 largest.extend(f.largest_field_value())
785 def encoded_size(self, dependencies):
786 '''Returns the size of the largest oneof field.'''
787 largest = EncodedSize(0)
788 for f in self.fields:
789 size = EncodedSize(f.encoded_size(dependencies))
790 if size.value is None:
793 return None # Cannot resolve maximum of symbols
794 elif size.value > largest.value:
799 # ---------------------------------------------------------------------------
800 # Generation of messages (structures)
801 # ---------------------------------------------------------------------------
805 def __init__(self, names, desc, message_options):
811 if message_options.msgid:
812 self.msgid = message_options.msgid
814 if hasattr(desc, 'oneof_decl'):
815 for i, f in enumerate(desc.oneof_decl):
816 oneof_options = get_nanopb_suboptions(desc, message_options, self.name + f.name)
817 if oneof_options.no_unions:
818 no_unions.append(i) # No union, but add fields normally
819 elif oneof_options.type == nanopb_pb2.FT_IGNORE:
820 pass # No union and skip fields also
822 oneof = OneOf(self.name, f)
823 if oneof_options.anonymous_oneof:
824 oneof.anonymous = True
825 self.oneofs[i] = oneof
826 self.fields.append(oneof)
829 field_options = get_nanopb_suboptions(f, message_options, self.name + f.name)
830 if field_options.type == nanopb_pb2.FT_IGNORE:
833 field = Field(self.name, f, field_options)
834 if (hasattr(f, 'oneof_index') and
835 f.HasField('oneof_index') and
836 f.oneof_index not in no_unions):
837 if f.oneof_index in self.oneofs:
838 self.oneofs[f.oneof_index].add_field(field)
840 self.fields.append(field)
842 if len(desc.extension_range) > 0:
843 field_options = get_nanopb_suboptions(desc, message_options, self.name + 'extensions')
844 range_start = min([r.start for r in desc.extension_range])
845 if field_options.type != nanopb_pb2.FT_IGNORE:
846 self.fields.append(ExtensionRange(self.name, range_start, field_options))
848 self.packed = message_options.packed_struct
849 self.ordered_fields = self.fields[:]
850 self.ordered_fields.sort()
852 def get_dependencies(self):
853 '''Get list of type names that this structure refers to.'''
855 for f in self.fields:
856 deps += f.get_dependencies()
860 result = 'typedef struct _%s {\n' % self.name
862 if not self.ordered_fields:
863 # Empty structs are not allowed in C standard.
864 # Therefore add a dummy field if an empty message occurs.
865 result += ' char dummy_field;'
867 result += '\n'.join([str(f) for f in self.ordered_fields])
868 result += '\n/* @@protoc_insertion_point(struct:%s) */' % self.name
872 result += ' pb_packed'
874 result += ' %s;' % self.name
877 result = 'PB_PACKED_STRUCT_START\n' + result
878 result += '\nPB_PACKED_STRUCT_END'
883 return ''.join([f.types() for f in self.fields])
885 def get_initializer(self, null_init):
886 if not self.ordered_fields:
890 for field in self.ordered_fields:
891 parts.append(field.get_initializer(null_init))
892 return '{' + ', '.join(parts) + '}'
894 def default_decl(self, declaration_only = False):
896 for field in self.fields:
897 default = field.default_decl(declaration_only)
898 if default is not None:
899 result += default + '\n'
902 def count_required_fields(self):
903 '''Returns number of required fields inside this message'''
905 for f in self.fields:
906 if not isinstance(f, OneOf):
907 if f.rules == 'REQUIRED':
911 def count_all_fields(self):
913 for f in self.fields:
914 if isinstance(f, OneOf):
915 count += len(f.fields)
920 def fields_declaration(self):
921 result = 'extern const pb_field_t %s_fields[%d];' % (self.name, self.count_all_fields() + 1)
924 def fields_definition(self):
925 result = 'const pb_field_t %s_fields[%d] = {\n' % (self.name, self.count_all_fields() + 1)
928 for field in self.ordered_fields:
929 result += field.pb_field_t(prev)
931 prev = field.get_last_field_name()
933 result += ' PB_LAST_FIELD\n};'
936 def encoded_size(self, dependencies):
937 '''Return the maximum size that this message can take when encoded.
938 If the size cannot be determined, returns None.
940 size = EncodedSize(0)
941 for field in self.fields:
942 fsize = field.encoded_size(dependencies)
950 # ---------------------------------------------------------------------------
951 # Processing of entire .proto files
952 # ---------------------------------------------------------------------------
954 def iterate_messages(desc, names = Names()):
955 '''Recursively find all messages. For each, yield name, DescriptorProto.'''
956 if hasattr(desc, 'message_type'):
957 submsgs = desc.message_type
959 submsgs = desc.nested_type
961 for submsg in submsgs:
962 sub_names = names + submsg.name
963 yield sub_names, submsg
965 for x in iterate_messages(submsg, sub_names):
968 def iterate_extensions(desc, names = Names()):
969 '''Recursively find all extensions.
970 For each, yield name, FieldDescriptorProto.
972 for extension in desc.extension:
973 yield names, extension
975 for subname, subdesc in iterate_messages(desc, names):
976 for extension in subdesc.extension:
977 yield subname, extension
981 From http://code.activestate.com/recipes/577413-topological-sort/
982 This function is under the MIT license.
984 for k, v in list(data.items()):
985 v.discard(k) # Ignore self dependencies
986 extra_items_in_deps = reduce(set.union, list(data.values()), set()) - set(data.keys())
987 data.update(dict([(item, set()) for item in extra_items_in_deps]))
989 ordered = set(item for item,dep in list(data.items()) if not dep)
992 for item in sorted(ordered):
994 data = dict([(item, (dep - ordered)) for item,dep in list(data.items())
995 if item not in ordered])
996 assert not data, "A cyclic dependency exists amongst %r" % data
998 def sort_dependencies(messages):
999 '''Sort a list of Messages based on dependencies.'''
1001 message_by_name = {}
1002 for message in messages:
1003 dependencies[str(message.name)] = set(message.get_dependencies())
1004 message_by_name[str(message.name)] = message
1006 for msgname in toposort2(dependencies):
1007 if msgname in message_by_name:
1008 yield message_by_name[msgname]
1010 def make_identifier(headername):
1011 '''Make #ifndef identifier that contains uppercase A-Z and digits 0-9'''
1013 for c in headername.upper():
1021 def __init__(self, fdesc, file_options):
1022 '''Takes a FileDescriptorProto and parses it.'''
1024 self.file_options = file_options
1025 self.dependencies = {}
1028 # Some of types used in this file probably come from the file itself.
1029 # Thus it has implicit dependency on itself.
1030 self.add_dependency(self)
1035 self.extensions = []
1037 if self.fdesc.package:
1038 base_name = Names(self.fdesc.package.split('.'))
1042 for enum in self.fdesc.enum_type:
1043 enum_options = get_nanopb_suboptions(enum, self.file_options, base_name + enum.name)
1044 self.enums.append(Enum(base_name, enum, enum_options))
1046 for names, message in iterate_messages(self.fdesc, base_name):
1047 message_options = get_nanopb_suboptions(message, self.file_options, names)
1049 if message_options.skip_message:
1052 self.messages.append(Message(names, message, message_options))
1053 for enum in message.enum_type:
1054 enum_options = get_nanopb_suboptions(enum, message_options, names + enum.name)
1055 self.enums.append(Enum(names, enum, enum_options))
1057 for names, extension in iterate_extensions(self.fdesc, base_name):
1058 field_options = get_nanopb_suboptions(extension, self.file_options, names + extension.name)
1059 if field_options.type != nanopb_pb2.FT_IGNORE:
1060 self.extensions.append(ExtensionField(names, extension, field_options))
1062 def add_dependency(self, other):
1063 for enum in other.enums:
1064 self.dependencies[str(enum.names)] = enum
1066 for msg in other.messages:
1067 self.dependencies[str(msg.name)] = msg
1069 # Fix field default values where enum short names are used.
1070 for enum in other.enums:
1071 if not enum.options.long_names:
1072 for message in self.messages:
1073 for field in message.fields:
1074 if field.default in enum.value_longnames:
1075 idx = enum.value_longnames.index(field.default)
1076 field.default = enum.values[idx][0]
1078 # Fix field data types where enums have negative values.
1079 for enum in other.enums:
1080 if not enum.has_negative():
1081 for message in self.messages:
1082 for field in message.fields:
1083 if field.pbtype == 'ENUM' and field.ctype == enum.names:
1084 field.pbtype = 'UENUM'
1086 def generate_header(self, includes, headername, options):
1087 '''Generate content for a header file.
1088 Generates strings, which should be concatenated and stored to file.
1091 yield '/* Automatically generated nanopb header */\n'
1092 if options.notimestamp:
1093 yield '/* Generated by %s */\n\n' % (nanopb_version)
1095 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
1097 if self.fdesc.package:
1098 symbol = make_identifier(self.fdesc.package + '_' + headername)
1100 symbol = make_identifier(headername)
1101 yield '#ifndef PB_%s_INCLUDED\n' % symbol
1102 yield '#define PB_%s_INCLUDED\n' % symbol
1104 yield options.libformat % ('pb.h')
1106 # no %s specified - use whatever was passed in as options.libformat
1107 yield options.libformat
1110 for incfile in includes:
1111 noext = os.path.splitext(incfile)[0]
1112 yield options.genformat % (noext + options.extension + '.h')
1115 yield '/* @@protoc_insertion_point(includes) */\n'
1117 yield '#if PB_PROTO_HEADER_VERSION != 30\n'
1118 yield '#error Regenerate this file with the current version of nanopb generator.\n'
1122 yield '#ifdef __cplusplus\n'
1123 yield 'extern "C" {\n'
1127 yield '/* Enum definitions */\n'
1128 for enum in self.enums:
1129 yield str(enum) + '\n\n'
1132 yield '/* Struct definitions */\n'
1133 for msg in sort_dependencies(self.messages):
1135 yield str(msg) + '\n\n'
1138 yield '/* Extensions */\n'
1139 for extension in self.extensions:
1140 yield extension.extension_decl()
1144 yield '/* Default values for struct fields */\n'
1145 for msg in self.messages:
1146 yield msg.default_decl(True)
1149 yield '/* Initializer values for message structs */\n'
1150 for msg in self.messages:
1151 identifier = '%s_init_default' % msg.name
1152 yield '#define %-40s %s\n' % (identifier, msg.get_initializer(False))
1153 for msg in self.messages:
1154 identifier = '%s_init_zero' % msg.name
1155 yield '#define %-40s %s\n' % (identifier, msg.get_initializer(True))
1158 yield '/* Field tags (for use in manual encoding/decoding) */\n'
1159 for msg in sort_dependencies(self.messages):
1160 for field in msg.fields:
1162 for extension in self.extensions:
1163 yield extension.tags()
1166 yield '/* Struct field encoding specification for nanopb */\n'
1167 for msg in self.messages:
1168 yield msg.fields_declaration() + '\n'
1171 yield '/* Maximum encoded size of messages (where known) */\n'
1172 for msg in self.messages:
1173 msize = msg.encoded_size(self.dependencies)
1174 identifier = '%s_size' % msg.name
1175 if msize is not None:
1176 yield '#define %-40s %s\n' % (identifier, msize)
1178 yield '/* %s depends on runtime parameters */\n' % identifier
1181 yield '/* Message IDs (where set with "msgid" option) */\n'
1183 yield '#ifdef PB_MSGID\n'
1184 for msg in self.messages:
1185 if hasattr(msg,'msgid'):
1186 yield '#define PB_MSG_%d %s\n' % (msg.msgid, msg.name)
1189 symbol = make_identifier(headername.split('.')[0])
1190 yield '#define %s_MESSAGES \\\n' % symbol
1192 for msg in self.messages:
1194 msize = msg.encoded_size(self.dependencies)
1195 if msize is not None:
1197 if hasattr(msg,'msgid'):
1198 yield '\tPB_MSG(%d,%s,%s) \\\n' % (msg.msgid, m, msg.name)
1201 for msg in self.messages:
1202 if hasattr(msg,'msgid'):
1203 yield '#define %s_msgid %d\n' % (msg.name, msg.msgid)
1208 yield '#ifdef __cplusplus\n'
1209 yield '} /* extern "C" */\n'
1213 yield '/* @@protoc_insertion_point(eof) */\n'
1216 def generate_source(self, headername, options):
1217 '''Generate content for a source file.'''
1219 yield '/* Automatically generated nanopb constant definitions */\n'
1220 if options.notimestamp:
1221 yield '/* Generated by %s */\n\n' % (nanopb_version)
1223 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
1224 yield options.genformat % (headername)
1226 yield '/* @@protoc_insertion_point(includes) */\n'
1228 yield '#if PB_PROTO_HEADER_VERSION != 30\n'
1229 yield '#error Regenerate this file with the current version of nanopb generator.\n'
1233 for msg in self.messages:
1234 yield msg.default_decl(False)
1238 for msg in self.messages:
1239 yield msg.fields_definition() + '\n\n'
1241 for ext in self.extensions:
1242 yield ext.extension_def() + '\n'
1244 for enum in self.enums:
1245 yield enum.enum_to_string_definition() + '\n'
1247 # Add checks for numeric limits
1249 largest_msg = max(self.messages, key = lambda m: m.count_required_fields())
1250 largest_count = largest_msg.count_required_fields()
1251 if largest_count > 64:
1252 yield '\n/* Check that missing required fields will be properly detected */\n'
1253 yield '#if PB_MAX_REQUIRED_FIELDS < %d\n' % largest_count
1254 yield '#error Properly detecting missing required fields in %s requires \\\n' % largest_msg.name
1255 yield ' setting PB_MAX_REQUIRED_FIELDS to %d or more.\n' % largest_count
1258 max_field = FieldMaxSize()
1259 checks_msgnames = []
1260 for msg in self.messages:
1261 checks_msgnames.append(msg.name)
1262 for field in msg.fields:
1263 max_field.extend(field.largest_field_value())
1265 worst = max_field.worst
1266 worst_field = max_field.worst_field
1267 checks = max_field.checks
1269 if worst > 255 or checks:
1270 yield '\n/* Check that field information fits in pb_field_t */\n'
1272 if worst > 65535 or checks:
1273 yield '#if !defined(PB_FIELD_32BIT)\n'
1275 yield '#error Field descriptor for %s is too large. Define PB_FIELD_32BIT to fix this.\n' % worst_field
1277 assertion = ' && '.join(str(c) + ' < 65536' for c in checks)
1278 msgs = '_'.join(str(n) for n in checks_msgnames)
1279 yield '/* If you get an error here, it means that you need to define PB_FIELD_32BIT\n'
1280 yield ' * compile-time option. You can do that in pb.h or on compiler command line.\n'
1282 yield ' * The reason you need to do this is that some of your messages contain tag\n'
1283 yield ' * numbers or field sizes that are larger than what can fit in 8 or 16 bit\n'
1284 yield ' * field descriptors.\n'
1286 yield 'PB_STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
1290 yield '#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT)\n'
1292 yield '#error Field descriptor for %s is too large. Define PB_FIELD_16BIT to fix this.\n' % worst_field
1294 assertion = ' && '.join(str(c) + ' < 256' for c in checks)
1295 msgs = '_'.join(str(n) for n in checks_msgnames)
1296 yield '/* If you get an error here, it means that you need to define PB_FIELD_16BIT\n'
1297 yield ' * compile-time option. You can do that in pb.h or on compiler command line.\n'
1299 yield ' * The reason you need to do this is that some of your messages contain tag\n'
1300 yield ' * numbers or field sizes that are larger than what can fit in the default\n'
1301 yield ' * 8 bit descriptors.\n'
1303 yield 'PB_STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
1306 # Add check for sizeof(double)
1308 for msg in self.messages:
1309 for field in msg.fields:
1310 if field.ctype == 'double':
1315 yield '/* On some platforms (such as AVR), double is really float.\n'
1316 yield ' * These are not directly supported by nanopb, but see example_avr_double.\n'
1317 yield ' * To get rid of this error, remove any double fields from your .proto.\n'
1319 yield 'PB_STATIC_ASSERT(sizeof(double) == 8, DOUBLE_MUST_BE_8_BYTES)\n'
1322 yield '/* @@protoc_insertion_point(eof) */\n'
1324 # ---------------------------------------------------------------------------
1325 # Options parsing for the .proto files
1326 # ---------------------------------------------------------------------------
1328 from fnmatch import fnmatch
1330 def read_options_file(infile):
1331 '''Parse a separate options file to list:
1332 [(namemask, options), ...]
1335 data = infile.read()
1336 data = re.sub('/\*.*?\*/', '', data, flags = re.MULTILINE)
1337 data = re.sub('//.*?$', '', data, flags = re.MULTILINE)
1338 data = re.sub('#.*?$', '', data, flags = re.MULTILINE)
1339 for i, line in enumerate(data.split('\n')):
1344 parts = line.split(None, 1)
1347 sys.stderr.write("%s:%d: " % (infile.name, i + 1) +
1348 "Option lines should have space between field name and options. " +
1349 "Skipping line: '%s'\n" % line)
1352 opts = nanopb_pb2.NanoPBOptions()
1355 text_format.Merge(parts[1], opts)
1356 except Exception as e:
1357 sys.stderr.write("%s:%d: " % (infile.name, i + 1) +
1358 "Unparseable option line: '%s'. " % line +
1359 "Error: %s\n" % str(e))
1361 results.append((parts[0], opts))
1366 '''Ugly global variables, should find a good way to pass these.'''
1367 verbose_options = False
1368 separate_options = []
1369 matched_namemasks = set()
1371 def get_nanopb_suboptions(subdesc, options, name):
1372 '''Get copy of options, and merge information from subdesc.'''
1373 new_options = nanopb_pb2.NanoPBOptions()
1374 new_options.CopyFrom(options)
1376 # Handle options defined in a separate file
1377 dotname = '.'.join(name.parts)
1378 for namemask, options in Globals.separate_options:
1379 if fnmatch(dotname, namemask):
1380 Globals.matched_namemasks.add(namemask)
1381 new_options.MergeFrom(options)
1383 if hasattr(subdesc, 'syntax') and subdesc.syntax == "proto3":
1384 new_options.proto3 = True
1386 # Handle options defined in .proto
1387 if isinstance(subdesc.options, descriptor.FieldOptions):
1388 ext_type = nanopb_pb2.nanopb
1389 elif isinstance(subdesc.options, descriptor.FileOptions):
1390 ext_type = nanopb_pb2.nanopb_fileopt
1391 elif isinstance(subdesc.options, descriptor.MessageOptions):
1392 ext_type = nanopb_pb2.nanopb_msgopt
1393 elif isinstance(subdesc.options, descriptor.EnumOptions):
1394 ext_type = nanopb_pb2.nanopb_enumopt
1396 raise Exception("Unknown options type")
1398 if subdesc.options.HasExtension(ext_type):
1399 ext = subdesc.options.Extensions[ext_type]
1400 new_options.MergeFrom(ext)
1402 if Globals.verbose_options:
1403 sys.stderr.write("Options for " + dotname + ": ")
1404 sys.stderr.write(text_format.MessageToString(new_options) + "\n")
1409 # ---------------------------------------------------------------------------
1410 # Command line interface
1411 # ---------------------------------------------------------------------------
1415 from optparse import OptionParser
1417 optparser = OptionParser(
1418 usage = "Usage: nanopb_generator.py [options] file.pb ...",
1419 epilog = "Compile file.pb from file.proto by: 'protoc -ofile.pb file.proto'. " +
1420 "Output will be written to file.pb.h and file.pb.c.")
1421 optparser.add_option("-x", dest="exclude", metavar="FILE", action="append", default=[],
1422 help="Exclude file from generated #include list.")
1423 optparser.add_option("-e", "--extension", dest="extension", metavar="EXTENSION", default=".pb",
1424 help="Set extension to use instead of '.pb' for generated files. [default: %default]")
1425 optparser.add_option("-f", "--options-file", dest="options_file", metavar="FILE", default="%s.options",
1426 help="Set name of a separate generator options file.")
1427 optparser.add_option("-I", "--options-path", dest="options_path", metavar="DIR",
1428 action="append", default = [],
1429 help="Search for .options files additionally in this path")
1430 optparser.add_option("-D", "--output-dir", dest="output_dir",
1431 metavar="OUTPUTDIR", default=None,
1432 help="Output directory of .pb.h and .pb.c files")
1433 optparser.add_option("-Q", "--generated-include-format", dest="genformat",
1434 metavar="FORMAT", default='#include "%s"\n',
1435 help="Set format string to use for including other .pb.h files. [default: %default]")
1436 optparser.add_option("-L", "--library-include-format", dest="libformat",
1437 metavar="FORMAT", default='#include <%s>\n',
1438 help="Set format string to use for including the nanopb pb.h header. [default: %default]")
1439 optparser.add_option("-T", "--no-timestamp", dest="notimestamp", action="store_true", default=False,
1440 help="Don't add timestamp to .pb.h and .pb.c preambles")
1441 optparser.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False,
1442 help="Don't print anything except errors.")
1443 optparser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
1444 help="Print more information.")
1445 optparser.add_option("-s", dest="settings", metavar="OPTION:VALUE", action="append", default=[],
1446 help="Set generator option (max_size, max_count etc.).")
1448 def parse_file(filename, fdesc, options):
1449 '''Parse a single file. Returns a ProtoFile instance.'''
1450 toplevel_options = nanopb_pb2.NanoPBOptions()
1451 for s in options.settings:
1452 text_format.Merge(s, toplevel_options)
1455 data = open(filename, 'rb').read()
1456 fdesc = descriptor.FileDescriptorSet.FromString(data).file[0]
1458 # Check if there is a separate .options file
1461 optfilename = options.options_file % os.path.splitext(filename)[0]
1463 # No %s specified, use the filename as-is
1464 optfilename = options.options_file
1467 paths = ['.'] + options.options_path
1469 if os.path.isfile(os.path.join(p, optfilename)):
1470 optfilename = os.path.join(p, optfilename)
1472 sys.stderr.write('Reading options from ' + optfilename + '\n')
1473 Globals.separate_options = read_options_file(open(optfilename, "rU"))
1476 # If we are given a full filename and it does not exist, give an error.
1477 # However, don't give error when we automatically look for .options file
1478 # with the same name as .proto.
1479 if options.verbose or had_abspath:
1480 sys.stderr.write('Options file not found: ' + optfilename + '\n')
1481 Globals.separate_options = []
1483 Globals.matched_namemasks = set()
1486 file_options = get_nanopb_suboptions(fdesc, toplevel_options, Names([filename]))
1487 f = ProtoFile(fdesc, file_options)
1488 f.optfilename = optfilename
1492 def process_file(filename, fdesc, options, other_files = {}):
1493 '''Process a single file.
1494 filename: The full path to the .proto or .pb source file, as string.
1495 fdesc: The loaded FileDescriptorSet, or None to read from the input file.
1496 options: Command line options as they come from OptionsParser.
1499 {'headername': Name of header file,
1500 'headerdata': Data for the .h header file,
1501 'sourcename': Name of the source code file,
1502 'sourcedata': Data for the .c source code file
1505 f = parse_file(filename, fdesc, options)
1507 # Provide dependencies if available
1508 for dep in f.fdesc.dependency:
1509 if dep in other_files:
1510 f.add_dependency(other_files[dep])
1512 # Decide the file names
1513 noext = os.path.splitext(filename)[0]
1514 headername = noext + options.extension + '.h'
1515 sourcename = noext + options.extension + '.c'
1516 headerbasename = os.path.basename(headername)
1518 # List of .proto files that should not be included in the C header file
1519 # even if they are mentioned in the source .proto.
1520 excludes = ['nanopb.proto', 'google/protobuf/descriptor.proto'] + options.exclude
1521 includes = [d for d in f.fdesc.dependency if d not in excludes]
1523 headerdata = ''.join(f.generate_header(includes, headerbasename, options))
1524 sourcedata = ''.join(f.generate_source(headerbasename, options))
1526 # Check if there were any lines in .options that did not match a member
1527 unmatched = [n for n,o in Globals.separate_options if n not in Globals.matched_namemasks]
1528 if unmatched and not options.quiet:
1529 sys.stderr.write("Following patterns in " + f.optfilename + " did not match any fields: "
1530 + ', '.join(unmatched) + "\n")
1531 if not Globals.verbose_options:
1532 sys.stderr.write("Use protoc --nanopb-out=-v:. to see a list of the field names.\n")
1534 return {'headername': headername, 'headerdata': headerdata,
1535 'sourcename': sourcename, 'sourcedata': sourcedata}
1538 '''Main function when invoked directly from the command line.'''
1540 options, filenames = optparser.parse_args()
1543 optparser.print_help()
1547 options.verbose = False
1549 if options.output_dir and not os.path.exists(options.output_dir):
1550 optparser.print_help()
1551 sys.stderr.write("\noutput_dir does not exist: %s\n" % options.output_dir)
1555 Globals.verbose_options = options.verbose
1556 for filename in filenames:
1557 results = process_file(filename, None, options)
1559 base_dir = options.output_dir or ''
1561 (os.path.join(base_dir, results['headername']), results['headerdata']),
1562 (os.path.join(base_dir, results['sourcename']), results['sourcedata']),
1565 if not options.quiet:
1566 paths = " and ".join([x[0] for x in to_write])
1567 sys.stderr.write("Writing to %s\n" % paths)
1569 for path, data in to_write:
1570 with open(path, 'w') as f:
1574 '''Main function when invoked as a protoc plugin.'''
1577 if sys.platform == "win32":
1579 # Set stdin and stdout to binary mode
1580 msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
1581 msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
1583 data = io.open(sys.stdin.fileno(), "rb").read()
1585 request = plugin_pb2.CodeGeneratorRequest.FromString(data)
1588 # Versions of Python prior to 2.7.3 do not support unicode
1589 # input to shlex.split(). Try to convert to str if possible.
1590 params = str(request.parameter)
1591 except UnicodeEncodeError:
1592 params = request.parameter
1595 args = shlex.split(params)
1596 options, dummy = optparser.parse_args(args)
1598 Globals.verbose_options = options.verbose
1600 response = plugin_pb2.CodeGeneratorResponse()
1602 # Google's protoc does not currently indicate the full path of proto files.
1603 # Instead always add the main file path to the search dirs, that works for
1606 options.options_path.append(os.path.dirname(request.file_to_generate[0]))
1608 # Process any include files first, in order to have them
1609 # available as dependencies
1611 for fdesc in request.proto_file:
1612 other_files[fdesc.name] = parse_file(fdesc.name, fdesc, options)
1614 for filename in request.file_to_generate:
1615 for fdesc in request.proto_file:
1616 if fdesc.name == filename:
1617 results = process_file(filename, fdesc, options, other_files)
1619 f = response.file.add()
1620 f.name = results['headername']
1621 f.content = results['headerdata']
1623 f = response.file.add()
1624 f.name = results['sourcename']
1625 f.content = results['sourcedata']
1627 io.open(sys.stdout.fileno(), "wb").write(response.SerializeToString())
1629 if __name__ == '__main__':
1630 # Check if we are running as a plugin under protoc
1631 if 'protoc-gen-' in sys.argv[0] or '--protoc-plugin' in sys.argv: