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 a conditional_expression.
135//
136// conditional_expression:
137// assignment_expression
138// assignment_expression "?" expression ":" expression
139//
141 auto lhs = ParseAssignmentExpression();
142 assert(lhs && "ASTNodeUP must not contain a nullptr");
143
144 // Check if it's a ternary operator.
145 if (CurToken().Is(Token::question)) {
146 Token token = CurToken();
147 m_dil_lexer.Advance();
148 auto true_op = ParseExpression();
149 assert(true_op && "ASTNodeUP must not contain a nullptr");
151 m_dil_lexer.Advance();
152 auto false_op = ParseExpression();
153 assert(false_op && "ASTNodeUP must not contain a nullptr");
154 lhs = std::make_unique<ConditionalNode>(token.GetLocation(), std::move(lhs),
155 std::move(true_op),
156 std::move(false_op));
157 }
158
159 return lhs;
160}
161
162// Parse an assignment_expression
163//
164// assignment_expression
165// logical_or_expression
166// logical_or_expression assignment_operator assignment_expression
167//
168// assignment_operator:
169// "="
170// "+="
171// "-="
172//
174 auto lhs = ParseLogicalOrExpression();
175 assert(lhs && "ASTNodeUP must not contain a nullptr");
176
177 // Check if it's an assignment expression.
179 // That's an assignment!
180 Token token = CurToken();
181 m_dil_lexer.Advance();
182 auto rhs = ParseAssignmentExpression();
183 assert(rhs && "ASTNodeUP must not contain a nullptr");
184 lhs = std::make_unique<BinaryOpNode>(
186 std::move(lhs), std::move(rhs));
187 }
188 return lhs;
189}
190
191// Parse a logical_or_expression.
192//
193// logical_or_expression:
194// logical_and_expression {"||" logical_and_expression}
195//
197 auto lhs = ParseLogicalAndExpression();
198 assert(lhs && "ASTNodeUP must not contain a nullptr");
199
200 while (CurToken().Is(Token::pipepipe)) {
201 Token token = CurToken();
202 m_dil_lexer.Advance();
203 auto rhs = ParseLogicalAndExpression();
204 assert(rhs && "ASTNodeUP must not contain a nullptr");
205 lhs = std::make_unique<BinaryOpNode>(
207 std::move(lhs), std::move(rhs));
208 }
209
210 return lhs;
211}
212
213// Parse a logical_and_expression.
214//
215// logical_and_expression:
216// inclusive_or_expression {"&&" inclusive_or_expression}
217//
219 auto lhs = ParseInclusiveOrExpression();
220 assert(lhs && "ASTNodeUP must not contain a nullptr");
221
222 while (CurToken().Is(Token::ampamp)) {
223 Token token = CurToken();
224 m_dil_lexer.Advance();
225 auto rhs = ParseInclusiveOrExpression();
226 assert(rhs && "ASTNodeUP must not contain a nullptr");
227 lhs = std::make_unique<BinaryOpNode>(
229 std::move(lhs), std::move(rhs));
230 }
231
232 return lhs;
233}
234
235// Parse an inclusive_or_expression.
236//
237// inclusive_or_expression:
238// exclusive_or_expression {"|" exclusive_or_expression}
239//
241 auto lhs = ParseExclusiveOrExpression();
242 assert(lhs && "ASTNodeUP must not contain a nullptr");
243
244 while (CurToken().Is(Token::pipe)) {
245 Token token = CurToken();
246 m_dil_lexer.Advance();
247 auto rhs = ParseExclusiveOrExpression();
248 assert(rhs && "ASTNodeUP must not contain a nullptr");
249 lhs = std::make_unique<BinaryOpNode>(
251 std::move(lhs), std::move(rhs));
252 }
253
254 return lhs;
255}
256
257// Parse an exclusive_or_expression.
258//
259// exclusive_or_expression:
260// and_expression {"^" and_expression}
261//
263 auto lhs = ParseAndExpression();
264 assert(lhs && "ASTNodeUP must not contain a nullptr");
265
266 while (CurToken().Is(Token::caret)) {
267 Token token = CurToken();
268 m_dil_lexer.Advance();
269 auto rhs = ParseAndExpression();
270 assert(rhs && "ASTNodeUP must not contain a nullptr");
271 lhs = std::make_unique<BinaryOpNode>(
273 std::move(lhs), std::move(rhs));
274 }
275
276 return lhs;
277}
278
279// Parse an and_expression.
280//
281// and_expression:
282// equality_expression {"&" equality_expression}
283//
285 auto lhs = ParseEqualityExpression();
286 assert(lhs && "ASTNodeUP must not contain a nullptr");
287
288 while (CurToken().Is(Token::amp)) {
289 Token token = CurToken();
290 if (token.Is(Token::amp) && m_mode != lldb::eDILModeFull) {
291 BailOut("bitwise and (&) is allowed only in DIL full mode",
292 token.GetLocation(), token.GetSpelling().length());
293 return std::make_unique<ErrorNode>();
294 }
295 m_dil_lexer.Advance();
296 auto rhs = ParseEqualityExpression();
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 equality_expression.
307//
308// equality_expression:
309// relational_expression {"==" relational_expression}
310// relational_expression {"!=" relational_expression}
311//
313 auto lhs = ParseRelationalExpression();
314 assert(lhs && "ASTNodeUP must not contain a nullptr");
315
316 while (CurToken().IsOneOf({Token::equalequal, Token::exclaimequal})) {
317 Token token = CurToken();
318 m_dil_lexer.Advance();
319 auto rhs = ParseRelationalExpression();
320 assert(rhs && "ASTNodeUP must not contain a nullptr");
321 lhs = std::make_unique<BinaryOpNode>(
323 std::move(lhs), std::move(rhs));
324 }
325
326 return lhs;
327}
328
329// Parse a relational_expression.
330//
331// relational_expression:
332// shift_expression {"<" shift_expression}
333// shift_expression {">" shift_expression}
334// shift_expression {"<=" shift_expression}
335// shift_expression {">=" shift_expression}
336//
338 auto lhs = ParseShiftExpression();
339 assert(lhs && "ASTNodeUP must not contain a nullptr");
340
341 while (CurToken().IsOneOf(
343 Token token = CurToken();
344 m_dil_lexer.Advance();
345 auto rhs = ParseShiftExpression();
346 assert(rhs && "ASTNodeUP must not contain a nullptr");
347 lhs = std::make_unique<BinaryOpNode>(
349 std::move(lhs), std::move(rhs));
350 }
351
352 return lhs;
353}
354
355// Parse a shift_expression.
356//
357// shift_expression:
358// additive_expression {"<<" additive_expression}
359// additive_expression {">>" additive_expression}
360//
362 auto lhs = ParseAdditiveExpression();
363 assert(lhs && "ASTNodeUP must not contain a nullptr");
364
365 while (CurToken().IsOneOf({Token::lessless, Token::greatergreater})) {
366 Token token = CurToken();
367 m_dil_lexer.Advance();
368 auto rhs = ParseAdditiveExpression();
369 assert(rhs && "ASTNodeUP must not contain a nullptr");
370 lhs = std::make_unique<BinaryOpNode>(
372 std::move(lhs), std::move(rhs));
373 }
374
375 return lhs;
376}
377
378// Parse an additive_expression.
379//
380// additive_expression:
381// multiplicative_expression {"+" multiplicative_expression}
382// multiplicative_expression {"-" multiplicative_expression}
383//
386 assert(lhs && "ASTNodeUP must not contain a nullptr");
387
388 while (CurToken().IsOneOf({Token::plus, Token::minus})) {
389 Token token = CurToken();
390 m_dil_lexer.Advance();
392 assert(rhs && "ASTNodeUP must not contain a nullptr");
393 lhs = std::make_unique<BinaryOpNode>(
395 std::move(lhs), std::move(rhs));
396 }
397
398 return lhs;
399}
400
401// Parse a multiplicative_expression.
402//
403// multiplicative_expression:
404// cast_expression {"*" cast_expression}
405// cast_expression {"/" cast_expression}
406// cast_expression {"%" cast_expression}
407//
409 auto lhs = ParseCastExpression();
410
411 while (CurToken().IsOneOf({Token::star, Token::slash, Token::percent})) {
412 Token token = CurToken();
413 if (token.Is(Token::star) && m_mode != lldb::eDILModeFull) {
414 BailOut("binary multiplication (*) is allowed only in DIL full mode",
415 token.GetLocation(), token.GetSpelling().length());
416 return std::make_unique<ErrorNode>();
417 }
418 m_dil_lexer.Advance();
419 auto rhs = ParseCastExpression();
420 assert(rhs && "ASTNodeUP must not contain a nullptr");
421 lhs = std::make_unique<BinaryOpNode>(
423 std::move(lhs), std::move(rhs));
424 }
425
426 return lhs;
427}
428
429// Parse a cast_expression.
430//
431// cast_expression:
432// unary_expression
433// "(" type_id ")" cast_expression
434
436 if (!CurToken().Is(Token::l_paren))
437 return ParseUnaryExpression();
438
439 // This could be a type cast, try parsing the contents as a type declaration.
440 Token token = CurToken();
441 uint32_t loc = token.GetLocation();
442
443 // Enable lexer backtracking, so that we can rollback in case it's not
444 // actually a type declaration.
445
446 // Start tentative parsing (save token location/idx, for possible rollback).
447 uint32_t save_token_idx = m_dil_lexer.GetCurrentTokenIdx();
448
449 // Consume the token only after enabling the backtracking.
450 m_dil_lexer.Advance();
451
452 // Try parsing the type declaration. If the returned value is not valid,
453 // then we should rollback and try parsing the expression.
454 auto type_id = ParseTypeId();
455 if (type_id) {
456 // Successfully parsed the type declaration. Commit the backtracked
457 // tokens and parse the cast_expression.
458
459 if (!type_id.value().IsValid())
460 return std::make_unique<ErrorNode>();
461
463 m_dil_lexer.Advance();
464 auto rhs = ParseCastExpression();
465 assert(rhs && "ASTNodeUP must not contain a nullptr");
466 return std::make_unique<CastNode>(loc, type_id.value(), std::move(rhs),
468 }
469
470 // Failed to parse the contents of the parentheses as a type declaration.
471 // Rollback the lexer and try parsing it as unary_expression.
472 TentativeParsingRollback(save_token_idx);
473
474 return ParseUnaryExpression();
475}
476
477// Parse an unary_expression.
478//
479// unary_expression:
480// postfix_expression
481// unary_operator cast_expression
482//
483// unary_operator:
484// "&"
485// "*"
486// "+"
487// "-"
488// "~"
489// "!"
490//
494 Token token = CurToken();
495 uint32_t loc = token.GetLocation();
496 m_dil_lexer.Advance();
497 auto rhs = ParseCastExpression();
498 assert(rhs && "ASTNodeUP must not contain a nullptr");
499 switch (token.GetKind()) {
500 case Token::star:
501 return std::make_unique<UnaryOpNode>(loc, UnaryOpKind::Deref,
502 std::move(rhs));
503 case Token::amp:
504 return std::make_unique<UnaryOpNode>(loc, UnaryOpKind::AddrOf,
505 std::move(rhs));
506 case Token::minus:
507 return std::make_unique<UnaryOpNode>(loc, UnaryOpKind::Minus,
508 std::move(rhs));
509 case Token::plus:
510 return std::make_unique<UnaryOpNode>(loc, UnaryOpKind::Plus,
511 std::move(rhs));
512 case Token::tilde:
513 return std::make_unique<UnaryOpNode>(loc, UnaryOpKind::Not,
514 std::move(rhs));
515 case Token::exclaim:
516 return std::make_unique<UnaryOpNode>(loc, UnaryOpKind::LNot,
517 std::move(rhs));
518 default:
519 llvm_unreachable("invalid token kind");
520 }
521 }
522 return ParsePostfixExpression();
523}
524
525// Parse a postfix_expression.
526//
527// postfix_expression:
528// primary_expression
529// postfix_expression "[" expression "]"
530// postfix_expression "[" expression ":" expression "]"
531// postfix_expression "." id_expression
532// postfix_expression "->" id_expression
533//
536 assert(lhs && "ASTNodeUP must not contain a nullptr");
537 while (CurToken().IsOneOf({Token::l_square, Token::period, Token::arrow})) {
538 uint32_t loc = CurToken().GetLocation();
539 Token token = CurToken();
540 switch (token.GetKind()) {
541 case Token::l_square: {
542 m_dil_lexer.Advance();
543 ASTNodeUP index = ParseExpression();
544 assert(index && "ASTNodeUP must not contain a nullptr");
545 if (CurToken().GetKind() == Token::colon) {
546 m_dil_lexer.Advance();
547 ASTNodeUP last_index = ParseExpression();
548 assert(last_index && "ASTNodeUP must not contain a nullptr");
549 lhs = std::make_unique<BitFieldExtractionNode>(
550 loc, std::move(lhs), std::move(index), std::move(last_index));
551 } else if (CurToken().GetKind() == Token::minus) {
552 BailOut("use of '-' for bitfield range is deprecated; use ':' instead",
553 CurToken().GetLocation(), CurToken().GetSpelling().length());
554 return std::make_unique<ErrorNode>();
555 } else {
556 lhs = std::make_unique<ArraySubscriptNode>(loc, std::move(lhs),
557 std::move(index));
558 }
560 m_dil_lexer.Advance();
561 break;
562 }
563 case Token::period:
564 case Token::arrow: {
565 m_dil_lexer.Advance();
566 Token member_token = CurToken();
567 std::string member_id = ParseIdExpression();
568 lhs = std::make_unique<MemberOfNode>(
569 member_token.GetLocation(), std::move(lhs),
570 token.GetKind() == Token::arrow, member_id);
571 break;
572 }
573 default:
574 llvm_unreachable("invalid token");
575 }
576 }
577
578 return lhs;
579}
580
581// Parse a primary_expression.
582//
583// primary_expression:
584// numeric_literal
585// boolean_literal
586// id_expression
587// "(" expression ")"
588//
591 return ParseNumericLiteral();
592 if (CurToken().IsOneOf({Token::kw_true, Token::kw_false}))
593 return ParseBooleanLiteral();
594 if (CurToken().IsOneOf(
596 // Save the source location for the diagnostics message.
597 uint32_t loc = CurToken().GetLocation();
598 std::string identifier = ParseIdExpression();
599
600 if (!identifier.empty()) {
601 if (identifier == "sizeof" && CurToken().Is(Token::l_paren)) {
602 m_dil_lexer.Advance();
603 uint32_t save_token_idx = m_dil_lexer.GetCurrentTokenIdx();
604 auto type_id = ParseTypeId();
605 if (type_id) {
607 m_dil_lexer.Advance();
608 return std::make_unique<SizeOfNode>(loc, *type_id);
609 }
610 TentativeParsingRollback(save_token_idx);
611 ASTNodeUP expr = ParseExpression();
613 m_dil_lexer.Advance();
614 return std::make_unique<SizeOfNode>(loc, std::move(expr));
615 }
616 return std::make_unique<IdentifierNode>(loc, identifier);
617 }
618 }
619
620 if (CurToken().Is(Token::l_paren)) {
621 m_dil_lexer.Advance();
622 auto expr = ParseExpression();
624 m_dil_lexer.Advance();
625 return expr;
626 }
627
628 BailOut(llvm::formatv("Unexpected token: {0}", CurToken()),
629 CurToken().GetLocation(), CurToken().GetSpelling().length());
630 return std::make_unique<ErrorNode>();
631}
632
633// Parse nested_name_specifier.
634//
635// nested_name_specifier:
636// type_name "::"
637// namespace_name "::"
638// nested_name_specifier identifier "::"
639//
641 // The first token in nested_name_specifier is always an identifier, or
642 // '(anonymous namespace)'.
643 switch (CurToken().GetKind()) {
644 case Token::l_paren: {
645 // Anonymous namespaces need to be treated specially: They are
646 // represented the the string '(anonymous namespace)', which has a
647 // space in it (throwing off normal parsing) and is not actually
648 // proper C++> Check to see if we're looking at
649 // '(anonymous namespace)::...'
650
651 // Look for all the pieces, in order:
652 // l_paren 'anonymous' 'namespace' r_paren coloncolon
653 if (m_dil_lexer.LookAhead(1).Is(Token::identifier) &&
654 (m_dil_lexer.LookAhead(1).GetSpelling() == "anonymous") &&
655 m_dil_lexer.LookAhead(2).Is(Token::identifier) &&
656 (m_dil_lexer.LookAhead(2).GetSpelling() == "namespace") &&
657 m_dil_lexer.LookAhead(3).Is(Token::r_paren) &&
658 m_dil_lexer.LookAhead(4).Is(Token::coloncolon)) {
659 m_dil_lexer.Advance(4);
660
662 m_dil_lexer.Advance();
663 if (!CurToken().Is(Token::identifier) && !CurToken().Is(Token::l_paren)) {
664 BailOut("Expected an identifier or anonymous namespace, but not found.",
665 CurToken().GetLocation(), CurToken().GetSpelling().length());
666 }
667 // Continue parsing the nested_namespace_specifier.
668 std::string identifier2 = ParseNestedNameSpecifier();
669
670 return "(anonymous namespace)::" + identifier2;
671 }
672
673 return "";
674 } // end of special handling for '(anonymous namespace)'
675 case Token::identifier: {
676 // If the next token is scope ("::"), then this is indeed a
677 // nested_name_specifier
678 if (m_dil_lexer.LookAhead(1).Is(Token::coloncolon)) {
679 // This nested_name_specifier is a single identifier.
680 std::string identifier = CurToken().GetSpelling();
681 m_dil_lexer.Advance(1);
683 m_dil_lexer.Advance();
684 // Continue parsing the nested_name_specifier.
685 return identifier + "::" + ParseNestedNameSpecifier();
686 }
687
688 return "";
689 }
690 default:
691 return "";
692 }
693}
694
695// Parse a type_id.
696//
697// type_id:
698// type_specifier_seq [abstract_declarator]
699//
700// type_specifier_seq:
701// type_specifier [type_specifier]
702//
703// type_specifier:
704// ["::"] [nested_name_specifier] type_name // not handled for now!
705// builtin_typename
706//
707std::optional<CompilerType> DILParser::ParseTypeId() {
708 CompilerType type;
709 auto maybe_builtin_type = ParseBuiltinType();
710 if (maybe_builtin_type) {
711 type = *maybe_builtin_type;
712 } else {
713 // Check to see if we have a user-defined type here.
714 // First build up the user-defined type name.
715 std::string type_name;
716 ParseTypeSpecifierSeq(type_name);
717
718 if (type_name.empty())
719 return {};
720 type = ResolveTypeByName(type_name, m_stack_frame);
721 if (!type.IsValid())
722 return {};
723
724 // Same-name identifiers should be preferred over typenames.
726 // TODO: Make type accessible with 'class', 'struct' and 'union' keywords.
727 return {};
728
729 // Same-name identifiers should be preferred over typenames.
731 m_stack_frame.CalculateTarget(), m_use_dynamic))
732 // TODO: Make type accessible with 'class', 'struct' and 'union' keywords
733 return {};
734 }
735
736 //
737 // abstract_declarator:
738 // ptr_operator [abstract_declarator]
739 //
740 std::vector<Token> ptr_operators;
741 while (CurToken().IsOneOf({Token::star, Token::amp})) {
742 Token tok = CurToken();
743 ptr_operators.push_back(std::move(tok));
744 m_dil_lexer.Advance();
745 }
746 type = ResolveTypeDeclarators(type, ptr_operators);
747
748 return type;
749}
750
751// Parse a built-in type
752//
753// builtin_typename:
754// identifer_seq
755//
756// identifier_seq
757// identifer [identifier_seq]
758//
759// A built-in type can be a single identifier or a space-separated
760// list of identifiers (e.g. "short" or "long long").
761std::optional<CompilerType> DILParser::ParseBuiltinType() {
762 std::string type_name = "";
763 uint32_t save_token_idx = m_dil_lexer.GetCurrentTokenIdx();
764 bool first_word = true;
765 while (CurToken().GetKind() == Token::identifier) {
766 if (CurToken().GetSpelling() == "const" ||
767 CurToken().GetSpelling() == "volatile") {
768 m_dil_lexer.Advance();
769 continue;
770 }
771 if (!first_word)
772 type_name.push_back(' ');
773 else
774 first_word = false;
775 type_name.append(CurToken().GetSpelling());
776 m_dil_lexer.Advance();
777 }
778
779 if (type_name.size() > 0) {
780 lldb::TargetSP target_sp = m_stack_frame.CalculateTarget();
781 ConstString const_type_name(type_name);
782 for (auto type_system_sp : target_sp->GetScratchTypeSystems())
783 if (auto compiler_type =
784 type_system_sp->GetBuiltinTypeByName(const_type_name))
785 return compiler_type;
786 }
787
788 TentativeParsingRollback(save_token_idx);
789 return {};
790}
791
792// Parse a type_specifier_seq.
793//
794// type_specifier_seq:
795// type_specifier [type_specifier_seq]
796//
797void DILParser::ParseTypeSpecifierSeq(std::string &type_name) {
798 while (true) {
799 std::optional<std::string> err_or_string = ParseTypeSpecifier();
800 if (!err_or_string)
801 break;
802 type_name = *err_or_string;
803 }
804}
805
806// Parse a type_specifier.
807//
808// type_specifier:
809// ["::"] [nested_name_specifier] type_name
810//
811// Returns TRUE if a type_specifier was successfully parsed at this location.
812//
813std::optional<std::string> DILParser::ParseTypeSpecifier() {
814 // The type_specifier must be a user-defined type. Try parsing a
815 // simple_type_specifier.
816
817 // Try parsing optional global scope operator.
818 bool global_scope = false;
819 if (CurToken().Is(Token::coloncolon)) {
820 global_scope = true;
821 m_dil_lexer.Advance();
822 }
823
824 // Try parsing optional nested_name_specifier.
825 auto nested_name_specifier = ParseNestedNameSpecifier();
826
827 // Try parsing required type_name.
828 auto type_name_or_err = ParseTypeName();
829 if (!type_name_or_err)
830 return type_name_or_err;
831 std::string type_name = *type_name_or_err;
832
833 // If there is a type_name, then this is indeed a simple_type_specifier.
834 // Global and qualified (namespace/class) scopes can be empty, since they're
835 // optional. In this case type_name is type we're looking for.
836 if (!type_name.empty())
837 // User-defined typenames can't be combined with builtin keywords.
838 return llvm::formatv("{0}{1}{2}", global_scope ? "::" : "",
839 nested_name_specifier, type_name);
840
841 // No type_specifier was found here.
842 return {};
843}
844
845// Parse a type_name.
846//
847// type_name:
848// class_name
849// enum_name
850// typedef_name
851//
852// class_name
853// identifier
854//
855// enum_name
856// identifier
857//
858// typedef_name
859// identifier
860//
861std::optional<std::string> DILParser::ParseTypeName() {
862 // Typename always starts with an identifier.
863 if (CurToken().IsNot(Token::identifier)) {
864 return std::nullopt;
865 }
866
867 // Otherwise look for a class_name, enum_name or a typedef_name.
868 std::string identifier = CurToken().GetSpelling();
869 m_dil_lexer.Advance();
870
871 return identifier;
872}
873
874// Parse an id_expression.
875//
876// id_expression:
877// unqualified_id
878// qualified_id
879//
880// qualified_id:
881// ["::"] [nested_name_specifier] unqualified_id
882// ["::"] identifier
883//
884// identifier:
885// ? Token::identifier ?
886//
888 // Try parsing optional global scope operator.
889 bool global_scope = false;
890 if (CurToken().Is(Token::coloncolon)) {
891 global_scope = true;
892 m_dil_lexer.Advance();
893 }
894
895 // Try parsing optional nested_name_specifier.
896 std::string nested_name_specifier = ParseNestedNameSpecifier();
897
898 // If nested_name_specifier is present, then it's qualified_id production.
899 // Follow the first production rule.
900 if (!nested_name_specifier.empty()) {
901 // Parse unqualified_id and construct a fully qualified id expression.
902 auto unqualified_id = ParseUnqualifiedId();
903
904 return llvm::formatv("{0}{1}{2}", global_scope ? "::" : "",
905 nested_name_specifier, unqualified_id);
906 }
907
908 if (!CurToken().Is(Token::identifier))
909 return "";
910
911 // No nested_name_specifier, but with global scope -- this is also a
912 // qualified_id production. Follow the second production rule.
913 if (global_scope) {
915 std::string identifier = CurToken().GetSpelling();
916 m_dil_lexer.Advance();
917 return llvm::formatv("{0}{1}", global_scope ? "::" : "", identifier);
918 }
919
920 // This is unqualified_id production.
921 return ParseUnqualifiedId();
922}
923
924// Parse an unqualified_id.
925//
926// unqualified_id:
927// identifier
928//
929// identifier:
930// ? Token::identifier ?
931//
934 std::string identifier = CurToken().GetSpelling();
935 m_dil_lexer.Advance();
936 return identifier;
937}
938
941 const std::vector<Token> &ptr_operators) {
942 // Resolve pointers/references.
943 for (Token tk : ptr_operators) {
944 uint32_t loc = tk.GetLocation();
945 if (tk.GetKind() == Token::star) {
946 // Pointers to reference types are forbidden.
947 if (type.IsReferenceType()) {
948 BailOut(llvm::formatv("'type name' declared as a pointer to a "
949 "reference of type {0}",
950 type.TypeDescription()),
951 loc, CurToken().GetSpelling().length());
952 return {};
953 }
954 // Get pointer type for the base type: e.g. int* -> int**.
955 type = type.GetPointerType();
956
957 } else if (tk.GetKind() == Token::amp) {
958 // References to references are forbidden.
959 // FIXME: In future we may want to allow rvalue references (i.e. &&).
960 if (type.IsReferenceType()) {
961 BailOut("type name declared as a reference to a reference", loc,
962 CurToken().GetSpelling().length());
963 return {};
964 }
965 // Get reference type for the base type: e.g. int -> int&.
966 type = type.GetLValueReferenceType();
967 }
968 }
969
970 return type;
971}
972
973// Parse an boolean_literal.
974//
975// boolean_literal:
976// "true"
977// "false"
978//
980 ExpectOneOf(std::vector<Token::Kind>{Token::kw_true, Token::kw_false});
981 uint32_t loc = CurToken().GetLocation();
982 bool literal_value = CurToken().Is(Token::kw_true);
983 m_dil_lexer.Advance();
984 return std::make_unique<BooleanLiteralNode>(loc, literal_value);
985}
986
987void DILParser::BailOut(const std::string &error, uint32_t loc,
988 uint16_t err_len) {
989 if (m_error)
990 // If error is already set, then the parser is in the "bail-out" mode. Don't
991 // do anything and keep the original error.
992 return;
993
994 m_error =
995 llvm::make_error<DILDiagnosticError>(m_input_expr, error, loc, err_len);
996 // Advance the lexer token index to the end of the lexed tokens vector.
997 m_dil_lexer.ResetTokenIdx(m_dil_lexer.NumLexedTokens() - 1);
998}
999
1000// Parse a numeric_literal.
1001//
1002// numeric_literal:
1003// ? Token::integer_constant ?
1004// ? Token::floating_constant ?
1005//
1007 ASTNodeUP numeric_constant;
1009 numeric_constant = ParseIntegerLiteral();
1010 else
1011 numeric_constant = ParseFloatingPointLiteral();
1012 if (numeric_constant->GetKind() == NodeKind::eErrorNode) {
1013 BailOut(llvm::formatv("Failed to parse token as numeric-constant: {0}",
1014 CurToken()),
1015 CurToken().GetLocation(), CurToken().GetSpelling().length());
1016 return numeric_constant;
1017 }
1018 m_dil_lexer.Advance();
1019 return numeric_constant;
1020}
1021
1023 Token token = CurToken();
1024 auto spelling = token.GetSpelling();
1025 llvm::StringRef spelling_ref = spelling;
1026
1027 auto radix = llvm::getAutoSenseRadix(spelling_ref);
1029 bool is_unsigned = false;
1030 if (spelling_ref.consume_back_insensitive("u"))
1031 is_unsigned = true;
1032 if (spelling_ref.consume_back_insensitive("ll"))
1034 else if (spelling_ref.consume_back_insensitive("l"))
1036 // Suffix 'u' can be only specified only once, before or after 'l'
1037 if (!is_unsigned && spelling_ref.consume_back_insensitive("u"))
1038 is_unsigned = true;
1039
1040 llvm::APInt raw_value;
1041 if (!spelling_ref.getAsInteger(radix, raw_value))
1042 return std::make_unique<IntegerLiteralNode>(token.GetLocation(), raw_value,
1043 radix, is_unsigned, type);
1044 return std::make_unique<ErrorNode>();
1045}
1046
1048 Token token = CurToken();
1049 auto spelling = token.GetSpelling();
1050 llvm::StringRef spelling_ref = spelling;
1051
1052 llvm::APFloat raw_float(llvm::APFloat::IEEEdouble());
1053 if (spelling_ref.consume_back_insensitive("f"))
1054 raw_float = llvm::APFloat(llvm::APFloat::IEEEsingle());
1055
1056 auto StatusOrErr = raw_float.convertFromString(
1057 spelling_ref, llvm::APFloat::rmNearestTiesToEven);
1058 if (!errorToBool(StatusOrErr.takeError()))
1059 return std::make_unique<FloatLiteralNode>(token.GetLocation(), raw_float);
1060 return std::make_unique<ErrorNode>();
1061}
1062
1064 if (CurToken().IsNot(kind)) {
1065 BailOut(llvm::formatv("expected {0}, got: {1}", kind, CurToken()),
1066 CurToken().GetLocation(), CurToken().GetSpelling().length());
1067 }
1068}
1069
1070void DILParser::ExpectOneOf(std::vector<Token::Kind> kinds_vec) {
1071 if (!CurToken().IsOneOf(kinds_vec)) {
1072 BailOut(llvm::formatv("expected any of ({0}), got: {1}",
1073 llvm::iterator_range(kinds_vec), CurToken()),
1074 CurToken().GetLocation(), CurToken().GetSpelling().length());
1075 }
1076}
1077
1078} // 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:94
ASTNodeUP ParseInclusiveOrExpression()
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:125
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:145
std::optional< std::string > ParseTypeName()
llvm::StringRef m_input_expr
Definition DILParser.h:138
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:75
uint32_t GetLocation() const
Definition DILLexer.h:83
Kind GetKind() const
Definition DILLexer.h:71
std::string GetSpelling() const
Definition DILLexer.h:73
@ eNone
Invalid promotion type (results in error).
Definition DILAST.h:80
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:326
std::unique_ptr< ASTNode > ASTNodeUP
Definition DILAST.h:115
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:284
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.