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