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