/proc/self/cwd/parser/internal/antlr_parser.cc
Line | Count | Source |
1 | | // Copyright 2021 Google LLC |
2 | | // |
3 | | // Licensed under the Apache License, Version 2.0 (the "License"); |
4 | | // you may not use this file except in compliance with the License. |
5 | | // You may obtain a copy of the License at |
6 | | // |
7 | | // https://www.apache.org/licenses/LICENSE-2.0 |
8 | | // |
9 | | // Unless required by applicable law or agreed to in writing, software |
10 | | // distributed under the License is distributed on an "AS IS" BASIS, |
11 | | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
12 | | // See the License for the specific language governing permissions and |
13 | | // limitations under the License. |
14 | | |
15 | | #include "parser/internal/antlr_parser.h" |
16 | | |
17 | | #include <algorithm> |
18 | | #include <any> |
19 | | #include <array> |
20 | | #include <cstddef> |
21 | | #include <cstdint> |
22 | | #include <exception> |
23 | | #include <functional> |
24 | | #include <iterator> |
25 | | #include <limits> |
26 | | #include <memory> |
27 | | #include <optional> |
28 | | #include <string> |
29 | | #include <type_traits> |
30 | | #include <utility> |
31 | | #include <vector> |
32 | | |
33 | | #include "absl/base/macros.h" |
34 | | #include "absl/base/nullability.h" |
35 | | #include "absl/base/optimization.h" |
36 | | #include "absl/cleanup/cleanup.h" |
37 | | #include "absl/container/btree_map.h" |
38 | | #include "absl/container/flat_hash_map.h" |
39 | | #include "absl/container/flat_hash_set.h" |
40 | | #include "absl/functional/overload.h" |
41 | | #include "absl/log/absl_check.h" |
42 | | #include "absl/log/check.h" |
43 | | #include "absl/memory/memory.h" |
44 | | #include "absl/status/status.h" |
45 | | #include "absl/status/statusor.h" |
46 | | #include "absl/strings/match.h" |
47 | | #include "absl/strings/numbers.h" |
48 | | #include "absl/strings/str_cat.h" |
49 | | #include "absl/strings/str_format.h" |
50 | | #include "absl/strings/str_join.h" |
51 | | #include "absl/strings/str_replace.h" |
52 | | #include "absl/strings/string_view.h" |
53 | | #include "absl/types/optional.h" |
54 | | #include "absl/types/span.h" |
55 | | #include "absl/types/variant.h" |
56 | | #include "antlr4-runtime.h" |
57 | | #include "common/ast.h" |
58 | | #include "common/constant.h" |
59 | | #include "common/expr.h" |
60 | | #include "common/expr_factory.h" |
61 | | #include "common/operators.h" |
62 | | #include "common/source.h" |
63 | | #include "internal/lexis.h" |
64 | | #include "internal/status_macros.h" |
65 | | #include "internal/strings.h" |
66 | | #pragma push_macro("IN") |
67 | | #undef IN |
68 | | #include "parser/internal/CelBaseVisitor.h" |
69 | | #include "parser/internal/CelLexer.h" |
70 | | #include "parser/internal/CelParser.h" |
71 | | #pragma pop_macro("IN") |
72 | | #include "parser/macro.h" |
73 | | #include "parser/macro_expr_factory.h" |
74 | | #include "parser/macro_registry.h" |
75 | | #include "parser/options.h" |
76 | | #include "parser/parser_interface.h" |
77 | | #include "parser/source_factory.h" |
78 | | |
79 | | namespace cel { |
80 | | |
81 | | namespace { |
82 | | |
83 | | constexpr const char kHiddenAccumulatorVariableName[] = "@result"; |
84 | | |
85 | 8.06M | std::any ExprPtrToAny(std::unique_ptr<Expr>&& expr) { |
86 | 8.06M | return std::make_any<Expr*>(expr.release()); |
87 | 8.06M | } |
88 | | |
89 | 8.06M | std::any ExprToAny(Expr&& expr) { |
90 | 8.06M | return ExprPtrToAny(std::make_unique<Expr>(std::move(expr))); |
91 | 8.06M | } |
92 | | |
93 | 8.06M | std::unique_ptr<Expr> ExprPtrFromAny(std::any&& any) { |
94 | 8.06M | return absl::WrapUnique(std::any_cast<Expr*>(std::move(any))); |
95 | 8.06M | } |
96 | | |
97 | 8.06M | Expr ExprFromAny(std::any&& any) { |
98 | 8.06M | auto expr = ExprPtrFromAny(std::move(any)); |
99 | 8.06M | return std::move(*expr); |
100 | 8.06M | } |
101 | | |
102 | | struct ParserError { |
103 | | std::string message; |
104 | | SourceRange range; |
105 | | }; |
106 | | |
107 | | std::string DisplayParserError(const cel::Source& source, |
108 | | SourceLocation location, |
109 | 233k | absl::string_view message) { |
110 | 233k | return absl::StrCat(absl::StrFormat("ERROR: %s:%zu:%zu: %s", |
111 | 233k | source.description(), location.line, |
112 | | // add one to the 0-based column |
113 | 233k | location.column + 1, message), |
114 | 233k | source.DisplayErrorLocation(location)); |
115 | 233k | } |
116 | | |
117 | 2.47M | int32_t PositiveOrMax(int32_t value) { |
118 | 2.47M | return value >= 0 ? value : std::numeric_limits<int32_t>::max(); |
119 | 2.47M | } |
120 | | |
121 | 6.41M | SourceRange SourceRangeFromToken(const antlr4::Token* token) { |
122 | 6.41M | SourceRange range; |
123 | 6.41M | if (token != nullptr) { |
124 | 6.41M | if (auto start = token->getStartIndex(); start != INVALID_INDEX) { |
125 | 6.40M | range.begin = static_cast<int32_t>(start); |
126 | 6.40M | } |
127 | 6.41M | if (auto end = token->getStopIndex(); end != INVALID_INDEX) { |
128 | 6.40M | range.end = static_cast<int32_t>(end + 1); |
129 | 6.40M | } |
130 | 6.41M | } |
131 | 6.41M | return range; |
132 | 6.41M | } |
133 | | |
134 | | SourceRange SourceRangeFromParserRuleContext( |
135 | 1.39M | const antlr4::ParserRuleContext* context) { |
136 | 1.39M | SourceRange range; |
137 | 1.39M | if (context != nullptr) { |
138 | 1.39M | if (auto start = context->getStart() != nullptr |
139 | 1.39M | ? context->getStart()->getStartIndex() |
140 | 1.39M | : INVALID_INDEX; |
141 | 1.39M | start != INVALID_INDEX) { |
142 | 1.39M | range.begin = static_cast<int32_t>(start); |
143 | 1.39M | } |
144 | 1.39M | if (auto end = context->getStop() != nullptr |
145 | 1.39M | ? context->getStop()->getStopIndex() |
146 | 1.39M | : INVALID_INDEX; |
147 | 1.39M | end != INVALID_INDEX) { |
148 | 1.38M | range.end = static_cast<int32_t>(end + 1); |
149 | 1.38M | } |
150 | 1.39M | } |
151 | 1.39M | return range; |
152 | 1.39M | } |
153 | | |
154 | | } // namespace |
155 | | |
156 | | class ParserMacroExprFactory final : public MacroExprFactory { |
157 | | public: |
158 | | explicit ParserMacroExprFactory(const cel::Source& source, |
159 | | int expression_node_limit) |
160 | 35.3k | : source_(source), expression_node_limit_(expression_node_limit) {} |
161 | | |
162 | 69.7k | void BeginMacro(SourceRange macro_position) { |
163 | 69.7k | macro_position_ = macro_position; |
164 | 69.7k | } |
165 | | |
166 | 69.7k | void EndMacro() { macro_position_ = SourceRange{}; } |
167 | | |
168 | 4.64k | Expr ReportError(absl::string_view message) override { |
169 | 4.64k | return ReportError(macro_position_, message); |
170 | 4.64k | } |
171 | | |
172 | 0 | Expr ReportError(int64_t expr_id, absl::string_view message) { |
173 | 0 | return ReportError(GetSourceRange(expr_id), message); |
174 | 0 | } |
175 | | |
176 | 1.81M | Expr ReportError(SourceRange range, absl::string_view message) { |
177 | 1.81M | ++error_count_; |
178 | 1.81M | if (errors_.size() <= 100) { |
179 | 232k | errors_.push_back(ParserError{std::string(message), range}); |
180 | 232k | } |
181 | 1.81M | return NewUnspecified(NextId(range)); |
182 | 1.81M | } |
183 | | |
184 | 22.7k | Expr ReportErrorAt(const Expr& expr, absl::string_view message) override { |
185 | 22.7k | return ReportError(GetSourceRange(expr.id()), message); |
186 | 22.7k | } |
187 | | |
188 | 92.5k | SourceRange GetSourceRange(int64_t id) const { |
189 | 92.5k | if (auto it = positions_.find(id); it != positions_.end()) { |
190 | 90.2k | return it->second; |
191 | 90.2k | } |
192 | 2.25k | return SourceRange{}; |
193 | 92.5k | } |
194 | | |
195 | 9.91M | int64_t NextId(const SourceRange& range) { |
196 | 9.91M | auto id = expr_id_++; |
197 | 9.91M | if (id > expression_node_limit_ && !node_limit_exceeded_) { |
198 | 0 | node_limit_exceeded_ = true; |
199 | 0 | ReportError(range, "expression node limit exceeded"); |
200 | 0 | } |
201 | 9.91M | if (range.begin != -1 || range.end != -1) { |
202 | 9.90M | positions_.insert(std::pair{id, range}); |
203 | 9.90M | } |
204 | 9.91M | return id; |
205 | 9.91M | } |
206 | | |
207 | 69.7k | bool is_node_limit_exceeded() const { return node_limit_exceeded_; } |
208 | | |
209 | 37.2k | bool HasErrors() const { return error_count_ != 0; } |
210 | | |
211 | 12.8k | std::vector<cel::ParseIssue> CollectIssues() { |
212 | | // Errors are collected as they are encountered, not by their location |
213 | | // within the source. To have a more stable error message as implementation |
214 | | // details change, we sort the collected errors by their source location |
215 | | // first. |
216 | 12.8k | std::stable_sort( |
217 | 12.8k | errors_.begin(), errors_.end(), |
218 | 619k | [](const ParserError& lhs, const ParserError& rhs) -> bool { |
219 | 619k | auto lhs_begin = PositiveOrMax(lhs.range.begin); |
220 | 619k | auto lhs_end = PositiveOrMax(lhs.range.end); |
221 | 619k | auto rhs_begin = PositiveOrMax(rhs.range.begin); |
222 | 619k | auto rhs_end = PositiveOrMax(rhs.range.end); |
223 | 619k | return lhs_begin < rhs_begin || |
224 | 560k | (lhs_begin == rhs_begin && lhs_end < rhs_end); |
225 | 619k | }); |
226 | | // Build the summary error message using the sorted errors. |
227 | 12.8k | bool errors_truncated = error_count_ > 100; |
228 | 12.8k | std::vector<cel::ParseIssue> issues; |
229 | 12.8k | issues.reserve( |
230 | 12.8k | errors_.size() + |
231 | 12.8k | errors_truncated); // Reserve space for the transform and an |
232 | | // additional element when truncation occurs. |
233 | 12.8k | std::transform( |
234 | 12.8k | errors_.begin(), errors_.end(), std::back_inserter(issues), |
235 | 232k | [this](const ParserError& error) { |
236 | 232k | auto location = |
237 | 232k | source_.GetLocation(error.range.begin).value_or(SourceLocation{}); |
238 | 232k | return cel::ParseIssue(location, error.message); |
239 | 232k | }); |
240 | 12.8k | if (errors_truncated) { |
241 | 930 | issues.push_back(cel::ParseIssue( |
242 | 930 | absl::StrCat(error_count_ - 100, " more errors were truncated."))); |
243 | 930 | } |
244 | 12.8k | return issues; |
245 | 12.8k | } |
246 | | |
247 | | void AddMacroCall(int64_t macro_id, absl::string_view function, |
248 | 0 | absl::optional<Expr> target, std::vector<Expr> arguments) { |
249 | 0 | macro_calls_.insert( |
250 | 0 | {macro_id, target.has_value() |
251 | 0 | ? NewMemberCall(0, function, std::move(*target), |
252 | 0 | std::move(arguments)) |
253 | 0 | : NewCall(0, function, std::move(arguments))}); |
254 | 0 | } |
255 | | |
256 | 0 | Expr BuildMacroCallArg(const Expr& expr) { |
257 | 0 | if (auto it = macro_calls_.find(expr.id()); it != macro_calls_.end()) { |
258 | 0 | return NewUnspecified(expr.id()); |
259 | 0 | } |
260 | 0 | return absl::visit( |
261 | 0 | absl::Overload( |
262 | 0 | [this, &expr](const UnspecifiedExpr&) -> Expr { |
263 | 0 | return NewUnspecified(expr.id()); |
264 | 0 | }, |
265 | 0 | [this, &expr](const Constant& const_expr) -> Expr { |
266 | 0 | return NewConst(expr.id(), const_expr); |
267 | 0 | }, |
268 | 0 | [this, &expr](const IdentExpr& ident_expr) -> Expr { |
269 | 0 | return NewIdent(expr.id(), ident_expr.name()); |
270 | 0 | }, |
271 | 0 | [this, &expr](const SelectExpr& select_expr) -> Expr { |
272 | 0 | return select_expr.test_only() |
273 | 0 | ? NewPresenceTest( |
274 | 0 | expr.id(), |
275 | 0 | BuildMacroCallArg(select_expr.operand()), |
276 | 0 | select_expr.field()) |
277 | 0 | : NewSelect(expr.id(), |
278 | 0 | BuildMacroCallArg(select_expr.operand()), |
279 | 0 | select_expr.field()); |
280 | 0 | }, |
281 | 0 | [this, &expr](const CallExpr& call_expr) -> Expr { |
282 | 0 | std::vector<Expr> macro_arguments; |
283 | 0 | macro_arguments.reserve(call_expr.args().size()); |
284 | 0 | for (const auto& argument : call_expr.args()) { |
285 | 0 | macro_arguments.push_back(BuildMacroCallArg(argument)); |
286 | 0 | } |
287 | 0 | absl::optional<Expr> macro_target; |
288 | 0 | if (call_expr.has_target()) { |
289 | 0 | macro_target = BuildMacroCallArg(call_expr.target()); |
290 | 0 | } |
291 | 0 | return macro_target.has_value() |
292 | 0 | ? NewMemberCall(expr.id(), call_expr.function(), |
293 | 0 | std::move(*macro_target), |
294 | 0 | std::move(macro_arguments)) |
295 | 0 | : NewCall(expr.id(), call_expr.function(), |
296 | 0 | std::move(macro_arguments)); |
297 | 0 | }, |
298 | 0 | [this, &expr](const ListExpr& list_expr) -> Expr { |
299 | 0 | std::vector<ListExprElement> macro_elements; |
300 | 0 | macro_elements.reserve(list_expr.elements().size()); |
301 | 0 | for (const auto& element : list_expr.elements()) { |
302 | 0 | auto& cloned_element = macro_elements.emplace_back(); |
303 | 0 | if (element.has_expr()) { |
304 | 0 | cloned_element.set_expr(BuildMacroCallArg(element.expr())); |
305 | 0 | } |
306 | 0 | cloned_element.set_optional(element.optional()); |
307 | 0 | } |
308 | 0 | return NewList(expr.id(), std::move(macro_elements)); |
309 | 0 | }, |
310 | 0 | [this, &expr](const StructExpr& struct_expr) -> Expr { |
311 | 0 | std::vector<StructExprField> macro_fields; |
312 | 0 | macro_fields.reserve(struct_expr.fields().size()); |
313 | 0 | for (const auto& field : struct_expr.fields()) { |
314 | 0 | auto& macro_field = macro_fields.emplace_back(); |
315 | 0 | macro_field.set_id(field.id()); |
316 | 0 | macro_field.set_name(field.name()); |
317 | 0 | macro_field.set_value(BuildMacroCallArg(field.value())); |
318 | 0 | macro_field.set_optional(field.optional()); |
319 | 0 | } |
320 | 0 | return NewStruct(expr.id(), struct_expr.name(), |
321 | 0 | std::move(macro_fields)); |
322 | 0 | }, |
323 | 0 | [this, &expr](const MapExpr& map_expr) -> Expr { |
324 | 0 | std::vector<MapExprEntry> macro_entries; |
325 | 0 | macro_entries.reserve(map_expr.entries().size()); |
326 | 0 | for (const auto& entry : map_expr.entries()) { |
327 | 0 | auto& macro_entry = macro_entries.emplace_back(); |
328 | 0 | macro_entry.set_id(entry.id()); |
329 | 0 | macro_entry.set_key(BuildMacroCallArg(entry.key())); |
330 | 0 | macro_entry.set_value(BuildMacroCallArg(entry.value())); |
331 | 0 | macro_entry.set_optional(entry.optional()); |
332 | 0 | } |
333 | 0 | return NewMap(expr.id(), std::move(macro_entries)); |
334 | 0 | }, |
335 | 0 | [this, &expr](const ComprehensionExpr& comprehension_expr) -> Expr { |
336 | 0 | return NewComprehension( |
337 | 0 | expr.id(), comprehension_expr.iter_var(), |
338 | 0 | BuildMacroCallArg(comprehension_expr.iter_range()), |
339 | 0 | comprehension_expr.accu_var(), |
340 | 0 | BuildMacroCallArg(comprehension_expr.accu_init()), |
341 | 0 | BuildMacroCallArg(comprehension_expr.loop_condition()), |
342 | 0 | BuildMacroCallArg(comprehension_expr.loop_step()), |
343 | 0 | BuildMacroCallArg(comprehension_expr.result())); |
344 | 0 | }), |
345 | 0 | expr.kind()); |
346 | 0 | } |
347 | | |
348 | | using ExprFactory::NewBoolConst; |
349 | | using ExprFactory::NewBytesConst; |
350 | | using ExprFactory::NewCall; |
351 | | using ExprFactory::NewComprehension; |
352 | | using ExprFactory::NewConst; |
353 | | using ExprFactory::NewDoubleConst; |
354 | | using ExprFactory::NewIdent; |
355 | | using ExprFactory::NewIntConst; |
356 | | using ExprFactory::NewList; |
357 | | using ExprFactory::NewListElement; |
358 | | using ExprFactory::NewMap; |
359 | | using ExprFactory::NewMapEntry; |
360 | | using ExprFactory::NewMemberCall; |
361 | | using ExprFactory::NewNullConst; |
362 | | using ExprFactory::NewPresenceTest; |
363 | | using ExprFactory::NewSelect; |
364 | | using ExprFactory::NewStringConst; |
365 | | using ExprFactory::NewStruct; |
366 | | using ExprFactory::NewStructField; |
367 | | using ExprFactory::NewUintConst; |
368 | | using ExprFactory::NewUnspecified; |
369 | | |
370 | 67.4k | const absl::btree_map<int64_t, SourceRange>& positions() const { |
371 | 67.4k | return positions_; |
372 | 67.4k | } |
373 | | |
374 | 0 | const absl::flat_hash_map<int64_t, Expr>& macro_calls() const { |
375 | 0 | return macro_calls_; |
376 | 0 | } |
377 | | |
378 | 22.4k | absl::flat_hash_map<int64_t, Expr> release_macro_calls() { |
379 | 22.4k | using std::swap; |
380 | 22.4k | absl::flat_hash_map<int64_t, Expr> result; |
381 | 22.4k | swap(result, macro_calls_); |
382 | 22.4k | return result; |
383 | 22.4k | } |
384 | | |
385 | 69.7k | void EraseId(ExprId id) { |
386 | 69.7k | positions_.erase(id); |
387 | 69.7k | if (expr_id_ == id + 1) { |
388 | 0 | --expr_id_; |
389 | 0 | } |
390 | 69.7k | } |
391 | | |
392 | | protected: |
393 | 341k | int64_t NextId() override { return NextId(macro_position_); } |
394 | | |
395 | 0 | int64_t CopyId(int64_t id) override { |
396 | 0 | if (id == 0) { |
397 | 0 | return 0; |
398 | 0 | } |
399 | 0 | return NextId(GetSourceRange(id)); |
400 | 0 | } |
401 | | |
402 | | private: |
403 | | int64_t expr_id_ = 1; |
404 | | absl::btree_map<int64_t, SourceRange> positions_; |
405 | | absl::flat_hash_map<int64_t, Expr> macro_calls_; |
406 | | std::vector<ParserError> errors_; |
407 | | size_t error_count_ = 0; |
408 | | const Source& source_; |
409 | | int expression_node_limit_; |
410 | | bool node_limit_exceeded_ = false; |
411 | | SourceRange macro_position_; |
412 | | }; |
413 | | |
414 | | } // namespace cel |
415 | | |
416 | | namespace cel::parser_internal { |
417 | | |
418 | | namespace { |
419 | | |
420 | | using ::antlr4::CharStream; |
421 | | using ::antlr4::CommonTokenStream; |
422 | | using ::antlr4::DefaultErrorStrategy; |
423 | | using ::antlr4::ParseCancellationException; |
424 | | using ::antlr4::Parser; |
425 | | using ::antlr4::ParserRuleContext; |
426 | | using ::antlr4::Token; |
427 | | using ::antlr4::misc::IntervalSet; |
428 | | using ::antlr4::tree::ErrorNode; |
429 | | using ::antlr4::tree::ParseTreeListener; |
430 | | using ::antlr4::tree::TerminalNode; |
431 | | using ::cel_parser_internal::CelBaseVisitor; |
432 | | using ::cel_parser_internal::CelLexer; |
433 | | using ::cel_parser_internal::CelParser; |
434 | | using ::google::api::expr::common::CelOperator; |
435 | | using ::google::api::expr::common::ReverseLookupOperator; |
436 | | |
437 | | class CodePointStream final : public CharStream { |
438 | | public: |
439 | | CodePointStream(cel::SourceContentView buffer, absl::string_view source_name) |
440 | 35.3k | : buffer_(buffer), |
441 | 35.3k | source_name_(source_name), |
442 | 35.3k | size_(buffer_.size()), |
443 | 35.3k | index_(0) {} |
444 | | |
445 | 83.7M | void consume() override { |
446 | 83.7M | if (ABSL_PREDICT_FALSE(index_ >= size_)) { |
447 | 0 | ABSL_ASSERT(LA(1) == IntStream::EOF); |
448 | 0 | throw antlr4::IllegalStateException("cannot consume EOF"); |
449 | 0 | } |
450 | 83.7M | index_++; |
451 | 83.7M | } |
452 | | |
453 | 192M | size_t LA(ptrdiff_t i) override { |
454 | 192M | if (ABSL_PREDICT_FALSE(i == 0)) { |
455 | 0 | return 0; |
456 | 0 | } |
457 | 192M | auto p = static_cast<ptrdiff_t>(index_); |
458 | 192M | if (i < 0) { |
459 | 0 | i++; |
460 | 0 | if (p + i - 1 < 0) { |
461 | 0 | return IntStream::EOF; |
462 | 0 | } |
463 | 0 | } |
464 | 192M | if (p + i - 1 >= static_cast<ptrdiff_t>(size_)) { |
465 | 71.6k | return IntStream::EOF; |
466 | 71.6k | } |
467 | 192M | return buffer_.at(static_cast<size_t>(p + i - 1)); |
468 | 192M | } |
469 | | |
470 | 23.4M | ptrdiff_t mark() override { return -1; } |
471 | | |
472 | 23.4M | void release(ptrdiff_t marker) override {} |
473 | | |
474 | 65.9M | size_t index() override { return index_; } |
475 | | |
476 | 10.8M | void seek(size_t index) override { index_ = std::min(index, size_); } |
477 | | |
478 | 10.9M | size_t size() override { return size_; } |
479 | | |
480 | 0 | std::string getSourceName() const override { |
481 | 0 | return source_name_.empty() ? IntStream::UNKNOWN_SOURCE_NAME |
482 | 0 | : std::string(source_name_); |
483 | 0 | } |
484 | | |
485 | 12.5M | std::string getText(const antlr4::misc::Interval& interval) override { |
486 | 12.5M | if (ABSL_PREDICT_FALSE(interval.a < 0 || interval.b < 0)) { |
487 | 0 | return std::string(); |
488 | 0 | } |
489 | 12.5M | size_t start = static_cast<size_t>(interval.a); |
490 | 12.5M | if (ABSL_PREDICT_FALSE(start >= size_)) { |
491 | 0 | return std::string(); |
492 | 0 | } |
493 | 12.5M | size_t stop = static_cast<size_t>(interval.b); |
494 | 12.5M | if (ABSL_PREDICT_FALSE(stop >= size_)) { |
495 | 982 | stop = size_ - 1; |
496 | 982 | } |
497 | 12.5M | return buffer_.ToString(static_cast<cel::SourcePosition>(start), |
498 | 12.5M | static_cast<cel::SourcePosition>(stop) + 1); |
499 | 12.5M | } |
500 | | |
501 | 0 | std::string toString() const override { return buffer_.ToString(); } |
502 | | |
503 | | private: |
504 | | cel::SourceContentView const buffer_; |
505 | | const absl::string_view source_name_; |
506 | | const size_t size_; |
507 | | size_t index_; |
508 | | }; |
509 | | |
510 | | // Scoped helper for incrementing the parse recursion count. |
511 | | // Increments on creation, decrements on destruction (stack unwind). |
512 | | class ScopedIncrement final { |
513 | | public: |
514 | | explicit ScopedIncrement(int& recursion_depth) |
515 | 7.29M | : recursion_depth_(recursion_depth) { |
516 | 7.29M | ++recursion_depth_; |
517 | 7.29M | } |
518 | | |
519 | 7.29M | ~ScopedIncrement() { --recursion_depth_; } |
520 | | |
521 | | private: |
522 | | int& recursion_depth_; |
523 | | }; |
524 | | |
525 | | // balancer performs tree balancing on operators whose arguments are of equal |
526 | | // precedence. |
527 | | // |
528 | | // The purpose of the balancer is to ensure a compact serialization format for |
529 | | // the logical &&, || operators which have a tendency to create long DAGs which |
530 | | // are skewed in one direction. Since the operators are commutative re-ordering |
531 | | // the terms *must not* affect the evaluation result. |
532 | | // |
533 | | // Based on code from //third_party/cel/go/parser/helper.go |
534 | | class ExpressionBalancer final { |
535 | | public: |
536 | | ExpressionBalancer(cel::ParserMacroExprFactory& factory, std::string function, |
537 | | Expr expr); |
538 | | |
539 | | // addTerm adds an operation identifier and term to the set of terms to be |
540 | | // balanced. |
541 | | void AddTerm(int64_t op, Expr term); |
542 | | |
543 | | // balance creates a balanced tree from the sub-terms and returns the final |
544 | | // Expr value. |
545 | | Expr Balance(bool enable_variadic = false); |
546 | | |
547 | | private: |
548 | | // balancedTree recursively balances the terms provided to a commutative |
549 | | // operator. |
550 | | Expr BalancedTree(int lo, int hi); |
551 | | |
552 | | private: |
553 | | cel::ParserMacroExprFactory& factory_; |
554 | | std::string function_; |
555 | | std::vector<Expr> terms_; |
556 | | std::vector<int64_t> ops_; |
557 | | }; |
558 | | |
559 | | ExpressionBalancer::ExpressionBalancer(cel::ParserMacroExprFactory& factory, |
560 | | std::string function, Expr expr) |
561 | 6.63k | : factory_(factory), function_(std::move(function)) { |
562 | 6.63k | terms_.push_back(std::move(expr)); |
563 | 6.63k | } |
564 | | |
565 | 239k | void ExpressionBalancer::AddTerm(int64_t op, Expr term) { |
566 | 239k | terms_.push_back(std::move(term)); |
567 | 239k | ops_.push_back(op); |
568 | 239k | } |
569 | | |
570 | 6.63k | Expr ExpressionBalancer::Balance(bool enable_variadic) { |
571 | 6.63k | if (terms_.size() == 1) { |
572 | 0 | return std::move(terms_[0]); |
573 | 0 | } |
574 | 6.63k | if (enable_variadic) { |
575 | 0 | return factory_.NewCall(ops_[0], function_, std::move(terms_)); |
576 | 0 | } |
577 | 6.63k | return BalancedTree(0, ops_.size() - 1); |
578 | 6.63k | } |
579 | | |
580 | 239k | Expr ExpressionBalancer::BalancedTree(int lo, int hi) { |
581 | 239k | int mid = (lo + hi + 1) / 2; |
582 | | |
583 | 239k | std::vector<Expr> arguments; |
584 | 239k | arguments.reserve(2); |
585 | | |
586 | 239k | if (mid == lo) { |
587 | 105k | arguments.push_back(std::move(terms_[mid])); |
588 | 134k | } else { |
589 | 134k | arguments.push_back(BalancedTree(lo, mid - 1)); |
590 | 134k | } |
591 | | |
592 | 239k | if (mid == hi) { |
593 | 140k | arguments.push_back(std::move(terms_[mid + 1])); |
594 | 140k | } else { |
595 | 98.8k | arguments.push_back(BalancedTree(mid + 1, hi)); |
596 | 98.8k | } |
597 | 239k | return factory_.NewCall(ops_[mid], function_, std::move(arguments)); |
598 | 239k | } |
599 | | |
600 | | std::string FormatIssues(const cel::Source& source, |
601 | 12.8k | absl::Span<const cel::ParseIssue> issues) { |
602 | 12.8k | return absl::StrJoin( |
603 | 233k | issues, "\n", [&source](std::string* out, const cel::ParseIssue& issue) { |
604 | 233k | absl::StrAppend( |
605 | 233k | out, DisplayParserError(source, issue.location(), issue.message())); |
606 | 233k | }); |
607 | 12.8k | } |
608 | | |
609 | | class ParserVisitor final : public CelBaseVisitor, |
610 | | public antlr4::BaseErrorListener { |
611 | | public: |
612 | | ParserVisitor(const cel::Source& source, int max_recursion_depth, |
613 | | int max_expression_node_count, |
614 | | const cel::MacroRegistry& macro_registry, |
615 | | bool add_macro_calls = false, |
616 | | bool enable_optional_syntax = false, |
617 | | bool enable_quoted_identifiers = false, |
618 | | bool enable_variadic_logical_operators = false, |
619 | | bool fold_unary_operators = false) |
620 | 35.3k | : source_(source), |
621 | 35.3k | factory_(source_, max_expression_node_count), |
622 | 35.3k | macro_registry_(macro_registry), |
623 | 35.3k | recursion_depth_(0), |
624 | 35.3k | max_recursion_depth_(max_recursion_depth), |
625 | 35.3k | add_macro_calls_(add_macro_calls), |
626 | 35.3k | enable_optional_syntax_(enable_optional_syntax), |
627 | 35.3k | enable_quoted_identifiers_(enable_quoted_identifiers), |
628 | 35.3k | enable_variadic_logical_operators_(enable_variadic_logical_operators), |
629 | 35.3k | fold_unary_operators_(fold_unary_operators) {} |
630 | | |
631 | 35.3k | ~ParserVisitor() override = default; |
632 | | |
633 | | std::any visit(antlr4::tree::ParseTree* tree) override; |
634 | | |
635 | | std::any visitStart(CelParser::StartContext* ctx) override; |
636 | | std::any visitExpr(CelParser::ExprContext* ctx) override; |
637 | | std::any visitConditionalOr(CelParser::ConditionalOrContext* ctx) override; |
638 | | std::any visitConditionalAnd(CelParser::ConditionalAndContext* ctx) override; |
639 | | std::any visitRelation(CelParser::RelationContext* ctx) override; |
640 | | std::any visitCalc(CelParser::CalcContext* ctx) override; |
641 | | std::any visitUnary(CelParser::UnaryContext* ctx); |
642 | | std::any visitLogicalNot(CelParser::LogicalNotContext* ctx) override; |
643 | | std::any visitNegate(CelParser::NegateContext* ctx) override; |
644 | | std::any visitSelect(CelParser::SelectContext* ctx) override; |
645 | | std::any visitMemberCall(CelParser::MemberCallContext* ctx) override; |
646 | | std::any visitIndex(CelParser::IndexContext* ctx) override; |
647 | | std::any visitCreateMessage(CelParser::CreateMessageContext* ctx) override; |
648 | | std::any visitFieldInitializerList( |
649 | | CelParser::FieldInitializerListContext* ctx) override; |
650 | | std::vector<StructExprField> visitFields( |
651 | | CelParser::FieldInitializerListContext* ctx); |
652 | | std::any visitGlobalCall(CelParser::GlobalCallContext* ctx) override; |
653 | | std::any visitIdent(CelParser::IdentContext* ctx) override; |
654 | | std::any visitNested(CelParser::NestedContext* ctx) override; |
655 | | std::any visitCreateList(CelParser::CreateListContext* ctx) override; |
656 | | std::vector<ListExprElement> visitList(CelParser::ListInitContext* ctx); |
657 | | std::vector<Expr> visitList(CelParser::ExprListContext* ctx); |
658 | | std::any visitCreateMap(CelParser::CreateMapContext* ctx) override; |
659 | | std::any visitConstantLiteral( |
660 | | CelParser::ConstantLiteralContext* ctx) override; |
661 | | std::any visitPrimaryExpr(CelParser::PrimaryExprContext* ctx) override; |
662 | | std::any visitMemberExpr(CelParser::MemberExprContext* ctx) override; |
663 | | |
664 | | std::any visitMapInitializerList( |
665 | | CelParser::MapInitializerListContext* ctx) override; |
666 | | std::vector<MapExprEntry> visitEntries( |
667 | | CelParser::MapInitializerListContext* ctx); |
668 | | std::any visitInt(CelParser::IntContext* ctx) override; |
669 | | std::any visitUint(CelParser::UintContext* ctx) override; |
670 | | std::any visitDouble(CelParser::DoubleContext* ctx) override; |
671 | | std::any visitString(CelParser::StringContext* ctx) override; |
672 | | std::any visitBytes(CelParser::BytesContext* ctx) override; |
673 | | std::any visitBoolTrue(CelParser::BoolTrueContext* ctx) override; |
674 | | std::any visitBoolFalse(CelParser::BoolFalseContext* ctx) override; |
675 | | std::any visitNull(CelParser::NullContext* ctx) override; |
676 | | // Note: this is destructive and intended to be called after the parse is |
677 | | // finished. |
678 | | cel::SourceInfo GetSourceInfo(); |
679 | | EnrichedSourceInfo enriched_source_info() const; |
680 | | void syntaxError(antlr4::Recognizer* recognizer, |
681 | | antlr4::Token* offending_symbol, size_t line, size_t col, |
682 | | const std::string& msg, std::exception_ptr e) override; |
683 | | bool HasErrored() const; |
684 | | |
685 | | std::vector<cel::ParseIssue> CollectIssues(); |
686 | | |
687 | | private: |
688 | | template <typename... Args> |
689 | | Expr GlobalCallOrMacro(int64_t expr_id, absl::string_view function, |
690 | 2.90M | Args&&... args) { |
691 | 2.90M | std::vector<Expr> arguments; |
692 | 2.90M | arguments.reserve(sizeof...(Args)); |
693 | 2.90M | (arguments.push_back(std::forward<Args>(args)), ...); |
694 | 2.90M | return GlobalCallOrMacroImpl(expr_id, function, std::move(arguments)); |
695 | 2.90M | } antlr_parser.cc:cel::Expr cel::parser_internal::(anonymous namespace)::ParserVisitor::GlobalCallOrMacro<cel::Expr, cel::Expr>(long, std::__1::basic_string_view<char, std::__1::char_traits<char> >, cel::Expr&&, cel::Expr&&) Line | Count | Source | 690 | 2.65M | Args&&... args) { | 691 | 2.65M | std::vector<Expr> arguments; | 692 | 2.65M | arguments.reserve(sizeof...(Args)); | 693 | 2.65M | (arguments.push_back(std::forward<Args>(args)), ...); | 694 | 2.65M | return GlobalCallOrMacroImpl(expr_id, function, std::move(arguments)); | 695 | 2.65M | } |
antlr_parser.cc:cel::Expr cel::parser_internal::(anonymous namespace)::ParserVisitor::GlobalCallOrMacro<cel::Expr>(long, std::__1::basic_string_view<char, std::__1::char_traits<char> >, cel::Expr&&) Line | Count | Source | 690 | 251k | Args&&... args) { | 691 | 251k | std::vector<Expr> arguments; | 692 | 251k | arguments.reserve(sizeof...(Args)); | 693 | 251k | (arguments.push_back(std::forward<Args>(args)), ...); | 694 | 251k | return GlobalCallOrMacroImpl(expr_id, function, std::move(arguments)); | 695 | 251k | } |
|
696 | | |
697 | | Expr GlobalCallOrMacroImpl(int64_t expr_id, absl::string_view function, |
698 | | std::vector<Expr> args); |
699 | | Expr ReceiverCallOrMacroImpl(int64_t expr_id, absl::string_view function, |
700 | | Expr target, std::vector<Expr> args); |
701 | | std::string ExtractQualifiedName(antlr4::ParserRuleContext* ctx, |
702 | | const Expr& e); |
703 | | |
704 | | std::string NormalizeIdentifier(CelParser::EscapeIdentContext* ctx); |
705 | | std::any VisitUnaryOps(const std::vector<antlr4::Token*>& ops, |
706 | | CelParser::MemberContext* member, |
707 | | absl::string_view op_name); |
708 | | // Attempt to unnest parse context. |
709 | | // |
710 | | // Walk the parse tree to the first complex term to reduce recursive depth in |
711 | | // the visit* calls. |
712 | | antlr4::tree::ParseTree* UnnestContext(antlr4::tree::ParseTree* tree); |
713 | | |
714 | | private: |
715 | | const cel::Source& source_; |
716 | | cel::ParserMacroExprFactory factory_; |
717 | | const cel::MacroRegistry& macro_registry_; |
718 | | int recursion_depth_; |
719 | | const int max_recursion_depth_; |
720 | | const bool add_macro_calls_; |
721 | | const bool enable_optional_syntax_; |
722 | | const bool enable_quoted_identifiers_; |
723 | | const bool enable_variadic_logical_operators_; |
724 | | const bool fold_unary_operators_; |
725 | | }; |
726 | | |
727 | | template <typename T, typename = std::enable_if_t< |
728 | | std::is_base_of<antlr4::tree::ParseTree, T>::value>> |
729 | 132M | T* tree_as(antlr4::tree::ParseTree* tree) { |
730 | 132M | return dynamic_cast<T*>(tree); |
731 | 132M | } antlr_parser.cc:cel_parser_internal::CelParser::PrimaryExprContext* cel::parser_internal::(anonymous namespace)::tree_as<cel_parser_internal::CelParser::PrimaryExprContext, void>(antlr4::tree::ParseTree*) Line | Count | Source | 729 | 9.61M | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 9.61M | return dynamic_cast<T*>(tree); | 731 | 9.61M | } |
antlr_parser.cc:cel_parser_internal::CelParser::SelectContext* cel::parser_internal::(anonymous namespace)::tree_as<cel_parser_internal::CelParser::SelectContext, void>(antlr4::tree::ParseTree*) Line | Count | Source | 729 | 392k | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 392k | return dynamic_cast<T*>(tree); | 731 | 392k | } |
antlr_parser.cc:cel_parser_internal::CelParser::MemberCallContext* cel::parser_internal::(anonymous namespace)::tree_as<cel_parser_internal::CelParser::MemberCallContext, void>(antlr4::tree::ParseTree*) Line | Count | Source | 729 | 335k | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 335k | return dynamic_cast<T*>(tree); | 731 | 335k | } |
antlr_parser.cc:cel_parser_internal::CelParser::IndexContext* cel::parser_internal::(anonymous namespace)::tree_as<cel_parser_internal::CelParser::IndexContext, void>(antlr4::tree::ParseTree*) Line | Count | Source | 729 | 19.0k | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 19.0k | return dynamic_cast<T*>(tree); | 731 | 19.0k | } |
antlr_parser.cc:cel_parser_internal::CelParser::SimpleIdentifierContext* cel::parser_internal::(anonymous namespace)::tree_as<cel_parser_internal::CelParser::SimpleIdentifierContext, void>(antlr4::tree::ParseTree*) Line | Count | Source | 729 | 75.1k | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 75.1k | return dynamic_cast<T*>(tree); | 731 | 75.1k | } |
antlr_parser.cc:cel_parser_internal::CelParser::EscapedIdentifierContext* cel::parser_internal::(anonymous namespace)::tree_as<cel_parser_internal::CelParser::EscapedIdentifierContext, void>(antlr4::tree::ParseTree*) Line | Count | Source | 729 | 2.44k | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 2.44k | return dynamic_cast<T*>(tree); | 731 | 2.44k | } |
antlr_parser.cc:cel_parser_internal::CelParser::NestedContext* cel::parser_internal::(anonymous namespace)::tree_as<cel_parser_internal::CelParser::NestedContext, void>(antlr4::tree::ParseTree*) Line | Count | Source | 729 | 8.49M | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 8.49M | return dynamic_cast<T*>(tree); | 731 | 8.49M | } |
antlr_parser.cc:cel_parser_internal::CelParser::IdentContext* cel::parser_internal::(anonymous namespace)::tree_as<cel_parser_internal::CelParser::IdentContext, void>(antlr4::tree::ParseTree*) Line | Count | Source | 729 | 4.24M | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 4.24M | return dynamic_cast<T*>(tree); | 731 | 4.24M | } |
antlr_parser.cc:cel_parser_internal::CelParser::GlobalCallContext* cel::parser_internal::(anonymous namespace)::tree_as<cel_parser_internal::CelParser::GlobalCallContext, void>(antlr4::tree::ParseTree*) Line | Count | Source | 729 | 1.40M | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 1.40M | return dynamic_cast<T*>(tree); | 731 | 1.40M | } |
antlr_parser.cc:cel_parser_internal::CelParser::CreateListContext* cel::parser_internal::(anonymous namespace)::tree_as<cel_parser_internal::CelParser::CreateListContext, void>(antlr4::tree::ParseTree*) Line | Count | Source | 729 | 1.36M | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 1.36M | return dynamic_cast<T*>(tree); | 731 | 1.36M | } |
antlr_parser.cc:cel_parser_internal::CelParser::CreateMapContext* cel::parser_internal::(anonymous namespace)::tree_as<cel_parser_internal::CelParser::CreateMapContext, void>(antlr4::tree::ParseTree*) Line | Count | Source | 729 | 1.32M | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 1.32M | return dynamic_cast<T*>(tree); | 731 | 1.32M | } |
antlr_parser.cc:cel_parser_internal::CelParser::CreateMessageContext* cel::parser_internal::(anonymous namespace)::tree_as<cel_parser_internal::CelParser::CreateMessageContext, void>(antlr4::tree::ParseTree*) Line | Count | Source | 729 | 1.31M | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 1.31M | return dynamic_cast<T*>(tree); | 731 | 1.31M | } |
antlr_parser.cc:cel_parser_internal::CelParser::ConstantLiteralContext* cel::parser_internal::(anonymous namespace)::tree_as<cel_parser_internal::CelParser::ConstantLiteralContext, void>(antlr4::tree::ParseTree*) Line | Count | Source | 729 | 1.30M | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 1.30M | return dynamic_cast<T*>(tree); | 731 | 1.30M | } |
antlr_parser.cc:cel_parser_internal::CelParser::IntContext* cel::parser_internal::(anonymous namespace)::tree_as<cel_parser_internal::CelParser::IntContext, void>(antlr4::tree::ParseTree*) Line | Count | Source | 729 | 1.30M | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 1.30M | return dynamic_cast<T*>(tree); | 731 | 1.30M | } |
antlr_parser.cc:cel_parser_internal::CelParser::UintContext* cel::parser_internal::(anonymous namespace)::tree_as<cel_parser_internal::CelParser::UintContext, void>(antlr4::tree::ParseTree*) Line | Count | Source | 729 | 387k | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 387k | return dynamic_cast<T*>(tree); | 731 | 387k | } |
antlr_parser.cc:cel_parser_internal::CelParser::DoubleContext* cel::parser_internal::(anonymous namespace)::tree_as<cel_parser_internal::CelParser::DoubleContext, void>(antlr4::tree::ParseTree*) Line | Count | Source | 729 | 368k | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 368k | return dynamic_cast<T*>(tree); | 731 | 368k | } |
antlr_parser.cc:cel_parser_internal::CelParser::StringContext* cel::parser_internal::(anonymous namespace)::tree_as<cel_parser_internal::CelParser::StringContext, void>(antlr4::tree::ParseTree*) Line | Count | Source | 729 | 315k | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 315k | return dynamic_cast<T*>(tree); | 731 | 315k | } |
antlr_parser.cc:cel_parser_internal::CelParser::BytesContext* cel::parser_internal::(anonymous namespace)::tree_as<cel_parser_internal::CelParser::BytesContext, void>(antlr4::tree::ParseTree*) Line | Count | Source | 729 | 39.8k | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 39.8k | return dynamic_cast<T*>(tree); | 731 | 39.8k | } |
antlr_parser.cc:cel_parser_internal::CelParser::BoolFalseContext* cel::parser_internal::(anonymous namespace)::tree_as<cel_parser_internal::CelParser::BoolFalseContext, void>(antlr4::tree::ParseTree*) Line | Count | Source | 729 | 29.6k | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 29.6k | return dynamic_cast<T*>(tree); | 731 | 29.6k | } |
antlr_parser.cc:cel_parser_internal::CelParser::BoolTrueContext* cel::parser_internal::(anonymous namespace)::tree_as<cel_parser_internal::CelParser::BoolTrueContext, void>(antlr4::tree::ParseTree*) Line | Count | Source | 729 | 5.43k | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 5.43k | return dynamic_cast<T*>(tree); | 731 | 5.43k | } |
antlr_parser.cc:cel_parser_internal::CelParser::NullContext* cel::parser_internal::(anonymous namespace)::tree_as<cel_parser_internal::CelParser::NullContext, void>(antlr4::tree::ParseTree*) Line | Count | Source | 729 | 3.25k | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 3.25k | return dynamic_cast<T*>(tree); | 731 | 3.25k | } |
antlr_parser.cc:cel_parser_internal::CelParser::StartContext* cel::parser_internal::(anonymous namespace)::tree_as<cel_parser_internal::CelParser::StartContext, void>(antlr4::tree::ParseTree*) Line | Count | Source | 729 | 14.9M | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 14.9M | return dynamic_cast<T*>(tree); | 731 | 14.9M | } |
antlr_parser.cc:cel_parser_internal::CelParser::ExprContext* cel::parser_internal::(anonymous namespace)::tree_as<cel_parser_internal::CelParser::ExprContext, void>(antlr4::tree::ParseTree*) Line | Count | Source | 729 | 14.9M | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 14.9M | return dynamic_cast<T*>(tree); | 731 | 14.9M | } |
antlr_parser.cc:cel_parser_internal::CelParser::ConditionalAndContext* cel::parser_internal::(anonymous namespace)::tree_as<cel_parser_internal::CelParser::ConditionalAndContext, void>(antlr4::tree::ParseTree*) Line | Count | Source | 729 | 14.9M | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 14.9M | return dynamic_cast<T*>(tree); | 731 | 14.9M | } |
antlr_parser.cc:cel_parser_internal::CelParser::ConditionalOrContext* cel::parser_internal::(anonymous namespace)::tree_as<cel_parser_internal::CelParser::ConditionalOrContext, void>(antlr4::tree::ParseTree*) Line | Count | Source | 729 | 14.9M | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 14.9M | return dynamic_cast<T*>(tree); | 731 | 14.9M | } |
antlr_parser.cc:cel_parser_internal::CelParser::RelationContext* cel::parser_internal::(anonymous namespace)::tree_as<cel_parser_internal::CelParser::RelationContext, void>(antlr4::tree::ParseTree*) Line | Count | Source | 729 | 14.9M | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 14.9M | return dynamic_cast<T*>(tree); | 731 | 14.9M | } |
antlr_parser.cc:cel_parser_internal::CelParser::CalcContext* cel::parser_internal::(anonymous namespace)::tree_as<cel_parser_internal::CelParser::CalcContext, void>(antlr4::tree::ParseTree*) Line | Count | Source | 729 | 14.8M | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 14.8M | return dynamic_cast<T*>(tree); | 731 | 14.8M | } |
antlr_parser.cc:cel_parser_internal::CelParser::LogicalNotContext* cel::parser_internal::(anonymous namespace)::tree_as<cel_parser_internal::CelParser::LogicalNotContext, void>(antlr4::tree::ParseTree*) Line | Count | Source | 729 | 4.64M | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 4.64M | return dynamic_cast<T*>(tree); | 731 | 4.64M | } |
antlr_parser.cc:cel_parser_internal::CelParser::MemberExprContext* cel::parser_internal::(anonymous namespace)::tree_as<cel_parser_internal::CelParser::MemberExprContext, void>(antlr4::tree::ParseTree*) Line | Count | Source | 729 | 5.37M | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 5.37M | return dynamic_cast<T*>(tree); | 731 | 5.37M | } |
antlr_parser.cc:cel_parser_internal::CelParser::MapInitializerListContext* cel::parser_internal::(anonymous namespace)::tree_as<cel_parser_internal::CelParser::MapInitializerListContext, void>(antlr4::tree::ParseTree*) Line | Count | Source | 729 | 279k | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 279k | return dynamic_cast<T*>(tree); | 731 | 279k | } |
antlr_parser.cc:cel_parser_internal::CelParser::NegateContext* cel::parser_internal::(anonymous namespace)::tree_as<cel_parser_internal::CelParser::NegateContext, void>(antlr4::tree::ParseTree*) Line | Count | Source | 729 | 279k | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 279k | return dynamic_cast<T*>(tree); | 731 | 279k | } |
antlr_parser.cc:cel_parser_internal::CelParser::UnaryContext* cel::parser_internal::(anonymous namespace)::tree_as<cel_parser_internal::CelParser::UnaryContext, void>(antlr4::tree::ParseTree*) Line | Count | Source | 729 | 10.6k | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 10.6k | return dynamic_cast<T*>(tree); | 731 | 10.6k | } |
Unexecuted instantiation: antlr_parser.cc:antlr4::ParserRuleContext* cel::parser_internal::(anonymous namespace)::tree_as<antlr4::ParserRuleContext, void>(antlr4::tree::ParseTree*) |
732 | | |
733 | 7.29M | std::any ParserVisitor::visit(antlr4::tree::ParseTree* tree) { |
734 | 7.29M | ScopedIncrement inc(recursion_depth_); |
735 | 7.29M | if (recursion_depth_ > max_recursion_depth_) { |
736 | 2.69k | return ExprToAny(factory_.ReportError( |
737 | 2.69k | absl::StrFormat("Exceeded max recursion depth of %d when parsing.", |
738 | 2.69k | max_recursion_depth_))); |
739 | 2.69k | } |
740 | 7.29M | tree = UnnestContext(tree); |
741 | 7.29M | if (auto* ctx = tree_as<CelParser::StartContext>(tree)) { |
742 | 0 | return visitStart(ctx); |
743 | 7.29M | } else if (auto* ctx = tree_as<CelParser::ExprContext>(tree)) { |
744 | 2.87k | return visitExpr(ctx); |
745 | 7.29M | } else if (auto* ctx = tree_as<CelParser::ConditionalAndContext>(tree)) { |
746 | 1.68k | return visitConditionalAnd(ctx); |
747 | 7.29M | } else if (auto* ctx = tree_as<CelParser::ConditionalOrContext>(tree)) { |
748 | 4.94k | return visitConditionalOr(ctx); |
749 | 7.28M | } else if (auto* ctx = tree_as<CelParser::RelationContext>(tree)) { |
750 | 44.3k | return visitRelation(ctx); |
751 | 7.24M | } else if (auto* ctx = tree_as<CelParser::CalcContext>(tree)) { |
752 | 2.60M | return visitCalc(ctx); |
753 | 4.64M | } else if (auto* ctx = tree_as<CelParser::LogicalNotContext>(tree)) { |
754 | 4.32k | return visitLogicalNot(ctx); |
755 | 4.63M | } else if (auto* ctx = tree_as<CelParser::PrimaryExprContext>(tree)) { |
756 | 4.24M | return visitPrimaryExpr(ctx); |
757 | 4.24M | } else if (auto* ctx = tree_as<CelParser::MemberExprContext>(tree)) { |
758 | 0 | return visitMemberExpr(ctx); |
759 | 392k | } else if (auto* ctx = tree_as<CelParser::SelectContext>(tree)) { |
760 | 57.3k | return visitSelect(ctx); |
761 | 335k | } else if (auto* ctx = tree_as<CelParser::MemberCallContext>(tree)) { |
762 | 56.3k | return visitMemberCall(ctx); |
763 | 279k | } else if (auto* ctx = tree_as<CelParser::MapInitializerListContext>(tree)) { |
764 | 0 | return visitMapInitializerList(ctx); |
765 | 279k | } else if (auto* ctx = tree_as<CelParser::NegateContext>(tree)) { |
766 | 259k | return visitNegate(ctx); |
767 | 259k | } else if (auto* ctx = tree_as<CelParser::IndexContext>(tree)) { |
768 | 8.41k | return visitIndex(ctx); |
769 | 10.6k | } else if (auto* ctx = tree_as<CelParser::UnaryContext>(tree)) { |
770 | 8.67k | return visitUnary(ctx); |
771 | 8.67k | } else if (auto* ctx = tree_as<CelParser::CreateListContext>(tree)) { |
772 | 0 | return visitCreateList(ctx); |
773 | 1.95k | } else if (auto* ctx = tree_as<CelParser::CreateMessageContext>(tree)) { |
774 | 0 | return visitCreateMessage(ctx); |
775 | 1.95k | } else if (auto* ctx = tree_as<CelParser::CreateMapContext>(tree)) { |
776 | 0 | return visitCreateMap(ctx); |
777 | 0 | } |
778 | | |
779 | 1.95k | if (tree) { |
780 | 0 | return ExprToAny( |
781 | 0 | factory_.ReportError(SourceRangeFromParserRuleContext( |
782 | 0 | tree_as<antlr4::ParserRuleContext>(tree)), |
783 | 0 | "unknown parsetree type")); |
784 | 0 | } |
785 | 1.95k | return ExprToAny(factory_.ReportError("<<nil>> parsetree")); |
786 | 1.95k | } |
787 | | |
788 | 4.24M | std::any ParserVisitor::visitPrimaryExpr(CelParser::PrimaryExprContext* pctx) { |
789 | 4.24M | CelParser::PrimaryContext* primary = pctx->primary(); |
790 | 4.24M | if (auto* ctx = tree_as<CelParser::NestedContext>(primary)) { |
791 | 0 | return visitNested(ctx); |
792 | 4.24M | } else if (auto* ctx = tree_as<CelParser::IdentContext>(primary)) { |
793 | 2.83M | return visitIdent(ctx); |
794 | 2.83M | } else if (auto* ctx = tree_as<CelParser::GlobalCallContext>(primary)) { |
795 | 48.0k | return visitGlobalCall(ctx); |
796 | 1.35M | } else if (auto* ctx = tree_as<CelParser::CreateListContext>(primary)) { |
797 | 31.4k | return visitCreateList(ctx); |
798 | 1.32M | } else if (auto* ctx = tree_as<CelParser::CreateMapContext>(primary)) { |
799 | 12.1k | return visitCreateMap(ctx); |
800 | 1.31M | } else if (auto* ctx = tree_as<CelParser::CreateMessageContext>(primary)) { |
801 | 12.2k | return visitCreateMessage(ctx); |
802 | 1.30M | } else if (auto* ctx = tree_as<CelParser::ConstantLiteralContext>(primary)) { |
803 | 1.30M | return visitConstantLiteral(ctx); |
804 | 1.30M | } |
805 | 1.95k | if (factory_.HasErrors()) { |
806 | | // ANTLR creates PrimaryContext rather than a derived class during certain |
807 | | // error conditions. This is odd, but we ignore it as we already have errors |
808 | | // that occurred. |
809 | 1.95k | return ExprToAny(factory_.NewUnspecified(factory_.NextId({}))); |
810 | 1.95k | } |
811 | 0 | return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(pctx), |
812 | 0 | "invalid primary expression")); |
813 | 1.95k | } |
814 | | |
815 | 0 | std::any ParserVisitor::visitMemberExpr(CelParser::MemberExprContext* mctx) { |
816 | 0 | CelParser::MemberContext* member = mctx->member(); |
817 | 0 | if (auto* ctx = tree_as<CelParser::PrimaryExprContext>(member)) { |
818 | 0 | return visitPrimaryExpr(ctx); |
819 | 0 | } else if (auto* ctx = tree_as<CelParser::SelectContext>(member)) { |
820 | 0 | return visitSelect(ctx); |
821 | 0 | } else if (auto* ctx = tree_as<CelParser::MemberCallContext>(member)) { |
822 | 0 | return visitMemberCall(ctx); |
823 | 0 | } else if (auto* ctx = tree_as<CelParser::IndexContext>(member)) { |
824 | 0 | return visitIndex(ctx); |
825 | 0 | } |
826 | 0 | return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(mctx), |
827 | 0 | "unsupported simple expression")); |
828 | 0 | } |
829 | | |
830 | 0 | std::any ParserVisitor::visitStart(CelParser::StartContext* ctx) { |
831 | 0 | return visit(ctx->expr()); |
832 | 0 | } |
833 | | |
834 | | antlr4::tree::ParseTree* ParserVisitor::UnnestContext( |
835 | 7.29M | antlr4::tree::ParseTree* tree) { |
836 | 7.29M | antlr4::tree::ParseTree* last = nullptr; |
837 | 8.03M | while (tree != last) { |
838 | 7.63M | last = tree; |
839 | | |
840 | 7.63M | if (auto* ctx = tree_as<CelParser::StartContext>(tree)) { |
841 | 33.6k | tree = ctx->expr(); |
842 | 33.6k | } |
843 | | |
844 | 7.63M | if (auto* ctx = tree_as<CelParser::ExprContext>(tree)) { |
845 | 594k | if (ctx->op != nullptr) { |
846 | 2.87k | return ctx; |
847 | 2.87k | } |
848 | 591k | tree = ctx->e; |
849 | 591k | } |
850 | | |
851 | 7.63M | if (auto* ctx = tree_as<CelParser::ConditionalOrContext>(tree)) { |
852 | 1.37M | if (!ctx->ops.empty()) { |
853 | 4.94k | return ctx; |
854 | 4.94k | } |
855 | 1.36M | tree = ctx->e; |
856 | 1.36M | } |
857 | | |
858 | 7.62M | if (auto* ctx = tree_as<CelParser::ConditionalAndContext>(tree)) { |
859 | 1.46M | if (!ctx->ops.empty()) { |
860 | 1.68k | return ctx; |
861 | 1.68k | } |
862 | 1.46M | tree = ctx->e; |
863 | 1.46M | } |
864 | | |
865 | 7.62M | if (auto* ctx = tree_as<CelParser::RelationContext>(tree)) { |
866 | 1.70M | if (ctx->calc() == nullptr) { |
867 | 44.3k | return ctx; |
868 | 44.3k | } |
869 | 1.65M | tree = ctx->calc(); |
870 | 1.65M | } |
871 | | |
872 | 7.57M | if (auto* ctx = tree_as<CelParser::CalcContext>(tree)) { |
873 | 6.85M | if (ctx->unary() == nullptr) { |
874 | 2.60M | return ctx; |
875 | 2.60M | } |
876 | 4.25M | tree = ctx->unary(); |
877 | 4.25M | } |
878 | | |
879 | 4.97M | if (auto* ctx = tree_as<CelParser::MemberExprContext>(tree)) { |
880 | 3.98M | tree = ctx->member(); |
881 | 3.98M | } |
882 | | |
883 | 4.97M | if (auto* ctx = tree_as<CelParser::PrimaryExprContext>(tree)) { |
884 | 4.24M | if (auto* nested = tree_as<CelParser::NestedContext>(ctx->primary())) { |
885 | 2.70k | tree = nested->e; |
886 | 4.24M | } else { |
887 | 4.24M | return ctx; |
888 | 4.24M | } |
889 | 4.24M | } |
890 | 4.97M | } |
891 | | |
892 | 397k | return tree; |
893 | 7.29M | } |
894 | | |
895 | 778k | std::any ParserVisitor::visitExpr(CelParser::ExprContext* ctx) { |
896 | 778k | auto result = ExprFromAny(visit(ctx->e)); |
897 | 778k | if (!ctx->op) { |
898 | 775k | return ExprToAny(std::move(result)); |
899 | 775k | } |
900 | 3.15k | std::vector<Expr> arguments; |
901 | 3.15k | arguments.reserve(3); |
902 | 3.15k | arguments.push_back(std::move(result)); |
903 | 3.15k | int64_t op_id = factory_.NextId(SourceRangeFromToken(ctx->op)); |
904 | 3.15k | arguments.push_back(ExprFromAny(visit(ctx->e1))); |
905 | 3.15k | arguments.push_back(ExprFromAny(visit(ctx->e2))); |
906 | | |
907 | 3.15k | return ExprToAny( |
908 | 3.15k | factory_.NewCall(op_id, CelOperator::CONDITIONAL, std::move(arguments))); |
909 | 778k | } |
910 | | |
911 | | std::any ParserVisitor::visitConditionalOr( |
912 | 4.94k | CelParser::ConditionalOrContext* ctx) { |
913 | 4.94k | auto result = ExprFromAny(visit(ctx->e)); |
914 | 4.94k | if (ctx->ops.empty()) { |
915 | 0 | return ExprToAny(std::move(result)); |
916 | 0 | } |
917 | 4.94k | ExpressionBalancer b(factory_, CelOperator::LOGICAL_OR, std::move(result)); |
918 | 100k | for (size_t i = 0; i < ctx->ops.size(); ++i) { |
919 | 95.9k | auto op = ctx->ops[i]; |
920 | 95.9k | if (i >= ctx->e1.size()) { |
921 | 0 | return ExprToAny( |
922 | 0 | factory_.ReportError(SourceRangeFromParserRuleContext(ctx), |
923 | 0 | "unexpected character, wanted '||'")); |
924 | 0 | } |
925 | 95.9k | auto next = ExprFromAny(visit(ctx->e1[i])); |
926 | 95.9k | int64_t op_id = factory_.NextId(SourceRangeFromToken(op)); |
927 | 95.9k | b.AddTerm(op_id, std::move(next)); |
928 | 95.9k | } |
929 | 4.94k | return ExprToAny(b.Balance(enable_variadic_logical_operators_)); |
930 | 4.94k | } |
931 | | |
932 | | std::any ParserVisitor::visitConditionalAnd( |
933 | 1.68k | CelParser::ConditionalAndContext* ctx) { |
934 | 1.68k | auto result = ExprFromAny(visit(ctx->e)); |
935 | 1.68k | if (ctx->ops.empty()) { |
936 | 0 | return ExprToAny(std::move(result)); |
937 | 0 | } |
938 | 1.68k | ExpressionBalancer b(factory_, CelOperator::LOGICAL_AND, std::move(result)); |
939 | 145k | for (size_t i = 0; i < ctx->ops.size(); ++i) { |
940 | 143k | auto op = ctx->ops[i]; |
941 | 143k | if (i >= ctx->e1.size()) { |
942 | 0 | return ExprToAny( |
943 | 0 | factory_.ReportError(SourceRangeFromParserRuleContext(ctx), |
944 | 0 | "unexpected character, wanted '&&'")); |
945 | 0 | } |
946 | 143k | auto next = ExprFromAny(visit(ctx->e1[i])); |
947 | 143k | int64_t op_id = factory_.NextId(SourceRangeFromToken(op)); |
948 | 143k | b.AddTerm(op_id, std::move(next)); |
949 | 143k | } |
950 | 1.68k | return ExprToAny(b.Balance(enable_variadic_logical_operators_)); |
951 | 1.68k | } |
952 | | |
953 | 44.3k | std::any ParserVisitor::visitRelation(CelParser::RelationContext* ctx) { |
954 | 44.3k | if (ctx->calc()) { |
955 | 0 | return visit(ctx->calc()); |
956 | 0 | } |
957 | 44.3k | std::string op_text; |
958 | 44.3k | if (ctx->op) { |
959 | 44.3k | op_text = ctx->op->getText(); |
960 | 44.3k | } |
961 | 44.3k | auto op = ReverseLookupOperator(op_text); |
962 | 44.3k | if (op) { |
963 | 44.3k | auto lhs = ExprFromAny(visit(ctx->relation(0))); |
964 | 44.3k | int64_t op_id = factory_.NextId(SourceRangeFromToken(ctx->op)); |
965 | 44.3k | auto rhs = ExprFromAny(visit(ctx->relation(1))); |
966 | 44.3k | return ExprToAny( |
967 | 44.3k | GlobalCallOrMacro(op_id, *op, std::move(lhs), std::move(rhs))); |
968 | 44.3k | } |
969 | 0 | return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(ctx), |
970 | 0 | "operator not found")); |
971 | 44.3k | } |
972 | | |
973 | 2.60M | std::any ParserVisitor::visitCalc(CelParser::CalcContext* ctx) { |
974 | 2.60M | if (ctx->unary()) { |
975 | 0 | return visit(ctx->unary()); |
976 | 0 | } |
977 | 2.60M | std::string op_text; |
978 | 2.60M | if (ctx->op) { |
979 | 2.60M | op_text = ctx->op->getText(); |
980 | 2.60M | } |
981 | 2.60M | auto op = ReverseLookupOperator(op_text); |
982 | 2.60M | if (op) { |
983 | 2.60M | auto lhs = ExprFromAny(visit(ctx->calc(0))); |
984 | 2.60M | int64_t op_id = factory_.NextId(SourceRangeFromToken(ctx->op)); |
985 | 2.60M | auto rhs = ExprFromAny(visit(ctx->calc(1))); |
986 | 2.60M | return ExprToAny( |
987 | 2.60M | GlobalCallOrMacro(op_id, *op, std::move(lhs), std::move(rhs))); |
988 | 2.60M | } |
989 | 0 | return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(ctx), |
990 | 0 | "operator not found")); |
991 | 2.60M | } |
992 | | |
993 | 8.67k | std::any ParserVisitor::visitUnary(CelParser::UnaryContext* ctx) { |
994 | 8.67k | return ExprToAny(factory_.NewStringConst( |
995 | 8.67k | factory_.NextId(SourceRangeFromParserRuleContext(ctx)), "<<error>>")); |
996 | 8.67k | } |
997 | | |
998 | | std::any ParserVisitor::VisitUnaryOps(const std::vector<antlr4::Token*>& ops, |
999 | | CelParser::MemberContext* member, |
1000 | 264k | absl::string_view op_name) { |
1001 | 264k | if (fold_unary_operators_) { |
1002 | 264k | if (ops.size() % 2 == 0) { |
1003 | 12.7k | return visit(member); |
1004 | 12.7k | } |
1005 | 251k | int64_t op_id = factory_.NextId(SourceRangeFromToken(ops[0])); |
1006 | 251k | auto target = ExprFromAny(visit(member)); |
1007 | 251k | return ExprToAny(GlobalCallOrMacro(op_id, op_name, std::move(target))); |
1008 | 264k | } |
1009 | | |
1010 | 0 | std::vector<int64_t> op_ids; |
1011 | 0 | op_ids.reserve(ops.size()); |
1012 | 0 | for (const auto* op : ops) { |
1013 | 0 | op_ids.push_back(factory_.NextId(SourceRangeFromToken(op))); |
1014 | 0 | } |
1015 | |
|
1016 | 0 | auto target = ExprFromAny(visit(member)); |
1017 | 0 | for (int i = static_cast<int>(op_ids.size()) - 1; i >= 0; --i) { |
1018 | 0 | target = GlobalCallOrMacro(op_ids[i], op_name, std::move(target)); |
1019 | 0 | } |
1020 | 0 | return ExprToAny(std::move(target)); |
1021 | 264k | } |
1022 | | |
1023 | 4.32k | std::any ParserVisitor::visitLogicalNot(CelParser::LogicalNotContext* ctx) { |
1024 | 4.32k | return VisitUnaryOps(ctx->ops, ctx->member(), CelOperator::LOGICAL_NOT); |
1025 | 4.32k | } |
1026 | | |
1027 | 259k | std::any ParserVisitor::visitNegate(CelParser::NegateContext* ctx) { |
1028 | 259k | return VisitUnaryOps(ctx->ops, ctx->member(), CelOperator::NEGATE); |
1029 | 259k | } |
1030 | | |
1031 | | std::string ParserVisitor::NormalizeIdentifier( |
1032 | 75.1k | CelParser::EscapeIdentContext* ctx) { |
1033 | 75.1k | if (auto* raw_id = tree_as<CelParser::SimpleIdentifierContext>(ctx); raw_id) { |
1034 | 72.7k | return raw_id->id->getText(); |
1035 | 72.7k | } |
1036 | 2.44k | if (auto* escaped_id = tree_as<CelParser::EscapedIdentifierContext>(ctx); |
1037 | 2.44k | escaped_id) { |
1038 | 1.31k | if (!enable_quoted_identifiers_) { |
1039 | 0 | factory_.ReportError(SourceRangeFromParserRuleContext(ctx), |
1040 | 0 | "unsupported syntax '`'"); |
1041 | 0 | } |
1042 | 1.31k | auto escaped_id_text = escaped_id->id->getText(); |
1043 | 1.31k | return escaped_id_text.substr(1, escaped_id_text.size() - 2); |
1044 | 1.31k | } |
1045 | | |
1046 | | // Fallthrough might occur if the parser is in an error state. |
1047 | 1.13k | return ""; |
1048 | 2.44k | } |
1049 | | |
1050 | 57.3k | std::any ParserVisitor::visitSelect(CelParser::SelectContext* ctx) { |
1051 | 57.3k | auto operand = ExprFromAny(visit(ctx->member())); |
1052 | | // Handle the error case where no valid identifier is specified. |
1053 | 57.3k | if (!ctx->id || !ctx->op) { |
1054 | 0 | return ExprToAny(factory_.NewUnspecified( |
1055 | 0 | factory_.NextId(SourceRangeFromParserRuleContext(ctx)))); |
1056 | 0 | } |
1057 | 57.3k | auto id = NormalizeIdentifier(ctx->id); |
1058 | 57.3k | if (ctx->opt != nullptr) { |
1059 | 6.37k | if (!enable_optional_syntax_) { |
1060 | 6.37k | return ExprToAny(factory_.ReportError( |
1061 | 6.37k | SourceRangeFromParserRuleContext(ctx), "unsupported syntax '.?'")); |
1062 | 6.37k | } |
1063 | 0 | auto op_id = factory_.NextId(SourceRangeFromToken(ctx->op)); |
1064 | 0 | std::vector<Expr> arguments; |
1065 | 0 | arguments.reserve(2); |
1066 | 0 | arguments.push_back(std::move(operand)); |
1067 | 0 | arguments.push_back(factory_.NewStringConst( |
1068 | 0 | factory_.NextId(SourceRangeFromParserRuleContext(ctx)), std::move(id))); |
1069 | 0 | return ExprToAny(factory_.NewCall(op_id, "_?._", std::move(arguments))); |
1070 | 6.37k | } |
1071 | 50.9k | return ExprToAny( |
1072 | 50.9k | factory_.NewSelect(factory_.NextId(SourceRangeFromToken(ctx->op)), |
1073 | 50.9k | std::move(operand), std::move(id))); |
1074 | 57.3k | } |
1075 | | |
1076 | 56.3k | std::any ParserVisitor::visitMemberCall(CelParser::MemberCallContext* ctx) { |
1077 | 56.3k | auto operand = ExprFromAny(visit(ctx->member())); |
1078 | | // Handle the error case where no valid identifier is specified. |
1079 | 56.3k | if (!ctx->id) { |
1080 | 0 | return ExprToAny(factory_.NewUnspecified( |
1081 | 0 | factory_.NextId(SourceRangeFromParserRuleContext(ctx)))); |
1082 | 0 | } |
1083 | 56.3k | auto id = ctx->id->getText(); |
1084 | 56.3k | int64_t op_id = factory_.NextId(SourceRangeFromToken(ctx->open)); |
1085 | 56.3k | auto args = visitList(ctx->args); |
1086 | 56.3k | return ExprToAny( |
1087 | 56.3k | ReceiverCallOrMacroImpl(op_id, id, std::move(operand), std::move(args))); |
1088 | 56.3k | } |
1089 | | |
1090 | 8.41k | std::any ParserVisitor::visitIndex(CelParser::IndexContext* ctx) { |
1091 | 8.41k | auto target = ExprFromAny(visit(ctx->member())); |
1092 | 8.41k | int64_t op_id = factory_.NextId(SourceRangeFromToken(ctx->op)); |
1093 | 8.41k | auto index = ExprFromAny(visit(ctx->index)); |
1094 | 8.41k | if (!enable_optional_syntax_ && ctx->opt != nullptr) { |
1095 | 1.58k | return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(ctx), |
1096 | 1.58k | "unsupported syntax '.?'")); |
1097 | 1.58k | } |
1098 | 6.82k | return ExprToAny(GlobalCallOrMacro( |
1099 | 6.82k | op_id, ctx->opt != nullptr ? "_[?_]" : CelOperator::INDEX, |
1100 | 6.82k | std::move(target), std::move(index))); |
1101 | 8.41k | } |
1102 | | |
1103 | | std::any ParserVisitor::visitCreateMessage( |
1104 | 12.2k | CelParser::CreateMessageContext* ctx) { |
1105 | 12.2k | std::vector<std::string> parts; |
1106 | 12.2k | parts.reserve(ctx->ids.size()); |
1107 | 21.5k | for (const auto* id : ctx->ids) { |
1108 | 21.5k | parts.push_back(id->getText()); |
1109 | 21.5k | } |
1110 | 12.2k | std::string name; |
1111 | 12.2k | if (ctx->leadingDot) { |
1112 | 4.85k | name.push_back('.'); |
1113 | 4.85k | name.append(absl::StrJoin(parts, ".")); |
1114 | 7.34k | } else { |
1115 | 7.34k | name = absl::StrJoin(parts, "."); |
1116 | 7.34k | } |
1117 | 12.2k | int64_t obj_id = factory_.NextId(SourceRangeFromParserRuleContext(ctx)); |
1118 | 12.2k | std::vector<StructExprField> fields; |
1119 | 12.2k | if (ctx->entries) { |
1120 | 2.85k | fields = visitFields(ctx->entries); |
1121 | 2.85k | } |
1122 | 12.2k | return ExprToAny( |
1123 | 12.2k | factory_.NewStruct(obj_id, std::move(name), std::move(fields))); |
1124 | 12.2k | } |
1125 | | |
1126 | | std::any ParserVisitor::visitFieldInitializerList( |
1127 | 0 | CelParser::FieldInitializerListContext* ctx) { |
1128 | 0 | return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(ctx), |
1129 | 0 | "<<unreachable>>")); |
1130 | 0 | } |
1131 | | |
1132 | | std::vector<StructExprField> ParserVisitor::visitFields( |
1133 | 2.85k | CelParser::FieldInitializerListContext* ctx) { |
1134 | 2.85k | std::vector<StructExprField> res; |
1135 | 2.85k | if (!ctx || ctx->fields.empty()) { |
1136 | 0 | return res; |
1137 | 0 | } |
1138 | | |
1139 | 2.85k | res.reserve(ctx->fields.size()); |
1140 | 20.6k | for (size_t i = 0; i < ctx->fields.size(); ++i) { |
1141 | 17.9k | if (i >= ctx->cols.size() || i >= ctx->values.size()) { |
1142 | | // This is the result of a syntax error detected elsewhere. |
1143 | 132 | return res; |
1144 | 132 | } |
1145 | 17.8k | auto* f = ctx->fields[i]; |
1146 | 17.8k | if (!f->escapeIdent()) { |
1147 | 0 | ABSL_DCHECK(HasErrored()); |
1148 | | // This is the result of a syntax error detected elsewhere. |
1149 | 0 | return res; |
1150 | 0 | } |
1151 | | |
1152 | 17.8k | std::string id = NormalizeIdentifier(f->escapeIdent()); |
1153 | | |
1154 | 17.8k | int64_t init_id = factory_.NextId(SourceRangeFromToken(ctx->cols[i])); |
1155 | 17.8k | if (!enable_optional_syntax_ && f->opt) { |
1156 | 643 | factory_.ReportError(SourceRangeFromParserRuleContext(ctx), |
1157 | 643 | "unsupported syntax '?'"); |
1158 | 643 | continue; |
1159 | 643 | } |
1160 | 17.1k | auto value = ExprFromAny(visit(ctx->values[i])); |
1161 | 17.1k | res.push_back(factory_.NewStructField(init_id, std::move(id), |
1162 | 17.1k | std::move(value), f->opt != nullptr)); |
1163 | 17.1k | } |
1164 | | |
1165 | 2.72k | return res; |
1166 | 2.85k | } |
1167 | | |
1168 | 2.83M | std::any ParserVisitor::visitIdent(CelParser::IdentContext* ctx) { |
1169 | 2.83M | std::string ident_name; |
1170 | 2.83M | if (ctx->leadingDot) { |
1171 | 5.60k | ident_name = "."; |
1172 | 5.60k | } |
1173 | 2.83M | if (!ctx->id) { |
1174 | 0 | return ExprToAny(factory_.NewUnspecified( |
1175 | 0 | factory_.NextId(SourceRangeFromParserRuleContext(ctx)))); |
1176 | 0 | } |
1177 | | // check if ID is in reserved identifiers |
1178 | 2.83M | if (cel::internal::LexisIsReserved(ctx->id->getText())) { |
1179 | 11.6k | return ExprToAny(factory_.ReportError( |
1180 | 11.6k | SourceRangeFromParserRuleContext(ctx), |
1181 | 11.6k | absl::StrFormat("reserved identifier: %s", ctx->id->getText()))); |
1182 | 11.6k | } |
1183 | | |
1184 | 2.82M | ident_name += ctx->id->getText(); |
1185 | | |
1186 | 2.82M | return ExprToAny(factory_.NewIdent( |
1187 | 2.82M | factory_.NextId(SourceRangeFromToken(ctx->id)), std::move(ident_name))); |
1188 | 2.83M | } |
1189 | | |
1190 | 48.0k | std::any ParserVisitor::visitGlobalCall(CelParser::GlobalCallContext* ctx) { |
1191 | 48.0k | std::string ident_name; |
1192 | 48.0k | if (ctx->leadingDot) { |
1193 | 2.47k | ident_name = "."; |
1194 | 2.47k | } |
1195 | 48.0k | if (!ctx->id || !ctx->op) { |
1196 | 0 | return ExprToAny(factory_.NewUnspecified( |
1197 | 0 | factory_.NextId(SourceRangeFromParserRuleContext(ctx)))); |
1198 | 0 | } |
1199 | | // check if ID is in reserved identifiers |
1200 | 48.0k | if (cel::internal::LexisIsReserved(ctx->id->getText())) { |
1201 | 1.02k | return ExprToAny(factory_.ReportError( |
1202 | 1.02k | SourceRangeFromParserRuleContext(ctx), |
1203 | 1.02k | absl::StrFormat("reserved identifier: %s", ctx->id->getText()))); |
1204 | 1.02k | } |
1205 | | |
1206 | 47.0k | ident_name += ctx->id->getText(); |
1207 | | |
1208 | 47.0k | int64_t op_id = factory_.NextId(SourceRangeFromToken(ctx->op)); |
1209 | 47.0k | auto args = visitList(ctx->args); |
1210 | 47.0k | return ExprToAny( |
1211 | 47.0k | GlobalCallOrMacroImpl(op_id, std::move(ident_name), std::move(args))); |
1212 | 48.0k | } |
1213 | | |
1214 | 0 | std::any ParserVisitor::visitNested(CelParser::NestedContext* ctx) { |
1215 | 0 | return visit(ctx->e); |
1216 | 0 | } |
1217 | | |
1218 | 31.4k | std::any ParserVisitor::visitCreateList(CelParser::CreateListContext* ctx) { |
1219 | 31.4k | int64_t list_id = factory_.NextId(SourceRangeFromParserRuleContext(ctx)); |
1220 | 31.4k | auto elems = visitList(ctx->elems); |
1221 | 31.4k | return ExprToAny(factory_.NewList(list_id, std::move(elems))); |
1222 | 31.4k | } |
1223 | | |
1224 | | std::vector<ListExprElement> ParserVisitor::visitList( |
1225 | 31.4k | CelParser::ListInitContext* ctx) { |
1226 | 31.4k | std::vector<ListExprElement> rv; |
1227 | 31.4k | if (!ctx) return rv; |
1228 | 27.1k | rv.reserve(ctx->elems.size()); |
1229 | 489k | for (size_t i = 0; i < ctx->elems.size(); ++i) { |
1230 | 462k | auto* expr_ctx = ctx->elems[i]; |
1231 | 462k | if (expr_ctx == nullptr) { |
1232 | 0 | return rv; |
1233 | 0 | } |
1234 | 462k | if (!enable_optional_syntax_ && expr_ctx->opt != nullptr) { |
1235 | 1.11k | factory_.ReportError(SourceRangeFromParserRuleContext(ctx), |
1236 | 1.11k | "unsupported syntax '?'"); |
1237 | | // Still generate an ID to detect node limit exceeded. |
1238 | 1.11k | factory_.NextId(SourceRangeFromParserRuleContext(ctx)); |
1239 | 1.11k | rv.push_back(factory_.NewListElement(factory_.NewUnspecified(0), false)); |
1240 | 1.11k | continue; |
1241 | 1.11k | } |
1242 | 461k | rv.push_back(factory_.NewListElement(ExprFromAny(visitExpr(expr_ctx->e)), |
1243 | 461k | expr_ctx->opt != nullptr)); |
1244 | 461k | } |
1245 | 27.1k | return rv; |
1246 | 27.1k | } |
1247 | | |
1248 | 103k | std::vector<Expr> ParserVisitor::visitList(CelParser::ExprListContext* ctx) { |
1249 | 103k | std::vector<Expr> rv; |
1250 | 103k | if (!ctx) return rv; |
1251 | 95.2k | std::transform(ctx->e.begin(), ctx->e.end(), std::back_inserter(rv), |
1252 | 314k | [this](CelParser::ExprContext* expr_ctx) { |
1253 | 314k | return ExprFromAny(visitExpr(expr_ctx)); |
1254 | 314k | }); |
1255 | 95.2k | return rv; |
1256 | 103k | } |
1257 | | |
1258 | 12.1k | std::any ParserVisitor::visitCreateMap(CelParser::CreateMapContext* ctx) { |
1259 | 12.1k | int64_t struct_id = factory_.NextId(SourceRangeFromParserRuleContext(ctx)); |
1260 | 12.1k | std::vector<MapExprEntry> entries; |
1261 | 12.1k | if (ctx->entries) { |
1262 | 5.61k | entries = visitEntries(ctx->entries); |
1263 | 5.61k | } |
1264 | 12.1k | return ExprToAny(factory_.NewMap(struct_id, std::move(entries))); |
1265 | 12.1k | } |
1266 | | |
1267 | | std::any ParserVisitor::visitConstantLiteral( |
1268 | 1.30M | CelParser::ConstantLiteralContext* clctx) { |
1269 | 1.30M | CelParser::LiteralContext* literal = clctx->literal(); |
1270 | 1.30M | if (auto* ctx = tree_as<CelParser::IntContext>(literal)) { |
1271 | 913k | return visitInt(ctx); |
1272 | 913k | } else if (auto* ctx = tree_as<CelParser::UintContext>(literal)) { |
1273 | 19.7k | return visitUint(ctx); |
1274 | 368k | } else if (auto* ctx = tree_as<CelParser::DoubleContext>(literal)) { |
1275 | 52.9k | return visitDouble(ctx); |
1276 | 315k | } else if (auto* ctx = tree_as<CelParser::StringContext>(literal)) { |
1277 | 275k | return visitString(ctx); |
1278 | 275k | } else if (auto* ctx = tree_as<CelParser::BytesContext>(literal)) { |
1279 | 10.2k | return visitBytes(ctx); |
1280 | 29.6k | } else if (auto* ctx = tree_as<CelParser::BoolFalseContext>(literal)) { |
1281 | 24.1k | return visitBoolFalse(ctx); |
1282 | 24.1k | } else if (auto* ctx = tree_as<CelParser::BoolTrueContext>(literal)) { |
1283 | 2.18k | return visitBoolTrue(ctx); |
1284 | 3.25k | } else if (auto* ctx = tree_as<CelParser::NullContext>(literal)) { |
1285 | 2.11k | return visitNull(ctx); |
1286 | 2.11k | } |
1287 | 1.14k | return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(clctx), |
1288 | 1.14k | "invalid constant literal expression")); |
1289 | 1.30M | } |
1290 | | |
1291 | | std::any ParserVisitor::visitMapInitializerList( |
1292 | 0 | CelParser::MapInitializerListContext* ctx) { |
1293 | 0 | return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(ctx), |
1294 | 0 | "<<unreachable>>")); |
1295 | 0 | } |
1296 | | |
1297 | | std::vector<MapExprEntry> ParserVisitor::visitEntries( |
1298 | 5.61k | CelParser::MapInitializerListContext* ctx) { |
1299 | 5.61k | std::vector<MapExprEntry> res; |
1300 | 5.61k | if (!ctx || ctx->keys.empty()) { |
1301 | 0 | return res; |
1302 | 0 | } |
1303 | | |
1304 | 5.61k | res.reserve(ctx->cols.size()); |
1305 | 271k | for (size_t i = 0; i < ctx->cols.size(); ++i) { |
1306 | 265k | auto id = factory_.NextId(SourceRangeFromToken(ctx->cols[i])); |
1307 | 265k | if (!enable_optional_syntax_ && ctx->keys[i]->opt) { |
1308 | 384 | factory_.ReportError(SourceRangeFromParserRuleContext(ctx), |
1309 | 384 | "unsupported syntax '?'"); |
1310 | | // Still generate an ID to detect node limit exceeded. |
1311 | 384 | factory_.NextId(SourceRangeFromParserRuleContext(ctx)); |
1312 | 384 | factory_.NextId(SourceRangeFromParserRuleContext(ctx)); |
1313 | 384 | res.push_back(factory_.NewMapEntry(0, factory_.NewUnspecified(0), |
1314 | 384 | factory_.NewUnspecified(0), false)); |
1315 | 384 | continue; |
1316 | 384 | } |
1317 | 265k | auto key = ExprFromAny(visit(ctx->keys[i]->e)); |
1318 | 265k | auto value = ExprFromAny(visit(ctx->values[i])); |
1319 | 265k | res.push_back(factory_.NewMapEntry(id, std::move(key), std::move(value), |
1320 | 265k | ctx->keys[i]->opt != nullptr)); |
1321 | 265k | } |
1322 | 5.61k | return res; |
1323 | 5.61k | } |
1324 | | |
1325 | 913k | std::any ParserVisitor::visitInt(CelParser::IntContext* ctx) { |
1326 | 913k | std::string value; |
1327 | 913k | if (ctx->sign) { |
1328 | 16.5k | value = ctx->sign->getText(); |
1329 | 16.5k | } |
1330 | 913k | value += ctx->tok->getText(); |
1331 | 913k | int64_t int_value; |
1332 | 913k | if (absl::StartsWith(ctx->tok->getText(), "0x")) { |
1333 | 3.06k | if (absl::SimpleHexAtoi(value, &int_value)) { |
1334 | 1.41k | return ExprToAny(factory_.NewIntConst( |
1335 | 1.41k | factory_.NextId(SourceRangeFromParserRuleContext(ctx)), int_value)); |
1336 | 1.64k | } else { |
1337 | 1.64k | return ExprToAny(factory_.ReportError( |
1338 | 1.64k | SourceRangeFromParserRuleContext(ctx), "invalid hex int literal")); |
1339 | 1.64k | } |
1340 | 3.06k | } |
1341 | 910k | if (absl::SimpleAtoi(value, &int_value)) { |
1342 | 908k | return ExprToAny(factory_.NewIntConst( |
1343 | 908k | factory_.NextId(SourceRangeFromParserRuleContext(ctx)), int_value)); |
1344 | 908k | } else { |
1345 | 2.17k | return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(ctx), |
1346 | 2.17k | "invalid int literal")); |
1347 | 2.17k | } |
1348 | 910k | } |
1349 | | |
1350 | 19.7k | std::any ParserVisitor::visitUint(CelParser::UintContext* ctx) { |
1351 | 19.7k | std::string value = ctx->tok->getText(); |
1352 | | // trim the 'u' designator included in the uint literal. |
1353 | 19.7k | if (!value.empty()) { |
1354 | 19.7k | value.resize(value.size() - 1); |
1355 | 19.7k | } |
1356 | 19.7k | uint64_t uint_value; |
1357 | 19.7k | if (absl::StartsWith(ctx->tok->getText(), "0x")) { |
1358 | 5.80k | if (absl::SimpleHexAtoi(value, &uint_value)) { |
1359 | 2.69k | return ExprToAny(factory_.NewUintConst( |
1360 | 2.69k | factory_.NextId(SourceRangeFromParserRuleContext(ctx)), uint_value)); |
1361 | 3.10k | } else { |
1362 | 3.10k | return ExprToAny(factory_.ReportError( |
1363 | 3.10k | SourceRangeFromParserRuleContext(ctx), "invalid hex uint literal")); |
1364 | 3.10k | } |
1365 | 5.80k | } |
1366 | 13.9k | if (absl::SimpleAtoi(value, &uint_value)) { |
1367 | 10.6k | return ExprToAny(factory_.NewUintConst( |
1368 | 10.6k | factory_.NextId(SourceRangeFromParserRuleContext(ctx)), uint_value)); |
1369 | 10.6k | } else { |
1370 | 3.25k | return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(ctx), |
1371 | 3.25k | "invalid uint literal")); |
1372 | 3.25k | } |
1373 | 13.9k | } |
1374 | | |
1375 | 52.9k | std::any ParserVisitor::visitDouble(CelParser::DoubleContext* ctx) { |
1376 | 52.9k | std::string value; |
1377 | 52.9k | if (ctx->sign) { |
1378 | 3.93k | value = ctx->sign->getText(); |
1379 | 3.93k | } |
1380 | 52.9k | value += ctx->tok->getText(); |
1381 | 52.9k | double double_value; |
1382 | 52.9k | if (absl::SimpleAtod(value, &double_value)) { |
1383 | 52.9k | return ExprToAny(factory_.NewDoubleConst( |
1384 | 52.9k | factory_.NextId(SourceRangeFromParserRuleContext(ctx)), double_value)); |
1385 | 52.9k | } else { |
1386 | 0 | return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(ctx), |
1387 | 0 | "invalid double literal")); |
1388 | 0 | } |
1389 | 52.9k | } |
1390 | | |
1391 | 275k | std::any ParserVisitor::visitString(CelParser::StringContext* ctx) { |
1392 | 275k | auto status_or_value = cel::internal::ParseStringLiteral(ctx->tok->getText()); |
1393 | 275k | if (!status_or_value.ok()) { |
1394 | 4.84k | return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(ctx), |
1395 | 4.84k | status_or_value.status().message())); |
1396 | 4.84k | } |
1397 | 270k | return ExprToAny(factory_.NewStringConst( |
1398 | 270k | factory_.NextId(SourceRangeFromParserRuleContext(ctx)), |
1399 | 270k | std::move(status_or_value).value())); |
1400 | 275k | } |
1401 | | |
1402 | 10.2k | std::any ParserVisitor::visitBytes(CelParser::BytesContext* ctx) { |
1403 | 10.2k | auto status_or_value = cel::internal::ParseBytesLiteral(ctx->tok->getText()); |
1404 | 10.2k | if (!status_or_value.ok()) { |
1405 | 2.63k | return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(ctx), |
1406 | 2.63k | status_or_value.status().message())); |
1407 | 2.63k | } |
1408 | 7.60k | return ExprToAny(factory_.NewBytesConst( |
1409 | 7.60k | factory_.NextId(SourceRangeFromParserRuleContext(ctx)), |
1410 | 7.60k | std::move(status_or_value).value())); |
1411 | 10.2k | } |
1412 | | |
1413 | 2.18k | std::any ParserVisitor::visitBoolTrue(CelParser::BoolTrueContext* ctx) { |
1414 | 2.18k | return ExprToAny(factory_.NewBoolConst( |
1415 | 2.18k | factory_.NextId(SourceRangeFromParserRuleContext(ctx)), true)); |
1416 | 2.18k | } |
1417 | | |
1418 | 24.1k | std::any ParserVisitor::visitBoolFalse(CelParser::BoolFalseContext* ctx) { |
1419 | 24.1k | return ExprToAny(factory_.NewBoolConst( |
1420 | 24.1k | factory_.NextId(SourceRangeFromParserRuleContext(ctx)), false)); |
1421 | 24.1k | } |
1422 | | |
1423 | 2.11k | std::any ParserVisitor::visitNull(CelParser::NullContext* ctx) { |
1424 | 2.11k | return ExprToAny(factory_.NewNullConst( |
1425 | 2.11k | factory_.NextId(SourceRangeFromParserRuleContext(ctx)))); |
1426 | 2.11k | } |
1427 | | |
1428 | 22.4k | cel::SourceInfo ParserVisitor::GetSourceInfo() { |
1429 | 22.4k | cel::SourceInfo source_info; |
1430 | 22.4k | source_info.set_location(std::string(source_.description())); |
1431 | 3.83M | for (const auto& positions : factory_.positions()) { |
1432 | 3.83M | source_info.mutable_positions().insert( |
1433 | 3.83M | std::pair{positions.first, positions.second.begin}); |
1434 | 3.83M | } |
1435 | 22.4k | source_info.mutable_line_offsets().reserve(source_.line_offsets().size()); |
1436 | 689k | for (const auto& line_offset : source_.line_offsets()) { |
1437 | 689k | source_info.mutable_line_offsets().push_back(line_offset); |
1438 | 689k | } |
1439 | | |
1440 | 22.4k | source_info.mutable_macro_calls() = factory_.release_macro_calls(); |
1441 | 22.4k | return source_info; |
1442 | 22.4k | } |
1443 | | |
1444 | 22.4k | EnrichedSourceInfo ParserVisitor::enriched_source_info() const { |
1445 | 22.4k | absl::flat_hash_map<int64_t, std::pair<int32_t, int32_t>> offsets; |
1446 | 22.4k | offsets.reserve(factory_.positions().size()); |
1447 | 3.83M | for (const auto& positions : factory_.positions()) { |
1448 | 3.83M | offsets.insert( |
1449 | 3.83M | std::pair{positions.first, |
1450 | 3.83M | std::pair{positions.second.begin, positions.second.end - 1}}); |
1451 | 3.83M | } |
1452 | 22.4k | return EnrichedSourceInfo(std::move(offsets)); |
1453 | 22.4k | } |
1454 | | |
1455 | | void ParserVisitor::syntaxError(antlr4::Recognizer* recognizer, |
1456 | | antlr4::Token* offending_symbol, size_t line, |
1457 | | size_t col, const std::string& msg, |
1458 | 1.74M | std::exception_ptr e) { |
1459 | 1.74M | cel::SourceRange range; |
1460 | 1.74M | if (auto position = source_.GetPosition(cel::SourceLocation{ |
1461 | 1.74M | static_cast<int32_t>(line), static_cast<int32_t>(col)}); |
1462 | 1.74M | position) { |
1463 | 1.74M | range.begin = *position; |
1464 | 1.74M | } |
1465 | 1.74M | factory_.ReportError(range, absl::StrCat("Syntax error: ", msg)); |
1466 | 1.74M | } |
1467 | | |
1468 | 35.3k | bool ParserVisitor::HasErrored() const { return factory_.HasErrors(); } |
1469 | | |
1470 | 12.8k | std::vector<cel::ParseIssue> ParserVisitor::CollectIssues() { |
1471 | 12.8k | return factory_.CollectIssues(); |
1472 | 12.8k | } |
1473 | | |
1474 | | Expr ParserVisitor::GlobalCallOrMacroImpl(int64_t expr_id, |
1475 | | absl::string_view function, |
1476 | 2.95M | std::vector<Expr> args) { |
1477 | 2.95M | auto macro = macro_registry_.FindMacro(function, args.size(), false); |
1478 | 2.95M | if (!macro) { |
1479 | 2.92M | return factory_.NewCall(expr_id, function, std::move(args)); |
1480 | 2.92M | } |
1481 | 26.4k | if (factory_.is_node_limit_exceeded()) { |
1482 | 0 | return factory_.ReportError( |
1483 | 0 | factory_.GetSourceRange(expr_id), |
1484 | 0 | "could not expand macro: expression node limit exceeded"); |
1485 | 0 | } |
1486 | 26.4k | std::vector<Expr> macro_args; |
1487 | 26.4k | if (add_macro_calls_) { |
1488 | 0 | macro_args.reserve(args.size()); |
1489 | 0 | for (const auto& arg : args) { |
1490 | 0 | macro_args.push_back(factory_.BuildMacroCallArg(arg)); |
1491 | 0 | } |
1492 | 0 | } |
1493 | 26.4k | factory_.BeginMacro(factory_.GetSourceRange(expr_id)); |
1494 | 26.4k | auto expr = macro->Expand(factory_, std::nullopt, absl::MakeSpan(args)); |
1495 | 26.4k | factory_.EndMacro(); |
1496 | 26.4k | if (expr) { |
1497 | 26.4k | if (add_macro_calls_) { |
1498 | 0 | factory_.AddMacroCall(expr->id(), function, std::nullopt, |
1499 | 0 | std::move(macro_args)); |
1500 | 0 | } |
1501 | | // We did not end up using `expr_id`. Delete metadata. |
1502 | 26.4k | factory_.EraseId(expr_id); |
1503 | 26.4k | return std::move(*expr); |
1504 | 26.4k | } |
1505 | 0 | return factory_.NewCall(expr_id, function, std::move(args)); |
1506 | 26.4k | } |
1507 | | |
1508 | | Expr ParserVisitor::ReceiverCallOrMacroImpl(int64_t expr_id, |
1509 | | absl::string_view function, |
1510 | | Expr target, |
1511 | 56.3k | std::vector<Expr> args) { |
1512 | 56.3k | auto macro = macro_registry_.FindMacro(function, args.size(), true); |
1513 | 56.3k | if (!macro) { |
1514 | 13.0k | return factory_.NewMemberCall(expr_id, function, std::move(target), |
1515 | 13.0k | std::move(args)); |
1516 | 13.0k | } |
1517 | 43.3k | if (factory_.is_node_limit_exceeded()) { |
1518 | 0 | return factory_.ReportError( |
1519 | 0 | factory_.GetSourceRange(expr_id), |
1520 | 0 | "could not expand macro: expression node limit exceeded"); |
1521 | 0 | } |
1522 | | |
1523 | 43.3k | Expr macro_target; |
1524 | 43.3k | std::vector<Expr> macro_args; |
1525 | 43.3k | if (add_macro_calls_) { |
1526 | 0 | macro_args.reserve(args.size()); |
1527 | 0 | macro_target = factory_.BuildMacroCallArg(target); |
1528 | 0 | for (const auto& arg : args) { |
1529 | 0 | macro_args.push_back(factory_.BuildMacroCallArg(arg)); |
1530 | 0 | } |
1531 | 0 | } |
1532 | 43.3k | factory_.BeginMacro(factory_.GetSourceRange(expr_id)); |
1533 | 43.3k | auto expr = macro->Expand(factory_, std::ref(target), absl::MakeSpan(args)); |
1534 | 43.3k | factory_.EndMacro(); |
1535 | 43.3k | if (expr) { |
1536 | 43.3k | if (add_macro_calls_) { |
1537 | 0 | factory_.AddMacroCall(expr->id(), function, std::move(macro_target), |
1538 | 0 | std::move(macro_args)); |
1539 | 0 | } |
1540 | | // We did not end up using `expr_id`. Delete metadata. |
1541 | 43.3k | factory_.EraseId(expr_id); |
1542 | 43.3k | return std::move(*expr); |
1543 | 43.3k | } |
1544 | | |
1545 | 0 | return factory_.NewMemberCall(expr_id, function, std::move(target), |
1546 | 0 | std::move(args)); |
1547 | 43.3k | } |
1548 | | |
1549 | | std::string ParserVisitor::ExtractQualifiedName(antlr4::ParserRuleContext* ctx, |
1550 | 0 | const Expr& e) { |
1551 | 0 | if (e == Expr{}) { |
1552 | 0 | return ""; |
1553 | 0 | } |
1554 | 0 |
|
1555 | 0 | if (const auto* ident_expr = absl::get_if<IdentExpr>(&e.kind()); ident_expr) { |
1556 | 0 | return ident_expr->name(); |
1557 | 0 | } |
1558 | 0 | if (const auto* select_expr = absl::get_if<SelectExpr>(&e.kind()); |
1559 | 0 | select_expr) { |
1560 | 0 | std::string prefix = ExtractQualifiedName(ctx, select_expr->operand()); |
1561 | 0 | if (!prefix.empty()) { |
1562 | 0 | return absl::StrCat(prefix, ".", select_expr->field()); |
1563 | 0 | } |
1564 | 0 | } |
1565 | 0 | factory_.ReportError(factory_.GetSourceRange(e.id()), |
1566 | 0 | "expected a qualified name"); |
1567 | 0 | return ""; |
1568 | 0 | } |
1569 | | |
1570 | | // Replacements for absl::StrReplaceAll for escaping standard whitespace |
1571 | | // characters. |
1572 | | static constexpr auto kStandardReplacements = |
1573 | | std::array<std::pair<absl::string_view, absl::string_view>, 3>{ |
1574 | | std::make_pair("\n", "\\n"), |
1575 | | std::make_pair("\r", "\\r"), |
1576 | | std::make_pair("\t", "\\t"), |
1577 | | }; |
1578 | | |
1579 | | static constexpr absl::string_view kSingleQuote = "'"; |
1580 | | |
1581 | | // ExprRecursionListener extends the standard ANTLR CelParser to ensure that |
1582 | | // recursive entries into the 'expr' rule are limited to a configurable depth so |
1583 | | // as to prevent stack overflows. |
1584 | | class ExprRecursionListener final : public ParseTreeListener { |
1585 | | public: |
1586 | | explicit ExprRecursionListener( |
1587 | | const int max_recursion_depth = kDefaultMaxRecursionDepth) |
1588 | 35.3k | : max_recursion_depth_(max_recursion_depth), recursion_depth_(0) {} |
1589 | | ~ExprRecursionListener() override = default; |
1590 | | |
1591 | 10.7M | void visitTerminal(TerminalNode* node) override {} |
1592 | 160k | void visitErrorNode(ErrorNode* error) override {} |
1593 | | void enterEveryRule(ParserRuleContext* ctx) override; |
1594 | | void exitEveryRule(ParserRuleContext* ctx) override; |
1595 | | |
1596 | | private: |
1597 | | const int max_recursion_depth_; |
1598 | | int recursion_depth_; |
1599 | | }; |
1600 | | |
1601 | 30.4M | void ExprRecursionListener::enterEveryRule(ParserRuleContext* ctx) { |
1602 | | // Throw a ParseCancellationException since the parsing would otherwise |
1603 | | // continue if this were treated as a syntax error and the problem would |
1604 | | // continue to manifest. |
1605 | 30.4M | if (ctx->getRuleIndex() == CelParser::RuleExpr) { |
1606 | 1.50M | if (recursion_depth_ > max_recursion_depth_) { |
1607 | 46 | throw ParseCancellationException( |
1608 | 46 | absl::StrFormat("Expression recursion limit exceeded. limit: %d", |
1609 | 46 | max_recursion_depth_)); |
1610 | 46 | } |
1611 | 1.50M | recursion_depth_++; |
1612 | 1.50M | } |
1613 | 30.4M | } |
1614 | | |
1615 | 30.4M | void ExprRecursionListener::exitEveryRule(ParserRuleContext* ctx) { |
1616 | 30.4M | if (ctx->getRuleIndex() == CelParser::RuleExpr) { |
1617 | 1.50M | recursion_depth_--; |
1618 | 1.50M | } |
1619 | 30.4M | } |
1620 | | |
1621 | | class RecoveryLimitErrorStrategy final : public DefaultErrorStrategy { |
1622 | | public: |
1623 | | explicit RecoveryLimitErrorStrategy( |
1624 | | int recovery_limit = kDefaultErrorRecoveryLimit, |
1625 | | int recovery_token_lookahead_limit = |
1626 | | kDefaultErrorRecoveryTokenLookaheadLimit) |
1627 | 35.3k | : recovery_limit_(recovery_limit), |
1628 | 35.3k | recovery_attempts_(0), |
1629 | 35.3k | recovery_token_lookahead_limit_(recovery_token_lookahead_limit) {} |
1630 | | |
1631 | 39.2k | void recover(Parser* recognizer, std::exception_ptr e) override { |
1632 | 39.2k | checkRecoveryLimit(recognizer); |
1633 | 39.2k | DefaultErrorStrategy::recover(recognizer, e); |
1634 | 39.2k | } |
1635 | | |
1636 | 26.4k | Token* recoverInline(Parser* recognizer) override { |
1637 | 26.4k | checkRecoveryLimit(recognizer); |
1638 | 26.4k | return DefaultErrorStrategy::recoverInline(recognizer); |
1639 | 26.4k | } |
1640 | | |
1641 | | // Override the ANTLR implementation to introduce a token lookahead limit as |
1642 | | // this prevents pathologically constructed, yet small (< 16kb) inputs from |
1643 | | // consuming inordinate amounts of compute. |
1644 | | // |
1645 | | // This method is only called on error recovery paths. |
1646 | 43.2k | void consumeUntil(Parser* recognizer, const IntervalSet& set) override { |
1647 | 43.2k | size_t ttype = recognizer->getInputStream()->LA(1); |
1648 | 43.2k | int recovery_search_depth = 0; |
1649 | 169k | while (ttype != Token::EOF && !set.contains(ttype) && |
1650 | 126k | recovery_search_depth++ < recovery_token_lookahead_limit_) { |
1651 | 126k | recognizer->consume(); |
1652 | 126k | ttype = recognizer->getInputStream()->LA(1); |
1653 | 126k | } |
1654 | | // Halt all parsing if the lookahead limit is reached during error recovery. |
1655 | 43.2k | if (recovery_search_depth == recovery_token_lookahead_limit_) { |
1656 | 3 | throw ParseCancellationException("Unable to find a recovery token"); |
1657 | 3 | } |
1658 | 43.2k | } |
1659 | | |
1660 | | protected: |
1661 | 65.4k | std::string escapeWSAndQuote(const std::string& s) const override { |
1662 | 65.4k | std::string result; |
1663 | 65.4k | result.reserve(s.size() + 2); |
1664 | 65.4k | absl::StrAppend(&result, kSingleQuote, s, kSingleQuote); |
1665 | 65.4k | absl::StrReplaceAll(kStandardReplacements, &result); |
1666 | 65.4k | return result; |
1667 | 65.4k | } |
1668 | | |
1669 | | private: |
1670 | 65.6k | void checkRecoveryLimit(Parser* recognizer) { |
1671 | 65.6k | if (recovery_attempts_++ >= recovery_limit_) { |
1672 | 1.64k | std::string too_many_errors = |
1673 | 1.64k | absl::StrFormat("More than %d parse errors.", recovery_limit_); |
1674 | 1.64k | recognizer->notifyErrorListeners(too_many_errors); |
1675 | 1.64k | throw ParseCancellationException(too_many_errors); |
1676 | 1.64k | } |
1677 | 65.6k | } |
1678 | | |
1679 | | int recovery_limit_; |
1680 | | int recovery_attempts_; |
1681 | | int recovery_token_lookahead_limit_; |
1682 | | }; |
1683 | | |
1684 | | } // namespace |
1685 | | |
1686 | | absl::StatusOr<std::unique_ptr<cel::Ast>> AntlrParseImpl( |
1687 | | const cel::Source& source, const cel::MacroRegistry& registry, |
1688 | | const ParserOptions& options, std::vector<cel::ParseIssue>* parse_issues, |
1689 | 35.3k | cel::EnrichedSourceInfo* enriched_source_info) { |
1690 | 35.3k | ABSL_DCHECK(!options.enable_pratt_parser); |
1691 | 35.3k | try { |
1692 | 35.3k | CodePointStream input(source.content(), source.description()); |
1693 | 35.3k | if (input.size() > options.expression_size_codepoint_limit) { |
1694 | 0 | return absl::InvalidArgumentError(absl::StrCat( |
1695 | 0 | "expression size exceeds codepoint limit.", " input size: ", |
1696 | 0 | input.size(), ", limit: ", options.expression_size_codepoint_limit)); |
1697 | 0 | } |
1698 | 35.3k | CelLexer lexer(&input); |
1699 | 35.3k | CommonTokenStream tokens(&lexer); |
1700 | 35.3k | CelParser parser(&tokens); |
1701 | 35.3k | ExprRecursionListener listener(options.max_recursion_depth); |
1702 | 35.3k | ParserVisitor visitor( |
1703 | 35.3k | source, options.max_recursion_depth, options.expression_node_limit, |
1704 | 35.3k | registry, options.add_macro_calls, options.enable_optional_syntax, |
1705 | 35.3k | options.enable_quoted_identifiers, |
1706 | 35.3k | options.enable_variadic_logical_operators, |
1707 | 35.3k | options.fold_unary_operators); |
1708 | | |
1709 | 35.3k | lexer.removeErrorListeners(); |
1710 | 35.3k | parser.removeErrorListeners(); |
1711 | 35.3k | lexer.addErrorListener(&visitor); |
1712 | 35.3k | parser.addErrorListener(&visitor); |
1713 | 35.3k | parser.addParseListener(&listener); |
1714 | | |
1715 | | // Limit the number of error recovery attempts to prevent bad expressions |
1716 | | // from consuming lots of cpu / memory. |
1717 | 35.3k | parser.setErrorHandler(std::make_shared<RecoveryLimitErrorStrategy>( |
1718 | 35.3k | options.error_recovery_limit, |
1719 | 35.3k | options.error_recovery_token_lookahead_limit)); |
1720 | | |
1721 | 35.3k | Expr expr; |
1722 | 35.3k | try { |
1723 | 35.3k | expr = ExprFromAny(visitor.visit(parser.start())); |
1724 | 35.3k | } catch (const ParseCancellationException& e) { |
1725 | 1.69k | if (visitor.HasErrored()) { |
1726 | 1.68k | auto issues = visitor.CollectIssues(); |
1727 | 1.68k | std::string error_message = FormatIssues(source, issues); |
1728 | 1.68k | if (parse_issues != nullptr) { |
1729 | 0 | *parse_issues = std::move(issues); |
1730 | 0 | } |
1731 | 1.68k | return absl::InvalidArgumentError(error_message); |
1732 | 1.68k | } |
1733 | 15 | return absl::CancelledError(e.what()); |
1734 | 1.69k | } |
1735 | | |
1736 | 33.6k | if (visitor.HasErrored()) { |
1737 | 11.1k | auto issues = visitor.CollectIssues(); |
1738 | 11.1k | std::string error_message = FormatIssues(source, issues); |
1739 | 11.1k | if (parse_issues != nullptr) { |
1740 | 0 | *parse_issues = std::move(issues); |
1741 | 0 | } |
1742 | 11.1k | return absl::InvalidArgumentError(error_message); |
1743 | 11.1k | } |
1744 | | |
1745 | 22.4k | if (enriched_source_info != nullptr) { |
1746 | 22.4k | *enriched_source_info = visitor.enriched_source_info(); |
1747 | 22.4k | } |
1748 | | |
1749 | 22.4k | return std::make_unique<cel::Ast>(std::move(expr), visitor.GetSourceInfo()); |
1750 | 33.6k | } catch (const std::exception& e) { |
1751 | 0 | return absl::AbortedError(e.what()); |
1752 | 0 | } catch (const char* what) { |
1753 | | // ANTLRv4 has historically thrown C string literals. |
1754 | 0 | return absl::AbortedError(what); |
1755 | 0 | } catch (...) { |
1756 | | // We guarantee to never throw and always return a status. |
1757 | 0 | return absl::UnknownError("An unknown exception occurred"); |
1758 | 0 | } |
1759 | 35.3k | } |
1760 | | |
1761 | | absl::StatusOr<std::unique_ptr<cel::Ast>> AntlrParserImpl::ParseImpl( |
1762 | | const cel::Source& source, |
1763 | 0 | std::vector<cel::ParseIssue>* absl_nullable parse_issues) const { |
1764 | 0 | return AntlrParseImpl(source, macro_registry_, options_, parse_issues); |
1765 | 0 | } |
1766 | | |
1767 | | absl::StatusOr<std::unique_ptr<cel::Source>> AntlrParserImpl::PrepareSourceImpl( |
1768 | 0 | absl::string_view input, absl::string_view description) const { |
1769 | 0 | return cel::NewSource( |
1770 | 0 | input, std::string(description), |
1771 | 0 | cel::SourceOptions{.max_codepoint_size = |
1772 | 0 | options_.expression_size_codepoint_limit}); |
1773 | 0 | } |
1774 | | |
1775 | 0 | absl::Status AntlrParserBuilderImpl::AddMacro(const cel::Macro& macro) { |
1776 | 0 | for (const auto& existing_macro : macros_) { |
1777 | 0 | if (existing_macro.key() == macro.key()) { |
1778 | 0 | return absl::AlreadyExistsError( |
1779 | 0 | absl::StrCat("macro already exists: ", macro.key())); |
1780 | 0 | } |
1781 | 0 | } |
1782 | 0 | macros_.push_back(macro); |
1783 | 0 | return absl::OkStatus(); |
1784 | 0 | } |
1785 | | |
1786 | 0 | absl::Status AntlrParserBuilderImpl::AddLibrary(cel::ParserLibrary library) { |
1787 | 0 | if (!library.id.empty()) { |
1788 | 0 | auto [it, inserted] = library_ids_.insert(library.id); |
1789 | 0 | if (!inserted) { |
1790 | 0 | return absl::AlreadyExistsError( |
1791 | 0 | absl::StrCat("parser library already exists: ", library.id)); |
1792 | 0 | } |
1793 | 0 | } |
1794 | 0 | libraries_.push_back(std::move(library)); |
1795 | 0 | return absl::OkStatus(); |
1796 | 0 | } |
1797 | | |
1798 | | absl::Status AntlrParserBuilderImpl::AddLibrarySubset( |
1799 | 0 | cel::ParserLibrarySubset subset) { |
1800 | 0 | if (subset.library_id.empty()) { |
1801 | 0 | return absl::InvalidArgumentError("subset must have a library id"); |
1802 | 0 | } |
1803 | 0 | std::string library_id = subset.library_id; |
1804 | 0 | auto [it, inserted] = |
1805 | 0 | library_subsets_.insert({library_id, std::move(subset)}); |
1806 | 0 | if (!inserted) { |
1807 | 0 | return absl::AlreadyExistsError( |
1808 | 0 | absl::StrCat("parser library subset already exists: ", library_id)); |
1809 | 0 | } |
1810 | 0 | return absl::OkStatus(); |
1811 | 0 | } |
1812 | | |
1813 | 0 | absl::StatusOr<std::unique_ptr<cel::Parser>> AntlrParserBuilderImpl::Build() { |
1814 | 0 | using std::swap; |
1815 | | // Save the old configured macros so they aren't affected by applying the |
1816 | | // libraries and can be restored if an error occurs. |
1817 | 0 | std::vector<cel::Macro> individual_macros; |
1818 | 0 | swap(individual_macros, macros_); |
1819 | 0 | absl::Cleanup cleanup([&] { swap(macros_, individual_macros); }); |
1820 | |
|
1821 | 0 | cel::MacroRegistry macro_registry; |
1822 | |
|
1823 | 0 | for (const auto& library : libraries_) { |
1824 | 0 | CEL_RETURN_IF_ERROR(library.configure(*this)); |
1825 | 0 | if (!library.id.empty()) { |
1826 | 0 | auto it = library_subsets_.find(library.id); |
1827 | 0 | if (it != library_subsets_.end()) { |
1828 | 0 | const cel::ParserLibrarySubset& subset = it->second; |
1829 | 0 | for (const auto& macro : macros_) { |
1830 | 0 | if (subset.should_include_macro(macro)) { |
1831 | 0 | CEL_RETURN_IF_ERROR(macro_registry.RegisterMacro(macro)); |
1832 | 0 | } |
1833 | 0 | } |
1834 | 0 | macros_.clear(); |
1835 | 0 | continue; |
1836 | 0 | } |
1837 | 0 | } |
1838 | | |
1839 | 0 | CEL_RETURN_IF_ERROR(macro_registry.RegisterMacros(macros_)); |
1840 | 0 | macros_.clear(); |
1841 | 0 | } |
1842 | | |
1843 | 0 | absl::flat_hash_set<std::string> library_ids(library_ids_); |
1844 | | |
1845 | | // Hack to support adding the standard library macros either by option or |
1846 | | // with a library configurer. |
1847 | 0 | if (!options_.disable_standard_macros && !library_ids_.contains("stdlib")) { |
1848 | 0 | CEL_RETURN_IF_ERROR(macro_registry.RegisterMacros(Macro::AllMacros())); |
1849 | 0 | library_ids.insert("stdlib"); |
1850 | 0 | } |
1851 | | |
1852 | 0 | if (options_.enable_optional_syntax && !library_ids_.contains("optional")) { |
1853 | 0 | CEL_RETURN_IF_ERROR(macro_registry.RegisterMacro(cel::OptMapMacro())); |
1854 | 0 | CEL_RETURN_IF_ERROR(macro_registry.RegisterMacro(cel::OptFlatMapMacro())); |
1855 | 0 | library_ids.insert("optional"); |
1856 | 0 | } |
1857 | 0 | CEL_RETURN_IF_ERROR(macro_registry.RegisterMacros(individual_macros)); |
1858 | 0 | return std::make_unique<AntlrParserImpl>(options_, std::move(macro_registry), |
1859 | 0 | std::move(library_ids)); |
1860 | 0 | } |
1861 | | |
1862 | 0 | std::unique_ptr<cel::ParserBuilder> AntlrParserImpl::ToBuilder() const { |
1863 | 0 | auto ins = std::make_unique<AntlrParserBuilderImpl>(options_); |
1864 | 0 | ins->library_ids_ = library_ids_; |
1865 | 0 | ins->macros_ = macro_registry_.ListMacros(); |
1866 | 0 | return ins; |
1867 | 0 | } |
1868 | | |
1869 | | } // namespace cel::parser_internal |