3 '''Generate header file for nanopb from a ProtoBuf FileDescriptorSet.'''
4 nanopb_version = "nanopb-0.2.5-dev"
7 import google, distutils.util # bbfreeze seems to need these
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 "*************************************************************"
19 import proto.nanopb_pb2 as nanopb_pb2
20 import proto.descriptor_pb2 as descriptor
23 print "********************************************************************"
24 print "*** Failed to import the protocol definitions for generator. ***"
25 print "*** You have to run 'make' in the nanopb/generator/proto folder. ***"
26 print "********************************************************************"
31 # ---------------------------------------------------------------------------
32 # Generation of single fields
33 # ---------------------------------------------------------------------------
38 # Values are tuple (c type, pb type, encoded size)
39 FieldD = descriptor.FieldDescriptorProto
41 FieldD.TYPE_BOOL: ('bool', 'BOOL', 1),
42 FieldD.TYPE_DOUBLE: ('double', 'DOUBLE', 8),
43 FieldD.TYPE_FIXED32: ('uint32_t', 'FIXED32', 4),
44 FieldD.TYPE_FIXED64: ('uint64_t', 'FIXED64', 8),
45 FieldD.TYPE_FLOAT: ('float', 'FLOAT', 4),
46 FieldD.TYPE_INT32: ('int32_t', 'INT32', 10),
47 FieldD.TYPE_INT64: ('int64_t', 'INT64', 10),
48 FieldD.TYPE_SFIXED32: ('int32_t', 'SFIXED32', 4),
49 FieldD.TYPE_SFIXED64: ('int64_t', 'SFIXED64', 8),
50 FieldD.TYPE_SINT32: ('int32_t', 'SINT32', 5),
51 FieldD.TYPE_SINT64: ('int64_t', 'SINT64', 10),
52 FieldD.TYPE_UINT32: ('uint32_t', 'UINT32', 5),
53 FieldD.TYPE_UINT64: ('uint64_t', 'UINT64', 10)
57 '''Keeps a set of nested names and formats them to C identifier.'''
58 def __init__(self, parts = ()):
59 if isinstance(parts, Names):
61 self.parts = tuple(parts)
64 return '_'.join(self.parts)
66 def __add__(self, other):
67 if isinstance(other, (str, unicode)):
68 return Names(self.parts + (other,))
69 elif isinstance(other, tuple):
70 return Names(self.parts + other)
72 raise ValueError("Name parts should be of type str")
74 def __eq__(self, other):
75 return isinstance(other, Names) and self.parts == other.parts
77 def names_from_type_name(type_name):
78 '''Parse Names() from FieldDescriptorProto type_name'''
79 if type_name[0] != '.':
80 raise NotImplementedError("Lookup of non-absolute type names is not supported")
81 return Names(type_name[1:].split('.'))
83 def varint_max_size(max_value):
84 '''Returns the maximum number of bytes a varint can take when encoded.'''
85 for i in range(1, 11):
86 if (max_value >> (i * 7)) == 0:
88 raise ValueError("Value too large for varint: " + str(max_value))
90 assert varint_max_size(0) == 1
91 assert varint_max_size(127) == 1
92 assert varint_max_size(128) == 2
95 '''Class used to represent the encoded size of a field or a message.
96 Consists of a combination of symbolic sizes and integer sizes.'''
97 def __init__(self, value = 0, symbols = []):
98 if isinstance(value, (str, Names)):
99 symbols = [str(value)]
102 self.symbols = symbols
104 def __add__(self, other):
105 if isinstance(other, (int, long)):
106 return EncodedSize(self.value + other, self.symbols)
107 elif isinstance(other, (str, Names)):
108 return EncodedSize(self.value, self.symbols + [str(other)])
109 elif isinstance(other, EncodedSize):
110 return EncodedSize(self.value + other.value, self.symbols + other.symbols)
112 raise ValueError("Cannot add size: " + repr(other))
114 def __mul__(self, other):
115 if isinstance(other, (int, long)):
116 return EncodedSize(self.value * other, [str(other) + '*' + s for s in self.symbols])
118 raise ValueError("Cannot multiply size: " + repr(other))
122 return str(self.value)
124 return '(' + str(self.value) + ' + ' + ' + '.join(self.symbols) + ')'
126 def upperlimit(self):
133 def __init__(self, names, desc, enum_options):
134 '''desc is EnumDescriptorProto'''
136 self.options = enum_options
137 self.names = names + desc.name
139 if enum_options.long_names:
140 self.values = [(self.names + x.name, x.number) for x in desc.value]
142 self.values = [(names + x.name, x.number) for x in desc.value]
144 self.value_longnames = [self.names + x.name for x in desc.value]
147 result = 'typedef enum _%s {\n' % self.names
148 result += ',\n'.join([" %s = %d" % x for x in self.values])
149 result += '\n} %s;' % self.names
153 def __init__(self, struct_name, desc, field_options):
154 '''desc is FieldDescriptorProto'''
155 self.tag = desc.number
156 self.struct_name = struct_name
157 self.name = desc.name
160 self.max_count = None
164 # Parse field options
165 if field_options.HasField("max_size"):
166 self.max_size = field_options.max_size
168 if field_options.HasField("max_count"):
169 self.max_count = field_options.max_count
171 if desc.HasField('default_value'):
172 self.default = desc.default_value
174 # Check field rules, i.e. required/optional/repeated.
176 if desc.label == FieldD.LABEL_REQUIRED:
177 self.rules = 'REQUIRED'
178 elif desc.label == FieldD.LABEL_OPTIONAL:
179 self.rules = 'OPTIONAL'
180 elif desc.label == FieldD.LABEL_REPEATED:
181 self.rules = 'REPEATED'
182 if self.max_count is None:
183 can_be_static = False
185 self.array_decl = '[%d]' % self.max_count
187 raise NotImplementedError(desc.label)
189 # Check if the field can be implemented with static allocation
190 # i.e. whether the data size is known.
191 if desc.type == FieldD.TYPE_STRING and self.max_size is None:
192 can_be_static = False
194 if desc.type == FieldD.TYPE_BYTES and self.max_size is None:
195 can_be_static = False
197 # Decide how the field data will be allocated
198 if field_options.type == nanopb_pb2.FT_DEFAULT:
200 field_options.type = nanopb_pb2.FT_STATIC
202 field_options.type = nanopb_pb2.FT_CALLBACK
204 if field_options.type == nanopb_pb2.FT_STATIC and not can_be_static:
205 raise Exception("Field %s is defined as static, but max_size or "
206 "max_count is not given." % self.name)
208 if field_options.type == nanopb_pb2.FT_STATIC:
209 self.allocation = 'STATIC'
210 elif field_options.type == nanopb_pb2.FT_POINTER:
211 self.allocation = 'POINTER'
212 elif field_options.type == nanopb_pb2.FT_CALLBACK:
213 self.allocation = 'CALLBACK'
215 raise NotImplementedError(field_options.type)
217 # Decide the C data type to use in the struct.
218 if datatypes.has_key(desc.type):
219 self.ctype, self.pbtype, self.enc_size = datatypes[desc.type]
220 elif desc.type == FieldD.TYPE_ENUM:
222 self.ctype = names_from_type_name(desc.type_name)
223 if self.default is not None:
224 self.default = self.ctype + self.default
225 self.enc_size = 5 # protoc rejects enum values > 32 bits
226 elif desc.type == FieldD.TYPE_STRING:
227 self.pbtype = 'STRING'
229 if self.allocation == 'STATIC':
231 self.array_decl += '[%d]' % self.max_size
232 self.enc_size = varint_max_size(self.max_size) + self.max_size
233 elif desc.type == FieldD.TYPE_BYTES:
234 self.pbtype = 'BYTES'
235 if self.allocation == 'STATIC':
236 self.ctype = self.struct_name + self.name + 't'
237 self.enc_size = varint_max_size(self.max_size) + self.max_size
238 elif self.allocation == 'POINTER':
239 self.ctype = 'pb_bytes_ptr_t'
240 elif desc.type == FieldD.TYPE_MESSAGE:
241 self.pbtype = 'MESSAGE'
242 self.ctype = self.submsgname = names_from_type_name(desc.type_name)
243 self.enc_size = None # Needs to be filled in after the message type is available
245 raise NotImplementedError(desc.type)
247 def __cmp__(self, other):
248 return cmp(self.tag, other.tag)
252 if self.allocation == 'POINTER':
253 if self.rules == 'REPEATED':
254 result += ' size_t ' + self.name + '_count;\n'
256 if self.pbtype == 'MESSAGE':
257 # Use struct definition, so recursive submessages are possible
258 result += ' struct _%s *%s;' % (self.ctype, self.name)
259 elif self.rules == 'REPEATED' and self.pbtype == 'STRING':
260 # String arrays need to be defined as pointers to pointers
261 result += ' %s **%s;' % (self.ctype, self.name)
263 result += ' %s *%s;' % (self.ctype, self.name)
264 elif self.allocation == 'CALLBACK':
265 result += ' pb_callback_t %s;' % self.name
267 if self.rules == 'OPTIONAL' and self.allocation == 'STATIC':
268 result += ' bool has_' + self.name + ';\n'
269 elif self.rules == 'REPEATED' and self.allocation == 'STATIC':
270 result += ' size_t ' + self.name + '_count;\n'
271 result += ' %s %s%s;' % (self.ctype, self.name, self.array_decl)
275 '''Return definitions for any special types this field might need.'''
276 if self.pbtype == 'BYTES' and self.allocation == 'STATIC':
277 result = 'typedef struct {\n'
278 result += ' size_t size;\n'
279 result += ' uint8_t bytes[%d];\n' % self.max_size
280 result += '} %s;\n' % self.ctype
285 def default_decl(self, declaration_only = False):
286 '''Return definition for this field's default value.'''
287 if self.default is None:
290 ctype, default = self.ctype, self.default
293 if self.pbtype == 'STRING':
294 if self.allocation != 'STATIC':
295 return None # Not implemented
297 array_decl = '[%d]' % self.max_size
298 default = str(self.default).encode('string_escape')
299 default = default.replace('"', '\\"')
300 default = '"' + default + '"'
301 elif self.pbtype == 'BYTES':
302 if self.allocation != 'STATIC':
303 return None # Not implemented
305 data = self.default.decode('string_escape')
306 data = ['0x%02x' % ord(c) for c in data]
307 default = '{%d, {%s}}' % (len(data), ','.join(data))
310 return 'extern const %s %s_default%s;' % (ctype, self.struct_name + self.name, array_decl)
312 return 'const %s %s_default%s = %s;' % (ctype, self.struct_name + self.name, array_decl, default)
315 '''Return the #define for the tag number of this field.'''
316 identifier = '%s_%s_tag' % (self.struct_name, self.name)
317 return '#define %-40s %d\n' % (identifier, self.tag)
319 def pb_field_t(self, prev_field_name):
320 '''Return the pb_field_t initializer to use in the constant array.
321 prev_field_name is the name of the previous field or None.
323 result = ' PB_FIELD2(%3d, ' % self.tag
324 result += '%-8s, ' % self.pbtype
325 result += '%s, ' % self.rules
326 result += '%-8s, ' % self.allocation
327 result += '%s, ' % ("FIRST" if not prev_field_name else "OTHER")
328 result += '%s, ' % self.struct_name
329 result += '%s, ' % self.name
330 result += '%s, ' % (prev_field_name or self.name)
332 if self.pbtype == 'MESSAGE':
333 result += '&%s_fields)' % self.submsgname
334 elif self.default is None:
336 elif self.pbtype in ['BYTES', 'STRING'] and self.allocation != 'STATIC':
337 result += '0)' # Arbitrary size default values not implemented
339 result += '&%s_default)' % (self.struct_name + self.name)
343 def largest_field_value(self):
344 '''Determine if this field needs 16bit or 32bit pb_field_t structure to compile properly.
345 Returns numeric value or a C-expression for assert.'''
346 if self.pbtype == 'MESSAGE':
347 if self.rules == 'REPEATED' and self.allocation == 'STATIC':
348 return 'pb_membersize(%s, %s[0])' % (self.struct_name, self.name)
350 return 'pb_membersize(%s, %s)' % (self.struct_name, self.name)
352 return max(self.tag, self.max_size, self.max_count)
354 def encoded_size(self, allmsgs):
355 '''Return the maximum size that this field can take when encoded,
356 including the field tag. If the size cannot be determined, returns
359 if self.allocation != 'STATIC':
362 if self.pbtype == 'MESSAGE':
364 if msg.name == self.submsgname:
365 encsize = msg.encoded_size(allmsgs)
367 return None # Submessage size is indeterminate
369 # Include submessage length prefix
370 encsize += varint_max_size(encsize.upperlimit())
373 # Submessage cannot be found, this currently occurs when
374 # the submessage type is defined in a different file.
375 # Instead of direct numeric value, reference the size that
376 # has been #defined in the other file.
377 encsize = EncodedSize(self.submsgname + 'size')
379 # We will have to make a conservative assumption on the length
380 # prefix size, though.
383 elif self.enc_size is None:
384 raise RuntimeError("Could not determine encoded size for %s.%s"
385 % (self.struct_name, self.name))
387 encsize = EncodedSize(self.enc_size)
389 encsize += varint_max_size(self.tag << 3) # Tag + wire type
391 if self.rules == 'REPEATED':
392 # Decoders must be always able to handle unpacked arrays.
393 # Therefore we have to reserve space for it, even though
394 # we emit packed arrays ourselves.
395 encsize *= self.max_count
400 class ExtensionRange(Field):
401 def __init__(self, struct_name, range_start, field_options):
402 '''Implements a special pb_extension_t* field in an extensible message
403 structure. The range_start signifies the index at which the extensions
404 start. Not necessarily all tags above this are extensions, it is merely
405 a speed optimization.
407 self.tag = range_start
408 self.struct_name = struct_name
409 self.name = 'extensions'
410 self.pbtype = 'EXTENSION'
411 self.rules = 'OPTIONAL'
412 self.allocation = 'CALLBACK'
413 self.ctype = 'pb_extension_t'
420 return ' pb_extension_t *extensions;'
428 def encoded_size(self, allmsgs):
429 # We exclude extensions from the count, because they cannot be known
430 # until runtime. Other option would be to return None here, but this
431 # way the value remains useful if extensions are not used.
432 return EncodedSize(0)
434 class ExtensionField(Field):
435 def __init__(self, struct_name, desc, field_options):
436 self.fullname = struct_name + desc.name
437 self.extendee_name = names_from_type_name(desc.extendee)
438 Field.__init__(self, self.fullname + 'struct', desc, field_options)
440 if self.rules != 'OPTIONAL':
444 self.rules = 'OPTEXT'
447 '''Return the #define for the tag number of this field.'''
448 identifier = '%s_tag' % self.fullname
449 return '#define %-40s %d\n' % (identifier, self.tag)
451 def extension_decl(self):
452 '''Declaration of the extension type in the .pb.h file'''
454 msg = '/* Extension field %s was skipped because only "optional"\n' % self.fullname
455 msg +=' type of extension fields is currently supported. */\n'
458 return 'extern const pb_extension_type_t %s;\n' % self.fullname
460 def extension_def(self):
461 '''Definition of the extension type in the .pb.c file'''
466 result = 'typedef struct {\n'
468 result += '\n} %s;\n\n' % self.struct_name
469 result += ('static const pb_field_t %s_field = \n %s;\n\n' %
470 (self.fullname, self.pb_field_t(None)))
471 result += 'const pb_extension_type_t %s = {\n' % self.fullname
474 result += ' &%s_field\n' % self.fullname
479 # ---------------------------------------------------------------------------
480 # Generation of messages (structures)
481 # ---------------------------------------------------------------------------
485 def __init__(self, names, desc, message_options):
490 field_options = get_nanopb_suboptions(f, message_options, self.name + f.name)
491 if field_options.type != nanopb_pb2.FT_IGNORE:
492 self.fields.append(Field(self.name, f, field_options))
494 if len(desc.extension_range) > 0:
495 field_options = get_nanopb_suboptions(desc, message_options, self.name + 'extensions')
496 range_start = min([r.start for r in desc.extension_range])
497 if field_options.type != nanopb_pb2.FT_IGNORE:
498 self.fields.append(ExtensionRange(self.name, range_start, field_options))
500 self.packed = message_options.packed_struct
501 self.ordered_fields = self.fields[:]
502 self.ordered_fields.sort()
504 def get_dependencies(self):
505 '''Get list of type names that this structure refers to.'''
506 return [str(field.ctype) for field in self.fields]
509 result = 'typedef struct _%s {\n' % self.name
511 if not self.ordered_fields:
512 # Empty structs are not allowed in C standard.
513 # Therefore add a dummy field if an empty message occurs.
514 result += ' uint8_t dummy_field;'
516 result += '\n'.join([str(f) for f in self.ordered_fields])
520 result += ' pb_packed'
522 result += ' %s;' % self.name
525 result = 'PB_PACKED_STRUCT_START\n' + result
526 result += '\nPB_PACKED_STRUCT_END'
532 for field in self.fields:
533 types = field.types()
534 if types is not None:
535 result += types + '\n'
538 def default_decl(self, declaration_only = False):
540 for field in self.fields:
541 default = field.default_decl(declaration_only)
542 if default is not None:
543 result += default + '\n'
546 def fields_declaration(self):
547 result = 'extern const pb_field_t %s_fields[%d];' % (self.name, len(self.fields) + 1)
550 def fields_definition(self):
551 result = 'const pb_field_t %s_fields[%d] = {\n' % (self.name, len(self.fields) + 1)
554 for field in self.ordered_fields:
555 result += field.pb_field_t(prev)
559 result += ' PB_LAST_FIELD\n};'
562 def encoded_size(self, allmsgs):
563 '''Return the maximum size that this message can take when encoded.
564 If the size cannot be determined, returns None.
566 size = EncodedSize(0)
567 for field in self.fields:
568 fsize = field.encoded_size(allmsgs)
576 # ---------------------------------------------------------------------------
577 # Processing of entire .proto files
578 # ---------------------------------------------------------------------------
581 def iterate_messages(desc, names = Names()):
582 '''Recursively find all messages. For each, yield name, DescriptorProto.'''
583 if hasattr(desc, 'message_type'):
584 submsgs = desc.message_type
586 submsgs = desc.nested_type
588 for submsg in submsgs:
589 sub_names = names + submsg.name
590 yield sub_names, submsg
592 for x in iterate_messages(submsg, sub_names):
595 def iterate_extensions(desc, names = Names()):
596 '''Recursively find all extensions.
597 For each, yield name, FieldDescriptorProto.
599 for extension in desc.extension:
600 yield names, extension
602 for subname, subdesc in iterate_messages(desc, names):
603 for extension in subdesc.extension:
604 yield subname, extension
606 def parse_file(fdesc, file_options):
607 '''Takes a FileDescriptorProto and returns tuple (enums, messages, extensions).'''
614 base_name = Names(fdesc.package.split('.'))
618 for enum in fdesc.enum_type:
619 enum_options = get_nanopb_suboptions(enum, file_options, base_name + enum.name)
620 enums.append(Enum(base_name, enum, enum_options))
622 for names, message in iterate_messages(fdesc, base_name):
623 message_options = get_nanopb_suboptions(message, file_options, names)
624 messages.append(Message(names, message, message_options))
625 for enum in message.enum_type:
626 enum_options = get_nanopb_suboptions(enum, message_options, names + enum.name)
627 enums.append(Enum(names, enum, enum_options))
629 for names, extension in iterate_extensions(fdesc, base_name):
630 field_options = get_nanopb_suboptions(extension, file_options, names)
631 if field_options.type != nanopb_pb2.FT_IGNORE:
632 extensions.append(ExtensionField(names, extension, field_options))
634 # Fix field default values where enum short names are used.
636 if not enum.options.long_names:
637 for message in messages:
638 for field in message.fields:
639 if field.default in enum.value_longnames:
640 idx = enum.value_longnames.index(field.default)
641 field.default = enum.values[idx][0]
643 return enums, messages, extensions
647 From http://code.activestate.com/recipes/577413-topological-sort/
648 This function is under the MIT license.
650 for k, v in data.items():
651 v.discard(k) # Ignore self dependencies
652 extra_items_in_deps = reduce(set.union, data.values(), set()) - set(data.keys())
653 data.update(dict([(item, set()) for item in extra_items_in_deps]))
655 ordered = set(item for item,dep in data.items() if not dep)
658 for item in sorted(ordered):
660 data = dict([(item, (dep - ordered)) for item,dep in data.items()
661 if item not in ordered])
662 assert not data, "A cyclic dependency exists amongst %r" % data
664 def sort_dependencies(messages):
665 '''Sort a list of Messages based on dependencies.'''
668 for message in messages:
669 dependencies[str(message.name)] = set(message.get_dependencies())
670 message_by_name[str(message.name)] = message
672 for msgname in toposort2(dependencies):
673 if msgname in message_by_name:
674 yield message_by_name[msgname]
676 def make_identifier(headername):
677 '''Make #ifndef identifier that contains uppercase A-Z and digits 0-9'''
679 for c in headername.upper():
686 def generate_header(dependencies, headername, enums, messages, extensions, options):
687 '''Generate content for a header file.
688 Generates strings, which should be concatenated and stored to file.
691 yield '/* Automatically generated nanopb header */\n'
692 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
694 symbol = make_identifier(headername)
695 yield '#ifndef _PB_%s_\n' % symbol
696 yield '#define _PB_%s_\n' % symbol
698 yield options.libformat % ('pb.h')
700 # no %s specified - use whatever was passed in as options.libformat
701 yield options.libformat
704 for dependency in dependencies:
705 noext = os.path.splitext(dependency)[0]
706 yield options.genformat % (noext + '.' + options.extension + '.h')
709 yield '#ifdef __cplusplus\n'
710 yield 'extern "C" {\n'
713 yield '/* Enum definitions */\n'
715 yield str(enum) + '\n\n'
717 yield '/* Struct definitions */\n'
718 for msg in sort_dependencies(messages):
720 yield str(msg) + '\n\n'
723 yield '/* Extensions */\n'
724 for extension in extensions:
725 yield extension.extension_decl()
728 yield '/* Default values for struct fields */\n'
730 yield msg.default_decl(True)
733 yield '/* Field tags (for use in manual encoding/decoding) */\n'
734 for msg in sort_dependencies(messages):
735 for field in msg.fields:
737 for extension in extensions:
738 yield extension.tags()
741 yield '/* Struct field encoding specification for nanopb */\n'
743 yield msg.fields_declaration() + '\n'
746 yield '/* Maximum encoded size of messages (where known) */\n'
748 msize = msg.encoded_size(messages)
749 if msize is not None:
750 identifier = '%s_size' % msg.name
751 yield '#define %-40s %s\n' % (identifier, msize)
754 yield '#ifdef __cplusplus\n'
755 yield '} /* extern "C" */\n'
761 def generate_source(headername, enums, messages, extensions, options):
762 '''Generate content for a source file.'''
764 yield '/* Automatically generated nanopb constant definitions */\n'
765 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
766 yield options.genformat % (headername)
770 yield msg.default_decl(False)
775 yield msg.fields_definition() + '\n\n'
777 for ext in extensions:
778 yield ext.extension_def() + '\n'
780 # Add checks for numeric limits
782 count_required_fields = lambda m: len([f for f in msg.fields if f.rules == 'REQUIRED'])
783 largest_msg = max(messages, key = count_required_fields)
784 largest_count = count_required_fields(largest_msg)
785 if largest_count > 64:
786 yield '\n/* Check that missing required fields will be properly detected */\n'
787 yield '#if PB_MAX_REQUIRED_FIELDS < %d\n' % largest_count
788 yield '#error Properly detecting missing required fields in %s requires \\\n' % largest_msg.name
789 yield ' setting PB_MAX_REQUIRED_FIELDS to %d or more.\n' % largest_count
797 checks_msgnames.append(msg.name)
798 for field in msg.fields:
799 status = field.largest_field_value()
800 if isinstance(status, (str, unicode)):
801 checks.append(status)
804 worst_field = str(field.struct_name) + '.' + str(field.name)
806 if worst > 255 or checks:
807 yield '\n/* Check that field information fits in pb_field_t */\n'
810 yield '#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT)\n'
812 yield '#error Field descriptor for %s is too large. Define PB_FIELD_16BIT to fix this.\n' % worst_field
814 assertion = ' && '.join(str(c) + ' < 256' for c in checks)
815 msgs = '_'.join(str(n) for n in checks_msgnames)
816 yield 'STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
819 if worst > 65535 or checks:
820 yield '#if !defined(PB_FIELD_32BIT)\n'
822 yield '#error Field descriptor for %s is too large. Define PB_FIELD_32BIT to fix this.\n' % worst_field
824 assertion = ' && '.join(str(c) + ' < 65536' for c in checks)
825 msgs = '_'.join(str(n) for n in checks_msgnames)
826 yield 'STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
829 # Add check for sizeof(double)
832 for field in msg.fields:
833 if field.ctype == 'double':
838 yield '/* On some platforms (such as AVR), double is really float.\n'
839 yield ' * These are not directly supported by nanopb, but see example_avr_double.\n'
840 yield ' * To get rid of this error, remove any double fields from your .proto.\n'
842 yield 'STATIC_ASSERT(sizeof(double) == 8, DOUBLE_MUST_BE_8_BYTES)\n'
846 # ---------------------------------------------------------------------------
847 # Options parsing for the .proto files
848 # ---------------------------------------------------------------------------
850 from fnmatch import fnmatch
852 def read_options_file(infile):
853 '''Parse a separate options file to list:
854 [(namemask, options), ...]
859 if not line or line.startswith('//') or line.startswith('#'):
862 parts = line.split(None, 1)
863 opts = nanopb_pb2.NanoPBOptions()
864 text_format.Merge(parts[1], opts)
865 results.append((parts[0], opts))
870 '''Ugly global variables, should find a good way to pass these.'''
871 verbose_options = False
872 separate_options = []
874 def get_nanopb_suboptions(subdesc, options, name):
875 '''Get copy of options, and merge information from subdesc.'''
876 new_options = nanopb_pb2.NanoPBOptions()
877 new_options.CopyFrom(options)
879 # Handle options defined in a separate file
880 dotname = '.'.join(name.parts)
881 for namemask, options in Globals.separate_options:
882 if fnmatch(dotname, namemask):
883 new_options.MergeFrom(options)
885 # Handle options defined in .proto
886 if isinstance(subdesc.options, descriptor.FieldOptions):
887 ext_type = nanopb_pb2.nanopb
888 elif isinstance(subdesc.options, descriptor.FileOptions):
889 ext_type = nanopb_pb2.nanopb_fileopt
890 elif isinstance(subdesc.options, descriptor.MessageOptions):
891 ext_type = nanopb_pb2.nanopb_msgopt
892 elif isinstance(subdesc.options, descriptor.EnumOptions):
893 ext_type = nanopb_pb2.nanopb_enumopt
895 raise Exception("Unknown options type")
897 if subdesc.options.HasExtension(ext_type):
898 ext = subdesc.options.Extensions[ext_type]
899 new_options.MergeFrom(ext)
901 if Globals.verbose_options:
902 print "Options for " + dotname + ":"
903 print text_format.MessageToString(new_options)
908 # ---------------------------------------------------------------------------
909 # Command line interface
910 # ---------------------------------------------------------------------------
914 from optparse import OptionParser
916 optparser = OptionParser(
917 usage = "Usage: nanopb_generator.py [options] file.pb ...",
918 epilog = "Compile file.pb from file.proto by: 'protoc -ofile.pb file.proto'. " +
919 "Output will be written to file.pb.h and file.pb.c.")
920 optparser.add_option("-x", dest="exclude", metavar="FILE", action="append", default=[],
921 help="Exclude file from generated #include list.")
922 optparser.add_option("-e", "--extension", dest="extension", metavar="EXTENSION", default="pb",
923 help="Set extension to use instead of 'pb' for generated files. [default: %default]")
924 optparser.add_option("-f", "--options-file", dest="options_file", metavar="FILE", default="%s.options",
925 help="Set name of a separate generator options file.")
926 optparser.add_option("-Q", "--generated-include-format", dest="genformat",
927 metavar="FORMAT", default='#include "%s"\n',
928 help="Set format string to use for including other .pb.h files. [default: %default]")
929 optparser.add_option("-L", "--library-include-format", dest="libformat",
930 metavar="FORMAT", default='#include <%s>\n',
931 help="Set format string to use for including the nanopb pb.h header. [default: %default]")
932 optparser.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False,
933 help="Don't print anything except errors.")
934 optparser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
935 help="Print more information.")
936 optparser.add_option("-s", dest="settings", metavar="OPTION:VALUE", action="append", default=[],
937 help="Set generator option (max_size, max_count etc.).")
939 def process_file(filename, fdesc, options):
940 '''Process a single file.
941 filename: The full path to the .proto or .pb source file, as string.
942 fdesc: The loaded FileDescriptorSet, or None to read from the input file.
943 options: Command line options as they come from OptionsParser.
946 {'headername': Name of header file,
947 'headerdata': Data for the .h header file,
948 'sourcename': Name of the source code file,
949 'sourcedata': Data for the .c source code file
952 toplevel_options = nanopb_pb2.NanoPBOptions()
953 for s in options.settings:
954 text_format.Merge(s, toplevel_options)
957 data = open(filename, 'rb').read()
958 fdesc = descriptor.FileDescriptorSet.FromString(data).file[0]
960 # Check if there is a separate .options file
962 optfilename = options.options_file % os.path.splitext(filename)[0]
964 # No %s specified, use the filename as-is
965 optfilename = options.options_file
968 print 'Reading options from ' + optfilename
970 if os.path.isfile(optfilename):
971 Globals.separate_options = read_options_file(open(optfilename, "rU"))
973 Globals.separate_options = []
976 file_options = get_nanopb_suboptions(fdesc, toplevel_options, Names([filename]))
977 enums, messages, extensions = parse_file(fdesc, file_options)
979 # Decide the file names
980 noext = os.path.splitext(filename)[0]
981 headername = noext + '.' + options.extension + '.h'
982 sourcename = noext + '.' + options.extension + '.c'
983 headerbasename = os.path.basename(headername)
985 # List of .proto files that should not be included in the C header file
986 # even if they are mentioned in the source .proto.
987 excludes = ['nanopb.proto', 'google/protobuf/descriptor.proto'] + options.exclude
988 dependencies = [d for d in fdesc.dependency if d not in excludes]
990 headerdata = ''.join(generate_header(dependencies, headerbasename, enums,
991 messages, extensions, options))
993 sourcedata = ''.join(generate_source(headerbasename, enums,
994 messages, extensions, options))
996 return {'headername': headername, 'headerdata': headerdata,
997 'sourcename': sourcename, 'sourcedata': sourcedata}
1000 '''Main function when invoked directly from the command line.'''
1002 options, filenames = optparser.parse_args()
1005 optparser.print_help()
1009 options.verbose = False
1011 Globals.verbose_options = options.verbose
1013 for filename in filenames:
1014 results = process_file(filename, None, options)
1016 if not options.quiet:
1017 print "Writing to " + results['headername'] + " and " + results['sourcename']
1019 open(results['headername'], 'w').write(results['headerdata'])
1020 open(results['sourcename'], 'w').write(results['sourcedata'])
1023 '''Main function when invoked as a protoc plugin.'''
1026 if sys.platform == "win32":
1028 # Set stdin and stdout to binary mode
1029 msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
1030 msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
1032 import proto.plugin_pb2 as plugin_pb2
1033 data = sys.stdin.read()
1034 request = plugin_pb2.CodeGeneratorRequest.FromString(data)
1037 args = shlex.split(request.parameter)
1038 options, dummy = optparser.parse_args(args)
1040 # We can't go printing stuff to stdout
1041 Globals.verbose_options = False
1042 options.verbose = False
1043 options.quiet = True
1045 response = plugin_pb2.CodeGeneratorResponse()
1047 for filename in request.file_to_generate:
1048 for fdesc in request.proto_file:
1049 if fdesc.name == filename:
1050 results = process_file(filename, fdesc, options)
1052 f = response.file.add()
1053 f.name = results['headername']
1054 f.content = results['headerdata']
1056 f = response.file.add()
1057 f.name = results['sourcename']
1058 f.content = results['sourcedata']
1060 sys.stdout.write(response.SerializeToString())
1062 if __name__ == '__main__':
1063 # Check if we are running as a plugin under protoc
1064 if 'protoc-gen-' in sys.argv[0] or '--protoc-plugin' in sys.argv: