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