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