LLDB mainline
DILParser.cpp
Go to the documentation of this file.
1//===-- DILParser.cpp -----------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7// This implements the recursive descent parser for the Data Inspection
8// Language (DIL), and its helper functions, which will eventually underlie the
9// 'frame variable' command. The language that this parser recognizes is
10// described in lldb/docs/dil-expr-lang.ebnf
11//
12//===----------------------------------------------------------------------===//
13
23#include "llvm/ADT/StringRef.h"
24#include "llvm/Support/FormatAdapters.h"
25#include <cstdlib>
26#include <limits.h>
27#include <memory>
28#include <sstream>
29#include <string>
30
31namespace lldb_private::dil {
32
34 const std::string &message, uint32_t loc,
35 uint16_t err_len)
36 : ErrorInfo(make_error_code(std::errc::invalid_argument)) {
38 FileSpec{}, /*line=*/1, static_cast<uint16_t>(loc + 1),
39 err_len, false, /*in_user_input=*/true};
40 // If the error is not handled by `RenderDiagnosticDetails`, this creates an
41 // error message that can be displayed instead.
42 // Example:
43 // (lldb) script lldb.frame.GetValueForVariablePath("1 + foo")
44 // error: <user expression>:1:5: use of undeclared identifier 'foo'
45 // 1 | 1 + foo
46 // | ^~~
47 auto msg = llvm::formatv("<user expression>:1:{0}: {1}\n 1 | {2}\n |",
48 loc + 1, message, expr);
49 std::string rendered_str;
50 llvm::raw_string_ostream rendered_os(rendered_str);
51 rendered_os << msg.str();
52 rendered_os << llvm::indent(loc + 1) << "^";
53 if (err_len > 1) {
54 // Underline the rest of the erroneous token after the cursor '^'.
55 rendered_os << std::string(err_len - 1, '~');
56 }
57 m_detail.source_location = sloc;
59 m_detail.message = message;
60 m_detail.rendered = std::move(rendered_str);
61}
62
63CompilerType ResolveTypeByName(const std::string &name,
64 ExecutionContextScope &ctx_scope) {
65 // Internally types don't have global scope qualifier in their names and
66 // LLDB doesn't support queries with it too.
67 llvm::StringRef name_ref(name);
68
69 if (name_ref.starts_with("::"))
70 name_ref = name_ref.drop_front(2);
71
72 std::vector<CompilerType> result_type_list;
73 lldb::TargetSP target_sp = ctx_scope.CalculateTarget();
74 if (!name_ref.empty() && target_sp) {
75 ModuleList &images = target_sp->GetImages();
76 TypeQuery query{ConstString(name_ref), TypeQueryOptions::e_exact_match |
77 TypeQueryOptions::e_find_one};
78 TypeResults results;
79 images.FindTypes(nullptr, query, results);
80 const lldb::TypeSP &type_sp = results.GetFirstType();
81 if (type_sp)
82 result_type_list.push_back(type_sp->GetFullCompilerType());
83 }
84
85 if (!result_type_list.empty()) {
86 CompilerType type = result_type_list[0];
87 if (type.IsValid() && type.GetTypeName().GetStringRef() == name_ref)
88 return type;
89 }
90
91 return {};
92}
93
94llvm::Expected<ASTNodeUP> DILParser::Parse(llvm::StringRef dil_input_expr,
95 DILLexer lexer,
96 StackFrame &stack_frame,
97 lldb::DynamicValueType use_dynamic,
98 lldb::DILMode mode) {
99 llvm::Error error = llvm::Error::success();
100 DILParser parser(dil_input_expr, lexer, stack_frame, use_dynamic, error,
101 mode);
102
103 ASTNodeUP node_up = parser.Run();
104 assert(node_up && "ASTNodeUP must not contain a nullptr");
105
106 if (error) {
108 "[DILParser::Parse] DIL parser failed:\n{0}",
109 llvm::toStringWithoutConsuming(error));
110 return error;
111 }
112
113 return node_up;
114}
115
116DILParser::DILParser(llvm::StringRef dil_input_expr, DILLexer lexer,
117 StackFrame &stack_frame,
118 lldb::DynamicValueType use_dynamic, llvm::Error &error,
119 lldb::DILMode mode)
120 : m_stack_frame(stack_frame), m_input_expr(dil_input_expr),
121 m_dil_lexer(std::move(lexer)), m_error(error), m_use_dynamic(use_dynamic),
122 m_mode(mode) {}
123
125 ASTNodeUP expr = ParseExpression();
126
128
129 return expr;
130}
131
132// Parse an expression.
133//
134// expression:
135// assignment_expression
136//
138
139// Parse an assignment_expression
140//
141// assignment_expression
142// conditional_expression
143// logical_or_expression assignment_operator pure_expression
144//
145// assignment_operator:
146// "="
147// "+="
148// "-="
149// "*="
150// "/="
151// "%="
152// "&="
153// "^="
154// "|="
155// "<<="
156// ">>="
157//
159 auto lhs = ParseLogicalOrExpression();
160 assert(lhs && "ASTNodeUP must not contain a nullptr");
161
162 // Check if it's an assignment expression.
168 // That's an assignment!
169 Token token = CurToken();
170 m_dil_lexer.Advance();
171 auto rhs = ParsePureExpression();
172 assert(rhs && "ASTNodeUP must not contain a nullptr");
173 lhs = std::make_unique<BinaryOpNode>(
175 std::move(lhs), std::move(rhs));
176 }
177
178 // Check if it's a ternary operator.
179 if (CurToken().Is(Token::question))
180 return ParseConditionalBranches(std::move(lhs));
181
182 return lhs;
183}
184
185// Parse a pure expression without side effects.
186//
187// pure_expression:
188// conditional_expression
189//
193
194// Parse a conditional_expression.
195//
196// conditional_expression:
197// logical_or_expression
198// logical_or_expression "?" pure_expression ":" pure_expression
199//
201 auto lhs = ParseLogicalOrExpression();
202 assert(lhs && "ASTNodeUP must not contain a nullptr");
203
204 if (CurToken().Is(Token::question))
205 return ParseConditionalBranches(std::move(lhs));
206
207 return lhs;
208}
209
211 assert(condition && "ASTNodeUP must not contain a nullptr");
212
213 Token token = CurToken();
214 m_dil_lexer.Advance();
215 auto true_op = ParsePureExpression();
216 assert(true_op && "ASTNodeUP must not contain a nullptr");
218 m_dil_lexer.Advance();
219 auto false_op = ParsePureExpression();
220 assert(false_op && "ASTNodeUP must not contain a nullptr");
221 return std::make_unique<ConditionalNode>(
222 token.GetLocation(), std::move(condition), std::move(true_op),
223 std::move(false_op));
224}
225
226// Parse a logical_or_expression.
227//
228// logical_or_expression:
229// logical_and_expression {"||" logical_and_expression}
230//
232 auto lhs = ParseLogicalAndExpression();
233 assert(lhs && "ASTNodeUP must not contain a nullptr");
234
235 while (CurToken().Is(Token::pipepipe)) {
236 Token token = CurToken();
237 m_dil_lexer.Advance();
238 auto rhs = ParseLogicalAndExpression();
239 assert(rhs && "ASTNodeUP must not contain a nullptr");
240 lhs = std::make_unique<BinaryOpNode>(
242 std::move(lhs), std::move(rhs));
243 }
244
245 return lhs;
246}
247
248// Parse a logical_and_expression.
249//
250// logical_and_expression:
251// inclusive_or_expression {"&&" inclusive_or_expression}
252//
254 auto lhs = ParseInclusiveOrExpression();
255 assert(lhs && "ASTNodeUP must not contain a nullptr");
256
257 while (CurToken().Is(Token::ampamp)) {
258 Token token = CurToken();
259 m_dil_lexer.Advance();
260 auto rhs = ParseInclusiveOrExpression();
261 assert(rhs && "ASTNodeUP must not contain a nullptr");
262 lhs = std::make_unique<BinaryOpNode>(
264 std::move(lhs), std::move(rhs));
265 }
266
267 return lhs;
268}
269
270// Parse an inclusive_or_expression.
271//
272// inclusive_or_expression:
273// exclusive_or_expression {"|" exclusive_or_expression}
274//
276 auto lhs = ParseExclusiveOrExpression();
277 assert(lhs && "ASTNodeUP must not contain a nullptr");
278
279 while (CurToken().Is(Token::pipe)) {
280 Token token = CurToken();
281 m_dil_lexer.Advance();
282 auto rhs = ParseExclusiveOrExpression();
283 assert(rhs && "ASTNodeUP must not contain a nullptr");
284 lhs = std::make_unique<BinaryOpNode>(
286 std::move(lhs), std::move(rhs));
287 }
288
289 return lhs;
290}
291
292// Parse an exclusive_or_expression.
293//
294// exclusive_or_expression:
295// and_expression {"^" and_expression}
296//
298 auto lhs = ParseAndExpression();
299 assert(lhs && "ASTNodeUP must not contain a nullptr");
300
301 while (CurToken().Is(Token::caret)) {
302 Token token = CurToken();
303 m_dil_lexer.Advance();
304 auto rhs = ParseAndExpression();
305 assert(rhs && "ASTNodeUP must not contain a nullptr");
306 lhs = std::make_unique<BinaryOpNode>(
308 std::move(lhs), std::move(rhs));
309 }
310
311 return lhs;
312}
313
314// Parse an and_expression.
315//
316// and_expression:
317// equality_expression {"&" equality_expression}
318//
320 auto lhs = ParseEqualityExpression();
321 assert(lhs && "ASTNodeUP must not contain a nullptr");
322
323 while (CurToken().Is(Token::amp)) {
324 Token token = CurToken();
325 if (token.Is(Token::amp) && m_mode != lldb::eDILModeFull) {
326 BailOut("bitwise and (&) is allowed only in DIL full mode",
327 token.GetLocation(), token.GetSpelling().length());
328 return std::make_unique<ErrorNode>();
329 }
330 m_dil_lexer.Advance();
331 auto rhs = ParseEqualityExpression();
332 assert(rhs && "ASTNodeUP must not contain a nullptr");
333 lhs = std::make_unique<BinaryOpNode>(
335 std::move(lhs), std::move(rhs));
336 }
337
338 return lhs;
339}
340
341// Parse an equality_expression.
342//
343// equality_expression:
344// relational_expression {"==" relational_expression}
345// relational_expression {"!=" relational_expression}
346//
348 auto lhs = ParseRelationalExpression();
349 assert(lhs && "ASTNodeUP must not contain a nullptr");
350
351 while (CurToken().IsOneOf({Token::equalequal, Token::exclaimequal})) {
352 Token token = CurToken();
353 m_dil_lexer.Advance();
354 auto rhs = ParseRelationalExpression();
355 assert(rhs && "ASTNodeUP must not contain a nullptr");
356 lhs = std::make_unique<BinaryOpNode>(
358 std::move(lhs), std::move(rhs));
359 }
360
361 return lhs;
362}
363
364// Parse a relational_expression.
365//
366// relational_expression:
367// shift_expression {"<" shift_expression}
368// shift_expression {">" shift_expression}
369// shift_expression {"<=" shift_expression}
370// shift_expression {">=" shift_expression}
371//
373 auto lhs = ParseShiftExpression();
374 assert(lhs && "ASTNodeUP must not contain a nullptr");
375
376 while (CurToken().IsOneOf(
378 Token token = CurToken();
379 m_dil_lexer.Advance();
380 auto rhs = ParseShiftExpression();
381 assert(rhs && "ASTNodeUP must not contain a nullptr");
382 lhs = std::make_unique<BinaryOpNode>(
384 std::move(lhs), std::move(rhs));
385 }
386
387 return lhs;
388}
389
390// Parse a shift_expression.
391//
392// shift_expression:
393// additive_expression {"<<" additive_expression}
394// additive_expression {">>" additive_expression}
395//
397 auto lhs = ParseAdditiveExpression();
398 assert(lhs && "ASTNodeUP must not contain a nullptr");
399
400 while (CurToken().IsOneOf({Token::lessless, Token::greatergreater})) {
401 Token token = CurToken();
402 m_dil_lexer.Advance();
403 auto rhs = ParseAdditiveExpression();
404 assert(rhs && "ASTNodeUP must not contain a nullptr");
405 lhs = std::make_unique<BinaryOpNode>(
407 std::move(lhs), std::move(rhs));
408 }
409
410 return lhs;
411}
412
413// Parse an additive_expression.
414//
415// additive_expression:
416// multiplicative_expression {"+" multiplicative_expression}
417// multiplicative_expression {"-" multiplicative_expression}
418//
421 assert(lhs && "ASTNodeUP must not contain a nullptr");
422
423 while (CurToken().IsOneOf({Token::plus, Token::minus})) {
424 Token token = CurToken();
425 m_dil_lexer.Advance();
427 assert(rhs && "ASTNodeUP must not contain a nullptr");
428 lhs = std::make_unique<BinaryOpNode>(
430 std::move(lhs), std::move(rhs));
431 }
432
433 return lhs;
434}
435
436// Parse a multiplicative_expression.
437//
438// multiplicative_expression:
439// cast_expression {"*" cast_expression}
440// cast_expression {"/" cast_expression}
441// cast_expression {"%" cast_expression}
442//
444 auto lhs = ParseCastExpression();
445
446 while (CurToken().IsOneOf({Token::star, Token::slash, Token::percent})) {
447 Token token = CurToken();
448 if (token.Is(Token::star) && m_mode != lldb::eDILModeFull) {
449 BailOut("binary multiplication (*) is allowed only in DIL full mode",
450 token.GetLocation(), token.GetSpelling().length());
451 return std::make_unique<ErrorNode>();
452 }
453 m_dil_lexer.Advance();
454 auto rhs = ParseCastExpression();
455 assert(rhs && "ASTNodeUP must not contain a nullptr");
456 lhs = std::make_unique<BinaryOpNode>(
458 std::move(lhs), std::move(rhs));
459 }
460
461 return lhs;
462}
463
464// Parse a cast_expression.
465//
466// cast_expression:
467// unary_expression
468// "(" type_id ")" cast_expression
469
471 if (!CurToken().Is(Token::l_paren))
472 return ParseUnaryExpression();
473
474 // This could be a type cast, try parsing the contents as a type declaration.
475 Token token = CurToken();
476 uint32_t loc = token.GetLocation();
477
478 // Enable lexer backtracking, so that we can rollback in case it's not
479 // actually a type declaration.
480
481 // Start tentative parsing (save token location/idx, for possible rollback).
482 uint32_t save_token_idx = m_dil_lexer.GetCurrentTokenIdx();
483
484 // Consume the token only after enabling the backtracking.
485 m_dil_lexer.Advance();
486
487 // Try parsing the type declaration. If the returned value is not valid,
488 // then we should rollback and try parsing the expression.
489 auto type_id = ParseTypeId();
490 if (type_id) {
491 // Successfully parsed the type declaration. Commit the backtracked
492 // tokens and parse the cast_expression.
493
494 if (!type_id.value().IsValid())
495 return std::make_unique<ErrorNode>();
496
498 m_dil_lexer.Advance();
499 auto rhs = ParseCastExpression();
500 assert(rhs && "ASTNodeUP must not contain a nullptr");
501 return std::make_unique<CastNode>(loc, type_id.value(), std::move(rhs),
503 }
504
505 // Failed to parse the contents of the parentheses as a type declaration.
506 // Rollback the lexer and try parsing it as unary_expression.
507 TentativeParsingRollback(save_token_idx);
508
509 return ParseUnaryExpression();
510}
511
512// Parse an unary_expression.
513//
514// unary_expression:
515// postfix_expression
516// unary_operator cast_expression
517//
518// unary_operator:
519// "&"
520// "*"
521// "+"
522// "-"
523// "~"
524// "!"
525//
529 Token::plusplus})) {
530 Token token = CurToken();
531 uint32_t loc = token.GetLocation();
532 m_dil_lexer.Advance();
533 auto rhs = ParseCastExpression();
534 assert(rhs && "ASTNodeUP must not contain a nullptr");
535 switch (token.GetKind()) {
536 case Token::star:
537 return std::make_unique<UnaryOpNode>(loc, UnaryOpKind::Deref,
538 std::move(rhs));
539 case Token::amp:
540 return std::make_unique<UnaryOpNode>(loc, UnaryOpKind::AddrOf,
541 std::move(rhs));
542 case Token::minus:
543 return std::make_unique<UnaryOpNode>(loc, UnaryOpKind::Minus,
544 std::move(rhs));
545 case Token::plus:
546 return std::make_unique<UnaryOpNode>(loc, UnaryOpKind::Plus,
547 std::move(rhs));
548 case Token::tilde:
549 return std::make_unique<UnaryOpNode>(loc, UnaryOpKind::Not,
550 std::move(rhs));
551 case Token::exclaim:
552 return std::make_unique<UnaryOpNode>(loc, UnaryOpKind::LNot,
553 std::move(rhs));
555 BailOut("Decrement operator is not supported. Use `-=` instead.",
556 CurToken().GetLocation(), CurToken().GetSpelling().length());
557 return std::make_unique<ErrorNode>();
558 case Token::plusplus:
559 BailOut("Increment operator is not supported. Use `+=` instead.",
560 CurToken().GetLocation(), CurToken().GetSpelling().length());
561 return std::make_unique<ErrorNode>();
562 default:
563 llvm_unreachable("invalid token kind");
564 }
565 }
566 return ParsePostfixExpression();
567}
568
569// Parse a postfix_expression.
570//
571// postfix_expression:
572// primary_expression
573// postfix_expression "[" pure_expression "]"
574// postfix_expression "[" pure_expression ":" pure_expression "]"
575// postfix_expression "." id_expression
576// postfix_expression "->" id_expression
577//
580 assert(lhs && "ASTNodeUP must not contain a nullptr");
583 uint32_t loc = CurToken().GetLocation();
584 Token token = CurToken();
585 switch (token.GetKind()) {
586 case Token::l_square: {
587 m_dil_lexer.Advance();
589 assert(index && "ASTNodeUP must not contain a nullptr");
590 if (CurToken().GetKind() == Token::colon) {
591 m_dil_lexer.Advance();
592 ASTNodeUP last_index = ParsePureExpression();
593 assert(last_index && "ASTNodeUP must not contain a nullptr");
594 lhs = std::make_unique<BitFieldExtractionNode>(
595 loc, std::move(lhs), std::move(index), std::move(last_index));
596 } else if (CurToken().GetKind() == Token::minus) {
597 BailOut("use of '-' for bitfield range is deprecated; use ':' instead",
598 CurToken().GetLocation(), CurToken().GetSpelling().length());
599 return std::make_unique<ErrorNode>();
600 } else {
601 lhs = std::make_unique<ArraySubscriptNode>(loc, std::move(lhs),
602 std::move(index));
603 }
605 m_dil_lexer.Advance();
606 break;
607 }
608 case Token::period:
609 case Token::arrow: {
610 m_dil_lexer.Advance();
611 Token member_token = CurToken();
612 std::string member_id = ParseIdExpression();
613 lhs = std::make_unique<MemberOfNode>(
614 member_token.GetLocation(), std::move(lhs),
615 token.GetKind() == Token::arrow, member_id);
616 break;
617 }
619 BailOut("Decrement operator is not supported. Use `-=` instead.",
620 CurToken().GetLocation(), CurToken().GetSpelling().length());
621 return std::make_unique<ErrorNode>();
622 case Token::plusplus:
623 BailOut("Increment operator is not supported. Use `+=` instead.",
624 CurToken().GetLocation(), CurToken().GetSpelling().length());
625 return std::make_unique<ErrorNode>();
626 default:
627 llvm_unreachable("invalid token");
628 }
629 }
630
631 return lhs;
632}
633
634// Parse a primary_expression.
635//
636// primary_expression:
637// numeric_literal
638// boolean_literal
639// id_expression
640// "(" pure_expression ")"
641//
644 return ParseNumericLiteral();
645 if (CurToken().IsOneOf({Token::kw_true, Token::kw_false}))
646 return ParseBooleanLiteral();
647 if (CurToken().IsOneOf(
649 // Save the source location for the diagnostics message.
650 uint32_t loc = CurToken().GetLocation();
651 std::string identifier = ParseIdExpression();
652
653 if (!identifier.empty()) {
654 if (identifier == "sizeof" && CurToken().Is(Token::l_paren)) {
655 m_dil_lexer.Advance();
656 uint32_t save_token_idx = m_dil_lexer.GetCurrentTokenIdx();
657 auto type_id = ParseTypeId();
658 if (type_id) {
660 m_dil_lexer.Advance();
661 return std::make_unique<SizeOfNode>(loc, *type_id);
662 }
663 TentativeParsingRollback(save_token_idx);
666 m_dil_lexer.Advance();
667 return std::make_unique<SizeOfNode>(loc, std::move(expr));
668 }
669 return std::make_unique<IdentifierNode>(loc, identifier);
670 }
671 }
672
673 if (CurToken().Is(Token::l_paren)) {
674 m_dil_lexer.Advance();
675 auto expr = ParsePureExpression();
677 m_dil_lexer.Advance();
678 return expr;
679 }
680
681 BailOut(llvm::formatv("Unexpected token: {0}", CurToken()),
682 CurToken().GetLocation(), CurToken().GetSpelling().length());
683 return std::make_unique<ErrorNode>();
684}
685
686// Parse nested_name_specifier.
687//
688// nested_name_specifier:
689// type_name "::"
690// namespace_name "::"
691// nested_name_specifier identifier "::"
692//
694 // The first token in nested_name_specifier is always an identifier, or
695 // '(anonymous namespace)'.
696 switch (CurToken().GetKind()) {
697 case Token::l_paren: {
698 // Anonymous namespaces need to be treated specially: They are
699 // represented the the string '(anonymous namespace)', which has a
700 // space in it (throwing off normal parsing) and is not actually
701 // proper C++> Check to see if we're looking at
702 // '(anonymous namespace)::...'
703
704 // Look for all the pieces, in order:
705 // l_paren 'anonymous' 'namespace' r_paren coloncolon
706 if (m_dil_lexer.LookAhead(1).Is(Token::identifier) &&
707 (m_dil_lexer.LookAhead(1).GetSpelling() == "anonymous") &&
708 m_dil_lexer.LookAhead(2).Is(Token::identifier) &&
709 (m_dil_lexer.LookAhead(2).GetSpelling() == "namespace") &&
710 m_dil_lexer.LookAhead(3).Is(Token::r_paren) &&
711 m_dil_lexer.LookAhead(4).Is(Token::coloncolon)) {
712 m_dil_lexer.Advance(4);
713
715 m_dil_lexer.Advance();
716 if (!CurToken().Is(Token::identifier) && !CurToken().Is(Token::l_paren)) {
717 BailOut("Expected an identifier or anonymous namespace, but not found.",
718 CurToken().GetLocation(), CurToken().GetSpelling().length());
719 }
720 // Continue parsing the nested_namespace_specifier.
721 std::string identifier2 = ParseNestedNameSpecifier();
722
723 return "(anonymous namespace)::" + identifier2;
724 }
725
726 return "";
727 } // end of special handling for '(anonymous namespace)'
728 case Token::identifier: {
729 // If the next token is scope ("::"), then this is indeed a
730 // nested_name_specifier
731 if (m_dil_lexer.LookAhead(1).Is(Token::coloncolon)) {
732 // This nested_name_specifier is a single identifier.
733 std::string identifier = CurToken().GetSpelling();
734 m_dil_lexer.Advance(1);
736 m_dil_lexer.Advance();
737 // Continue parsing the nested_name_specifier.
738 return identifier + "::" + ParseNestedNameSpecifier();
739 }
740
741 return "";
742 }
743 default:
744 return "";
745 }
746}
747
748// Parse a type_id.
749//
750// type_id:
751// type_specifier_seq [abstract_declarator]
752//
753// type_specifier_seq:
754// type_specifier [type_specifier]
755//
756// type_specifier:
757// ["::"] [nested_name_specifier] type_name // not handled for now!
758// builtin_typename
759//
760std::optional<CompilerType> DILParser::ParseTypeId() {
761 CompilerType type;
762 auto maybe_builtin_type = ParseBuiltinType();
763 if (maybe_builtin_type) {
764 type = *maybe_builtin_type;
765 } else {
766 // Check to see if we have a user-defined type here.
767 // First build up the user-defined type name.
768 std::string type_name;
769 ParseTypeSpecifierSeq(type_name);
770
771 if (type_name.empty())
772 return {};
773 type = ResolveTypeByName(type_name, m_stack_frame);
774 if (!type.IsValid())
775 return {};
776
777 // Same-name identifiers should be preferred over typenames.
779 // TODO: Make type accessible with 'class', 'struct' and 'union' keywords.
780 return {};
781
782 // Same-name identifiers should be preferred over typenames.
784 m_stack_frame.CalculateTarget(), m_use_dynamic))
785 // TODO: Make type accessible with 'class', 'struct' and 'union' keywords
786 return {};
787 }
788
789 //
790 // abstract_declarator:
791 // ptr_operator [abstract_declarator]
792 //
793 std::vector<Token> ptr_operators;
794 while (CurToken().IsOneOf({Token::star, Token::amp})) {
795 Token tok = CurToken();
796 ptr_operators.push_back(std::move(tok));
797 m_dil_lexer.Advance();
798 }
799 type = ResolveTypeDeclarators(type, ptr_operators);
800
801 return type;
802}
803
804// Parse a built-in type
805//
806// builtin_typename:
807// identifer_seq
808//
809// identifier_seq
810// identifer [identifier_seq]
811//
812// A built-in type can be a single identifier or a space-separated
813// list of identifiers (e.g. "short" or "long long").
814std::optional<CompilerType> DILParser::ParseBuiltinType() {
815 std::string type_name = "";
816 uint32_t save_token_idx = m_dil_lexer.GetCurrentTokenIdx();
817 bool first_word = true;
818 while (CurToken().GetKind() == Token::identifier) {
819 if (CurToken().GetSpelling() == "const" ||
820 CurToken().GetSpelling() == "volatile") {
821 m_dil_lexer.Advance();
822 continue;
823 }
824 if (!first_word)
825 type_name.push_back(' ');
826 else
827 first_word = false;
828 type_name.append(CurToken().GetSpelling());
829 m_dil_lexer.Advance();
830 }
831
832 if (type_name.size() > 0) {
833 lldb::TargetSP target_sp = m_stack_frame.CalculateTarget();
834 ConstString const_type_name(type_name);
835 for (auto type_system_sp : target_sp->GetScratchTypeSystems())
836 if (auto compiler_type =
837 type_system_sp->GetBuiltinTypeByName(const_type_name))
838 return compiler_type;
839 }
840
841 TentativeParsingRollback(save_token_idx);
842 return {};
843}
844
845// Parse a type_specifier_seq.
846//
847// type_specifier_seq:
848// type_specifier [type_specifier_seq]
849//
850void DILParser::ParseTypeSpecifierSeq(std::string &type_name) {
851 while (true) {
852 std::optional<std::string> err_or_string = ParseTypeSpecifier();
853 if (!err_or_string)
854 break;
855 type_name = *err_or_string;
856 }
857}
858
859// Parse a type_specifier.
860//
861// type_specifier:
862// ["::"] [nested_name_specifier] type_name
863//
864// Returns TRUE if a type_specifier was successfully parsed at this location.
865//
866std::optional<std::string> DILParser::ParseTypeSpecifier() {
867 // The type_specifier must be a user-defined type. Try parsing a
868 // simple_type_specifier.
869
870 // Try parsing optional global scope operator.
871 bool global_scope = false;
872 if (CurToken().Is(Token::coloncolon)) {
873 global_scope = true;
874 m_dil_lexer.Advance();
875 }
876
877 // Try parsing optional nested_name_specifier.
878 auto nested_name_specifier = ParseNestedNameSpecifier();
879
880 // Try parsing required type_name.
881 auto type_name_or_err = ParseTypeName();
882 if (!type_name_or_err)
883 return type_name_or_err;
884 std::string type_name = *type_name_or_err;
885
886 // If there is a type_name, then this is indeed a simple_type_specifier.
887 // Global and qualified (namespace/class) scopes can be empty, since they're
888 // optional. In this case type_name is type we're looking for.
889 if (!type_name.empty())
890 // User-defined typenames can't be combined with builtin keywords.
891 return llvm::formatv("{0}{1}{2}", global_scope ? "::" : "",
892 nested_name_specifier, type_name);
893
894 // No type_specifier was found here.
895 return {};
896}
897
898// Parse a type_name.
899//
900// type_name:
901// class_name
902// enum_name
903// typedef_name
904//
905// class_name
906// identifier
907//
908// enum_name
909// identifier
910//
911// typedef_name
912// identifier
913//
914std::optional<std::string> DILParser::ParseTypeName() {
915 // Typename always starts with an identifier.
916 if (CurToken().IsNot(Token::identifier)) {
917 return std::nullopt;
918 }
919
920 // Otherwise look for a class_name, enum_name or a typedef_name.
921 std::string identifier = CurToken().GetSpelling();
922 m_dil_lexer.Advance();
923
924 return identifier;
925}
926
927// Parse an id_expression.
928//
929// id_expression:
930// unqualified_id
931// qualified_id
932//
933// qualified_id:
934// ["::"] [nested_name_specifier] unqualified_id
935// ["::"] identifier
936//
937// identifier:
938// ? Token::identifier ?
939//
941 // Try parsing optional global scope operator.
942 bool global_scope = false;
943 if (CurToken().Is(Token::coloncolon)) {
944 global_scope = true;
945 m_dil_lexer.Advance();
946 }
947
948 // Try parsing optional nested_name_specifier.
949 std::string nested_name_specifier = ParseNestedNameSpecifier();
950
951 // If nested_name_specifier is present, then it's qualified_id production.
952 // Follow the first production rule.
953 if (!nested_name_specifier.empty()) {
954 // Parse unqualified_id and construct a fully qualified id expression.
955 auto unqualified_id = ParseUnqualifiedId();
956
957 return llvm::formatv("{0}{1}{2}", global_scope ? "::" : "",
958 nested_name_specifier, unqualified_id);
959 }
960
961 if (!CurToken().Is(Token::identifier))
962 return "";
963
964 // No nested_name_specifier, but with global scope -- this is also a
965 // qualified_id production. Follow the second production rule.
966 if (global_scope) {
968 std::string identifier = CurToken().GetSpelling();
969 m_dil_lexer.Advance();
970 return llvm::formatv("{0}{1}", global_scope ? "::" : "", identifier);
971 }
972
973 // This is unqualified_id production.
974 return ParseUnqualifiedId();
975}
976
977// Parse an unqualified_id.
978//
979// unqualified_id:
980// identifier
981//
982// identifier:
983// ? Token::identifier ?
984//
987 std::string identifier = CurToken().GetSpelling();
988 m_dil_lexer.Advance();
989 return identifier;
990}
991
994 const std::vector<Token> &ptr_operators) {
995 // Resolve pointers/references.
996 for (Token tk : ptr_operators) {
997 uint32_t loc = tk.GetLocation();
998 if (tk.GetKind() == Token::star) {
999 // Pointers to reference types are forbidden.
1000 if (type.IsReferenceType()) {
1001 BailOut(llvm::formatv("'type name' declared as a pointer to a "
1002 "reference of type {0}",
1003 type.TypeDescription()),
1004 loc, CurToken().GetSpelling().length());
1005 return {};
1006 }
1007 // Get pointer type for the base type: e.g. int* -> int**.
1008 type = type.GetPointerType();
1009
1010 } else if (tk.GetKind() == Token::amp) {
1011 // References to references are forbidden.
1012 // FIXME: In future we may want to allow rvalue references (i.e. &&).
1013 if (type.IsReferenceType()) {
1014 BailOut("type name declared as a reference to a reference", loc,
1015 CurToken().GetSpelling().length());
1016 return {};
1017 }
1018 // Get reference type for the base type: e.g. int -> int&.
1019 type = type.GetLValueReferenceType();
1020 }
1021 }
1022
1023 return type;
1024}
1025
1026// Parse an boolean_literal.
1027//
1028// boolean_literal:
1029// "true"
1030// "false"
1031//
1033 ExpectOneOf(std::vector<Token::Kind>{Token::kw_true, Token::kw_false});
1034 uint32_t loc = CurToken().GetLocation();
1035 bool literal_value = CurToken().Is(Token::kw_true);
1036 m_dil_lexer.Advance();
1037 return std::make_unique<BooleanLiteralNode>(loc, literal_value);
1038}
1039
1040void DILParser::BailOut(const std::string &error, uint32_t loc,
1041 uint16_t err_len) {
1042 if (m_error)
1043 // If error is already set, then the parser is in the "bail-out" mode. Don't
1044 // do anything and keep the original error.
1045 return;
1046
1047 m_error =
1048 llvm::make_error<DILDiagnosticError>(m_input_expr, error, loc, err_len);
1049 // Advance the lexer token index to the end of the lexed tokens vector.
1050 m_dil_lexer.ResetTokenIdx(m_dil_lexer.NumLexedTokens() - 1);
1051}
1052
1053// Parse a numeric_literal.
1054//
1055// numeric_literal:
1056// ? Token::integer_constant ?
1057// ? Token::floating_constant ?
1058//
1060 ASTNodeUP numeric_constant;
1062 numeric_constant = ParseIntegerLiteral();
1063 else
1064 numeric_constant = ParseFloatingPointLiteral();
1065 if (numeric_constant->GetKind() == NodeKind::eErrorNode) {
1066 BailOut(llvm::formatv("Failed to parse token as numeric-constant: {0}",
1067 CurToken()),
1068 CurToken().GetLocation(), CurToken().GetSpelling().length());
1069 return numeric_constant;
1070 }
1071 m_dil_lexer.Advance();
1072 return numeric_constant;
1073}
1074
1076 Token token = CurToken();
1077 auto spelling = token.GetSpelling();
1078 llvm::StringRef spelling_ref = spelling;
1079
1080 auto radix = llvm::getAutoSenseRadix(spelling_ref);
1082 bool is_unsigned = false;
1083 if (spelling_ref.consume_back_insensitive("u"))
1084 is_unsigned = true;
1085 if (spelling_ref.consume_back_insensitive("ll"))
1087 else if (spelling_ref.consume_back_insensitive("l"))
1089 // Suffix 'u' can be only specified only once, before or after 'l'
1090 if (!is_unsigned && spelling_ref.consume_back_insensitive("u"))
1091 is_unsigned = true;
1092
1093 llvm::APInt raw_value;
1094 if (!spelling_ref.getAsInteger(radix, raw_value))
1095 return std::make_unique<IntegerLiteralNode>(token.GetLocation(), raw_value,
1096 radix, is_unsigned, type);
1097 return std::make_unique<ErrorNode>();
1098}
1099
1101 Token token = CurToken();
1102 auto spelling = token.GetSpelling();
1103 llvm::StringRef spelling_ref = spelling;
1104
1105 llvm::APFloat raw_float(llvm::APFloat::IEEEdouble());
1106 if (spelling_ref.consume_back_insensitive("f"))
1107 raw_float = llvm::APFloat(llvm::APFloat::IEEEsingle());
1108
1109 auto StatusOrErr = raw_float.convertFromString(
1110 spelling_ref, llvm::APFloat::rmNearestTiesToEven);
1111 if (!errorToBool(StatusOrErr.takeError()))
1112 return std::make_unique<FloatLiteralNode>(token.GetLocation(), raw_float);
1113 return std::make_unique<ErrorNode>();
1114}
1115
1118 BailOut("Assignment is allowed only at top level.",
1119 CurToken().GetLocation(), CurToken().GetSpelling().length());
1120 }
1121 if (CurToken().IsNot(kind)) {
1122 BailOut(llvm::formatv("expected {0}, got: {1}", kind, CurToken()),
1123 CurToken().GetLocation(), CurToken().GetSpelling().length());
1124 }
1125}
1126
1127void DILParser::ExpectOneOf(std::vector<Token::Kind> kinds_vec) {
1128 if (!CurToken().IsOneOf(kinds_vec)) {
1129 BailOut(llvm::formatv("expected any of ({0}), got: {1}",
1130 llvm::iterator_range(kinds_vec), CurToken()),
1131 CurToken().GetLocation(), CurToken().GetSpelling().length());
1132 }
1133}
1134
1135} // namespace lldb_private::dil
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:375
uint32_t GetKind(uint32_t data)
Return the type kind encoded in the given data.
Generic representation of a type in a programming language.
CompilerType GetPointerType() const
Return a new CompilerType that is a pointer to this type.
CompilerType GetLValueReferenceType() const
Return a new CompilerType that is a L value reference to this type if this type is valid and the type...
ConstString GetTypeName(bool BaseOnly=false) const
bool IsReferenceType(CompilerType *pointee_type=nullptr, bool *is_rvalue=nullptr) const
A uniqued constant string class.
Definition ConstString.h:40
llvm::StringRef GetStringRef() const
Get the string value as a llvm::StringRef.
"lldb/Target/ExecutionContextScope.h" Inherit from this if your object can reconstruct its execution ...
virtual lldb::TargetSP CalculateTarget()=0
A file utility class.
Definition FileSpec.h:56
A collection class for Module objects.
Definition ModuleList.h:125
void FindTypes(Module *search_first, const TypeQuery &query, lldb_private::TypeResults &results) const
Find types using a type-matching object that contains all search parameters.
This base class provides an interface to stack frames.
Definition StackFrame.h:44
A class that contains all state required for type lookups.
Definition Type.h:104
This class tracks the state and results of a TypeQuery.
Definition Type.h:344
lldb::TypeSP GetFirstType() const
Definition Type.h:385
DILDiagnosticError(DiagnosticDetail detail)
Definition DILParser.h:48
std::string message() const override
Definition DILParser.h:63
Class for doing the simple lexing required by DIL.
Definition DILLexer.h:104
ASTNodeUP ParseInclusiveOrExpression()
ASTNodeUP ParseConditionalBranches(ASTNodeUP condition)
void ParseTypeSpecifierSeq(std::string &type_name)
void Expect(Token::Kind kind)
std::optional< CompilerType > ParseTypeId()
static llvm::Expected< ASTNodeUP > Parse(llvm::StringRef dil_input_expr, DILLexer lexer, StackFrame &stack_frame, lldb::DynamicValueType use_dynamic, lldb::DILMode mode)
Parse the lexed tokens.
Definition DILParser.cpp:94
void TentativeParsingRollback(uint32_t saved_idx)
Definition DILParser.h:129
ASTNodeUP ParseLogicalAndExpression()
void ExpectOneOf(std::vector< Token::Kind > kinds_vec)
std::optional< std::string > ParseTypeSpecifier()
ASTNodeUP ParseRelationalExpression()
ASTNodeUP ParseAssignmentExpression()
std::optional< CompilerType > ParseBuiltinType()
DILParser(llvm::StringRef dil_input_expr, DILLexer lexer, StackFrame &stack_frame, lldb::DynamicValueType use_dynamic, llvm::Error &error, lldb::DILMode mode)
void BailOut(const std::string &error, uint32_t loc, uint16_t err_len)
CompilerType ResolveTypeDeclarators(CompilerType type, const std::vector< Token > &ptr_operators)
ASTNodeUP ParseMultiplicativeExpression()
lldb::DynamicValueType m_use_dynamic
Definition DILParser.h:149
std::optional< std::string > ParseTypeName()
llvm::StringRef m_input_expr
Definition DILParser.h:142
ASTNodeUP ParseConditionalExpression()
std::string ParseNestedNameSpecifier()
ASTNodeUP ParseExclusiveOrExpression()
Class defining the tokens generated by the DIL lexer and used by the DIL parser.
Definition DILLexer.h:25
bool Is(Kind kind) const
Definition DILLexer.h:85
uint32_t GetLocation() const
Definition DILLexer.h:93
Kind GetKind() const
Definition DILLexer.h:81
std::string GetSpelling() const
Definition DILLexer.h:83
@ eNone
Invalid promotion type (results in error).
Definition DILAST.h:88
lldb::ValueObjectSP LookupIdentifier(llvm::StringRef name_ref, StackFrame &stack_frame, lldb::DynamicValueType use_dynamic)
Given the name of an identifier (variable name, member name, type name, etc.), find the ValueObject f...
Definition DILEval.cpp:368
std::unique_ptr< ASTNode > ASTNodeUP
Definition DILAST.h:123
lldb::ValueObjectSP LookupGlobalIdentifier(llvm::StringRef name_ref, StackFrame &stack_frame, lldb::TargetSP target_sp, lldb::DynamicValueType use_dynamic)
Given the name of an identifier, check to see if it matches the name of a global variable.
Definition DILEval.cpp:312
BinaryOpKind GetBinaryOpKindFromToken(Token::Kind token_kind)
Translates DIL tokens to BinaryOpKind.
Definition DILAST.cpp:14
CompilerType ResolveTypeByName(const std::string &name, ExecutionContextScope &ctx_scope)
Definition DILParser.cpp:63
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:338
std::shared_ptr< lldb_private::Type > TypeSP
std::shared_ptr< lldb_private::Target > TargetSP
DILMode
Data Inspection Language (DIL) evaluation modes.
@ eDILModeFull
Allowed: everything supported by DIL.
A source location consisting of a file name and position.