3 '''Generate header file for nanopb from a ProtoBuf FileDescriptorSet.'''
4 nanopb_version = "nanopb-0.2.5-dev"
7 import google.protobuf.descriptor_pb2 as descriptor
8 import google.protobuf.text_format as text_format
11 print "*************************************************************"
12 print "*** Could not import the Google protobuf Python libraries ***"
13 print "*** Try installing package 'python-protobuf' or similar. ***"
14 print "*************************************************************"
22 print "***************************************************************"
23 print "*** Could not import the precompiled nanopb_pb2.py. ***"
24 print "*** Run 'make' in the 'generator' folder to update the file.***"
25 print "***************************************************************"
34 # ---------------------------------------------------------------------------
35 # Generation of single fields
36 # ---------------------------------------------------------------------------
41 # Values are tuple (c type, pb type, encoded size)
42 FieldD = descriptor.FieldDescriptorProto
44 FieldD.TYPE_BOOL: ('bool', 'BOOL', 1),
45 FieldD.TYPE_DOUBLE: ('double', 'DOUBLE', 8),
46 FieldD.TYPE_FIXED32: ('uint32_t', 'FIXED32', 4),
47 FieldD.TYPE_FIXED64: ('uint64_t', 'FIXED64', 8),
48 FieldD.TYPE_FLOAT: ('float', 'FLOAT', 4),
49 FieldD.TYPE_INT32: ('int32_t', 'INT32', 10),
50 FieldD.TYPE_INT64: ('int64_t', 'INT64', 10),
51 FieldD.TYPE_SFIXED32: ('int32_t', 'SFIXED32', 4),
52 FieldD.TYPE_SFIXED64: ('int64_t', 'SFIXED64', 8),
53 FieldD.TYPE_SINT32: ('int32_t', 'SINT32', 5),
54 FieldD.TYPE_SINT64: ('int64_t', 'SINT64', 10),
55 FieldD.TYPE_UINT32: ('uint32_t', 'UINT32', 5),
56 FieldD.TYPE_UINT64: ('uint64_t', 'UINT64', 10)
60 '''Keeps a set of nested names and formats them to C identifier.'''
61 def __init__(self, parts = ()):
62 if isinstance(parts, Names):
64 self.parts = tuple(parts)
67 return '_'.join(self.parts)
69 def __add__(self, other):
70 if isinstance(other, (str, unicode)):
71 return Names(self.parts + (other,))
72 elif isinstance(other, tuple):
73 return Names(self.parts + other)
75 raise ValueError("Name parts should be of type str")
77 def __eq__(self, other):
78 return isinstance(other, Names) and self.parts == other.parts
80 def names_from_type_name(type_name):
81 '''Parse Names() from FieldDescriptorProto type_name'''
82 if type_name[0] != '.':
83 raise NotImplementedError("Lookup of non-absolute type names is not supported")
84 return Names(type_name[1:].split('.'))
86 def varint_max_size(max_value):
87 '''Returns the maximum number of bytes a varint can take when encoded.'''
88 for i in range(1, 11):
89 if (max_value >> (i * 7)) == 0:
91 raise ValueError("Value too large for varint: " + str(max_value))
93 assert varint_max_size(0) == 1
94 assert varint_max_size(127) == 1
95 assert varint_max_size(128) == 2
98 '''Class used to represent the encoded size of a field or a message.
99 Consists of a combination of symbolic sizes and integer sizes.'''
100 def __init__(self, value = 0, symbols = []):
101 if isinstance(value, (str, Names)):
102 symbols = [str(value)]
105 self.symbols = symbols
107 def __add__(self, other):
108 if isinstance(other, (int, long)):
109 return EncodedSize(self.value + other, self.symbols)
110 elif isinstance(other, (str, Names)):
111 return EncodedSize(self.value, self.symbols + [str(other)])
112 elif isinstance(other, EncodedSize):
113 return EncodedSize(self.value + other.value, self.symbols + other.symbols)
115 raise ValueError("Cannot add size: " + repr(other))
117 def __mul__(self, other):
118 if isinstance(other, (int, long)):
119 return EncodedSize(self.value * other, [str(other) + '*' + s for s in self.symbols])
121 raise ValueError("Cannot multiply size: " + repr(other))
125 return str(self.value)
127 return '(' + str(self.value) + ' + ' + ' + '.join(self.symbols) + ')'
129 def upperlimit(self):
136 def __init__(self, names, desc, enum_options):
137 '''desc is EnumDescriptorProto'''
139 self.options = enum_options
140 self.names = names + desc.name
142 if enum_options.long_names:
143 self.values = [(self.names + x.name, x.number) for x in desc.value]
145 self.values = [(names + x.name, x.number) for x in desc.value]
147 self.value_longnames = [self.names + x.name for x in desc.value]
150 result = 'typedef enum _%s {\n' % self.names
151 result += ',\n'.join([" %s = %d" % x for x in self.values])
152 result += '\n} %s;' % self.names
156 def __init__(self, struct_name, desc, field_options):
157 '''desc is FieldDescriptorProto'''
158 self.tag = desc.number
159 self.struct_name = struct_name
160 self.name = desc.name
163 self.max_count = None
167 # Parse field options
168 if field_options.HasField("max_size"):
169 self.max_size = field_options.max_size
171 if field_options.HasField("max_count"):
172 self.max_count = field_options.max_count
174 if desc.HasField('default_value'):
175 self.default = desc.default_value
177 # Check field rules, i.e. required/optional/repeated.
179 if desc.label == FieldD.LABEL_REQUIRED:
180 self.rules = 'REQUIRED'
181 elif desc.label == FieldD.LABEL_OPTIONAL:
182 self.rules = 'OPTIONAL'
183 elif desc.label == FieldD.LABEL_REPEATED:
184 self.rules = 'REPEATED'
185 if self.max_count is None:
186 can_be_static = False
188 self.array_decl = '[%d]' % self.max_count
190 raise NotImplementedError(desc.label)
192 # Check if the field can be implemented with static allocation
193 # i.e. whether the data size is known.
194 if desc.type == FieldD.TYPE_STRING and self.max_size is None:
195 can_be_static = False
197 if desc.type == FieldD.TYPE_BYTES and self.max_size is None:
198 can_be_static = False
200 # Decide how the field data will be allocated
201 if field_options.type == nanopb_pb2.FT_DEFAULT:
203 field_options.type = nanopb_pb2.FT_STATIC
205 field_options.type = nanopb_pb2.FT_CALLBACK
207 if field_options.type == nanopb_pb2.FT_STATIC and not can_be_static:
208 raise Exception("Field %s is defined as static, but max_size or "
209 "max_count is not given." % self.name)
211 if field_options.type == nanopb_pb2.FT_STATIC:
212 self.allocation = 'STATIC'
213 elif field_options.type == nanopb_pb2.FT_POINTER:
214 self.allocation = 'POINTER'
215 elif field_options.type == nanopb_pb2.FT_CALLBACK:
216 self.allocation = 'CALLBACK'
218 raise NotImplementedError(field_options.type)
220 # Decide the C data type to use in the struct.
221 if datatypes.has_key(desc.type):
222 self.ctype, self.pbtype, self.enc_size = datatypes[desc.type]
223 elif desc.type == FieldD.TYPE_ENUM:
225 self.ctype = names_from_type_name(desc.type_name)
226 if self.default is not None:
227 self.default = self.ctype + self.default
228 self.enc_size = 5 # protoc rejects enum values > 32 bits
229 elif desc.type == FieldD.TYPE_STRING:
230 self.pbtype = 'STRING'
232 if self.allocation == 'STATIC':
234 self.array_decl += '[%d]' % self.max_size
235 self.enc_size = varint_max_size(self.max_size) + self.max_size
236 elif desc.type == FieldD.TYPE_BYTES:
237 self.pbtype = 'BYTES'
238 if self.allocation == 'STATIC':
239 self.ctype = self.struct_name + self.name + 't'
240 self.enc_size = varint_max_size(self.max_size) + self.max_size
241 elif self.allocation == 'POINTER':
242 self.ctype = 'pb_bytes_ptr_t'
243 elif desc.type == FieldD.TYPE_MESSAGE:
244 self.pbtype = 'MESSAGE'
245 self.ctype = self.submsgname = names_from_type_name(desc.type_name)
246 self.enc_size = None # Needs to be filled in after the message type is available
248 raise NotImplementedError(desc.type)
250 def __cmp__(self, other):
251 return cmp(self.tag, other.tag)
255 if self.allocation == 'POINTER':
256 if self.rules == 'REPEATED':
257 result += ' size_t ' + self.name + '_count;\n'
259 if self.pbtype == 'MESSAGE':
260 # Use struct definition, so recursive submessages are possible
261 result += ' struct _%s *%s;' % (self.ctype, self.name)
262 elif self.rules == 'REPEATED' and self.pbtype == 'STRING':
263 # String arrays need to be defined as pointers to pointers
264 result += ' %s **%s;' % (self.ctype, self.name)
266 result += ' %s *%s;' % (self.ctype, self.name)
267 elif self.allocation == 'CALLBACK':
268 result += ' pb_callback_t %s;' % self.name
270 if self.rules == 'OPTIONAL' and self.allocation == 'STATIC':
271 result += ' bool has_' + self.name + ';\n'
272 elif self.rules == 'REPEATED' and self.allocation == 'STATIC':
273 result += ' size_t ' + self.name + '_count;\n'
274 result += ' %s %s%s;' % (self.ctype, self.name, self.array_decl)
278 '''Return definitions for any special types this field might need.'''
279 if self.pbtype == 'BYTES' and self.allocation == 'STATIC':
280 result = 'typedef struct {\n'
281 result += ' size_t size;\n'
282 result += ' uint8_t bytes[%d];\n' % self.max_size
283 result += '} %s;\n' % self.ctype
288 def default_decl(self, declaration_only = False):
289 '''Return definition for this field's default value.'''
290 if self.default is None:
293 ctype, default = self.ctype, self.default
296 if self.pbtype == 'STRING':
297 if self.allocation != 'STATIC':
298 return None # Not implemented
300 array_decl = '[%d]' % self.max_size
301 default = str(self.default).encode('string_escape')
302 default = default.replace('"', '\\"')
303 default = '"' + default + '"'
304 elif self.pbtype == 'BYTES':
305 if self.allocation != 'STATIC':
306 return None # Not implemented
308 data = self.default.decode('string_escape')
309 data = ['0x%02x' % ord(c) for c in data]
310 default = '{%d, {%s}}' % (len(data), ','.join(data))
313 return 'extern const %s %s_default%s;' % (ctype, self.struct_name + self.name, array_decl)
315 return 'const %s %s_default%s = %s;' % (ctype, self.struct_name + self.name, array_decl, default)
318 '''Return the #define for the tag number of this field.'''
319 identifier = '%s_%s_tag' % (self.struct_name, self.name)
320 return '#define %-40s %d\n' % (identifier, self.tag)
322 def pb_field_t(self, prev_field_name):
323 '''Return the pb_field_t initializer to use in the constant array.
324 prev_field_name is the name of the previous field or None.
326 result = ' PB_FIELD2(%3d, ' % self.tag
327 result += '%-8s, ' % self.pbtype
328 result += '%s, ' % self.rules
329 result += '%-8s, ' % self.allocation
330 result += '%s, ' % ("FIRST" if not prev_field_name else "OTHER")
331 result += '%s, ' % self.struct_name
332 result += '%s, ' % self.name
333 result += '%s, ' % (prev_field_name or self.name)
335 if self.pbtype == 'MESSAGE':
336 result += '&%s_fields)' % self.submsgname
337 elif self.default is None:
339 elif self.pbtype in ['BYTES', 'STRING'] and self.allocation != 'STATIC':
340 result += '0)' # Arbitrary size default values not implemented
342 result += '&%s_default)' % (self.struct_name + self.name)
346 def largest_field_value(self):
347 '''Determine if this field needs 16bit or 32bit pb_field_t structure to compile properly.
348 Returns numeric value or a C-expression for assert.'''
349 if self.pbtype == 'MESSAGE':
350 if self.rules == 'REPEATED' and self.allocation == 'STATIC':
351 return 'pb_membersize(%s, %s[0])' % (self.struct_name, self.name)
353 return 'pb_membersize(%s, %s)' % (self.struct_name, self.name)
355 return max(self.tag, self.max_size, self.max_count)
357 def encoded_size(self, allmsgs):
358 '''Return the maximum size that this field can take when encoded,
359 including the field tag. If the size cannot be determined, returns
362 if self.allocation != 'STATIC':
365 if self.pbtype == 'MESSAGE':
367 if msg.name == self.submsgname:
368 encsize = msg.encoded_size(allmsgs)
370 return None # Submessage size is indeterminate
372 # Include submessage length prefix
373 encsize += varint_max_size(encsize.upperlimit())
376 # Submessage cannot be found, this currently occurs when
377 # the submessage type is defined in a different file.
378 # Instead of direct numeric value, reference the size that
379 # has been #defined in the other file.
380 encsize = EncodedSize(self.submsgname + 'size')
382 # We will have to make a conservative assumption on the length
383 # prefix size, though.
386 elif self.enc_size is None:
387 raise RuntimeError("Could not determine encoded size for %s.%s"
388 % (self.struct_name, self.name))
390 encsize = EncodedSize(self.enc_size)
392 encsize += varint_max_size(self.tag << 3) # Tag + wire type
394 if self.rules == 'REPEATED':
395 # Decoders must be always able to handle unpacked arrays.
396 # Therefore we have to reserve space for it, even though
397 # we emit packed arrays ourselves.
398 encsize *= self.max_count
403 class ExtensionRange(Field):
404 def __init__(self, struct_name, range_start, field_options):
405 '''Implements a special pb_extension_t* field in an extensible message
406 structure. The range_start signifies the index at which the extensions
407 start. Not necessarily all tags above this are extensions, it is merely
408 a speed optimization.
410 self.tag = range_start
411 self.struct_name = struct_name
412 self.name = 'extensions'
413 self.pbtype = 'EXTENSION'
414 self.rules = 'OPTIONAL'
415 self.allocation = 'CALLBACK'
416 self.ctype = 'pb_extension_t'
423 return ' pb_extension_t *extensions;'
431 def encoded_size(self, allmsgs):
432 # We exclude extensions from the count, because they cannot be known
433 # until runtime. Other option would be to return None here, but this
434 # way the value remains useful if extensions are not used.
435 return EncodedSize(0)
437 class ExtensionField(Field):
438 def __init__(self, struct_name, desc, field_options):
439 self.fullname = struct_name + desc.name
440 self.extendee_name = names_from_type_name(desc.extendee)
441 Field.__init__(self, self.fullname + 'struct', desc, field_options)
443 if self.rules != 'OPTIONAL':
447 self.rules = 'OPTEXT'
450 '''Return the #define for the tag number of this field.'''
451 identifier = '%s_tag' % self.fullname
452 return '#define %-40s %d\n' % (identifier, self.tag)
454 def extension_decl(self):
455 '''Declaration of the extension type in the .pb.h file'''
457 msg = '/* Extension field %s was skipped because only "optional"\n' % self.fullname
458 msg +=' type of extension fields is currently supported. */\n'
461 return 'extern const pb_extension_type_t %s;\n' % self.fullname
463 def extension_def(self):
464 '''Definition of the extension type in the .pb.c file'''
469 result = 'typedef struct {\n'
471 result += '\n} %s;\n\n' % self.struct_name
472 result += ('static const pb_field_t %s_field = \n %s;\n\n' %
473 (self.fullname, self.pb_field_t(None)))
474 result += 'const pb_extension_type_t %s = {\n' % self.fullname
477 result += ' &%s_field\n' % self.fullname
482 # ---------------------------------------------------------------------------
483 # Generation of messages (structures)
484 # ---------------------------------------------------------------------------
488 def __init__(self, names, desc, message_options):
493 field_options = get_nanopb_suboptions(f, message_options, self.name + f.name)
494 if field_options.type != nanopb_pb2.FT_IGNORE:
495 self.fields.append(Field(self.name, f, field_options))
497 if len(desc.extension_range) > 0:
498 field_options = get_nanopb_suboptions(desc, message_options, self.name + 'extensions')
499 range_start = min([r.start for r in desc.extension_range])
500 if field_options.type != nanopb_pb2.FT_IGNORE:
501 self.fields.append(ExtensionRange(self.name, range_start, field_options))
503 self.packed = message_options.packed_struct
504 self.ordered_fields = self.fields[:]
505 self.ordered_fields.sort()
507 def get_dependencies(self):
508 '''Get list of type names that this structure refers to.'''
509 return [str(field.ctype) for field in self.fields]
512 result = 'typedef struct _%s {\n' % self.name
514 if not self.ordered_fields:
515 # Empty structs are not allowed in C standard.
516 # Therefore add a dummy field if an empty message occurs.
517 result += ' uint8_t dummy_field;'
519 result += '\n'.join([str(f) for f in self.ordered_fields])
523 result += ' pb_packed'
525 result += ' %s;' % self.name
528 result = 'PB_PACKED_STRUCT_START\n' + result
529 result += '\nPB_PACKED_STRUCT_END'
535 for field in self.fields:
536 types = field.types()
537 if types is not None:
538 result += types + '\n'
541 def default_decl(self, declaration_only = False):
543 for field in self.fields:
544 default = field.default_decl(declaration_only)
545 if default is not None:
546 result += default + '\n'
549 def fields_declaration(self):
550 result = 'extern const pb_field_t %s_fields[%d];' % (self.name, len(self.fields) + 1)
553 def fields_definition(self):
554 result = 'const pb_field_t %s_fields[%d] = {\n' % (self.name, len(self.fields) + 1)
557 for field in self.ordered_fields:
558 result += field.pb_field_t(prev)
562 result += ' PB_LAST_FIELD\n};'
565 def encoded_size(self, allmsgs):
566 '''Return the maximum size that this message can take when encoded.
567 If the size cannot be determined, returns None.
569 size = EncodedSize(0)
570 for field in self.fields:
571 fsize = field.encoded_size(allmsgs)
579 # ---------------------------------------------------------------------------
580 # Processing of entire .proto files
581 # ---------------------------------------------------------------------------
584 def iterate_messages(desc, names = Names()):
585 '''Recursively find all messages. For each, yield name, DescriptorProto.'''
586 if hasattr(desc, 'message_type'):
587 submsgs = desc.message_type
589 submsgs = desc.nested_type
591 for submsg in submsgs:
592 sub_names = names + submsg.name
593 yield sub_names, submsg
595 for x in iterate_messages(submsg, sub_names):
598 def iterate_extensions(desc, names = Names()):
599 '''Recursively find all extensions.
600 For each, yield name, FieldDescriptorProto.
602 for extension in desc.extension:
603 yield names, extension
605 for subname, subdesc in iterate_messages(desc, names):
606 for extension in subdesc.extension:
607 yield subname, extension
609 def parse_file(fdesc, file_options):
610 '''Takes a FileDescriptorProto and returns tuple (enums, messages, extensions).'''
617 base_name = Names(fdesc.package.split('.'))
621 for enum in fdesc.enum_type:
622 enum_options = get_nanopb_suboptions(enum, file_options, base_name + enum.name)
623 enums.append(Enum(base_name, enum, enum_options))
625 for names, message in iterate_messages(fdesc, base_name):
626 message_options = get_nanopb_suboptions(message, file_options, names)
627 messages.append(Message(names, message, message_options))
628 for enum in message.enum_type:
629 enum_options = get_nanopb_suboptions(enum, message_options, names + enum.name)
630 enums.append(Enum(names, enum, enum_options))
632 for names, extension in iterate_extensions(fdesc, base_name):
633 field_options = get_nanopb_suboptions(extension, file_options, names)
634 if field_options.type != nanopb_pb2.FT_IGNORE:
635 extensions.append(ExtensionField(names, extension, field_options))
637 # Fix field default values where enum short names are used.
639 if not enum.options.long_names:
640 for message in messages:
641 for field in message.fields:
642 if field.default in enum.value_longnames:
643 idx = enum.value_longnames.index(field.default)
644 field.default = enum.values[idx][0]
646 return enums, messages, extensions
650 From http://code.activestate.com/recipes/577413-topological-sort/
651 This function is under the MIT license.
653 for k, v in data.items():
654 v.discard(k) # Ignore self dependencies
655 extra_items_in_deps = reduce(set.union, data.values(), set()) - set(data.keys())
656 data.update(dict([(item, set()) for item in extra_items_in_deps]))
658 ordered = set(item for item,dep in data.items() if not dep)
661 for item in sorted(ordered):
663 data = dict([(item, (dep - ordered)) for item,dep in data.items()
664 if item not in ordered])
665 assert not data, "A cyclic dependency exists amongst %r" % data
667 def sort_dependencies(messages):
668 '''Sort a list of Messages based on dependencies.'''
671 for message in messages:
672 dependencies[str(message.name)] = set(message.get_dependencies())
673 message_by_name[str(message.name)] = message
675 for msgname in toposort2(dependencies):
676 if msgname in message_by_name:
677 yield message_by_name[msgname]
679 def make_identifier(headername):
680 '''Make #ifndef identifier that contains uppercase A-Z and digits 0-9'''
682 for c in headername.upper():
689 def generate_header(dependencies, headername, enums, messages, extensions, options):
690 '''Generate content for a header file.
691 Generates strings, which should be concatenated and stored to file.
694 yield '/* Automatically generated nanopb header */\n'
695 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
697 symbol = make_identifier(headername)
698 yield '#ifndef _PB_%s_\n' % symbol
699 yield '#define _PB_%s_\n' % symbol
701 yield options.libformat % ('pb.h')
703 # no %s specified - use whatever was passed in as options.libformat
704 yield options.libformat
707 for dependency in dependencies:
708 noext = os.path.splitext(dependency)[0]
709 yield options.genformat % (noext + '.' + options.extension + '.h')
712 yield '#ifdef __cplusplus\n'
713 yield 'extern "C" {\n'
716 yield '/* Enum definitions */\n'
718 yield str(enum) + '\n\n'
720 yield '/* Struct definitions */\n'
721 for msg in sort_dependencies(messages):
723 yield str(msg) + '\n\n'
726 yield '/* Extensions */\n'
727 for extension in extensions:
728 yield extension.extension_decl()
731 yield '/* Default values for struct fields */\n'
733 yield msg.default_decl(True)
736 yield '/* Field tags (for use in manual encoding/decoding) */\n'
737 for msg in sort_dependencies(messages):
738 for field in msg.fields:
740 for extension in extensions:
741 yield extension.tags()
744 yield '/* Struct field encoding specification for nanopb */\n'
746 yield msg.fields_declaration() + '\n'
749 yield '/* Maximum encoded size of messages (where known) */\n'
751 msize = msg.encoded_size(messages)
752 if msize is not None:
753 identifier = '%s_size' % msg.name
754 yield '#define %-40s %s\n' % (identifier, msize)
757 yield '#ifdef __cplusplus\n'
758 yield '} /* extern "C" */\n'
764 def generate_source(headername, enums, messages, extensions, options):
765 '''Generate content for a source file.'''
767 yield '/* Automatically generated nanopb constant definitions */\n'
768 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
769 yield options.genformat % (headername)
773 yield msg.default_decl(False)
778 yield msg.fields_definition() + '\n\n'
780 for ext in extensions:
781 yield ext.extension_def() + '\n'
783 # Add checks for numeric limits
785 count_required_fields = lambda m: len([f for f in msg.fields if f.rules == 'REQUIRED'])
786 largest_msg = max(messages, key = count_required_fields)
787 largest_count = count_required_fields(largest_msg)
788 if largest_count > 64:
789 yield '\n/* Check that missing required fields will be properly detected */\n'
790 yield '#if PB_MAX_REQUIRED_FIELDS < %d\n' % largest_count
791 yield '#error Properly detecting missing required fields in %s requires \\\n' % largest_msg.name
792 yield ' setting PB_MAX_REQUIRED_FIELDS to %d or more.\n' % largest_count
800 checks_msgnames.append(msg.name)
801 for field in msg.fields:
802 status = field.largest_field_value()
803 if isinstance(status, (str, unicode)):
804 checks.append(status)
807 worst_field = str(field.struct_name) + '.' + str(field.name)
809 if worst > 255 or checks:
810 yield '\n/* Check that field information fits in pb_field_t */\n'
813 yield '#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT)\n'
815 yield '#error Field descriptor for %s is too large. Define PB_FIELD_16BIT to fix this.\n' % worst_field
817 assertion = ' && '.join(str(c) + ' < 256' for c in checks)
818 msgs = '_'.join(str(n) for n in checks_msgnames)
819 yield 'STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
822 if worst > 65535 or checks:
823 yield '#if !defined(PB_FIELD_32BIT)\n'
825 yield '#error Field descriptor for %s is too large. Define PB_FIELD_32BIT to fix this.\n' % worst_field
827 assertion = ' && '.join(str(c) + ' < 65536' for c in checks)
828 msgs = '_'.join(str(n) for n in checks_msgnames)
829 yield 'STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
832 # Add check for sizeof(double)
835 for field in msg.fields:
836 if field.ctype == 'double':
841 yield '/* On some platforms (such as AVR), double is really float.\n'
842 yield ' * These are not directly supported by nanopb, but see example_avr_double.\n'
843 yield ' * To get rid of this error, remove any double fields from your .proto.\n'
845 yield 'STATIC_ASSERT(sizeof(double) == 8, DOUBLE_MUST_BE_8_BYTES)\n'
849 # ---------------------------------------------------------------------------
850 # Options parsing for the .proto files
851 # ---------------------------------------------------------------------------
853 from fnmatch import fnmatch
855 def read_options_file(infile):
856 '''Parse a separate options file to list:
857 [(namemask, options), ...]
862 if not line or line.startswith('//') or line.startswith('#'):
865 parts = line.split(None, 1)
866 opts = nanopb_pb2.NanoPBOptions()
867 text_format.Merge(parts[1], opts)
868 results.append((parts[0], opts))
873 '''Ugly global variables, should find a good way to pass these.'''
874 verbose_options = False
875 separate_options = []
877 def get_nanopb_suboptions(subdesc, options, name):
878 '''Get copy of options, and merge information from subdesc.'''
879 new_options = nanopb_pb2.NanoPBOptions()
880 new_options.CopyFrom(options)
882 # Handle options defined in a separate file
883 dotname = '.'.join(name.parts)
884 for namemask, options in Globals.separate_options:
885 if fnmatch(dotname, namemask):
886 new_options.MergeFrom(options)
888 # Handle options defined in .proto
889 if isinstance(subdesc.options, descriptor.FieldOptions):
890 ext_type = nanopb_pb2.nanopb
891 elif isinstance(subdesc.options, descriptor.FileOptions):
892 ext_type = nanopb_pb2.nanopb_fileopt
893 elif isinstance(subdesc.options, descriptor.MessageOptions):
894 ext_type = nanopb_pb2.nanopb_msgopt
895 elif isinstance(subdesc.options, descriptor.EnumOptions):
896 ext_type = nanopb_pb2.nanopb_enumopt
898 raise Exception("Unknown options type")
900 if subdesc.options.HasExtension(ext_type):
901 ext = subdesc.options.Extensions[ext_type]
902 new_options.MergeFrom(ext)
904 if Globals.verbose_options:
905 print "Options for " + dotname + ":"
906 print text_format.MessageToString(new_options)
911 # ---------------------------------------------------------------------------
912 # Command line interface
913 # ---------------------------------------------------------------------------
917 from optparse import OptionParser
919 optparser = OptionParser(
920 usage = "Usage: nanopb_generator.py [options] file.pb ...",
921 epilog = "Compile file.pb from file.proto by: 'protoc -ofile.pb file.proto'. " +
922 "Output will be written to file.pb.h and file.pb.c.")
923 optparser.add_option("-x", dest="exclude", metavar="FILE", action="append", default=[],
924 help="Exclude file from generated #include list.")
925 optparser.add_option("-e", "--extension", dest="extension", metavar="EXTENSION", default="pb",
926 help="Set extension to use instead of 'pb' for generated files. [default: %default]")
927 optparser.add_option("-f", "--options-file", dest="options_file", metavar="FILE", default="%s.options",
928 help="Set name of a separate generator options file.")
929 optparser.add_option("-Q", "--generated-include-format", dest="genformat",
930 metavar="FORMAT", default='#include "%s"\n',
931 help="Set format string to use for including other .pb.h files. [default: %default]")
932 optparser.add_option("-L", "--library-include-format", dest="libformat",
933 metavar="FORMAT", default='#include <%s>\n',
934 help="Set format string to use for including the nanopb pb.h header. [default: %default]")
935 optparser.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False,
936 help="Don't print anything except errors.")
937 optparser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
938 help="Print more information.")
939 optparser.add_option("-s", dest="settings", metavar="OPTION:VALUE", action="append", default=[],
940 help="Set generator option (max_size, max_count etc.).")
942 def process_file(filename, fdesc, options):
943 '''Process a single file.
944 filename: The full path to the .proto or .pb source file, as string.
945 fdesc: The loaded FileDescriptorSet, or None to read from the input file.
946 options: Command line options as they come from OptionsParser.
949 {'headername': Name of header file,
950 'headerdata': Data for the .h header file,
951 'sourcename': Name of the source code file,
952 'sourcedata': Data for the .c source code file
955 toplevel_options = nanopb_pb2.NanoPBOptions()
956 for s in options.settings:
957 text_format.Merge(s, toplevel_options)
960 data = open(filename, 'rb').read()
961 fdesc = descriptor.FileDescriptorSet.FromString(data).file[0]
963 # Check if there is a separate .options file
965 optfilename = options.options_file % os.path.splitext(filename)[0]
967 # No %s specified, use the filename as-is
968 optfilename = options.options_file
971 print 'Reading options from ' + optfilename
973 if os.path.isfile(optfilename):
974 Globals.separate_options = read_options_file(open(optfilename, "rU"))
976 Globals.separate_options = []
979 file_options = get_nanopb_suboptions(fdesc, toplevel_options, Names([filename]))
980 enums, messages, extensions = parse_file(fdesc, file_options)
982 # Decide the file names
983 noext = os.path.splitext(filename)[0]
984 headername = noext + '.' + options.extension + '.h'
985 sourcename = noext + '.' + options.extension + '.c'
986 headerbasename = os.path.basename(headername)
988 # List of .proto files that should not be included in the C header file
989 # even if they are mentioned in the source .proto.
990 excludes = ['nanopb.proto', 'google/protobuf/descriptor.proto'] + options.exclude
991 dependencies = [d for d in fdesc.dependency if d not in excludes]
993 headerdata = ''.join(generate_header(dependencies, headerbasename, enums,
994 messages, extensions, options))
996 sourcedata = ''.join(generate_source(headerbasename, enums,
997 messages, extensions, options))
999 return {'headername': headername, 'headerdata': headerdata,
1000 'sourcename': sourcename, 'sourcedata': sourcedata}
1003 '''Main function when invoked directly from the command line.'''
1005 options, filenames = optparser.parse_args()
1008 optparser.print_help()
1012 options.verbose = False
1014 Globals.verbose_options = options.verbose
1016 for filename in filenames:
1017 results = process_file(filename, None, options)
1019 if not options.quiet:
1020 print "Writing to " + results['headername'] + " and " + results['sourcename']
1022 open(results['headername'], 'w').write(results['headerdata'])
1023 open(results['sourcename'], 'w').write(results['sourcedata'])
1026 '''Main function when invoked as a protoc plugin.'''
1029 data = sys.stdin.read()
1030 request = plugin_pb2.CodeGeneratorRequest.FromString(data)
1033 args = shlex.split(request.parameter)
1034 options, dummy = optparser.parse_args(args)
1036 # We can't go printing stuff to stdout
1037 Globals.verbose_options = False
1038 options.verbose = False
1039 options.quiet = True
1041 response = plugin_pb2.CodeGeneratorResponse()
1043 for filename in request.file_to_generate:
1044 for fdesc in request.proto_file:
1045 if fdesc.name == filename:
1046 results = process_file(filename, fdesc, options)
1048 f = response.file.add()
1049 f.name = results['headername']
1050 f.content = results['headerdata']
1052 f = response.file.add()
1053 f.name = results['sourcename']
1054 f.content = results['sourcedata']
1056 sys.stdout.write(response.SerializeToString())
1058 if __name__ == '__main__':
1059 # Check if we are running as a plugin under protoc
1060 if 'protoc-gen-' in sys.argv[0]: