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 "*************************************************************"
18 import proto.nanopb_pb2 as nanopb_pb2
19 import proto.descriptor_pb2 as descriptor
24 # ---------------------------------------------------------------------------
25 # Generation of single fields
26 # ---------------------------------------------------------------------------
31 # Values are tuple (c type, pb type, encoded size)
32 FieldD = descriptor.FieldDescriptorProto
34 FieldD.TYPE_BOOL: ('bool', 'BOOL', 1),
35 FieldD.TYPE_DOUBLE: ('double', 'DOUBLE', 8),
36 FieldD.TYPE_FIXED32: ('uint32_t', 'FIXED32', 4),
37 FieldD.TYPE_FIXED64: ('uint64_t', 'FIXED64', 8),
38 FieldD.TYPE_FLOAT: ('float', 'FLOAT', 4),
39 FieldD.TYPE_INT32: ('int32_t', 'INT32', 10),
40 FieldD.TYPE_INT64: ('int64_t', 'INT64', 10),
41 FieldD.TYPE_SFIXED32: ('int32_t', 'SFIXED32', 4),
42 FieldD.TYPE_SFIXED64: ('int64_t', 'SFIXED64', 8),
43 FieldD.TYPE_SINT32: ('int32_t', 'SINT32', 5),
44 FieldD.TYPE_SINT64: ('int64_t', 'SINT64', 10),
45 FieldD.TYPE_UINT32: ('uint32_t', 'UINT32', 5),
46 FieldD.TYPE_UINT64: ('uint64_t', 'UINT64', 10)
50 '''Keeps a set of nested names and formats them to C identifier.'''
51 def __init__(self, parts = ()):
52 if isinstance(parts, Names):
54 self.parts = tuple(parts)
57 return '_'.join(self.parts)
59 def __add__(self, other):
60 if isinstance(other, (str, unicode)):
61 return Names(self.parts + (other,))
62 elif isinstance(other, tuple):
63 return Names(self.parts + other)
65 raise ValueError("Name parts should be of type str")
67 def __eq__(self, other):
68 return isinstance(other, Names) and self.parts == other.parts
70 def names_from_type_name(type_name):
71 '''Parse Names() from FieldDescriptorProto type_name'''
72 if type_name[0] != '.':
73 raise NotImplementedError("Lookup of non-absolute type names is not supported")
74 return Names(type_name[1:].split('.'))
76 def varint_max_size(max_value):
77 '''Returns the maximum number of bytes a varint can take when encoded.'''
78 for i in range(1, 11):
79 if (max_value >> (i * 7)) == 0:
81 raise ValueError("Value too large for varint: " + str(max_value))
83 assert varint_max_size(0) == 1
84 assert varint_max_size(127) == 1
85 assert varint_max_size(128) == 2
88 '''Class used to represent the encoded size of a field or a message.
89 Consists of a combination of symbolic sizes and integer sizes.'''
90 def __init__(self, value = 0, symbols = []):
91 if isinstance(value, (str, Names)):
92 symbols = [str(value)]
95 self.symbols = symbols
97 def __add__(self, other):
98 if isinstance(other, (int, long)):
99 return EncodedSize(self.value + other, self.symbols)
100 elif isinstance(other, (str, Names)):
101 return EncodedSize(self.value, self.symbols + [str(other)])
102 elif isinstance(other, EncodedSize):
103 return EncodedSize(self.value + other.value, self.symbols + other.symbols)
105 raise ValueError("Cannot add size: " + repr(other))
107 def __mul__(self, other):
108 if isinstance(other, (int, long)):
109 return EncodedSize(self.value * other, [str(other) + '*' + s for s in self.symbols])
111 raise ValueError("Cannot multiply size: " + repr(other))
115 return str(self.value)
117 return '(' + str(self.value) + ' + ' + ' + '.join(self.symbols) + ')'
119 def upperlimit(self):
126 def __init__(self, names, desc, enum_options):
127 '''desc is EnumDescriptorProto'''
129 self.options = enum_options
130 self.names = names + desc.name
132 if enum_options.long_names:
133 self.values = [(self.names + x.name, x.number) for x in desc.value]
135 self.values = [(names + x.name, x.number) for x in desc.value]
137 self.value_longnames = [self.names + x.name for x in desc.value]
140 result = 'typedef enum _%s {\n' % self.names
141 result += ',\n'.join([" %s = %d" % x for x in self.values])
142 result += '\n} %s;' % self.names
146 def __init__(self, struct_name, desc, field_options):
147 '''desc is FieldDescriptorProto'''
148 self.tag = desc.number
149 self.struct_name = struct_name
150 self.name = desc.name
153 self.max_count = None
157 # Parse field options
158 if field_options.HasField("max_size"):
159 self.max_size = field_options.max_size
161 if field_options.HasField("max_count"):
162 self.max_count = field_options.max_count
164 if desc.HasField('default_value'):
165 self.default = desc.default_value
167 # Check field rules, i.e. required/optional/repeated.
169 if desc.label == FieldD.LABEL_REQUIRED:
170 self.rules = 'REQUIRED'
171 elif desc.label == FieldD.LABEL_OPTIONAL:
172 self.rules = 'OPTIONAL'
173 elif desc.label == FieldD.LABEL_REPEATED:
174 self.rules = 'REPEATED'
175 if self.max_count is None:
176 can_be_static = False
178 self.array_decl = '[%d]' % self.max_count
180 raise NotImplementedError(desc.label)
182 # Check if the field can be implemented with static allocation
183 # i.e. whether the data size is known.
184 if desc.type == FieldD.TYPE_STRING and self.max_size is None:
185 can_be_static = False
187 if desc.type == FieldD.TYPE_BYTES and self.max_size is None:
188 can_be_static = False
190 # Decide how the field data will be allocated
191 if field_options.type == nanopb_pb2.FT_DEFAULT:
193 field_options.type = nanopb_pb2.FT_STATIC
195 field_options.type = nanopb_pb2.FT_CALLBACK
197 if field_options.type == nanopb_pb2.FT_STATIC and not can_be_static:
198 raise Exception("Field %s is defined as static, but max_size or "
199 "max_count is not given." % self.name)
201 if field_options.type == nanopb_pb2.FT_STATIC:
202 self.allocation = 'STATIC'
203 elif field_options.type == nanopb_pb2.FT_POINTER:
204 self.allocation = 'POINTER'
205 elif field_options.type == nanopb_pb2.FT_CALLBACK:
206 self.allocation = 'CALLBACK'
208 raise NotImplementedError(field_options.type)
210 # Decide the C data type to use in the struct.
211 if datatypes.has_key(desc.type):
212 self.ctype, self.pbtype, self.enc_size = datatypes[desc.type]
213 elif desc.type == FieldD.TYPE_ENUM:
215 self.ctype = names_from_type_name(desc.type_name)
216 if self.default is not None:
217 self.default = self.ctype + self.default
218 self.enc_size = 5 # protoc rejects enum values > 32 bits
219 elif desc.type == FieldD.TYPE_STRING:
220 self.pbtype = 'STRING'
222 if self.allocation == 'STATIC':
224 self.array_decl += '[%d]' % self.max_size
225 self.enc_size = varint_max_size(self.max_size) + self.max_size
226 elif desc.type == FieldD.TYPE_BYTES:
227 self.pbtype = 'BYTES'
228 if self.allocation == 'STATIC':
229 self.ctype = self.struct_name + self.name + 't'
230 self.enc_size = varint_max_size(self.max_size) + self.max_size
231 elif self.allocation == 'POINTER':
232 self.ctype = 'pb_bytes_ptr_t'
233 elif desc.type == FieldD.TYPE_MESSAGE:
234 self.pbtype = 'MESSAGE'
235 self.ctype = self.submsgname = names_from_type_name(desc.type_name)
236 self.enc_size = None # Needs to be filled in after the message type is available
238 raise NotImplementedError(desc.type)
240 def __cmp__(self, other):
241 return cmp(self.tag, other.tag)
245 if self.allocation == 'POINTER':
246 if self.rules == 'REPEATED':
247 result += ' size_t ' + self.name + '_count;\n'
249 if self.pbtype == 'MESSAGE':
250 # Use struct definition, so recursive submessages are possible
251 result += ' struct _%s *%s;' % (self.ctype, self.name)
252 elif self.rules == 'REPEATED' and self.pbtype == 'STRING':
253 # String arrays need to be defined as pointers to pointers
254 result += ' %s **%s;' % (self.ctype, self.name)
256 result += ' %s *%s;' % (self.ctype, self.name)
257 elif self.allocation == 'CALLBACK':
258 result += ' pb_callback_t %s;' % self.name
260 if self.rules == 'OPTIONAL' and self.allocation == 'STATIC':
261 result += ' bool has_' + self.name + ';\n'
262 elif self.rules == 'REPEATED' and self.allocation == 'STATIC':
263 result += ' size_t ' + self.name + '_count;\n'
264 result += ' %s %s%s;' % (self.ctype, self.name, self.array_decl)
268 '''Return definitions for any special types this field might need.'''
269 if self.pbtype == 'BYTES' and self.allocation == 'STATIC':
270 result = 'typedef struct {\n'
271 result += ' size_t size;\n'
272 result += ' uint8_t bytes[%d];\n' % self.max_size
273 result += '} %s;\n' % self.ctype
278 def default_decl(self, declaration_only = False):
279 '''Return definition for this field's default value.'''
280 if self.default is None:
283 ctype, default = self.ctype, self.default
286 if self.pbtype == 'STRING':
287 if self.allocation != 'STATIC':
288 return None # Not implemented
290 array_decl = '[%d]' % self.max_size
291 default = str(self.default).encode('string_escape')
292 default = default.replace('"', '\\"')
293 default = '"' + default + '"'
294 elif self.pbtype == 'BYTES':
295 if self.allocation != 'STATIC':
296 return None # Not implemented
298 data = self.default.decode('string_escape')
299 data = ['0x%02x' % ord(c) for c in data]
300 default = '{%d, {%s}}' % (len(data), ','.join(data))
303 return 'extern const %s %s_default%s;' % (ctype, self.struct_name + self.name, array_decl)
305 return 'const %s %s_default%s = %s;' % (ctype, self.struct_name + self.name, array_decl, default)
308 '''Return the #define for the tag number of this field.'''
309 identifier = '%s_%s_tag' % (self.struct_name, self.name)
310 return '#define %-40s %d\n' % (identifier, self.tag)
312 def pb_field_t(self, prev_field_name):
313 '''Return the pb_field_t initializer to use in the constant array.
314 prev_field_name is the name of the previous field or None.
316 result = ' PB_FIELD2(%3d, ' % self.tag
317 result += '%-8s, ' % self.pbtype
318 result += '%s, ' % self.rules
319 result += '%-8s, ' % self.allocation
320 result += '%s, ' % ("FIRST" if not prev_field_name else "OTHER")
321 result += '%s, ' % self.struct_name
322 result += '%s, ' % self.name
323 result += '%s, ' % (prev_field_name or self.name)
325 if self.pbtype == 'MESSAGE':
326 result += '&%s_fields)' % self.submsgname
327 elif self.default is None:
329 elif self.pbtype in ['BYTES', 'STRING'] and self.allocation != 'STATIC':
330 result += '0)' # Arbitrary size default values not implemented
332 result += '&%s_default)' % (self.struct_name + self.name)
336 def largest_field_value(self):
337 '''Determine if this field needs 16bit or 32bit pb_field_t structure to compile properly.
338 Returns numeric value or a C-expression for assert.'''
339 if self.pbtype == 'MESSAGE':
340 if self.rules == 'REPEATED' and self.allocation == 'STATIC':
341 return 'pb_membersize(%s, %s[0])' % (self.struct_name, self.name)
343 return 'pb_membersize(%s, %s)' % (self.struct_name, self.name)
345 return max(self.tag, self.max_size, self.max_count)
347 def encoded_size(self, allmsgs):
348 '''Return the maximum size that this field can take when encoded,
349 including the field tag. If the size cannot be determined, returns
352 if self.allocation != 'STATIC':
355 if self.pbtype == 'MESSAGE':
357 if msg.name == self.submsgname:
358 encsize = msg.encoded_size(allmsgs)
360 return None # Submessage size is indeterminate
362 # Include submessage length prefix
363 encsize += varint_max_size(encsize.upperlimit())
366 # Submessage cannot be found, this currently occurs when
367 # the submessage type is defined in a different file.
368 # Instead of direct numeric value, reference the size that
369 # has been #defined in the other file.
370 encsize = EncodedSize(self.submsgname + 'size')
372 # We will have to make a conservative assumption on the length
373 # prefix size, though.
376 elif self.enc_size is None:
377 raise RuntimeError("Could not determine encoded size for %s.%s"
378 % (self.struct_name, self.name))
380 encsize = EncodedSize(self.enc_size)
382 encsize += varint_max_size(self.tag << 3) # Tag + wire type
384 if self.rules == 'REPEATED':
385 # Decoders must be always able to handle unpacked arrays.
386 # Therefore we have to reserve space for it, even though
387 # we emit packed arrays ourselves.
388 encsize *= self.max_count
393 class ExtensionRange(Field):
394 def __init__(self, struct_name, range_start, field_options):
395 '''Implements a special pb_extension_t* field in an extensible message
396 structure. The range_start signifies the index at which the extensions
397 start. Not necessarily all tags above this are extensions, it is merely
398 a speed optimization.
400 self.tag = range_start
401 self.struct_name = struct_name
402 self.name = 'extensions'
403 self.pbtype = 'EXTENSION'
404 self.rules = 'OPTIONAL'
405 self.allocation = 'CALLBACK'
406 self.ctype = 'pb_extension_t'
413 return ' pb_extension_t *extensions;'
421 def encoded_size(self, allmsgs):
422 # We exclude extensions from the count, because they cannot be known
423 # until runtime. Other option would be to return None here, but this
424 # way the value remains useful if extensions are not used.
425 return EncodedSize(0)
427 class ExtensionField(Field):
428 def __init__(self, struct_name, desc, field_options):
429 self.fullname = struct_name + desc.name
430 self.extendee_name = names_from_type_name(desc.extendee)
431 Field.__init__(self, self.fullname + 'struct', desc, field_options)
433 if self.rules != 'OPTIONAL':
437 self.rules = 'OPTEXT'
440 '''Return the #define for the tag number of this field.'''
441 identifier = '%s_tag' % self.fullname
442 return '#define %-40s %d\n' % (identifier, self.tag)
444 def extension_decl(self):
445 '''Declaration of the extension type in the .pb.h file'''
447 msg = '/* Extension field %s was skipped because only "optional"\n' % self.fullname
448 msg +=' type of extension fields is currently supported. */\n'
451 return 'extern const pb_extension_type_t %s;\n' % self.fullname
453 def extension_def(self):
454 '''Definition of the extension type in the .pb.c file'''
459 result = 'typedef struct {\n'
461 result += '\n} %s;\n\n' % self.struct_name
462 result += ('static const pb_field_t %s_field = \n %s;\n\n' %
463 (self.fullname, self.pb_field_t(None)))
464 result += 'const pb_extension_type_t %s = {\n' % self.fullname
467 result += ' &%s_field\n' % self.fullname
472 # ---------------------------------------------------------------------------
473 # Generation of messages (structures)
474 # ---------------------------------------------------------------------------
478 def __init__(self, names, desc, message_options):
483 field_options = get_nanopb_suboptions(f, message_options, self.name + f.name)
484 if field_options.type != nanopb_pb2.FT_IGNORE:
485 self.fields.append(Field(self.name, f, field_options))
487 if len(desc.extension_range) > 0:
488 field_options = get_nanopb_suboptions(desc, message_options, self.name + 'extensions')
489 range_start = min([r.start for r in desc.extension_range])
490 if field_options.type != nanopb_pb2.FT_IGNORE:
491 self.fields.append(ExtensionRange(self.name, range_start, field_options))
493 self.packed = message_options.packed_struct
494 self.ordered_fields = self.fields[:]
495 self.ordered_fields.sort()
497 def get_dependencies(self):
498 '''Get list of type names that this structure refers to.'''
499 return [str(field.ctype) for field in self.fields]
502 result = 'typedef struct _%s {\n' % self.name
504 if not self.ordered_fields:
505 # Empty structs are not allowed in C standard.
506 # Therefore add a dummy field if an empty message occurs.
507 result += ' uint8_t dummy_field;'
509 result += '\n'.join([str(f) for f in self.ordered_fields])
513 result += ' pb_packed'
515 result += ' %s;' % self.name
518 result = 'PB_PACKED_STRUCT_START\n' + result
519 result += '\nPB_PACKED_STRUCT_END'
525 for field in self.fields:
526 types = field.types()
527 if types is not None:
528 result += types + '\n'
531 def default_decl(self, declaration_only = False):
533 for field in self.fields:
534 default = field.default_decl(declaration_only)
535 if default is not None:
536 result += default + '\n'
539 def fields_declaration(self):
540 result = 'extern const pb_field_t %s_fields[%d];' % (self.name, len(self.fields) + 1)
543 def fields_definition(self):
544 result = 'const pb_field_t %s_fields[%d] = {\n' % (self.name, len(self.fields) + 1)
547 for field in self.ordered_fields:
548 result += field.pb_field_t(prev)
552 result += ' PB_LAST_FIELD\n};'
555 def encoded_size(self, allmsgs):
556 '''Return the maximum size that this message can take when encoded.
557 If the size cannot be determined, returns None.
559 size = EncodedSize(0)
560 for field in self.fields:
561 fsize = field.encoded_size(allmsgs)
569 # ---------------------------------------------------------------------------
570 # Processing of entire .proto files
571 # ---------------------------------------------------------------------------
574 def iterate_messages(desc, names = Names()):
575 '''Recursively find all messages. For each, yield name, DescriptorProto.'''
576 if hasattr(desc, 'message_type'):
577 submsgs = desc.message_type
579 submsgs = desc.nested_type
581 for submsg in submsgs:
582 sub_names = names + submsg.name
583 yield sub_names, submsg
585 for x in iterate_messages(submsg, sub_names):
588 def iterate_extensions(desc, names = Names()):
589 '''Recursively find all extensions.
590 For each, yield name, FieldDescriptorProto.
592 for extension in desc.extension:
593 yield names, extension
595 for subname, subdesc in iterate_messages(desc, names):
596 for extension in subdesc.extension:
597 yield subname, extension
599 def parse_file(fdesc, file_options):
600 '''Takes a FileDescriptorProto and returns tuple (enums, messages, extensions).'''
607 base_name = Names(fdesc.package.split('.'))
611 for enum in fdesc.enum_type:
612 enum_options = get_nanopb_suboptions(enum, file_options, base_name + enum.name)
613 enums.append(Enum(base_name, enum, enum_options))
615 for names, message in iterate_messages(fdesc, base_name):
616 message_options = get_nanopb_suboptions(message, file_options, names)
617 messages.append(Message(names, message, message_options))
618 for enum in message.enum_type:
619 enum_options = get_nanopb_suboptions(enum, message_options, names + enum.name)
620 enums.append(Enum(names, enum, enum_options))
622 for names, extension in iterate_extensions(fdesc, base_name):
623 field_options = get_nanopb_suboptions(extension, file_options, names)
624 if field_options.type != nanopb_pb2.FT_IGNORE:
625 extensions.append(ExtensionField(names, extension, field_options))
627 # Fix field default values where enum short names are used.
629 if not enum.options.long_names:
630 for message in messages:
631 for field in message.fields:
632 if field.default in enum.value_longnames:
633 idx = enum.value_longnames.index(field.default)
634 field.default = enum.values[idx][0]
636 return enums, messages, extensions
640 From http://code.activestate.com/recipes/577413-topological-sort/
641 This function is under the MIT license.
643 for k, v in data.items():
644 v.discard(k) # Ignore self dependencies
645 extra_items_in_deps = reduce(set.union, data.values(), set()) - set(data.keys())
646 data.update(dict([(item, set()) for item in extra_items_in_deps]))
648 ordered = set(item for item,dep in data.items() if not dep)
651 for item in sorted(ordered):
653 data = dict([(item, (dep - ordered)) for item,dep in data.items()
654 if item not in ordered])
655 assert not data, "A cyclic dependency exists amongst %r" % data
657 def sort_dependencies(messages):
658 '''Sort a list of Messages based on dependencies.'''
661 for message in messages:
662 dependencies[str(message.name)] = set(message.get_dependencies())
663 message_by_name[str(message.name)] = message
665 for msgname in toposort2(dependencies):
666 if msgname in message_by_name:
667 yield message_by_name[msgname]
669 def make_identifier(headername):
670 '''Make #ifndef identifier that contains uppercase A-Z and digits 0-9'''
672 for c in headername.upper():
679 def generate_header(dependencies, headername, enums, messages, extensions, options):
680 '''Generate content for a header file.
681 Generates strings, which should be concatenated and stored to file.
684 yield '/* Automatically generated nanopb header */\n'
685 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
687 symbol = make_identifier(headername)
688 yield '#ifndef _PB_%s_\n' % symbol
689 yield '#define _PB_%s_\n' % symbol
691 yield options.libformat % ('pb.h')
693 # no %s specified - use whatever was passed in as options.libformat
694 yield options.libformat
697 for dependency in dependencies:
698 noext = os.path.splitext(dependency)[0]
699 yield options.genformat % (noext + '.' + options.extension + '.h')
702 yield '#ifdef __cplusplus\n'
703 yield 'extern "C" {\n'
706 yield '/* Enum definitions */\n'
708 yield str(enum) + '\n\n'
710 yield '/* Struct definitions */\n'
711 for msg in sort_dependencies(messages):
713 yield str(msg) + '\n\n'
716 yield '/* Extensions */\n'
717 for extension in extensions:
718 yield extension.extension_decl()
721 yield '/* Default values for struct fields */\n'
723 yield msg.default_decl(True)
726 yield '/* Field tags (for use in manual encoding/decoding) */\n'
727 for msg in sort_dependencies(messages):
728 for field in msg.fields:
730 for extension in extensions:
731 yield extension.tags()
734 yield '/* Struct field encoding specification for nanopb */\n'
736 yield msg.fields_declaration() + '\n'
739 yield '/* Maximum encoded size of messages (where known) */\n'
741 msize = msg.encoded_size(messages)
742 if msize is not None:
743 identifier = '%s_size' % msg.name
744 yield '#define %-40s %s\n' % (identifier, msize)
747 yield '#ifdef __cplusplus\n'
748 yield '} /* extern "C" */\n'
754 def generate_source(headername, enums, messages, extensions, options):
755 '''Generate content for a source file.'''
757 yield '/* Automatically generated nanopb constant definitions */\n'
758 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
759 yield options.genformat % (headername)
763 yield msg.default_decl(False)
768 yield msg.fields_definition() + '\n\n'
770 for ext in extensions:
771 yield ext.extension_def() + '\n'
773 # Add checks for numeric limits
775 count_required_fields = lambda m: len([f for f in msg.fields if f.rules == 'REQUIRED'])
776 largest_msg = max(messages, key = count_required_fields)
777 largest_count = count_required_fields(largest_msg)
778 if largest_count > 64:
779 yield '\n/* Check that missing required fields will be properly detected */\n'
780 yield '#if PB_MAX_REQUIRED_FIELDS < %d\n' % largest_count
781 yield '#error Properly detecting missing required fields in %s requires \\\n' % largest_msg.name
782 yield ' setting PB_MAX_REQUIRED_FIELDS to %d or more.\n' % largest_count
790 checks_msgnames.append(msg.name)
791 for field in msg.fields:
792 status = field.largest_field_value()
793 if isinstance(status, (str, unicode)):
794 checks.append(status)
797 worst_field = str(field.struct_name) + '.' + str(field.name)
799 if worst > 255 or checks:
800 yield '\n/* Check that field information fits in pb_field_t */\n'
803 yield '#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT)\n'
805 yield '#error Field descriptor for %s is too large. Define PB_FIELD_16BIT to fix this.\n' % worst_field
807 assertion = ' && '.join(str(c) + ' < 256' for c in checks)
808 msgs = '_'.join(str(n) for n in checks_msgnames)
809 yield 'STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
812 if worst > 65535 or checks:
813 yield '#if !defined(PB_FIELD_32BIT)\n'
815 yield '#error Field descriptor for %s is too large. Define PB_FIELD_32BIT to fix this.\n' % worst_field
817 assertion = ' && '.join(str(c) + ' < 65536' for c in checks)
818 msgs = '_'.join(str(n) for n in checks_msgnames)
819 yield 'STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
822 # Add check for sizeof(double)
825 for field in msg.fields:
826 if field.ctype == 'double':
831 yield '/* On some platforms (such as AVR), double is really float.\n'
832 yield ' * These are not directly supported by nanopb, but see example_avr_double.\n'
833 yield ' * To get rid of this error, remove any double fields from your .proto.\n'
835 yield 'STATIC_ASSERT(sizeof(double) == 8, DOUBLE_MUST_BE_8_BYTES)\n'
839 # ---------------------------------------------------------------------------
840 # Options parsing for the .proto files
841 # ---------------------------------------------------------------------------
843 from fnmatch import fnmatch
845 def read_options_file(infile):
846 '''Parse a separate options file to list:
847 [(namemask, options), ...]
852 if not line or line.startswith('//') or line.startswith('#'):
855 parts = line.split(None, 1)
856 opts = nanopb_pb2.NanoPBOptions()
857 text_format.Merge(parts[1], opts)
858 results.append((parts[0], opts))
863 '''Ugly global variables, should find a good way to pass these.'''
864 verbose_options = False
865 separate_options = []
867 def get_nanopb_suboptions(subdesc, options, name):
868 '''Get copy of options, and merge information from subdesc.'''
869 new_options = nanopb_pb2.NanoPBOptions()
870 new_options.CopyFrom(options)
872 # Handle options defined in a separate file
873 dotname = '.'.join(name.parts)
874 for namemask, options in Globals.separate_options:
875 if fnmatch(dotname, namemask):
876 new_options.MergeFrom(options)
878 # Handle options defined in .proto
879 if isinstance(subdesc.options, descriptor.FieldOptions):
880 ext_type = nanopb_pb2.nanopb
881 elif isinstance(subdesc.options, descriptor.FileOptions):
882 ext_type = nanopb_pb2.nanopb_fileopt
883 elif isinstance(subdesc.options, descriptor.MessageOptions):
884 ext_type = nanopb_pb2.nanopb_msgopt
885 elif isinstance(subdesc.options, descriptor.EnumOptions):
886 ext_type = nanopb_pb2.nanopb_enumopt
888 raise Exception("Unknown options type")
890 if subdesc.options.HasExtension(ext_type):
891 ext = subdesc.options.Extensions[ext_type]
892 new_options.MergeFrom(ext)
894 if Globals.verbose_options:
895 print "Options for " + dotname + ":"
896 print text_format.MessageToString(new_options)
901 # ---------------------------------------------------------------------------
902 # Command line interface
903 # ---------------------------------------------------------------------------
907 from optparse import OptionParser
909 optparser = OptionParser(
910 usage = "Usage: nanopb_generator.py [options] file.pb ...",
911 epilog = "Compile file.pb from file.proto by: 'protoc -ofile.pb file.proto'. " +
912 "Output will be written to file.pb.h and file.pb.c.")
913 optparser.add_option("-x", dest="exclude", metavar="FILE", action="append", default=[],
914 help="Exclude file from generated #include list.")
915 optparser.add_option("-e", "--extension", dest="extension", metavar="EXTENSION", default="pb",
916 help="Set extension to use instead of 'pb' for generated files. [default: %default]")
917 optparser.add_option("-f", "--options-file", dest="options_file", metavar="FILE", default="%s.options",
918 help="Set name of a separate generator options file.")
919 optparser.add_option("-Q", "--generated-include-format", dest="genformat",
920 metavar="FORMAT", default='#include "%s"\n',
921 help="Set format string to use for including other .pb.h files. [default: %default]")
922 optparser.add_option("-L", "--library-include-format", dest="libformat",
923 metavar="FORMAT", default='#include <%s>\n',
924 help="Set format string to use for including the nanopb pb.h header. [default: %default]")
925 optparser.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False,
926 help="Don't print anything except errors.")
927 optparser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
928 help="Print more information.")
929 optparser.add_option("-s", dest="settings", metavar="OPTION:VALUE", action="append", default=[],
930 help="Set generator option (max_size, max_count etc.).")
932 def process_file(filename, fdesc, options):
933 '''Process a single file.
934 filename: The full path to the .proto or .pb source file, as string.
935 fdesc: The loaded FileDescriptorSet, or None to read from the input file.
936 options: Command line options as they come from OptionsParser.
939 {'headername': Name of header file,
940 'headerdata': Data for the .h header file,
941 'sourcename': Name of the source code file,
942 'sourcedata': Data for the .c source code file
945 toplevel_options = nanopb_pb2.NanoPBOptions()
946 for s in options.settings:
947 text_format.Merge(s, toplevel_options)
950 data = open(filename, 'rb').read()
951 fdesc = descriptor.FileDescriptorSet.FromString(data).file[0]
953 # Check if there is a separate .options file
955 optfilename = options.options_file % os.path.splitext(filename)[0]
957 # No %s specified, use the filename as-is
958 optfilename = options.options_file
961 print 'Reading options from ' + optfilename
963 if os.path.isfile(optfilename):
964 Globals.separate_options = read_options_file(open(optfilename, "rU"))
966 Globals.separate_options = []
969 file_options = get_nanopb_suboptions(fdesc, toplevel_options, Names([filename]))
970 enums, messages, extensions = parse_file(fdesc, file_options)
972 # Decide the file names
973 noext = os.path.splitext(filename)[0]
974 headername = noext + '.' + options.extension + '.h'
975 sourcename = noext + '.' + options.extension + '.c'
976 headerbasename = os.path.basename(headername)
978 # List of .proto files that should not be included in the C header file
979 # even if they are mentioned in the source .proto.
980 excludes = ['nanopb.proto', 'google/protobuf/descriptor.proto'] + options.exclude
981 dependencies = [d for d in fdesc.dependency if d not in excludes]
983 headerdata = ''.join(generate_header(dependencies, headerbasename, enums,
984 messages, extensions, options))
986 sourcedata = ''.join(generate_source(headerbasename, enums,
987 messages, extensions, options))
989 return {'headername': headername, 'headerdata': headerdata,
990 'sourcename': sourcename, 'sourcedata': sourcedata}
993 '''Main function when invoked directly from the command line.'''
995 options, filenames = optparser.parse_args()
998 optparser.print_help()
1002 options.verbose = False
1004 Globals.verbose_options = options.verbose
1006 for filename in filenames:
1007 results = process_file(filename, None, options)
1009 if not options.quiet:
1010 print "Writing to " + results['headername'] + " and " + results['sourcename']
1012 open(results['headername'], 'w').write(results['headerdata'])
1013 open(results['sourcename'], 'w').write(results['sourcedata'])
1016 '''Main function when invoked as a protoc plugin.'''
1019 if sys.platform == "win32":
1021 # Set stdin and stdout to binary mode
1022 msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
1023 msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
1025 import proto.plugin_pb2 as plugin_pb2
1026 data = sys.stdin.read()
1027 request = plugin_pb2.CodeGeneratorRequest.FromString(data)
1030 args = shlex.split(request.parameter)
1031 options, dummy = optparser.parse_args(args)
1033 # We can't go printing stuff to stdout
1034 Globals.verbose_options = False
1035 options.verbose = False
1036 options.quiet = True
1038 response = plugin_pb2.CodeGeneratorResponse()
1040 for filename in request.file_to_generate:
1041 for fdesc in request.proto_file:
1042 if fdesc.name == filename:
1043 results = process_file(filename, fdesc, options)
1045 f = response.file.add()
1046 f.name = results['headername']
1047 f.content = results['headerdata']
1049 f = response.file.add()
1050 f.name = results['sourcename']
1051 f.content = results['sourcedata']
1053 sys.stdout.write(response.SerializeToString())
1055 if __name__ == '__main__':
1056 # Check if we are running as a plugin under protoc
1057 if 'protoc-gen-' in sys.argv[0]: