-
Notifications
You must be signed in to change notification settings - Fork 0
/
qapi.py
2033 lines (1724 loc) · 69.8 KB
/
qapi.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# QAPI helper library
#
# Copyright IBM, Corp. 2011
# Copyright (c) 2013-2016 Red Hat Inc.
#
# Authors:
# Anthony Liguori <[email protected]>
# Markus Armbruster <[email protected]>
#
# This work is licensed under the terms of the GNU GPL, version 2.
# See the COPYING file in the top-level directory.
import errno
import getopt
import os
import re
import string
import sys
from ordereddict import OrderedDict
builtin_types = {
'null': 'QTYPE_QNULL',
'str': 'QTYPE_QSTRING',
'int': 'QTYPE_QNUM',
'number': 'QTYPE_QNUM',
'bool': 'QTYPE_QBOOL',
'int8': 'QTYPE_QNUM',
'int16': 'QTYPE_QNUM',
'int32': 'QTYPE_QNUM',
'int64': 'QTYPE_QNUM',
'uint8': 'QTYPE_QNUM',
'uint16': 'QTYPE_QNUM',
'uint32': 'QTYPE_QNUM',
'uint64': 'QTYPE_QNUM',
'size': 'QTYPE_QNUM',
'any': None, # any QType possible, actually
'QType': 'QTYPE_QSTRING',
}
# Are documentation comments required?
doc_required = False
# Whitelist of commands allowed to return a non-dictionary
returns_whitelist = []
# Whitelist of entities allowed to violate case conventions
name_case_whitelist = []
enum_types = {}
struct_types = {}
union_types = {}
all_names = {}
#
# Parsing the schema into expressions
#
def error_path(parent):
res = ''
while parent:
res = ('In file included from %s:%d:\n' % (parent['file'],
parent['line'])) + res
parent = parent['parent']
return res
class QAPIError(Exception):
def __init__(self, fname, line, col, incl_info, msg):
Exception.__init__(self)
self.fname = fname
self.line = line
self.col = col
self.info = incl_info
self.msg = msg
def __str__(self):
loc = '%s:%d' % (self.fname, self.line)
if self.col is not None:
loc += ':%s' % self.col
return error_path(self.info) + '%s: %s' % (loc, self.msg)
class QAPIParseError(QAPIError):
def __init__(self, parser, msg):
col = 1
for ch in parser.src[parser.line_pos:parser.pos]:
if ch == '\t':
col = (col + 7) % 8 + 1
else:
col += 1
QAPIError.__init__(self, parser.fname, parser.line, col,
parser.incl_info, msg)
class QAPISemError(QAPIError):
def __init__(self, info, msg):
QAPIError.__init__(self, info['file'], info['line'], None,
info['parent'], msg)
class QAPIDoc(object):
class Section(object):
def __init__(self, name=None):
# optional section name (argument/member or section name)
self.name = name
# the list of lines for this section
self.content = []
def append(self, line):
self.content.append(line)
def __repr__(self):
return '\n'.join(self.content).strip()
class ArgSection(Section):
def __init__(self, name):
QAPIDoc.Section.__init__(self, name)
self.member = None
def connect(self, member):
self.member = member
def __init__(self, parser, info):
# self.parser is used to report errors with QAPIParseError. The
# resulting error position depends on the state of the parser.
# It happens to be the beginning of the comment. More or less
# servicable, but action at a distance.
self.parser = parser
self.info = info
self.symbol = None
self.body = QAPIDoc.Section()
# dict mapping parameter name to ArgSection
self.args = OrderedDict()
# a list of Section
self.sections = []
# the current section
self.section = self.body
def has_section(self, name):
"""Return True if we have a section with this name."""
for i in self.sections:
if i.name == name:
return True
return False
def append(self, line):
"""Parse a comment line and add it to the documentation."""
line = line[1:]
if not line:
self._append_freeform(line)
return
if line[0] != ' ':
raise QAPIParseError(self.parser, "Missing space after #")
line = line[1:]
# FIXME not nice: things like '# @foo:' and '# @foo: ' aren't
# recognized, and get silently treated as ordinary text
if self.symbol:
self._append_symbol_line(line)
elif not self.body.content and line.startswith('@'):
if not line.endswith(':'):
raise QAPIParseError(self.parser, "Line should end with :")
self.symbol = line[1:-1]
# FIXME invalid names other than the empty string aren't flagged
if not self.symbol:
raise QAPIParseError(self.parser, "Invalid name")
else:
self._append_freeform(line)
def end_comment(self):
self._end_section()
def _append_symbol_line(self, line):
name = line.split(' ', 1)[0]
if name.startswith('@') and name.endswith(':'):
line = line[len(name)+1:]
self._start_args_section(name[1:-1])
elif name in ('Returns:', 'Since:',
# those are often singular or plural
'Note:', 'Notes:',
'Example:', 'Examples:',
'TODO:'):
line = line[len(name)+1:]
self._start_section(name[:-1])
self._append_freeform(line)
def _start_args_section(self, name):
# FIXME invalid names other than the empty string aren't flagged
if not name:
raise QAPIParseError(self.parser, "Invalid parameter name")
if name in self.args:
raise QAPIParseError(self.parser,
"'%s' parameter name duplicated" % name)
if self.sections:
raise QAPIParseError(self.parser,
"'@%s:' can't follow '%s' section"
% (name, self.sections[0].name))
self._end_section()
self.section = QAPIDoc.ArgSection(name)
self.args[name] = self.section
def _start_section(self, name=''):
if name in ('Returns', 'Since') and self.has_section(name):
raise QAPIParseError(self.parser,
"Duplicated '%s' section" % name)
self._end_section()
self.section = QAPIDoc.Section(name)
self.sections.append(self.section)
def _end_section(self):
if self.section:
contents = str(self.section)
if self.section.name and (not contents or contents.isspace()):
raise QAPIParseError(self.parser, "Empty doc section '%s'"
% self.section.name)
self.section = None
def _append_freeform(self, line):
in_arg = isinstance(self.section, QAPIDoc.ArgSection)
if (in_arg and self.section.content
and not self.section.content[-1]
and line and not line[0].isspace()):
self._start_section()
if (in_arg or not self.section.name
or not self.section.name.startswith('Example')):
line = line.strip()
match = re.match(r'(@\S+:)', line)
if match:
raise QAPIParseError(self.parser,
"'%s' not allowed in free-form documentation"
% match.group(1))
# TODO Drop this once the dust has settled
if (isinstance(self.section, QAPIDoc.ArgSection)
and '#optional' in line):
raise QAPISemError(self.info, "Please drop the #optional tag")
self.section.append(line)
def connect_member(self, member):
if member.name not in self.args:
# Undocumented TODO outlaw
self.args[member.name] = QAPIDoc.ArgSection(member.name)
self.args[member.name].connect(member)
def check_expr(self, expr):
if self.has_section('Returns') and 'command' not in expr:
raise QAPISemError(self.info,
"'Returns:' is only valid for commands")
def check(self):
bogus = [name for name, section in self.args.iteritems()
if not section.member]
if bogus:
raise QAPISemError(
self.info,
"The following documented members are not in "
"the declaration: %s" % ", ".join(bogus))
class QAPISchemaParser(object):
def __init__(self, fp, previously_included=[], incl_info=None):
abs_fname = os.path.abspath(fp.name)
fname = fp.name
self.fname = fname
previously_included.append(abs_fname)
self.incl_info = incl_info
self.src = fp.read()
if self.src == '' or self.src[-1] != '\n':
self.src += '\n'
self.cursor = 0
self.line = 1
self.line_pos = 0
self.exprs = []
self.docs = []
self.cur_doc = None
self.accept()
while self.tok is not None:
info = {'file': fname, 'line': self.line,
'parent': self.incl_info}
if self.tok == '#':
self.reject_expr_doc()
self.cur_doc = self.get_doc(info)
self.docs.append(self.cur_doc)
continue
expr = self.get_expr(False)
if 'include' in expr:
self.reject_expr_doc()
if len(expr) != 1:
raise QAPISemError(info, "Invalid 'include' directive")
include = expr['include']
if not isinstance(include, str):
raise QAPISemError(info,
"Value of 'include' must be a string")
self._include(include, info, os.path.dirname(abs_fname),
previously_included)
elif "pragma" in expr:
self.reject_expr_doc()
if len(expr) != 1:
raise QAPISemError(info, "Invalid 'pragma' directive")
pragma = expr['pragma']
if not isinstance(pragma, dict):
raise QAPISemError(
info, "Value of 'pragma' must be a dictionary")
for name, value in pragma.iteritems():
self._pragma(name, value, info)
else:
expr_elem = {'expr': expr,
'info': info}
if self.cur_doc:
if not self.cur_doc.symbol:
raise QAPISemError(
self.cur_doc.info,
"Expression documentation required")
expr_elem['doc'] = self.cur_doc
self.exprs.append(expr_elem)
self.cur_doc = None
self.reject_expr_doc()
def reject_expr_doc(self):
if self.cur_doc and self.cur_doc.symbol:
raise QAPISemError(
self.cur_doc.info,
"Documentation for '%s' is not followed by the definition"
% self.cur_doc.symbol)
def _include(self, include, info, base_dir, previously_included):
incl_abs_fname = os.path.join(base_dir, include)
# catch inclusion cycle
inf = info
while inf:
if incl_abs_fname == os.path.abspath(inf['file']):
raise QAPISemError(info, "Inclusion loop for %s" % include)
inf = inf['parent']
# skip multiple include of the same file
if incl_abs_fname in previously_included:
return
try:
fobj = open(incl_abs_fname, 'r')
except IOError as e:
raise QAPISemError(info, '%s: %s' % (e.strerror, include))
exprs_include = QAPISchemaParser(fobj, previously_included, info)
self.exprs.extend(exprs_include.exprs)
self.docs.extend(exprs_include.docs)
def _pragma(self, name, value, info):
global doc_required, returns_whitelist, name_case_whitelist
if name == 'doc-required':
if not isinstance(value, bool):
raise QAPISemError(info,
"Pragma 'doc-required' must be boolean")
doc_required = value
elif name == 'returns-whitelist':
if (not isinstance(value, list)
or any([not isinstance(elt, str) for elt in value])):
raise QAPISemError(info,
"Pragma returns-whitelist must be"
" a list of strings")
returns_whitelist = value
elif name == 'name-case-whitelist':
if (not isinstance(value, list)
or any([not isinstance(elt, str) for elt in value])):
raise QAPISemError(info,
"Pragma name-case-whitelist must be"
" a list of strings")
name_case_whitelist = value
else:
raise QAPISemError(info, "Unknown pragma '%s'" % name)
def accept(self, skip_comment=True):
while True:
self.tok = self.src[self.cursor]
self.pos = self.cursor
self.cursor += 1
self.val = None
if self.tok == '#':
if self.src[self.cursor] == '#':
# Start of doc comment
skip_comment = False
self.cursor = self.src.find('\n', self.cursor)
if not skip_comment:
self.val = self.src[self.pos:self.cursor]
return
elif self.tok in '{}:,[]':
return
elif self.tok == "'":
string = ''
esc = False
while True:
ch = self.src[self.cursor]
self.cursor += 1
if ch == '\n':
raise QAPIParseError(self, 'Missing terminating "\'"')
if esc:
if ch == 'b':
string += '\b'
elif ch == 'f':
string += '\f'
elif ch == 'n':
string += '\n'
elif ch == 'r':
string += '\r'
elif ch == 't':
string += '\t'
elif ch == 'u':
value = 0
for _ in range(0, 4):
ch = self.src[self.cursor]
self.cursor += 1
if ch not in '0123456789abcdefABCDEF':
raise QAPIParseError(self,
'\\u escape needs 4 '
'hex digits')
value = (value << 4) + int(ch, 16)
# If Python 2 and 3 didn't disagree so much on
# how to handle Unicode, then we could allow
# Unicode string defaults. But most of QAPI is
# ASCII-only, so we aren't losing much for now.
if not value or value > 0x7f:
raise QAPIParseError(self,
'For now, \\u escape '
'only supports non-zero '
'values up to \\u007f')
string += chr(value)
elif ch in '\\/\'"':
string += ch
else:
raise QAPIParseError(self,
"Unknown escape \\%s" % ch)
esc = False
elif ch == '\\':
esc = True
elif ch == "'":
self.val = string
return
else:
string += ch
elif self.src.startswith('true', self.pos):
self.val = True
self.cursor += 3
return
elif self.src.startswith('false', self.pos):
self.val = False
self.cursor += 4
return
elif self.src.startswith('null', self.pos):
self.val = None
self.cursor += 3
return
elif self.tok == '\n':
if self.cursor == len(self.src):
self.tok = None
return
self.line += 1
self.line_pos = self.cursor
elif not self.tok.isspace():
raise QAPIParseError(self, 'Stray "%s"' % self.tok)
def get_members(self):
expr = OrderedDict()
if self.tok == '}':
self.accept()
return expr
if self.tok != "'":
raise QAPIParseError(self, 'Expected string or "}"')
while True:
key = self.val
self.accept()
if self.tok != ':':
raise QAPIParseError(self, 'Expected ":"')
self.accept()
if key in expr:
raise QAPIParseError(self, 'Duplicate key "%s"' % key)
expr[key] = self.get_expr(True)
if self.tok == '}':
self.accept()
return expr
if self.tok != ',':
raise QAPIParseError(self, 'Expected "," or "}"')
self.accept()
if self.tok != "'":
raise QAPIParseError(self, 'Expected string')
def get_values(self):
expr = []
if self.tok == ']':
self.accept()
return expr
if self.tok not in "{['tfn":
raise QAPIParseError(self, 'Expected "{", "[", "]", string, '
'boolean or "null"')
while True:
expr.append(self.get_expr(True))
if self.tok == ']':
self.accept()
return expr
if self.tok != ',':
raise QAPIParseError(self, 'Expected "," or "]"')
self.accept()
def get_expr(self, nested):
if self.tok != '{' and not nested:
raise QAPIParseError(self, 'Expected "{"')
if self.tok == '{':
self.accept()
expr = self.get_members()
elif self.tok == '[':
self.accept()
expr = self.get_values()
elif self.tok in "'tfn":
expr = self.val
self.accept()
else:
raise QAPIParseError(self, 'Expected "{", "[", string, '
'boolean or "null"')
return expr
def get_doc(self, info):
if self.val != '##':
raise QAPIParseError(self, "Junk after '##' at start of "
"documentation comment")
doc = QAPIDoc(self, info)
self.accept(False)
while self.tok == '#':
if self.val.startswith('##'):
# End of doc comment
if self.val != '##':
raise QAPIParseError(self, "Junk after '##' at end of "
"documentation comment")
doc.end_comment()
self.accept()
return doc
else:
doc.append(self.val)
self.accept(False)
raise QAPIParseError(self, "Documentation comment must end with '##'")
#
# Semantic analysis of schema expressions
# TODO fold into QAPISchema
# TODO catching name collisions in generated code would be nice
#
def find_base_members(base):
if isinstance(base, dict):
return base
base_struct_define = struct_types.get(base)
if not base_struct_define:
return None
return base_struct_define['data']
# Return the qtype of an alternate branch, or None on error.
def find_alternate_member_qtype(qapi_type):
if qapi_type in builtin_types:
return builtin_types[qapi_type]
elif qapi_type in struct_types:
return 'QTYPE_QDICT'
elif qapi_type in enum_types:
return 'QTYPE_QSTRING'
elif qapi_type in union_types:
return 'QTYPE_QDICT'
return None
# Return the discriminator enum define if discriminator is specified as an
# enum type, otherwise return None.
def discriminator_find_enum_define(expr):
base = expr.get('base')
discriminator = expr.get('discriminator')
if not (discriminator and base):
return None
base_members = find_base_members(base)
if not base_members:
return None
discriminator_type = base_members.get(discriminator)
if not discriminator_type:
return None
return enum_types.get(discriminator_type)
# Names must be letters, numbers, -, and _. They must start with letter,
# except for downstream extensions which must start with __RFQDN_.
# Dots are only valid in the downstream extension prefix.
valid_name = re.compile(r'^(__[a-zA-Z0-9.-]+_)?'
'[a-zA-Z][a-zA-Z0-9_-]*$')
def check_name(info, source, name, allow_optional=False,
enum_member=False):
global valid_name
membername = name
if not isinstance(name, str):
raise QAPISemError(info, "%s requires a string name" % source)
if name.startswith('*'):
membername = name[1:]
if not allow_optional:
raise QAPISemError(info, "%s does not allow optional name '%s'"
% (source, name))
# Enum members can start with a digit, because the generated C
# code always prefixes it with the enum name
if enum_member and membername[0].isdigit():
membername = 'D' + membername
# Reserve the entire 'q_' namespace for c_name(), and for 'q_empty'
# and 'q_obj_*' implicit type names.
if not valid_name.match(membername) or \
c_name(membername, False).startswith('q_'):
raise QAPISemError(info, "%s uses invalid name '%s'" % (source, name))
def add_name(name, info, meta, implicit=False):
global all_names
check_name(info, "'%s'" % meta, name)
# FIXME should reject names that differ only in '_' vs. '.'
# vs. '-', because they're liable to clash in generated C.
if name in all_names:
raise QAPISemError(info, "%s '%s' is already defined"
% (all_names[name], name))
if not implicit and (name.endswith('Kind') or name.endswith('List')):
raise QAPISemError(info, "%s '%s' should not end in '%s'"
% (meta, name, name[-4:]))
all_names[name] = meta
def check_type(info, source, value, allow_array=False,
allow_dict=False, allow_optional=False,
allow_metas=[]):
global all_names
if value is None:
return
# Check if array type for value is okay
if isinstance(value, list):
if not allow_array:
raise QAPISemError(info, "%s cannot be an array" % source)
if len(value) != 1 or not isinstance(value[0], str):
raise QAPISemError(info,
"%s: array type must contain single type name" %
source)
value = value[0]
# Check if type name for value is okay
if isinstance(value, str):
if value not in all_names:
raise QAPISemError(info, "%s uses unknown type '%s'"
% (source, value))
if not all_names[value] in allow_metas:
raise QAPISemError(info, "%s cannot use %s type '%s'" %
(source, all_names[value], value))
return
if not allow_dict:
raise QAPISemError(info, "%s should be a type name" % source)
if not isinstance(value, OrderedDict):
raise QAPISemError(info,
"%s should be a dictionary or type name" % source)
# value is a dictionary, check that each member is okay
for (key, arg) in value.items():
check_name(info, "Member of %s" % source, key,
allow_optional=allow_optional)
if c_name(key, False) == 'u' or c_name(key, False).startswith('has_'):
raise QAPISemError(info, "Member of %s uses reserved name '%s'"
% (source, key))
# Todo: allow dictionaries to represent default values of
# an optional argument.
check_type(info, "Member '%s' of %s" % (key, source), arg,
allow_array=True,
allow_metas=['built-in', 'union', 'alternate', 'struct',
'enum'])
def check_command(expr, info):
name = expr['command']
boxed = expr.get('boxed', False)
args_meta = ['struct']
if boxed:
args_meta += ['union', 'alternate']
check_type(info, "'data' for command '%s'" % name,
expr.get('data'), allow_dict=not boxed, allow_optional=True,
allow_metas=args_meta)
returns_meta = ['union', 'struct']
if name in returns_whitelist:
returns_meta += ['built-in', 'alternate', 'enum']
check_type(info, "'returns' for command '%s'" % name,
expr.get('returns'), allow_array=True,
allow_optional=True, allow_metas=returns_meta)
def check_event(expr, info):
name = expr['event']
boxed = expr.get('boxed', False)
meta = ['struct']
if boxed:
meta += ['union', 'alternate']
check_type(info, "'data' for event '%s'" % name,
expr.get('data'), allow_dict=not boxed, allow_optional=True,
allow_metas=meta)
def check_union(expr, info):
name = expr['union']
base = expr.get('base')
discriminator = expr.get('discriminator')
members = expr['data']
# Two types of unions, determined by discriminator.
# With no discriminator it is a simple union.
if discriminator is None:
enum_define = None
allow_metas = ['built-in', 'union', 'alternate', 'struct', 'enum']
if base is not None:
raise QAPISemError(info, "Simple union '%s' must not have a base" %
name)
# Else, it's a flat union.
else:
# The object must have a string or dictionary 'base'.
check_type(info, "'base' for union '%s'" % name,
base, allow_dict=True, allow_optional=True,
allow_metas=['struct'])
if not base:
raise QAPISemError(info, "Flat union '%s' must have a base"
% name)
base_members = find_base_members(base)
assert base_members is not None
# The value of member 'discriminator' must name a non-optional
# member of the base struct.
check_name(info, "Discriminator of flat union '%s'" % name,
discriminator)
discriminator_type = base_members.get(discriminator)
if not discriminator_type:
raise QAPISemError(info,
"Discriminator '%s' is not a member of base "
"struct '%s'"
% (discriminator, base))
enum_define = enum_types.get(discriminator_type)
allow_metas = ['struct']
# Do not allow string discriminator
if not enum_define:
raise QAPISemError(info,
"Discriminator '%s' must be of enumeration "
"type" % discriminator)
# Check every branch; don't allow an empty union
if len(members) == 0:
raise QAPISemError(info, "Union '%s' cannot have empty 'data'" % name)
for (key, value) in members.items():
check_name(info, "Member of union '%s'" % name, key)
# Each value must name a known type
check_type(info, "Member '%s' of union '%s'" % (key, name),
value, allow_array=not base, allow_metas=allow_metas)
# If the discriminator names an enum type, then all members
# of 'data' must also be members of the enum type.
if enum_define:
if key not in enum_define['data']:
raise QAPISemError(info,
"Discriminator value '%s' is not found in "
"enum '%s'"
% (key, enum_define['enum']))
# If discriminator is user-defined, ensure all values are covered
if enum_define:
for value in enum_define['data']:
if value not in members.keys():
raise QAPISemError(info, "Union '%s' data missing '%s' branch"
% (name, value))
def check_alternate(expr, info):
name = expr['alternate']
members = expr['data']
types_seen = {}
# Check every branch; require at least two branches
if len(members) < 2:
raise QAPISemError(info,
"Alternate '%s' should have at least two branches "
"in 'data'" % name)
for (key, value) in members.items():
check_name(info, "Member of alternate '%s'" % name, key)
# Ensure alternates have no type conflicts.
check_type(info, "Member '%s' of alternate '%s'" % (key, name),
value,
allow_metas=['built-in', 'union', 'struct', 'enum'])
qtype = find_alternate_member_qtype(value)
if not qtype:
raise QAPISemError(info, "Alternate '%s' member '%s' cannot use "
"type '%s'" % (name, key, value))
conflicting = set([qtype])
if qtype == 'QTYPE_QSTRING':
enum_expr = enum_types.get(value)
if enum_expr:
for v in enum_expr['data']:
if v in ['on', 'off']:
conflicting.add('QTYPE_QBOOL')
if re.match(r'[-+0-9.]', v): # lazy, could be tightened
conflicting.add('QTYPE_QNUM')
else:
conflicting.add('QTYPE_QNUM')
conflicting.add('QTYPE_QBOOL')
for qt in conflicting:
if qt in types_seen:
raise QAPISemError(info, "Alternate '%s' member '%s' can't "
"be distinguished from member '%s'"
% (name, key, types_seen[qt]))
types_seen[qt] = key
def check_enum(expr, info):
name = expr['enum']
members = expr.get('data')
prefix = expr.get('prefix')
if not isinstance(members, list):
raise QAPISemError(info,
"Enum '%s' requires an array for 'data'" % name)
if prefix is not None and not isinstance(prefix, str):
raise QAPISemError(info,
"Enum '%s' requires a string for 'prefix'" % name)
for member in members:
check_name(info, "Member of enum '%s'" % name, member,
enum_member=True)
def check_struct(expr, info):
name = expr['struct']
members = expr['data']
check_type(info, "'data' for struct '%s'" % name, members,
allow_dict=True, allow_optional=True)
check_type(info, "'base' for struct '%s'" % name, expr.get('base'),
allow_metas=['struct'])
def check_keys(expr_elem, meta, required, optional=[]):
expr = expr_elem['expr']
info = expr_elem['info']
name = expr[meta]
if not isinstance(name, str):
raise QAPISemError(info, "'%s' key must have a string value" % meta)
required = required + [meta]
for (key, value) in expr.items():
if key not in required and key not in optional:
raise QAPISemError(info, "Unknown key '%s' in %s '%s'"
% (key, meta, name))
if (key == 'gen' or key == 'success-response') and value is not False:
raise QAPISemError(info,
"'%s' of %s '%s' should only use false value"
% (key, meta, name))
if key == 'boxed' and value is not True:
raise QAPISemError(info,
"'%s' of %s '%s' should only use true value"
% (key, meta, name))
for key in required:
if key not in expr:
raise QAPISemError(info, "Key '%s' is missing from %s '%s'"
% (key, meta, name))
def check_exprs(exprs):
global all_names
# Populate name table with names of built-in types
for builtin in builtin_types.keys():
all_names[builtin] = 'built-in'
# Learn the types and check for valid expression keys
for expr_elem in exprs:
expr = expr_elem['expr']
info = expr_elem['info']
doc = expr_elem.get('doc')
if not doc and doc_required:
raise QAPISemError(info,
"Expression missing documentation comment")
if 'enum' in expr:
meta = 'enum'
check_keys(expr_elem, 'enum', ['data'], ['prefix'])
enum_types[expr[meta]] = expr
elif 'union' in expr:
meta = 'union'
check_keys(expr_elem, 'union', ['data'],
['base', 'discriminator'])
union_types[expr[meta]] = expr
elif 'alternate' in expr:
meta = 'alternate'
check_keys(expr_elem, 'alternate', ['data'])
elif 'struct' in expr:
meta = 'struct'
check_keys(expr_elem, 'struct', ['data'], ['base'])
struct_types[expr[meta]] = expr
elif 'command' in expr:
meta = 'command'
check_keys(expr_elem, 'command', [],
['data', 'returns', 'gen', 'success-response', 'boxed'])
elif 'event' in expr:
meta = 'event'
check_keys(expr_elem, 'event', [], ['data', 'boxed'])
else:
raise QAPISemError(expr_elem['info'],
"Expression is missing metatype")
name = expr[meta]
add_name(name, info, meta)
if doc and doc.symbol != name:
raise QAPISemError(info, "Definition of '%s' follows documentation"
" for '%s'" % (name, doc.symbol))
# Try again for hidden UnionKind enum
for expr_elem in exprs:
expr = expr_elem['expr']
if 'union' in expr and not discriminator_find_enum_define(expr):
name = '%sKind' % expr['union']
elif 'alternate' in expr:
name = '%sKind' % expr['alternate']
else:
continue
enum_types[name] = {'enum': name}
add_name(name, info, 'enum', implicit=True)
# Validate that exprs make sense
for expr_elem in exprs:
expr = expr_elem['expr']
info = expr_elem['info']
doc = expr_elem.get('doc')
if 'enum' in expr:
check_enum(expr, info)
elif 'union' in expr:
check_union(expr, info)
elif 'alternate' in expr:
check_alternate(expr, info)
elif 'struct' in expr:
check_struct(expr, info)
elif 'command' in expr:
check_command(expr, info)
elif 'event' in expr:
check_event(expr, info)
else:
assert False, 'unexpected meta type'
if doc:
doc.check_expr(expr)
return exprs
#
# Schema compiler frontend
#
class QAPISchemaEntity(object):
def __init__(self, name, info, doc):
assert isinstance(name, str)
self.name = name
# For explicitly defined entities, info points to the (explicit)
# definition. For builtins (and their arrays), info is None.
# For implicitly defined entities, info points to a place that
# triggered the implicit definition (there may be more than one
# such place).
self.info = info
self.doc = doc
def c_name(self):
return c_name(self.name)
def check(self, schema):
pass
def is_implicit(self):
return not self.info
def visit(self, visitor):