ovsdb-idl: Export ovsdb_idl_txn_delete() and ovsdb_idl_txn_insert().
[cascardo/ovs.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 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     def toJson(self):
55         d = {"name": self.name,
56              "tables": {}}
57         for name, table in self.tables.iteritems():
58             d["tables"][name] = table.toJson()
59         if self.comment != None:
60             d["comment"] = self.comment
61         return d
62
63 class TableSchema:
64     def __init__(self, comment, columns):
65         self.comment = comment
66         self.columns = columns
67
68     @staticmethod
69     def fromJson(json, description):
70         comment = getMember(json, 'comment', [unicode], description)
71         columnsJson = mustGetMember(json, 'columns', [dict], description)
72         columns = {}
73         for name, json in columnsJson.iteritems():
74             columns[name] = ColumnSchema.fromJson(
75                 json, "column %s in %s" % (name, description))
76         return TableSchema(comment, columns)
77
78     def toJson(self):
79         d = {"columns": {}}
80         for name, column in self.columns.iteritems():
81             d["columns"][name] = column.toJson()
82         if self.comment != None:
83             d["comment"] = self.comment
84         return d
85
86 class ColumnSchema:
87     def __init__(self, comment, type, persistent):
88         self.comment = comment
89         self.type = type
90         self.persistent = persistent
91
92     @staticmethod
93     def fromJson(json, description):
94         comment = getMember(json, 'comment', [unicode], description)
95         type = Type.fromJson(mustGetMember(json, 'type', [dict, unicode],
96                                            description),
97                              'type of %s' % description)
98         ephemeral = getMember(json, 'ephemeral', [bool], description)
99         persistent = ephemeral != True
100         return ColumnSchema(comment, type, persistent)
101
102     def toJson(self):
103         d = {"type": self.type.toJson()}
104         if self.persistent == False:
105             d["ephemeral"] = True
106         if self.comment != None:
107             d["comment"] = self.comment
108         return d
109
110 class Type:
111     def __init__(self, key, keyRefTable=None, value=None, valueRefTable=None,
112                  min=1, max=1):
113         self.key = key
114         self.keyRefTable = keyRefTable
115         self.value = value
116         self.valueRefTable = valueRefTable
117         self.min = min
118         self.max = max
119     
120     @staticmethod
121     def fromJson(json, description):
122         if type(json) == unicode:
123             return Type(json)
124         else:
125             key = mustGetMember(json, 'key', [unicode], description)
126             keyRefTable = getMember(json, 'keyRefTable', [unicode], description)
127             value = getMember(json, 'value', [unicode], description)
128             valueRefTable = getMember(json, 'valueRefTable', [unicode], description)
129             min = getMember(json, 'min', [int], description, 1)
130             max = getMember(json, 'max', [int, unicode], description, 1)
131             return Type(key, keyRefTable, value, valueRefTable, min, max)
132
133     def toJson(self):
134         if self.value == None and self.min == 1 and self.max == 1:
135             return self.key
136         else:
137             d = {"key": self.key}
138             if self.value != None:
139                 d["value"] = self.value
140             if self.min != 1:
141                 d["min"] = self.min
142             if self.max != 1:
143                 d["max"] = self.max
144             return d
145
146     def isScalar(self):
147         return self.min == 1 and self.max == 1 and not self.value
148
149     def isOptional(self):
150         return self.min == 0 and self.max == 1
151
152     def toEnglish(self):
153         keyName = atomicTypeToEnglish(self.key, self.keyRefTable)
154         if self.value:
155             valueName = atomicTypeToEnglish(self.value, self.valueRefTable)
156
157         if self.isScalar():
158             return atomicTypeToEnglish(self.key, self.keyRefTable)
159         elif self.isOptional():
160             if self.value:
161                 return "optional %s-%s pair" % (keyName, valueName)
162             else:
163                 return "optional %s" % keyName
164         else:
165             if self.max == "unlimited":
166                 if self.min:
167                     quantity = "%d or more " % self.min
168                 else:
169                     quantity = ""
170             elif self.min:
171                 quantity = "%d to %d " % (self.min, self.max)
172             else:
173                 quantity = "up to %d " % self.max
174
175             if self.value:
176                 return "map of %s%s-%s pairs" % (quantity, keyName, valueName)
177             else:
178                 return "set of %s%s" % (quantity, keyName)
179                 
180
181 def atomicTypeToEnglish(base, refTable):
182     if base == 'uuid' and refTable:
183         return refTable
184     else:
185         return base
186
187 def parseSchema(filename):
188     return DbSchema.fromJson(json.load(open(filename, "r")))
189
190 def annotateSchema(schemaFile, annotationFile):
191     schemaJson = json.load(open(schemaFile, "r"))
192     execfile(annotationFile, globals(), {"s": schemaJson})
193     json.dump(schemaJson, sys.stdout)
194
195 def cBaseType(prefix, type, refTable=None):
196     if type == 'uuid' and refTable:
197         return "struct %s%s *" % (prefix, refTable.lower())
198     else:
199         return {'integer': 'int64_t ',
200                 'real': 'double ',
201                 'uuid': 'struct uuid ',
202                 'boolean': 'bool ',
203                 'string': 'char *'}[type]
204
205 def cCopyType(indent, dst, src, type, refTable=None):
206     args = {'indent': indent,
207             'dst': dst,
208             'src': src}
209     if type == 'uuid' and refTable:
210         return ("%(indent)s%(dst)s = %(src)s->header_.uuid;") % args
211     elif type == 'string':
212         return "%(indent)s%(dst)s = xstrdup(%(src)s);" % args
213     else:
214         return "%(indent)s%(dst)s = %(src)s;" % args
215
216 def typeIsOptionalPointer(type):
217     return (type.min == 0 and type.max == 1 and not type.value
218             and (type.key == 'string'
219                  or (type.key == 'uuid' and type.keyRefTable)))
220
221 def cDeclComment(type):
222     if type.min == 1 and type.max == 1 and type.key == "string":
223         return "\t/* Always nonnull. */"
224     else:
225         return ""
226
227 def cInitDefault(var, type, refTable, isOptional):
228     if type == 'uuid' and refTable:
229         return "%s = NULL;" % var
230     elif type == 'string' and not isOptional:
231         return "%s = \"\";" % var
232     else:
233         return {'integer': '%s = 0;',
234                 'real': '%s = 0.0;',
235                 'uuid': 'uuid_zero(&%s);',
236                 'boolean': '%s = false;',
237                 'string': '%s = NULL;'}[type] % var
238
239 def constify(cType, const):
240     if (const
241         and cType.endswith('*') and not cType.endswith('**')
242         and (cType.startswith('struct uuid') or cType.startswith('char'))):
243         return 'const %s' % cType
244     else:
245         return cType
246
247 def cMembers(prefix, columnName, column, const):
248     type = column.type
249     if type.min == 1 and type.max == 1:
250         singleton = True
251         pointer = ''
252     else:
253         singleton = False
254         if typeIsOptionalPointer(type):
255             pointer = ''
256         else:
257             pointer = '*'
258
259     if type.value:
260         key = {'name': "key_%s" % columnName,
261                'type': constify(cBaseType(prefix, type.key, type.keyRefTable) + pointer, const),
262                'comment': ''}
263         value = {'name': "value_%s" % columnName,
264                  'type': constify(cBaseType(prefix, type.value, type.valueRefTable) + pointer, const),
265                  'comment': ''}
266         members = [key, value]
267     else:
268         m = {'name': columnName,
269              'type': constify(cBaseType(prefix, type.key, type.keyRefTable) + pointer, const),
270              'comment': cDeclComment(type)}
271         members = [m]
272
273     if not singleton and not typeIsOptionalPointer(type):
274         members.append({'name': 'n_%s' % columnName,
275                         'type': 'size_t ',
276                         'comment': ''})
277     return members
278
279 def printCIDLHeader(schemaFile):
280     schema = parseSchema(schemaFile)
281     prefix = schema.idlPrefix
282     print '''\
283 /* Generated automatically -- do not modify!    -*- buffer-read-only: t -*- */
284
285 #ifndef %(prefix)sIDL_HEADER
286 #define %(prefix)sIDL_HEADER 1
287
288 #include <stdbool.h>
289 #include <stddef.h>
290 #include <stdint.h>
291 #include "ovsdb-idl-provider.h"
292 #include "uuid.h"''' % {'prefix': prefix.upper()}
293
294     for tableName, table in schema.tables.iteritems():
295         structName = "%s%s" % (prefix, tableName.lower())
296
297         print "\f"
298         print "/* %s table. */" % tableName
299         print "struct %s {" % structName
300         print "\tstruct ovsdb_idl_row header_;"
301         for columnName, column in table.columns.iteritems():
302             print "\n\t/* %s column. */" % columnName
303             for member in cMembers(prefix, columnName, column, False):
304                 print "\t%(type)s%(name)s;%(comment)s" % member
305         print "};"
306
307         # Column indexes.
308         printEnum(["%s_COL_%s" % (structName.upper(), columnName.upper())
309                    for columnName in table.columns]
310                   + ["%s_N_COLUMNS" % structName.upper()])
311
312         print
313         for columnName in table.columns:
314             print "#define %(s)s_col_%(c)s (%(s)s_columns[%(S)s_COL_%(C)s])" % {
315                 's': structName,
316                 'S': structName.upper(),
317                 'c': columnName,
318                 'C': columnName.upper()}
319
320         print "\nextern struct ovsdb_idl_column %s_columns[%s_N_COLUMNS];" % (structName, structName.upper())
321
322         print '''
323 const struct %(s)s *%(s)s_first(const struct ovsdb_idl *);
324 const struct %(s)s *%(s)s_next(const struct %(s)s *);
325 #define %(S)s_FOR_EACH(ROW, IDL) for ((ROW) = %(s)s_first(IDL); (ROW); (ROW) = %(s)s_next(ROW))
326
327 void %(s)s_delete(const struct %(s)s *);
328 struct %(s)s *%(s)s_insert(struct ovsdb_idl_txn *);
329 ''' % {'s': structName, 'S': structName.upper()}
330
331         for columnName, column in table.columns.iteritems():
332             print 'void %(s)s_verify_%(c)s(const struct %(s)s *);' % {'s': structName, 'c': columnName}
333
334         print
335         for columnName, column in table.columns.iteritems():
336
337             print 'void %(s)s_set_%(c)s(const struct %(s)s *,' % {'s': structName, 'c': columnName},
338             args = ['%(type)s%(name)s' % member for member
339                     in cMembers(prefix, columnName, column, True)]
340             print '%s);' % ', '.join(args)
341
342     # Table indexes.
343     printEnum(["%sTABLE_%s" % (prefix.upper(), tableName.upper()) for tableName in schema.tables] + ["%sN_TABLES" % prefix.upper()])
344     print
345     for tableName in schema.tables:
346         print "#define %(p)stable_%(t)s (%(p)stable_classes[%(P)sTABLE_%(T)s])" % {
347             'p': prefix,
348             'P': prefix.upper(),
349             't': tableName.lower(),
350             'T': tableName.upper()}
351     print "\nextern struct ovsdb_idl_table_class %stable_classes[%sN_TABLES];" % (prefix, prefix.upper())
352
353     print "\nextern struct ovsdb_idl_class %sidl_class;" % prefix
354     print "\n#endif /* %(prefix)sIDL_HEADER */" % {'prefix': prefix.upper()}
355
356 def printEnum(members):
357     if len(members) == 0:
358         return
359
360     print "\nenum {";
361     for member in members[:-1]:
362         print "    %s," % member
363     print "    %s" % members[-1]
364     print "};"
365
366 def printCIDLSource(schemaFile):
367     schema = parseSchema(schemaFile)
368     prefix = schema.idlPrefix
369     print '''\
370 /* Generated automatically -- do not modify!    -*- buffer-read-only: t -*- */
371
372 #include <config.h>
373 #include %s
374 #include <limits.h>
375 #include "ovsdb-data.h"''' % schema.idlHeader
376
377     # Cast functions.
378     for tableName, table in schema.tables.iteritems():
379         structName = "%s%s" % (prefix, tableName.lower())
380         print '''
381 static struct %(s)s *
382 %(s)s_cast(const struct ovsdb_idl_row *row)
383 {
384     return row ? CONTAINER_OF(row, struct %(s)s, header_) : NULL;
385 }\
386 ''' % {'s': structName}
387
388
389     for tableName, table in schema.tables.iteritems():
390         structName = "%s%s" % (prefix, tableName.lower())
391         print "\f"
392         if table.comment != None:
393             print "/* %s table (%s). */" % (tableName, table.comment)
394         else:
395             print "/* %s table. */" % (tableName)
396
397         # Parse functions.
398         for columnName, column in table.columns.iteritems():
399             print '''
400 static void
401 %(s)s_parse_%(c)s(struct ovsdb_idl_row *row_, const struct ovsdb_datum *datum)
402 {
403     struct %(s)s *row = %(s)s_cast(row_);''' % {'s': structName,
404                                                 'c': columnName}
405
406             type = column.type
407             refKey = type.key == "uuid" and type.keyRefTable
408             refValue = type.value == "uuid" and type.valueRefTable
409             if type.value:
410                 keyVar = "row->key_%s" % columnName
411                 valueVar = "row->value_%s" % columnName
412             else:
413                 keyVar = "row->%s" % columnName
414                 valueVar = None
415
416             if ((type.min == 1 and type.max == 1) or
417                 typeIsOptionalPointer(type)):
418                 print
419                 print "    if (datum->n >= 1) {"
420                 if not refKey:
421                     print "        %s = datum->keys[0].%s;" % (keyVar, type.key)
422                 else:
423                     print "        %s = %s%s_cast(ovsdb_idl_get_row_arc(row_, &%stable_classes[%sTABLE_%s], &datum->keys[0].uuid));" % (keyVar, prefix, type.keyRefTable.lower(), prefix, prefix.upper(), type.keyRefTable.upper())
424
425                 if valueVar:
426                     if refValue:
427                         print "        %s = datum->values[0].%s;" % (valueVar, type.value)
428                     else:
429                         print "        %s = %s%s_cast(ovsdb_idl_get_row_arc(row_, &%stable_classes[%sTABLE_%s], &datum->values[0].uuid));" % (valueVar, prefix, type.valueRefTable.lower(), prefix, prefix.upper(), type.valueRefTable.upper())
430                 print "    } else {"
431                 print "        %s" % cInitDefault(keyVar, type.key, type.keyRefTable, type.min == 0)
432                 if valueVar:
433                     print "        %s" % cInitDefault(valueVar, type.value, type.valueRefTable, type.min == 0)
434                 print "    }"
435             else:
436                 if type.max != 'unlimited':
437                     print "    size_t n = MIN(%d, datum->n);" % type.max
438                     nMax = "n"
439                 else:
440                     nMax = "datum->n"
441                 print "    size_t i;"
442                 print
443                 print "    %s = NULL;" % keyVar
444                 if valueVar:
445                     print "    %s = NULL;" % valueVar
446                 print "    row->n_%s = 0;" % columnName
447                 print "    for (i = 0; i < %s; i++) {" % nMax
448                 refs = []
449                 if refKey:
450                     print "        struct %s%s *keyRow = %s%s_cast(ovsdb_idl_get_row_arc(row_, &%stable_classes[%sTABLE_%s], &datum->keys[i].uuid));" % (prefix, type.keyRefTable.lower(), prefix, type.keyRefTable.lower(), prefix, prefix.upper(), type.keyRefTable.upper())
451                     keySrc = "keyRow"
452                     refs.append('keyRow')
453                 else:
454                     keySrc = "datum->keys[i].%s" % type.key
455                 if refValue:
456                     print "        struct %s%s *valueRow = %s%s_cast(ovsdb_idl_get_row_arc(row_, &%stable_classes[%sTABLE_%s], &datum->values[i].uuid));" % (prefix, type.valueRefTable.lower(), prefix, type.valueRefTable.lower(), prefix, prefix.upper(), type.valueRefTable.upper())
457                     valueSrc = "valueRow"
458                     refs.append('valueRow')
459                 elif valueVar:
460                     valueSrc = "datum->values[i].%s" % type.value
461                 if refs:
462                     print "        if (%s) {" % ' && '.join(refs)
463                     indent = "            "
464                 else:
465                     indent = "        "
466                 print "%sif (!row->n_%s) {" % (indent, columnName)
467                 print "%s    %s = xmalloc(%s * sizeof *%s);" % (indent, keyVar, nMax, keyVar)
468                 if valueVar:
469                     print "%s    %s = xmalloc(%s * sizeof %s);" % (indent, valueVar, nMax, valueVar)
470                 print "%s}" % indent
471                 print "%s%s[row->n_%s] = %s;" % (indent, keyVar, columnName, keySrc)
472                 if valueVar:
473                     print "%s%s[row->n_%s] = %s;" % (indent, valueVar, columnName, valueSrc)
474                 print "%srow->n_%s++;" % (indent, columnName)
475                 if refs:
476                     print "        }"
477                 print "    }"
478             print "}"
479
480         # Unparse functions.
481         for columnName, column in table.columns.iteritems():
482             type = column.type
483             if (type.min != 1 or type.max != 1) and not typeIsOptionalPointer(type):
484                 print '''
485 static void
486 %(s)s_unparse_%(c)s(struct ovsdb_idl_row *row_)
487 {
488     struct %(s)s *row = %(s)s_cast(row_);
489 ''' % {'s': structName, 'c': columnName}
490                 if type.value:
491                     keyVar = "row->key_%s" % columnName
492                     valueVar = "row->value_%s" % columnName
493                 else:
494                     keyVar = "row->%s" % columnName
495                     valueVar = None
496                 print "    free(%s);" % keyVar
497                 if valueVar:
498                     print "    free(%s);" % valueVar
499                 print '}'
500             else:
501                 print '''
502 static void
503 %(s)s_unparse_%(c)s(struct ovsdb_idl_row *row UNUSED)
504 {
505     /* Nothing to do. */
506 }''' % {'s': structName, 'c': columnName}
507  
508         # First, next functions.
509         print '''
510 const struct %(s)s *
511 %(s)s_first(const struct ovsdb_idl *idl)
512 {
513     return %(s)s_cast(ovsdb_idl_first_row(idl, &%(p)stable_classes[%(P)sTABLE_%(T)s]));
514 }
515
516 const struct %(s)s *
517 %(s)s_next(const struct %(s)s *row)
518 {
519     return %(s)s_cast(ovsdb_idl_next_row(&row->header_));
520 }''' % {'s': structName,
521         'p': prefix,
522         'P': prefix.upper(),
523         'T': tableName.upper()}
524
525         print '''
526 void
527 %(s)s_delete(const struct %(s)s *row)
528 {
529     ovsdb_idl_txn_delete(&row->header_);
530 }
531
532 struct %(s)s *
533 %(s)s_insert(struct ovsdb_idl_txn *txn)
534 {
535     return %(s)s_cast(ovsdb_idl_txn_insert(txn, &%(p)stable_classes[%(P)sTABLE_%(T)s]));
536 }
537 ''' % {'s': structName,
538        'p': prefix,
539        'P': prefix.upper(),
540        'T': tableName.upper()}
541
542         # Verify functions.
543         for columnName, column in table.columns.iteritems():
544             print '''
545 void
546 %(s)s_verify_%(c)s(const struct %(s)s *row)
547 {
548     ovsdb_idl_txn_verify(&row->header_, &%(s)s_columns[%(S)s_COL_%(C)s]);
549 }''' % {'s': structName,
550         'S': structName.upper(),
551         'c': columnName,
552         'C': columnName.upper()}
553
554         # Set functions.
555         for columnName, column in table.columns.iteritems():
556             type = column.type
557             print '\nvoid'
558             members = cMembers(prefix, columnName, column, True)
559             keyVar = members[0]['name']
560             nVar = None
561             valueVar = None
562             if type.value:
563                 valueVar = members[1]['name']
564                 if len(members) > 2:
565                     nVar = members[2]['name']
566             else:
567                 if len(members) > 1:
568                     nVar = members[1]['name']
569             print '%(s)s_set_%(c)s(const struct %(s)s *row, %(args)s)' % \
570                 {'s': structName, 'c': columnName,
571                  'args': ', '.join(['%(type)s%(name)s' % m for m in members])}
572             print "{"
573             print "    struct ovsdb_datum datum;"
574             if type.min == 1 and type.max == 1:
575                 print
576                 print "    datum.n = 1;"
577                 print "    datum.keys = xmalloc(sizeof *datum.keys);"
578                 print cCopyType("    ", "datum.keys[0].%s" % type.key, keyVar, type.key, type.keyRefTable)
579                 if type.value:
580                     print "    datum.values = xmalloc(sizeof *datum.values);"
581                     print cCopyType("    ", "datum.values[0].%s" % type.value, valueVar, type.value, type.valueRefTable)
582                 else:
583                     print "    datum.values = NULL;"
584             elif typeIsOptionalPointer(type):
585                 print
586                 print "    if (%s) {" % keyVar
587                 print "        datum.n = 1;"
588                 print "        datum.keys = xmalloc(sizeof *datum.keys);"
589                 print cCopyType("        ", "datum.keys[0].%s" % type.key, keyVar, type.key, type.keyRefTable)
590                 print "    } else {"
591                 print "        datum.n = 0;"
592                 print "        datum.keys = NULL;"
593                 print "    }"
594                 print "    datum.values = NULL;"
595             else:
596                 print "    size_t i;"
597                 print
598                 print "    datum.n = %s;" % nVar
599                 print "    datum.keys = xmalloc(%s * sizeof *datum.keys);" % nVar
600                 if type.value:
601                     print "    datum.values = xmalloc(%s * sizeof *datum.values);" % nVar
602                 else:
603                     print "    datum.values = NULL;"
604                 print "    for (i = 0; i < %s; i++) {" % nVar
605                 print cCopyType("        ", "datum.keys[i].%s" % type.key, "%s[i]" % keyVar, type.key, type.keyRefTable)
606                 if type.value:
607                     print cCopyType("        ", "datum.values[i].%s" % type.value, "%s[i]" % valueVar, type.value, type.valueRefTable)
608                 print "    }"
609             print "    ovsdb_idl_txn_write(&row->header_, &%(s)s_columns[%(S)s_COL_%(C)s], &datum);" \
610                 % {'s': structName,
611                    'S': structName.upper(),
612                    'C': columnName.upper()}
613             print "}"
614
615         # Table columns.
616         print "\nstruct ovsdb_idl_column %s_columns[%s_N_COLUMNS] = {" % (
617             structName, structName.upper())
618         for columnName, column in table.columns.iteritems():
619             type = column.type
620             
621             if type.value:
622                 valueTypeName = type.value.upper()
623             else:
624                 valueTypeName = "VOID"
625             if type.max == "unlimited":
626                 max = "UINT_MAX"
627             else:
628                 max = type.max
629             print """\
630     {"%(c)s",
631      {OVSDB_TYPE_%(kt)s, OVSDB_TYPE_%(vt)s, %(min)s, %(max)s},
632      %(s)s_parse_%(c)s,
633      %(s)s_unparse_%(c)s},""" % {'c': columnName,
634                                  's': structName,
635                                  'kt': type.key.upper(),
636                                  'vt': valueTypeName,
637                                  'min': type.min,
638                                  'max': max}
639         print "};"
640
641     # Table classes.
642     print "\f"
643     print "struct ovsdb_idl_table_class %stable_classes[%sN_TABLES] = {" % (prefix, prefix.upper())
644     for tableName, table in schema.tables.iteritems():
645         structName = "%s%s" % (prefix, tableName.lower())
646         print "    {\"%s\"," % tableName
647         print "     %s_columns, ARRAY_SIZE(%s_columns)," % (
648             structName, structName)
649         print "     sizeof(struct %s)}," % structName
650     print "};"
651
652     # IDL class.
653     print "\nstruct ovsdb_idl_class %sidl_class = {" % prefix
654     print "    %stable_classes, ARRAY_SIZE(%stable_classes)" % (prefix, prefix)
655     print "};"
656
657 def ovsdb_escape(string):
658     def escape(match):
659         c = match.group(0)
660         if c == '\0':
661             raise Error("strings may not contain null bytes")
662         elif c == '\\':
663             return '\\\\'
664         elif c == '\n':
665             return '\\n'
666         elif c == '\r':
667             return '\\r'
668         elif c == '\t':
669             return '\\t'
670         elif c == '\b':
671             return '\\b'
672         elif c == '\a':
673             return '\\a'
674         else:
675             return '\\x%02x' % ord(c)
676     return re.sub(r'["\\\000-\037]', escape, string)
677
678 def printDoc(schemaFile):
679     schema = parseSchema(schemaFile)
680     print schema.name
681     if schema.comment:
682         print schema.comment
683
684     for tableName, table in sorted(schema.tables.iteritems()):
685         title = "%s table" % tableName
686         print
687         print title
688         print '-' * len(title)
689         if table.comment:
690             print table.comment
691
692         for columnName, column in sorted(table.columns.iteritems()):
693             print
694             print "%s (%s)" % (columnName, column.type.toEnglish())
695             if column.comment:
696                 print "\t%s" % column.comment
697
698 def usage():
699     print """\
700 %(argv0)s: ovsdb schema compiler
701 usage: %(argv0)s [OPTIONS] COMMAND ARG...
702
703 The following commands are supported:
704   annotate SCHEMA ANNOTATIONS print SCHEMA combined with ANNOTATIONS
705   c-idl-header IDL            print C header file for IDL
706   c-idl-source IDL            print C source file for IDL implementation
707   doc IDL                     print schema documentation
708
709 The following options are also available:
710   -h, --help                  display this help message
711   -V, --version               display version information\
712 """ % {'argv0': argv0}
713     sys.exit(0)
714
715 if __name__ == "__main__":
716     try:
717         try:
718             options, args = getopt.gnu_getopt(sys.argv[1:], 'C:hV',
719                                               ['directory',
720                                                'help',
721                                                'version'])
722         except getopt.GetoptError, geo:
723             sys.stderr.write("%s: %s\n" % (argv0, geo.msg))
724             sys.exit(1)
725             
726         for key, value in options:
727             if key in ['-h', '--help']:
728                 usage()
729             elif key in ['-V', '--version']:
730                 print "ovsdb-idlc (Open vSwitch) @VERSION@"
731             elif key in ['-C', '--directory']:
732                 os.chdir(value)
733             else:
734                 sys.exit(0)
735             
736         optKeys = [key for key, value in options]
737
738         if not args:
739             sys.stderr.write("%s: missing command argument "
740                              "(use --help for help)\n" % argv0)
741             sys.exit(1)
742
743         commands = {"annotate": (annotateSchema, 2),
744                     "c-idl-header": (printCIDLHeader, 1),
745                     "c-idl-source": (printCIDLSource, 1),
746                     "doc": (printDoc, 1)}
747
748         if not args[0] in commands:
749             sys.stderr.write("%s: unknown command \"%s\" "
750                              "(use --help for help)\n" % (argv0, args[0]))
751             sys.exit(1)
752
753         func, n_args = commands[args[0]]
754         if len(args) - 1 != n_args:
755             sys.stderr.write("%s: \"%s\" requires %d arguments but %d "
756                              "provided\n"
757                              % (argv0, args[0], n_args, len(args) - 1))
758             sys.exit(1)
759
760         func(*args[1:])
761     except Error, e:
762         sys.stderr.write("%s: %s\n" % (argv0, e.msg))
763         sys.exit(1)
764
765 # Local variables:
766 # mode: python
767 # End: