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