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