3 '''Generate header file for nanopb from a ProtoBuf FileDescriptorSet.'''
4 nanopb_version = "nanopb-0.3.2-dev"
9 # Add some dummy imports to keep packaging tools happy.
10 import google, distutils.util # bbfreeze seems to need these
11 import pkg_resources # pyinstaller / protobuf 2.5 seem to need these
13 # Don't care, we will error out later if it is actually important.
17 import google.protobuf.text_format as text_format
18 import google.protobuf.descriptor_pb2 as descriptor
21 *************************************************************
22 *** Could not import the Google protobuf Python libraries ***
23 *** Try installing package 'python-protobuf' or similar. ***
24 *************************************************************
29 import proto.nanopb_pb2 as nanopb_pb2
30 import proto.plugin_pb2 as plugin_pb2
33 ********************************************************************
34 *** Failed to import the protocol definitions for generator. ***
35 *** You have to run 'make' in the nanopb/generator/proto folder. ***
36 ********************************************************************
40 # ---------------------------------------------------------------------------
41 # Generation of single fields
42 # ---------------------------------------------------------------------------
47 # Values are tuple (c type, pb type, encoded size, int_size_allowed)
48 FieldD = descriptor.FieldDescriptorProto
50 FieldD.TYPE_BOOL: ('bool', 'BOOL', 1, False),
51 FieldD.TYPE_DOUBLE: ('double', 'DOUBLE', 8, False),
52 FieldD.TYPE_FIXED32: ('uint32_t', 'FIXED32', 4, False),
53 FieldD.TYPE_FIXED64: ('uint64_t', 'FIXED64', 8, False),
54 FieldD.TYPE_FLOAT: ('float', 'FLOAT', 4, False),
55 FieldD.TYPE_INT32: ('int32_t', 'INT32', 10, True),
56 FieldD.TYPE_INT64: ('int64_t', 'INT64', 10, True),
57 FieldD.TYPE_SFIXED32: ('int32_t', 'SFIXED32', 4, False),
58 FieldD.TYPE_SFIXED64: ('int64_t', 'SFIXED64', 8, False),
59 FieldD.TYPE_SINT32: ('int32_t', 'SINT32', 5, True),
60 FieldD.TYPE_SINT64: ('int64_t', 'SINT64', 10, True),
61 FieldD.TYPE_UINT32: ('uint32_t', 'UINT32', 5, True),
62 FieldD.TYPE_UINT64: ('uint64_t', 'UINT64', 10, True)
65 # Integer size overrides (from .proto settings)
67 nanopb_pb2.IS_8: 'int8_t',
68 nanopb_pb2.IS_16: 'int16_t',
69 nanopb_pb2.IS_32: 'int32_t',
70 nanopb_pb2.IS_64: 'int64_t',
74 '''Keeps a set of nested names and formats them to C identifier.'''
75 def __init__(self, parts = ()):
76 if isinstance(parts, Names):
78 self.parts = tuple(parts)
81 return '_'.join(self.parts)
83 def __add__(self, other):
84 if isinstance(other, (str, unicode)):
85 return Names(self.parts + (other,))
86 elif isinstance(other, tuple):
87 return Names(self.parts + other)
89 raise ValueError("Name parts should be of type str")
91 def __eq__(self, other):
92 return isinstance(other, Names) and self.parts == other.parts
94 def names_from_type_name(type_name):
95 '''Parse Names() from FieldDescriptorProto type_name'''
96 if type_name[0] != '.':
97 raise NotImplementedError("Lookup of non-absolute type names is not supported")
98 return Names(type_name[1:].split('.'))
100 def varint_max_size(max_value):
101 '''Returns the maximum number of bytes a varint can take when encoded.'''
102 for i in range(1, 11):
103 if (max_value >> (i * 7)) == 0:
105 raise ValueError("Value too large for varint: " + str(max_value))
107 assert varint_max_size(0) == 1
108 assert varint_max_size(127) == 1
109 assert varint_max_size(128) == 2
112 '''Class used to represent the encoded size of a field or a message.
113 Consists of a combination of symbolic sizes and integer sizes.'''
114 def __init__(self, value = 0, symbols = []):
115 if isinstance(value, (str, Names)):
116 symbols = [str(value)]
119 self.symbols = symbols
121 def __add__(self, other):
122 if isinstance(other, (int, long)):
123 return EncodedSize(self.value + other, self.symbols)
124 elif isinstance(other, (str, Names)):
125 return EncodedSize(self.value, self.symbols + [str(other)])
126 elif isinstance(other, EncodedSize):
127 return EncodedSize(self.value + other.value, self.symbols + other.symbols)
129 raise ValueError("Cannot add size: " + repr(other))
131 def __mul__(self, other):
132 if isinstance(other, (int, long)):
133 return EncodedSize(self.value * other, [str(other) + '*' + s for s in self.symbols])
135 raise ValueError("Cannot multiply size: " + repr(other))
139 return str(self.value)
141 return '(' + str(self.value) + ' + ' + ' + '.join(self.symbols) + ')'
143 def upperlimit(self):
150 def __init__(self, names, desc, enum_options):
151 '''desc is EnumDescriptorProto'''
153 self.options = enum_options
154 self.names = names + desc.name
156 if enum_options.long_names:
157 self.values = [(self.names + x.name, x.number) for x in desc.value]
159 self.values = [(names + x.name, x.number) for x in desc.value]
161 self.value_longnames = [self.names + x.name for x in desc.value]
164 result = 'typedef enum _%s {\n' % self.names
165 result += ',\n'.join([" %s = %d" % x for x in self.values])
166 result += '\n} %s;' % self.names
170 def __init__(self, struct_name, desc, field_options):
171 '''desc is FieldDescriptorProto'''
172 self.tag = desc.number
173 self.struct_name = struct_name
174 self.name = desc.name
177 self.max_count = None
182 # Parse field options
183 if field_options.HasField("max_size"):
184 self.max_size = field_options.max_size
186 if field_options.HasField("max_count"):
187 self.max_count = field_options.max_count
189 if desc.HasField('default_value'):
190 self.default = desc.default_value
192 # Check field rules, i.e. required/optional/repeated.
194 if desc.label == FieldD.LABEL_REQUIRED:
195 self.rules = 'REQUIRED'
196 elif desc.label == FieldD.LABEL_OPTIONAL:
197 self.rules = 'OPTIONAL'
198 elif desc.label == FieldD.LABEL_REPEATED:
199 self.rules = 'REPEATED'
200 if self.max_count is None:
201 can_be_static = False
203 self.array_decl = '[%d]' % self.max_count
205 raise NotImplementedError(desc.label)
207 # Check if the field can be implemented with static allocation
208 # i.e. whether the data size is known.
209 if desc.type == FieldD.TYPE_STRING and self.max_size is None:
210 can_be_static = False
212 if desc.type == FieldD.TYPE_BYTES and self.max_size is None:
213 can_be_static = False
215 # Decide how the field data will be allocated
216 if field_options.type == nanopb_pb2.FT_DEFAULT:
218 field_options.type = nanopb_pb2.FT_STATIC
220 field_options.type = nanopb_pb2.FT_CALLBACK
222 if field_options.type == nanopb_pb2.FT_STATIC and not can_be_static:
223 raise Exception("Field %s is defined as static, but max_size or "
224 "max_count is not given." % self.name)
226 if field_options.type == nanopb_pb2.FT_STATIC:
227 self.allocation = 'STATIC'
228 elif field_options.type == nanopb_pb2.FT_POINTER:
229 self.allocation = 'POINTER'
230 elif field_options.type == nanopb_pb2.FT_CALLBACK:
231 self.allocation = 'CALLBACK'
233 raise NotImplementedError(field_options.type)
235 # Decide the C data type to use in the struct.
236 if datatypes.has_key(desc.type):
237 self.ctype, self.pbtype, self.enc_size, isa = datatypes[desc.type]
239 # Override the field size if user wants to use smaller integers
240 if isa and field_options.int_size != nanopb_pb2.IS_DEFAULT:
241 self.ctype = intsizes[field_options.int_size]
242 if desc.type == FieldD.TYPE_UINT32 or desc.type == FieldD.TYPE_UINT64:
243 self.ctype = 'u' + self.ctype;
244 elif desc.type == FieldD.TYPE_ENUM:
246 self.ctype = names_from_type_name(desc.type_name)
247 if self.default is not None:
248 self.default = self.ctype + self.default
249 self.enc_size = 5 # protoc rejects enum values > 32 bits
250 elif desc.type == FieldD.TYPE_STRING:
251 self.pbtype = 'STRING'
253 if self.allocation == 'STATIC':
255 self.array_decl += '[%d]' % self.max_size
256 self.enc_size = varint_max_size(self.max_size) + self.max_size
257 elif desc.type == FieldD.TYPE_BYTES:
258 self.pbtype = 'BYTES'
259 if self.allocation == 'STATIC':
260 self.ctype = self.struct_name + self.name + 't'
261 self.enc_size = varint_max_size(self.max_size) + self.max_size
262 elif self.allocation == 'POINTER':
263 self.ctype = 'pb_bytes_array_t'
264 elif desc.type == FieldD.TYPE_MESSAGE:
265 self.pbtype = 'MESSAGE'
266 self.ctype = self.submsgname = names_from_type_name(desc.type_name)
267 self.enc_size = None # Needs to be filled in after the message type is available
269 raise NotImplementedError(desc.type)
271 def __cmp__(self, other):
272 return cmp(self.tag, other.tag)
276 if self.allocation == 'POINTER':
277 if self.rules == 'REPEATED':
278 result += ' pb_size_t ' + self.name + '_count;\n'
280 if self.pbtype == 'MESSAGE':
281 # Use struct definition, so recursive submessages are possible
282 result += ' struct _%s *%s;' % (self.ctype, self.name)
283 elif self.rules == 'REPEATED' and self.pbtype in ['STRING', 'BYTES']:
284 # String/bytes arrays need to be defined as pointers to pointers
285 result += ' %s **%s;' % (self.ctype, self.name)
287 result += ' %s *%s;' % (self.ctype, self.name)
288 elif self.allocation == 'CALLBACK':
289 result += ' pb_callback_t %s;' % self.name
291 if self.rules == 'OPTIONAL' and self.allocation == 'STATIC':
292 result += ' bool has_' + self.name + ';\n'
293 elif self.rules == 'REPEATED' and self.allocation == 'STATIC':
294 result += ' pb_size_t ' + self.name + '_count;\n'
295 result += ' %s %s%s;' % (self.ctype, self.name, self.array_decl)
299 '''Return definitions for any special types this field might need.'''
300 if self.pbtype == 'BYTES' and self.allocation == 'STATIC':
301 result = 'typedef PB_BYTES_ARRAY_T(%d) %s;\n' % (self.max_size, self.ctype)
306 def get_initializer(self, null_init):
307 '''Return literal expression for this field's default value.'''
309 if self.pbtype == 'MESSAGE':
311 return '%s_init_zero' % self.ctype
313 return '%s_init_default' % self.ctype
315 if self.default is None or null_init:
316 if self.pbtype == 'STRING':
318 elif self.pbtype == 'BYTES':
320 elif self.pbtype == 'ENUM':
321 return '(%s)0' % self.ctype
325 default = str(self.default)
327 if self.pbtype == 'STRING':
328 default = default.encode('utf-8').encode('string_escape')
329 default = default.replace('"', '\\"')
330 default = '"' + default + '"'
331 elif self.pbtype == 'BYTES':
332 data = default.decode('string_escape')
333 data = ['0x%02x' % ord(c) for c in data]
337 default = '{%d, {%s}}' % (len(data), ','.join(data))
338 elif self.pbtype in ['FIXED32', 'UINT32']:
340 elif self.pbtype in ['FIXED64', 'UINT64']:
342 elif self.pbtype in ['SFIXED64', 'INT64']:
347 def default_decl(self, declaration_only = False):
348 '''Return definition for this field's default value.'''
349 if self.default is None:
353 default = self.get_initializer(False)
356 if self.pbtype == 'STRING':
357 if self.allocation != 'STATIC':
358 return None # Not implemented
359 array_decl = '[%d]' % self.max_size
360 elif self.pbtype == 'BYTES':
361 if self.allocation != 'STATIC':
362 return None # Not implemented
365 return 'extern const %s %s_default%s;' % (ctype, self.struct_name + self.name, array_decl)
367 return 'const %s %s_default%s = %s;' % (ctype, self.struct_name + self.name, array_decl, default)
370 '''Return the #define for the tag number of this field.'''
371 identifier = '%s_%s_tag' % (self.struct_name, self.name)
372 return '#define %-40s %d\n' % (identifier, self.tag)
374 def pb_field_t(self, prev_field_name):
375 '''Return the pb_field_t initializer to use in the constant array.
376 prev_field_name is the name of the previous field or None.
378 result = ' PB_FIELD(%3d, ' % self.tag
379 result += '%-8s, ' % self.pbtype
380 result += '%s, ' % self.rules
381 result += '%-8s, ' % self.allocation
382 result += '%s, ' % ("FIRST" if not prev_field_name else "OTHER")
383 result += '%s, ' % self.struct_name
384 result += '%s, ' % self.name
385 result += '%s, ' % (prev_field_name or self.name)
387 if self.pbtype == 'MESSAGE':
388 result += '&%s_fields)' % self.submsgname
389 elif self.default is None:
391 elif self.pbtype in ['BYTES', 'STRING'] and self.allocation != 'STATIC':
392 result += '0)' # Arbitrary size default values not implemented
393 elif self.rules == 'OPTEXT':
394 result += '0)' # Default value for extensions is not implemented
396 result += '&%s_default)' % (self.struct_name + self.name)
400 def largest_field_value(self):
401 '''Determine if this field needs 16bit or 32bit pb_field_t structure to compile properly.
402 Returns numeric value or a C-expression for assert.'''
403 if self.pbtype == 'MESSAGE':
404 if self.rules == 'REPEATED' and self.allocation == 'STATIC':
405 return 'pb_membersize(%s, %s[0])' % (self.struct_name, self.name)
407 return 'pb_membersize(%s, %s)' % (self.struct_name, self.name)
409 return max(self.tag, self.max_size, self.max_count)
411 def encoded_size(self, allmsgs):
412 '''Return the maximum size that this field can take when encoded,
413 including the field tag. If the size cannot be determined, returns
416 if self.allocation != 'STATIC':
419 if self.pbtype == 'MESSAGE':
421 if msg.name == self.submsgname:
422 encsize = msg.encoded_size(allmsgs)
424 return None # Submessage size is indeterminate
426 # Include submessage length prefix
427 encsize += varint_max_size(encsize.upperlimit())
430 # Submessage cannot be found, this currently occurs when
431 # the submessage type is defined in a different file.
432 # Instead of direct numeric value, reference the size that
433 # has been #defined in the other file.
434 encsize = EncodedSize(self.submsgname + 'size')
436 # We will have to make a conservative assumption on the length
437 # prefix size, though.
440 elif self.enc_size is None:
441 raise RuntimeError("Could not determine encoded size for %s.%s"
442 % (self.struct_name, self.name))
444 encsize = EncodedSize(self.enc_size)
446 encsize += varint_max_size(self.tag << 3) # Tag + wire type
448 if self.rules == 'REPEATED':
449 # Decoders must be always able to handle unpacked arrays.
450 # Therefore we have to reserve space for it, even though
451 # we emit packed arrays ourselves.
452 encsize *= self.max_count
457 class ExtensionRange(Field):
458 def __init__(self, struct_name, range_start, field_options):
459 '''Implements a special pb_extension_t* field in an extensible message
460 structure. The range_start signifies the index at which the extensions
461 start. Not necessarily all tags above this are extensions, it is merely
462 a speed optimization.
464 self.tag = range_start
465 self.struct_name = struct_name
466 self.name = 'extensions'
467 self.pbtype = 'EXTENSION'
468 self.rules = 'OPTIONAL'
469 self.allocation = 'CALLBACK'
470 self.ctype = 'pb_extension_t'
477 return ' pb_extension_t *extensions;'
485 def encoded_size(self, allmsgs):
486 # We exclude extensions from the count, because they cannot be known
487 # until runtime. Other option would be to return None here, but this
488 # way the value remains useful if extensions are not used.
489 return EncodedSize(0)
491 class ExtensionField(Field):
492 def __init__(self, struct_name, desc, field_options):
493 self.fullname = struct_name + desc.name
494 self.extendee_name = names_from_type_name(desc.extendee)
495 Field.__init__(self, self.fullname + 'struct', desc, field_options)
497 if self.rules != 'OPTIONAL':
501 self.rules = 'OPTEXT'
504 '''Return the #define for the tag number of this field.'''
505 identifier = '%s_tag' % self.fullname
506 return '#define %-40s %d\n' % (identifier, self.tag)
508 def extension_decl(self):
509 '''Declaration of the extension type in the .pb.h file'''
511 msg = '/* Extension field %s was skipped because only "optional"\n' % self.fullname
512 msg +=' type of extension fields is currently supported. */\n'
515 return ('extern const pb_extension_type_t %s; /* field type: %s */\n' %
516 (self.fullname, str(self).strip()))
518 def extension_def(self):
519 '''Definition of the extension type in the .pb.c file'''
524 result = 'typedef struct {\n'
526 result += '\n} %s;\n\n' % self.struct_name
527 result += ('static const pb_field_t %s_field = \n %s;\n\n' %
528 (self.fullname, self.pb_field_t(None)))
529 result += 'const pb_extension_type_t %s = {\n' % self.fullname
532 result += ' &%s_field\n' % self.fullname
537 # ---------------------------------------------------------------------------
538 # Generation of messages (structures)
539 # ---------------------------------------------------------------------------
543 def __init__(self, names, desc, message_options):
548 field_options = get_nanopb_suboptions(f, message_options, self.name + f.name)
549 if field_options.type != nanopb_pb2.FT_IGNORE:
550 self.fields.append(Field(self.name, f, field_options))
552 if len(desc.extension_range) > 0:
553 field_options = get_nanopb_suboptions(desc, message_options, self.name + 'extensions')
554 range_start = min([r.start for r in desc.extension_range])
555 if field_options.type != nanopb_pb2.FT_IGNORE:
556 self.fields.append(ExtensionRange(self.name, range_start, field_options))
558 self.packed = message_options.packed_struct
559 self.ordered_fields = self.fields[:]
560 self.ordered_fields.sort()
562 def get_dependencies(self):
563 '''Get list of type names that this structure refers to.'''
564 return [str(field.ctype) for field in self.fields if field.allocation == 'STATIC']
567 result = 'typedef struct _%s {\n' % self.name
569 if not self.ordered_fields:
570 # Empty structs are not allowed in C standard.
571 # Therefore add a dummy field if an empty message occurs.
572 result += ' uint8_t dummy_field;'
574 result += '\n'.join([str(f) for f in self.ordered_fields])
578 result += ' pb_packed'
580 result += ' %s;' % self.name
583 result = 'PB_PACKED_STRUCT_START\n' + result
584 result += '\nPB_PACKED_STRUCT_END'
590 for field in self.fields:
591 types = field.types()
592 if types is not None:
593 result += types + '\n'
596 def get_initializer(self, null_init):
597 if not self.ordered_fields:
601 for field in self.ordered_fields:
602 if field.allocation == 'STATIC':
603 if field.rules == 'REPEATED':
606 + ', '.join([field.get_initializer(null_init)] * field.max_count)
608 elif field.rules == 'OPTIONAL':
609 parts.append('false')
610 parts.append(field.get_initializer(null_init))
612 parts.append(field.get_initializer(null_init))
613 elif field.allocation == 'POINTER':
614 if field.rules == 'REPEATED':
617 elif field.allocation == 'CALLBACK':
618 if field.pbtype == 'EXTENSION':
621 parts.append('{{NULL}, NULL}')
622 return '{' + ', '.join(parts) + '}'
624 def default_decl(self, declaration_only = False):
626 for field in self.fields:
627 default = field.default_decl(declaration_only)
628 if default is not None:
629 result += default + '\n'
632 def fields_declaration(self):
633 result = 'extern const pb_field_t %s_fields[%d];' % (self.name, len(self.fields) + 1)
636 def fields_definition(self):
637 result = 'const pb_field_t %s_fields[%d] = {\n' % (self.name, len(self.fields) + 1)
640 for field in self.ordered_fields:
641 result += field.pb_field_t(prev)
645 result += ' PB_LAST_FIELD\n};'
648 def encoded_size(self, allmsgs):
649 '''Return the maximum size that this message can take when encoded.
650 If the size cannot be determined, returns None.
652 size = EncodedSize(0)
653 for field in self.fields:
654 fsize = field.encoded_size(allmsgs)
662 # ---------------------------------------------------------------------------
663 # Processing of entire .proto files
664 # ---------------------------------------------------------------------------
667 def iterate_messages(desc, names = Names()):
668 '''Recursively find all messages. For each, yield name, DescriptorProto.'''
669 if hasattr(desc, 'message_type'):
670 submsgs = desc.message_type
672 submsgs = desc.nested_type
674 for submsg in submsgs:
675 sub_names = names + submsg.name
676 yield sub_names, submsg
678 for x in iterate_messages(submsg, sub_names):
681 def iterate_extensions(desc, names = Names()):
682 '''Recursively find all extensions.
683 For each, yield name, FieldDescriptorProto.
685 for extension in desc.extension:
686 yield names, extension
688 for subname, subdesc in iterate_messages(desc, names):
689 for extension in subdesc.extension:
690 yield subname, extension
692 def parse_file(fdesc, file_options):
693 '''Takes a FileDescriptorProto and returns tuple (enums, messages, extensions).'''
700 base_name = Names(fdesc.package.split('.'))
704 for enum in fdesc.enum_type:
705 enum_options = get_nanopb_suboptions(enum, file_options, base_name + enum.name)
706 enums.append(Enum(base_name, enum, enum_options))
708 for names, message in iterate_messages(fdesc, base_name):
709 message_options = get_nanopb_suboptions(message, file_options, names)
711 if message_options.skip_message:
714 messages.append(Message(names, message, message_options))
715 for enum in message.enum_type:
716 enum_options = get_nanopb_suboptions(enum, message_options, names + enum.name)
717 enums.append(Enum(names, enum, enum_options))
719 for names, extension in iterate_extensions(fdesc, base_name):
720 field_options = get_nanopb_suboptions(extension, file_options, names + extension.name)
721 if field_options.type != nanopb_pb2.FT_IGNORE:
722 extensions.append(ExtensionField(names, extension, field_options))
724 # Fix field default values where enum short names are used.
726 if not enum.options.long_names:
727 for message in messages:
728 for field in message.fields:
729 if field.default in enum.value_longnames:
730 idx = enum.value_longnames.index(field.default)
731 field.default = enum.values[idx][0]
733 return enums, messages, extensions
737 From http://code.activestate.com/recipes/577413-topological-sort/
738 This function is under the MIT license.
740 for k, v in data.items():
741 v.discard(k) # Ignore self dependencies
742 extra_items_in_deps = reduce(set.union, data.values(), set()) - set(data.keys())
743 data.update(dict([(item, set()) for item in extra_items_in_deps]))
745 ordered = set(item for item,dep in data.items() if not dep)
748 for item in sorted(ordered):
750 data = dict([(item, (dep - ordered)) for item,dep in data.items()
751 if item not in ordered])
752 assert not data, "A cyclic dependency exists amongst %r" % data
754 def sort_dependencies(messages):
755 '''Sort a list of Messages based on dependencies.'''
758 for message in messages:
759 dependencies[str(message.name)] = set(message.get_dependencies())
760 message_by_name[str(message.name)] = message
762 for msgname in toposort2(dependencies):
763 if msgname in message_by_name:
764 yield message_by_name[msgname]
766 def make_identifier(headername):
767 '''Make #ifndef identifier that contains uppercase A-Z and digits 0-9'''
769 for c in headername.upper():
776 def generate_header(dependencies, headername, enums, messages, extensions, options):
777 '''Generate content for a header file.
778 Generates strings, which should be concatenated and stored to file.
781 yield '/* Automatically generated nanopb header */\n'
782 if options.notimestamp:
783 yield '/* Generated by %s */\n\n' % (nanopb_version)
785 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
787 symbol = make_identifier(headername)
788 yield '#ifndef PB_%s_INCLUDED\n' % symbol
789 yield '#define PB_%s_INCLUDED\n' % symbol
791 yield options.libformat % ('pb.h')
793 # no %s specified - use whatever was passed in as options.libformat
794 yield options.libformat
797 for dependency in dependencies:
798 noext = os.path.splitext(dependency)[0]
799 yield options.genformat % (noext + options.extension + '.h')
802 yield '#if PB_PROTO_HEADER_VERSION != 30\n'
803 yield '#error Regenerate this file with the current version of nanopb generator.\n'
807 yield '#ifdef __cplusplus\n'
808 yield 'extern "C" {\n'
811 yield '/* Enum definitions */\n'
813 yield str(enum) + '\n\n'
815 yield '/* Struct definitions */\n'
816 for msg in sort_dependencies(messages):
818 yield str(msg) + '\n\n'
821 yield '/* Extensions */\n'
822 for extension in extensions:
823 yield extension.extension_decl()
826 yield '/* Default values for struct fields */\n'
828 yield msg.default_decl(True)
831 yield '/* Initializer values for message structs */\n'
833 identifier = '%s_init_default' % msg.name
834 yield '#define %-40s %s\n' % (identifier, msg.get_initializer(False))
836 identifier = '%s_init_zero' % msg.name
837 yield '#define %-40s %s\n' % (identifier, msg.get_initializer(True))
840 yield '/* Field tags (for use in manual encoding/decoding) */\n'
841 for msg in sort_dependencies(messages):
842 for field in msg.fields:
844 for extension in extensions:
845 yield extension.tags()
848 yield '/* Struct field encoding specification for nanopb */\n'
850 yield msg.fields_declaration() + '\n'
853 yield '/* Maximum encoded size of messages (where known) */\n'
855 msize = msg.encoded_size(messages)
856 if msize is not None:
857 identifier = '%s_size' % msg.name
858 yield '#define %-40s %s\n' % (identifier, msize)
861 yield '#ifdef __cplusplus\n'
862 yield '} /* extern "C" */\n'
868 def generate_source(headername, enums, messages, extensions, options):
869 '''Generate content for a source file.'''
871 yield '/* Automatically generated nanopb constant definitions */\n'
872 if options.notimestamp:
873 yield '/* Generated by %s */\n\n' % (nanopb_version)
875 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
876 yield options.genformat % (headername)
879 yield '#if PB_PROTO_HEADER_VERSION != 30\n'
880 yield '#error Regenerate this file with the current version of nanopb generator.\n'
885 yield msg.default_decl(False)
890 yield msg.fields_definition() + '\n\n'
892 for ext in extensions:
893 yield ext.extension_def() + '\n'
895 # Add checks for numeric limits
897 count_required_fields = lambda m: len([f for f in msg.fields if f.rules == 'REQUIRED'])
898 largest_msg = max(messages, key = count_required_fields)
899 largest_count = count_required_fields(largest_msg)
900 if largest_count > 64:
901 yield '\n/* Check that missing required fields will be properly detected */\n'
902 yield '#if PB_MAX_REQUIRED_FIELDS < %d\n' % largest_count
903 yield '#error Properly detecting missing required fields in %s requires \\\n' % largest_msg.name
904 yield ' setting PB_MAX_REQUIRED_FIELDS to %d or more.\n' % largest_count
912 checks_msgnames.append(msg.name)
913 for field in msg.fields:
914 status = field.largest_field_value()
915 if isinstance(status, (str, unicode)):
916 checks.append(status)
919 worst_field = str(field.struct_name) + '.' + str(field.name)
921 if worst > 255 or checks:
922 yield '\n/* Check that field information fits in pb_field_t */\n'
924 if worst > 65535 or checks:
925 yield '#if !defined(PB_FIELD_32BIT)\n'
927 yield '#error Field descriptor for %s is too large. Define PB_FIELD_32BIT to fix this.\n' % worst_field
929 assertion = ' && '.join(str(c) + ' < 65536' for c in checks)
930 msgs = '_'.join(str(n) for n in checks_msgnames)
931 yield '/* If you get an error here, it means that you need to define PB_FIELD_32BIT\n'
932 yield ' * compile-time option. You can do that in pb.h or on compiler command line.\n'
934 yield ' * The reason you need to do this is that some of your messages contain tag\n'
935 yield ' * numbers or field sizes that are larger than what can fit in 8 or 16 bit\n'
936 yield ' * field descriptors.\n'
938 yield 'PB_STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
942 yield '#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT)\n'
944 yield '#error Field descriptor for %s is too large. Define PB_FIELD_16BIT to fix this.\n' % worst_field
946 assertion = ' && '.join(str(c) + ' < 256' for c in checks)
947 msgs = '_'.join(str(n) for n in checks_msgnames)
948 yield '/* If you get an error here, it means that you need to define PB_FIELD_16BIT\n'
949 yield ' * compile-time option. You can do that in pb.h or on compiler command line.\n'
951 yield ' * The reason you need to do this is that some of your messages contain tag\n'
952 yield ' * numbers or field sizes that are larger than what can fit in the default\n'
953 yield ' * 8 bit descriptors.\n'
955 yield 'PB_STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
958 # Add check for sizeof(double)
961 for field in msg.fields:
962 if field.ctype == 'double':
967 yield '/* On some platforms (such as AVR), double is really float.\n'
968 yield ' * These are not directly supported by nanopb, but see example_avr_double.\n'
969 yield ' * To get rid of this error, remove any double fields from your .proto.\n'
971 yield 'PB_STATIC_ASSERT(sizeof(double) == 8, DOUBLE_MUST_BE_8_BYTES)\n'
975 # ---------------------------------------------------------------------------
976 # Options parsing for the .proto files
977 # ---------------------------------------------------------------------------
979 from fnmatch import fnmatch
981 def read_options_file(infile):
982 '''Parse a separate options file to list:
983 [(namemask, options), ...]
988 if not line or line.startswith('//') or line.startswith('#'):
991 parts = line.split(None, 1)
992 opts = nanopb_pb2.NanoPBOptions()
993 text_format.Merge(parts[1], opts)
994 results.append((parts[0], opts))
999 '''Ugly global variables, should find a good way to pass these.'''
1000 verbose_options = False
1001 separate_options = []
1002 matched_namemasks = set()
1004 def get_nanopb_suboptions(subdesc, options, name):
1005 '''Get copy of options, and merge information from subdesc.'''
1006 new_options = nanopb_pb2.NanoPBOptions()
1007 new_options.CopyFrom(options)
1009 # Handle options defined in a separate file
1010 dotname = '.'.join(name.parts)
1011 for namemask, options in Globals.separate_options:
1012 if fnmatch(dotname, namemask):
1013 Globals.matched_namemasks.add(namemask)
1014 new_options.MergeFrom(options)
1016 # Handle options defined in .proto
1017 if isinstance(subdesc.options, descriptor.FieldOptions):
1018 ext_type = nanopb_pb2.nanopb
1019 elif isinstance(subdesc.options, descriptor.FileOptions):
1020 ext_type = nanopb_pb2.nanopb_fileopt
1021 elif isinstance(subdesc.options, descriptor.MessageOptions):
1022 ext_type = nanopb_pb2.nanopb_msgopt
1023 elif isinstance(subdesc.options, descriptor.EnumOptions):
1024 ext_type = nanopb_pb2.nanopb_enumopt
1026 raise Exception("Unknown options type")
1028 if subdesc.options.HasExtension(ext_type):
1029 ext = subdesc.options.Extensions[ext_type]
1030 new_options.MergeFrom(ext)
1032 if Globals.verbose_options:
1033 sys.stderr.write("Options for " + dotname + ": ")
1034 sys.stderr.write(text_format.MessageToString(new_options) + "\n")
1039 # ---------------------------------------------------------------------------
1040 # Command line interface
1041 # ---------------------------------------------------------------------------
1045 from optparse import OptionParser
1047 optparser = OptionParser(
1048 usage = "Usage: nanopb_generator.py [options] file.pb ...",
1049 epilog = "Compile file.pb from file.proto by: 'protoc -ofile.pb file.proto'. " +
1050 "Output will be written to file.pb.h and file.pb.c.")
1051 optparser.add_option("-x", dest="exclude", metavar="FILE", action="append", default=[],
1052 help="Exclude file from generated #include list.")
1053 optparser.add_option("-e", "--extension", dest="extension", metavar="EXTENSION", default=".pb",
1054 help="Set extension to use instead of '.pb' for generated files. [default: %default]")
1055 optparser.add_option("-f", "--options-file", dest="options_file", metavar="FILE", default="%s.options",
1056 help="Set name of a separate generator options file.")
1057 optparser.add_option("-Q", "--generated-include-format", dest="genformat",
1058 metavar="FORMAT", default='#include "%s"\n',
1059 help="Set format string to use for including other .pb.h files. [default: %default]")
1060 optparser.add_option("-L", "--library-include-format", dest="libformat",
1061 metavar="FORMAT", default='#include <%s>\n',
1062 help="Set format string to use for including the nanopb pb.h header. [default: %default]")
1063 optparser.add_option("-T", "--no-timestamp", dest="notimestamp", action="store_true", default=False,
1064 help="Don't add timestamp to .pb.h and .pb.c preambles")
1065 optparser.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False,
1066 help="Don't print anything except errors.")
1067 optparser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
1068 help="Print more information.")
1069 optparser.add_option("-s", dest="settings", metavar="OPTION:VALUE", action="append", default=[],
1070 help="Set generator option (max_size, max_count etc.).")
1072 def process_file(filename, fdesc, options):
1073 '''Process a single file.
1074 filename: The full path to the .proto or .pb source file, as string.
1075 fdesc: The loaded FileDescriptorSet, or None to read from the input file.
1076 options: Command line options as they come from OptionsParser.
1079 {'headername': Name of header file,
1080 'headerdata': Data for the .h header file,
1081 'sourcename': Name of the source code file,
1082 'sourcedata': Data for the .c source code file
1085 toplevel_options = nanopb_pb2.NanoPBOptions()
1086 for s in options.settings:
1087 text_format.Merge(s, toplevel_options)
1090 data = open(filename, 'rb').read()
1091 fdesc = descriptor.FileDescriptorSet.FromString(data).file[0]
1093 # Check if there is a separate .options file
1096 optfilename = options.options_file % os.path.splitext(filename)[0]
1098 # No %s specified, use the filename as-is
1099 optfilename = options.options_file
1102 if os.path.isfile(optfilename):
1104 sys.stderr.write('Reading options from ' + optfilename + '\n')
1106 Globals.separate_options = read_options_file(open(optfilename, "rU"))
1108 # If we are given a full filename and it does not exist, give an error.
1109 # However, don't give error when we automatically look for .options file
1110 # with the same name as .proto.
1111 if options.verbose or had_abspath:
1112 sys.stderr.write('Options file not found: ' + optfilename)
1114 Globals.separate_options = []
1116 Globals.matched_namemasks = set()
1119 file_options = get_nanopb_suboptions(fdesc, toplevel_options, Names([filename]))
1120 enums, messages, extensions = parse_file(fdesc, file_options)
1122 # Decide the file names
1123 noext = os.path.splitext(filename)[0]
1124 headername = noext + options.extension + '.h'
1125 sourcename = noext + options.extension + '.c'
1126 headerbasename = os.path.basename(headername)
1128 # List of .proto files that should not be included in the C header file
1129 # even if they are mentioned in the source .proto.
1130 excludes = ['nanopb.proto', 'google/protobuf/descriptor.proto'] + options.exclude
1131 dependencies = [d for d in fdesc.dependency if d not in excludes]
1133 headerdata = ''.join(generate_header(dependencies, headerbasename, enums,
1134 messages, extensions, options))
1136 sourcedata = ''.join(generate_source(headerbasename, enums,
1137 messages, extensions, options))
1139 # Check if there were any lines in .options that did not match a member
1140 unmatched = [n for n,o in Globals.separate_options if n not in Globals.matched_namemasks]
1141 if unmatched and not options.quiet:
1142 sys.stderr.write("Following patterns in " + optfilename + " did not match any fields: "
1143 + ', '.join(unmatched) + "\n")
1144 if not Globals.verbose_options:
1145 sys.stderr.write("Use protoc --nanopb-out=-v:. to see a list of the field names.\n")
1147 return {'headername': headername, 'headerdata': headerdata,
1148 'sourcename': sourcename, 'sourcedata': sourcedata}
1151 '''Main function when invoked directly from the command line.'''
1153 options, filenames = optparser.parse_args()
1156 optparser.print_help()
1160 options.verbose = False
1162 Globals.verbose_options = options.verbose
1164 for filename in filenames:
1165 results = process_file(filename, None, options)
1167 if not options.quiet:
1168 sys.stderr.write("Writing to " + results['headername'] + " and "
1169 + results['sourcename'] + "\n")
1171 open(results['headername'], 'w').write(results['headerdata'])
1172 open(results['sourcename'], 'w').write(results['sourcedata'])
1175 '''Main function when invoked as a protoc plugin.'''
1178 if sys.platform == "win32":
1180 # Set stdin and stdout to binary mode
1181 msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
1182 msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
1184 data = sys.stdin.read()
1185 request = plugin_pb2.CodeGeneratorRequest.FromString(data)
1188 args = shlex.split(request.parameter)
1189 options, dummy = optparser.parse_args(args)
1191 Globals.verbose_options = options.verbose
1193 response = plugin_pb2.CodeGeneratorResponse()
1195 for filename in request.file_to_generate:
1196 for fdesc in request.proto_file:
1197 if fdesc.name == filename:
1198 results = process_file(filename, fdesc, options)
1200 f = response.file.add()
1201 f.name = results['headername']
1202 f.content = results['headerdata']
1204 f = response.file.add()
1205 f.name = results['sourcename']
1206 f.content = results['sourcedata']
1208 sys.stdout.write(response.SerializeToString())
1210 if __name__ == '__main__':
1211 # Check if we are running as a plugin under protoc
1212 if 'protoc-gen-' in sys.argv[0] or '--protoc-plugin' in sys.argv: