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