Fix a few remaining bugs related to CHAR_BIT!=8 platforms.
[apps/agl-service-can-low-level.git] / generator / nanopb_generator.py
1 #!/usr/bin/env python
2
3 from __future__ import unicode_literals
4
5 '''Generate header file for nanopb from a ProtoBuf FileDescriptorSet.'''
6 nanopb_version = "nanopb-0.3.5-dev"
7
8 import sys
9 import re
10 from functools import reduce
11
12 try:
13     # Add some dummy imports to keep packaging tools happy.
14     import google, distutils.util # bbfreeze seems to need these
15     import pkg_resources # pyinstaller / protobuf 2.5 seem to need these
16 except:
17     # Don't care, we will error out later if it is actually important.
18     pass
19
20 try:
21     import google.protobuf.text_format as text_format
22     import google.protobuf.descriptor_pb2 as descriptor
23 except:
24     sys.stderr.write('''
25          *************************************************************
26          *** Could not import the Google protobuf Python libraries ***
27          *** Try installing package 'python-protobuf' or similar.  ***
28          *************************************************************
29     ''' + '\n')
30     raise
31
32 try:
33     import proto.nanopb_pb2 as nanopb_pb2
34     import proto.plugin_pb2 as plugin_pb2
35 except:
36     sys.stderr.write('''
37          ********************************************************************
38          *** Failed to import the protocol definitions for generator.     ***
39          *** You have to run 'make' in the nanopb/generator/proto folder. ***
40          ********************************************************************
41     ''' + '\n')
42     raise
43
44 # ---------------------------------------------------------------------------
45 #                     Generation of single fields
46 # ---------------------------------------------------------------------------
47
48 import time
49 import os.path
50
51 # Values are tuple (c type, pb type, encoded size, int_size_allowed)
52 FieldD = descriptor.FieldDescriptorProto
53 datatypes = {
54     FieldD.TYPE_BOOL:       ('bool',     'BOOL',        1,  False),
55     FieldD.TYPE_DOUBLE:     ('double',   'DOUBLE',      8,  False),
56     FieldD.TYPE_FIXED32:    ('uint32_t', 'FIXED32',     4,  False),
57     FieldD.TYPE_FIXED64:    ('uint64_t', 'FIXED64',     8,  False),
58     FieldD.TYPE_FLOAT:      ('float',    'FLOAT',       4,  False),
59     FieldD.TYPE_INT32:      ('int32_t',  'INT32',      10,  True),
60     FieldD.TYPE_INT64:      ('int64_t',  'INT64',      10,  True),
61     FieldD.TYPE_SFIXED32:   ('int32_t',  'SFIXED32',    4,  False),
62     FieldD.TYPE_SFIXED64:   ('int64_t',  'SFIXED64',    8,  False),
63     FieldD.TYPE_SINT32:     ('int32_t',  'SINT32',      5,  True),
64     FieldD.TYPE_SINT64:     ('int64_t',  'SINT64',     10,  True),
65     FieldD.TYPE_UINT32:     ('uint32_t', 'UINT32',      5,  True),
66     FieldD.TYPE_UINT64:     ('uint64_t', 'UINT64',     10,  True)
67 }
68
69 # Integer size overrides (from .proto settings)
70 intsizes = {
71     nanopb_pb2.IS_8:     'int8_t',
72     nanopb_pb2.IS_16:    'int16_t',
73     nanopb_pb2.IS_32:    'int32_t',
74     nanopb_pb2.IS_64:    'int64_t',
75 }
76
77 # String types (for python 2 / python 3 compatibility)
78 try:
79     strtypes = (unicode, str)
80 except NameError:
81     strtypes = (str, )
82
83 class Names:
84     '''Keeps a set of nested names and formats them to C identifier.'''
85     def __init__(self, parts = ()):
86         if isinstance(parts, Names):
87             parts = parts.parts
88         self.parts = tuple(parts)
89
90     def __str__(self):
91         return '_'.join(self.parts)
92
93     def __add__(self, other):
94         if isinstance(other, strtypes):
95             return Names(self.parts + (other,))
96         elif isinstance(other, tuple):
97             return Names(self.parts + other)
98         else:
99             raise ValueError("Name parts should be of type str")
100
101     def __eq__(self, other):
102         return isinstance(other, Names) and self.parts == other.parts
103
104 def names_from_type_name(type_name):
105     '''Parse Names() from FieldDescriptorProto type_name'''
106     if type_name[0] != '.':
107         raise NotImplementedError("Lookup of non-absolute type names is not supported")
108     return Names(type_name[1:].split('.'))
109
110 def varint_max_size(max_value):
111     '''Returns the maximum number of bytes a varint can take when encoded.'''
112     if max_value < 0:
113         max_value = 2**64 - max_value
114     for i in range(1, 11):
115         if (max_value >> (i * 7)) == 0:
116             return i
117     raise ValueError("Value too large for varint: " + str(max_value))
118
119 assert varint_max_size(-1) == 10
120 assert varint_max_size(0) == 1
121 assert varint_max_size(127) == 1
122 assert varint_max_size(128) == 2
123
124 class EncodedSize:
125     '''Class used to represent the encoded size of a field or a message.
126     Consists of a combination of symbolic sizes and integer sizes.'''
127     def __init__(self, value = 0, symbols = []):
128         if isinstance(value, EncodedSize):
129             self.value = value.value
130             self.symbols = value.symbols
131         elif isinstance(value, strtypes + (Names,)):
132             self.symbols = [str(value)]
133             self.value = 0
134         else:
135             self.value = value
136             self.symbols = symbols
137
138     def __add__(self, other):
139         if isinstance(other, int):
140             return EncodedSize(self.value + other, self.symbols)
141         elif isinstance(other, strtypes + (Names,)):
142             return EncodedSize(self.value, self.symbols + [str(other)])
143         elif isinstance(other, EncodedSize):
144             return EncodedSize(self.value + other.value, self.symbols + other.symbols)
145         else:
146             raise ValueError("Cannot add size: " + repr(other))
147
148     def __mul__(self, other):
149         if isinstance(other, int):
150             return EncodedSize(self.value * other, [str(other) + '*' + s for s in self.symbols])
151         else:
152             raise ValueError("Cannot multiply size: " + repr(other))
153
154     def __str__(self):
155         if not self.symbols:
156             return str(self.value)
157         else:
158             return '(' + str(self.value) + ' + ' + ' + '.join(self.symbols) + ')'
159
160     def upperlimit(self):
161         if not self.symbols:
162             return self.value
163         else:
164             return 2**32 - 1
165
166 class Enum:
167     def __init__(self, names, desc, enum_options):
168         '''desc is EnumDescriptorProto'''
169
170         self.options = enum_options
171         self.names = names + desc.name
172
173         if enum_options.long_names:
174             self.values = [(self.names + x.name, x.number) for x in desc.value]
175         else:
176             self.values = [(names + x.name, x.number) for x in desc.value]
177
178         self.value_longnames = [self.names + x.name for x in desc.value]
179         self.packed = enum_options.packed_enum
180
181     def has_negative(self):
182         for n, v in self.values:
183             if v < 0:
184                 return True
185         return False
186
187     def encoded_size(self):
188         return max([varint_max_size(v) for n,v in self.values])
189
190     def __str__(self):
191         result = 'typedef enum _%s {\n' % self.names
192         result += ',\n'.join(["    %s = %d" % x for x in self.values])
193         result += '\n}'
194
195         if self.packed:
196             result += ' pb_packed'
197
198         result += ' %s;' % self.names
199
200         if not self.options.long_names:
201             # Define the long names always so that enum value references
202             # from other files work properly.
203             for i, x in enumerate(self.values):
204                 result += '\n#define %s %s' % (self.value_longnames[i], x[0])
205
206         return result
207
208 class FieldMaxSize:
209     def __init__(self, worst = 0, checks = [], field_name = 'undefined'):
210         if isinstance(worst, list):
211             self.worst = max(i for i in worst if i is not None)
212         else:
213             self.worst = worst
214
215         self.worst_field = field_name
216         self.checks = checks
217
218     def extend(self, extend, field_name = None):
219         self.worst = max(self.worst, extend.worst)
220
221         if self.worst == extend.worst:
222             self.worst_field = extend.worst_field
223
224         self.checks.extend(extend.checks)
225
226 class Field:
227     def __init__(self, struct_name, desc, field_options):
228         '''desc is FieldDescriptorProto'''
229         self.tag = desc.number
230         self.struct_name = struct_name
231         self.union_name = None
232         self.name = desc.name
233         self.default = None
234         self.max_size = None
235         self.max_count = None
236         self.array_decl = ""
237         self.enc_size = None
238         self.ctype = None
239
240         # Parse field options
241         if field_options.HasField("max_size"):
242             self.max_size = field_options.max_size
243
244         if field_options.HasField("max_count"):
245             self.max_count = field_options.max_count
246
247         if desc.HasField('default_value'):
248             self.default = desc.default_value
249
250         # Check field rules, i.e. required/optional/repeated.
251         can_be_static = True
252         if desc.label == FieldD.LABEL_REQUIRED:
253             self.rules = 'REQUIRED'
254         elif desc.label == FieldD.LABEL_OPTIONAL:
255             self.rules = 'OPTIONAL'
256         elif desc.label == FieldD.LABEL_REPEATED:
257             self.rules = 'REPEATED'
258             if self.max_count is None:
259                 can_be_static = False
260             else:
261                 self.array_decl = '[%d]' % self.max_count
262         else:
263             raise NotImplementedError(desc.label)
264
265         # Check if the field can be implemented with static allocation
266         # i.e. whether the data size is known.
267         if desc.type == FieldD.TYPE_STRING and self.max_size is None:
268             can_be_static = False
269
270         if desc.type == FieldD.TYPE_BYTES and self.max_size is None:
271             can_be_static = False
272
273         # Decide how the field data will be allocated
274         if field_options.type == nanopb_pb2.FT_DEFAULT:
275             if can_be_static:
276                 field_options.type = nanopb_pb2.FT_STATIC
277             else:
278                 field_options.type = nanopb_pb2.FT_CALLBACK
279
280         if field_options.type == nanopb_pb2.FT_STATIC and not can_be_static:
281             raise Exception("Field %s is defined as static, but max_size or "
282                             "max_count is not given." % self.name)
283
284         if field_options.type == nanopb_pb2.FT_STATIC:
285             self.allocation = 'STATIC'
286         elif field_options.type == nanopb_pb2.FT_POINTER:
287             self.allocation = 'POINTER'
288         elif field_options.type == nanopb_pb2.FT_CALLBACK:
289             self.allocation = 'CALLBACK'
290         else:
291             raise NotImplementedError(field_options.type)
292
293         # Decide the C data type to use in the struct.
294         if desc.type in datatypes:
295             self.ctype, self.pbtype, self.enc_size, isa = datatypes[desc.type]
296
297             # Override the field size if user wants to use smaller integers
298             if isa and field_options.int_size != nanopb_pb2.IS_DEFAULT:
299                 self.ctype = intsizes[field_options.int_size]
300                 if desc.type == FieldD.TYPE_UINT32 or desc.type == FieldD.TYPE_UINT64:
301                     self.ctype = 'u' + self.ctype;
302         elif desc.type == FieldD.TYPE_ENUM:
303             self.pbtype = 'ENUM'
304             self.ctype = names_from_type_name(desc.type_name)
305             if self.default is not None:
306                 self.default = self.ctype + self.default
307             self.enc_size = None # Needs to be filled in when enum values are known
308         elif desc.type == FieldD.TYPE_STRING:
309             self.pbtype = 'STRING'
310             self.ctype = 'char'
311             if self.allocation == 'STATIC':
312                 self.ctype = 'char'
313                 self.array_decl += '[%d]' % self.max_size
314                 self.enc_size = varint_max_size(self.max_size) + self.max_size
315         elif desc.type == FieldD.TYPE_BYTES:
316             self.pbtype = 'BYTES'
317             if self.allocation == 'STATIC':
318                 self.ctype = self.struct_name + self.name + 't'
319                 self.enc_size = varint_max_size(self.max_size) + self.max_size
320             elif self.allocation == 'POINTER':
321                 self.ctype = 'pb_bytes_array_t'
322         elif desc.type == FieldD.TYPE_MESSAGE:
323             self.pbtype = 'MESSAGE'
324             self.ctype = self.submsgname = names_from_type_name(desc.type_name)
325             self.enc_size = None # Needs to be filled in after the message type is available
326         else:
327             raise NotImplementedError(desc.type)
328
329     def __lt__(self, other):
330         return self.tag < other.tag
331
332     def __str__(self):
333         result = ''
334         if self.allocation == 'POINTER':
335             if self.rules == 'REPEATED':
336                 result += '    pb_size_t ' + self.name + '_count;\n'
337
338             if self.pbtype == 'MESSAGE':
339                 # Use struct definition, so recursive submessages are possible
340                 result += '    struct _%s *%s;' % (self.ctype, self.name)
341             elif self.rules == 'REPEATED' and self.pbtype in ['STRING', 'BYTES']:
342                 # String/bytes arrays need to be defined as pointers to pointers
343                 result += '    %s **%s;' % (self.ctype, self.name)
344             else:
345                 result += '    %s *%s;' % (self.ctype, self.name)
346         elif self.allocation == 'CALLBACK':
347             result += '    pb_callback_t %s;' % self.name
348         else:
349             if self.rules == 'OPTIONAL' and self.allocation == 'STATIC':
350                 result += '    bool has_' + self.name + ';\n'
351             elif self.rules == 'REPEATED' and self.allocation == 'STATIC':
352                 result += '    pb_size_t ' + self.name + '_count;\n'
353             result += '    %s %s%s;' % (self.ctype, self.name, self.array_decl)
354         return result
355
356     def types(self):
357         '''Return definitions for any special types this field might need.'''
358         if self.pbtype == 'BYTES' and self.allocation == 'STATIC':
359             result = 'typedef PB_BYTES_ARRAY_T(%d) %s;\n' % (self.max_size, self.ctype)
360         else:
361             result = ''
362         return result
363
364     def get_dependencies(self):
365         '''Get list of type names used by this field.'''
366         if self.allocation == 'STATIC':
367             return [str(self.ctype)]
368         else:
369             return []
370
371     def get_initializer(self, null_init, inner_init_only = False):
372         '''Return literal expression for this field's default value.
373         null_init: If True, initialize to a 0 value instead of default from .proto
374         inner_init_only: If True, exclude initialization for any count/has fields
375         '''
376
377         inner_init = None
378         if self.pbtype == 'MESSAGE':
379             if null_init:
380                 inner_init = '%s_init_zero' % self.ctype
381             else:
382                 inner_init = '%s_init_default' % self.ctype
383         elif self.default is None or null_init:
384             if self.pbtype == 'STRING':
385                 inner_init = '""'
386             elif self.pbtype == 'BYTES':
387                 inner_init = '{0, {0}}'
388             elif self.pbtype in ('ENUM', 'UENUM'):
389                 inner_init = '(%s)0' % self.ctype
390             else:
391                 inner_init = '0'
392         else:
393             if self.pbtype == 'STRING':
394                 inner_init = self.default.replace('"', '\\"')
395                 inner_init = '"' + inner_init + '"'
396             elif self.pbtype == 'BYTES':
397                 data = ['0x%02x' % ord(c) for c in self.default]
398                 if len(data) == 0:
399                     inner_init = '{0, {0}}'
400                 else:
401                     inner_init = '{%d, {%s}}' % (len(data), ','.join(data))
402             elif self.pbtype in ['FIXED32', 'UINT32']:
403                 inner_init = str(self.default) + 'u'
404             elif self.pbtype in ['FIXED64', 'UINT64']:
405                 inner_init = str(self.default) + 'ull'
406             elif self.pbtype in ['SFIXED64', 'INT64']:
407                 inner_init = str(self.default) + 'll'
408             else:
409                 inner_init = str(self.default)
410
411         if inner_init_only:
412             return inner_init
413
414         outer_init = None
415         if self.allocation == 'STATIC':
416             if self.rules == 'REPEATED':
417                 outer_init = '0, {'
418                 outer_init += ', '.join([inner_init] * self.max_count)
419                 outer_init += '}'
420             elif self.rules == 'OPTIONAL':
421                 outer_init = 'false, ' + inner_init
422             else:
423                 outer_init = inner_init
424         elif self.allocation == 'POINTER':
425             if self.rules == 'REPEATED':
426                 outer_init = '0, NULL'
427             else:
428                 outer_init = 'NULL'
429         elif self.allocation == 'CALLBACK':
430             if self.pbtype == 'EXTENSION':
431                 outer_init = 'NULL'
432             else:
433                 outer_init = '{{NULL}, NULL}'
434
435         return outer_init
436
437     def default_decl(self, declaration_only = False):
438         '''Return definition for this field's default value.'''
439         if self.default is None:
440             return None
441
442         ctype = self.ctype
443         default = self.get_initializer(False, True)
444         array_decl = ''
445
446         if self.pbtype == 'STRING':
447             if self.allocation != 'STATIC':
448                 return None # Not implemented
449             array_decl = '[%d]' % self.max_size
450         elif self.pbtype == 'BYTES':
451             if self.allocation != 'STATIC':
452                 return None # Not implemented
453
454         if declaration_only:
455             return 'extern const %s %s_default%s;' % (ctype, self.struct_name + self.name, array_decl)
456         else:
457             return 'const %s %s_default%s = %s;' % (ctype, self.struct_name + self.name, array_decl, default)
458
459     def tags(self):
460         '''Return the #define for the tag number of this field.'''
461         identifier = '%s_%s_tag' % (self.struct_name, self.name)
462         return '#define %-40s %d\n' % (identifier, self.tag)
463
464     def pb_field_t(self, prev_field_name):
465         '''Return the pb_field_t initializer to use in the constant array.
466         prev_field_name is the name of the previous field or None.
467         '''
468
469         if self.rules == 'ONEOF':
470             if self.anonymous:
471                 result = '    PB_ANONYMOUS_ONEOF_FIELD(%s, ' % self.union_name
472             else:
473                 result = '    PB_ONEOF_FIELD(%s, ' % self.union_name
474         else:
475             result = '    PB_FIELD('
476
477         result += '%3d, ' % self.tag
478         result += '%-8s, ' % self.pbtype
479         result += '%s, ' % self.rules
480         result += '%-8s, ' % self.allocation
481         result += '%s, ' % ("FIRST" if not prev_field_name else "OTHER")
482         result += '%s, ' % self.struct_name
483         result += '%s, ' % self.name
484         result += '%s, ' % (prev_field_name or self.name)
485
486         if self.pbtype == 'MESSAGE':
487             result += '&%s_fields)' % self.submsgname
488         elif self.default is None:
489             result += '0)'
490         elif self.pbtype in ['BYTES', 'STRING'] and self.allocation != 'STATIC':
491             result += '0)' # Arbitrary size default values not implemented
492         elif self.rules == 'OPTEXT':
493             result += '0)' # Default value for extensions is not implemented
494         else:
495             result += '&%s_default)' % (self.struct_name + self.name)
496
497         return result
498
499     def get_last_field_name(self):
500         return self.name
501
502     def largest_field_value(self):
503         '''Determine if this field needs 16bit or 32bit pb_field_t structure to compile properly.
504         Returns numeric value or a C-expression for assert.'''
505         check = []
506         if self.pbtype == 'MESSAGE':
507             if self.rules == 'REPEATED' and self.allocation == 'STATIC':
508                 check.append('pb_membersize(%s, %s[0])' % (self.struct_name, self.name))
509             elif self.rules == 'ONEOF':
510                 if self.anonymous:
511                     check.append('pb_membersize(%s, %s)' % (self.struct_name, self.name))
512                 else:
513                     check.append('pb_membersize(%s, %s.%s)' % (self.struct_name, self.union_name, self.name))
514             else:
515                 check.append('pb_membersize(%s, %s)' % (self.struct_name, self.name))
516
517         return FieldMaxSize([self.tag, self.max_size, self.max_count],
518                             check,
519                             ('%s.%s' % (self.struct_name, self.name)))
520
521     def encoded_size(self, dependencies):
522         '''Return the maximum size that this field can take when encoded,
523         including the field tag. If the size cannot be determined, returns
524         None.'''
525
526         if self.allocation != 'STATIC':
527             return None
528
529         if self.pbtype == 'MESSAGE':
530             encsize = None
531             if str(self.submsgname) in dependencies:
532                 submsg = dependencies[str(self.submsgname)]
533                 encsize = submsg.encoded_size(dependencies)
534                 if encsize is not None:
535                     # Include submessage length prefix
536                     encsize += varint_max_size(encsize.upperlimit())
537
538             if encsize is None:
539                 # Submessage or its size cannot be found.
540                 # This can occur if submessage is defined in different
541                 # file, and it or its .options could not be found.
542                 # Instead of direct numeric value, reference the size that
543                 # has been #defined in the other file.
544                 encsize = EncodedSize(self.submsgname + 'size')
545
546                 # We will have to make a conservative assumption on the length
547                 # prefix size, though.
548                 encsize += 5
549
550         elif self.pbtype in ['ENUM', 'UENUM']:
551             if str(self.ctype) in dependencies:
552                 enumtype = dependencies[str(self.ctype)]
553                 encsize = enumtype.encoded_size()
554             else:
555                 # Conservative assumption
556                 encsize = 10
557
558         elif self.enc_size is None:
559             raise RuntimeError("Could not determine encoded size for %s.%s"
560                                % (self.struct_name, self.name))
561         else:
562             encsize = EncodedSize(self.enc_size)
563
564         encsize += varint_max_size(self.tag << 3) # Tag + wire type
565
566         if self.rules == 'REPEATED':
567             # Decoders must be always able to handle unpacked arrays.
568             # Therefore we have to reserve space for it, even though
569             # we emit packed arrays ourselves.
570             encsize *= self.max_count
571
572         return encsize
573
574
575 class ExtensionRange(Field):
576     def __init__(self, struct_name, range_start, field_options):
577         '''Implements a special pb_extension_t* field in an extensible message
578         structure. The range_start signifies the index at which the extensions
579         start. Not necessarily all tags above this are extensions, it is merely
580         a speed optimization.
581         '''
582         self.tag = range_start
583         self.struct_name = struct_name
584         self.name = 'extensions'
585         self.pbtype = 'EXTENSION'
586         self.rules = 'OPTIONAL'
587         self.allocation = 'CALLBACK'
588         self.ctype = 'pb_extension_t'
589         self.array_decl = ''
590         self.default = None
591         self.max_size = 0
592         self.max_count = 0
593
594     def __str__(self):
595         return '    pb_extension_t *extensions;'
596
597     def types(self):
598         return ''
599
600     def tags(self):
601         return ''
602
603     def encoded_size(self, dependencies):
604         # We exclude extensions from the count, because they cannot be known
605         # until runtime. Other option would be to return None here, but this
606         # way the value remains useful if extensions are not used.
607         return EncodedSize(0)
608
609 class ExtensionField(Field):
610     def __init__(self, struct_name, desc, field_options):
611         self.fullname = struct_name + desc.name
612         self.extendee_name = names_from_type_name(desc.extendee)
613         Field.__init__(self, self.fullname + 'struct', desc, field_options)
614
615         if self.rules != 'OPTIONAL':
616             self.skip = True
617         else:
618             self.skip = False
619             self.rules = 'OPTEXT'
620
621     def tags(self):
622         '''Return the #define for the tag number of this field.'''
623         identifier = '%s_tag' % self.fullname
624         return '#define %-40s %d\n' % (identifier, self.tag)
625
626     def extension_decl(self):
627         '''Declaration of the extension type in the .pb.h file'''
628         if self.skip:
629             msg = '/* Extension field %s was skipped because only "optional"\n' % self.fullname
630             msg +='   type of extension fields is currently supported. */\n'
631             return msg
632
633         return ('extern const pb_extension_type_t %s; /* field type: %s */\n' %
634             (self.fullname, str(self).strip()))
635
636     def extension_def(self):
637         '''Definition of the extension type in the .pb.c file'''
638
639         if self.skip:
640             return ''
641
642         result  = 'typedef struct {\n'
643         result += str(self)
644         result += '\n} %s;\n\n' % self.struct_name
645         result += ('static const pb_field_t %s_field = \n  %s;\n\n' %
646                     (self.fullname, self.pb_field_t(None)))
647         result += 'const pb_extension_type_t %s = {\n' % self.fullname
648         result += '    NULL,\n'
649         result += '    NULL,\n'
650         result += '    &%s_field\n' % self.fullname
651         result += '};\n'
652         return result
653
654
655 # ---------------------------------------------------------------------------
656 #                   Generation of oneofs (unions)
657 # ---------------------------------------------------------------------------
658
659 class OneOf(Field):
660     def __init__(self, struct_name, oneof_desc):
661         self.struct_name = struct_name
662         self.name = oneof_desc.name
663         self.ctype = 'union'
664         self.pbtype = 'oneof'
665         self.fields = []
666         self.allocation = 'ONEOF'
667         self.default = None
668         self.rules = 'ONEOF'
669         self.anonymous = False
670
671     def add_field(self, field):
672         if field.allocation == 'CALLBACK':
673             raise Exception("Callback fields inside of oneof are not supported"
674                             + " (field %s)" % field.name)
675
676         field.union_name = self.name
677         field.rules = 'ONEOF'
678         field.anonymous = self.anonymous
679         self.fields.append(field)
680         self.fields.sort(key = lambda f: f.tag)
681
682         # Sort by the lowest tag number inside union
683         self.tag = min([f.tag for f in self.fields])
684
685     def __str__(self):
686         result = ''
687         if self.fields:
688             result += '    pb_size_t which_' + self.name + ";\n"
689             result += '    union {\n'
690             for f in self.fields:
691                 result += '    ' + str(f).replace('\n', '\n    ') + '\n'
692             if self.anonymous:
693                 result += '    };'
694             else:
695                 result += '    } ' + self.name + ';'
696         return result
697
698     def types(self):
699         return ''.join([f.types() for f in self.fields])
700
701     def get_dependencies(self):
702         deps = []
703         for f in self.fields:
704             deps += f.get_dependencies()
705         return deps
706
707     def get_initializer(self, null_init):
708         return '0, {' + self.fields[0].get_initializer(null_init) + '}'
709
710     def default_decl(self, declaration_only = False):
711         return None
712
713     def tags(self):
714         return ''.join([f.tags() for f in self.fields])
715
716     def pb_field_t(self, prev_field_name):
717         result = ',\n'.join([f.pb_field_t(prev_field_name) for f in self.fields])
718         return result
719
720     def get_last_field_name(self):
721         if self.anonymous:
722             return self.fields[-1].name
723         else:
724             return self.name + '.' + self.fields[-1].name
725
726     def largest_field_value(self):
727         largest = FieldMaxSize()
728         for f in self.fields:
729             largest.extend(f.largest_field_value())
730         return largest
731
732     def encoded_size(self, dependencies):
733         '''Returns the size of the largest oneof field.'''
734         largest = EncodedSize(0)
735         for f in self.fields:
736             size = EncodedSize(f.encoded_size(dependencies))
737             if size.value is None:
738                 return None
739             elif size.symbols:
740                 return None # Cannot resolve maximum of symbols
741             elif size.value > largest.value:
742                 largest = size
743
744         return largest
745
746 # ---------------------------------------------------------------------------
747 #                   Generation of messages (structures)
748 # ---------------------------------------------------------------------------
749
750
751 class Message:
752     def __init__(self, names, desc, message_options):
753         self.name = names
754         self.fields = []
755         self.oneofs = {}
756         no_unions = []
757
758         if message_options.msgid:
759             self.msgid = message_options.msgid
760
761         if hasattr(desc, 'oneof_decl'):
762             for i, f in enumerate(desc.oneof_decl):
763                 oneof_options = get_nanopb_suboptions(desc, message_options, self.name + f.name)
764                 if oneof_options.no_unions:
765                     no_unions.append(i) # No union, but add fields normally
766                 elif oneof_options.type == nanopb_pb2.FT_IGNORE:
767                     pass # No union and skip fields also
768                 else:
769                     oneof = OneOf(self.name, f)
770                     if oneof_options.anonymous_oneof:
771                         oneof.anonymous = True
772                     self.oneofs[i] = oneof
773                     self.fields.append(oneof)
774
775         for f in desc.field:
776             field_options = get_nanopb_suboptions(f, message_options, self.name + f.name)
777             if field_options.type == nanopb_pb2.FT_IGNORE:
778                 continue
779
780             field = Field(self.name, f, field_options)
781             if (hasattr(f, 'oneof_index') and
782                 f.HasField('oneof_index') and
783                 f.oneof_index not in no_unions):
784                 if f.oneof_index in self.oneofs:
785                     self.oneofs[f.oneof_index].add_field(field)
786             else:
787                 self.fields.append(field)
788
789         if len(desc.extension_range) > 0:
790             field_options = get_nanopb_suboptions(desc, message_options, self.name + 'extensions')
791             range_start = min([r.start for r in desc.extension_range])
792             if field_options.type != nanopb_pb2.FT_IGNORE:
793                 self.fields.append(ExtensionRange(self.name, range_start, field_options))
794
795         self.packed = message_options.packed_struct
796         self.ordered_fields = self.fields[:]
797         self.ordered_fields.sort()
798
799     def get_dependencies(self):
800         '''Get list of type names that this structure refers to.'''
801         deps = []
802         for f in self.fields:
803             deps += f.get_dependencies()
804         return deps
805
806     def __str__(self):
807         result = 'typedef struct _%s {\n' % self.name
808
809         if not self.ordered_fields:
810             # Empty structs are not allowed in C standard.
811             # Therefore add a dummy field if an empty message occurs.
812             result += '    char dummy_field;'
813
814         result += '\n'.join([str(f) for f in self.ordered_fields])
815         result += '\n}'
816
817         if self.packed:
818             result += ' pb_packed'
819
820         result += ' %s;' % self.name
821
822         if self.packed:
823             result = 'PB_PACKED_STRUCT_START\n' + result
824             result += '\nPB_PACKED_STRUCT_END'
825
826         return result
827
828     def types(self):
829         return ''.join([f.types() for f in self.fields])
830
831     def get_initializer(self, null_init):
832         if not self.ordered_fields:
833             return '{0}'
834
835         parts = []
836         for field in self.ordered_fields:
837             parts.append(field.get_initializer(null_init))
838         return '{' + ', '.join(parts) + '}'
839
840     def default_decl(self, declaration_only = False):
841         result = ""
842         for field in self.fields:
843             default = field.default_decl(declaration_only)
844             if default is not None:
845                 result += default + '\n'
846         return result
847
848     def count_required_fields(self):
849         '''Returns number of required fields inside this message'''
850         count = 0
851         for f in self.fields:
852             if not isinstance(f, OneOf):
853                 if f.rules == 'REQUIRED':
854                     count += 1
855         return count
856
857     def count_all_fields(self):
858         count = 0
859         for f in self.fields:
860             if isinstance(f, OneOf):
861                 count += len(f.fields)
862             else:
863                 count += 1
864         return count
865
866     def fields_declaration(self):
867         result = 'extern const pb_field_t %s_fields[%d];' % (self.name, self.count_all_fields() + 1)
868         return result
869
870     def fields_definition(self):
871         result = 'const pb_field_t %s_fields[%d] = {\n' % (self.name, self.count_all_fields() + 1)
872
873         prev = None
874         for field in self.ordered_fields:
875             result += field.pb_field_t(prev)
876             result += ',\n'
877             prev = field.get_last_field_name()
878
879         result += '    PB_LAST_FIELD\n};'
880         return result
881
882     def encoded_size(self, dependencies):
883         '''Return the maximum size that this message can take when encoded.
884         If the size cannot be determined, returns None.
885         '''
886         size = EncodedSize(0)
887         for field in self.fields:
888             fsize = field.encoded_size(dependencies)
889             if fsize is None:
890                 return None
891             size += fsize
892
893         return size
894
895
896 # ---------------------------------------------------------------------------
897 #                    Processing of entire .proto files
898 # ---------------------------------------------------------------------------
899
900 def iterate_messages(desc, names = Names()):
901     '''Recursively find all messages. For each, yield name, DescriptorProto.'''
902     if hasattr(desc, 'message_type'):
903         submsgs = desc.message_type
904     else:
905         submsgs = desc.nested_type
906
907     for submsg in submsgs:
908         sub_names = names + submsg.name
909         yield sub_names, submsg
910
911         for x in iterate_messages(submsg, sub_names):
912             yield x
913
914 def iterate_extensions(desc, names = Names()):
915     '''Recursively find all extensions.
916     For each, yield name, FieldDescriptorProto.
917     '''
918     for extension in desc.extension:
919         yield names, extension
920
921     for subname, subdesc in iterate_messages(desc, names):
922         for extension in subdesc.extension:
923             yield subname, extension
924
925 def toposort2(data):
926     '''Topological sort.
927     From http://code.activestate.com/recipes/577413-topological-sort/
928     This function is under the MIT license.
929     '''
930     for k, v in list(data.items()):
931         v.discard(k) # Ignore self dependencies
932     extra_items_in_deps = reduce(set.union, list(data.values()), set()) - set(data.keys())
933     data.update(dict([(item, set()) for item in extra_items_in_deps]))
934     while True:
935         ordered = set(item for item,dep in list(data.items()) if not dep)
936         if not ordered:
937             break
938         for item in sorted(ordered):
939             yield item
940         data = dict([(item, (dep - ordered)) for item,dep in list(data.items())
941                 if item not in ordered])
942     assert not data, "A cyclic dependency exists amongst %r" % data
943
944 def sort_dependencies(messages):
945     '''Sort a list of Messages based on dependencies.'''
946     dependencies = {}
947     message_by_name = {}
948     for message in messages:
949         dependencies[str(message.name)] = set(message.get_dependencies())
950         message_by_name[str(message.name)] = message
951
952     for msgname in toposort2(dependencies):
953         if msgname in message_by_name:
954             yield message_by_name[msgname]
955
956 def make_identifier(headername):
957     '''Make #ifndef identifier that contains uppercase A-Z and digits 0-9'''
958     result = ""
959     for c in headername.upper():
960         if c.isalnum():
961             result += c
962         else:
963             result += '_'
964     return result
965
966 class ProtoFile:
967     def __init__(self, fdesc, file_options):
968         '''Takes a FileDescriptorProto and parses it.'''
969         self.fdesc = fdesc
970         self.file_options = file_options
971         self.dependencies = {}
972         self.parse()
973
974         # Some of types used in this file probably come from the file itself.
975         # Thus it has implicit dependency on itself.
976         self.add_dependency(self)
977
978     def parse(self):
979         self.enums = []
980         self.messages = []
981         self.extensions = []
982
983         if self.fdesc.package:
984             base_name = Names(self.fdesc.package.split('.'))
985         else:
986             base_name = Names()
987
988         for enum in self.fdesc.enum_type:
989             enum_options = get_nanopb_suboptions(enum, self.file_options, base_name + enum.name)
990             self.enums.append(Enum(base_name, enum, enum_options))
991
992         for names, message in iterate_messages(self.fdesc, base_name):
993             message_options = get_nanopb_suboptions(message, self.file_options, names)
994
995             if message_options.skip_message:
996                 continue
997
998             self.messages.append(Message(names, message, message_options))
999             for enum in message.enum_type:
1000                 enum_options = get_nanopb_suboptions(enum, message_options, names + enum.name)
1001                 self.enums.append(Enum(names, enum, enum_options))
1002
1003         for names, extension in iterate_extensions(self.fdesc, base_name):
1004             field_options = get_nanopb_suboptions(extension, self.file_options, names + extension.name)
1005             if field_options.type != nanopb_pb2.FT_IGNORE:
1006                 self.extensions.append(ExtensionField(names, extension, field_options))
1007
1008     def add_dependency(self, other):
1009         for enum in other.enums:
1010             self.dependencies[str(enum.names)] = enum
1011
1012         for msg in other.messages:
1013             self.dependencies[str(msg.name)] = msg
1014
1015         # Fix field default values where enum short names are used.
1016         for enum in other.enums:
1017             if not enum.options.long_names:
1018                 for message in self.messages:
1019                     for field in message.fields:
1020                         if field.default in enum.value_longnames:
1021                             idx = enum.value_longnames.index(field.default)
1022                             field.default = enum.values[idx][0]
1023
1024         # Fix field data types where enums have negative values.
1025         for enum in other.enums:
1026             if not enum.has_negative():
1027                 for message in self.messages:
1028                     for field in message.fields:
1029                         if field.pbtype == 'ENUM' and field.ctype == enum.names:
1030                             field.pbtype = 'UENUM'
1031
1032     def generate_header(self, includes, headername, options):
1033         '''Generate content for a header file.
1034         Generates strings, which should be concatenated and stored to file.
1035         '''
1036
1037         yield '/* Automatically generated nanopb header */\n'
1038         if options.notimestamp:
1039             yield '/* Generated by %s */\n\n' % (nanopb_version)
1040         else:
1041             yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
1042
1043         symbol = make_identifier(headername)
1044         yield '#ifndef PB_%s_INCLUDED\n' % symbol
1045         yield '#define PB_%s_INCLUDED\n' % symbol
1046         try:
1047             yield options.libformat % ('pb.h')
1048         except TypeError:
1049             # no %s specified - use whatever was passed in as options.libformat
1050             yield options.libformat
1051         yield '\n'
1052
1053         for incfile in includes:
1054             noext = os.path.splitext(incfile)[0]
1055             yield options.genformat % (noext + options.extension + '.h')
1056             yield '\n'
1057
1058         yield '#if PB_PROTO_HEADER_VERSION != 30\n'
1059         yield '#error Regenerate this file with the current version of nanopb generator.\n'
1060         yield '#endif\n'
1061         yield '\n'
1062
1063         yield '#ifdef __cplusplus\n'
1064         yield 'extern "C" {\n'
1065         yield '#endif\n\n'
1066
1067         if self.enums:
1068             yield '/* Enum definitions */\n'
1069             for enum in self.enums:
1070                 yield str(enum) + '\n\n'
1071
1072         if self.messages:
1073             yield '/* Struct definitions */\n'
1074             for msg in sort_dependencies(self.messages):
1075                 yield msg.types()
1076                 yield str(msg) + '\n\n'
1077
1078         if self.extensions:
1079             yield '/* Extensions */\n'
1080             for extension in self.extensions:
1081                 yield extension.extension_decl()
1082             yield '\n'
1083
1084         if self.messages:
1085             yield '/* Default values for struct fields */\n'
1086             for msg in self.messages:
1087                 yield msg.default_decl(True)
1088             yield '\n'
1089
1090             yield '/* Initializer values for message structs */\n'
1091             for msg in self.messages:
1092                 identifier = '%s_init_default' % msg.name
1093                 yield '#define %-40s %s\n' % (identifier, msg.get_initializer(False))
1094             for msg in self.messages:
1095                 identifier = '%s_init_zero' % msg.name
1096                 yield '#define %-40s %s\n' % (identifier, msg.get_initializer(True))
1097             yield '\n'
1098
1099             yield '/* Field tags (for use in manual encoding/decoding) */\n'
1100             for msg in sort_dependencies(self.messages):
1101                 for field in msg.fields:
1102                     yield field.tags()
1103             for extension in self.extensions:
1104                 yield extension.tags()
1105             yield '\n'
1106
1107             yield '/* Struct field encoding specification for nanopb */\n'
1108             for msg in self.messages:
1109                 yield msg.fields_declaration() + '\n'
1110             yield '\n'
1111
1112             yield '/* Maximum encoded size of messages (where known) */\n'
1113             for msg in self.messages:
1114                 msize = msg.encoded_size(self.dependencies)
1115                 if msize is not None:
1116                     identifier = '%s_size' % msg.name
1117                     yield '#define %-40s %s\n' % (identifier, msize)
1118             yield '\n'
1119
1120             yield '/* Message IDs (where set with "msgid" option) */\n'
1121
1122             yield '#ifdef PB_MSGID\n'
1123             for msg in self.messages:
1124                 if hasattr(msg,'msgid'):
1125                     yield '#define PB_MSG_%d %s\n' % (msg.msgid, msg.name)
1126             yield '\n'
1127
1128             symbol = make_identifier(headername.split('.')[0])
1129             yield '#define %s_MESSAGES \\\n' % symbol
1130
1131             for msg in self.messages:
1132                 m = "-1"
1133                 msize = msg.encoded_size(self.dependencies)
1134                 if msize is not None:
1135                     m = msize
1136                 if hasattr(msg,'msgid'):
1137                     yield '\tPB_MSG(%d,%s,%s) \\\n' % (msg.msgid, m, msg.name)
1138             yield '\n'
1139
1140             for msg in self.messages:
1141                 if hasattr(msg,'msgid'):
1142                     yield '#define %s_msgid %d\n' % (msg.name, msg.msgid)
1143             yield '\n'
1144
1145             yield '#endif\n\n'
1146
1147         yield '#ifdef __cplusplus\n'
1148         yield '} /* extern "C" */\n'
1149         yield '#endif\n'
1150
1151         # End of header
1152         yield '\n#endif\n'
1153
1154     def generate_source(self, headername, options):
1155         '''Generate content for a source file.'''
1156
1157         yield '/* Automatically generated nanopb constant definitions */\n'
1158         if options.notimestamp:
1159             yield '/* Generated by %s */\n\n' % (nanopb_version)
1160         else:
1161             yield '/* Generated by %s at %s. */\n\n' % (nanopb_version, time.asctime())
1162         yield options.genformat % (headername)
1163         yield '\n'
1164
1165         yield '#if PB_PROTO_HEADER_VERSION != 30\n'
1166         yield '#error Regenerate this file with the current version of nanopb generator.\n'
1167         yield '#endif\n'
1168         yield '\n'
1169
1170         for msg in self.messages:
1171             yield msg.default_decl(False)
1172
1173         yield '\n\n'
1174
1175         for msg in self.messages:
1176             yield msg.fields_definition() + '\n\n'
1177
1178         for ext in self.extensions:
1179             yield ext.extension_def() + '\n'
1180
1181         # Add checks for numeric limits
1182         if self.messages:
1183             largest_msg = max(self.messages, key = lambda m: m.count_required_fields())
1184             largest_count = largest_msg.count_required_fields()
1185             if largest_count > 64:
1186                 yield '\n/* Check that missing required fields will be properly detected */\n'
1187                 yield '#if PB_MAX_REQUIRED_FIELDS < %d\n' % largest_count
1188                 yield '#error Properly detecting missing required fields in %s requires \\\n' % largest_msg.name
1189                 yield '       setting PB_MAX_REQUIRED_FIELDS to %d or more.\n' % largest_count
1190                 yield '#endif\n'
1191
1192         max_field = FieldMaxSize()
1193         checks_msgnames = []
1194         for msg in self.messages:
1195             checks_msgnames.append(msg.name)
1196             for field in msg.fields:
1197                 max_field.extend(field.largest_field_value())
1198
1199         worst = max_field.worst
1200         worst_field = max_field.worst_field
1201         checks = max_field.checks
1202
1203         if worst > 255 or checks:
1204             yield '\n/* Check that field information fits in pb_field_t */\n'
1205
1206             if worst > 65535 or checks:
1207                 yield '#if !defined(PB_FIELD_32BIT)\n'
1208                 if worst > 65535:
1209                     yield '#error Field descriptor for %s is too large. Define PB_FIELD_32BIT to fix this.\n' % worst_field
1210                 else:
1211                     assertion = ' && '.join(str(c) + ' < 65536' for c in checks)
1212                     msgs = '_'.join(str(n) for n in checks_msgnames)
1213                     yield '/* If you get an error here, it means that you need to define PB_FIELD_32BIT\n'
1214                     yield ' * compile-time option. You can do that in pb.h or on compiler command line.\n'
1215                     yield ' * \n'
1216                     yield ' * The reason you need to do this is that some of your messages contain tag\n'
1217                     yield ' * numbers or field sizes that are larger than what can fit in 8 or 16 bit\n'
1218                     yield ' * field descriptors.\n'
1219                     yield ' */\n'
1220                     yield 'PB_STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
1221                 yield '#endif\n\n'
1222
1223             if worst < 65536:
1224                 yield '#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT)\n'
1225                 if worst > 255:
1226                     yield '#error Field descriptor for %s is too large. Define PB_FIELD_16BIT to fix this.\n' % worst_field
1227                 else:
1228                     assertion = ' && '.join(str(c) + ' < 256' for c in checks)
1229                     msgs = '_'.join(str(n) for n in checks_msgnames)
1230                     yield '/* If you get an error here, it means that you need to define PB_FIELD_16BIT\n'
1231                     yield ' * compile-time option. You can do that in pb.h or on compiler command line.\n'
1232                     yield ' * \n'
1233                     yield ' * The reason you need to do this is that some of your messages contain tag\n'
1234                     yield ' * numbers or field sizes that are larger than what can fit in the default\n'
1235                     yield ' * 8 bit descriptors.\n'
1236                     yield ' */\n'
1237                     yield 'PB_STATIC_ASSERT((%s), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_%s)\n'%(assertion,msgs)
1238                 yield '#endif\n\n'
1239
1240         # Add check for sizeof(double)
1241         has_double = False
1242         for msg in self.messages:
1243             for field in msg.fields:
1244                 if field.ctype == 'double':
1245                     has_double = True
1246
1247         if has_double:
1248             yield '\n'
1249             yield '/* On some platforms (such as AVR), double is really float.\n'
1250             yield ' * These are not directly supported by nanopb, but see example_avr_double.\n'
1251             yield ' * To get rid of this error, remove any double fields from your .proto.\n'
1252             yield ' */\n'
1253             yield 'PB_STATIC_ASSERT(sizeof(double) == 8, DOUBLE_MUST_BE_8_BYTES)\n'
1254
1255         yield '\n'
1256
1257 # ---------------------------------------------------------------------------
1258 #                    Options parsing for the .proto files
1259 # ---------------------------------------------------------------------------
1260
1261 from fnmatch import fnmatch
1262
1263 def read_options_file(infile):
1264     '''Parse a separate options file to list:
1265         [(namemask, options), ...]
1266     '''
1267     results = []
1268     data = infile.read()
1269     data = re.sub('/\*.*?\*/', '', data, flags = re.MULTILINE)
1270     data = re.sub('//.*?$', '', data, flags = re.MULTILINE)
1271     data = re.sub('#.*?$', '', data, flags = re.MULTILINE)
1272     for i, line in enumerate(data.split('\n')):
1273         line = line.strip()
1274         if not line:
1275             continue
1276
1277         parts = line.split(None, 1)
1278
1279         if len(parts) < 2:
1280             sys.stderr.write("%s:%d: " % (infile.name, i + 1) +
1281                              "Option lines should have space between field name and options. " +
1282                              "Skipping line: '%s'\n" % line)
1283             continue
1284
1285         opts = nanopb_pb2.NanoPBOptions()
1286
1287         try:
1288             text_format.Merge(parts[1], opts)
1289         except Exception as e:
1290             sys.stderr.write("%s:%d: " % (infile.name, i + 1) +
1291                              "Unparseable option line: '%s'. " % line +
1292                              "Error: %s\n" % str(e))
1293             continue
1294         results.append((parts[0], opts))
1295
1296     return results
1297
1298 class Globals:
1299     '''Ugly global variables, should find a good way to pass these.'''
1300     verbose_options = False
1301     separate_options = []
1302     matched_namemasks = set()
1303
1304 def get_nanopb_suboptions(subdesc, options, name):
1305     '''Get copy of options, and merge information from subdesc.'''
1306     new_options = nanopb_pb2.NanoPBOptions()
1307     new_options.CopyFrom(options)
1308
1309     # Handle options defined in a separate file
1310     dotname = '.'.join(name.parts)
1311     for namemask, options in Globals.separate_options:
1312         if fnmatch(dotname, namemask):
1313             Globals.matched_namemasks.add(namemask)
1314             new_options.MergeFrom(options)
1315
1316     # Handle options defined in .proto
1317     if isinstance(subdesc.options, descriptor.FieldOptions):
1318         ext_type = nanopb_pb2.nanopb
1319     elif isinstance(subdesc.options, descriptor.FileOptions):
1320         ext_type = nanopb_pb2.nanopb_fileopt
1321     elif isinstance(subdesc.options, descriptor.MessageOptions):
1322         ext_type = nanopb_pb2.nanopb_msgopt
1323     elif isinstance(subdesc.options, descriptor.EnumOptions):
1324         ext_type = nanopb_pb2.nanopb_enumopt
1325     else:
1326         raise Exception("Unknown options type")
1327
1328     if subdesc.options.HasExtension(ext_type):
1329         ext = subdesc.options.Extensions[ext_type]
1330         new_options.MergeFrom(ext)
1331
1332     if Globals.verbose_options:
1333         sys.stderr.write("Options for " + dotname + ": ")
1334         sys.stderr.write(text_format.MessageToString(new_options) + "\n")
1335
1336     return new_options
1337
1338
1339 # ---------------------------------------------------------------------------
1340 #                         Command line interface
1341 # ---------------------------------------------------------------------------
1342
1343 import sys
1344 import os.path
1345 from optparse import OptionParser
1346
1347 optparser = OptionParser(
1348     usage = "Usage: nanopb_generator.py [options] file.pb ...",
1349     epilog = "Compile file.pb from file.proto by: 'protoc -ofile.pb file.proto'. " +
1350              "Output will be written to file.pb.h and file.pb.c.")
1351 optparser.add_option("-x", dest="exclude", metavar="FILE", action="append", default=[],
1352     help="Exclude file from generated #include list.")
1353 optparser.add_option("-e", "--extension", dest="extension", metavar="EXTENSION", default=".pb",
1354     help="Set extension to use instead of '.pb' for generated files. [default: %default]")
1355 optparser.add_option("-f", "--options-file", dest="options_file", metavar="FILE", default="%s.options",
1356     help="Set name of a separate generator options file.")
1357 optparser.add_option("-I", "--options-path", dest="options_path", metavar="DIR",
1358     action="append", default = [],
1359     help="Search for .options files additionally in this path")
1360 optparser.add_option("-Q", "--generated-include-format", dest="genformat",
1361     metavar="FORMAT", default='#include "%s"\n',
1362     help="Set format string to use for including other .pb.h files. [default: %default]")
1363 optparser.add_option("-L", "--library-include-format", dest="libformat",
1364     metavar="FORMAT", default='#include <%s>\n',
1365     help="Set format string to use for including the nanopb pb.h header. [default: %default]")
1366 optparser.add_option("-T", "--no-timestamp", dest="notimestamp", action="store_true", default=False,
1367     help="Don't add timestamp to .pb.h and .pb.c preambles")
1368 optparser.add_option("-q", "--quiet", dest="quiet", action="store_true", default=False,
1369     help="Don't print anything except errors.")
1370 optparser.add_option("-v", "--verbose", dest="verbose", action="store_true", default=False,
1371     help="Print more information.")
1372 optparser.add_option("-s", dest="settings", metavar="OPTION:VALUE", action="append", default=[],
1373     help="Set generator option (max_size, max_count etc.).")
1374
1375 def parse_file(filename, fdesc, options):
1376     '''Parse a single file. Returns a ProtoFile instance.'''
1377     toplevel_options = nanopb_pb2.NanoPBOptions()
1378     for s in options.settings:
1379         text_format.Merge(s, toplevel_options)
1380
1381     if not fdesc:
1382         data = open(filename, 'rb').read()
1383         fdesc = descriptor.FileDescriptorSet.FromString(data).file[0]
1384
1385     # Check if there is a separate .options file
1386     had_abspath = False
1387     try:
1388         optfilename = options.options_file % os.path.splitext(filename)[0]
1389     except TypeError:
1390         # No %s specified, use the filename as-is
1391         optfilename = options.options_file
1392         had_abspath = True
1393
1394     paths = ['.'] + options.options_path
1395     for p in paths:
1396         if os.path.isfile(os.path.join(p, optfilename)):
1397             optfilename = os.path.join(p, optfilename)
1398             if options.verbose:
1399                 sys.stderr.write('Reading options from ' + optfilename + '\n')
1400             Globals.separate_options = read_options_file(open(optfilename, "rU"))
1401             break
1402     else:
1403         # If we are given a full filename and it does not exist, give an error.
1404         # However, don't give error when we automatically look for .options file
1405         # with the same name as .proto.
1406         if options.verbose or had_abspath:
1407             sys.stderr.write('Options file not found: ' + optfilename + '\n')
1408         Globals.separate_options = []
1409
1410     Globals.matched_namemasks = set()
1411
1412     # Parse the file
1413     file_options = get_nanopb_suboptions(fdesc, toplevel_options, Names([filename]))
1414     f = ProtoFile(fdesc, file_options)
1415     f.optfilename = optfilename
1416
1417     return f
1418
1419 def process_file(filename, fdesc, options, other_files = {}):
1420     '''Process a single file.
1421     filename: The full path to the .proto or .pb source file, as string.
1422     fdesc: The loaded FileDescriptorSet, or None to read from the input file.
1423     options: Command line options as they come from OptionsParser.
1424
1425     Returns a dict:
1426         {'headername': Name of header file,
1427          'headerdata': Data for the .h header file,
1428          'sourcename': Name of the source code file,
1429          'sourcedata': Data for the .c source code file
1430         }
1431     '''
1432     f = parse_file(filename, fdesc, options)
1433
1434     # Provide dependencies if available
1435     for dep in f.fdesc.dependency:
1436         if dep in other_files:
1437             f.add_dependency(other_files[dep])
1438
1439     # Decide the file names
1440     noext = os.path.splitext(filename)[0]
1441     headername = noext + options.extension + '.h'
1442     sourcename = noext + options.extension + '.c'
1443     headerbasename = os.path.basename(headername)
1444
1445     # List of .proto files that should not be included in the C header file
1446     # even if they are mentioned in the source .proto.
1447     excludes = ['nanopb.proto', 'google/protobuf/descriptor.proto'] + options.exclude
1448     includes = [d for d in f.fdesc.dependency if d not in excludes]
1449
1450     headerdata = ''.join(f.generate_header(includes, headerbasename, options))
1451     sourcedata = ''.join(f.generate_source(headerbasename, options))
1452
1453     # Check if there were any lines in .options that did not match a member
1454     unmatched = [n for n,o in Globals.separate_options if n not in Globals.matched_namemasks]
1455     if unmatched and not options.quiet:
1456         sys.stderr.write("Following patterns in " + f.optfilename + " did not match any fields: "
1457                          + ', '.join(unmatched) + "\n")
1458         if not Globals.verbose_options:
1459             sys.stderr.write("Use  protoc --nanopb-out=-v:.   to see a list of the field names.\n")
1460
1461     return {'headername': headername, 'headerdata': headerdata,
1462             'sourcename': sourcename, 'sourcedata': sourcedata}
1463
1464 def main_cli():
1465     '''Main function when invoked directly from the command line.'''
1466
1467     options, filenames = optparser.parse_args()
1468
1469     if not filenames:
1470         optparser.print_help()
1471         sys.exit(1)
1472
1473     if options.quiet:
1474         options.verbose = False
1475
1476     Globals.verbose_options = options.verbose
1477
1478     for filename in filenames:
1479         results = process_file(filename, None, options)
1480
1481         if not options.quiet:
1482             sys.stderr.write("Writing to " + results['headername'] + " and "
1483                              + results['sourcename'] + "\n")
1484
1485         open(results['headername'], 'w').write(results['headerdata'])
1486         open(results['sourcename'], 'w').write(results['sourcedata'])
1487
1488 def main_plugin():
1489     '''Main function when invoked as a protoc plugin.'''
1490
1491     import io, sys
1492     if sys.platform == "win32":
1493         import os, msvcrt
1494         # Set stdin and stdout to binary mode
1495         msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
1496         msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
1497
1498     data = io.open(sys.stdin.fileno(), "rb").read()
1499
1500     request = plugin_pb2.CodeGeneratorRequest.FromString(data)
1501
1502     try:
1503         # Versions of Python prior to 2.7.3 do not support unicode
1504         # input to shlex.split(). Try to convert to str if possible.
1505         params = str(request.parameter)
1506     except UnicodeEncodeError:
1507         params = request.parameter
1508
1509     import shlex
1510     args = shlex.split(params)
1511     options, dummy = optparser.parse_args(args)
1512
1513     Globals.verbose_options = options.verbose
1514
1515     response = plugin_pb2.CodeGeneratorResponse()
1516
1517     # Google's protoc does not currently indicate the full path of proto files.
1518     # Instead always add the main file path to the search dirs, that works for
1519     # the common case.
1520     import os.path
1521     options.options_path.append(os.path.dirname(request.file_to_generate[0]))
1522
1523     # Process any include files first, in order to have them
1524     # available as dependencies
1525     other_files = {}
1526     for fdesc in request.proto_file:
1527         other_files[fdesc.name] = parse_file(fdesc.name, fdesc, options)
1528
1529     for filename in request.file_to_generate:
1530         for fdesc in request.proto_file:
1531             if fdesc.name == filename:
1532                 results = process_file(filename, fdesc, options, other_files)
1533
1534                 f = response.file.add()
1535                 f.name = results['headername']
1536                 f.content = results['headerdata']
1537
1538                 f = response.file.add()
1539                 f.name = results['sourcename']
1540                 f.content = results['sourcedata']
1541
1542     io.open(sys.stdout.fileno(), "wb").write(response.SerializeToString())
1543
1544 if __name__ == '__main__':
1545     # Check if we are running as a plugin under protoc
1546     if 'protoc-gen-' in sys.argv[0] or '--protoc-plugin' in sys.argv:
1547         main_plugin()
1548     else:
1549         main_cli()
1550