ovsdb: Add support for "enum" constraints.
[sliver-openvswitch.git] / ovsdb / ovsdb-idlc.in
1 #! @PYTHON@
2
3 import getopt
4 import os
5 import re
6 import sys
7
8 sys.path.insert(0, "@abs_top_srcdir@/ovsdb")
9 import simplejson as json
10
11 argv0 = sys.argv[0]
12
13 class Error(Exception):
14     def __init__(self, msg):
15         Exception.__init__(self)
16         self.msg = msg
17
18 def getMember(json, name, validTypes, description, default=None):
19     if name in json:
20         member = json[name]
21         if len(validTypes) and type(member) not in validTypes:
22             raise Error("%s: type mismatch for '%s' member"
23                         % (description, name))
24         return member
25     return default
26
27 def mustGetMember(json, name, expectedType, description):
28     member = getMember(json, name, expectedType, description)
29     if member == None:
30         raise Error("%s: missing '%s' member" % (description, name))
31     return member
32
33 class DbSchema:
34     def __init__(self, name, comment, tables, idlPrefix, idlHeader):
35         self.name = name
36         self.comment = comment
37         self.tables = tables
38         self.idlPrefix = idlPrefix
39         self.idlHeader = idlHeader
40
41     @staticmethod
42     def fromJson(json):
43         name = mustGetMember(json, 'name', [unicode], 'database')
44         comment = getMember(json, 'comment', [unicode], 'database')
45         tablesJson = mustGetMember(json, 'tables', [dict], 'database')
46         tables = {}
47         for tableName, tableJson in tablesJson.iteritems():
48             tables[tableName] = TableSchema.fromJson(tableJson,
49                                                      "%s table" % tableName)
50         idlPrefix = mustGetMember(json, 'idlPrefix', [unicode], 'database')
51         idlHeader = mustGetMember(json, 'idlHeader', [unicode], 'database')
52         return DbSchema(name, comment, tables, idlPrefix, idlHeader)
53
54 class TableSchema:
55     def __init__(self, comment, columns):
56         self.comment = comment
57         self.columns = columns
58
59     @staticmethod
60     def fromJson(json, description):
61         comment = getMember(json, 'comment', [unicode], description)
62         columnsJson = mustGetMember(json, 'columns', [dict], description)
63         columns = {}
64         for name, json in columnsJson.iteritems():
65             columns[name] = ColumnSchema.fromJson(
66                 json, "column %s in %s" % (name, description))
67         return TableSchema(comment, columns)
68
69 class ColumnSchema:
70     def __init__(self, comment, type, persistent):
71         self.comment = comment
72         self.type = type
73         self.persistent = persistent
74
75     @staticmethod
76     def fromJson(json, description):
77         comment = getMember(json, 'comment', [unicode], description)
78         type = Type.fromJson(mustGetMember(json, 'type', [dict, unicode],
79                                            description),
80                              'type of %s' % description)
81         ephemeral = getMember(json, 'ephemeral', [bool], description)
82         persistent = ephemeral != True
83         return ColumnSchema(comment, type, persistent)
84
85 def escapeCString(src):
86     dst = ""
87     for c in src:
88         if c in "\\\"":
89             dst += "\\" + c
90         elif ord(c) < 32:
91             if c == '\n':
92                 dst += '\\n'
93             elif c == '\r':
94                 dst += '\\r'
95             elif c == '\a':
96                 dst += '\\a'
97             elif c == '\b':
98                 dst += '\\b'
99             elif c == '\f':
100                 dst += '\\f'
101             elif c == '\t':
102                 dst += '\\t'
103             elif c == '\v':
104                 dst += '\\v'
105             else:
106                 dst += '\\%03o' % ord(c)
107         else:
108             dst += c
109     return dst
110
111 class UUID:
112     x = "[0-9a-fA-f]"
113     uuidRE = re.compile("^(%s{8})-(%s{4})-(%s{4})-(%s{4})-(%s{4})(%s{8})$"
114                         % (x, x, x, x, x, x))
115
116     def __init__(self, value):
117         self.value = value
118
119     @staticmethod
120     def fromString(s):
121         if not uuidRE.match(s):
122             raise Error("%s is not a valid UUID" % s)
123         return UUID(s)
124
125     @staticmethod
126     def fromJson(json):
127         if UUID.isValidJson(json):
128             return UUID(json[1])
129         else:
130             raise Error("%s is not valid JSON for a UUID" % json)
131
132     @staticmethod
133     def isValidJson(json):
134         return len(json) == 2 and json[0] == "uuid" and uuidRE.match(json[1])
135             
136     def toJson(self):
137         return ["uuid", self.value]
138
139     def cInitUUID(self, var):
140         m = re.match(self.value)
141         return ["%s.parts[0] = 0x%s;" % (var, m.group(1)),
142                 "%s.parts[1] = 0x%s%s;" % (var, m.group(2), m.group(3)),
143                 "%s.parts[2] = 0x%s%s;" % (var, m.group(4), m.group(5)),
144                 "%s.parts[3] = 0x%s;" % (var, m.group(6))]
145
146 class Atom:
147     def __init__(self, type, value):
148         self.type = type
149         self.value = value
150
151     @staticmethod
152     def fromJson(type_, json):
153         if ((type_ == 'integer' and type(json) in [int, long])
154             or (type_ == 'real' and type(json) in [int, long, float])
155             or (type_ == 'boolean' and json in [True, False])
156             or (type_ == 'string' and type(json) in [str, unicode])):
157             return Atom(type_, json)
158         elif type_ == 'uuid':
159             return UUID.fromJson(json)
160         else:
161             raise Error("%s is not valid JSON for type %s" % (json, type_))
162
163     def toJson(self):
164         if self.type == 'uuid':
165             return self.value.toString()
166         else:
167             return self.value
168
169     def cInitAtom(self, var):
170         if self.type == 'integer':
171             return ['%s.integer = %d;' % (var, self.value)]
172         elif self.type == 'real':
173             return ['%s.real = %.15g;' % (var, self.value)]
174         elif self.type == 'boolean':
175             if self.value:
176                 return ['%s.boolean = true;']
177             else:
178                 return ['%s.boolean = false;']
179         elif self.type == 'string':
180             return ['%s.string = xstrdup("%s");'
181                     % (var, escapeCString(self.value))]
182         elif self.type == 'uuid':
183             return self.value.cInitUUID(var)        
184
185 class BaseType:
186     def __init__(self, type,
187                  enum=None,
188                  refTable=None,
189                  minInteger=None, maxInteger=None,
190                  minReal=None, maxReal=None,
191                  minLength=None, maxLength=None):
192         self.type = type
193         self.enum = enum
194         self.refTable = refTable
195         self.minInteger = minInteger
196         self.maxInteger = maxInteger
197         self.minReal = minReal
198         self.maxReal = maxReal
199         self.minLength = minLength
200         self.maxLength = maxLength
201
202     @staticmethod
203     def fromJson(json, description):
204         if type(json) == unicode:
205             return BaseType(json)
206         else:
207             atomicType = mustGetMember(json, 'type', [unicode], description)
208             enum = getMember(json, 'enum', [], description)
209             if enum:
210                 enumType = Type(atomicType, None, 0, 'unlimited')
211                 enum = Datum.fromJson(enumType, enum)
212             refTable = getMember(json, 'refTable', [unicode], description)
213             minInteger = getMember(json, 'minInteger', [int, long], description)
214             maxInteger = getMember(json, 'maxInteger', [int, long], description)
215             minReal = getMember(json, 'minReal', [int, long, float], description)
216             maxReal = getMember(json, 'maxReal', [int, long, float], description)
217             minLength = getMember(json, 'minLength', [int], description)
218             maxLength = getMember(json, 'minLength', [int], description)
219             return BaseType(atomicType, enum, refTable, minInteger, maxInteger, minReal, maxReal, minLength, maxLength)
220
221     def toEnglish(self):
222         if self.type == 'uuid' and self.refTable:
223             return self.refTable
224         else:
225             return self.type
226
227     def toCType(self, prefix):
228         if self.refTable:
229             return "struct %s%s *" % (prefix, self.refTable.lower())
230         else:
231             return {'integer': 'int64_t ',
232                     'real': 'double ',
233                     'uuid': 'struct uuid ',
234                     'boolean': 'bool ',
235                     'string': 'char *'}[self.type]
236
237     def copyCValue(self, dst, src):
238         args = {'dst': dst, 'src': src}
239         if self.refTable:
240             return ("%(dst)s = %(src)s->header_.uuid;") % args
241         elif self.type == 'string':
242             return "%(dst)s = xstrdup(%(src)s);" % args
243         else:
244             return "%(dst)s = %(src)s;" % args
245
246     def initCDefault(self, var, isOptional):
247         if self.refTable:
248             return "%s = NULL;" % var
249         elif self.type == 'string' and not isOptional:
250             return "%s = \"\";" % var
251         else:
252             return {'integer': '%s = 0;',
253                     'real': '%s = 0.0;',
254                     'uuid': 'uuid_zero(&%s);',
255                     'boolean': '%s = false;',
256                     'string': '%s = NULL;'}[self.type] % var
257
258     def cInitBaseType(self, indent, var):
259         stmts = []
260         stmts.append('ovsdb_base_type_init(&%s, OVSDB_TYPE_%s);' % (
261                 var, self.type.upper()),)
262         if self.enum:
263             stmts.append("%s.enum_ = xmalloc(sizeof *%s.enum_);"
264                          % (var, var))
265             stmts += self.enum.cInitDatum("%s.enum_" % var)
266         if self.type == 'integer':
267             if self.minInteger != None:
268                 stmts.append('%s.u.integer.min = %d;' % (var, self.minInteger))
269             if self.maxInteger != None:
270                 stmts.append('%s.u.integer.max = %d;' % (var, self.maxInteger))
271         elif self.type == 'real':
272             if self.minReal != None:
273                 stmts.append('%s.u.real.min = %d;' % (var, self.minReal))
274             if self.maxReal != None:
275                 stmts.append('%s.u.real.max = %d;' % (var, self.maxReal))
276         elif self.type == 'string':
277             if self.minLength != None:
278                 stmts.append('%s.u.string.minLen = %d;' % (var, self.minLength))            
279             if self.maxLength != None:
280                 stmts.append('%s.u.string.maxLen = %d;' % (var, self.maxLength))
281         elif self.type == 'uuid':
282             if self.refTable != None:
283                 stmts.append('%s.u.uuid.refTableName = "%s";' % (var, escapeCString(self.refTable)))
284         return '\n'.join([indent + stmt for stmt in stmts])
285
286 class Type:
287     def __init__(self, key, value=None, min=1, max=1):
288         self.key = key
289         self.value = value
290         self.min = min
291         self.max = max
292     
293     @staticmethod
294     def fromJson(json, description):
295         if type(json) == unicode:
296             return Type(BaseType(json))
297         else:
298             keyJson = mustGetMember(json, 'key', [dict, unicode], description)
299             key = BaseType.fromJson(keyJson, 'key in %s' % description)
300
301             valueJson = getMember(json, 'value', [dict, unicode], description)
302             if valueJson:
303                 value = BaseType.fromJson(valueJson,
304                                           'value in %s' % description)
305             else:
306                 value = None
307
308             min = getMember(json, 'min', [int], description, 1)
309             max = getMember(json, 'max', [int, unicode], description, 1)
310             return Type(key, value, min, max)
311
312     def isScalar(self):
313         return self.min == 1 and self.max == 1 and not self.value
314
315     def isOptional(self):
316         return self.min == 0 and self.max == 1
317
318     def isOptionalPointer(self):
319         return (self.min == 0 and self.max == 1 and not self.value
320                 and (self.key.type == 'string' or self.key.refTable))
321
322     def toEnglish(self):
323         keyName = self.key.toEnglish()
324         if self.value:
325             valueName = self.value.toEnglish()
326
327         if self.isScalar():
328             return keyName
329         elif self.isOptional():
330             if self.value:
331                 return "optional %s-%s pair" % (keyName, valueName)
332             else:
333                 return "optional %s" % keyName
334         else:
335             if self.max == "unlimited":
336                 if self.min:
337                     quantity = "%d or more " % self.min
338                 else:
339                     quantity = ""
340             elif self.min:
341                 quantity = "%d to %d " % (self.min, self.max)
342             else:
343                 quantity = "up to %d " % self.max
344
345             if self.value:
346                 return "map of %s%s-%s pairs" % (quantity, keyName, valueName)
347             else:
348                 return "set of %s%s" % (quantity, keyName)
349                 
350     def cDeclComment(self):
351         if self.min == 1 and self.max == 1 and self.key.type == "string":
352             return "\t/* Always nonnull. */"
353         else:
354             return ""
355
356     def cInitType(self, indent, var):
357         initKey = self.key.cInitBaseType(indent, "%s.key" % var)
358         if self.value:
359             initValue = self.value.cInitBaseType(indent, "%s.value" % var)
360         else:
361             initValue = ('%sovsdb_base_type_init(&%s.value, '
362                          'OVSDB_TYPE_VOID);' % (indent, var))
363         initMin = "%s%s.n_min = %s;" % (indent, var, self.min)
364         if self.max == "unlimited":
365             max = "UINT_MAX"
366         else:
367             max = self.max
368         initMax = "%s%s.n_max = %s;" % (indent, var, max)
369         return "\n".join((initKey, initValue, initMin, initMax))
370
371 class Datum:
372     def __init__(self, type, values):
373         self.type = type
374         self.values = values
375
376     @staticmethod
377     def fromJson(type_, json):
378         if not type_.value:
379             if len(json) == 2 and json[0] == "set":
380                 values = []
381                 for atomJson in json[1]:
382                     values += [Atom.fromJson(type_.key, atomJson)]
383             else:
384                 values = [Atom.fromJson(type_.key, json)]
385         else:
386             if len(json) != 2 or json[0] != "map":
387                 raise Error("%s is not valid JSON for a map" % json)
388             values = []
389             for pairJson in json[1]:
390                 values += [(Atom.fromJson(type_.key, pairJson[0]),
391                             Atom.fromJson(type_.value, pairJson[1]))]
392         return Datum(type_, values)
393
394     def cInitDatum(self, var):
395         if len(self.values) == 0:
396             return ["ovsdb_datum_init_empty(%s);" % var]
397
398         s = ["%s->n = %d;" % (var, len(self.values))]
399         s += ["%s->keys = xmalloc(%d * sizeof *%s->keys);"
400               % (var, len(self.values), var)]
401
402         for i in range(len(self.values)):
403             key = self.values[i]
404             if self.type.value:
405                 key = key[0]
406             s += key.cInitAtom("%s->keys[%d]" % (var, i))
407         
408         if self.type.value:
409             s += ["%s->values = xmalloc(%d * sizeof *%s->values);"
410                   % (var, len(self.values), var)]
411             for i in range(len(self.values)):
412                 value = self.values[i][1]
413                 s += key.cInitAtom("%s->values[%d]" % (var, i))
414         else:
415             s += ["%s->values = NULL;" % var]
416
417         if len(self.values) > 1:
418             s += ["ovsdb_datum_sort_assert(%s, OVSDB_TYPE_%s);"
419                   % (var, self.type.key.upper())]
420
421         return s
422
423 def parseSchema(filename):
424     return DbSchema.fromJson(json.load(open(filename, "r")))
425
426 def annotateSchema(schemaFile, annotationFile):
427     schemaJson = json.load(open(schemaFile, "r"))
428     execfile(annotationFile, globals(), {"s": schemaJson})
429     json.dump(schemaJson, sys.stdout)
430
431 def constify(cType, const):
432     if (const
433         and cType.endswith('*') and not cType.endswith('**')
434         and (cType.startswith('struct uuid') or cType.startswith('char'))):
435         return 'const %s' % cType
436     else:
437         return cType
438
439 def cMembers(prefix, columnName, column, const):
440     type = column.type
441     if type.min == 1 and type.max == 1:
442         singleton = True
443         pointer = ''
444     else:
445         singleton = False
446         if type.isOptionalPointer():
447             pointer = ''
448         else:
449             pointer = '*'
450
451     if type.value:
452         key = {'name': "key_%s" % columnName,
453                'type': constify(type.key.toCType(prefix) + pointer, const),
454                'comment': ''}
455         value = {'name': "value_%s" % columnName,
456                  'type': constify(type.value.toCType(prefix) + pointer, const),
457                  'comment': ''}
458         members = [key, value]
459     else:
460         m = {'name': columnName,
461              'type': constify(type.key.toCType(prefix) + pointer, const),
462              'comment': type.cDeclComment()}
463         members = [m]
464
465     if not singleton and not type.isOptionalPointer():
466         members.append({'name': 'n_%s' % columnName,
467                         'type': 'size_t ',
468                         'comment': ''})
469     return members
470
471 def printCIDLHeader(schemaFile):
472     schema = parseSchema(schemaFile)
473     prefix = schema.idlPrefix
474     print '''\
475 /* Generated automatically -- do not modify!    -*- buffer-read-only: t -*- */
476
477 #ifndef %(prefix)sIDL_HEADER
478 #define %(prefix)sIDL_HEADER 1
479
480 #include <stdbool.h>
481 #include <stddef.h>
482 #include <stdint.h>
483 #include "ovsdb-idl-provider.h"
484 #include "uuid.h"''' % {'prefix': prefix.upper()}
485
486     for tableName, table in sorted(schema.tables.iteritems()):
487         structName = "%s%s" % (prefix, tableName.lower())
488
489         print "\f"
490         print "/* %s table. */" % tableName
491         print "struct %s {" % structName
492         print "\tstruct ovsdb_idl_row header_;"
493         for columnName, column in sorted(table.columns.iteritems()):
494             print "\n\t/* %s column. */" % columnName
495             for member in cMembers(prefix, columnName, column, False):
496                 print "\t%(type)s%(name)s;%(comment)s" % member
497         print "};"
498
499         # Column indexes.
500         printEnum(["%s_COL_%s" % (structName.upper(), columnName.upper())
501                    for columnName in sorted(table.columns)]
502                   + ["%s_N_COLUMNS" % structName.upper()])
503
504         print
505         for columnName in table.columns:
506             print "#define %(s)s_col_%(c)s (%(s)s_columns[%(S)s_COL_%(C)s])" % {
507                 's': structName,
508                 'S': structName.upper(),
509                 'c': columnName,
510                 'C': columnName.upper()}
511
512         print "\nextern struct ovsdb_idl_column %s_columns[%s_N_COLUMNS];" % (structName, structName.upper())
513
514         print '''
515 const struct %(s)s *%(s)s_first(const struct ovsdb_idl *);
516 const struct %(s)s *%(s)s_next(const struct %(s)s *);
517 #define %(S)s_FOR_EACH(ROW, IDL) for ((ROW) = %(s)s_first(IDL); (ROW); (ROW) = %(s)s_next(ROW))
518
519 void %(s)s_delete(const struct %(s)s *);
520 struct %(s)s *%(s)s_insert(struct ovsdb_idl_txn *);
521 ''' % {'s': structName, 'S': structName.upper()}
522
523         for columnName, column in sorted(table.columns.iteritems()):
524             print 'void %(s)s_verify_%(c)s(const struct %(s)s *);' % {'s': structName, 'c': columnName}
525
526         print
527         for columnName, column in sorted(table.columns.iteritems()):
528
529             print 'void %(s)s_set_%(c)s(const struct %(s)s *,' % {'s': structName, 'c': columnName},
530             args = ['%(type)s%(name)s' % member for member
531                     in cMembers(prefix, columnName, column, True)]
532             print '%s);' % ', '.join(args)
533
534     # Table indexes.
535     printEnum(["%sTABLE_%s" % (prefix.upper(), tableName.upper()) for tableName in sorted(schema.tables)] + ["%sN_TABLES" % prefix.upper()])
536     print
537     for tableName in schema.tables:
538         print "#define %(p)stable_%(t)s (%(p)stable_classes[%(P)sTABLE_%(T)s])" % {
539             'p': prefix,
540             'P': prefix.upper(),
541             't': tableName.lower(),
542             'T': tableName.upper()}
543     print "\nextern struct ovsdb_idl_table_class %stable_classes[%sN_TABLES];" % (prefix, prefix.upper())
544
545     print "\nextern struct ovsdb_idl_class %sidl_class;" % prefix
546     print "\nvoid %sinit(void);" % prefix
547     print "\n#endif /* %(prefix)sIDL_HEADER */" % {'prefix': prefix.upper()}
548
549 def printEnum(members):
550     if len(members) == 0:
551         return
552
553     print "\nenum {";
554     for member in members[:-1]:
555         print "    %s," % member
556     print "    %s" % members[-1]
557     print "};"
558
559 def printCIDLSource(schemaFile):
560     schema = parseSchema(schemaFile)
561     prefix = schema.idlPrefix
562     print '''\
563 /* Generated automatically -- do not modify!    -*- buffer-read-only: t -*- */
564
565 #include <config.h>
566 #include %s
567 #include <assert.h>
568 #include <limits.h>
569 #include "ovsdb-data.h"
570 #include "ovsdb-error.h"
571
572 static bool inited;
573 ''' % schema.idlHeader
574
575     # Cast functions.
576     for tableName, table in sorted(schema.tables.iteritems()):
577         structName = "%s%s" % (prefix, tableName.lower())
578         print '''
579 static struct %(s)s *
580 %(s)s_cast(const struct ovsdb_idl_row *row)
581 {
582     return row ? CONTAINER_OF(row, struct %(s)s, header_) : NULL;
583 }\
584 ''' % {'s': structName}
585
586
587     for tableName, table in sorted(schema.tables.iteritems()):
588         structName = "%s%s" % (prefix, tableName.lower())
589         print "\f"
590         if table.comment != None:
591             print "/* %s table (%s). */" % (tableName, table.comment)
592         else:
593             print "/* %s table. */" % (tableName)
594
595         # Parse functions.
596         for columnName, column in sorted(table.columns.iteritems()):
597             print '''
598 static void
599 %(s)s_parse_%(c)s(struct ovsdb_idl_row *row_, const struct ovsdb_datum *datum)
600 {
601     struct %(s)s *row = %(s)s_cast(row_);''' % {'s': structName,
602                                                 'c': columnName}
603
604             type = column.type
605             if type.value:
606                 keyVar = "row->key_%s" % columnName
607                 valueVar = "row->value_%s" % columnName
608             else:
609                 keyVar = "row->%s" % columnName
610                 valueVar = None
611
612             if (type.min == 1 and type.max == 1) or type.isOptionalPointer():
613                 print
614                 print "    assert(inited);"
615                 print "    if (datum->n >= 1) {"
616                 if not type.key.refTable:
617                     print "        %s = datum->keys[0].%s;" % (keyVar, type.key.type)
618                 else:
619                     print "        %s = %s%s_cast(ovsdb_idl_get_row_arc(row_, &%stable_classes[%sTABLE_%s], &datum->keys[0].uuid));" % (keyVar, prefix, type.key.refTable.lower(), prefix, prefix.upper(), type.key.refTable.upper())
620
621                 if valueVar:
622                     if type.value.refTable:
623                         print "        %s = datum->values[0].%s;" % (valueVar, type.value.type)
624                     else:
625                         print "        %s = %s%s_cast(ovsdb_idl_get_row_arc(row_, &%stable_classes[%sTABLE_%s], &datum->values[0].uuid));" % (valueVar, prefix, type.value.refTable.lower(), prefix, prefix.upper(), type.value.refTable.upper())
626                 print "    } else {"
627                 print "        %s" % type.key.initCDefault(keyVar, type.min == 0)
628                 if valueVar:
629                     print "        %s" % type.value.initCDefault(valueVar, type.min == 0)
630                 print "    }"
631             else:
632                 if type.max != 'unlimited':
633                     print "    size_t n = MIN(%d, datum->n);" % type.max
634                     nMax = "n"
635                 else:
636                     nMax = "datum->n"
637                 print "    size_t i;"
638                 print
639                 print "    assert(inited);"
640                 print "    %s = NULL;" % keyVar
641                 if valueVar:
642                     print "    %s = NULL;" % valueVar
643                 print "    row->n_%s = 0;" % columnName
644                 print "    for (i = 0; i < %s; i++) {" % nMax
645                 refs = []
646                 if type.key.refTable:
647                     print "        struct %s%s *keyRow = %s%s_cast(ovsdb_idl_get_row_arc(row_, &%stable_classes[%sTABLE_%s], &datum->keys[i].uuid));" % (prefix, type.key.refTable.lower(), prefix, type.key.refTable.lower(), prefix, prefix.upper(), type.key.refTable.upper())
648                     keySrc = "keyRow"
649                     refs.append('keyRow')
650                 else:
651                     keySrc = "datum->keys[i].%s" % type.key.type
652                 if type.value and type.value.refTable:
653                     print "        struct %s%s *valueRow = %s%s_cast(ovsdb_idl_get_row_arc(row_, &%stable_classes[%sTABLE_%s], &datum->values[i].uuid));" % (prefix, type.value.refTable.lower(), prefix, type.value.refTable.lower(), prefix, prefix.upper(), type.value.refTable.upper())
654                     valueSrc = "valueRow"
655                     refs.append('valueRow')
656                 elif valueVar:
657                     valueSrc = "datum->values[i].%s" % type.value.type
658                 if refs:
659                     print "        if (%s) {" % ' && '.join(refs)
660                     indent = "            "
661                 else:
662                     indent = "        "
663                 print "%sif (!row->n_%s) {" % (indent, columnName)
664                 print "%s    %s = xmalloc(%s * sizeof *%s);" % (indent, keyVar, nMax, keyVar)
665                 if valueVar:
666                     print "%s    %s = xmalloc(%s * sizeof %s);" % (indent, valueVar, nMax, valueVar)
667                 print "%s}" % indent
668                 print "%s%s[row->n_%s] = %s;" % (indent, keyVar, columnName, keySrc)
669                 if valueVar:
670                     print "%s%s[row->n_%s] = %s;" % (indent, valueVar, columnName, valueSrc)
671                 print "%srow->n_%s++;" % (indent, columnName)
672                 if refs:
673                     print "        }"
674                 print "    }"
675             print "}"
676
677         # Unparse functions.
678         for columnName, column in sorted(table.columns.iteritems()):
679             type = column.type
680             if (type.min != 1 or type.max != 1) and not type.isOptionalPointer():
681                 print '''
682 static void
683 %(s)s_unparse_%(c)s(struct ovsdb_idl_row *row_)
684 {
685     struct %(s)s *row = %(s)s_cast(row_);
686
687     assert(inited);''' % {'s': structName, 'c': columnName}
688                 if type.value:
689                     keyVar = "row->key_%s" % columnName
690                     valueVar = "row->value_%s" % columnName
691                 else:
692                     keyVar = "row->%s" % columnName
693                     valueVar = None
694                 print "    free(%s);" % keyVar
695                 if valueVar:
696                     print "    free(%s);" % valueVar
697                 print '}'
698             else:
699                 print '''
700 static void
701 %(s)s_unparse_%(c)s(struct ovsdb_idl_row *row OVS_UNUSED)
702 {
703     /* Nothing to do. */
704 }''' % {'s': structName, 'c': columnName}
705  
706         # First, next functions.
707         print '''
708 const struct %(s)s *
709 %(s)s_first(const struct ovsdb_idl *idl)
710 {
711     return %(s)s_cast(ovsdb_idl_first_row(idl, &%(p)stable_classes[%(P)sTABLE_%(T)s]));
712 }
713
714 const struct %(s)s *
715 %(s)s_next(const struct %(s)s *row)
716 {
717     return %(s)s_cast(ovsdb_idl_next_row(&row->header_));
718 }''' % {'s': structName,
719         'p': prefix,
720         'P': prefix.upper(),
721         'T': tableName.upper()}
722
723         print '''
724 void
725 %(s)s_delete(const struct %(s)s *row)
726 {
727     ovsdb_idl_txn_delete(&row->header_);
728 }
729
730 struct %(s)s *
731 %(s)s_insert(struct ovsdb_idl_txn *txn)
732 {
733     return %(s)s_cast(ovsdb_idl_txn_insert(txn, &%(p)stable_classes[%(P)sTABLE_%(T)s]));
734 }
735 ''' % {'s': structName,
736        'p': prefix,
737        'P': prefix.upper(),
738        'T': tableName.upper()}
739
740         # Verify functions.
741         for columnName, column in sorted(table.columns.iteritems()):
742             print '''
743 void
744 %(s)s_verify_%(c)s(const struct %(s)s *row)
745 {
746     assert(inited);
747     ovsdb_idl_txn_verify(&row->header_, &%(s)s_columns[%(S)s_COL_%(C)s]);
748 }''' % {'s': structName,
749         'S': structName.upper(),
750         'c': columnName,
751         'C': columnName.upper()}
752
753         # Set functions.
754         for columnName, column in sorted(table.columns.iteritems()):
755             type = column.type
756             print '\nvoid'
757             members = cMembers(prefix, columnName, column, True)
758             keyVar = members[0]['name']
759             nVar = None
760             valueVar = None
761             if type.value:
762                 valueVar = members[1]['name']
763                 if len(members) > 2:
764                     nVar = members[2]['name']
765             else:
766                 if len(members) > 1:
767                     nVar = members[1]['name']
768             print '%(s)s_set_%(c)s(const struct %(s)s *row, %(args)s)' % \
769                 {'s': structName, 'c': columnName,
770                  'args': ', '.join(['%(type)s%(name)s' % m for m in members])}
771             print "{"
772             print "    struct ovsdb_datum datum;"
773             if type.min == 1 and type.max == 1:
774                 print
775                 print "    assert(inited);"
776                 print "    datum.n = 1;"
777                 print "    datum.keys = xmalloc(sizeof *datum.keys);"
778                 print "    " + type.key.copyCValue("datum.keys[0].%s" % type.key.type, keyVar)
779                 if type.value:
780                     print "    datum.values = xmalloc(sizeof *datum.values);"
781                     print "    "+ type.value.copyCValue("datum.values[0].%s" % type.value.type, valueVar)
782                 else:
783                     print "    datum.values = NULL;"
784             elif type.isOptionalPointer():
785                 print
786                 print "    assert(inited);"
787                 print "    if (%s) {" % keyVar
788                 print "        datum.n = 1;"
789                 print "        datum.keys = xmalloc(sizeof *datum.keys);"
790                 print "        " + type.key.copyCValue("datum.keys[0].%s" % type.key.type, keyVar)
791                 print "    } else {"
792                 print "        datum.n = 0;"
793                 print "        datum.keys = NULL;"
794                 print "    }"
795                 print "    datum.values = NULL;"
796             else:
797                 print "    size_t i;"
798                 print
799                 print "    assert(inited);"
800                 print "    datum.n = %s;" % nVar
801                 print "    datum.keys = xmalloc(%s * sizeof *datum.keys);" % nVar
802                 if type.value:
803                     print "    datum.values = xmalloc(%s * sizeof *datum.values);" % nVar
804                 else:
805                     print "    datum.values = NULL;"
806                 print "    for (i = 0; i < %s; i++) {" % nVar
807                 print "        " + type.key.copyCValue("datum.keys[i].%s" % type.key.type, "%s[i]" % keyVar)
808                 if type.value:
809                     print "        " + type.value.copyCValue("datum.values[i].%s" % type.value.type, "%s[i]" % valueVar)
810                 print "    }"
811             print "    ovsdb_idl_txn_write(&row->header_, &%(s)s_columns[%(S)s_COL_%(C)s], &datum);" \
812                 % {'s': structName,
813                    'S': structName.upper(),
814                    'C': columnName.upper()}
815             print "}"
816
817         # Table columns.
818         print "\nstruct ovsdb_idl_column %s_columns[%s_N_COLUMNS];" % (
819             structName, structName.upper())
820         print """
821 static void\n%s_columns_init(void)
822 {
823     struct ovsdb_idl_column *c;\
824 """ % structName
825         for columnName, column in sorted(table.columns.iteritems()):
826             cs = "%s_col_%s" % (structName, columnName)
827             d = {'cs': cs, 'c': columnName, 's': structName}
828             print
829             print "    /* Initialize %(cs)s. */" % d
830             print "    c = &%(cs)s;" % d
831             print "    c->name = \"%(c)s\";" % d
832             print column.type.cInitType("    ", "c->type")
833             print "    c->parse = %(s)s_parse_%(c)s;" % d
834             print "    c->unparse = %(s)s_unparse_%(c)s;" % d
835         print "}"
836
837     # Table classes.
838     print "\f"
839     print "struct ovsdb_idl_table_class %stable_classes[%sN_TABLES] = {" % (prefix, prefix.upper())
840     for tableName, table in sorted(schema.tables.iteritems()):
841         structName = "%s%s" % (prefix, tableName.lower())
842         print "    {\"%s\"," % tableName
843         print "     %s_columns, ARRAY_SIZE(%s_columns)," % (
844             structName, structName)
845         print "     sizeof(struct %s)}," % structName
846     print "};"
847
848     # IDL class.
849     print "\nstruct ovsdb_idl_class %sidl_class = {" % prefix
850     print "    \"%s\", %stable_classes, ARRAY_SIZE(%stable_classes)" % (
851         schema.name, prefix, prefix)
852     print "};"
853
854     # global init function
855     print """
856 void
857 %sinit(void)
858 {
859     if (inited) {
860         return;
861     }
862     inited = true;
863 """ % prefix
864     for tableName, table in sorted(schema.tables.iteritems()):
865         structName = "%s%s" % (prefix, tableName.lower())
866         print "    %s_columns_init();" % structName
867     print "}"
868
869 def ovsdb_escape(string):
870     def escape(match):
871         c = match.group(0)
872         if c == '\0':
873             raise Error("strings may not contain null bytes")
874         elif c == '\\':
875             return '\\\\'
876         elif c == '\n':
877             return '\\n'
878         elif c == '\r':
879             return '\\r'
880         elif c == '\t':
881             return '\\t'
882         elif c == '\b':
883             return '\\b'
884         elif c == '\a':
885             return '\\a'
886         else:
887             return '\\x%02x' % ord(c)
888     return re.sub(r'["\\\000-\037]', escape, string)
889
890 def printDoc(schemaFile):
891     schema = parseSchema(schemaFile)
892     print schema.name
893     if schema.comment:
894         print schema.comment
895
896     for tableName, table in sorted(schema.tables.iteritems()):
897         title = "%s table" % tableName
898         print
899         print title
900         print '-' * len(title)
901         if table.comment:
902             print table.comment
903
904         for columnName, column in sorted(table.columns.iteritems()):
905             print
906             print "%s (%s)" % (columnName, column.type.toEnglish())
907             if column.comment:
908                 print "\t%s" % column.comment
909
910 def usage():
911     print """\
912 %(argv0)s: ovsdb schema compiler
913 usage: %(argv0)s [OPTIONS] COMMAND ARG...
914
915 The following commands are supported:
916   annotate SCHEMA ANNOTATIONS print SCHEMA combined with ANNOTATIONS
917   c-idl-header IDL            print C header file for IDL
918   c-idl-source IDL            print C source file for IDL implementation
919   doc IDL                     print schema documentation
920
921 The following options are also available:
922   -h, --help                  display this help message
923   -V, --version               display version information\
924 """ % {'argv0': argv0}
925     sys.exit(0)
926
927 if __name__ == "__main__":
928     try:
929         try:
930             options, args = getopt.gnu_getopt(sys.argv[1:], 'C:hV',
931                                               ['directory',
932                                                'help',
933                                                'version'])
934         except getopt.GetoptError, geo:
935             sys.stderr.write("%s: %s\n" % (argv0, geo.msg))
936             sys.exit(1)
937             
938         for key, value in options:
939             if key in ['-h', '--help']:
940                 usage()
941             elif key in ['-V', '--version']:
942                 print "ovsdb-idlc (Open vSwitch) @VERSION@"
943             elif key in ['-C', '--directory']:
944                 os.chdir(value)
945             else:
946                 sys.exit(0)
947             
948         optKeys = [key for key, value in options]
949
950         if not args:
951             sys.stderr.write("%s: missing command argument "
952                              "(use --help for help)\n" % argv0)
953             sys.exit(1)
954
955         commands = {"annotate": (annotateSchema, 2),
956                     "c-idl-header": (printCIDLHeader, 1),
957                     "c-idl-source": (printCIDLSource, 1),
958                     "doc": (printDoc, 1)}
959
960         if not args[0] in commands:
961             sys.stderr.write("%s: unknown command \"%s\" "
962                              "(use --help for help)\n" % (argv0, args[0]))
963             sys.exit(1)
964
965         func, n_args = commands[args[0]]
966         if len(args) - 1 != n_args:
967             sys.stderr.write("%s: \"%s\" requires %d arguments but %d "
968                              "provided\n"
969                              % (argv0, args[0], n_args, len(args) - 1))
970             sys.exit(1)
971
972         func(*args[1:])
973     except Error, e:
974         sys.stderr.write("%s: %s\n" % (argv0, e.msg))
975         sys.exit(1)
976
977 # Local variables:
978 # mode: python
979 # End: