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