ovsdb-idlc: C code generation improvements.
[cascardo/ovs.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 name, tableJson in tablesJson.iteritems():
47             tables[name] = TableSchema.fromJson(tableJson, "%s table" % name)
48         idlPrefix = mustGetMember(json, 'idlPrefix', [unicode], 'database')
49         idlHeader = mustGetMember(json, 'idlHeader', [unicode], 'database')
50         return DbSchema(name, comment, tables, idlPrefix, idlHeader)
51
52     def toJson(self):
53         d = {"name": self.name,
54              "tables": {}}
55         for name, table in self.tables.iteritems():
56             d["tables"][name] = table.toJson()
57         if self.comment != None:
58             d["comment"] = self.comment
59         return d
60
61 class TableSchema:
62     def __init__(self, comment, columns):
63         self.comment = comment
64         self.columns = columns
65
66     @staticmethod
67     def fromJson(json, description):
68         comment = getMember(json, 'comment', [unicode], description)
69         columnsJson = mustGetMember(json, 'columns', [dict], description)
70         columns = {}
71         for name, json in columnsJson.iteritems():
72             columns[name] = ColumnSchema.fromJson(
73                 json, "column %s in %s" % (name, description))
74         return TableSchema(comment, columns)
75
76     def toJson(self):
77         d = {"columns": {}}
78         for name, column in self.columns.iteritems():
79             d["columns"][name] = column.toJson()
80         if self.comment != None:
81             d["comment"] = self.comment
82         return d
83
84 class ColumnSchema:
85     def __init__(self, comment, type, persistent):
86         self.comment = comment
87         self.type = type
88         self.persistent = persistent
89
90     @staticmethod
91     def fromJson(json, description):
92         comment = getMember(json, 'comment', [unicode], description)
93         type = Type.fromJson(mustGetMember(json, 'type', [dict, unicode],
94                                            description),
95                              'type of %s' % description)
96         ephemeral = getMember(json, 'ephemeral', [True,False], description)
97         persistent = ephemeral != True
98         return ColumnSchema(comment, type, persistent)
99
100     def toJson(self):
101         d = {"type": self.type.toJson()}
102         if self.persistent == False:
103             d["ephemeral"] = True
104         if self.comment != None:
105             d["comment"] = self.comment
106         return d
107
108 class Type:
109     def __init__(self, key, keyRefTable=None, value=None, valueRefTable=None,
110                  min=1, max=1):
111         self.key = key
112         self.keyRefTable = keyRefTable
113         self.value = value
114         self.valueRefTable = valueRefTable
115         self.min = min
116         self.max = max
117     
118     @staticmethod
119     def fromJson(json, description):
120         if type(json) == unicode:
121             return Type(json)
122         else:
123             key = mustGetMember(json, 'key', [unicode], description)
124             keyRefTable = getMember(json, 'keyRefTable', [unicode], description)
125             value = getMember(json, 'value', [unicode], description)
126             valueRefTable = getMember(json, 'valueRefTable', [unicode], description)
127             min = getMember(json, 'min', [int], description, 1)
128             max = getMember(json, 'max', [int, unicode], description, 1)
129             return Type(key, keyRefTable, value, valueRefTable, min, max)
130
131     def toJson(self):
132         if self.value == None and self.min == 1 and self.max == 1:
133             return self.key
134         else:
135             d = {"key": self.key}
136             if self.value != None:
137                 d["value"] = self.value
138             if self.min != 1:
139                 d["min"] = self.min
140             if self.max != 1:
141                 d["max"] = self.max
142             return d
143
144 def parseSchema(filename):
145     file = open(filename, "r")
146     s = ""
147     for line in file:
148         if not line.startswith('//'):
149             s += line
150     return DbSchema.fromJson(json.loads(s))
151
152 def cBaseType(prefix, type, refTable=None):
153     if type == 'uuid' and refTable:
154         return "struct %s%s *" % (prefix, refTable.lower())
155     else:
156         return {'integer': 'int64_t ',
157                 'real': 'double ',
158                 'uuid': 'struct uuid ',
159                 'boolean': 'bool ',
160                 'string': 'char *'}[type]
161
162 def typeIsOptionalPointer(type):
163     return (type.min == 0 and type.max == 1 and not type.value
164             and (type.key == 'string'
165                  or (type.key == 'uuid' and type.keyRefTable)))
166
167 def cDeclComment(type):
168     if type.min == 1 and type.max == 1 and type.key == "string":
169         return "\t/* Always nonnull. */"
170     else:
171         return ""
172
173 def printCIDLHeader(schema):
174     prefix = schema.idlPrefix
175     print '''\
176 /* Generated automatically -- do not modify!    -*- buffer-read-only: t -*- */
177
178 #ifndef %(prefix)sIDL_HEADER
179 #define %(prefix)sIDL_HEADER 1
180
181 #include <stdbool.h>
182 #include <stddef.h>
183 #include <stdint.h>
184 #include "ovsdb-idl-provider.h"
185 #include "uuid.h"''' % {'prefix': prefix.upper()}
186     for tableName, table in schema.tables.iteritems():
187         print
188         print "/* %s table. */" % tableName
189         structName = "%s%s" % (prefix, tableName.lower())
190         print "struct %s {" % structName
191         print "\tstruct ovsdb_idl_row header_;"
192         for columnName, column in table.columns.iteritems():
193             print "\n\t/* %s column. */" % columnName
194             type = column.type
195             if type.min == 1 and type.max == 1:
196                 singleton = True
197                 pointer = ''
198             else:
199                 singleton = False
200                 if typeIsOptionalPointer(type):
201                     pointer = ''
202                 else:
203                     pointer = '*'
204             if type.value:
205                 print "\t%s%skey_%s;" % (cBaseType(prefix, type.key, type.keyRefTable), pointer, columnName)
206                 print "\t%s%svalue_%s;" % (cBaseType(prefix, type.value, type.valueRefTable), pointer, columnName)
207             else:
208                 print "\t%s%s%s;%s" % (cBaseType(prefix, type.key, type.keyRefTable), pointer, columnName, cDeclComment(type))
209             if not singleton and not typeIsOptionalPointer(type):
210                 print "\tsize_t n_%s;" % columnName
211         print '''\
212 };
213
214 const struct %(s)s *%(s)s_first(const struct ovsdb_idl *);
215 const struct %(s)s *%(s)s_next(const struct %(s)s *);
216 #define %(S)s_FOR_EACH(ROW, IDL) for ((ROW) = %(s)s_first(IDL); (ROW); (ROW) = %(s)s_next(ROW))''' % {'s': structName, 'S': structName.upper()}
217     print "\nextern struct ovsdb_idl_class %sidl_class;" % prefix
218     print "\n#endif /* %(prefix)sIDL_HEADER */" % {'prefix': prefix.upper()}
219
220 def printEnum(members):
221     if len(members) == 0:
222         return
223
224     print "\nenum {";
225     for member in members[:-1]:
226         print "    %s," % member
227     print "    %s" % members[-1]
228     print "};"
229
230 def printCIDLSource(schema):
231     prefix = schema.idlPrefix
232     print '''\
233 /* Generated automatically -- do not modify!    -*- buffer-read-only: t -*- */
234
235 #include <config.h>
236 #include %s
237 #include <limits.h>
238 #include "ovsdb-data.h"''' % schema.idlHeader
239
240     # Table indexes.
241     printEnum(["%sTABLE_%s" % (prefix.upper(), tableName.upper()) for tableName in schema.tables] + ["%sN_TABLES" % prefix.upper()])
242     print "\nstatic struct ovsdb_idl_table_class %stable_classes[%sN_TABLES];" % (prefix, prefix.upper())
243
244     # Cast functions.
245     for tableName, table in schema.tables.iteritems():
246         structName = "%s%s" % (prefix, tableName.lower())
247         print '''
248 static struct %(s)s *
249 %(s)s_cast(struct ovsdb_idl_row *row)
250 {
251     return row ? CONTAINER_OF(row, struct %(s)s, header_) : NULL;
252 }\
253 ''' % {'s': structName}
254
255
256     for tableName, table in schema.tables.iteritems():
257         structName = "%s%s" % (prefix, tableName.lower())
258         print "\f"
259         if table.comment != None:
260             print "/* %s table (%s). */" % (tableName, table.comment)
261         else:
262             print "/* %s table. */" % (tableName)
263
264         # Column indexes.
265         printEnum(["%s_COL_%s" % (structName.upper(), columnName.upper())
266                    for columnName in table.columns]
267                   + ["%s_N_COLUMNS" % structName.upper()])
268
269         # Parse function.
270         print '''\
271 static void
272 %s_parse(struct ovsdb_idl_row *row_)
273 {
274     struct %s *row = %s_cast(row_);
275     const struct ovsdb_datum *datum;
276     size_t i UNUSED;
277
278     memset(row_ + 1, 0, sizeof *row - sizeof *row_);''' % (structName, structName, structName)
279
280
281         for columnName, column in table.columns.iteritems():
282             type = column.type
283             refKey = type.key == "uuid" and type.keyRefTable
284             refValue = type.value == "uuid" and type.valueRefTable
285             print
286             print "    datum = &row_->fields[%s_COL_%s];" % (structName.upper(), columnName.upper())
287             if type.value:
288                 keyVar = "row->key_%s" % columnName
289                 valueVar = "row->value_%s" % columnName
290             else:
291                 keyVar = "row->%s" % columnName
292                 valueVar = None
293
294             if (type.min == 1 and type.max == 1) or typeIsOptionalPointer(type):
295                 print "    if (datum->n >= 1) {"
296                 if not refKey:
297                     print "        %s = datum->keys[0].%s;" % (keyVar, type.key)
298                 else:
299                     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())
300
301                 if valueVar:
302                     if refValue:
303                         print "        %s = datum->values[0].%s;" % (valueVar, type.value)
304                     else:
305                         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())
306                 if (not typeIsOptionalPointer(type) and
307                     (type.key == "string" or type.value == "string")):
308                     print "    } else {"
309                     if type.key == "string":
310                         print "        %s = \"\";" % keyVar
311                     if type.value == "string":
312                         print "        %s = \"\";" % valueVar
313                 print "    }"
314
315             else:
316                 if type.max != 'unlimited':
317                     nMax = "MIN(%d, datum->n)" % type.max
318                 else:
319                     nMax = "datum->n"
320                 print "    for (i = 0; i < %s; i++) {" % nMax
321                 refs = []
322                 if refKey:
323                     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())
324                     keySrc = "keyRow"
325                     refs.append('keyRow')
326                 else:
327                     keySrc = "datum->keys[i].%s" % type.key
328                 if refValue:
329                     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())
330                     valueSrc = "valueRow"
331                     refs.append('valueRow')
332                 elif valueVar:
333                     valueSrc = "datum->values[i].%s" % type.value
334                 if refs:
335                     print "        if (%s) {" % ' && '.join(refs)
336                     indent = "            "
337                 else:
338                     indent = "        "
339                 print "%sif (!row->n_%s) {" % (indent, columnName)
340                 print "%s    %s = xmalloc(%s * sizeof *%s);" % (indent, keyVar, nMax, keyVar)
341                 if valueVar:
342                     print "%s    %s = xmalloc(%s * sizeof %s);" % (indent, valueVar, nMax, valueVar)
343                 print "%s}" % indent
344                 print "%s%s[row->n_%s] = %s;" % (indent, keyVar, columnName, keySrc)
345                 if valueVar:
346                     print "%s%s[row->n_%s] = %s;" % (indent, valueVar, columnName, valueSrc)
347                 print "%srow->n_%s++;" % (indent, columnName)
348                 if refs:
349                     print "        }"
350                 print "    }"
351         print "}"
352
353         # Unparse function.
354         nArrays = 0
355         for columnName, column in table.columns.iteritems():
356             type = column.type
357             if (type.min != 1 or type.max != 1) and not typeIsOptionalPointer(type):
358                 if not nArrays:
359                     print '''
360 static void
361 %s_unparse(struct ovsdb_idl_row *row_)
362 {
363     struct %s *row = %s_cast(row_);
364 ''' % (structName, structName, structName)
365                 if type.value:
366                     keyVar = "row->key_%s" % columnName
367                     valueVar = "row->value_%s" % columnName
368                 else:
369                     keyVar = "row->%s" % columnName
370                     valueVar = None
371                 print "    free(%s);" % keyVar
372                 if valueVar:
373                     print "    free(%s);" % valueVar
374                 nArrays += 1
375         if not nArrays:
376             print '''
377 static void
378 %s_unparse(struct ovsdb_idl_row *row UNUSED)
379 {''' % (structName)
380         print "}"
381
382         # First, next functions.
383         print '''
384 const struct %(s)s *
385 %(s)s_first(const struct ovsdb_idl *idl)
386 {
387     return %(s)s_cast(ovsdb_idl_first_row(idl, &%(p)stable_classes[%(P)sTABLE_%(T)s]));
388 }
389
390 const struct %(s)s *
391 %(s)s_next(const struct %(s)s *row)
392 {
393     return %(s)s_cast(ovsdb_idl_next_row(&row->header_));
394 }''' % {'s': structName, 'p': prefix, 'P': prefix.upper(), 'T': tableName.upper()}
395
396         # Table columns.
397         print "\nstatic struct ovsdb_idl_column %s_columns[%s_N_COLUMNS] = {" % (
398             structName, structName.upper())
399         for columnName, column in table.columns.iteritems():
400             type = column.type
401             
402             if type.value:
403                 valueTypeName = type.value.upper()
404             else:
405                 valueTypeName = "VOID"
406             if type.max == "unlimited":
407                 max = "UINT_MAX"
408             else:
409                 max = type.max
410             print "    {\"%s\", {OVSDB_TYPE_%s, OVSDB_TYPE_%s, %d, %s}}," % (
411                 columnName, type.key.upper(), valueTypeName,
412                 type.min, max)
413         print "};"
414
415     # Table classes.
416     print "\f"
417     print "static struct ovsdb_idl_table_class %stable_classes[%sN_TABLES] = {" % (prefix, prefix.upper())
418     for tableName, table in schema.tables.iteritems():
419         structName = "%s%s" % (prefix, tableName.lower())
420         print "    {\"%s\"," % tableName
421         print "     %s_columns, ARRAY_SIZE(%s_columns)," % (
422             structName, structName)
423         print "     sizeof(struct %s)," % structName
424         print "     %s_parse," % structName
425         print "     %s_unparse}," % structName
426     print "};"
427
428     # IDL class.
429     print "\nstruct ovsdb_idl_class %sidl_class = {" % prefix
430     print "    %stable_classes, ARRAY_SIZE(%stable_classes)" % (prefix, prefix)
431     print "};"
432
433 def ovsdb_escape(string):
434     def escape(match):
435         c = match.group(0)
436         if c == '\0':
437             raise Error("strings may not contain null bytes")
438         elif c == '\\':
439             return '\\\\'
440         elif c == '\n':
441             return '\\n'
442         elif c == '\r':
443             return '\\r'
444         elif c == '\t':
445             return '\\t'
446         elif c == '\b':
447             return '\\b'
448         elif c == '\a':
449             return '\\a'
450         else:
451             return '\\x%02x' % ord(c)
452     return re.sub(r'["\\\000-\037]', escape, string)
453
454 def printOVSDBSchema(schema):
455     json.dump(schema.toJson(), sys.stdout, sort_keys=True, indent=2)
456
457 def usage():
458     print """\
459 %(argv0)s: ovsdb schema compiler
460 usage: %(argv0)s [OPTIONS] ACTION SCHEMA
461 where SCHEMA is the ovsdb schema to read (in JSON format).
462
463 One of the following actions must specified:
464   validate                    validate schema without taking any other action
465   c-idl-header                print C header file for IDL
466   c-idl-source                print C source file for IDL implementation
467   ovsdb-schema                print ovsdb parseable schema
468
469 The following options are also available:
470   -h, --help                  display this help message
471   -V, --version               display version information\
472 """ % {'argv0': argv0}
473     sys.exit(0)
474
475 if __name__ == "__main__":
476     try:
477         try:
478             options, args = getopt.gnu_getopt(sys.argv[1:], 'hV',
479                                               ['help',
480                                                'version'])
481         except getopt.GetoptError, geo:
482             sys.stderr.write("%s: %s\n" % (argv0, geo.msg))
483             sys.exit(1)
484             
485         optKeys = [key for key, value in options]
486         if '-h' in optKeys or '--help' in optKeys:
487             usage()
488         elif '-V' in optKeys or '--version' in optKeys:
489             print "ovsdb-idlc (Open vSwitch) @VERSION@"
490             sys.exit(0)
491
492         if len(args) != 2:
493             sys.stderr.write("%s: exactly two non-option arguments are "
494                              "required (use --help for help)\n" % argv0)
495             sys.exit(1)
496
497         action, inputFile = args
498         schema = parseSchema(inputFile)
499         if action == 'validate':
500             pass
501         elif action == 'ovsdb-schema':
502             printOVSDBSchema(schema)
503         elif action == 'c-idl-header':
504             printCIDLHeader(schema)
505         elif action == 'c-idl-source':
506             printCIDLSource(schema)
507         else:
508             sys.stderr.write(
509                 "%s: unknown action '%s' (use --help for help)\n" %
510                 (argv0, action))
511             sys.exit(1)
512     except Error, e:
513         sys.stderr.write("%s: %s\n" % (argv0, e.msg))
514         sys.exit(1)
515
516 # Local variables:
517 # mode: python
518 # End: