/
expression_parser.cpp
2045 lines (1777 loc) · 82.3 KB
/
expression_parser.cpp
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
// expression_parser.cpp
/**
* Copyright (C) 2013 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* 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 GNU Affero General 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.
*/
#include "mongo/platform/basic.h"
#include "mongo/db/matcher/expression_parser.h"
#include <boost/container/flat_set.hpp>
#include <pcrecpp.h>
#include "mongo/base/init.h"
#include "mongo/bson/bsonmisc.h"
#include "mongo/bson/bsonobj.h"
#include "mongo/bson/bsonobjbuilder.h"
#include "mongo/db/matcher/expression_always_boolean.h"
#include "mongo/db/matcher/expression_array.h"
#include "mongo/db/matcher/expression_expr.h"
#include "mongo/db/matcher/expression_geo.h"
#include "mongo/db/matcher/expression_leaf.h"
#include "mongo/db/matcher/expression_tree.h"
#include "mongo/db/matcher/expression_type.h"
#include "mongo/db/matcher/expression_with_placeholder.h"
#include "mongo/db/matcher/schema/expression_internal_schema_all_elem_match_from_index.h"
#include "mongo/db/matcher/schema/expression_internal_schema_allowed_properties.h"
#include "mongo/db/matcher/schema/expression_internal_schema_cond.h"
#include "mongo/db/matcher/schema/expression_internal_schema_eq.h"
#include "mongo/db/matcher/schema/expression_internal_schema_fmod.h"
#include "mongo/db/matcher/schema/expression_internal_schema_match_array_index.h"
#include "mongo/db/matcher/schema/expression_internal_schema_max_items.h"
#include "mongo/db/matcher/schema/expression_internal_schema_max_length.h"
#include "mongo/db/matcher/schema/expression_internal_schema_max_properties.h"
#include "mongo/db/matcher/schema/expression_internal_schema_min_items.h"
#include "mongo/db/matcher/schema/expression_internal_schema_min_length.h"
#include "mongo/db/matcher/schema/expression_internal_schema_min_properties.h"
#include "mongo/db/matcher/schema/expression_internal_schema_object_match.h"
#include "mongo/db/matcher/schema/expression_internal_schema_root_doc_eq.h"
#include "mongo/db/matcher/schema/expression_internal_schema_unique_items.h"
#include "mongo/db/matcher/schema/expression_internal_schema_xor.h"
#include "mongo/db/matcher/schema/json_schema_parser.h"
#include "mongo/db/namespace_string.h"
#include "mongo/db/query/query_knobs.h"
#include "mongo/stdx/memory.h"
#include "mongo/util/mongoutils/str.h"
#include "mongo/util/string_map.h"
namespace {
using namespace mongo;
/**
* Returns true if subtree contains MatchExpression 'type'.
*/
bool hasNode(const MatchExpression* root, MatchExpression::MatchType type) {
if (type == root->matchType()) {
return true;
}
for (size_t i = 0; i < root->numChildren(); ++i) {
if (hasNode(root->getChild(i), type)) {
return true;
}
}
return false;
}
} // namespace
namespace mongo {
constexpr StringData AlwaysFalseMatchExpression::kName;
constexpr StringData AlwaysTrueMatchExpression::kName;
constexpr StringData OrMatchExpression::kName;
constexpr StringData AndMatchExpression::kName;
constexpr StringData NorMatchExpression::kName;
const double MatchExpressionParser::kLongLongMaxPlusOneAsDouble =
scalbn(1, std::numeric_limits<long long>::digits);
/**
* 'DocumentParseLevel' refers to the current position of the parser as it descends a
* MatchExpression tree.
*/
enum class DocumentParseLevel {
// Indicates that the parser is looking at the root level of the BSON object containing the
// user's query predicate.
kPredicateTopLevel,
// Indicates that match expression nodes in this position will match against the complete
// user document, as opposed to matching against a nested document or a subdocument inside
// an array.
kUserDocumentTopLevel,
// Indicates that match expression nodes in this position will match against a nested
// document or a subdocument inside an array.
kUserSubDocument,
};
StatusWith<long long> MatchExpressionParser::parseIntegerElementToNonNegativeLong(
BSONElement elem) {
auto number = parseIntegerElementToLong(elem);
if (!number.isOK()) {
return number;
}
if (number.getValue() < 0) {
return Status(ErrorCodes::FailedToParse,
str::stream() << "Expected a positive number in: " << elem);
}
return number;
}
StatusWith<long long> MatchExpressionParser::parseIntegerElementToLong(BSONElement elem) {
if (!elem.isNumber()) {
return Status(ErrorCodes::FailedToParse, str::stream() << "Expected a number in: " << elem);
}
long long number = 0;
if (elem.type() == BSONType::NumberDouble) {
auto eDouble = elem.numberDouble();
// NaN doubles are rejected.
if (std::isnan(eDouble)) {
return Status(ErrorCodes::FailedToParse,
str::stream() << "Expected an integer, but found NaN in: " << elem);
}
// No integral doubles that are too large to be represented as a 64 bit signed integer.
// We use 'kLongLongMaxAsDouble' because if we just did eDouble > 2^63-1, it would be
// compared against 2^63. eDouble=2^63 would not get caught that way.
if (eDouble >= MatchExpressionParser::kLongLongMaxPlusOneAsDouble ||
eDouble < std::numeric_limits<long long>::min()) {
return Status(ErrorCodes::FailedToParse,
str::stream() << "Cannot represent as a 64-bit integer: " << elem);
}
// This checks if elem is an integral double.
if (eDouble != static_cast<double>(static_cast<long long>(eDouble))) {
return Status(ErrorCodes::FailedToParse,
str::stream() << "Expected an integer: " << elem);
}
number = elem.numberLong();
} else if (elem.type() == BSONType::NumberDecimal) {
uint32_t signalingFlags = Decimal128::kNoFlag;
number = elem.numberDecimal().toLongExact(&signalingFlags);
if (signalingFlags != Decimal128::kNoFlag) {
return Status(ErrorCodes::FailedToParse,
str::stream() << "Cannot represent as a 64-bit integer: " << elem);
}
} else {
number = elem.numberLong();
}
return number;
}
StatusWith<int> MatchExpressionParser::parseIntegerElementToInt(BSONElement elem) {
auto parsedLong = MatchExpressionParser::parseIntegerElementToLong(elem);
if (!parsedLong.isOK()) {
return parsedLong.getStatus();
}
auto valueLong = parsedLong.getValue();
if (valueLong < std::numeric_limits<int>::min() ||
valueLong > std::numeric_limits<int>::max()) {
return {ErrorCodes::FailedToParse,
str::stream() << "Cannot represent " << elem << " in an int"};
}
return static_cast<int>(valueLong);
}
namespace {
// Forward declarations.
Status parseSub(StringData name,
const BSONObj& sub,
AndMatchExpression* root,
const boost::intrusive_ptr<ExpressionContext>& expCtx,
const ExtensionsCallback* extensionsCallback,
MatchExpressionParser::AllowedFeatureSet allowedFeatures,
DocumentParseLevel currentLevel);
stdx::function<StatusWithMatchExpression(StringData,
BSONElement,
const boost::intrusive_ptr<ExpressionContext>&,
const ExtensionsCallback*,
MatchExpressionParser::AllowedFeatureSet,
DocumentParseLevel)>
retrievePathlessParser(StringData name);
StatusWithMatchExpression parseRegexElement(StringData name, BSONElement e) {
if (e.type() != BSONType::RegEx)
return {Status(ErrorCodes::BadValue, "not a regex")};
auto temp = stdx::make_unique<RegexMatchExpression>();
auto s = temp->init(name, e.regex(), e.regexFlags());
if (!s.isOK())
return s;
return {std::move(temp)};
}
StatusWithMatchExpression parseComparison(
StringData name,
ComparisonMatchExpression* cmp,
BSONElement e,
const boost::intrusive_ptr<ExpressionContext>& expCtx,
MatchExpressionParser::AllowedFeatureSet allowedFeatures) {
std::unique_ptr<ComparisonMatchExpression> temp(cmp);
// Non-equality comparison match expressions cannot have a regular expression as the argument.
// (e.g. {a: {$gt: /b/}} is illegal).
if (MatchExpression::EQ != cmp->matchType() && BSONType::RegEx == e.type()) {
return {Status(ErrorCodes::BadValue,
str::stream() << "Can't have RegEx as arg to predicate over field '" << name
<< "'.")};
}
auto s = temp->init(name, e);
if (!s.isOK()) {
return s;
}
temp->setCollator(expCtx->getCollator());
return {std::move(temp)};
}
/**
* DBRef fields are ordered in the collection. In the query, we consider an embedded object a query
* on a DBRef as long as it contains $ref and $id.
* Required fields: $ref and $id (if incomplete DBRefs are not allowed).
*
* If incomplete DBRefs are allowed, we accept the BSON object as long as it contains $ref, $id or
* $db.
*
* Field names are checked but not field types.
*
* { $ref: "s", $id: "x" } = true
* { $ref : "s" } = true (if incomplete DBRef is allowed)
* { $id : "x" } = true (if incomplete DBRef is allowed)
* { $db : "x" } = true (if incomplete DBRef is allowed)
*/
bool isDBRefDocument(const BSONObj& obj, bool allowIncompleteDBRef) {
bool hasRef = false;
bool hasID = false;
bool hasDB = false;
BSONObjIterator i(obj);
while (i.more() && !(hasRef && hasID)) {
auto element = i.next();
auto fieldName = element.fieldNameStringData();
// $ref
if (!hasRef && "$ref"_sd == fieldName) {
hasRef = true;
}
// $id
else if (!hasID && "$id"_sd == fieldName) {
hasID = true;
}
// $db
else if (!hasDB && "$db"_sd == fieldName) {
hasDB = true;
}
}
if (allowIncompleteDBRef) {
return hasRef || hasID || hasDB;
}
return hasRef && hasID;
}
/**
* 5 = false
* { a : 5 } = false
* { $lt : 5 } = true
* { $ref: "s", $id: "x" } = false
* { $ref: "s", $id: "x", $db: "mydb" } = false
* { $ref : "s" } = false (if incomplete DBRef is allowed)
* { $id : "x" } = false (if incomplete DBRef is allowed)
* { $db : "mydb" } = false (if incomplete DBRef is allowed)
*/
bool isExpressionDocument(BSONElement e, bool allowIncompleteDBRef) {
if (e.type() != BSONType::Object)
return false;
auto o = e.Obj();
if (o.isEmpty())
return false;
auto name = o.firstElement().fieldNameStringData();
if (name[0] != '$')
return false;
if (isDBRefDocument(o, allowIncompleteDBRef)) {
return false;
}
return true;
}
/**
* Parse 'obj' and return either a MatchExpression or an error.
*/
StatusWithMatchExpression parse(const BSONObj& obj,
const boost::intrusive_ptr<ExpressionContext>& expCtx,
const ExtensionsCallback* extensionsCallback,
MatchExpressionParser::AllowedFeatureSet allowedFeatures,
DocumentParseLevel currentLevel) {
auto root = stdx::make_unique<AndMatchExpression>();
const DocumentParseLevel nextLevel = (currentLevel == DocumentParseLevel::kPredicateTopLevel)
? DocumentParseLevel::kUserDocumentTopLevel
: currentLevel;
for (auto e : obj) {
if (e.fieldName()[0] == '$') {
auto name = e.fieldNameStringData().substr(1);
auto parseExpressionMatchFunction = retrievePathlessParser(name);
if (!parseExpressionMatchFunction) {
return {Status(ErrorCodes::BadValue,
str::stream() << "unknown top level operator: "
<< e.fieldNameStringData())};
}
auto parsedExpression = parseExpressionMatchFunction(
name, e, expCtx, extensionsCallback, allowedFeatures, currentLevel);
if (!parsedExpression.isOK()) {
return parsedExpression;
}
// A nullptr for 'parsedExpression' indicates that the particular operator should not
// be added to 'root', because it is handled outside of the MatchExpressionParser
// library. The following operators currently follow this convention:
// - $atomic is explicitly handled in CanonicalQuery::init()
// - $comment has no action associated with the operator.
// - $isolated is explicitly handled in CanoncialQuery::init()
if (parsedExpression.getValue().get()) {
root->add(parsedExpression.getValue().release());
}
continue;
}
if (isExpressionDocument(e, false)) {
auto s = parseSub(e.fieldNameStringData(),
e.Obj(),
root.get(),
expCtx,
extensionsCallback,
allowedFeatures,
nextLevel);
if (!s.isOK())
return s;
continue;
}
if (e.type() == BSONType::RegEx) {
auto result = parseRegexElement(e.fieldNameStringData(), e);
if (!result.isOK())
return result;
root->add(result.getValue().release());
continue;
}
auto eq = parseComparison(
e.fieldNameStringData(), new EqualityMatchExpression(), e, expCtx, allowedFeatures);
if (!eq.isOK())
return eq;
root->add(eq.getValue().release());
}
if (root->numChildren() == 1) {
std::unique_ptr<MatchExpression> real(root->getChild(0));
root->clearAndRelease();
return {std::move(real)};
}
return {std::move(root)};
}
StatusWithMatchExpression parseAtomicOrIsolated(
StringData name,
BSONElement elem,
const boost::intrusive_ptr<ExpressionContext>& expCtx,
const ExtensionsCallback* extensionsCallback,
MatchExpressionParser::AllowedFeatureSet allowedFeatures,
DocumentParseLevel currentLevel) {
if ((allowedFeatures & MatchExpressionParser::AllowedFeatures::kIsolated) == 0u) {
return {Status(ErrorCodes::QueryFeatureNotAllowed,
"$isolated ($atomic) is not allowed in this context")};
}
if (currentLevel != DocumentParseLevel::kPredicateTopLevel) {
return {
Status(ErrorCodes::FailedToParse, "$isolated ($atomic) has to be at the top level")};
}
return {nullptr};
}
StatusWithMatchExpression parseComment(StringData name,
BSONElement elem,
const boost::intrusive_ptr<ExpressionContext>& expCtx,
const ExtensionsCallback* extensionsCallback,
MatchExpressionParser::AllowedFeatureSet allowedFeatures,
DocumentParseLevel currentLevel) {
return {nullptr};
}
StatusWithMatchExpression parseWhere(StringData name,
BSONElement elem,
const boost::intrusive_ptr<ExpressionContext>& expCtx,
const ExtensionsCallback* extensionsCallback,
MatchExpressionParser::AllowedFeatureSet allowedFeatures,
DocumentParseLevel currentLevel) {
if ((allowedFeatures & MatchExpressionParser::AllowedFeatures::kJavascript) == 0u) {
return {Status(ErrorCodes::BadValue, "$where is not allowed in this context")};
}
return extensionsCallback->parseWhere(elem);
}
StatusWithMatchExpression parseText(StringData name,
BSONElement elem,
const boost::intrusive_ptr<ExpressionContext>& expCtx,
const ExtensionsCallback* extensionsCallback,
MatchExpressionParser::AllowedFeatureSet allowedFeatures,
DocumentParseLevel currentLevel) {
if ((allowedFeatures & MatchExpressionParser::AllowedFeatures::kText) == 0u) {
return {Status(ErrorCodes::BadValue, "$text is not allowed in this context")};
}
return extensionsCallback->parseText(elem);
}
StatusWithMatchExpression parseDBRef(StringData name,
BSONElement elem,
const boost::intrusive_ptr<ExpressionContext>& expCtx,
const ExtensionsCallback* extensionsCallback,
MatchExpressionParser::AllowedFeatureSet allowedFeatures,
DocumentParseLevel currentLevel) {
auto eq = stdx::make_unique<EqualityMatchExpression>();
auto s = eq->init(elem.fieldName(), elem);
if (!s.isOK()) {
return s;
}
// 'id' is collation-aware. 'ref' and 'db' are compared using binary comparison.
eq->setCollator("id"_sd == name ? expCtx->getCollator() : nullptr);
return {std::move(eq)};
}
StatusWithMatchExpression parseJSONSchema(StringData name,
BSONElement elem,
const boost::intrusive_ptr<ExpressionContext>& expCtx,
const ExtensionsCallback* extensionsCallback,
MatchExpressionParser::AllowedFeatureSet allowedFeatures,
DocumentParseLevel currentLevel) {
if ((allowedFeatures & MatchExpressionParser::AllowedFeatures::kJSONSchema) == 0u) {
return Status(ErrorCodes::QueryFeatureNotAllowed,
"$jsonSchema is not allowed in this context");
}
if (elem.type() != BSONType::Object) {
return {Status(ErrorCodes::TypeMismatch, "$jsonSchema must be an object")};
}
return JSONSchemaParser::parse(elem.Obj(), internalQueryIgnoreUnknownJSONSchemaKeywords.load());
}
template <class T>
StatusWithMatchExpression parseAlwaysBoolean(
StringData name,
BSONElement elem,
const boost::intrusive_ptr<ExpressionContext>& expCtx,
const ExtensionsCallback* extensionsCallback,
MatchExpressionParser::AllowedFeatureSet allowedFeatures,
DocumentParseLevel currentLevel) {
auto statusWithLong = MatchExpressionParser::parseIntegerElementToLong(elem);
if (!statusWithLong.isOK()) {
return statusWithLong.getStatus();
}
if (statusWithLong.getValue() != 1) {
return {Status(ErrorCodes::FailedToParse,
str::stream() << T::kName << " must be an integer value of 1")};
}
return {stdx::make_unique<T>()};
}
StatusWithMatchExpression parseExpr(StringData name,
BSONElement elem,
const boost::intrusive_ptr<ExpressionContext>& expCtx,
const ExtensionsCallback* extensionsCallback,
MatchExpressionParser::AllowedFeatureSet allowedFeatures,
DocumentParseLevel currentLevel) {
if (currentLevel == DocumentParseLevel::kUserSubDocument) {
return {
Status(ErrorCodes::BadValue, "$expr can only be applied to the top-level document")};
}
if ((allowedFeatures & MatchExpressionParser::AllowedFeatures::kExpr) == 0u) {
return {Status(ErrorCodes::QueryFeatureNotAllowed, "$expr is not allowed in this context")};
}
return {stdx::make_unique<ExprMatchExpression>(std::move(elem), expCtx)};
}
StatusWithMatchExpression parseMOD(StringData name, BSONElement e) {
if (e.type() != BSONType::Array)
return {Status(ErrorCodes::BadValue, "malformed mod, needs to be an array")};
BSONObjIterator i(e.Obj());
if (!i.more())
return {Status(ErrorCodes::BadValue, "malformed mod, not enough elements")};
auto d = i.next();
if (!d.isNumber())
return {Status(ErrorCodes::BadValue, "malformed mod, divisor not a number")};
if (!i.more())
return {Status(ErrorCodes::BadValue, "malformed mod, not enough elements")};
auto r = i.next();
if (!d.isNumber())
return {Status(ErrorCodes::BadValue, "malformed mod, remainder not a number")};
if (i.more())
return {Status(ErrorCodes::BadValue, "malformed mod, too many elements")};
auto temp = stdx::make_unique<ModMatchExpression>();
auto s = temp->init(name, d.numberInt(), r.numberInt());
if (!s.isOK())
return s;
return {std::move(temp)};
}
StatusWithMatchExpression parseRegexDocument(StringData name, const BSONObj& doc) {
StringData regex;
StringData regexOptions;
for (auto e : doc) {
auto matchType = MatchExpressionParser::parsePathAcceptingKeyword(e);
if (!matchType) {
continue;
}
switch (*matchType) {
case PathAcceptingKeyword::REGEX:
if (e.type() == BSONType::String) {
regex = e.valueStringData();
} else if (e.type() == BSONType::RegEx) {
regex = e.regex();
regexOptions = e.regexFlags();
} else {
return {Status(ErrorCodes::BadValue, "$regex has to be a string")};
}
break;
case PathAcceptingKeyword::OPTIONS:
if (e.type() != BSONType::String)
return {Status(ErrorCodes::BadValue, "$options has to be a string")};
regexOptions = e.valueStringData();
break;
default:
break;
}
}
auto temp = stdx::make_unique<RegexMatchExpression>();
auto s = temp->init(name, regex, regexOptions);
if (!s.isOK())
return s;
return {std::move(temp)};
}
Status parseInExpression(InMatchExpression* inExpression,
const BSONObj& theArray,
const boost::intrusive_ptr<ExpressionContext>& expCtx) {
inExpression->setCollator(expCtx->getCollator());
std::vector<BSONElement> equalities;
for (auto e : theArray) {
// Allow DBRefs, but reject all fields with names starting with $.
if (isExpressionDocument(e, false)) {
return Status(ErrorCodes::BadValue, "cannot nest $ under $in");
}
if (e.type() == BSONType::RegEx) {
auto r = stdx::make_unique<RegexMatchExpression>();
auto s = r->init("", e);
if (!s.isOK())
return s;
s = inExpression->addRegex(std::move(r));
if (!s.isOK())
return s;
} else {
equalities.push_back(e);
}
}
return inExpression->setEqualities(std::move(equalities));
}
template <class T>
StatusWithMatchExpression parseType(StringData name, BSONElement elt) {
auto typeSet = MatcherTypeSet::parse(elt, MatcherTypeSet::kTypeAliasMap);
if (!typeSet.isOK()) {
return typeSet.getStatus();
}
auto typeExpr = stdx::make_unique<T>();
if (typeSet.getValue().isEmpty()) {
return {Status(ErrorCodes::FailedToParse,
str::stream() << typeExpr->name() << " must match at least one type")};
}
auto status = typeExpr->init(name, std::move(typeSet.getValue()));
if (!status.isOK()) {
return status;
}
return {std::move(typeExpr)};
}
/**
* Converts 'theArray', a BSONArray of integers, into a std::vector of integers.
*/
StatusWith<std::vector<uint32_t>> parseBitPositionsArray(const BSONObj& theArray) {
std::vector<uint32_t> bitPositions;
// Fill temporary bit position array with integers read from the BSON array.
for (auto e : theArray) {
if (!e.isNumber()) {
return Status(ErrorCodes::BadValue,
str::stream() << "bit positions must be an integer but got: " << e);
}
if (e.type() == BSONType::NumberDouble) {
auto eDouble = e.numberDouble();
// NaN doubles are rejected.
if (std::isnan(eDouble)) {
return Status(ErrorCodes::BadValue,
str::stream() << "bit positions cannot take a NaN: " << e);
}
// This makes sure e does not overflow a 32-bit integer container.
if (eDouble > std::numeric_limits<int>::max() ||
eDouble < std::numeric_limits<int>::min()) {
return Status(
ErrorCodes::BadValue,
str::stream()
<< "bit positions cannot be represented as a 32-bit signed integer: "
<< e);
}
// This checks if e is integral.
if (eDouble != static_cast<double>(static_cast<long long>(eDouble))) {
return Status(ErrorCodes::BadValue,
str::stream() << "bit positions must be an integer but got: " << e);
}
}
if (e.type() == BSONType::NumberLong) {
auto eLong = e.numberLong();
// This makes sure e does not overflow a 32-bit integer container.
if (eLong > std::numeric_limits<int>::max() ||
eLong < std::numeric_limits<int>::min()) {
return Status(
ErrorCodes::BadValue,
str::stream()
<< "bit positions cannot be represented as a 32-bit signed integer: "
<< e);
}
}
auto eValue = e.numberInt();
// No negatives.
if (eValue < 0) {
return Status(ErrorCodes::BadValue,
str::stream() << "bit positions must be >= 0 but got: " << e);
}
bitPositions.push_back(eValue);
}
return bitPositions;
}
/**
* Parses 'e' into a BitTestMatchExpression.
*/
template <class T>
StatusWithMatchExpression parseBitTest(StringData name, BSONElement e) {
auto bitTestMatchExpression = stdx::make_unique<T>();
if (e.type() == BSONType::Array) {
// Array of bit positions provided as value.
auto statusWithBitPositions = parseBitPositionsArray(e.Obj());
if (!statusWithBitPositions.isOK()) {
return statusWithBitPositions.getStatus();
}
std::vector<uint32_t> bitPositions = statusWithBitPositions.getValue();
auto s = bitTestMatchExpression->init(name, bitPositions);
if (!s.isOK()) {
return s;
}
} else if (e.isNumber()) {
// Integer bitmask provided as value.
auto bitMask = MatchExpressionParser::parseIntegerElementToNonNegativeLong(e);
if (!bitMask.isOK()) {
return bitMask.getStatus();
}
auto s = bitTestMatchExpression->init(name, bitMask.getValue());
if (!s.isOK()) {
return s;
}
} else if (e.type() == BSONType::BinData) {
// Binary bitmask provided as value.
int eBinaryLen;
auto eBinary = e.binData(eBinaryLen);
auto s = bitTestMatchExpression->init(name, eBinary, eBinaryLen);
if (!s.isOK()) {
return s;
}
} else {
return Status(
ErrorCodes::BadValue,
str::stream() << name << " takes an Array, a number, or a BinData but received: " << e);
}
return {std::move(bitTestMatchExpression)};
}
StatusWithMatchExpression parseInternalSchemaFmod(StringData name, BSONElement elem) {
auto path(name);
if (elem.type() != BSONType::Array)
return {ErrorCodes::BadValue,
str::stream() << path << " must be an array, but got type " << elem.type()};
BSONObjIterator i(elem.embeddedObject());
if (!i.more())
return {ErrorCodes::BadValue, str::stream() << path << " does not have enough elements"};
auto d = i.next();
if (!d.isNumber())
return {ErrorCodes::TypeMismatch,
str::stream() << path << " does not have a numeric divisor"};
if (!i.more())
return {ErrorCodes::BadValue, str::stream() << path << " does not have enough elements"};
auto r = i.next();
if (!d.isNumber())
return {ErrorCodes::TypeMismatch,
str::stream() << path << " does not have a numeric remainder"};
if (i.more())
return {ErrorCodes::BadValue, str::stream() << path << " has too many elements"};
auto result = stdx::make_unique<InternalSchemaFmodMatchExpression>();
auto s = result->init(name, d.numberDecimal(), r.numberDecimal());
if (!s.isOK())
return s;
return {std::move(result)};
}
StatusWithMatchExpression parseInternalSchemaRootDocEq(
StringData name,
BSONElement elem,
const boost::intrusive_ptr<ExpressionContext>& expCtx,
const ExtensionsCallback* extensionsCallback,
MatchExpressionParser::AllowedFeatureSet allowedFeatures,
DocumentParseLevel currentLevel) {
if (currentLevel == DocumentParseLevel::kUserSubDocument) {
return {Status(ErrorCodes::FailedToParse,
str::stream() << InternalSchemaRootDocEqMatchExpression::kName
<< " can only be applied to the top level document")};
}
if (elem.type() != BSONType::Object) {
return {Status(ErrorCodes::TypeMismatch,
str::stream() << InternalSchemaRootDocEqMatchExpression::kName
<< " must be an object, found type "
<< elem.type())};
}
auto rootDocEq = stdx::make_unique<InternalSchemaRootDocEqMatchExpression>();
rootDocEq->init(elem.embeddedObject());
return {std::move(rootDocEq)};
}
/**
* Parses the given BSONElement into a single integer argument and creates a MatchExpression
* of type 'T' that gets initialized with the resulting integer.
*/
template <class T>
StatusWithMatchExpression parseInternalSchemaSingleIntegerArgument(StringData name,
BSONElement elem) {
auto parsedInt = MatchExpressionParser::parseIntegerElementToNonNegativeLong(elem);
if (!parsedInt.isOK()) {
return parsedInt.getStatus();
}
auto matchExpression = stdx::make_unique<T>();
auto status = matchExpression->init(name, parsedInt.getValue());
if (!status.isOK()) {
return status;
}
return {std::move(matchExpression)};
}
/**
* Same as the parseInternalSchemaSingleIntegerArgument function, but for top-level
* operators which don't have paths.
*/
template <class T>
StatusWithMatchExpression parseTopLevelInternalSchemaSingleIntegerArgument(
StringData name,
BSONElement elem,
const boost::intrusive_ptr<ExpressionContext>& expCtx,
const ExtensionsCallback* extensionsCallback,
MatchExpressionParser::AllowedFeatureSet allowedFeatures,
DocumentParseLevel currentLevel) {
auto parsedInt = MatchExpressionParser::parseIntegerElementToNonNegativeLong(elem);
if (!parsedInt.isOK()) {
return parsedInt.getStatus();
}
auto matchExpression = stdx::make_unique<T>();
auto status = matchExpression->init(parsedInt.getValue());
if (!status.isOK()) {
return status;
}
return {std::move(matchExpression)};
}
/**
* Looks at the field named 'namePlaceholderFieldName' within 'containingObject' and parses a name
* placeholder from that element. 'expressionName' is the name of the expression that requires the
* name placeholder and is used to generate helpful error messages.
*/
StatusWith<StringData> parseNamePlaceholder(const BSONObj& containingObject,
StringData namePlaceholderFieldName,
StringData expressionName) {
auto namePlaceholderElem = containingObject[namePlaceholderFieldName];
if (!namePlaceholderElem) {
return {ErrorCodes::FailedToParse,
str::stream() << expressionName << " requires a '" << namePlaceholderFieldName
<< "'"};
} else if (namePlaceholderElem.type() != BSONType::String) {
return {ErrorCodes::TypeMismatch,
str::stream() << expressionName << " requires '" << namePlaceholderFieldName
<< "' to be a string, not "
<< namePlaceholderElem.type()};
}
return {namePlaceholderElem.valueStringData()};
}
/**
* Looks at the field named 'exprWithPlaceholderFieldName' within 'containingObject' and parses an
* ExpressionWithPlaceholder from that element. Fails if an error occurs during parsing, or if the
* ExpressionWithPlaceholder has a different name placeholder than 'expectedPlaceholder'.
* 'expressionName' is the name of the expression that requires the ExpressionWithPlaceholder and is
* used to generate helpful error messages.
*/
StatusWith<std::unique_ptr<ExpressionWithPlaceholder>> parseExprWithPlaceholder(
const BSONObj& containingObject,
StringData exprWithPlaceholderFieldName,
StringData expressionName,
StringData expectedPlaceholder,
const boost::intrusive_ptr<ExpressionContext>& expCtx,
const ExtensionsCallback* extensionsCallback,
MatchExpressionParser::AllowedFeatureSet allowedFeatures,
DocumentParseLevel currentLevel) {
auto exprWithPlaceholderElem = containingObject[exprWithPlaceholderFieldName];
if (!exprWithPlaceholderElem) {
return {ErrorCodes::FailedToParse,
str::stream() << expressionName << " requires '" << exprWithPlaceholderFieldName
<< "'"};
} else if (exprWithPlaceholderElem.type() != BSONType::Object) {
return {ErrorCodes::TypeMismatch,
str::stream() << expressionName << " found '" << exprWithPlaceholderFieldName
<< "', which is an incompatible type: "
<< exprWithPlaceholderElem.type()};
}
auto filter = parse(exprWithPlaceholderElem.embeddedObject(),
expCtx,
extensionsCallback,
MatchExpressionParser::kBanAllSpecialFeatures,
currentLevel);
if (!filter.isOK()) {
return filter.getStatus();
}
auto result = ExpressionWithPlaceholder::make(std::move(filter.getValue()));
if (!result.isOK()) {
return result.getStatus();
}
auto placeholder = result.getValue()->getPlaceholder();
if (placeholder && (*placeholder != expectedPlaceholder)) {
return {ErrorCodes::FailedToParse,
str::stream() << expressionName << " expected a name placeholder of "
<< expectedPlaceholder
<< ", but '"
<< exprWithPlaceholderElem.fieldNameStringData()
<< "' has a mismatching placeholder '"
<< *placeholder
<< "'"};
}
return result;
}
StatusWith<std::vector<InternalSchemaAllowedPropertiesMatchExpression::PatternSchema>>
parsePatternProperties(BSONElement patternPropertiesElem,
StringData expectedPlaceholder,
const boost::intrusive_ptr<ExpressionContext>& expCtx,
const ExtensionsCallback* extensionsCallback,
MatchExpressionParser::AllowedFeatureSet allowedFeatures,
DocumentParseLevel currentLevel) {
if (!patternPropertiesElem) {
return {ErrorCodes::FailedToParse,
str::stream() << InternalSchemaAllowedPropertiesMatchExpression::kName
<< " requires 'patternProperties'"};
} else if (patternPropertiesElem.type() != BSONType::Array) {
return {ErrorCodes::TypeMismatch,
str::stream() << InternalSchemaAllowedPropertiesMatchExpression::kName
<< " requires 'patternProperties' to be an array, not "
<< patternPropertiesElem.type()};
}
std::vector<InternalSchemaAllowedPropertiesMatchExpression::PatternSchema> patternProperties;
for (auto constraintElem : patternPropertiesElem.embeddedObject()) {
if (constraintElem.type() != BSONType::Object) {
return {ErrorCodes::TypeMismatch,
str::stream() << InternalSchemaAllowedPropertiesMatchExpression::kName
<< " requires 'patternProperties' to be an array of objects"};
}
auto constraint = constraintElem.embeddedObject();
if (constraint.nFields() != 2) {
return {ErrorCodes::FailedToParse,
str::stream() << InternalSchemaAllowedPropertiesMatchExpression::kName
<< " requires 'patternProperties' to be an array of objects "
"containing exactly two fields, 'regex' and 'expression'"};
}
auto expressionWithPlaceholder =
parseExprWithPlaceholder(constraint,
"expression"_sd,
InternalSchemaAllowedPropertiesMatchExpression::kName,
expectedPlaceholder,
expCtx,
extensionsCallback,
allowedFeatures,
currentLevel);
if (!expressionWithPlaceholder.isOK()) {
return expressionWithPlaceholder.getStatus();
}
auto regexElem = constraint["regex"];
if (!regexElem) {
return {
ErrorCodes::FailedToParse,
str::stream() << InternalSchemaAllowedPropertiesMatchExpression::kName