/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 | 5.23M | std::any ExprPtrToAny(std::unique_ptr<Expr>&& expr) { |
86 | 5.23M | return std::make_any<Expr*>(expr.release()); |
87 | 5.23M | } |
88 | | |
89 | 5.23M | std::any ExprToAny(Expr&& expr) { |
90 | 5.23M | return ExprPtrToAny(std::make_unique<Expr>(std::move(expr))); |
91 | 5.23M | } |
92 | | |
93 | 5.23M | std::unique_ptr<Expr> ExprPtrFromAny(std::any&& any) { |
94 | 5.23M | return absl::WrapUnique(std::any_cast<Expr*>(std::move(any))); |
95 | 5.23M | } |
96 | | |
97 | 5.23M | Expr ExprFromAny(std::any&& any) { |
98 | 5.23M | auto expr = ExprPtrFromAny(std::move(any)); |
99 | 5.23M | return std::move(*expr); |
100 | 5.23M | } |
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 | 172k | absl::string_view message) { |
110 | 172k | return absl::StrCat(absl::StrFormat("ERROR: %s:%zu:%zu: %s", |
111 | 172k | source.description(), location.line, |
112 | | // add one to the 0-based column |
113 | 172k | location.column + 1, message), |
114 | 172k | source.DisplayErrorLocation(location)); |
115 | 172k | } |
116 | | |
117 | 1.81M | int32_t PositiveOrMax(int32_t value) { |
118 | 1.81M | return value >= 0 ? value : std::numeric_limits<int32_t>::max(); |
119 | 1.81M | } |
120 | | |
121 | 3.96M | SourceRange SourceRangeFromToken(const antlr4::Token* token) { |
122 | 3.96M | SourceRange range; |
123 | 3.96M | if (token != nullptr) { |
124 | 3.96M | if (auto start = token->getStartIndex(); start != INVALID_INDEX) { |
125 | 3.96M | range.begin = static_cast<int32_t>(start); |
126 | 3.96M | } |
127 | 3.96M | if (auto end = token->getStopIndex(); end != INVALID_INDEX) { |
128 | 3.96M | range.end = static_cast<int32_t>(end + 1); |
129 | 3.96M | } |
130 | 3.96M | } |
131 | 3.96M | return range; |
132 | 3.96M | } |
133 | | |
134 | | SourceRange SourceRangeFromParserRuleContext( |
135 | 1.01M | const antlr4::ParserRuleContext* context) { |
136 | 1.01M | SourceRange range; |
137 | 1.01M | if (context != nullptr) { |
138 | 1.01M | if (auto start = context->getStart() != nullptr |
139 | 1.01M | ? context->getStart()->getStartIndex() |
140 | 1.01M | : INVALID_INDEX; |
141 | 1.01M | start != INVALID_INDEX) { |
142 | 1.01M | range.begin = static_cast<int32_t>(start); |
143 | 1.01M | } |
144 | 1.01M | if (auto end = context->getStop() != nullptr |
145 | 1.01M | ? context->getStop()->getStopIndex() |
146 | 1.01M | : INVALID_INDEX; |
147 | 1.01M | end != INVALID_INDEX) { |
148 | 1.01M | range.end = static_cast<int32_t>(end + 1); |
149 | 1.01M | } |
150 | 1.01M | } |
151 | 1.01M | return range; |
152 | 1.01M | } |
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 | 28.8k | : source_(source), expression_node_limit_(expression_node_limit) {} |
161 | | |
162 | 57.6k | void BeginMacro(SourceRange macro_position) { |
163 | 57.6k | macro_position_ = macro_position; |
164 | 57.6k | } |
165 | | |
166 | 57.6k | void EndMacro() { macro_position_ = SourceRange{}; } |
167 | | |
168 | 4.48k | Expr ReportError(absl::string_view message) override { |
169 | 4.48k | return ReportError(macro_position_, message); |
170 | 4.48k | } |
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.65M | Expr ReportError(SourceRange range, absl::string_view message) { |
177 | 1.65M | ++error_count_; |
178 | 1.65M | if (errors_.size() <= 100) { |
179 | 171k | errors_.push_back(ParserError{std::string(message), range}); |
180 | 171k | } |
181 | 1.65M | return NewUnspecified(NextId(range)); |
182 | 1.65M | } |
183 | | |
184 | 16.3k | Expr ReportErrorAt(const Expr& expr, absl::string_view message) override { |
185 | 16.3k | return ReportError(GetSourceRange(expr.id()), message); |
186 | 16.3k | } |
187 | | |
188 | 74.0k | SourceRange GetSourceRange(int64_t id) const { |
189 | 74.0k | if (auto it = positions_.find(id); it != positions_.end()) { |
190 | 72.4k | return it->second; |
191 | 72.4k | } |
192 | 1.56k | return SourceRange{}; |
193 | 74.0k | } |
194 | | |
195 | 6.94M | int64_t NextId(const SourceRange& range) { |
196 | 6.94M | auto id = expr_id_++; |
197 | 6.94M | 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 | 6.94M | if (range.begin != -1 || range.end != -1) { |
202 | 6.93M | positions_.insert(std::pair{id, range}); |
203 | 6.93M | } |
204 | 6.94M | return id; |
205 | 6.94M | } |
206 | | |
207 | 57.6k | bool is_node_limit_exceeded() const { return node_limit_exceeded_; } |
208 | | |
209 | 30.2k | bool HasErrors() const { return error_count_ != 0; } |
210 | | |
211 | 9.57k | 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 | 9.57k | std::stable_sort( |
217 | 9.57k | errors_.begin(), errors_.end(), |
218 | 454k | [](const ParserError& lhs, const ParserError& rhs) -> bool { |
219 | 454k | auto lhs_begin = PositiveOrMax(lhs.range.begin); |
220 | 454k | auto lhs_end = PositiveOrMax(lhs.range.end); |
221 | 454k | auto rhs_begin = PositiveOrMax(rhs.range.begin); |
222 | 454k | auto rhs_end = PositiveOrMax(rhs.range.end); |
223 | 454k | return lhs_begin < rhs_begin || |
224 | 413k | (lhs_begin == rhs_begin && lhs_end < rhs_end); |
225 | 454k | }); |
226 | | // Build the summary error message using the sorted errors. |
227 | 9.57k | bool errors_truncated = error_count_ > 100; |
228 | 9.57k | std::vector<cel::ParseIssue> issues; |
229 | 9.57k | issues.reserve( |
230 | 9.57k | errors_.size() + |
231 | 9.57k | errors_truncated); // Reserve space for the transform and an |
232 | | // additional element when truncation occurs. |
233 | 9.57k | std::transform( |
234 | 9.57k | errors_.begin(), errors_.end(), std::back_inserter(issues), |
235 | 171k | [this](const ParserError& error) { |
236 | 171k | auto location = |
237 | 171k | source_.GetLocation(error.range.begin).value_or(SourceLocation{}); |
238 | 171k | return cel::ParseIssue(location, error.message); |
239 | 171k | }); |
240 | 9.57k | if (errors_truncated) { |
241 | 677 | issues.push_back(cel::ParseIssue( |
242 | 677 | absl::StrCat(error_count_ - 100, " more errors were truncated."))); |
243 | 677 | } |
244 | 9.57k | return issues; |
245 | 9.57k | } |
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 | 57.7k | const absl::btree_map<int64_t, SourceRange>& positions() const { |
371 | 57.7k | return positions_; |
372 | 57.7k | } |
373 | | |
374 | 0 | const absl::flat_hash_map<int64_t, Expr>& macro_calls() const { |
375 | 0 | return macro_calls_; |
376 | 0 | } |
377 | | |
378 | 19.2k | absl::flat_hash_map<int64_t, Expr> release_macro_calls() { |
379 | 19.2k | using std::swap; |
380 | 19.2k | absl::flat_hash_map<int64_t, Expr> result; |
381 | 19.2k | swap(result, macro_calls_); |
382 | 19.2k | return result; |
383 | 19.2k | } |
384 | | |
385 | 57.6k | void EraseId(ExprId id) { |
386 | 57.6k | positions_.erase(id); |
387 | 57.6k | if (expr_id_ == id + 1) { |
388 | 0 | --expr_id_; |
389 | 0 | } |
390 | 57.6k | } |
391 | | |
392 | | protected: |
393 | 327k | 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 | 28.8k | : buffer_(buffer), |
441 | 28.8k | source_name_(source_name), |
442 | 28.8k | size_(buffer_.size()), |
443 | 28.8k | index_(0) {} |
444 | | |
445 | 61.3M | void consume() override { |
446 | 61.3M | 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 | 61.3M | index_++; |
451 | 61.3M | } |
452 | | |
453 | 140M | size_t LA(ptrdiff_t i) override { |
454 | 140M | if (ABSL_PREDICT_FALSE(i == 0)) { |
455 | 0 | return 0; |
456 | 0 | } |
457 | 140M | auto p = static_cast<ptrdiff_t>(index_); |
458 | 140M | if (i < 0) { |
459 | 0 | i++; |
460 | 0 | if (p + i - 1 < 0) { |
461 | 0 | return IntStream::EOF; |
462 | 0 | } |
463 | 0 | } |
464 | 140M | if (p + i - 1 >= static_cast<ptrdiff_t>(size_)) { |
465 | 58.5k | return IntStream::EOF; |
466 | 58.5k | } |
467 | 140M | return buffer_.at(static_cast<size_t>(p + i - 1)); |
468 | 140M | } |
469 | | |
470 | 16.4M | ptrdiff_t mark() override { return -1; } |
471 | | |
472 | 16.4M | void release(ptrdiff_t marker) override {} |
473 | | |
474 | 47.5M | size_t index() override { return index_; } |
475 | | |
476 | 7.44M | void seek(size_t index) override { index_ = std::min(index, size_); } |
477 | | |
478 | 6.95M | 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 | 8.48M | std::string getText(const antlr4::misc::Interval& interval) override { |
486 | 8.48M | if (ABSL_PREDICT_FALSE(interval.a < 0 || interval.b < 0)) { |
487 | 0 | return std::string(); |
488 | 0 | } |
489 | 8.48M | size_t start = static_cast<size_t>(interval.a); |
490 | 8.48M | if (ABSL_PREDICT_FALSE(start >= size_)) { |
491 | 0 | return std::string(); |
492 | 0 | } |
493 | 8.48M | size_t stop = static_cast<size_t>(interval.b); |
494 | 8.48M | if (ABSL_PREDICT_FALSE(stop >= size_)) { |
495 | 785 | stop = size_ - 1; |
496 | 785 | } |
497 | 8.48M | return buffer_.ToString(static_cast<cel::SourcePosition>(start), |
498 | 8.48M | static_cast<cel::SourcePosition>(stop) + 1); |
499 | 8.48M | } |
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 | 4.66M | : recursion_depth_(recursion_depth) { |
516 | 4.66M | ++recursion_depth_; |
517 | 4.66M | } |
518 | | |
519 | 4.66M | ~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.16k | : factory_(factory), function_(std::move(function)) { |
562 | 6.16k | terms_.push_back(std::move(expr)); |
563 | 6.16k | } |
564 | | |
565 | 154k | void ExpressionBalancer::AddTerm(int64_t op, Expr term) { |
566 | 154k | terms_.push_back(std::move(term)); |
567 | 154k | ops_.push_back(op); |
568 | 154k | } |
569 | | |
570 | 6.16k | Expr ExpressionBalancer::Balance(bool enable_variadic) { |
571 | 6.16k | if (terms_.size() == 1) { |
572 | 0 | return std::move(terms_[0]); |
573 | 0 | } |
574 | 6.16k | if (enable_variadic) { |
575 | 0 | return factory_.NewCall(ops_[0], function_, std::move(terms_)); |
576 | 0 | } |
577 | 6.16k | return BalancedTree(0, ops_.size() - 1); |
578 | 6.16k | } |
579 | | |
580 | 154k | Expr ExpressionBalancer::BalancedTree(int lo, int hi) { |
581 | 154k | int mid = (lo + hi + 1) / 2; |
582 | | |
583 | 154k | std::vector<Expr> arguments; |
584 | 154k | arguments.reserve(2); |
585 | | |
586 | 154k | if (mid == lo) { |
587 | 68.1k | arguments.push_back(std::move(terms_[mid])); |
588 | 86.2k | } else { |
589 | 86.2k | arguments.push_back(BalancedTree(lo, mid - 1)); |
590 | 86.2k | } |
591 | | |
592 | 154k | if (mid == hi) { |
593 | 92.4k | arguments.push_back(std::move(terms_[mid + 1])); |
594 | 92.4k | } else { |
595 | 61.9k | arguments.push_back(BalancedTree(mid + 1, hi)); |
596 | 61.9k | } |
597 | 154k | return factory_.NewCall(ops_[mid], function_, std::move(arguments)); |
598 | 154k | } |
599 | | |
600 | | std::string FormatIssues(const cel::Source& source, |
601 | 9.57k | absl::Span<const cel::ParseIssue> issues) { |
602 | 9.57k | return absl::StrJoin( |
603 | 172k | issues, "\n", [&source](std::string* out, const cel::ParseIssue& issue) { |
604 | 172k | absl::StrAppend( |
605 | 172k | out, DisplayParserError(source, issue.location(), issue.message())); |
606 | 172k | }); |
607 | 9.57k | } |
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 | 28.8k | : source_(source), |
621 | 28.8k | factory_(source_, max_expression_node_count), |
622 | 28.8k | macro_registry_(macro_registry), |
623 | 28.8k | recursion_depth_(0), |
624 | 28.8k | max_recursion_depth_(max_recursion_depth), |
625 | 28.8k | add_macro_calls_(add_macro_calls), |
626 | 28.8k | enable_optional_syntax_(enable_optional_syntax), |
627 | 28.8k | enable_quoted_identifiers_(enable_quoted_identifiers), |
628 | 28.8k | enable_variadic_logical_operators_(enable_variadic_logical_operators), |
629 | 28.8k | fold_unary_operators_(fold_unary_operators) {} |
630 | | |
631 | 28.8k | ~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 | 1.80M | Args&&... args) { |
691 | 1.80M | std::vector<Expr> arguments; |
692 | 1.80M | arguments.reserve(sizeof...(Args)); |
693 | 1.80M | (arguments.push_back(std::forward<Args>(args)), ...); |
694 | 1.80M | return GlobalCallOrMacroImpl(expr_id, function, std::move(arguments)); |
695 | 1.80M | } 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 | 1.62M | Args&&... args) { | 691 | 1.62M | std::vector<Expr> arguments; | 692 | 1.62M | arguments.reserve(sizeof...(Args)); | 693 | 1.62M | (arguments.push_back(std::forward<Args>(args)), ...); | 694 | 1.62M | return GlobalCallOrMacroImpl(expr_id, function, std::move(arguments)); | 695 | 1.62M | } |
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 | 178k | Args&&... args) { | 691 | 178k | std::vector<Expr> arguments; | 692 | 178k | arguments.reserve(sizeof...(Args)); | 693 | 178k | (arguments.push_back(std::forward<Args>(args)), ...); | 694 | 178k | return GlobalCallOrMacroImpl(expr_id, function, std::move(arguments)); | 695 | 178k | } |
|
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 | 86.0M | T* tree_as(antlr4::tree::ParseTree* tree) { |
730 | 86.0M | return dynamic_cast<T*>(tree); |
731 | 86.0M | } 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 | 6.31M | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 6.31M | return dynamic_cast<T*>(tree); | 731 | 6.31M | } |
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 | 297k | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 297k | return dynamic_cast<T*>(tree); | 731 | 297k | } |
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 | 250k | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 250k | return dynamic_cast<T*>(tree); | 731 | 250k | } |
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 | 17.0k | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 17.0k | return dynamic_cast<T*>(tree); | 731 | 17.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 | 57.2k | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 57.2k | return dynamic_cast<T*>(tree); | 731 | 57.2k | } |
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 | 1.86k | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 1.86k | return dynamic_cast<T*>(tree); | 731 | 1.86k | } |
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 | 5.46M | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 5.46M | return dynamic_cast<T*>(tree); | 731 | 5.46M | } |
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 | 2.73M | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 2.73M | return dynamic_cast<T*>(tree); | 731 | 2.73M | } |
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.04M | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 1.04M | return dynamic_cast<T*>(tree); | 731 | 1.04M | } |
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.00M | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 1.00M | return dynamic_cast<T*>(tree); | 731 | 1.00M | } |
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 | 968k | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 968k | return dynamic_cast<T*>(tree); | 731 | 968k | } |
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 | 955k | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 955k | return dynamic_cast<T*>(tree); | 731 | 955k | } |
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 | 946k | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 946k | return dynamic_cast<T*>(tree); | 731 | 946k | } |
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 | 945k | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 945k | return dynamic_cast<T*>(tree); | 731 | 945k | } |
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 | 268k | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 268k | return dynamic_cast<T*>(tree); | 731 | 268k | } |
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 | 250k | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 250k | return dynamic_cast<T*>(tree); | 731 | 250k | } |
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 | 194k | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 194k | return dynamic_cast<T*>(tree); | 731 | 194k | } |
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 | 14.2k | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 14.2k | return dynamic_cast<T*>(tree); | 731 | 14.2k | } |
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 | 5.74k | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 5.74k | return dynamic_cast<T*>(tree); | 731 | 5.74k | } |
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 | 4.60k | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 4.60k | return dynamic_cast<T*>(tree); | 731 | 4.60k | } |
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 | 2.73k | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 2.73k | return dynamic_cast<T*>(tree); | 731 | 2.73k | } |
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 | 9.56M | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 9.56M | return dynamic_cast<T*>(tree); | 731 | 9.56M | } |
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 | 9.56M | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 9.56M | return dynamic_cast<T*>(tree); | 731 | 9.56M | } |
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 | 9.55M | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 9.55M | return dynamic_cast<T*>(tree); | 731 | 9.55M | } |
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 | 9.56M | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 9.56M | return dynamic_cast<T*>(tree); | 731 | 9.56M | } |
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 | 9.55M | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 9.55M | return dynamic_cast<T*>(tree); | 731 | 9.55M | } |
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 | 9.46M | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 9.46M | return dynamic_cast<T*>(tree); | 731 | 9.46M | } |
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 | 3.03M | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 3.03M | return dynamic_cast<T*>(tree); | 731 | 3.03M | } |
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 | 3.58M | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 3.58M | return dynamic_cast<T*>(tree); | 731 | 3.58M | } |
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 | 196k | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 196k | return dynamic_cast<T*>(tree); | 731 | 196k | } |
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 | 196k | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 196k | return dynamic_cast<T*>(tree); | 731 | 196k | } |
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 | 7.41k | T* tree_as(antlr4::tree::ParseTree* tree) { | 730 | 7.41k | return dynamic_cast<T*>(tree); | 731 | 7.41k | } |
Unexecuted instantiation: antlr_parser.cc:antlr4::ParserRuleContext* cel::parser_internal::(anonymous namespace)::tree_as<antlr4::ParserRuleContext, void>(antlr4::tree::ParseTree*) |
732 | | |
733 | 4.66M | std::any ParserVisitor::visit(antlr4::tree::ParseTree* tree) { |
734 | 4.66M | ScopedIncrement inc(recursion_depth_); |
735 | 4.66M | if (recursion_depth_ > max_recursion_depth_) { |
736 | 3.01k | return ExprToAny(factory_.ReportError( |
737 | 3.01k | absl::StrFormat("Exceeded max recursion depth of %d when parsing.", |
738 | 3.01k | max_recursion_depth_))); |
739 | 3.01k | } |
740 | 4.66M | tree = UnnestContext(tree); |
741 | 4.66M | if (auto* ctx = tree_as<CelParser::StartContext>(tree)) { |
742 | 0 | return visitStart(ctx); |
743 | 4.66M | } else if (auto* ctx = tree_as<CelParser::ExprContext>(tree)) { |
744 | 2.25k | return visitExpr(ctx); |
745 | 4.65M | } else if (auto* ctx = tree_as<CelParser::ConditionalAndContext>(tree)) { |
746 | 1.62k | return visitConditionalAnd(ctx); |
747 | 4.65M | } else if (auto* ctx = tree_as<CelParser::ConditionalOrContext>(tree)) { |
748 | 4.53k | return visitConditionalOr(ctx); |
749 | 4.65M | } else if (auto* ctx = tree_as<CelParser::RelationContext>(tree)) { |
750 | 42.8k | return visitRelation(ctx); |
751 | 4.60M | } else if (auto* ctx = tree_as<CelParser::CalcContext>(tree)) { |
752 | 1.57M | return visitCalc(ctx); |
753 | 3.03M | } else if (auto* ctx = tree_as<CelParser::LogicalNotContext>(tree)) { |
754 | 4.83k | return visitLogicalNot(ctx); |
755 | 3.03M | } else if (auto* ctx = tree_as<CelParser::PrimaryExprContext>(tree)) { |
756 | 2.73M | return visitPrimaryExpr(ctx); |
757 | 2.73M | } else if (auto* ctx = tree_as<CelParser::MemberExprContext>(tree)) { |
758 | 0 | return visitMemberExpr(ctx); |
759 | 297k | } else if (auto* ctx = tree_as<CelParser::SelectContext>(tree)) { |
760 | 46.7k | return visitSelect(ctx); |
761 | 250k | } else if (auto* ctx = tree_as<CelParser::MemberCallContext>(tree)) { |
762 | 54.2k | return visitMemberCall(ctx); |
763 | 196k | } else if (auto* ctx = tree_as<CelParser::MapInitializerListContext>(tree)) { |
764 | 0 | return visitMapInitializerList(ctx); |
765 | 196k | } else if (auto* ctx = tree_as<CelParser::NegateContext>(tree)) { |
766 | 179k | return visitNegate(ctx); |
767 | 179k | } else if (auto* ctx = tree_as<CelParser::IndexContext>(tree)) { |
768 | 9.59k | return visitIndex(ctx); |
769 | 9.59k | } else if (auto* ctx = tree_as<CelParser::UnaryContext>(tree)) { |
770 | 5.94k | return visitUnary(ctx); |
771 | 5.94k | } else if (auto* ctx = tree_as<CelParser::CreateListContext>(tree)) { |
772 | 0 | return visitCreateList(ctx); |
773 | 1.46k | } else if (auto* ctx = tree_as<CelParser::CreateMessageContext>(tree)) { |
774 | 0 | return visitCreateMessage(ctx); |
775 | 1.46k | } else if (auto* ctx = tree_as<CelParser::CreateMapContext>(tree)) { |
776 | 0 | return visitCreateMap(ctx); |
777 | 0 | } |
778 | | |
779 | 1.46k | 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.46k | return ExprToAny(factory_.ReportError("<<nil>> parsetree")); |
786 | 1.46k | } |
787 | | |
788 | 2.73M | std::any ParserVisitor::visitPrimaryExpr(CelParser::PrimaryExprContext* pctx) { |
789 | 2.73M | CelParser::PrimaryContext* primary = pctx->primary(); |
790 | 2.73M | if (auto* ctx = tree_as<CelParser::NestedContext>(primary)) { |
791 | 0 | return visitNested(ctx); |
792 | 2.73M | } else if (auto* ctx = tree_as<CelParser::IdentContext>(primary)) { |
793 | 1.68M | return visitIdent(ctx); |
794 | 1.68M | } else if (auto* ctx = tree_as<CelParser::GlobalCallContext>(primary)) { |
795 | 40.8k | return visitGlobalCall(ctx); |
796 | 1.00M | } else if (auto* ctx = tree_as<CelParser::CreateListContext>(primary)) { |
797 | 35.4k | return visitCreateList(ctx); |
798 | 967k | } else if (auto* ctx = tree_as<CelParser::CreateMapContext>(primary)) { |
799 | 12.8k | return visitCreateMap(ctx); |
800 | 954k | } else if (auto* ctx = tree_as<CelParser::CreateMessageContext>(primary)) { |
801 | 7.29k | return visitCreateMessage(ctx); |
802 | 946k | } else if (auto* ctx = tree_as<CelParser::ConstantLiteralContext>(primary)) { |
803 | 945k | return visitConstantLiteral(ctx); |
804 | 945k | } |
805 | 1.41k | 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.41k | return ExprToAny(factory_.NewUnspecified(factory_.NextId({}))); |
810 | 1.41k | } |
811 | 0 | return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(pctx), |
812 | 0 | "invalid primary expression")); |
813 | 1.41k | } |
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 | 4.66M | antlr4::tree::ParseTree* tree) { |
836 | 4.66M | antlr4::tree::ParseTree* last = nullptr; |
837 | 5.21M | while (tree != last) { |
838 | 4.90M | last = tree; |
839 | | |
840 | 4.90M | if (auto* ctx = tree_as<CelParser::StartContext>(tree)) { |
841 | 27.6k | tree = ctx->expr(); |
842 | 27.6k | } |
843 | | |
844 | 4.90M | if (auto* ctx = tree_as<CelParser::ExprContext>(tree)) { |
845 | 390k | if (ctx->op != nullptr) { |
846 | 2.25k | return ctx; |
847 | 2.25k | } |
848 | 388k | tree = ctx->e; |
849 | 388k | } |
850 | | |
851 | 4.90M | if (auto* ctx = tree_as<CelParser::ConditionalOrContext>(tree)) { |
852 | 972k | if (!ctx->ops.empty()) { |
853 | 4.53k | return ctx; |
854 | 4.53k | } |
855 | 968k | tree = ctx->e; |
856 | 968k | } |
857 | | |
858 | 4.90M | if (auto* ctx = tree_as<CelParser::ConditionalAndContext>(tree)) { |
859 | 1.06M | if (!ctx->ops.empty()) { |
860 | 1.62k | return ctx; |
861 | 1.62k | } |
862 | 1.06M | tree = ctx->e; |
863 | 1.06M | } |
864 | | |
865 | 4.89M | if (auto* ctx = tree_as<CelParser::RelationContext>(tree)) { |
866 | 1.21M | if (ctx->calc() == nullptr) { |
867 | 42.8k | return ctx; |
868 | 42.8k | } |
869 | 1.16M | tree = ctx->calc(); |
870 | 1.16M | } |
871 | | |
872 | 4.85M | if (auto* ctx = tree_as<CelParser::CalcContext>(tree)) { |
873 | 4.31M | if (ctx->unary() == nullptr) { |
874 | 1.57M | return ctx; |
875 | 1.57M | } |
876 | 2.74M | tree = ctx->unary(); |
877 | 2.74M | } |
878 | | |
879 | 3.28M | if (auto* ctx = tree_as<CelParser::MemberExprContext>(tree)) { |
880 | 2.55M | tree = ctx->member(); |
881 | 2.55M | } |
882 | | |
883 | 3.28M | if (auto* ctx = tree_as<CelParser::PrimaryExprContext>(tree)) { |
884 | 2.73M | if (auto* nested = tree_as<CelParser::NestedContext>(ctx->primary())) { |
885 | 2.32k | tree = nested->e; |
886 | 2.73M | } else { |
887 | 2.73M | return ctx; |
888 | 2.73M | } |
889 | 2.73M | } |
890 | 3.28M | } |
891 | | |
892 | 302k | return tree; |
893 | 4.66M | } |
894 | | |
895 | 582k | std::any ParserVisitor::visitExpr(CelParser::ExprContext* ctx) { |
896 | 582k | auto result = ExprFromAny(visit(ctx->e)); |
897 | 582k | if (!ctx->op) { |
898 | 579k | return ExprToAny(std::move(result)); |
899 | 579k | } |
900 | 2.48k | std::vector<Expr> arguments; |
901 | 2.48k | arguments.reserve(3); |
902 | 2.48k | arguments.push_back(std::move(result)); |
903 | 2.48k | int64_t op_id = factory_.NextId(SourceRangeFromToken(ctx->op)); |
904 | 2.48k | arguments.push_back(ExprFromAny(visit(ctx->e1))); |
905 | 2.48k | arguments.push_back(ExprFromAny(visit(ctx->e2))); |
906 | | |
907 | 2.48k | return ExprToAny( |
908 | 2.48k | factory_.NewCall(op_id, CelOperator::CONDITIONAL, std::move(arguments))); |
909 | 582k | } |
910 | | |
911 | | std::any ParserVisitor::visitConditionalOr( |
912 | 4.53k | CelParser::ConditionalOrContext* ctx) { |
913 | 4.53k | auto result = ExprFromAny(visit(ctx->e)); |
914 | 4.53k | if (ctx->ops.empty()) { |
915 | 0 | return ExprToAny(std::move(result)); |
916 | 0 | } |
917 | 4.53k | ExpressionBalancer b(factory_, CelOperator::LOGICAL_OR, std::move(result)); |
918 | 95.4k | for (size_t i = 0; i < ctx->ops.size(); ++i) { |
919 | 90.8k | auto op = ctx->ops[i]; |
920 | 90.8k | if (i >= ctx->e1.size()) { |
921 | 0 | return ExprToAny( |
922 | 0 | factory_.ReportError(SourceRangeFromParserRuleContext(ctx), |
923 | 0 | "unexpected character, wanted '||'")); |
924 | 0 | } |
925 | 90.8k | auto next = ExprFromAny(visit(ctx->e1[i])); |
926 | 90.8k | int64_t op_id = factory_.NextId(SourceRangeFromToken(op)); |
927 | 90.8k | b.AddTerm(op_id, std::move(next)); |
928 | 90.8k | } |
929 | 4.53k | return ExprToAny(b.Balance(enable_variadic_logical_operators_)); |
930 | 4.53k | } |
931 | | |
932 | | std::any ParserVisitor::visitConditionalAnd( |
933 | 1.62k | CelParser::ConditionalAndContext* ctx) { |
934 | 1.62k | auto result = ExprFromAny(visit(ctx->e)); |
935 | 1.62k | if (ctx->ops.empty()) { |
936 | 0 | return ExprToAny(std::move(result)); |
937 | 0 | } |
938 | 1.62k | ExpressionBalancer b(factory_, CelOperator::LOGICAL_AND, std::move(result)); |
939 | 65.1k | for (size_t i = 0; i < ctx->ops.size(); ++i) { |
940 | 63.4k | auto op = ctx->ops[i]; |
941 | 63.4k | if (i >= ctx->e1.size()) { |
942 | 0 | return ExprToAny( |
943 | 0 | factory_.ReportError(SourceRangeFromParserRuleContext(ctx), |
944 | 0 | "unexpected character, wanted '&&'")); |
945 | 0 | } |
946 | 63.4k | auto next = ExprFromAny(visit(ctx->e1[i])); |
947 | 63.4k | int64_t op_id = factory_.NextId(SourceRangeFromToken(op)); |
948 | 63.4k | b.AddTerm(op_id, std::move(next)); |
949 | 63.4k | } |
950 | 1.62k | return ExprToAny(b.Balance(enable_variadic_logical_operators_)); |
951 | 1.62k | } |
952 | | |
953 | 42.8k | std::any ParserVisitor::visitRelation(CelParser::RelationContext* ctx) { |
954 | 42.8k | if (ctx->calc()) { |
955 | 0 | return visit(ctx->calc()); |
956 | 0 | } |
957 | 42.8k | std::string op_text; |
958 | 42.8k | if (ctx->op) { |
959 | 42.8k | op_text = ctx->op->getText(); |
960 | 42.8k | } |
961 | 42.8k | auto op = ReverseLookupOperator(op_text); |
962 | 42.8k | if (op) { |
963 | 42.8k | auto lhs = ExprFromAny(visit(ctx->relation(0))); |
964 | 42.8k | int64_t op_id = factory_.NextId(SourceRangeFromToken(ctx->op)); |
965 | 42.8k | auto rhs = ExprFromAny(visit(ctx->relation(1))); |
966 | 42.8k | return ExprToAny( |
967 | 42.8k | GlobalCallOrMacro(op_id, *op, std::move(lhs), std::move(rhs))); |
968 | 42.8k | } |
969 | 0 | return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(ctx), |
970 | 0 | "operator not found")); |
971 | 42.8k | } |
972 | | |
973 | 1.57M | std::any ParserVisitor::visitCalc(CelParser::CalcContext* ctx) { |
974 | 1.57M | if (ctx->unary()) { |
975 | 0 | return visit(ctx->unary()); |
976 | 0 | } |
977 | 1.57M | std::string op_text; |
978 | 1.57M | if (ctx->op) { |
979 | 1.57M | op_text = ctx->op->getText(); |
980 | 1.57M | } |
981 | 1.57M | auto op = ReverseLookupOperator(op_text); |
982 | 1.57M | if (op) { |
983 | 1.57M | auto lhs = ExprFromAny(visit(ctx->calc(0))); |
984 | 1.57M | int64_t op_id = factory_.NextId(SourceRangeFromToken(ctx->op)); |
985 | 1.57M | auto rhs = ExprFromAny(visit(ctx->calc(1))); |
986 | 1.57M | return ExprToAny( |
987 | 1.57M | GlobalCallOrMacro(op_id, *op, std::move(lhs), std::move(rhs))); |
988 | 1.57M | } |
989 | 0 | return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(ctx), |
990 | 0 | "operator not found")); |
991 | 1.57M | } |
992 | | |
993 | 5.94k | std::any ParserVisitor::visitUnary(CelParser::UnaryContext* ctx) { |
994 | 5.94k | return ExprToAny(factory_.NewStringConst( |
995 | 5.94k | factory_.NextId(SourceRangeFromParserRuleContext(ctx)), "<<error>>")); |
996 | 5.94k | } |
997 | | |
998 | | std::any ParserVisitor::VisitUnaryOps(const std::vector<antlr4::Token*>& ops, |
999 | | CelParser::MemberContext* member, |
1000 | 184k | absl::string_view op_name) { |
1001 | 184k | if (fold_unary_operators_) { |
1002 | 184k | if (ops.size() % 2 == 0) { |
1003 | 5.71k | return visit(member); |
1004 | 5.71k | } |
1005 | 178k | int64_t op_id = factory_.NextId(SourceRangeFromToken(ops[0])); |
1006 | 178k | auto target = ExprFromAny(visit(member)); |
1007 | 178k | return ExprToAny(GlobalCallOrMacro(op_id, op_name, std::move(target))); |
1008 | 184k | } |
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 | 184k | } |
1022 | | |
1023 | 4.83k | std::any ParserVisitor::visitLogicalNot(CelParser::LogicalNotContext* ctx) { |
1024 | 4.83k | return VisitUnaryOps(ctx->ops, ctx->member(), CelOperator::LOGICAL_NOT); |
1025 | 4.83k | } |
1026 | | |
1027 | 179k | std::any ParserVisitor::visitNegate(CelParser::NegateContext* ctx) { |
1028 | 179k | return VisitUnaryOps(ctx->ops, ctx->member(), CelOperator::NEGATE); |
1029 | 179k | } |
1030 | | |
1031 | | std::string ParserVisitor::NormalizeIdentifier( |
1032 | 57.2k | CelParser::EscapeIdentContext* ctx) { |
1033 | 57.2k | if (auto* raw_id = tree_as<CelParser::SimpleIdentifierContext>(ctx); raw_id) { |
1034 | 55.3k | return raw_id->id->getText(); |
1035 | 55.3k | } |
1036 | 1.86k | if (auto* escaped_id = tree_as<CelParser::EscapedIdentifierContext>(ctx); |
1037 | 1.86k | escaped_id) { |
1038 | 1.07k | if (!enable_quoted_identifiers_) { |
1039 | 0 | factory_.ReportError(SourceRangeFromParserRuleContext(ctx), |
1040 | 0 | "unsupported syntax '`'"); |
1041 | 0 | } |
1042 | 1.07k | auto escaped_id_text = escaped_id->id->getText(); |
1043 | 1.07k | return escaped_id_text.substr(1, escaped_id_text.size() - 2); |
1044 | 1.07k | } |
1045 | | |
1046 | | // Fallthrough might occur if the parser is in an error state. |
1047 | 787 | return ""; |
1048 | 1.86k | } |
1049 | | |
1050 | 46.7k | std::any ParserVisitor::visitSelect(CelParser::SelectContext* ctx) { |
1051 | 46.7k | auto operand = ExprFromAny(visit(ctx->member())); |
1052 | | // Handle the error case where no valid identifier is specified. |
1053 | 46.7k | if (!ctx->id || !ctx->op) { |
1054 | 0 | return ExprToAny(factory_.NewUnspecified( |
1055 | 0 | factory_.NextId(SourceRangeFromParserRuleContext(ctx)))); |
1056 | 0 | } |
1057 | 46.7k | auto id = NormalizeIdentifier(ctx->id); |
1058 | 46.7k | if (ctx->opt != nullptr) { |
1059 | 5.14k | if (!enable_optional_syntax_) { |
1060 | 5.14k | return ExprToAny(factory_.ReportError( |
1061 | 5.14k | SourceRangeFromParserRuleContext(ctx), "unsupported syntax '.?'")); |
1062 | 5.14k | } |
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 | 5.14k | } |
1071 | 41.6k | return ExprToAny( |
1072 | 41.6k | factory_.NewSelect(factory_.NextId(SourceRangeFromToken(ctx->op)), |
1073 | 41.6k | std::move(operand), std::move(id))); |
1074 | 46.7k | } |
1075 | | |
1076 | 54.2k | std::any ParserVisitor::visitMemberCall(CelParser::MemberCallContext* ctx) { |
1077 | 54.2k | auto operand = ExprFromAny(visit(ctx->member())); |
1078 | | // Handle the error case where no valid identifier is specified. |
1079 | 54.2k | if (!ctx->id) { |
1080 | 0 | return ExprToAny(factory_.NewUnspecified( |
1081 | 0 | factory_.NextId(SourceRangeFromParserRuleContext(ctx)))); |
1082 | 0 | } |
1083 | 54.2k | auto id = ctx->id->getText(); |
1084 | 54.2k | int64_t op_id = factory_.NextId(SourceRangeFromToken(ctx->open)); |
1085 | 54.2k | auto args = visitList(ctx->args); |
1086 | 54.2k | return ExprToAny( |
1087 | 54.2k | ReceiverCallOrMacroImpl(op_id, id, std::move(operand), std::move(args))); |
1088 | 54.2k | } |
1089 | | |
1090 | 9.59k | std::any ParserVisitor::visitIndex(CelParser::IndexContext* ctx) { |
1091 | 9.59k | auto target = ExprFromAny(visit(ctx->member())); |
1092 | 9.59k | int64_t op_id = factory_.NextId(SourceRangeFromToken(ctx->op)); |
1093 | 9.59k | auto index = ExprFromAny(visit(ctx->index)); |
1094 | 9.59k | if (!enable_optional_syntax_ && ctx->opt != nullptr) { |
1095 | 913 | return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(ctx), |
1096 | 913 | "unsupported syntax '.?'")); |
1097 | 913 | } |
1098 | 8.67k | return ExprToAny(GlobalCallOrMacro( |
1099 | 8.67k | op_id, ctx->opt != nullptr ? "_[?_]" : CelOperator::INDEX, |
1100 | 8.67k | std::move(target), std::move(index))); |
1101 | 9.59k | } |
1102 | | |
1103 | | std::any ParserVisitor::visitCreateMessage( |
1104 | 7.29k | CelParser::CreateMessageContext* ctx) { |
1105 | 7.29k | std::vector<std::string> parts; |
1106 | 7.29k | parts.reserve(ctx->ids.size()); |
1107 | 28.8k | for (const auto* id : ctx->ids) { |
1108 | 28.8k | parts.push_back(id->getText()); |
1109 | 28.8k | } |
1110 | 7.29k | std::string name; |
1111 | 7.29k | if (ctx->leadingDot) { |
1112 | 1.88k | name.push_back('.'); |
1113 | 1.88k | name.append(absl::StrJoin(parts, ".")); |
1114 | 5.41k | } else { |
1115 | 5.41k | name = absl::StrJoin(parts, "."); |
1116 | 5.41k | } |
1117 | 7.29k | int64_t obj_id = factory_.NextId(SourceRangeFromParserRuleContext(ctx)); |
1118 | 7.29k | std::vector<StructExprField> fields; |
1119 | 7.29k | if (ctx->entries) { |
1120 | 2.26k | fields = visitFields(ctx->entries); |
1121 | 2.26k | } |
1122 | 7.29k | return ExprToAny( |
1123 | 7.29k | factory_.NewStruct(obj_id, std::move(name), std::move(fields))); |
1124 | 7.29k | } |
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.26k | CelParser::FieldInitializerListContext* ctx) { |
1134 | 2.26k | std::vector<StructExprField> res; |
1135 | 2.26k | if (!ctx || ctx->fields.empty()) { |
1136 | 0 | return res; |
1137 | 0 | } |
1138 | | |
1139 | 2.26k | res.reserve(ctx->fields.size()); |
1140 | 12.7k | for (size_t i = 0; i < ctx->fields.size(); ++i) { |
1141 | 10.5k | if (i >= ctx->cols.size() || i >= ctx->values.size()) { |
1142 | | // This is the result of a syntax error detected elsewhere. |
1143 | 124 | return res; |
1144 | 124 | } |
1145 | 10.4k | auto* f = ctx->fields[i]; |
1146 | 10.4k | 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 | 10.4k | std::string id = NormalizeIdentifier(f->escapeIdent()); |
1153 | | |
1154 | 10.4k | int64_t init_id = factory_.NextId(SourceRangeFromToken(ctx->cols[i])); |
1155 | 10.4k | if (!enable_optional_syntax_ && f->opt) { |
1156 | 412 | factory_.ReportError(SourceRangeFromParserRuleContext(ctx), |
1157 | 412 | "unsupported syntax '?'"); |
1158 | 412 | continue; |
1159 | 412 | } |
1160 | 10.0k | auto value = ExprFromAny(visit(ctx->values[i])); |
1161 | 10.0k | res.push_back(factory_.NewStructField(init_id, std::move(id), |
1162 | 10.0k | std::move(value), f->opt != nullptr)); |
1163 | 10.0k | } |
1164 | | |
1165 | 2.14k | return res; |
1166 | 2.26k | } |
1167 | | |
1168 | 1.68M | std::any ParserVisitor::visitIdent(CelParser::IdentContext* ctx) { |
1169 | 1.68M | std::string ident_name; |
1170 | 1.68M | if (ctx->leadingDot) { |
1171 | 7.14k | ident_name = "."; |
1172 | 7.14k | } |
1173 | 1.68M | 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 | 1.68M | if (cel::internal::LexisIsReserved(ctx->id->getText())) { |
1179 | 1.04k | return ExprToAny(factory_.ReportError( |
1180 | 1.04k | SourceRangeFromParserRuleContext(ctx), |
1181 | 1.04k | absl::StrFormat("reserved identifier: %s", ctx->id->getText()))); |
1182 | 1.04k | } |
1183 | | |
1184 | 1.68M | ident_name += ctx->id->getText(); |
1185 | | |
1186 | 1.68M | return ExprToAny(factory_.NewIdent( |
1187 | 1.68M | factory_.NextId(SourceRangeFromToken(ctx->id)), std::move(ident_name))); |
1188 | 1.68M | } |
1189 | | |
1190 | 40.8k | std::any ParserVisitor::visitGlobalCall(CelParser::GlobalCallContext* ctx) { |
1191 | 40.8k | std::string ident_name; |
1192 | 40.8k | if (ctx->leadingDot) { |
1193 | 2.60k | ident_name = "."; |
1194 | 2.60k | } |
1195 | 40.8k | 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 | 40.8k | if (cel::internal::LexisIsReserved(ctx->id->getText())) { |
1201 | 363 | return ExprToAny(factory_.ReportError( |
1202 | 363 | SourceRangeFromParserRuleContext(ctx), |
1203 | 363 | absl::StrFormat("reserved identifier: %s", ctx->id->getText()))); |
1204 | 363 | } |
1205 | | |
1206 | 40.4k | ident_name += ctx->id->getText(); |
1207 | | |
1208 | 40.4k | int64_t op_id = factory_.NextId(SourceRangeFromToken(ctx->op)); |
1209 | 40.4k | auto args = visitList(ctx->args); |
1210 | 40.4k | return ExprToAny( |
1211 | 40.4k | GlobalCallOrMacroImpl(op_id, std::move(ident_name), std::move(args))); |
1212 | 40.8k | } |
1213 | | |
1214 | 0 | std::any ParserVisitor::visitNested(CelParser::NestedContext* ctx) { |
1215 | 0 | return visit(ctx->e); |
1216 | 0 | } |
1217 | | |
1218 | 35.4k | std::any ParserVisitor::visitCreateList(CelParser::CreateListContext* ctx) { |
1219 | 35.4k | int64_t list_id = factory_.NextId(SourceRangeFromParserRuleContext(ctx)); |
1220 | 35.4k | auto elems = visitList(ctx->elems); |
1221 | 35.4k | return ExprToAny(factory_.NewList(list_id, std::move(elems))); |
1222 | 35.4k | } |
1223 | | |
1224 | | std::vector<ListExprElement> ParserVisitor::visitList( |
1225 | 35.4k | CelParser::ListInitContext* ctx) { |
1226 | 35.4k | std::vector<ListExprElement> rv; |
1227 | 35.4k | if (!ctx) return rv; |
1228 | 31.5k | rv.reserve(ctx->elems.size()); |
1229 | 377k | for (size_t i = 0; i < ctx->elems.size(); ++i) { |
1230 | 345k | auto* expr_ctx = ctx->elems[i]; |
1231 | 345k | if (expr_ctx == nullptr) { |
1232 | 0 | return rv; |
1233 | 0 | } |
1234 | 345k | if (!enable_optional_syntax_ && expr_ctx->opt != nullptr) { |
1235 | 1.10k | factory_.ReportError(SourceRangeFromParserRuleContext(ctx), |
1236 | 1.10k | "unsupported syntax '?'"); |
1237 | | // Still generate an ID to detect node limit exceeded. |
1238 | 1.10k | factory_.NextId(SourceRangeFromParserRuleContext(ctx)); |
1239 | 1.10k | rv.push_back(factory_.NewListElement(factory_.NewUnspecified(0), false)); |
1240 | 1.10k | continue; |
1241 | 1.10k | } |
1242 | 344k | rv.push_back(factory_.NewListElement(ExprFromAny(visitExpr(expr_ctx->e)), |
1243 | 344k | expr_ctx->opt != nullptr)); |
1244 | 344k | } |
1245 | 31.5k | return rv; |
1246 | 31.5k | } |
1247 | | |
1248 | 94.7k | std::vector<Expr> ParserVisitor::visitList(CelParser::ExprListContext* ctx) { |
1249 | 94.7k | std::vector<Expr> rv; |
1250 | 94.7k | if (!ctx) return rv; |
1251 | 84.4k | std::transform(ctx->e.begin(), ctx->e.end(), std::back_inserter(rv), |
1252 | 235k | [this](CelParser::ExprContext* expr_ctx) { |
1253 | 235k | return ExprFromAny(visitExpr(expr_ctx)); |
1254 | 235k | }); |
1255 | 84.4k | return rv; |
1256 | 94.7k | } |
1257 | | |
1258 | 12.8k | std::any ParserVisitor::visitCreateMap(CelParser::CreateMapContext* ctx) { |
1259 | 12.8k | int64_t struct_id = factory_.NextId(SourceRangeFromParserRuleContext(ctx)); |
1260 | 12.8k | std::vector<MapExprEntry> entries; |
1261 | 12.8k | if (ctx->entries) { |
1262 | 7.85k | entries = visitEntries(ctx->entries); |
1263 | 7.85k | } |
1264 | 12.8k | return ExprToAny(factory_.NewMap(struct_id, std::move(entries))); |
1265 | 12.8k | } |
1266 | | |
1267 | | std::any ParserVisitor::visitConstantLiteral( |
1268 | 945k | CelParser::ConstantLiteralContext* clctx) { |
1269 | 945k | CelParser::LiteralContext* literal = clctx->literal(); |
1270 | 945k | if (auto* ctx = tree_as<CelParser::IntContext>(literal)) { |
1271 | 676k | return visitInt(ctx); |
1272 | 676k | } else if (auto* ctx = tree_as<CelParser::UintContext>(literal)) { |
1273 | 18.5k | return visitUint(ctx); |
1274 | 250k | } else if (auto* ctx = tree_as<CelParser::DoubleContext>(literal)) { |
1275 | 55.3k | return visitDouble(ctx); |
1276 | 194k | } else if (auto* ctx = tree_as<CelParser::StringContext>(literal)) { |
1277 | 180k | return visitString(ctx); |
1278 | 180k | } else if (auto* ctx = tree_as<CelParser::BytesContext>(literal)) { |
1279 | 8.47k | return visitBytes(ctx); |
1280 | 8.47k | } else if (auto* ctx = tree_as<CelParser::BoolFalseContext>(literal)) { |
1281 | 1.14k | return visitBoolFalse(ctx); |
1282 | 4.60k | } else if (auto* ctx = tree_as<CelParser::BoolTrueContext>(literal)) { |
1283 | 1.86k | return visitBoolTrue(ctx); |
1284 | 2.73k | } else if (auto* ctx = tree_as<CelParser::NullContext>(literal)) { |
1285 | 2.02k | return visitNull(ctx); |
1286 | 2.02k | } |
1287 | 710 | return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(clctx), |
1288 | 710 | "invalid constant literal expression")); |
1289 | 945k | } |
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 | 7.85k | CelParser::MapInitializerListContext* ctx) { |
1299 | 7.85k | std::vector<MapExprEntry> res; |
1300 | 7.85k | if (!ctx || ctx->keys.empty()) { |
1301 | 0 | return res; |
1302 | 0 | } |
1303 | | |
1304 | 7.85k | res.reserve(ctx->cols.size()); |
1305 | 178k | for (size_t i = 0; i < ctx->cols.size(); ++i) { |
1306 | 170k | auto id = factory_.NextId(SourceRangeFromToken(ctx->cols[i])); |
1307 | 170k | if (!enable_optional_syntax_ && ctx->keys[i]->opt) { |
1308 | 308 | factory_.ReportError(SourceRangeFromParserRuleContext(ctx), |
1309 | 308 | "unsupported syntax '?'"); |
1310 | | // Still generate an ID to detect node limit exceeded. |
1311 | 308 | factory_.NextId(SourceRangeFromParserRuleContext(ctx)); |
1312 | 308 | factory_.NextId(SourceRangeFromParserRuleContext(ctx)); |
1313 | 308 | res.push_back(factory_.NewMapEntry(0, factory_.NewUnspecified(0), |
1314 | 308 | factory_.NewUnspecified(0), false)); |
1315 | 308 | continue; |
1316 | 308 | } |
1317 | 170k | auto key = ExprFromAny(visit(ctx->keys[i]->e)); |
1318 | 170k | auto value = ExprFromAny(visit(ctx->values[i])); |
1319 | 170k | res.push_back(factory_.NewMapEntry(id, std::move(key), std::move(value), |
1320 | 170k | ctx->keys[i]->opt != nullptr)); |
1321 | 170k | } |
1322 | 7.85k | return res; |
1323 | 7.85k | } |
1324 | | |
1325 | 676k | std::any ParserVisitor::visitInt(CelParser::IntContext* ctx) { |
1326 | 676k | std::string value; |
1327 | 676k | if (ctx->sign) { |
1328 | 18.1k | value = ctx->sign->getText(); |
1329 | 18.1k | } |
1330 | 676k | value += ctx->tok->getText(); |
1331 | 676k | int64_t int_value; |
1332 | 676k | if (absl::StartsWith(ctx->tok->getText(), "0x")) { |
1333 | 2.35k | if (absl::SimpleHexAtoi(value, &int_value)) { |
1334 | 1.13k | return ExprToAny(factory_.NewIntConst( |
1335 | 1.13k | factory_.NextId(SourceRangeFromParserRuleContext(ctx)), int_value)); |
1336 | 1.21k | } else { |
1337 | 1.21k | return ExprToAny(factory_.ReportError( |
1338 | 1.21k | SourceRangeFromParserRuleContext(ctx), "invalid hex int literal")); |
1339 | 1.21k | } |
1340 | 2.35k | } |
1341 | 674k | if (absl::SimpleAtoi(value, &int_value)) { |
1342 | 672k | return ExprToAny(factory_.NewIntConst( |
1343 | 672k | factory_.NextId(SourceRangeFromParserRuleContext(ctx)), int_value)); |
1344 | 672k | } else { |
1345 | 2.32k | return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(ctx), |
1346 | 2.32k | "invalid int literal")); |
1347 | 2.32k | } |
1348 | 674k | } |
1349 | | |
1350 | 18.5k | std::any ParserVisitor::visitUint(CelParser::UintContext* ctx) { |
1351 | 18.5k | std::string value = ctx->tok->getText(); |
1352 | | // trim the 'u' designator included in the uint literal. |
1353 | 18.5k | if (!value.empty()) { |
1354 | 18.5k | value.resize(value.size() - 1); |
1355 | 18.5k | } |
1356 | 18.5k | uint64_t uint_value; |
1357 | 18.5k | if (absl::StartsWith(ctx->tok->getText(), "0x")) { |
1358 | 3.44k | if (absl::SimpleHexAtoi(value, &uint_value)) { |
1359 | 1.69k | return ExprToAny(factory_.NewUintConst( |
1360 | 1.69k | factory_.NextId(SourceRangeFromParserRuleContext(ctx)), uint_value)); |
1361 | 1.74k | } else { |
1362 | 1.74k | return ExprToAny(factory_.ReportError( |
1363 | 1.74k | SourceRangeFromParserRuleContext(ctx), "invalid hex uint literal")); |
1364 | 1.74k | } |
1365 | 3.44k | } |
1366 | 15.0k | if (absl::SimpleAtoi(value, &uint_value)) { |
1367 | 10.5k | return ExprToAny(factory_.NewUintConst( |
1368 | 10.5k | factory_.NextId(SourceRangeFromParserRuleContext(ctx)), uint_value)); |
1369 | 10.5k | } else { |
1370 | 4.51k | return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(ctx), |
1371 | 4.51k | "invalid uint literal")); |
1372 | 4.51k | } |
1373 | 15.0k | } |
1374 | | |
1375 | 55.3k | std::any ParserVisitor::visitDouble(CelParser::DoubleContext* ctx) { |
1376 | 55.3k | std::string value; |
1377 | 55.3k | if (ctx->sign) { |
1378 | 5.52k | value = ctx->sign->getText(); |
1379 | 5.52k | } |
1380 | 55.3k | value += ctx->tok->getText(); |
1381 | 55.3k | double double_value; |
1382 | 55.3k | if (absl::SimpleAtod(value, &double_value)) { |
1383 | 55.3k | return ExprToAny(factory_.NewDoubleConst( |
1384 | 55.3k | factory_.NextId(SourceRangeFromParserRuleContext(ctx)), double_value)); |
1385 | 55.3k | } else { |
1386 | 0 | return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(ctx), |
1387 | 0 | "invalid double literal")); |
1388 | 0 | } |
1389 | 55.3k | } |
1390 | | |
1391 | 180k | std::any ParserVisitor::visitString(CelParser::StringContext* ctx) { |
1392 | 180k | auto status_or_value = cel::internal::ParseStringLiteral(ctx->tok->getText()); |
1393 | 180k | if (!status_or_value.ok()) { |
1394 | 2.81k | return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(ctx), |
1395 | 2.81k | status_or_value.status().message())); |
1396 | 2.81k | } |
1397 | 177k | return ExprToAny(factory_.NewStringConst( |
1398 | 177k | factory_.NextId(SourceRangeFromParserRuleContext(ctx)), |
1399 | 177k | std::move(status_or_value).value())); |
1400 | 180k | } |
1401 | | |
1402 | 8.47k | std::any ParserVisitor::visitBytes(CelParser::BytesContext* ctx) { |
1403 | 8.47k | auto status_or_value = cel::internal::ParseBytesLiteral(ctx->tok->getText()); |
1404 | 8.47k | if (!status_or_value.ok()) { |
1405 | 2.06k | return ExprToAny(factory_.ReportError(SourceRangeFromParserRuleContext(ctx), |
1406 | 2.06k | status_or_value.status().message())); |
1407 | 2.06k | } |
1408 | 6.40k | return ExprToAny(factory_.NewBytesConst( |
1409 | 6.40k | factory_.NextId(SourceRangeFromParserRuleContext(ctx)), |
1410 | 6.40k | std::move(status_or_value).value())); |
1411 | 8.47k | } |
1412 | | |
1413 | 1.86k | std::any ParserVisitor::visitBoolTrue(CelParser::BoolTrueContext* ctx) { |
1414 | 1.86k | return ExprToAny(factory_.NewBoolConst( |
1415 | 1.86k | factory_.NextId(SourceRangeFromParserRuleContext(ctx)), true)); |
1416 | 1.86k | } |
1417 | | |
1418 | 1.14k | std::any ParserVisitor::visitBoolFalse(CelParser::BoolFalseContext* ctx) { |
1419 | 1.14k | return ExprToAny(factory_.NewBoolConst( |
1420 | 1.14k | factory_.NextId(SourceRangeFromParserRuleContext(ctx)), false)); |
1421 | 1.14k | } |
1422 | | |
1423 | 2.02k | std::any ParserVisitor::visitNull(CelParser::NullContext* ctx) { |
1424 | 2.02k | return ExprToAny(factory_.NewNullConst( |
1425 | 2.02k | factory_.NextId(SourceRangeFromParserRuleContext(ctx)))); |
1426 | 2.02k | } |
1427 | | |
1428 | 19.2k | cel::SourceInfo ParserVisitor::GetSourceInfo() { |
1429 | 19.2k | cel::SourceInfo source_info; |
1430 | 19.2k | source_info.set_location(std::string(source_.description())); |
1431 | 2.43M | for (const auto& positions : factory_.positions()) { |
1432 | 2.43M | source_info.mutable_positions().insert( |
1433 | 2.43M | std::pair{positions.first, positions.second.begin}); |
1434 | 2.43M | } |
1435 | 19.2k | source_info.mutable_line_offsets().reserve(source_.line_offsets().size()); |
1436 | 426k | for (const auto& line_offset : source_.line_offsets()) { |
1437 | 426k | source_info.mutable_line_offsets().push_back(line_offset); |
1438 | 426k | } |
1439 | | |
1440 | 19.2k | source_info.mutable_macro_calls() = factory_.release_macro_calls(); |
1441 | 19.2k | return source_info; |
1442 | 19.2k | } |
1443 | | |
1444 | 19.2k | EnrichedSourceInfo ParserVisitor::enriched_source_info() const { |
1445 | 19.2k | absl::flat_hash_map<int64_t, std::pair<int32_t, int32_t>> offsets; |
1446 | 19.2k | offsets.reserve(factory_.positions().size()); |
1447 | 2.43M | for (const auto& positions : factory_.positions()) { |
1448 | 2.43M | offsets.insert( |
1449 | 2.43M | std::pair{positions.first, |
1450 | 2.43M | std::pair{positions.second.begin, positions.second.end - 1}}); |
1451 | 2.43M | } |
1452 | 19.2k | return EnrichedSourceInfo(std::move(offsets)); |
1453 | 19.2k | } |
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.60M | std::exception_ptr e) { |
1459 | 1.60M | cel::SourceRange range; |
1460 | 1.60M | if (auto position = source_.GetPosition(cel::SourceLocation{ |
1461 | 1.60M | static_cast<int32_t>(line), static_cast<int32_t>(col)}); |
1462 | 1.60M | position) { |
1463 | 1.60M | range.begin = *position; |
1464 | 1.60M | } |
1465 | 1.60M | factory_.ReportError(range, absl::StrCat("Syntax error: ", msg)); |
1466 | 1.60M | } |
1467 | | |
1468 | 28.8k | bool ParserVisitor::HasErrored() const { return factory_.HasErrors(); } |
1469 | | |
1470 | 9.57k | std::vector<cel::ParseIssue> ParserVisitor::CollectIssues() { |
1471 | 9.57k | return factory_.CollectIssues(); |
1472 | 9.57k | } |
1473 | | |
1474 | | Expr ParserVisitor::GlobalCallOrMacroImpl(int64_t expr_id, |
1475 | | absl::string_view function, |
1476 | 1.84M | std::vector<Expr> args) { |
1477 | 1.84M | auto macro = macro_registry_.FindMacro(function, args.size(), false); |
1478 | 1.84M | if (!macro) { |
1479 | 1.82M | return factory_.NewCall(expr_id, function, std::move(args)); |
1480 | 1.82M | } |
1481 | 17.1k | 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 | 17.1k | std::vector<Expr> macro_args; |
1487 | 17.1k | 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 | 17.1k | factory_.BeginMacro(factory_.GetSourceRange(expr_id)); |
1494 | 17.1k | auto expr = macro->Expand(factory_, std::nullopt, absl::MakeSpan(args)); |
1495 | 17.1k | factory_.EndMacro(); |
1496 | 17.1k | if (expr) { |
1497 | 17.1k | 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 | 17.1k | factory_.EraseId(expr_id); |
1503 | 17.1k | return std::move(*expr); |
1504 | 17.1k | } |
1505 | 0 | return factory_.NewCall(expr_id, function, std::move(args)); |
1506 | 17.1k | } |
1507 | | |
1508 | | Expr ParserVisitor::ReceiverCallOrMacroImpl(int64_t expr_id, |
1509 | | absl::string_view function, |
1510 | | Expr target, |
1511 | 54.2k | std::vector<Expr> args) { |
1512 | 54.2k | auto macro = macro_registry_.FindMacro(function, args.size(), true); |
1513 | 54.2k | if (!macro) { |
1514 | 13.7k | return factory_.NewMemberCall(expr_id, function, std::move(target), |
1515 | 13.7k | std::move(args)); |
1516 | 13.7k | } |
1517 | 40.4k | 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 | 40.4k | Expr macro_target; |
1524 | 40.4k | std::vector<Expr> macro_args; |
1525 | 40.4k | 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 | 40.4k | factory_.BeginMacro(factory_.GetSourceRange(expr_id)); |
1533 | 40.4k | auto expr = macro->Expand(factory_, std::ref(target), absl::MakeSpan(args)); |
1534 | 40.4k | factory_.EndMacro(); |
1535 | 40.4k | if (expr) { |
1536 | 40.4k | 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 | 40.4k | factory_.EraseId(expr_id); |
1542 | 40.4k | return std::move(*expr); |
1543 | 40.4k | } |
1544 | | |
1545 | 0 | return factory_.NewMemberCall(expr_id, function, std::move(target), |
1546 | 0 | std::move(args)); |
1547 | 40.4k | } |
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 | 28.8k | : max_recursion_depth_(max_recursion_depth), recursion_depth_(0) {} |
1589 | | ~ExprRecursionListener() override = default; |
1590 | | |
1591 | 7.33M | void visitTerminal(TerminalNode* node) override {} |
1592 | 115k | 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 | 20.6M | 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 | 20.6M | if (ctx->getRuleIndex() == CelParser::RuleExpr) { |
1606 | 1.06M | if (recursion_depth_ > max_recursion_depth_) { |
1607 | 48 | throw ParseCancellationException( |
1608 | 48 | absl::StrFormat("Expression recursion limit exceeded. limit: %d", |
1609 | 48 | max_recursion_depth_)); |
1610 | 48 | } |
1611 | 1.06M | recursion_depth_++; |
1612 | 1.06M | } |
1613 | 20.6M | } |
1614 | | |
1615 | 20.6M | void ExprRecursionListener::exitEveryRule(ParserRuleContext* ctx) { |
1616 | 20.6M | if (ctx->getRuleIndex() == CelParser::RuleExpr) { |
1617 | 1.06M | recursion_depth_--; |
1618 | 1.06M | } |
1619 | 20.6M | } |
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 | 28.8k | : recovery_limit_(recovery_limit), |
1628 | 28.8k | recovery_attempts_(0), |
1629 | 28.8k | recovery_token_lookahead_limit_(recovery_token_lookahead_limit) {} |
1630 | | |
1631 | 28.3k | void recover(Parser* recognizer, std::exception_ptr e) override { |
1632 | 28.3k | checkRecoveryLimit(recognizer); |
1633 | 28.3k | DefaultErrorStrategy::recover(recognizer, e); |
1634 | 28.3k | } |
1635 | | |
1636 | 19.3k | Token* recoverInline(Parser* recognizer) override { |
1637 | 19.3k | checkRecoveryLimit(recognizer); |
1638 | 19.3k | return DefaultErrorStrategy::recoverInline(recognizer); |
1639 | 19.3k | } |
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 | 30.8k | void consumeUntil(Parser* recognizer, const IntervalSet& set) override { |
1647 | 30.8k | size_t ttype = recognizer->getInputStream()->LA(1); |
1648 | 30.8k | int recovery_search_depth = 0; |
1649 | 122k | while (ttype != Token::EOF && !set.contains(ttype) && |
1650 | 91.5k | recovery_search_depth++ < recovery_token_lookahead_limit_) { |
1651 | 91.5k | recognizer->consume(); |
1652 | 91.5k | ttype = recognizer->getInputStream()->LA(1); |
1653 | 91.5k | } |
1654 | | // Halt all parsing if the lookahead limit is reached during error recovery. |
1655 | 30.8k | if (recovery_search_depth == recovery_token_lookahead_limit_) { |
1656 | 3 | throw ParseCancellationException("Unable to find a recovery token"); |
1657 | 3 | } |
1658 | 30.8k | } |
1659 | | |
1660 | | protected: |
1661 | 45.9k | std::string escapeWSAndQuote(const std::string& s) const override { |
1662 | 45.9k | std::string result; |
1663 | 45.9k | result.reserve(s.size() + 2); |
1664 | 45.9k | absl::StrAppend(&result, kSingleQuote, s, kSingleQuote); |
1665 | 45.9k | absl::StrReplaceAll(kStandardReplacements, &result); |
1666 | 45.9k | return result; |
1667 | 45.9k | } |
1668 | | |
1669 | | private: |
1670 | 47.7k | void checkRecoveryLimit(Parser* recognizer) { |
1671 | 47.7k | if (recovery_attempts_++ >= recovery_limit_) { |
1672 | 1.16k | std::string too_many_errors = |
1673 | 1.16k | absl::StrFormat("More than %d parse errors.", recovery_limit_); |
1674 | 1.16k | recognizer->notifyErrorListeners(too_many_errors); |
1675 | 1.16k | throw ParseCancellationException(too_many_errors); |
1676 | 1.16k | } |
1677 | 47.7k | } |
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 | 28.8k | cel::EnrichedSourceInfo* enriched_source_info) { |
1690 | 28.8k | ABSL_DCHECK(!options.enable_pratt_parser); |
1691 | 28.8k | try { |
1692 | 28.8k | CodePointStream input(source.content(), source.description()); |
1693 | 28.8k | 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 | 28.8k | CelLexer lexer(&input); |
1699 | 28.8k | CommonTokenStream tokens(&lexer); |
1700 | 28.8k | CelParser parser(&tokens); |
1701 | 28.8k | ExprRecursionListener listener(options.max_recursion_depth); |
1702 | 28.8k | ParserVisitor visitor( |
1703 | 28.8k | source, options.max_recursion_depth, options.expression_node_limit, |
1704 | 28.8k | registry, options.add_macro_calls, options.enable_optional_syntax, |
1705 | 28.8k | options.enable_quoted_identifiers, |
1706 | 28.8k | options.enable_variadic_logical_operators, |
1707 | 28.8k | options.fold_unary_operators); |
1708 | | |
1709 | 28.8k | lexer.removeErrorListeners(); |
1710 | 28.8k | parser.removeErrorListeners(); |
1711 | 28.8k | lexer.addErrorListener(&visitor); |
1712 | 28.8k | parser.addErrorListener(&visitor); |
1713 | 28.8k | parser.addParseListener(&listener); |
1714 | | |
1715 | | // Limit the number of error recovery attempts to prevent bad expressions |
1716 | | // from consuming lots of cpu / memory. |
1717 | 28.8k | parser.setErrorHandler(std::make_shared<RecoveryLimitErrorStrategy>( |
1718 | 28.8k | options.error_recovery_limit, |
1719 | 28.8k | options.error_recovery_token_lookahead_limit)); |
1720 | | |
1721 | 28.8k | Expr expr; |
1722 | 28.8k | try { |
1723 | 28.8k | expr = ExprFromAny(visitor.visit(parser.start())); |
1724 | 28.8k | } catch (const ParseCancellationException& e) { |
1725 | 1.21k | if (visitor.HasErrored()) { |
1726 | 1.19k | auto issues = visitor.CollectIssues(); |
1727 | 1.19k | std::string error_message = FormatIssues(source, issues); |
1728 | 1.19k | if (parse_issues != nullptr) { |
1729 | 0 | *parse_issues = std::move(issues); |
1730 | 0 | } |
1731 | 1.19k | return absl::InvalidArgumentError(error_message); |
1732 | 1.19k | } |
1733 | 20 | return absl::CancelledError(e.what()); |
1734 | 1.21k | } |
1735 | | |
1736 | 27.6k | if (visitor.HasErrored()) { |
1737 | 8.37k | auto issues = visitor.CollectIssues(); |
1738 | 8.37k | std::string error_message = FormatIssues(source, issues); |
1739 | 8.37k | if (parse_issues != nullptr) { |
1740 | 0 | *parse_issues = std::move(issues); |
1741 | 0 | } |
1742 | 8.37k | return absl::InvalidArgumentError(error_message); |
1743 | 8.37k | } |
1744 | | |
1745 | 19.2k | if (enriched_source_info != nullptr) { |
1746 | 19.2k | *enriched_source_info = visitor.enriched_source_info(); |
1747 | 19.2k | } |
1748 | | |
1749 | 19.2k | return std::make_unique<cel::Ast>(std::move(expr), visitor.GetSourceInfo()); |
1750 | 27.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 | 28.8k | } |
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 |