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
62static CompilerType 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 std::shared_ptr<StackFrame> frame_sp,
96 lldb::DynamicValueType use_dynamic,
97 lldb::DILMode mode) {
98 llvm::Error error = llvm::Error::success();
99 DILParser parser(dil_input_expr, lexer, frame_sp, use_dynamic, error, mode);
100
101 ASTNodeUP node_up = parser.Run();
102 assert(node_up && "ASTNodeUP must not contain a nullptr");
103
104 if (error)
105 return error;
106
107 return node_up;
108}
109
110DILParser::DILParser(llvm::StringRef dil_input_expr, DILLexer lexer,
111 std::shared_ptr<StackFrame> frame_sp,
112 lldb::DynamicValueType use_dynamic, llvm::Error &error,
113 lldb::DILMode mode)
114 : m_ctx_scope(frame_sp), m_input_expr(dil_input_expr),
115 m_dil_lexer(std::move(lexer)), m_error(error), m_use_dynamic(use_dynamic),
116 m_mode(mode) {}
117
119 ASTNodeUP expr = ParseExpression();
120
122
123 return expr;
124}
125
126// Parse an expression.
127//
128// expression:
129// cast_expression
130//
132
133// Parse an additive_expression.
134//
135// additive_expression:
136// multiplicative_expression {"+" multiplicative_expression}
137//
140 assert(lhs && "ASTNodeUP must not contain a nullptr");
141
142 while (CurToken().IsOneOf({Token::plus, Token::minus})) {
143 Token token = CurToken();
144 m_dil_lexer.Advance();
146 assert(rhs && "ASTNodeUP must not contain a nullptr");
147 lhs = std::make_unique<BinaryOpNode>(
149 std::move(lhs), std::move(rhs));
150 }
151
152 return lhs;
153}
154
155// Parse a multiplicative_expression.
156//
157// multiplicative_expression:
158// cast_expression {"*" cast_expression}
159// cast_expression {"/" cast_expression}
160// cast_expression {"%" cast_expression}
161//
163 auto lhs = ParseCastExpression();
164
165 while (CurToken().IsOneOf({Token::star, Token::slash, Token::percent})) {
166 Token token = CurToken();
167 if (token.Is(Token::star) && m_mode != lldb::eDILModeFull) {
168 BailOut("binary multiplication (*) is allowed only in DIL full mode",
169 token.GetLocation(), token.GetSpelling().length());
170 return std::make_unique<ErrorNode>();
171 }
172 m_dil_lexer.Advance();
173 auto rhs = ParseCastExpression();
174 assert(rhs && "ASTNodeUP must not contain a nullptr");
175 lhs = std::make_unique<BinaryOpNode>(
177 std::move(lhs), std::move(rhs));
178 }
179
180 return lhs;
181}
182
183// Parse a cast_expression.
184//
185// cast_expression:
186// unary_expression
187// "(" type_id ")" cast_expression
188
190 if (!CurToken().Is(Token::l_paren))
191 return ParseUnaryExpression();
192
193 // This could be a type cast, try parsing the contents as a type declaration.
194 Token token = CurToken();
195 uint32_t loc = token.GetLocation();
196
197 // Enable lexer backtracking, so that we can rollback in case it's not
198 // actually a type declaration.
199
200 // Start tentative parsing (save token location/idx, for possible rollback).
201 uint32_t save_token_idx = m_dil_lexer.GetCurrentTokenIdx();
202
203 // Consume the token only after enabling the backtracking.
204 m_dil_lexer.Advance();
205
206 // Try parsing the type declaration. If the returned value is not valid,
207 // then we should rollback and try parsing the expression.
208 auto type_id = ParseTypeId();
209 if (type_id) {
210 // Successfully parsed the type declaration. Commit the backtracked
211 // tokens and parse the cast_expression.
212
213 if (!type_id.value().IsValid())
214 return std::make_unique<ErrorNode>();
215
217 m_dil_lexer.Advance();
218 auto rhs = ParseCastExpression();
219 assert(rhs && "ASTNodeUP must not contain a nullptr");
220 return std::make_unique<CastNode>(loc, type_id.value(), std::move(rhs),
222 }
223
224 // Failed to parse the contents of the parentheses as a type declaration.
225 // Rollback the lexer and try parsing it as unary_expression.
226 TentativeParsingRollback(save_token_idx);
227
228 return ParseUnaryExpression();
229}
230
231// Parse an unary_expression.
232//
233// unary_expression:
234// postfix_expression
235// unary_operator cast_expression
236//
237// unary_operator:
238// "&"
239// "*"
240// "+"
241// "-"
242//
244 if (CurToken().IsOneOf(
246 Token token = CurToken();
247 uint32_t loc = token.GetLocation();
248 m_dil_lexer.Advance();
249 auto rhs = ParseCastExpression();
250 assert(rhs && "ASTNodeUP must not contain a nullptr");
251 switch (token.GetKind()) {
252 case Token::star:
253 return std::make_unique<UnaryOpNode>(loc, UnaryOpKind::Deref,
254 std::move(rhs));
255 case Token::amp:
256 return std::make_unique<UnaryOpNode>(loc, UnaryOpKind::AddrOf,
257 std::move(rhs));
258 case Token::minus:
259 return std::make_unique<UnaryOpNode>(loc, UnaryOpKind::Minus,
260 std::move(rhs));
261 case Token::plus:
262 return std::make_unique<UnaryOpNode>(loc, UnaryOpKind::Plus,
263 std::move(rhs));
264 default:
265 llvm_unreachable("invalid token kind");
266 }
267 }
268 return ParsePostfixExpression();
269}
270
271// Parse a postfix_expression.
272//
273// postfix_expression:
274// primary_expression
275// postfix_expression "[" expression "]"
276// postfix_expression "[" expression ":" expression "]"
277// postfix_expression "." id_expression
278// postfix_expression "->" id_expression
279//
282 assert(lhs && "ASTNodeUP must not contain a nullptr");
283 while (CurToken().IsOneOf({Token::l_square, Token::period, Token::arrow})) {
284 uint32_t loc = CurToken().GetLocation();
285 Token token = CurToken();
286 switch (token.GetKind()) {
287 case Token::l_square: {
288 m_dil_lexer.Advance();
289 ASTNodeUP index = ParseExpression();
290 assert(index && "ASTNodeUP must not contain a nullptr");
291 if (CurToken().GetKind() == Token::colon) {
292 m_dil_lexer.Advance();
293 ASTNodeUP last_index = ParseExpression();
294 assert(last_index && "ASTNodeUP must not contain a nullptr");
295 lhs = std::make_unique<BitFieldExtractionNode>(
296 loc, std::move(lhs), std::move(index), std::move(last_index));
297 } else if (CurToken().GetKind() == Token::minus) {
298 BailOut("use of '-' for bitfield range is deprecated; use ':' instead",
299 CurToken().GetLocation(), CurToken().GetSpelling().length());
300 return std::make_unique<ErrorNode>();
301 } else {
302 lhs = std::make_unique<ArraySubscriptNode>(loc, std::move(lhs),
303 std::move(index));
304 }
306 m_dil_lexer.Advance();
307 break;
308 }
309 case Token::period:
310 case Token::arrow: {
311 m_dil_lexer.Advance();
312 Token member_token = CurToken();
313 std::string member_id = ParseIdExpression();
314 lhs = std::make_unique<MemberOfNode>(
315 member_token.GetLocation(), std::move(lhs),
316 token.GetKind() == Token::arrow, member_id);
317 break;
318 }
319 default:
320 llvm_unreachable("invalid token");
321 }
322 }
323
324 return lhs;
325}
326
327// Parse a primary_expression.
328//
329// primary_expression:
330// numeric_literal
331// boolean_literal
332// id_expression
333// "(" expression ")"
334//
337 return ParseNumericLiteral();
338 if (CurToken().IsOneOf({Token::kw_true, Token::kw_false}))
339 return ParseBooleanLiteral();
340 if (CurToken().IsOneOf(
342 // Save the source location for the diagnostics message.
343 uint32_t loc = CurToken().GetLocation();
344 std::string identifier = ParseIdExpression();
345
346 if (!identifier.empty())
347 return std::make_unique<IdentifierNode>(loc, identifier);
348 }
349
350 if (CurToken().Is(Token::l_paren)) {
351 m_dil_lexer.Advance();
352 auto expr = ParseExpression();
354 m_dil_lexer.Advance();
355 return expr;
356 }
357
358 BailOut(llvm::formatv("Unexpected token: {0}", CurToken()),
359 CurToken().GetLocation(), CurToken().GetSpelling().length());
360 return std::make_unique<ErrorNode>();
361}
362
363// Parse nested_name_specifier.
364//
365// nested_name_specifier:
366// type_name "::"
367// namespace_name "::"
368// nested_name_specifier identifier "::"
369//
371 // The first token in nested_name_specifier is always an identifier, or
372 // '(anonymous namespace)'.
373 switch (CurToken().GetKind()) {
374 case Token::l_paren: {
375 // Anonymous namespaces need to be treated specially: They are
376 // represented the the string '(anonymous namespace)', which has a
377 // space in it (throwing off normal parsing) and is not actually
378 // proper C++> Check to see if we're looking at
379 // '(anonymous namespace)::...'
380
381 // Look for all the pieces, in order:
382 // l_paren 'anonymous' 'namespace' r_paren coloncolon
383 if (m_dil_lexer.LookAhead(1).Is(Token::identifier) &&
384 (m_dil_lexer.LookAhead(1).GetSpelling() == "anonymous") &&
385 m_dil_lexer.LookAhead(2).Is(Token::identifier) &&
386 (m_dil_lexer.LookAhead(2).GetSpelling() == "namespace") &&
387 m_dil_lexer.LookAhead(3).Is(Token::r_paren) &&
388 m_dil_lexer.LookAhead(4).Is(Token::coloncolon)) {
389 m_dil_lexer.Advance(4);
390
392 m_dil_lexer.Advance();
393 if (!CurToken().Is(Token::identifier) && !CurToken().Is(Token::l_paren)) {
394 BailOut("Expected an identifier or anonymous namespace, but not found.",
395 CurToken().GetLocation(), CurToken().GetSpelling().length());
396 }
397 // Continue parsing the nested_namespace_specifier.
398 std::string identifier2 = ParseNestedNameSpecifier();
399
400 return "(anonymous namespace)::" + identifier2;
401 }
402
403 return "";
404 } // end of special handling for '(anonymous namespace)'
405 case Token::identifier: {
406 // If the next token is scope ("::"), then this is indeed a
407 // nested_name_specifier
408 if (m_dil_lexer.LookAhead(1).Is(Token::coloncolon)) {
409 // This nested_name_specifier is a single identifier.
410 std::string identifier = CurToken().GetSpelling();
411 m_dil_lexer.Advance(1);
413 m_dil_lexer.Advance();
414 // Continue parsing the nested_name_specifier.
415 return identifier + "::" + ParseNestedNameSpecifier();
416 }
417
418 return "";
419 }
420 default:
421 return "";
422 }
423}
424
425// Parse a type_id.
426//
427// type_id:
428// type_specifier_seq [abstract_declarator]
429//
430// type_specifier_seq:
431// type_specifier [type_specifier]
432//
433// type_specifier:
434// ["::"] [nested_name_specifier] type_name // not handled for now!
435// builtin_typename
436//
437std::optional<CompilerType> DILParser::ParseTypeId() {
438 CompilerType type;
439 auto maybe_builtin_type = ParseBuiltinType();
440 if (maybe_builtin_type) {
441 type = *maybe_builtin_type;
442 } else {
443 // Check to see if we have a user-defined type here.
444 // First build up the user-defined type name.
445 std::string type_name;
446 ParseTypeSpecifierSeq(type_name);
447
448 if (type_name.empty())
449 return {};
450 type = ResolveTypeByName(type_name, *m_ctx_scope);
451 if (!type.IsValid())
452 return {};
453
454 // Same-name identifiers should be preferred over typenames.
456 // TODO: Make type accessible with 'class', 'struct' and 'union' keywords.
457 return {};
458
459 // Same-name identifiers should be preferred over typenames.
460 if (LookupGlobalIdentifier(type_name, m_ctx_scope,
461 m_ctx_scope->CalculateTarget(), m_use_dynamic))
462 // TODO: Make type accessible with 'class', 'struct' and 'union' keywords
463 return {};
464 }
465
466 //
467 // abstract_declarator:
468 // ptr_operator [abstract_declarator]
469 //
470 std::vector<Token> ptr_operators;
471 while (CurToken().IsOneOf({Token::star, Token::amp})) {
472 Token tok = CurToken();
473 ptr_operators.push_back(std::move(tok));
474 m_dil_lexer.Advance();
475 }
476 type = ResolveTypeDeclarators(type, ptr_operators);
477
478 return type;
479}
480
481// Parse a built-in type
482//
483// builtin_typename:
484// identifer_seq
485//
486// identifier_seq
487// identifer [identifier_seq]
488//
489// A built-in type can be a single identifier or a space-separated
490// list of identifiers (e.g. "short" or "long long").
491std::optional<CompilerType> DILParser::ParseBuiltinType() {
492 std::string type_name = "";
493 uint32_t save_token_idx = m_dil_lexer.GetCurrentTokenIdx();
494 bool first_word = true;
495 while (CurToken().GetKind() == Token::identifier) {
496 if (CurToken().GetSpelling() == "const" ||
497 CurToken().GetSpelling() == "volatile")
498 continue;
499 if (!first_word)
500 type_name.push_back(' ');
501 else
502 first_word = false;
503 type_name.append(CurToken().GetSpelling());
504 m_dil_lexer.Advance();
505 }
506
507 if (type_name.size() > 0) {
508 lldb::TargetSP target_sp = m_ctx_scope->CalculateTarget();
509 ConstString const_type_name(type_name.c_str());
510 for (auto type_system_sp : target_sp->GetScratchTypeSystems())
511 if (auto compiler_type =
512 type_system_sp->GetBuiltinTypeByName(const_type_name))
513 return compiler_type;
514 }
515
516 TentativeParsingRollback(save_token_idx);
517 return {};
518}
519
520// Parse a type_specifier_seq.
521//
522// type_specifier_seq:
523// type_specifier [type_specifier_seq]
524//
525void DILParser::ParseTypeSpecifierSeq(std::string &type_name) {
526 while (true) {
527 std::optional<std::string> err_or_string = ParseTypeSpecifier();
528 if (!err_or_string)
529 break;
530 type_name = *err_or_string;
531 }
532}
533
534// Parse a type_specifier.
535//
536// type_specifier:
537// ["::"] [nested_name_specifier] type_name
538//
539// Returns TRUE if a type_specifier was successfully parsed at this location.
540//
541std::optional<std::string> DILParser::ParseTypeSpecifier() {
542 // The type_specifier must be a user-defined type. Try parsing a
543 // simple_type_specifier.
544
545 // Try parsing optional global scope operator.
546 bool global_scope = false;
547 if (CurToken().Is(Token::coloncolon)) {
548 global_scope = true;
549 m_dil_lexer.Advance();
550 }
551
552 // Try parsing optional nested_name_specifier.
553 auto nested_name_specifier = ParseNestedNameSpecifier();
554
555 // Try parsing required type_name.
556 auto type_name_or_err = ParseTypeName();
557 if (!type_name_or_err)
558 return type_name_or_err;
559 std::string type_name = *type_name_or_err;
560
561 // If there is a type_name, then this is indeed a simple_type_specifier.
562 // Global and qualified (namespace/class) scopes can be empty, since they're
563 // optional. In this case type_name is type we're looking for.
564 if (!type_name.empty())
565 // User-defined typenames can't be combined with builtin keywords.
566 return llvm::formatv("{0}{1}{2}", global_scope ? "::" : "",
567 nested_name_specifier, type_name);
568
569 // No type_specifier was found here.
570 return {};
571}
572
573// Parse a type_name.
574//
575// type_name:
576// class_name
577// enum_name
578// typedef_name
579//
580// class_name
581// identifier
582//
583// enum_name
584// identifier
585//
586// typedef_name
587// identifier
588//
589std::optional<std::string> DILParser::ParseTypeName() {
590 // Typename always starts with an identifier.
591 if (CurToken().IsNot(Token::identifier)) {
592 return std::nullopt;
593 }
594
595 // Otherwise look for a class_name, enum_name or a typedef_name.
596 std::string identifier = CurToken().GetSpelling();
597 m_dil_lexer.Advance();
598
599 return identifier;
600}
601
602// Parse an id_expression.
603//
604// id_expression:
605// unqualified_id
606// qualified_id
607//
608// qualified_id:
609// ["::"] [nested_name_specifier] unqualified_id
610// ["::"] identifier
611//
612// identifier:
613// ? Token::identifier ?
614//
616 // Try parsing optional global scope operator.
617 bool global_scope = false;
618 if (CurToken().Is(Token::coloncolon)) {
619 global_scope = true;
620 m_dil_lexer.Advance();
621 }
622
623 // Try parsing optional nested_name_specifier.
624 std::string nested_name_specifier = ParseNestedNameSpecifier();
625
626 // If nested_name_specifier is present, then it's qualified_id production.
627 // Follow the first production rule.
628 if (!nested_name_specifier.empty()) {
629 // Parse unqualified_id and construct a fully qualified id expression.
630 auto unqualified_id = ParseUnqualifiedId();
631
632 return llvm::formatv("{0}{1}{2}", global_scope ? "::" : "",
633 nested_name_specifier, unqualified_id);
634 }
635
636 if (!CurToken().Is(Token::identifier))
637 return "";
638
639 // No nested_name_specifier, but with global scope -- this is also a
640 // qualified_id production. Follow the second production rule.
641 if (global_scope) {
643 std::string identifier = CurToken().GetSpelling();
644 m_dil_lexer.Advance();
645 return llvm::formatv("{0}{1}", global_scope ? "::" : "", identifier);
646 }
647
648 // This is unqualified_id production.
649 return ParseUnqualifiedId();
650}
651
652// Parse an unqualified_id.
653//
654// unqualified_id:
655// identifier
656//
657// identifier:
658// ? Token::identifier ?
659//
662 std::string identifier = CurToken().GetSpelling();
663 m_dil_lexer.Advance();
664 return identifier;
665}
666
669 const std::vector<Token> &ptr_operators) {
670 // Resolve pointers/references.
671 for (Token tk : ptr_operators) {
672 uint32_t loc = tk.GetLocation();
673 if (tk.GetKind() == Token::star) {
674 // Pointers to reference types are forbidden.
675 if (type.IsReferenceType()) {
676 BailOut(llvm::formatv("'type name' declared as a pointer to a "
677 "reference of type {0}",
678 type.TypeDescription()),
679 loc, CurToken().GetSpelling().length());
680 return {};
681 }
682 // Get pointer type for the base type: e.g. int* -> int**.
683 type = type.GetPointerType();
684
685 } else if (tk.GetKind() == Token::amp) {
686 // References to references are forbidden.
687 // FIXME: In future we may want to allow rvalue references (i.e. &&).
688 if (type.IsReferenceType()) {
689 BailOut("type name declared as a reference to a reference", loc,
690 CurToken().GetSpelling().length());
691 return {};
692 }
693 // Get reference type for the base type: e.g. int -> int&.
694 type = type.GetLValueReferenceType();
695 }
696 }
697
698 return type;
699}
700
701// Parse an boolean_literal.
702//
703// boolean_literal:
704// "true"
705// "false"
706//
708 ExpectOneOf(std::vector<Token::Kind>{Token::kw_true, Token::kw_false});
709 uint32_t loc = CurToken().GetLocation();
710 bool literal_value = CurToken().Is(Token::kw_true);
711 m_dil_lexer.Advance();
712 return std::make_unique<BooleanLiteralNode>(loc, literal_value);
713}
714
715void DILParser::BailOut(const std::string &error, uint32_t loc,
716 uint16_t err_len) {
717 if (m_error)
718 // If error is already set, then the parser is in the "bail-out" mode. Don't
719 // do anything and keep the original error.
720 return;
721
722 m_error =
723 llvm::make_error<DILDiagnosticError>(m_input_expr, error, loc, err_len);
724 // Advance the lexer token index to the end of the lexed tokens vector.
725 m_dil_lexer.ResetTokenIdx(m_dil_lexer.NumLexedTokens() - 1);
726}
727
728// Parse a numeric_literal.
729//
730// numeric_literal:
731// ? Token::integer_constant ?
732// ? Token::floating_constant ?
733//
735 ASTNodeUP numeric_constant;
737 numeric_constant = ParseIntegerLiteral();
738 else
739 numeric_constant = ParseFloatingPointLiteral();
740 if (numeric_constant->GetKind() == NodeKind::eErrorNode) {
741 BailOut(llvm::formatv("Failed to parse token as numeric-constant: {0}",
742 CurToken()),
743 CurToken().GetLocation(), CurToken().GetSpelling().length());
744 return numeric_constant;
745 }
746 m_dil_lexer.Advance();
747 return numeric_constant;
748}
749
751 Token token = CurToken();
752 auto spelling = token.GetSpelling();
753 llvm::StringRef spelling_ref = spelling;
754
755 auto radix = llvm::getAutoSenseRadix(spelling_ref);
757 bool is_unsigned = false;
758 if (spelling_ref.consume_back_insensitive("u"))
759 is_unsigned = true;
760 if (spelling_ref.consume_back_insensitive("ll"))
762 else if (spelling_ref.consume_back_insensitive("l"))
764 // Suffix 'u' can be only specified only once, before or after 'l'
765 if (!is_unsigned && spelling_ref.consume_back_insensitive("u"))
766 is_unsigned = true;
767
768 llvm::APInt raw_value;
769 if (!spelling_ref.getAsInteger(radix, raw_value))
770 return std::make_unique<IntegerLiteralNode>(token.GetLocation(), raw_value,
771 radix, is_unsigned, type);
772 return std::make_unique<ErrorNode>();
773}
774
776 Token token = CurToken();
777 auto spelling = token.GetSpelling();
778 llvm::StringRef spelling_ref = spelling;
779
780 llvm::APFloat raw_float(llvm::APFloat::IEEEdouble());
781 if (spelling_ref.consume_back_insensitive("f"))
782 raw_float = llvm::APFloat(llvm::APFloat::IEEEsingle());
783
784 auto StatusOrErr = raw_float.convertFromString(
785 spelling_ref, llvm::APFloat::rmNearestTiesToEven);
786 if (!errorToBool(StatusOrErr.takeError()))
787 return std::make_unique<FloatLiteralNode>(token.GetLocation(), raw_float);
788 return std::make_unique<ErrorNode>();
789}
790
792 if (CurToken().IsNot(kind)) {
793 BailOut(llvm::formatv("expected {0}, got: {1}", kind, CurToken()),
794 CurToken().GetLocation(), CurToken().GetSpelling().length());
795 }
796}
797
798void DILParser::ExpectOneOf(std::vector<Token::Kind> kinds_vec) {
799 if (!CurToken().IsOneOf(kinds_vec)) {
800 BailOut(llvm::formatv("expected any of ({0}), got: {1}",
801 llvm::iterator_range(kinds_vec), CurToken()),
802 CurToken().GetLocation(), CurToken().GetSpelling().length());
803 }
804}
805
806} // 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.
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:45
std::string message() const override
Definition DILParser.h:60
Class for doing the simple lexing required by DIL.
Definition DILLexer.h:76
void ParseTypeSpecifierSeq(std::string &type_name)
void Expect(Token::Kind kind)
std::optional< CompilerType > ParseTypeId()
void TentativeParsingRollback(uint32_t saved_idx)
Definition DILParser.h:114
ASTNodeUP ParseFloatingPointLiteral()
void ExpectOneOf(std::vector< Token::Kind > kinds_vec)
std::optional< std::string > ParseTypeSpecifier()
std::optional< CompilerType > ParseBuiltinType()
std::shared_ptr< StackFrame > m_ctx_scope
Definition DILParser.h:125
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:134
DILParser(llvm::StringRef dil_input_expr, DILLexer lexer, std::shared_ptr< StackFrame > frame_sp, lldb::DynamicValueType use_dynamic, llvm::Error &error, lldb::DILMode mode)
static llvm::Expected< ASTNodeUP > Parse(llvm::StringRef dil_input_expr, DILLexer lexer, std::shared_ptr< StackFrame > frame_sp, lldb::DynamicValueType use_dynamic, lldb::DILMode mode)
Definition DILParser.cpp:93
std::optional< std::string > ParseTypeName()
llvm::StringRef m_input_expr
Definition DILParser.h:127
std::string ParseNestedNameSpecifier()
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:57
uint32_t GetLocation() const
Definition DILLexer.h:65
Kind GetKind() const
Definition DILLexer.h:53
std::string GetSpelling() const
Definition DILLexer.h:55
@ eNone
Invalid promotion type (results in error).
Definition DILAST.h:60
static CompilerType ResolveTypeByName(const std::string &name, ExecutionContextScope &ctx_scope)
Definition DILParser.cpp:62
std::unique_ptr< ASTNode > ASTNodeUP
Definition DILAST.h:93
BinaryOpKind GetBinaryOpKindFromToken(Token::Kind token_kind)
Translates DIL tokens to BinaryOpKind.
Definition DILAST.cpp:14
lldb::ValueObjectSP LookupGlobalIdentifier(llvm::StringRef name_ref, std::shared_ptr< StackFrame > frame_sp, 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:282
lldb::ValueObjectSP LookupIdentifier(llvm::StringRef name_ref, std::shared_ptr< StackFrame > frame_sp, lldb::DynamicValueType use_dynamic)
Given the name of an identifier (variable name, member name, type name, etc.), find the ValueObject f...
Definition DILEval.cpp:323
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.