[Go to site: main page, start]

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 if (identifier == "sizeof" && CurToken().Is(Token::l_paren)) {
477 m_dil_lexer.Advance();
478 uint32_t save_token_idx = m_dil_lexer.GetCurrentTokenIdx();
479 auto type_id = ParseTypeId();
480 if (type_id) {
482 m_dil_lexer.Advance();
483 return std::make_unique<SizeOfNode>(loc, *type_id);
484 }
485 TentativeParsingRollback(save_token_idx);
486 ASTNodeUP expr = ParseExpression();
488 m_dil_lexer.Advance();
489 return std::make_unique<SizeOfNode>(loc, std::move(expr));
490 }
491 return std::make_unique<IdentifierNode>(loc, identifier);
492 }
493 }
494
495 if (CurToken().Is(Token::l_paren)) {
496 m_dil_lexer.Advance();
497 auto expr = ParseExpression();
499 m_dil_lexer.Advance();
500 return expr;
501 }
502
503 BailOut(llvm::formatv("Unexpected token: {0}", CurToken()),
504 CurToken().GetLocation(), CurToken().GetSpelling().length());
505 return std::make_unique<ErrorNode>();
506}
507
508// Parse nested_name_specifier.
509//
510// nested_name_specifier:
511// type_name "::"
512// namespace_name "::"
513// nested_name_specifier identifier "::"
514//
516 // The first token in nested_name_specifier is always an identifier, or
517 // '(anonymous namespace)'.
518 switch (CurToken().GetKind()) {
519 case Token::l_paren: {
520 // Anonymous namespaces need to be treated specially: They are
521 // represented the the string '(anonymous namespace)', which has a
522 // space in it (throwing off normal parsing) and is not actually
523 // proper C++> Check to see if we're looking at
524 // '(anonymous namespace)::...'
525
526 // Look for all the pieces, in order:
527 // l_paren 'anonymous' 'namespace' r_paren coloncolon
528 if (m_dil_lexer.LookAhead(1).Is(Token::identifier) &&
529 (m_dil_lexer.LookAhead(1).GetSpelling() == "anonymous") &&
530 m_dil_lexer.LookAhead(2).Is(Token::identifier) &&
531 (m_dil_lexer.LookAhead(2).GetSpelling() == "namespace") &&
532 m_dil_lexer.LookAhead(3).Is(Token::r_paren) &&
533 m_dil_lexer.LookAhead(4).Is(Token::coloncolon)) {
534 m_dil_lexer.Advance(4);
535
537 m_dil_lexer.Advance();
538 if (!CurToken().Is(Token::identifier) && !CurToken().Is(Token::l_paren)) {
539 BailOut("Expected an identifier or anonymous namespace, but not found.",
540 CurToken().GetLocation(), CurToken().GetSpelling().length());
541 }
542 // Continue parsing the nested_namespace_specifier.
543 std::string identifier2 = ParseNestedNameSpecifier();
544
545 return "(anonymous namespace)::" + identifier2;
546 }
547
548 return "";
549 } // end of special handling for '(anonymous namespace)'
550 case Token::identifier: {
551 // If the next token is scope ("::"), then this is indeed a
552 // nested_name_specifier
553 if (m_dil_lexer.LookAhead(1).Is(Token::coloncolon)) {
554 // This nested_name_specifier is a single identifier.
555 std::string identifier = CurToken().GetSpelling();
556 m_dil_lexer.Advance(1);
558 m_dil_lexer.Advance();
559 // Continue parsing the nested_name_specifier.
560 return identifier + "::" + ParseNestedNameSpecifier();
561 }
562
563 return "";
564 }
565 default:
566 return "";
567 }
568}
569
570// Parse a type_id.
571//
572// type_id:
573// type_specifier_seq [abstract_declarator]
574//
575// type_specifier_seq:
576// type_specifier [type_specifier]
577//
578// type_specifier:
579// ["::"] [nested_name_specifier] type_name // not handled for now!
580// builtin_typename
581//
582std::optional<CompilerType> DILParser::ParseTypeId() {
583 CompilerType type;
584 auto maybe_builtin_type = ParseBuiltinType();
585 if (maybe_builtin_type) {
586 type = *maybe_builtin_type;
587 } else {
588 // Check to see if we have a user-defined type here.
589 // First build up the user-defined type name.
590 std::string type_name;
591 ParseTypeSpecifierSeq(type_name);
592
593 if (type_name.empty())
594 return {};
595 type = ResolveTypeByName(type_name, m_stack_frame);
596 if (!type.IsValid())
597 return {};
598
599 // Same-name identifiers should be preferred over typenames.
601 // TODO: Make type accessible with 'class', 'struct' and 'union' keywords.
602 return {};
603
604 // Same-name identifiers should be preferred over typenames.
606 m_stack_frame.CalculateTarget(), m_use_dynamic))
607 // TODO: Make type accessible with 'class', 'struct' and 'union' keywords
608 return {};
609 }
610
611 //
612 // abstract_declarator:
613 // ptr_operator [abstract_declarator]
614 //
615 std::vector<Token> ptr_operators;
616 while (CurToken().IsOneOf({Token::star, Token::amp})) {
617 Token tok = CurToken();
618 ptr_operators.push_back(std::move(tok));
619 m_dil_lexer.Advance();
620 }
621 type = ResolveTypeDeclarators(type, ptr_operators);
622
623 return type;
624}
625
626// Parse a built-in type
627//
628// builtin_typename:
629// identifer_seq
630//
631// identifier_seq
632// identifer [identifier_seq]
633//
634// A built-in type can be a single identifier or a space-separated
635// list of identifiers (e.g. "short" or "long long").
636std::optional<CompilerType> DILParser::ParseBuiltinType() {
637 std::string type_name = "";
638 uint32_t save_token_idx = m_dil_lexer.GetCurrentTokenIdx();
639 bool first_word = true;
640 while (CurToken().GetKind() == Token::identifier) {
641 if (CurToken().GetSpelling() == "const" ||
642 CurToken().GetSpelling() == "volatile") {
643 m_dil_lexer.Advance();
644 continue;
645 }
646 if (!first_word)
647 type_name.push_back(' ');
648 else
649 first_word = false;
650 type_name.append(CurToken().GetSpelling());
651 m_dil_lexer.Advance();
652 }
653
654 if (type_name.size() > 0) {
655 lldb::TargetSP target_sp = m_stack_frame.CalculateTarget();
656 ConstString const_type_name(type_name);
657 for (auto type_system_sp : target_sp->GetScratchTypeSystems())
658 if (auto compiler_type =
659 type_system_sp->GetBuiltinTypeByName(const_type_name))
660 return compiler_type;
661 }
662
663 TentativeParsingRollback(save_token_idx);
664 return {};
665}
666
667// Parse a type_specifier_seq.
668//
669// type_specifier_seq:
670// type_specifier [type_specifier_seq]
671//
672void DILParser::ParseTypeSpecifierSeq(std::string &type_name) {
673 while (true) {
674 std::optional<std::string> err_or_string = ParseTypeSpecifier();
675 if (!err_or_string)
676 break;
677 type_name = *err_or_string;
678 }
679}
680
681// Parse a type_specifier.
682//
683// type_specifier:
684// ["::"] [nested_name_specifier] type_name
685//
686// Returns TRUE if a type_specifier was successfully parsed at this location.
687//
688std::optional<std::string> DILParser::ParseTypeSpecifier() {
689 // The type_specifier must be a user-defined type. Try parsing a
690 // simple_type_specifier.
691
692 // Try parsing optional global scope operator.
693 bool global_scope = false;
694 if (CurToken().Is(Token::coloncolon)) {
695 global_scope = true;
696 m_dil_lexer.Advance();
697 }
698
699 // Try parsing optional nested_name_specifier.
700 auto nested_name_specifier = ParseNestedNameSpecifier();
701
702 // Try parsing required type_name.
703 auto type_name_or_err = ParseTypeName();
704 if (!type_name_or_err)
705 return type_name_or_err;
706 std::string type_name = *type_name_or_err;
707
708 // If there is a type_name, then this is indeed a simple_type_specifier.
709 // Global and qualified (namespace/class) scopes can be empty, since they're
710 // optional. In this case type_name is type we're looking for.
711 if (!type_name.empty())
712 // User-defined typenames can't be combined with builtin keywords.
713 return llvm::formatv("{0}{1}{2}", global_scope ? "::" : "",
714 nested_name_specifier, type_name);
715
716 // No type_specifier was found here.
717 return {};
718}
719
720// Parse a type_name.
721//
722// type_name:
723// class_name
724// enum_name
725// typedef_name
726//
727// class_name
728// identifier
729//
730// enum_name
731// identifier
732//
733// typedef_name
734// identifier
735//
736std::optional<std::string> DILParser::ParseTypeName() {
737 // Typename always starts with an identifier.
738 if (CurToken().IsNot(Token::identifier)) {
739 return std::nullopt;
740 }
741
742 // Otherwise look for a class_name, enum_name or a typedef_name.
743 std::string identifier = CurToken().GetSpelling();
744 m_dil_lexer.Advance();
745
746 return identifier;
747}
748
749// Parse an id_expression.
750//
751// id_expression:
752// unqualified_id
753// qualified_id
754//
755// qualified_id:
756// ["::"] [nested_name_specifier] unqualified_id
757// ["::"] identifier
758//
759// identifier:
760// ? Token::identifier ?
761//
763 // Try parsing optional global scope operator.
764 bool global_scope = false;
765 if (CurToken().Is(Token::coloncolon)) {
766 global_scope = true;
767 m_dil_lexer.Advance();
768 }
769
770 // Try parsing optional nested_name_specifier.
771 std::string nested_name_specifier = ParseNestedNameSpecifier();
772
773 // If nested_name_specifier is present, then it's qualified_id production.
774 // Follow the first production rule.
775 if (!nested_name_specifier.empty()) {
776 // Parse unqualified_id and construct a fully qualified id expression.
777 auto unqualified_id = ParseUnqualifiedId();
778
779 return llvm::formatv("{0}{1}{2}", global_scope ? "::" : "",
780 nested_name_specifier, unqualified_id);
781 }
782
783 if (!CurToken().Is(Token::identifier))
784 return "";
785
786 // No nested_name_specifier, but with global scope -- this is also a
787 // qualified_id production. Follow the second production rule.
788 if (global_scope) {
790 std::string identifier = CurToken().GetSpelling();
791 m_dil_lexer.Advance();
792 return llvm::formatv("{0}{1}", global_scope ? "::" : "", identifier);
793 }
794
795 // This is unqualified_id production.
796 return ParseUnqualifiedId();
797}
798
799// Parse an unqualified_id.
800//
801// unqualified_id:
802// identifier
803//
804// identifier:
805// ? Token::identifier ?
806//
809 std::string identifier = CurToken().GetSpelling();
810 m_dil_lexer.Advance();
811 return identifier;
812}
813
816 const std::vector<Token> &ptr_operators) {
817 // Resolve pointers/references.
818 for (Token tk : ptr_operators) {
819 uint32_t loc = tk.GetLocation();
820 if (tk.GetKind() == Token::star) {
821 // Pointers to reference types are forbidden.
822 if (type.IsReferenceType()) {
823 BailOut(llvm::formatv("'type name' declared as a pointer to a "
824 "reference of type {0}",
825 type.TypeDescription()),
826 loc, CurToken().GetSpelling().length());
827 return {};
828 }
829 // Get pointer type for the base type: e.g. int* -> int**.
830 type = type.GetPointerType();
831
832 } else if (tk.GetKind() == Token::amp) {
833 // References to references are forbidden.
834 // FIXME: In future we may want to allow rvalue references (i.e. &&).
835 if (type.IsReferenceType()) {
836 BailOut("type name declared as a reference to a reference", loc,
837 CurToken().GetSpelling().length());
838 return {};
839 }
840 // Get reference type for the base type: e.g. int -> int&.
841 type = type.GetLValueReferenceType();
842 }
843 }
844
845 return type;
846}
847
848// Parse an boolean_literal.
849//
850// boolean_literal:
851// "true"
852// "false"
853//
855 ExpectOneOf(std::vector<Token::Kind>{Token::kw_true, Token::kw_false});
856 uint32_t loc = CurToken().GetLocation();
857 bool literal_value = CurToken().Is(Token::kw_true);
858 m_dil_lexer.Advance();
859 return std::make_unique<BooleanLiteralNode>(loc, literal_value);
860}
861
862void DILParser::BailOut(const std::string &error, uint32_t loc,
863 uint16_t err_len) {
864 if (m_error)
865 // If error is already set, then the parser is in the "bail-out" mode. Don't
866 // do anything and keep the original error.
867 return;
868
869 m_error =
870 llvm::make_error<DILDiagnosticError>(m_input_expr, error, loc, err_len);
871 // Advance the lexer token index to the end of the lexed tokens vector.
872 m_dil_lexer.ResetTokenIdx(m_dil_lexer.NumLexedTokens() - 1);
873}
874
875// Parse a numeric_literal.
876//
877// numeric_literal:
878// ? Token::integer_constant ?
879// ? Token::floating_constant ?
880//
882 ASTNodeUP numeric_constant;
884 numeric_constant = ParseIntegerLiteral();
885 else
886 numeric_constant = ParseFloatingPointLiteral();
887 if (numeric_constant->GetKind() == NodeKind::eErrorNode) {
888 BailOut(llvm::formatv("Failed to parse token as numeric-constant: {0}",
889 CurToken()),
890 CurToken().GetLocation(), CurToken().GetSpelling().length());
891 return numeric_constant;
892 }
893 m_dil_lexer.Advance();
894 return numeric_constant;
895}
896
898 Token token = CurToken();
899 auto spelling = token.GetSpelling();
900 llvm::StringRef spelling_ref = spelling;
901
902 auto radix = llvm::getAutoSenseRadix(spelling_ref);
904 bool is_unsigned = false;
905 if (spelling_ref.consume_back_insensitive("u"))
906 is_unsigned = true;
907 if (spelling_ref.consume_back_insensitive("ll"))
909 else if (spelling_ref.consume_back_insensitive("l"))
911 // Suffix 'u' can be only specified only once, before or after 'l'
912 if (!is_unsigned && spelling_ref.consume_back_insensitive("u"))
913 is_unsigned = true;
914
915 llvm::APInt raw_value;
916 if (!spelling_ref.getAsInteger(radix, raw_value))
917 return std::make_unique<IntegerLiteralNode>(token.GetLocation(), raw_value,
918 radix, is_unsigned, type);
919 return std::make_unique<ErrorNode>();
920}
921
923 Token token = CurToken();
924 auto spelling = token.GetSpelling();
925 llvm::StringRef spelling_ref = spelling;
926
927 llvm::APFloat raw_float(llvm::APFloat::IEEEdouble());
928 if (spelling_ref.consume_back_insensitive("f"))
929 raw_float = llvm::APFloat(llvm::APFloat::IEEEsingle());
930
931 auto StatusOrErr = raw_float.convertFromString(
932 spelling_ref, llvm::APFloat::rmNearestTiesToEven);
933 if (!errorToBool(StatusOrErr.takeError()))
934 return std::make_unique<FloatLiteralNode>(token.GetLocation(), raw_float);
935 return std::make_unique<ErrorNode>();
936}
937
939 if (CurToken().IsNot(kind)) {
940 BailOut(llvm::formatv("expected {0}, got: {1}", kind, CurToken()),
941 CurToken().GetLocation(), CurToken().GetSpelling().length());
942 }
943}
944
945void DILParser::ExpectOneOf(std::vector<Token::Kind> kinds_vec) {
946 if (!CurToken().IsOneOf(kinds_vec)) {
947 BailOut(llvm::formatv("expected any of ({0}), got: {1}",
948 llvm::iterator_range(kinds_vec), CurToken()),
949 CurToken().GetLocation(), CurToken().GetSpelling().length());
950 }
951}
952
953} // 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: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:70
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:103
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.