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