/
binder.py
1608 lines (1221 loc) · 61.2 KB
/
binder.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
# Copyright (C) 2018-present MongoDB, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the Server Side Public License, version 1,
# as published by MongoDB, Inc.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# Server Side Public License for more details.
#
# You should have received a copy of the Server Side Public License
# along with this program. If not, see
# <http://www.mongodb.com/licensing/server-side-public-license>.
#
# As a special exception, the copyright holders give permission to link the
# code of portions of this program with the OpenSSL library under certain
# conditions as described in each individual source file and distribute
# linked combinations including the program with the OpenSSL library. You
# must comply with the Server Side Public License in all respects for
# all of the code used other than as permitted herein. If you modify file(s)
# with this exception, you may extend this exception to your version of the
# file(s), but you are not obligated to do so. If you do not wish to do so,
# delete this exception statement from your version. If you delete this
# exception statement from all source files in the program, then also delete
# it in the license file.
#
# pylint: disable=too-many-lines
"""Transform idl.syntax trees from the parser into well-defined idl.ast trees."""
import collections
import re
import typing
from typing import Type, TypeVar, cast, List, Set, Union, Optional
from . import ast
from . import bson
from . import common
from . import enum_types
from . import errors
from . import syntax
def _validate_single_bson_type(ctxt, idl_type, syntax_type):
# type: (errors.ParserContext, Union[syntax.Type, ast.Type], str) -> bool
"""Validate bson serialization type is correct for a type."""
bson_type = idl_type.bson_serialization_type[0]
# Any and Chain are only valid if they are the only bson types specified
if bson_type in ["any", "chain"]:
return True
if not bson.is_valid_bson_type(bson_type):
ctxt.add_bad_bson_type_error(idl_type, syntax_type, idl_type.name, bson_type)
return False
# Validate bindata_subytpe
if bson_type == "bindata":
subtype = idl_type.bindata_subtype
if subtype is None:
subtype = "<unknown>"
if not bson.is_valid_bindata_subtype(subtype):
ctxt.add_bad_bson_bindata_subtype_value_error(idl_type, syntax_type, idl_type.name,
subtype)
elif idl_type.bindata_subtype is not None:
ctxt.add_bad_bson_bindata_subtype_error(idl_type, syntax_type, idl_type.name, bson_type)
return True
def _validate_bson_types_list(ctxt, idl_type, syntax_type):
# type: (errors.ParserContext, Union[syntax.Type, ast.Type], str) -> bool
"""Validate bson serialization type(s) is correct for a type."""
bson_types = idl_type.bson_serialization_type
if len(bson_types) == 1:
return _validate_single_bson_type(ctxt, idl_type, syntax_type)
for bson_type in bson_types:
if bson_type in ["any", "chain"]:
ctxt.add_bad_any_type_use_error(idl_type, bson_type, syntax_type, idl_type.name)
return False
if not bson.is_valid_bson_type(bson_type):
ctxt.add_bad_bson_type_error(idl_type, syntax_type, idl_type.name, bson_type)
return False
if not isinstance(idl_type, syntax.VariantType):
if bson_type == "bindata":
ctxt.add_bad_bson_type_error(idl_type, syntax_type, idl_type.name, bson_type)
return False
# Cannot mix non-scalar types into the list of types
if not bson.is_scalar_bson_type(bson_type):
ctxt.add_bad_bson_scalar_type_error(idl_type, syntax_type, idl_type.name, bson_type)
return False
return True
def _validate_type(ctxt, idl_type):
# type: (errors.ParserContext, syntax.Type) -> None
"""Validate each type is correct."""
# Validate naming restrictions
if idl_type.name.startswith("array<"):
ctxt.add_array_not_valid_error(idl_type, "type", idl_type.name)
_validate_type_properties(ctxt, idl_type, 'type')
def _validate_cpp_type(ctxt, idl_type, syntax_type):
# type: (errors.ParserContext, Union[syntax.Type, ast.Type], str) -> None
"""Validate the cpp_type is correct."""
# Validate cpp_type
# Do not allow StringData, use std::string instead.
if "StringData" in idl_type.cpp_type:
ctxt.add_no_string_data_error(idl_type, syntax_type, idl_type.name)
# We do not support C++ char and float types for style reasons
if idl_type.cpp_type in ['char', 'wchar_t', 'char16_t', 'char32_t', 'float']:
ctxt.add_bad_cpp_numeric_type_use_error(idl_type, syntax_type, idl_type.name,
idl_type.cpp_type)
# We do not support C++ builtin integer for style reasons
for numeric_word in ['signed', "unsigned", "int", "long", "short"]:
if re.search(r'\b%s\b' % (numeric_word), idl_type.cpp_type):
ctxt.add_bad_cpp_numeric_type_use_error(idl_type, syntax_type, idl_type.name,
idl_type.cpp_type)
# Return early so we only throw one error for types like "signed short int"
return
# Check for std fixed integer types which are allowed
if idl_type.cpp_type in ["std::int32_t", "std::int64_t", "std::uint32_t", "std::uint64_t"]:
return
# Only allow 16-byte arrays since they are for MD5 and UUID
if idl_type.cpp_type.replace(" ", "") == "std::array<std::uint8_t,16>":
return
# Support vector for variable length BinData.
if idl_type.cpp_type == "std::vector<std::uint8_t>":
return
# Support variant for writeConcernW.
if idl_type.cpp_type == "stdx::variant<std::string, std::int64_t>":
return
# Check for std fixed integer types which are not allowed. These are not allowed even if they
# have the "std::" prefix.
for std_numeric_type in [
"int8_t", "int16_t", "int32_t", "int64_t", "uint8_t", "uint16_t", "uint32_t", "uint64_t"
]:
if std_numeric_type in idl_type.cpp_type:
ctxt.add_bad_cpp_numeric_type_use_error(idl_type, syntax_type, idl_type.name,
idl_type.cpp_type)
return
def _validate_chain_type_properties(ctxt, idl_type, syntax_type):
# type: (errors.ParserContext, Union[syntax.Type, ast.Type], str) -> None
"""Validate a chained type has both a deserializer and serializer."""
assert len(
idl_type.bson_serialization_type) == 1 and idl_type.bson_serialization_type[0] == 'chain'
if idl_type.deserializer is None:
ctxt.add_missing_ast_required_field_error(idl_type, syntax_type, idl_type.name,
"deserializer")
if idl_type.serializer is None:
ctxt.add_missing_ast_required_field_error(idl_type, syntax_type, idl_type.name,
"serializer")
def _validate_type_properties(ctxt, idl_type, syntax_type):
# type: (errors.ParserContext, Union[syntax.Type, ast.Type], str) -> None
# pylint: disable=too-many-branches
"""Validate each type is correct."""
# Validate bson type restrictions
if not _validate_bson_types_list(ctxt, idl_type, syntax_type):
return
if len(idl_type.bson_serialization_type) == 1:
bson_type = idl_type.bson_serialization_type[0]
if bson_type == "any":
# For 'any', a deserializer is required but the user can try to get away with the default
# serialization for their C++ type.
if idl_type.deserializer is None:
ctxt.add_missing_ast_required_field_error(idl_type, syntax_type, idl_type.name,
"deserializer")
elif bson_type == "chain":
_validate_chain_type_properties(ctxt, idl_type, syntax_type)
elif bson_type == "string":
# Strings support custom serialization unlike other non-object scalar types
if idl_type.deserializer is None:
ctxt.add_missing_ast_required_field_error(idl_type, syntax_type, idl_type.name,
"deserializer")
elif not bson_type in ["array", "object", "bindata"]:
if idl_type.deserializer is None:
ctxt.add_missing_ast_required_field_error(idl_type, syntax_type, idl_type.name,
"deserializer")
if idl_type.deserializer is not None and "BSONElement" not in idl_type.deserializer:
ctxt.add_not_custom_scalar_serialization_not_supported_error(
idl_type, syntax_type, idl_type.name, bson_type)
if idl_type.serializer is not None:
ctxt.add_not_custom_scalar_serialization_not_supported_error(
idl_type, syntax_type, idl_type.name, bson_type)
if bson_type == "bindata" and isinstance(idl_type, syntax.Type) and idl_type.default:
ctxt.add_bindata_no_default(idl_type, syntax_type, idl_type.name)
else:
# Now, this is a list of scalar types
if idl_type.deserializer is None:
ctxt.add_missing_ast_required_field_error(idl_type, syntax_type, idl_type.name,
"deserializer")
_validate_cpp_type(ctxt, idl_type, syntax_type)
def _validate_types(ctxt, parsed_spec):
# type: (errors.ParserContext, syntax.IDLSpec) -> None
"""Validate all types are correct."""
for idl_type in parsed_spec.symbols.types:
_validate_type(ctxt, idl_type)
def _is_duplicate_field(ctxt, field_container, fields, ast_field):
# type: (errors.ParserContext, str, List[ast.Field], ast.Field) -> bool
"""Return True if there is a naming conflict for a given field."""
# This is normally tested in the parser as part of duplicate detection in a map
if ast_field.name in [field.name for field in fields]:
for field in fields:
if field.name == ast_field.name:
duplicate_field = field
ctxt.add_duplicate_field_error(ast_field, field_container, ast_field.name, duplicate_field)
return True
return False
def _get_struct_qualified_cpp_name(struct):
# type: (syntax.Struct) -> str
return common.qualify_cpp_name(struct.cpp_namespace,
common.title_case(struct.cpp_name or struct.name))
def _bind_struct_common(ctxt, parsed_spec, struct, ast_struct):
# type: (errors.ParserContext, syntax.IDLSpec, syntax.Struct, ast.Struct) -> None
# pylint: disable=too-many-branches
ast_struct.name = struct.name
ast_struct.description = struct.description
ast_struct.strict = struct.strict
ast_struct.immutable = struct.immutable
ast_struct.inline_chained_structs = struct.inline_chained_structs
ast_struct.generate_comparison_operators = struct.generate_comparison_operators
ast_struct.cpp_validator_func = struct.cpp_validator_func
ast_struct.cpp_name = struct.cpp_name or struct.name
ast_struct.qualified_cpp_name = _get_struct_qualified_cpp_name(struct)
ast_struct.allow_global_collection_name = struct.allow_global_collection_name
ast_struct.non_const_getter = struct.non_const_getter
# Validate naming restrictions
if ast_struct.name.startswith("array<"):
ctxt.add_array_not_valid_error(ast_struct, "struct", ast_struct.name)
# Merge chained types as chained fields
if struct.chained_types:
if ast_struct.strict:
ctxt.add_chained_type_no_strict_error(ast_struct, ast_struct.name)
for chained_type in struct.chained_types:
ast_field = _bind_chained_type(ctxt, parsed_spec, ast_struct, chained_type)
if ast_field and not _is_duplicate_field(ctxt, chained_type.name, ast_struct.fields,
ast_field):
ast_struct.fields.append(ast_field)
# Merge chained structs as a chained struct and ignored fields
for chained_struct in struct.chained_structs or []:
_bind_chained_struct(ctxt, parsed_spec, ast_struct, chained_struct)
# Parse the fields last so that they are serialized after chained stuff.
for field in struct.fields or []:
ast_field = _bind_field(ctxt, parsed_spec, field)
if ast_field:
if ast_field.supports_doc_sequence and not isinstance(ast_struct, ast.Command):
# Doc sequences are only supported in commands at the moment
ctxt.add_bad_struct_field_as_doc_sequence_error(ast_struct, ast_struct.name,
ast_field.name)
if ast_field.non_const_getter and struct.immutable:
ctxt.add_bad_field_non_const_getter_in_immutable_struct_error(
ast_struct, ast_struct.name, ast_field.name)
if not _is_duplicate_field(ctxt, ast_struct.name, ast_struct.fields, ast_field):
ast_struct.fields.append(ast_field)
# Fill out the field comparison_order property as needed
if ast_struct.generate_comparison_operators and ast_struct.fields:
# If the user did not specify an ordering of fields, then number all fields in
# declared field.
use_default_order = True
comparison_orders = set() # type: Set[int]
for ast_field in ast_struct.fields:
if not ast_field.comparison_order == -1:
use_default_order = False
if ast_field.comparison_order in comparison_orders:
ctxt.add_duplicate_comparison_order_field_error(ast_struct, ast_struct.name,
ast_field.comparison_order)
comparison_orders.add(ast_field.comparison_order)
if use_default_order:
pos = 0
for ast_field in ast_struct.fields:
ast_field.comparison_order = pos
pos += 1
def _bind_struct(ctxt, parsed_spec, struct):
# type: (errors.ParserContext, syntax.IDLSpec, syntax.Struct) -> ast.Struct
"""
Bind a struct.
- Validating a struct and fields.
- Create the idl.ast version from the idl.syntax tree.
"""
ast_struct = ast.Struct(struct.file_name, struct.line, struct.column)
_bind_struct_common(ctxt, parsed_spec, struct, ast_struct)
return ast_struct
def _bind_field_list_entry(field_list_entry):
# type: (syntax.FieldListEntry) -> ast.FieldListEntry
"""Bind a generic argument or reply field list entry."""
ast_entry = ast.FieldListEntry(field_list_entry.file_name, field_list_entry.line,
field_list_entry.column)
ast_entry.name = field_list_entry.name
ast_entry.forward_to_shards = field_list_entry.forward_to_shards
ast_entry.forward_from_shards = field_list_entry.forward_from_shards
return ast_entry
ASTFieldListBaseClass = TypeVar("ASTFieldListBaseClass", bound=ast.FieldListBase, covariant=True)
def _bind_field_list(field_list, ast_class):
# type: (syntax.FieldListBase, Type[ASTFieldListBaseClass]) -> ASTFieldListBaseClass
"""Bind a generic argument or reply field list (helper method).
The ast_class param must be a subclass of ast.FieldListBase. The returned value is an
instance of ast_class.
"""
ast_field_list = ast_class(field_list.file_name, field_list.line, field_list.column)
ast_field_list.description = field_list.description
ast_field_list.cpp_name = field_list.name
if field_list.cpp_name:
ast_field_list.cpp_name = field_list.cpp_name
return ast_field_list
def _bind_generic_argument_list(field_list):
# type: (syntax.GenericArgumentList) -> ast.GenericArgumentList
"""Bind a generic argument list."""
ast_field_list = _bind_field_list(field_list, ast.GenericArgumentList)
ast_field_list.fields = [_bind_field_list_entry(f) for f in field_list.fields]
return ast_field_list
def _bind_generic_reply_field_list(field_list):
# type: (syntax.GenericReplyFieldList) -> ast.GenericReplyFieldList
"""Bind a generic reply field list."""
ast_field_list = _bind_field_list(field_list, ast.GenericReplyFieldList)
ast_field_list.fields = [_bind_field_list_entry(f) for f in field_list.fields]
return ast_field_list
def _inject_hidden_command_fields(command):
# type: (syntax.Command) -> None
"""Inject hidden fields to aid deserialization/serialization for OpMsg parsing of commands."""
# Inject a "$db" which we can decode during command parsing
db_field = syntax.Field(command.file_name, command.line, command.column)
db_field.name = "$db"
db_field.type = syntax.FieldTypeSingle(command.file_name, command.line, command.column)
db_field.type.type_name = "string" # This comes from basic_types.idl
db_field.cpp_name = "dbName"
db_field.serialize_op_msg_request_only = True
# Commands that require namespaces do not need to have db defaulted in the constructor
if command.namespace == common.COMMAND_NAMESPACE_CONCATENATE_WITH_DB:
db_field.constructed = True
command.fields.append(db_field)
# Inject "$tenant" for use by cluster administrators overriding tenant in multitenancy.
tenant_field = syntax.Field(command.file_name, command.line, command.column)
tenant_field.name = "$tenant"
tenant_field.type = syntax.FieldTypeSingle(command.file_name, command.line, command.column)
tenant_field.type.type_name = "tenant_id" # This comes from basic_types.idl
tenant_field.cpp_name = "dollarTenant"
tenant_field.optional = True
# The $tenant field should be injected when serializing to OpMsgRequest and to
# BSONObjBuilder if it exists.
tenant_field.serialize_op_msg_request_only = False
command.fields.append(tenant_field)
def _bind_struct_type(struct):
# type: (syntax.Struct) -> ast.Type
# Use Type to represent a struct-type field. (The Struct class is to generate a C++ class, not
# represent a field's type.)
ast_type = ast.Type(struct.file_name, struct.line, struct.column)
ast_type.is_struct = True
ast_type.name = struct.name
ast_type.cpp_type = _get_struct_qualified_cpp_name(struct)
ast_type.bson_serialization_type = ["object"]
return ast_type
def _bind_struct_field(ctxt, ast_field, idl_type):
# type: (errors.ParserContext, ast.Field, Union[syntax.Enum, syntax.Struct, syntax.Type]) -> None
# The signature includes Enum to match SymbolTable.resolve_field_type, but it's not allowed.
assert not isinstance(idl_type, syntax.Enum)
if isinstance(idl_type, syntax.Struct):
struct = cast(syntax.Struct, idl_type)
else:
assert isinstance(idl_type, syntax.ArrayType)
array = cast(syntax.ArrayType, idl_type)
assert isinstance(array.element_type, syntax.Struct)
struct = cast(syntax.Struct, array.element_type)
ast_field.type = _bind_struct_type(struct)
ast_field.type.is_array = isinstance(idl_type, syntax.ArrayType)
_validate_default_of_type_struct(ctxt, ast_field)
def _bind_variant_field(ctxt, ast_field, idl_type):
# type: (errors.ParserContext, ast.Field, syntax.VariantType) -> None
ast_field.type = _bind_type(idl_type)
ast_field.type.is_variant = True
_validate_bson_types_list(ctxt, idl_type, "field")
for alternative in idl_type.variant_types:
ast_alternative = _bind_type(alternative)
ast_field.type.variant_types.append(ast_alternative)
if idl_type.variant_struct_type:
ast_field.type.variant_struct_type = _bind_struct_type(idl_type.variant_struct_type)
def gen_cpp_types():
for alternative in ast_field.type.variant_types:
if alternative.is_array:
yield f'std::vector<{alternative.cpp_type}>'
else:
yield alternative.cpp_type
if ast_field.type.variant_struct_type:
yield ast_field.type.variant_struct_type.cpp_type
ast_field.type.cpp_type = f'stdx::variant<{", ".join(gen_cpp_types())}>'
# Validation doc_sequence types
_validate_doc_sequence_field(ctxt, ast_field)
def _bind_command_type(ctxt, parsed_spec, command):
# type: (errors.ParserContext, syntax.IDLSpec, syntax.Command) -> ast.Field
"""Bind the type field in a command as the first field."""
# pylint: disable=too-many-branches,too-many-statements
ast_field = ast.Field(command.file_name, command.line, command.column)
ast_field.name = command.name
ast_field.description = command.description
ast_field.optional = False
ast_field.supports_doc_sequence = False
ast_field.serialize_op_msg_request_only = False
ast_field.constructed = False
ast_field.cpp_name = "CommandParameter"
# Validate naming restrictions
if ast_field.name.startswith("array<"):
ctxt.add_array_not_valid_error(ast_field, "field", ast_field.name)
# Resolve the command type as a field
syntax_symbol = parsed_spec.symbols.resolve_field_type(ctxt, command, command.name,
command.type)
if syntax_symbol is None:
return None
if isinstance(syntax_symbol, syntax.Command):
ctxt.add_bad_command_as_field_error(ast_field, command.type.debug_string())
return None
assert not isinstance(syntax_symbol, syntax.Enum)
base_type = (syntax_symbol.element_type
if isinstance(syntax_symbol, syntax.ArrayType) else syntax_symbol)
# Copy over only the needed information if this is a struct or a type.
if isinstance(base_type, syntax.Struct):
_bind_struct_field(ctxt, ast_field, syntax_symbol)
elif isinstance(base_type, syntax.VariantType):
# Arrays of variants aren't supported for now.
assert isinstance(syntax_symbol, syntax.VariantType)
_bind_variant_field(ctxt, ast_field, cast(syntax.VariantType, syntax_symbol))
else:
assert isinstance(base_type, syntax.Type)
idltype = cast(syntax.Type, base_type)
ast_field.type = _bind_type(idltype)
ast_field.type.is_array = isinstance(syntax_symbol, syntax.ArrayType)
ast_field.default = idltype.default
# Validate merged type
_validate_type_properties(ctxt, ast_field.type, "command.type")
# Validate merged type
_validate_field_properties(ctxt, ast_field)
return ast_field
def _bind_command_reply_type(ctxt, parsed_spec, command):
# type: (errors.ParserContext, syntax.IDLSpec, syntax.Command) -> ast.Field
"""Bind the reply_type field in a command."""
ast_field = ast.Field(command.file_name, command.line, command.column)
ast_field.name = "replyType"
ast_field.description = f"{command.name} reply type"
# Resolve the command type as a field
syntax_symbol = parsed_spec.symbols.resolve_type_from_name(ctxt, command, command.name,
command.reply_type)
if syntax_symbol is None:
# Resolution failed, we've recorded an error.
return None
if not isinstance(syntax_symbol, syntax.Struct):
ctxt.add_reply_type_invalid_type(ast_field, command.name, command.reply_type)
else:
ast_field.type = _bind_struct_type(syntax_symbol)
return ast_field
def resolve_enum_value(ctxt, location, syntax_enum, name):
# type: (errors.ParserContext, common.SourceLocation, syntax.Enum, str) -> syntax.EnumValue
"""Resolve a single enum value in an enum."""
for value in syntax_enum.values:
if value.value == name:
return value
ctxt.add_unknown_enum_value(location, syntax_enum.name, name)
return None
def _bind_enum_value(ctxt, parsed_spec, location, enum_name, enum_value):
# type: (errors.ParserContext, syntax.IDLSpec, common.SourceLocation, str, str) -> str
# Look up the enum for "enum_name" in the symbol table
access_check_enum = parsed_spec.symbols.resolve_type_from_name(ctxt, location, "access_check",
enum_name)
if access_check_enum is None:
# Resolution failed, we've recorded an error.
return None
if not isinstance(access_check_enum, syntax.Enum):
ctxt.add_unknown_type_error(location, enum_name, "enum")
return None
syntax_enum = resolve_enum_value(ctxt, location, cast(syntax.Enum, access_check_enum),
enum_value)
if not syntax_enum:
return None
return syntax_enum.name
def _bind_single_check(ctxt, parsed_spec, access_check):
# type: (errors.ParserContext, syntax.IDLSpec, syntax.AccessCheck) -> ast.AccessCheck
"""Bind a single access_check."""
ast_access_check = ast.AccessCheck(access_check.file_name, access_check.line,
access_check.column)
assert bool(access_check.check) != bool(access_check.privilege)
if access_check.check:
ast_access_check.check = _bind_enum_value(ctxt, parsed_spec, access_check, "AccessCheck",
access_check.check)
if not ast_access_check.check:
return None
else:
privilege = access_check.privilege
ast_privilege = ast.Privilege(privilege.file_name, privilege.line, privilege.column)
ast_privilege.resource_pattern = _bind_enum_value(ctxt, parsed_spec, privilege, "MatchType",
privilege.resource_pattern)
if not ast_privilege.resource_pattern:
return None
ast_privilege.action_type = []
at_names = []
for at in privilege.action_type:
at_names.append(at)
bound_at = _bind_enum_value(ctxt, parsed_spec, privilege, "ActionType", at)
if not bound_at:
return None
ast_privilege.action_type.append(bound_at)
at_names_set = set(at_names)
if len(at_names_set) != len(at_names):
for name in at_names_set:
if at_names.count(name) > 1:
ctxt.add_duplicate_action_types(ast_privilege, name)
return None
ast_access_check.privilege = ast_privilege
return ast_access_check
def _validate_check_uniqueness(ctxt, access_checks):
# type: (errors.ParserContext, List[ast.AccessCheck]) -> bool
"""Validate there is no duplication among checks."""
checks_set = set()
for ac in access_checks:
if not ac.check:
continue
if ac.check in checks_set:
ctxt.add_duplicate_access_check(ac, ac.check)
return False
checks_set.add(ac.check)
privs_set = set()
for ac in access_checks:
if not ac.privilege:
continue
priv = ac.privilege
# Produce pairs of resource_pattern and action type, then de-dup them
for at in priv.action_type:
priv_tuple = (priv.resource_pattern, at)
if priv_tuple in privs_set:
ctxt.add_duplicate_access_check(ac, ac.check)
return False
privs_set.add(priv_tuple)
return True
def _bind_access_check(ctxt, parsed_spec, command):
# type: (errors.ParserContext, syntax.IDLSpec, syntax.Command) -> Optional[List[ast.AccessCheck]]
"""Bind the access_check field in a command."""
# pylint: disable=too-many-return-statements
if not command.access_check:
return None
access_check = command.access_check
if access_check.none:
return []
if access_check.simple:
ast_access_check = _bind_single_check(ctxt, parsed_spec, access_check.simple)
if not ast_access_check:
return None
return [ast_access_check]
if access_check.complex:
checks = [] # List[ast.AccessCheck]
for ac in access_check.complex:
ast_access_check = _bind_single_check(ctxt, parsed_spec, ac)
if not ast_access_check:
return None
checks.append(ast_access_check)
if not _validate_check_uniqueness(ctxt, checks):
return None
return checks
return None
def _bind_command(ctxt, parsed_spec, command):
# type: (errors.ParserContext, syntax.IDLSpec, syntax.Command) -> ast.Command
"""
Bind a command.
- Validating a command and fields.
- Create the idl.ast version from the idl.syntax tree.
"""
ast_command = ast.Command(command.file_name, command.line, command.column)
ast_command.api_version = command.api_version
ast_command.is_deprecated = command.is_deprecated
ast_command.command_name = command.command_name
ast_command.command_alias = command.command_alias
# Inject special fields used for command parsing
_inject_hidden_command_fields(command)
_bind_struct_common(ctxt, parsed_spec, command, ast_command)
ast_command.access_checks = _bind_access_check(ctxt, parsed_spec, command)
if command.api_version != "" and command.access_check is None:
ctxt.add_missing_access_check(ast_command, ast_command.name)
ast_command.namespace = command.namespace
if command.type:
ast_command.command_field = _bind_command_type(ctxt, parsed_spec, command)
if command.reply_type:
ast_command.reply_type = _bind_command_reply_type(ctxt, parsed_spec, command)
if [field for field in ast_command.fields if field.name == ast_command.name]:
ctxt.add_bad_command_name_duplicates_field(ast_command, ast_command.name)
return ast_command
def _validate_ignored_field(ctxt, field):
# type: (errors.ParserContext, syntax.Field) -> None
"""Validate that for ignored fields, no other properties are set."""
if field.optional:
ctxt.add_ignored_field_must_be_empty_error(field, field.name, "optional")
if field.default is not None:
ctxt.add_ignored_field_must_be_empty_error(field, field.name, "default")
def _validate_default_of_type_struct(ctxt, field):
# type: (errors.ParserContext, Union[syntax.Field, ast.Field]) -> None
"""Validate that for fields with a type of struct, the only default permitted is true, which causes it to be default-constructed."""
if (field.default is not None) and (field.default != "true"):
ctxt.add_struct_default_must_be_true_or_empty_error(field, field.name)
def _validate_variant_type(ctxt, syntax_symbol, field):
# type: (errors.ParserContext, syntax.VariantType, syntax.Field) -> None
# pylint: disable=unused-argument
"""Validate that this field is a proper variant type."""
# Check for duplicate BSON serialization types.
type_count: typing.Counter[str] = collections.Counter()
array_type_count: typing.Counter[str] = collections.Counter()
def add_to_count(counter, bson_serialization_type):
# type: (typing.Counter[str], List[str]) -> None
for the_type in bson_serialization_type:
counter[the_type] += 1
for alternative in syntax_symbol.variant_types:
# Impossible: there's no IDL syntax for expressing nested variants.
assert not isinstance(alternative, syntax.VariantType), "Nested variant types"
if isinstance(alternative, syntax.ArrayType):
if isinstance(alternative.element_type, syntax.Type):
element_type = cast(syntax.Type, alternative.element_type)
add_to_count(array_type_count, element_type.bson_serialization_type)
else:
assert isinstance(alternative.element_type, syntax.Struct)
add_to_count(array_type_count, ["object"])
else:
add_to_count(type_count, alternative.bson_serialization_type)
if syntax_symbol.variant_struct_type:
type_count["object"] += 1
for type_name, count in type_count.items():
if count > 1:
ctxt.add_variant_duplicate_types_error(syntax_symbol, field.name, type_name)
for type_name, count in array_type_count.items():
if count > 1:
ctxt.add_variant_duplicate_types_error(syntax_symbol, field.name, f'array<{type_name}>')
types = len(syntax_symbol.variant_types) + (1 if syntax_symbol.variant_struct_type else 0)
if types < 2:
ctxt.add_useless_variant_error(syntax_symbol)
def _validate_array_type(ctxt, syntax_symbol, field):
# type: (errors.ParserContext, syntax.ArrayType, syntax.Field) -> None
"""Validate this an array of plain objects or a struct."""
elem_type = syntax_symbol.element_type
if field.default or isinstance(elem_type, syntax.Type) and elem_type.default:
ctxt.add_array_no_default_error(field, field.name)
def _validate_field_properties(ctxt, ast_field):
# type: (errors.ParserContext, ast.Field) -> None
"""Validate field specific rules."""
if ast_field.default:
if ast_field.optional:
ctxt.add_bad_field_default_and_optional(ast_field, ast_field.name)
if ast_field.type.bson_serialization_type == ['bindata']:
ctxt.add_bindata_no_default(ast_field, ast_field.type.name, ast_field.name)
if ast_field.always_serialize and not ast_field.optional:
ctxt.add_bad_field_always_serialize_not_optional(ast_field, ast_field.name)
# A "chain" type should never appear as a field.
if ast_field.type.bson_serialization_type == ['chain']:
ctxt.add_bad_array_of_chain(ast_field, ast_field.name)
def _validate_doc_sequence_field(ctxt, ast_field):
# type: (errors.ParserContext, ast.Field) -> None
"""Validate the doc_sequence is an array of plain objects."""
if not ast_field.supports_doc_sequence:
return
assert ast_field.type.is_array
# The only allowed BSON type for a doc_sequence field is "object"
if ast_field.type.bson_serialization_type != ['object']:
ctxt.add_bad_non_object_as_doc_sequence_error(ast_field, ast_field.name)
def _normalize_method_name(cpp_type_name, cpp_method_name):
# type: (str, str) -> str
"""Normalize the method name to be fully-qualified with the type name."""
# Default deserializer
if not cpp_method_name:
return cpp_method_name
# Global function
if cpp_method_name.startswith('::'):
return cpp_method_name
# Method is full qualified already
if cpp_method_name.startswith(cpp_type_name):
return cpp_method_name
# Get the unqualified type name
type_name = cpp_type_name.split("::")[-1]
# Method is prefixed with just the type name
if cpp_method_name.startswith(type_name):
return '::'.join(cpp_type_name.split('::')[0:-1]) + "::" + cpp_method_name
return cpp_method_name
def _bind_expression(expr, allow_literal_string=True):
# type: (syntax.Expression, bool) -> ast.Expression
"""Bind an expression."""
node = ast.Expression(expr.file_name, expr.line, expr.column)
if expr.literal is None:
node.expr = expr.expr
node.validate_constexpr = expr.is_constexpr
node.export = expr.is_constexpr
return node
node.validate_constexpr = False
node.export = True
# bool
if (expr.literal == "true") or (expr.literal == "false"):
node.expr = expr.literal
return node
# int32_t
try:
intval = int(expr.literal)
if intval >= -0x80000000 and intval <= 0x7FFFFFFF: # pylint: disable=chained-comparison
node.expr = repr(intval)
return node
except ValueError:
pass
# float
try:
node.expr = repr(float(expr.literal))
return node
except ValueError:
pass
# std::string
if allow_literal_string:
strval = expr.literal
for i in ['\\', '"', "'"]:
if i in strval:
strval = strval.replace(i, '\\' + i)
node.expr = '"' + strval + '"'
return node
# Unable to bind expression.
return None
def _bind_validator(ctxt, validator):
# type: (errors.ParserContext, syntax.Validator) -> ast.Validator
"""Bind a validator from the idl.syntax tree."""
ast_validator = ast.Validator(validator.file_name, validator.line, validator.column)
# Parse syntax value as numeric if possible.
for pred in ["gt", "lt", "gte", "lte"]:
src = getattr(validator, pred)
if src is None:
continue
dest = _bind_expression(src, allow_literal_string=False)
if dest is None:
# This only happens if we have a non-numeric literal.
ctxt.add_value_not_numeric_error(ast_validator, pred, src)
return None
setattr(ast_validator, pred, dest)
ast_validator.callback = validator.callback
return ast_validator
def _bind_condition(condition):
# type: (syntax.Condition) -> ast.Condition
"""Bind a condition from the idl.syntax tree."""
if not condition:
return None
ast_condition = ast.Condition(condition.file_name, condition.line, condition.column)
ast_condition.expr = condition.expr
ast_condition.constexpr = condition.constexpr
ast_condition.preprocessor = condition.preprocessor
return ast_condition
def _bind_type(idltype):
# type: (syntax.Type) -> ast.Type
"""Bind a type."""
if isinstance(idltype, syntax.ArrayType):
if isinstance(idltype.element_type, syntax.Struct):
ast_type = _bind_struct_type(cast(syntax.Struct, idltype.element_type))
else:
assert isinstance(idltype.element_type, syntax.Type)
ast_type = _bind_type(idltype.element_type)
ast_type.is_array = True
return ast_type
ast_type = ast.Type(idltype.file_name, idltype.line, idltype.column)
ast_type.name = idltype.name
ast_type.cpp_type = idltype.cpp_type
ast_type.bson_serialization_type = idltype.bson_serialization_type
ast_type.bindata_subtype = idltype.bindata_subtype
ast_type.serializer = _normalize_method_name(idltype.cpp_type, idltype.serializer)
ast_type.deserializer = _normalize_method_name(idltype.cpp_type, idltype.deserializer)
return ast_type
def _bind_field(ctxt, parsed_spec, field):
# type: (errors.ParserContext, syntax.IDLSpec, syntax.Field) -> ast.Field
"""
Bind a field from the idl.syntax tree.
- Create the idl.ast version from the idl.syntax tree.
- Validate the resulting type is correct.
"""
# pylint: disable=too-many-branches,too-many-statements
ast_field = ast.Field(field.file_name, field.line, field.column)
ast_field.name = field.name
ast_field.description = field.description
ast_field.optional = field.optional