3 '''Generate header file for nanopb from a ProtoBuf FileDescriptorSet.'''
4 nanopb_version = "nanopb-0.2.5-dev"
9 import google, distutils.util # bbfreeze seems to need these
10 import google.protobuf.text_format as text_format
13 *************************************************************
14 *** Could not import the Google protobuf Python libraries ***
15 *** Try installing package 'python-protobuf' or similar. ***
16 *************************************************************
21 import proto.nanopb_pb2 as nanopb_pb2
22 import proto.descriptor_pb2 as descriptor
25 ********************************************************************
26 *** Failed to import the protocol definitions for generator. ***
27 *** You have to run 'make' in the nanopb/generator/proto folder. ***
28 ********************************************************************
33 # ---------------------------------------------------------------------------
34 # Generation of single fields
35 # ---------------------------------------------------------------------------
40 # Values are tuple (c type, pb type, encoded size)
41 FieldD = descriptor.FieldDescriptorProto
43 FieldD.TYPE_BOOL: ('bool', 'BOOL', 1),
44 FieldD.TYPE_DOUBLE: ('double', 'DOUBLE', 8),
45 FieldD.TYPE_FIXED32: ('uint32_t', 'FIXED32', 4),
46 FieldD.TYPE_FIXED64: ('uint64_t', 'FIXED64', 8),
47 FieldD.TYPE_FLOAT: ('float', 'FLOAT', 4),
48 FieldD.TYPE_INT32: ('int32_t', 'INT32', 10),
49 FieldD.TYPE_INT64: ('int64_t', 'INT64', 10),
50 FieldD.TYPE_SFIXED32: ('int32_t', 'SFIXED32', 4),
51 FieldD.TYPE_SFIXED64: ('int64_t', 'SFIXED64', 8),
52 FieldD.TYPE_SINT32: ('int32_t', 'SINT32', 5),
53 FieldD.TYPE_SINT64: ('int64_t', 'SINT64', 10),
54 FieldD.TYPE_UINT32: ('uint32_t', 'UINT32', 5),
55 FieldD.TYPE_UINT64: ('uint64_t', 'UINT64', 10)
59 '''Keeps a set of nested names and formats them to C identifier.'''
60 def __init__(self, parts = ()):
61 if isinstance(parts, Names):
63 self.parts = tuple(parts)
66 return '_'.join(self.parts)
68 def __add__(self, other):
69 if isinstance(other, (str, unicode)):
70 return Names(self.parts + (other,))
71 elif isinstance(other, tuple):
72 return Names(self.parts + other)
74 raise ValueError("Name parts should be of type str")
76 def __eq__(self, other):
77 return isinstance(other, Names) and self.parts == other.parts
79 def names_from_type_name(type_name):
80 '''Parse Names() from FieldDescriptorProto type_name'''
81 if type_name[0] != '.':
82 raise NotImplementedError("Lookup of non-absolute type names is not supported")
83 return Names(type_name[1:].split('.'))
85 def varint_max_size(max_value):
86 '''Returns the maximum number of bytes a varint can take when encoded.'''
87 for i in range(1, 11):
88 if (max_value >> (i * 7)) == 0:
90 raise ValueError("Value too large for varint: " + str(max_value))
92 assert varint_max_size(0) == 1
93 assert varint_max_size(127) == 1
94 assert varint_max_size(128) == 2
97 '''Class used to represent the encoded size of a field or a message.
98 Consists of a combination of symbolic sizes and integer sizes.'''
99 def __init__(self, value = 0, symbols = []):
100 if isinstance(value, (str, Names)):
101 symbols = [str(value)]
104 self.symbols = symbols
106 def __add__(self, other):
107 if isinstance(other, (int, long)):
108 return EncodedSize(self.value + other, self.symbols)
109 elif isinstance(other, (str, Names)):
110 return EncodedSize(self.value, self.symbols + [str(other)])
111 elif isinstance(other, EncodedSize):
112 return EncodedSize(self.value + other.value, self.symbols + other.symbols)
114 raise ValueError("Cannot add size: " + repr(other))
116 def __mul__(self, other):
117 if isinstance(other, (int, long)):
118 return EncodedSize(self.value * other, [str(other) + '*' + s for s in self.symbols])
120 raise ValueError("Cannot multiply size: " + repr(other))
124 return str(self.value)
126 return '(' + str(self.value) + ' + ' + ' + '.join(self.symbols) + ')'
128 def upperlimit(self):
135 def __init__(self, names, desc, enum_options):
136 '''desc is EnumDescriptorProto'''
138 self.options = enum_options
139 self.names = names + desc.name
141 if enum_options.long_names:
142 self.values = [(self.names + x.name, x.number) for x in desc.value]
144 self.values = [(names + x.name, x.number) for x in desc.value]
146 self.value_longnames = [self.names + x.name for x in desc.value]
149 result = 'typedef enum _%s {\n' % self.names
150 result += ',\n'.join([" %s = %d" % x for x in self.values])
151 result += '\n} %s;' % self.names
155 def __init__(self, struct_name, desc, field_options):
156 '''desc is FieldDescriptorProto'''
157 self.tag = desc.number
158 self.struct_name = struct_name
159 self.name = desc.name
162 self.max_count = None
166 # Parse field options
167 if field_options.HasField("max_size"):
168 self.max_size = field_options.max_size
170 if field_options.HasField("max_count"):
171 self.max_count = field_options.max_count
173 if desc.HasField('default_value'):
174 self.default = desc.default_value
176 # Check field rules, i.e. required/optional/repeated.
178 if desc.label == FieldD.LABEL_REQUIRED:
179 self.rules = 'REQUIRED'
180 elif desc.label == FieldD.LABEL_OPTIONAL:
181 self.rules = 'OPTIONAL'
182 elif desc.label == FieldD.LABEL_REPEATED:
183 self.rules = 'REPEATED'
184 if self.max_count is None:
185 can_be_static = False
187 self.array_decl = '[%d]' % self.max_count
189 raise NotImplementedError(desc.label)
191 # Check if the field can be implemented with static allocation
192 # i.e. whether the data size is known.
193 if desc.type == FieldD.TYPE_STRING and self.max_size is None:
194 can_be_static = False
196 if desc.type == FieldD.TYPE_BYTES and self.max_size is None:
197 can_be_static = False
199 # Decide how the field data will be allocated
200 if field_options.type == nanopb_pb2.FT_DEFAULT:
202 field_options.type = nanopb_pb2.FT_STATIC
204 field_options.type = nanopb_pb2.FT_CALLBACK
206 if field_options.type == nanopb_pb2.FT_STATIC and not can_be_static:
207 raise Exception("Field %s is defined as static, but max_size or "
208 "max_count is not given." % self.name)
210 if field_options.type == nanopb_pb2.FT_STATIC:
211 self.allocation = 'STATIC'
212 elif field_options.type == nanopb_pb2.FT_POINTER:
213 self.allocation = 'POINTER'
214 elif field_options.type == nanopb_pb2.FT_CALLBACK:
215 self.allocation = 'CALLBACK'
217 raise NotImplementedError(field_options.type)
219 # Decide the C data type to use in the struct.
220 if datatypes.has_key(desc.type):
221 self.ctype, self.pbtype, self.enc_size = datatypes[desc.type]
222 elif desc.type == FieldD.TYPE_ENUM:
224 self.ctype = names_from_type_name(desc.type_name)
225 if self.default is not None:
226 self.default = self.ctype + self.default
227 self.enc_size = 5 # protoc rejects enum values > 32 bits
228 elif desc.type == FieldD.TYPE_STRING:
229 self.pbtype = 'STRING'
231 if self.allocation == 'STATIC':
233 self.array_decl += '[%d]' % self.max_size
234 self.enc_size = varint_max_size(self.max_size) + self.max_size
235 elif desc.type == FieldD.TYPE_BYTES:
236 self.pbtype = 'BYTES'
237 if self.allocation == 'STATIC':
238 self.ctype = self.struct_name + self.name + 't'
239 self.enc_size = varint_max_size(self.max_size) + self.max_size
240 elif self.allocation == 'POINTER':
241 self.ctype = 'pb_bytes_ptr_t'
242 elif desc.type == FieldD.TYPE_MESSAGE:
243 self.pbtype = 'MESSAGE'
244 self.ctype = self.submsgname = names_from_type_name(desc.type_name)
245 self.enc_size = None # Needs to be filled in after the message type is available
247 raise NotImplementedError(desc.type)
249 def __cmp__(self, other):
250 return cmp(self.tag, other.tag)
254 if self.allocation == 'POINTER':
255 if self.rules == 'REPEATED':
256 result += ' size_t ' + self.name + '_count;\n'
258 if self.pbtype == 'MESSAGE':
259 # Use struct definition, so recursive submessages are possible
260 result += ' struct _%s *%s;' % (self.ctype, self.name)
261 elif self.rules == 'REPEATED' and self.pbtype == 'STRING':
262 # String arrays need to be defined as pointers to pointers
263 result += ' %s **%s;' % (self.ctype, self.name)
265 result += ' %s *%s;' % (self.ctype, self.name)
266 elif self.allocation == 'CALLBACK':
267 result += ' pb_callback_t %s;' % self.name
269 if self.rules == 'OPTIONAL' and self.allocation == 'STATIC':
270 result += ' bool has_' + self.name + ';\n'
271 elif self.rules == 'REPEATED' and self.allocation == 'STATIC':
272 result += ' size_t ' + self.name + '_count;\n'
273 result += ' %s %s%s;' % (self.ctype, self.name, self.array_decl)
277 '''Return definitions for any special types this field might need.'''
278 if self.pbtype == 'BYTES' and self.allocation == 'STATIC':
279 result = 'typedef struct {\n'
280 result += ' size_t size;\n'
281 result += ' uint8_t bytes[%d];\n' % self.max_size
282 result += '} %s;\n' % self.ctype
287 def default_decl(self, declaration_only = False):
288 '''Return definition for this field's default value.'''
289 if self.default is None:
292 ctype, default = self.ctype, self.default
295 if self.pbtype == 'STRING':
296 if self.allocation != 'STATIC':
297 return None # Not implemented
299 array_decl = '[%d]' % self.max_size
300 default = str(self.default).encode('string_escape')
301 default = default.replace('"', '\\"')
302 default = '"' + default + '"'
303 elif self.pbtype == 'BYTES':
304 if self.allocation != 'STATIC':
305 return None # Not implemented
307 data = self.default.decode('string_escape')
308 data = ['0x%02x' % ord(c) for c in data]
309 default = '{%d, {%s}}' % (len(data), ','.join(data))
312 return 'extern const %s %s_default%s;' % (ctype, self.struct_name + self.name, array_decl)
314 return 'const %s %s_default%s = %s;' % (ctype, self.struct_name + self.name, array_decl, default)
317 '''Return the #define for the tag number of this field.'''
318 identifier = '%s_%s_tag' % (self.struct_name, self.name)
319 return '#define %-40s %d\n' % (identifier, self.tag)
321 def pb_field_t(self, prev_field_name):
322 '''Return the pb_field_t initializer to use in the constant array.
323 prev_field_name is the name of the previous field or None.
325 result = ' PB_FIELD2(%3d, ' % self.tag
326 result += '%-8s, ' % self.pbtype
327 result += '%s, ' % self.rules
328 result += '%-8s, ' % self.allocation
329 result += '%s, ' % ("FIRST" if not prev_field_name else "OTHER")
330 result += '%s, ' % self.struct_name
331 result += '%s, ' % self.name
332 result += '%s, ' % (prev_field_name or self.name)
334 if self.pbtype == 'MESSAGE':
335 result += '&%s_fields)' % self.submsgname
336 elif self.default is None:
338 elif self.pbtype in ['BYTES', 'STRING'] and self.allocation != 'STATIC':
339 result += '0)' # Arbitrary size default values not implemented
341 result += '&%s_default)' % (self.struct_name + self.name)
345 def largest_field_value(self):
346 '''Determine if this field needs 16bit or 32bit pb_field_t structure to compile properly.
347 Returns numeric value or a C-expression for assert.'''
348 if self.pbtype == 'MESSAGE':
349 if self.rules == 'REPEATED' and self.allocation == 'STATIC':
350 return 'pb_membersize(%s, %s[0])' % (self.struct_name, self.name)
352 return 'pb_membersize(%s, %s)' % (self.struct_name, self.name)
354 return max(self.tag, self.max_size, self.max_count)
356 def encoded_size(self, allmsgs):
357 '''Return the maximum size that this field can take when encoded,
358 including the field tag. If the size cannot be determined, returns
361 if self.allocation != 'STATIC':
364 if self.pbtype == 'MESSAGE':
366 if msg.name == self.submsgname:
367 encsize = msg.encoded_size(allmsgs)
369 return None # Submessage size is indeterminate
371 # Include submessage length prefix
372 encsize += varint_max_size(encsize.upperlimit())
375 # Submessage cannot be found, this currently occurs when
376 # the submessage type is defined in a different file.
377 # Instead of direct numeric value, reference the size that
378 # has been #defined in the other file.
379 encsize = EncodedSize(self.submsgname + 'size')
381 # We will have to make a conservative assumption on the length
382 # prefix size, though.
385 elif self.enc_size is None:
386 raise RuntimeError("Could not determine encoded size for %s.%s"
387 % (self.struct_name, self.name))
389 encsize = EncodedSize(self.enc_size)
391 encsize += varint_max_size(self.tag << 3) # Tag + wire type
393 if self.rules == 'REPEATED':
394 # Decoders must be always able to handle unpacked arrays.
395 # Therefore we have to reserve space for it, even though
396 # we emit packed arrays ourselves.
397 encsize *= self.max_count
402 class ExtensionRange(Field):
403 def __init__(self, struct_name, range_start, field_options):
404 '''Implements a special pb_extension_t* field in an extensible message
405 structure. The range_start signifies the index at which the extensions
406 start. Not necessarily all tags above this are extensions, it is merely
407 a speed optimization.
409 self.tag = range_start
410 self.struct_name = struct_name
411 self.name = 'extensions'
412 self.pbtype = 'EXTENSION'
413 self.rules = 'OPTIONAL'
414 self.allocation = 'CALLBACK'
415 self.ctype = 'pb_extension_t'
422 return ' pb_extension_t *extensions;'
430 def encoded_size(self, allmsgs):
431 # We exclude extensions from the count, because they cannot be known
432 # until runtime. Other option would be to return None here, but this
433 # way the value remains useful if extensions are not used.
434 return EncodedSize(0)
436 class ExtensionField(Field):
437 def __init__(self, struct_name, desc, field_options):
438 self.fullname = struct_name + desc.name
439 self.extendee_name = names_from_type_name(desc.extendee)
440 Field.__init__(self, self.fullname + 'struct', desc, field_options)
442 if self.rules != 'OPTIONAL':
446 self.rules = 'OPTEXT'
449 '''Return the #define for the tag number of this field.'''
450 identifier = '%s_tag' % self.fullname
451 return '#define %-40s %d\n' % (identifier, self.tag)
453 def extension_decl(self):
454 '''Declaration of the extension type in the .pb.h file'''
456 msg = '/* Extension field %s was skipped because only "optional"\n' % self.fullname
457 msg +=' type of extension fields is currently supported. */\n'
460 return 'extern const pb_extension_type_t %s;\n' % self.fullname
462 def extension_def(self):
463 '''Definition of the extension type in the .pb.c file'''
468 result = 'typedef struct {\n'
470 result += '\n} %s;\n\n' % self.struct_name
471 result += ('static const pb_field_t %s_field = \n %s;\n\n' %
472 (self.fullname, self.pb_field_t(None)))
473 result += 'const pb_extension_type_t %s = {\n' % self.fullname
476 result += ' &%s_field\n' % self.fullname
481 # ---------------------------------------------------------------------------
482 # Generation of messages (structures)
483 # ---------------------------------------------------------------------------
487 def __init__(self, names, desc, message_options):
492 field_options = get_nanopb_suboptions(f, message_options, self.name + f.name)
493 if field_options.type != nanopb_pb2.FT_IGNORE:
494 self.fields.append(Field(self.name, f, field_options))
496 if len(desc.extension_range) > 0:
497 field_options = get_nanopb_suboptions(desc, message_options, self.name + 'extensions')
498 range_start = min([r.start for r in desc.extension_range])
499 if field_options.type != nanopb_pb2.FT_IGNORE:
500 self.fields.append(ExtensionRange(self.name, range_start, field_options))
502 self.packed = message_options.packed_struct
503 self.ordered_fields = self.fields[:]
504 self.ordered_fields.sort()
506 def get_dependencies(self):
507 '''Get list of type names that this structure refers to.'''
508 return [str(field.ctype) for field in self.fields]
511 result = 'typedef struct _%s {\n' % self.name
513 if not self.ordered_fields:
514 # Empty structs are not allowed in C standard.
515 # Therefore add a dummy field if an empty message occurs.
516 result += ' uint8_t dummy_field;'
518 result += '\n'.join([str(f) for f in self.ordered_fields])
522 result += ' pb_packed'
524 result += ' %s;' % self.name
527 result = 'PB_PACKED_STRUCT_START\n' + result
528 result += '\nPB_PACKED_STRUCT_END'
534 for field in self.fields:
535 types = field.types()
536 if types is not None:
537 result += types + '\n'
540 def default_decl(self, declaration_only = False):
542 for field in self.fields:
543 default = field.default_decl(declaration_only)
544 if default is not None:
545 result += default + '\n'
548 def fields_declaration(self):
549 result = 'extern const pb_field_t %s_fields[%d];' % (self.name, len(self.fields) + 1)
552 def fields_definition(self):
553 result = 'const pb_field_t %s_fields[%d] = {\n' % (self.name, len(self.fields) + 1)
556 for field in self.ordered_fields:
557 result += field.pb_field_t(prev)
561 result += ' PB_LAST_FIELD\n};'
564 def encoded_size(self, allmsgs):
565 '''Return the maximum size that this message can take when encoded.
566 If the size cannot be determined, returns None.
568 size = EncodedSize(0)
569 for field in self.fields:
570 fsize = field.encoded_size(allmsgs)
578 # ---------------------------------------------------------------------------
579 # Processing of entire .proto files
580 # ---------------------------------------------------------------------------
583 def iterate_messages(desc, names = Names()):
584 '''Recursively find all messages. For each, yield name, DescriptorProto.'''
585 if hasattr(desc, 'message_type'):
586 submsgs = desc.message_type
588 submsgs = desc.nested_type
590 for submsg in submsgs:
591 sub_names = names + submsg.name
592 yield sub_names, submsg
594 for x in iterate_messages(submsg, sub_names):
597 def iterate_extensions(desc, names = Names()):
598 '''Recursively find all extensions.
599 For each, yield name, FieldDescriptorProto.
601 for extension in desc.extension:
602 yield names, extension
604 for subname, subdesc in iterate_messages(desc, names):
605 for extension in subdesc.extension:
606 yield subname, extension
608 def parse_file(fdesc, file_options):
609 '''Takes a FileDescriptorProto and returns tuple (enums, messages, extensions).'''
616 base_name = Names(fdesc.package.split('.'))
620 for enum in fdesc.enum_type:
621 enum_options = get_nanopb_suboptions(enum, file_options, base_name + enum.name)
622 enums.append(Enum(base_name, enum, enum_options))
624 for names, message in iterate_messages(fdesc, base_name):
625 message_options = get_nanopb_suboptions(message, file_options, names)
626 messages.append(Message(names, message, message_options))
627 for enum in message.enum_type:
628 enum_options = get_nanopb_suboptions(enum, message_options, names + enum.name)
629 enums.append(Enum(names, enum, enum_options))
631 for names, extension in iterate_extensions(fdesc, base_name):
632 field_options = get_nanopb_suboptions(extension, file_options, names)
633 if field_options.type != nanopb_pb2.FT_IGNORE:
634 extensions.append(ExtensionField(names, extension, field_options))
636 # Fix field default values where enum short names are used.
638 if not enum.options.long_names:
639 for message in messages:
640 for field in message.fields:
641 if field.default in enum.value_longnames:
642 idx = enum.value_longnames.index(field.default)
643 field.default = enum.values[idx][0]
645 return enums, messages, extensions
649 From http://code.activestate.com/recipes/577413-topological-sort/
650 This function is under the MIT license.
652 for k, v in data.items():
653 v.discard(k) # Ignore self dependencies
654 extra_items_in_deps = reduce(set.union, data.values(), set()) - set(data.keys())
655 data.update(dict([(item, set()) for item in extra_items_in_deps]))
657 ordered = set(item for item,dep in data.items() if not dep)
660 for item in sorted(ordered):
662 data = dict([(item, (dep - ordered)) for item,dep in data.items()
663 if item not in ordered])
664 assert not data, "A cyclic dependency exists amongst %r" % data
666 def sort_dependencies(messages):
667 '''Sort a list of Messages based on dependencies.'''
670 for message in messages:
671 dependencies[str(message.name)] = set(message.get_dependencies())
672 message_by_name[str(message.name)] = message
674 for msgname in toposort2(dependencies):
675 if msgname in message_by_name:
676 yield message_by_name[msgname]
678 def make_identifier(headername):
679 '''Make #ifndef identifier that contains uppercase A-Z and digits 0-9'''
681 for c in headername.upper():
688 def generate_header(dependencies, headername, enums, messages, extensions, options):
689 '''Generate content for a header file.
690 Generates strings, which should be concatenated and stored to file.
693 yield '/* Automatically generated nanopb header */\n'
694 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
696 symbol = make_identifier(headername)
697 yield '#ifndef _PB_%s_\n' % symbol
698 yield '#define _PB_%s_\n' % symbol
700 yield options.libformat % ('pb.h')
702 # no %s specified - use whatever was passed in as options.libformat
703 yield options.libformat
706 for dependency in dependencies:
707 noext = os.path.splitext(dependency)[0]
708 yield options.genformat % (noext + '.' + options.extension + '.h')
711 yield '#ifdef __cplusplus\n'
712 yield 'extern "C" {\n'
715 yield '/* Enum definitions */\n'
717 yield str(enum) + '\n\n'
719 yield '/* Struct definitions */\n'
720 for msg in sort_dependencies(messages):
722 yield str(msg) + '\n\n'
725 yield '/* Extensions */\n'
726 for extension in extensions:
727 yield extension.extension_decl()
730 yield '/* Default values for struct fields */\n'
732 yield msg.default_decl(True)
735 yield '/* Field tags (for use in manual encoding/decoding) */\n'
736 for msg in sort_dependencies(messages):
737 for field in msg.fields:
739 for extension in extensions:
740 yield extension.tags()
743 yield '/* Struct field encoding specification for nanopb */\n'
745 yield msg.fields_declaration() + '\n'
748 yield '/* Maximum encoded size of messages (where known) */\n'
750 msize = msg.encoded_size(messages)
751 if msize is not None:
752 identifier = '%s_size' % msg.name
753 yield '#define %-40s %s\n' % (identifier, msize)
756 yield '#ifdef __cplusplus\n'
757 yield '} /* extern "C" */\n'
763 def generate_source(headername, enums, messages, extensions, options):
764 '''Generate content for a source file.'''
766 yield '/* Automatically generated nanopb constant definitions */\n'
767 yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
768 yield options.genformat % (headername)
772 yield msg.default_decl(False)
777 yield msg.fields_definition() + '\n\n'
779 for ext in extensions:
780 yield ext.extension_def() + '\n'
782 # Add checks for numeric limits
784 count_required_fields = lambda m: len([f for f in msg.fields if f.rules == 'REQUIRED'])
785 largest_msg = max(messages, key = count_required_fields)
786 largest_count = count_required_fields(largest_msg)
787 if largest_count > 64:
788 yield '\n/* Check that missing required fields will be properly detected */\n'
789 yield '#if PB_MAX_REQUIRED_FIELDS < %d\n' % largest_count
790 yield '#error Properly detecting missing required fields in %s requires \\\n' % largest_msg.name
791 yield ' setting PB_MAX_REQUIRED_FIELDS to %d or more.\n' % largest_count
799 checks_msgnames.append(msg.name)
800 for field in msg.fields:
801 status = field.largest_field_value()
802 if isinstance(status, (str, unicode)):
803 checks.append(status)
806 worst_field = str(field.struct_name) + '.' + str(field.name)
808 if worst > 255 or checks:
809 yield '\n/* Check that field information fits in pb_field_t */\n'
812 yield '#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT)\n'
814 yield '#error Field descriptor for %s is too large. Define PB_FIELD_16BIT to fix this.\n' % worst_field
816 assertion = ' && '.join(str(c) + ' < 256' for c in checks)
817 msgs = '_'.join(str(n) for n in checks_msgnames)
818 yield 'STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
821 if worst > 65535 or checks:
822 yield '#if !defined(PB_FIELD_32BIT)\n'
824 yield '#error Field descriptor for %s is too large. Define PB_FIELD_32BIT to fix this.\n' % worst_field
826 assertion = ' && '.join(str(c) + ' < 65536' for c in checks)
827 msgs = '_'.join(str(n) for n in checks_msgnames)
828 yield 'STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
831 # Add check for sizeof(double)
834 for field in msg.fields:
835 if field.ctype == 'double':
840 yield '/* On some platforms (such as AVR), double is really float.\n'
841 yield ' * These are not directly supported by nanopb, but see example_avr_double.\n'
842 yield ' * To get rid of this error, remove any double fields from your .proto.\n'
844 yield 'STATIC_ASSERT(sizeof(double) == 8, DOUBLE_MUST_BE_8_BYTES)\n'
848 # ---------------------------------------------------------------------------
849 # Options parsing for the .proto files
850 # ---------------------------------------------------------------------------
852 from fnmatch import fnmatch
854 def read_options_file(infile):
855 '''Parse a separate options file to list:
856 [(namemask, options), ...]
861 if not line or line.startswith('//') or line.startswith('#'):
864 parts = line.split(None, 1)
865 opts = nanopb_pb2.NanoPBOptions()
866 text_format.Merge(parts[1], opts)
867 results.append((parts[0], opts))
872 '''Ugly global variables, should find a good way to pass these.'''
873 verbose_options = False
874 separate_options = []
876 def get_nanopb_suboptions(subdesc, options, name):
877 '''Get copy of options, and merge information from subdesc.'''
878 new_options = nanopb_pb2.NanoPBOptions()
879 new_options.CopyFrom(options)
881 # Handle options defined in a separate file
882 dotname = '.'.join(name.parts)
883 for namemask, options in Globals.separate_options:
884 if fnmatch(dotname, namemask):
885 new_options.MergeFrom(options)
887 # Handle options defined in .proto
888 if isinstance(subdesc.options, descriptor.FieldOptions):
889 ext_type = nanopb_pb2.nanopb
890 elif isinstance(subdesc.options, descriptor.FileOptions):
891 ext_type = nanopb_pb2.nanopb_fileopt
892 elif isinstance(subdesc.options, descriptor.MessageOptions):
893 ext_type = nanopb_pb2.nanopb_msgopt
894 elif isinstance(subdesc.options, descriptor.EnumOptions):
895 ext_type = nanopb_pb2.nanopb_enumopt
897 raise Exception("Unknown options type")
899 if subdesc.options.HasExtension(ext_type):
900 ext = subdesc.options.Extensions[ext_type]
901 new_options.MergeFrom(ext)
903 if Globals.verbose_options:
904 print "Options for " + dotname + ":"
905 print text_format.MessageToString(new_options)
910 # ---------------------------------------------------------------------------
911 # Command line interface
912 # ---------------------------------------------------------------------------
916 from optparse import OptionParser
918 optparser = OptionParser(
919 usage = "Usage: nanopb_generator.py [options] file.pb ...",
920 epilog = "Compile file.pb from file.proto by: 'protoc -ofile.pb file.proto'. " +
921 "Output will be written to file.pb.h and file.pb.c.")
922 optparser.add_option("-x", dest="exclude", metavar="FILE", action="append", default=[],
923 help="Exclude file from generated #include list.")
924 optparser.add_option("-e", "--extension", dest="extension", metavar="EXTENSION", default="pb",
925 help="Set extension to use instead of 'pb' for generated files. [default: %default]")
926 optparser.add_option("-f", "--options-file", dest="options_file", metavar="FILE", default="%s.options",
927 help="Set name of a separate generator options file.")
928 optparser.add_option("-Q", "--generated-include-format", dest="genformat",
929 metavar="FORMAT", default='#include "%s"\n',
930 help="Set format string to use for including other .pb.h files. [default: %default]")
931 optparser.add_option("-L", "--library-include-format", dest="libformat",
932 metavar="FORMAT", default='#include <%s>\n',
933 help="Set format string to use for including the nanopb pb.h header. [default: %default]")
934 optparser.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False,
935 help="Don't print anything except errors.")
936 optparser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
937 help="Print more information.")
938 optparser.add_option("-s", dest="settings", metavar="OPTION:VALUE", action="append", default=[],
939 help="Set generator option (max_size, max_count etc.).")
941 def process_file(filename, fdesc, options):
942 '''Process a single file.
943 filename: The full path to the .proto or .pb source file, as string.
944 fdesc: The loaded FileDescriptorSet, or None to read from the input file.
945 options: Command line options as they come from OptionsParser.
948 {'headername': Name of header file,
949 'headerdata': Data for the .h header file,
950 'sourcename': Name of the source code file,
951 'sourcedata': Data for the .c source code file
954 toplevel_options = nanopb_pb2.NanoPBOptions()
955 for s in options.settings:
956 text_format.Merge(s, toplevel_options)
959 data = open(filename, 'rb').read()
960 fdesc = descriptor.FileDescriptorSet.FromString(data).file[0]
962 # Check if there is a separate .options file
964 optfilename = options.options_file % os.path.splitext(filename)[0]
966 # No %s specified, use the filename as-is
967 optfilename = options.options_file
970 print 'Reading options from ' + optfilename
972 if os.path.isfile(optfilename):
973 Globals.separate_options = read_options_file(open(optfilename, "rU"))
975 Globals.separate_options = []
978 file_options = get_nanopb_suboptions(fdesc, toplevel_options, Names([filename]))
979 enums, messages, extensions = parse_file(fdesc, file_options)
981 # Decide the file names
982 noext = os.path.splitext(filename)[0]
983 headername = noext + '.' + options.extension + '.h'
984 sourcename = noext + '.' + options.extension + '.c'
985 headerbasename = os.path.basename(headername)
987 # List of .proto files that should not be included in the C header file
988 # even if they are mentioned in the source .proto.
989 excludes = ['nanopb.proto', 'google/protobuf/descriptor.proto'] + options.exclude
990 dependencies = [d for d in fdesc.dependency if d not in excludes]
992 headerdata = ''.join(generate_header(dependencies, headerbasename, enums,
993 messages, extensions, options))
995 sourcedata = ''.join(generate_source(headerbasename, enums,
996 messages, extensions, options))
998 return {'headername': headername, 'headerdata': headerdata,
999 'sourcename': sourcename, 'sourcedata': sourcedata}
1002 '''Main function when invoked directly from the command line.'''
1004 options, filenames = optparser.parse_args()
1007 optparser.print_help()
1011 options.verbose = False
1013 Globals.verbose_options = options.verbose
1015 for filename in filenames:
1016 results = process_file(filename, None, options)
1018 if not options.quiet:
1019 print "Writing to " + results['headername'] + " and " + results['sourcename']
1021 open(results['headername'], 'w').write(results['headerdata'])
1022 open(results['sourcename'], 'w').write(results['sourcedata'])
1025 '''Main function when invoked as a protoc plugin.'''
1028 if sys.platform == "win32":
1030 # Set stdin and stdout to binary mode
1031 msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
1032 msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
1034 import proto.plugin_pb2 as plugin_pb2
1035 data = sys.stdin.read()
1036 request = plugin_pb2.CodeGeneratorRequest.FromString(data)
1039 args = shlex.split(request.parameter)
1040 options, dummy = optparser.parse_args(args)
1042 # We can't go printing stuff to stdout
1043 Globals.verbose_options = False
1044 options.verbose = False
1045 options.quiet = True
1047 response = plugin_pb2.CodeGeneratorResponse()
1049 for filename in request.file_to_generate:
1050 for fdesc in request.proto_file:
1051 if fdesc.name == filename:
1052 results = process_file(filename, fdesc, options)
1054 f = response.file.add()
1055 f.name = results['headername']
1056 f.content = results['headerdata']
1058 f = response.file.add()
1059 f.name = results['sourcename']
1060 f.content = results['sourcedata']
1062 sys.stdout.write(response.SerializeToString())
1064 if __name__ == '__main__':
1065 # Check if we are running as a plugin under protoc
1066 if 'protoc-gen-' in sys.argv[0] or '--protoc-plugin' in sys.argv: