LLDB mainline
DILParser.cpp
Go to the documentation of this file.
1//===-- DILParser.cpp -----------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7// This implements the recursive descent parser for the Data Inspection
8// Language (DIL), and its helper functions, which will eventually underlie the
9// 'frame variable' command. The language that this parser recognizes is
10// described in lldb/docs/dil-expr-lang.ebnf
11//
12//===----------------------------------------------------------------------===//
13
21#include "llvm/ADT/StringRef.h"
22#include "llvm/Support/FormatAdapters.h"
23#include <cstdlib>
24#include <limits.h>
25#include <memory>
26#include <sstream>
27#include <string>
28
29namespace lldb_private::dil {
30
32 const std::string &message, uint32_t loc,
33 uint16_t err_len)
34 : ErrorInfo(make_error_code(std::errc::invalid_argument)) {
36 FileSpec{}, /*line=*/1, static_cast<uint16_t>(loc + 1),
37 err_len, false, /*in_user_input=*/true};
38 std::string rendered_msg =
39 llvm::formatv("<user expression 0>:1:{0}: {1}\n 1 | {2}\n | ^",
40 loc + 1, message, expr);
41 m_detail.source_location = sloc;
43 m_detail.message = message;
44 m_detail.rendered = std::move(rendered_msg);
45}
46
47llvm::Expected<ASTNodeUP>
48DILParser::Parse(llvm::StringRef dil_input_expr, DILLexer lexer,
49 std::shared_ptr<StackFrame> frame_sp,
50 lldb::DynamicValueType use_dynamic, bool use_synthetic,
51 bool fragile_ivar, bool check_ptr_vs_member) {
52 llvm::Error error = llvm::Error::success();
53 DILParser parser(dil_input_expr, lexer, frame_sp, use_dynamic, use_synthetic,
54 fragile_ivar, check_ptr_vs_member, error);
55
56 ASTNodeUP node_up = parser.Run();
57 assert(node_up && "ASTNodeUP must not contain a nullptr");
58
59 if (error)
60 return error;
61
62 return node_up;
63}
64
65DILParser::DILParser(llvm::StringRef dil_input_expr, DILLexer lexer,
66 std::shared_ptr<StackFrame> frame_sp,
67 lldb::DynamicValueType use_dynamic, bool use_synthetic,
68 bool fragile_ivar, bool check_ptr_vs_member,
69 llvm::Error &error)
70 : m_ctx_scope(frame_sp), m_input_expr(dil_input_expr),
71 m_dil_lexer(std::move(lexer)), m_error(error), m_use_dynamic(use_dynamic),
72 m_use_synthetic(use_synthetic), m_fragile_ivar(fragile_ivar),
73 m_check_ptr_vs_member(check_ptr_vs_member) {}
74
77
79
80 return expr;
81}
82
83// Parse an expression.
84//
85// expression:
86// cast_expression
87//
89
90// Parse a cast_expression.
91//
92// cast_expression:
93// unary_expression
94// "(" type_id ")" cast_expression
95
97 if (!CurToken().Is(Token::l_paren))
98 return ParseUnaryExpression();
99
100 // This could be a type cast, try parsing the contents as a type declaration.
101 Token token = CurToken();
102 uint32_t loc = token.GetLocation();
103
104 // Enable lexer backtracking, so that we can rollback in case it's not
105 // actually a type declaration.
106
107 // Start tentative parsing (save token location/idx, for possible rollback).
108 uint32_t save_token_idx = m_dil_lexer.GetCurrentTokenIdx();
109
110 // Consume the token only after enabling the backtracking.
111 m_dil_lexer.Advance();
112
113 // Try parsing the type declaration. If the returned value is not valid,
114 // then we should rollback and try parsing the expression.
115 auto type_id = ParseTypeId();
116 if (type_id) {
117 // Successfully parsed the type declaration. Commit the backtracked
118 // tokens and parse the cast_expression.
119
120 if (!type_id.value().IsValid())
121 return std::make_unique<ErrorNode>();
122
124 m_dil_lexer.Advance();
125 auto rhs = ParseCastExpression();
126 assert(rhs && "ASTNodeUP must not contain a nullptr");
127 return std::make_unique<CastNode>(loc, type_id.value(), std::move(rhs),
129 }
130
131 // Failed to parse the contents of the parentheses as a type declaration.
132 // Rollback the lexer and try parsing it as unary_expression.
133 TentativeParsingRollback(save_token_idx);
134
135 return ParseUnaryExpression();
136}
137
138// Parse an unary_expression.
139//
140// unary_expression:
141// postfix_expression
142// unary_operator cast_expression
143//
144// unary_operator:
145// "&"
146// "*"
147// "+"
148// "-"
149//
151 if (CurToken().IsOneOf(
153 Token token = CurToken();
154 uint32_t loc = token.GetLocation();
155 m_dil_lexer.Advance();
156 auto rhs = ParseCastExpression();
157 assert(rhs && "ASTNodeUP must not contain a nullptr");
158 switch (token.GetKind()) {
159 case Token::star:
160 return std::make_unique<UnaryOpNode>(loc, UnaryOpKind::Deref,
161 std::move(rhs));
162 case Token::amp:
163 return std::make_unique<UnaryOpNode>(loc, UnaryOpKind::AddrOf,
164 std::move(rhs));
165 case Token::minus:
166 return std::make_unique<UnaryOpNode>(loc, UnaryOpKind::Minus,
167 std::move(rhs));
168 case Token::plus:
169 return std::make_unique<UnaryOpNode>(loc, UnaryOpKind::Plus,
170 std::move(rhs));
171 default:
172 llvm_unreachable("invalid token kind");
173 }
174 }
175 return ParsePostfixExpression();
176}
177
178// Parse a postfix_expression.
179//
180// postfix_expression:
181// primary_expression
182// postfix_expression "[" expression "]"
183// postfix_expression "[" expression "-" expression "]"
184// postfix_expression "." id_expression
185// postfix_expression "->" id_expression
186//
189 assert(lhs && "ASTNodeUP must not contain a nullptr");
190 while (CurToken().IsOneOf({Token::l_square, Token::period, Token::arrow})) {
191 uint32_t loc = CurToken().GetLocation();
192 Token token = CurToken();
193 switch (token.GetKind()) {
194 case Token::l_square: {
195 m_dil_lexer.Advance();
196 ASTNodeUP index = ParseExpression();
197 assert(index && "ASTNodeUP must not contain a nullptr");
198 if (CurToken().GetKind() == Token::minus) {
199 m_dil_lexer.Advance();
200 ASTNodeUP last_index = ParseExpression();
201 assert(last_index && "ASTNodeUP must not contain a nullptr");
202 lhs = std::make_unique<BitFieldExtractionNode>(
203 loc, std::move(lhs), std::move(index), std::move(last_index));
204 } else {
205 lhs = std::make_unique<ArraySubscriptNode>(loc, std::move(lhs),
206 std::move(index));
207 }
209 m_dil_lexer.Advance();
210 break;
211 }
212 case Token::period:
213 case Token::arrow: {
214 m_dil_lexer.Advance();
215 Token member_token = CurToken();
216 std::string member_id = ParseIdExpression();
217 lhs = std::make_unique<MemberOfNode>(
218 member_token.GetLocation(), std::move(lhs),
219 token.GetKind() == Token::arrow, member_id);
220 break;
221 }
222 default:
223 llvm_unreachable("invalid token");
224 }
225 }
226
227 return lhs;
228}
229
230// Parse a primary_expression.
231//
232// primary_expression:
233// numeric_literal
234// boolean_literal
235// id_expression
236// "(" expression ")"
237//
240 return ParseNumericLiteral();
241 if (CurToken().IsOneOf({Token::kw_true, Token::kw_false}))
242 return ParseBooleanLiteral();
243 if (CurToken().IsOneOf(
245 // Save the source location for the diagnostics message.
246 uint32_t loc = CurToken().GetLocation();
247 std::string identifier = ParseIdExpression();
248
249 if (!identifier.empty())
250 return std::make_unique<IdentifierNode>(loc, identifier);
251 }
252
253 if (CurToken().Is(Token::l_paren)) {
254 m_dil_lexer.Advance();
255 auto expr = ParseExpression();
257 m_dil_lexer.Advance();
258 return expr;
259 }
260
261 BailOut(llvm::formatv("Unexpected token: {0}", CurToken()),
262 CurToken().GetLocation(), CurToken().GetSpelling().length());
263 return std::make_unique<ErrorNode>();
264}
265
266// Parse nested_name_specifier.
267//
268// nested_name_specifier:
269// type_name "::"
270// namespace_name "::"
271// nested_name_specifier identifier "::"
272//
274 // The first token in nested_name_specifier is always an identifier, or
275 // '(anonymous namespace)'.
276 switch (CurToken().GetKind()) {
277 case Token::l_paren: {
278 // Anonymous namespaces need to be treated specially: They are
279 // represented the the string '(anonymous namespace)', which has a
280 // space in it (throwing off normal parsing) and is not actually
281 // proper C++> Check to see if we're looking at
282 // '(anonymous namespace)::...'
283
284 // Look for all the pieces, in order:
285 // l_paren 'anonymous' 'namespace' r_paren coloncolon
286 if (m_dil_lexer.LookAhead(1).Is(Token::identifier) &&
287 (m_dil_lexer.LookAhead(1).GetSpelling() == "anonymous") &&
288 m_dil_lexer.LookAhead(2).Is(Token::identifier) &&
289 (m_dil_lexer.LookAhead(2).GetSpelling() == "namespace") &&
290 m_dil_lexer.LookAhead(3).Is(Token::r_paren) &&
291 m_dil_lexer.LookAhead(4).Is(Token::coloncolon)) {
292 m_dil_lexer.Advance(4);
293
295 m_dil_lexer.Advance();
296 if (!CurToken().Is(Token::identifier) && !CurToken().Is(Token::l_paren)) {
297 BailOut("Expected an identifier or anonymous namespace, but not found.",
298 CurToken().GetLocation(), CurToken().GetSpelling().length());
299 }
300 // Continue parsing the nested_namespace_specifier.
301 std::string identifier2 = ParseNestedNameSpecifier();
302
303 return "(anonymous namespace)::" + identifier2;
304 }
305
306 return "";
307 } // end of special handling for '(anonymous namespace)'
308 case Token::identifier: {
309 // If the next token is scope ("::"), then this is indeed a
310 // nested_name_specifier
311 if (m_dil_lexer.LookAhead(1).Is(Token::coloncolon)) {
312 // This nested_name_specifier is a single identifier.
313 std::string identifier = CurToken().GetSpelling();
314 m_dil_lexer.Advance(1);
316 m_dil_lexer.Advance();
317 // Continue parsing the nested_name_specifier.
318 return identifier + "::" + ParseNestedNameSpecifier();
319 }
320
321 return "";
322 }
323 default:
324 return "";
325 }
326}
327
328// Parse a type_id.
329//
330// type_id:
331// type_specifier_seq [abstract_declarator]
332//
333// type_specifier_seq:
334// type_specifier [type_specifier]
335//
336// type_specifier:
337// ["::"] [nested_name_specifier] type_name // not handled for now!
338// builtin_typename
339//
340std::optional<CompilerType> DILParser::ParseTypeId() {
341 CompilerType type;
342 // For now only allow builtin types -- will expand add to this later.
343 auto maybe_builtin_type = ParseBuiltinType();
344 if (maybe_builtin_type) {
345 type = *maybe_builtin_type;
346 } else
347 return {};
348
349 //
350 // abstract_declarator:
351 // ptr_operator [abstract_declarator]
352 //
353 std::vector<Token> ptr_operators;
354 while (CurToken().IsOneOf({Token::star, Token::amp})) {
355 Token tok = CurToken();
356 ptr_operators.push_back(std::move(tok));
357 m_dil_lexer.Advance();
358 }
359 type = ResolveTypeDeclarators(type, ptr_operators);
360
361 return type;
362}
363
364// Parse a built-in type
365//
366// builtin_typename:
367// identifer_seq
368//
369// identifier_seq
370// identifer [identifier_seq]
371//
372// A built-in type can be a single identifier or a space-separated
373// list of identifiers (e.g. "short" or "long long").
374std::optional<CompilerType> DILParser::ParseBuiltinType() {
375 std::string type_name = "";
376 uint32_t save_token_idx = m_dil_lexer.GetCurrentTokenIdx();
377 bool first_word = true;
378 while (CurToken().GetKind() == Token::identifier) {
379 if (CurToken().GetSpelling() == "const" ||
380 CurToken().GetSpelling() == "volatile")
381 continue;
382 if (!first_word)
383 type_name.push_back(' ');
384 else
385 first_word = false;
386 type_name.append(CurToken().GetSpelling());
387 m_dil_lexer.Advance();
388 }
389
390 if (type_name.size() > 0) {
391 lldb::TargetSP target_sp = m_ctx_scope->CalculateTarget();
392 ConstString const_type_name(type_name.c_str());
393 for (auto type_system_sp : target_sp->GetScratchTypeSystems())
394 if (auto compiler_type =
395 type_system_sp->GetBuiltinTypeByName(const_type_name))
396 return compiler_type;
397 }
398
399 TentativeParsingRollback(save_token_idx);
400 return {};
401}
402
403// Parse an id_expression.
404//
405// id_expression:
406// unqualified_id
407// qualified_id
408//
409// qualified_id:
410// ["::"] [nested_name_specifier] unqualified_id
411// ["::"] identifier
412//
413// identifier:
414// ? Token::identifier ?
415//
417 // Try parsing optional global scope operator.
418 bool global_scope = false;
419 if (CurToken().Is(Token::coloncolon)) {
420 global_scope = true;
421 m_dil_lexer.Advance();
422 }
423
424 // Try parsing optional nested_name_specifier.
425 std::string nested_name_specifier = ParseNestedNameSpecifier();
426
427 // If nested_name_specifier is present, then it's qualified_id production.
428 // Follow the first production rule.
429 if (!nested_name_specifier.empty()) {
430 // Parse unqualified_id and construct a fully qualified id expression.
431 auto unqualified_id = ParseUnqualifiedId();
432
433 return llvm::formatv("{0}{1}{2}", global_scope ? "::" : "",
434 nested_name_specifier, unqualified_id);
435 }
436
437 if (!CurToken().Is(Token::identifier))
438 return "";
439
440 // No nested_name_specifier, but with global scope -- this is also a
441 // qualified_id production. Follow the second production rule.
442 if (global_scope) {
444 std::string identifier = CurToken().GetSpelling();
445 m_dil_lexer.Advance();
446 return llvm::formatv("{0}{1}", global_scope ? "::" : "", identifier);
447 }
448
449 // This is unqualified_id production.
450 return ParseUnqualifiedId();
451}
452
453// Parse an unqualified_id.
454//
455// unqualified_id:
456// identifier
457//
458// identifier:
459// ? Token::identifier ?
460//
463 std::string identifier = CurToken().GetSpelling();
464 m_dil_lexer.Advance();
465 return identifier;
466}
467
470 const std::vector<Token> &ptr_operators) {
471 // Resolve pointers/references.
472 for (Token tk : ptr_operators) {
473 uint32_t loc = tk.GetLocation();
474 if (tk.GetKind() == Token::star) {
475 // Pointers to reference types are forbidden.
476 if (type.IsReferenceType()) {
477 BailOut(llvm::formatv("'type name' declared as a pointer to a "
478 "reference of type {0}",
479 type.TypeDescription()),
480 loc, CurToken().GetSpelling().length());
481 return {};
482 }
483 // Get pointer type for the base type: e.g. int* -> int**.
484 type = type.GetPointerType();
485
486 } else if (tk.GetKind() == Token::amp) {
487 // References to references are forbidden.
488 // FIXME: In future we may want to allow rvalue references (i.e. &&).
489 if (type.IsReferenceType()) {
490 BailOut("type name declared as a reference to a reference", loc,
491 CurToken().GetSpelling().length());
492 return {};
493 }
494 // Get reference type for the base type: e.g. int -> int&.
495 type = type.GetLValueReferenceType();
496 }
497 }
498
499 return type;
500}
501
502// Parse an boolean_literal.
503//
504// boolean_literal:
505// "true"
506// "false"
507//
509 ExpectOneOf(std::vector<Token::Kind>{Token::kw_true, Token::kw_false});
510 uint32_t loc = CurToken().GetLocation();
511 bool literal_value = CurToken().Is(Token::kw_true);
512 m_dil_lexer.Advance();
513 return std::make_unique<BooleanLiteralNode>(loc, literal_value);
514}
515
516void DILParser::BailOut(const std::string &error, uint32_t loc,
517 uint16_t err_len) {
518 if (m_error)
519 // If error is already set, then the parser is in the "bail-out" mode. Don't
520 // do anything and keep the original error.
521 return;
522
523 m_error =
524 llvm::make_error<DILDiagnosticError>(m_input_expr, error, loc, err_len);
525 // Advance the lexer token index to the end of the lexed tokens vector.
526 m_dil_lexer.ResetTokenIdx(m_dil_lexer.NumLexedTokens() - 1);
527}
528
529// Parse a numeric_literal.
530//
531// numeric_literal:
532// ? Token::integer_constant ?
533// ? Token::floating_constant ?
534//
536 ASTNodeUP numeric_constant;
538 numeric_constant = ParseIntegerLiteral();
539 else
540 numeric_constant = ParseFloatingPointLiteral();
541 if (numeric_constant->GetKind() == NodeKind::eErrorNode) {
542 BailOut(llvm::formatv("Failed to parse token as numeric-constant: {0}",
543 CurToken()),
544 CurToken().GetLocation(), CurToken().GetSpelling().length());
545 return numeric_constant;
546 }
547 m_dil_lexer.Advance();
548 return numeric_constant;
549}
550
552 Token token = CurToken();
553 auto spelling = token.GetSpelling();
554 llvm::StringRef spelling_ref = spelling;
555
556 auto radix = llvm::getAutoSenseRadix(spelling_ref);
558 bool is_unsigned = false;
559 if (spelling_ref.consume_back_insensitive("u"))
560 is_unsigned = true;
561 if (spelling_ref.consume_back_insensitive("ll"))
563 else if (spelling_ref.consume_back_insensitive("l"))
565 // Suffix 'u' can be only specified only once, before or after 'l'
566 if (!is_unsigned && spelling_ref.consume_back_insensitive("u"))
567 is_unsigned = true;
568
569 llvm::APInt raw_value;
570 if (!spelling_ref.getAsInteger(radix, raw_value))
571 return std::make_unique<IntegerLiteralNode>(token.GetLocation(), raw_value,
572 radix, is_unsigned, type);
573 return std::make_unique<ErrorNode>();
574}
575
577 Token token = CurToken();
578 auto spelling = token.GetSpelling();
579 llvm::StringRef spelling_ref = spelling;
580
581 llvm::APFloat raw_float(llvm::APFloat::IEEEdouble());
582 if (spelling_ref.consume_back_insensitive("f"))
583 raw_float = llvm::APFloat(llvm::APFloat::IEEEsingle());
584
585 auto StatusOrErr = raw_float.convertFromString(
586 spelling_ref, llvm::APFloat::rmNearestTiesToEven);
587 if (!errorToBool(StatusOrErr.takeError()))
588 return std::make_unique<FloatLiteralNode>(token.GetLocation(), raw_float);
589 return std::make_unique<ErrorNode>();
590}
591
593 if (CurToken().IsNot(kind)) {
594 BailOut(llvm::formatv("expected {0}, got: {1}", kind, CurToken()),
595 CurToken().GetLocation(), CurToken().GetSpelling().length());
596 }
597}
598
599void DILParser::ExpectOneOf(std::vector<Token::Kind> kinds_vec) {
600 if (!CurToken().IsOneOf(kinds_vec)) {
601 BailOut(llvm::formatv("expected any of ({0}), got: {1}",
602 llvm::iterator_range(kinds_vec), CurToken()),
603 CurToken().GetLocation(), CurToken().GetSpelling().length());
604 }
605}
606
607} // 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...
bool IsReferenceType(CompilerType *pointee_type=nullptr, bool *is_rvalue=nullptr) const
A uniqued constant string class.
Definition ConstString.h:40
A file utility class.
Definition FileSpec.h:57
DILDiagnosticError(DiagnosticDetail detail)
Definition DILParser.h:41
std::string message() const override
Definition DILParser.h:56
Class for doing the simple lexing required by DIL.
Definition DILLexer.h:72
void Expect(Token::Kind kind)
static llvm::Expected< ASTNodeUP > Parse(llvm::StringRef dil_input_expr, DILLexer lexer, std::shared_ptr< StackFrame > frame_sp, lldb::DynamicValueType use_dynamic, bool use_synthetic, bool fragile_ivar, bool check_ptr_vs_member)
Definition DILParser.cpp:48
std::optional< CompilerType > ParseTypeId()
void TentativeParsingRollback(uint32_t saved_idx)
Definition DILParser.h:115
ASTNodeUP ParseFloatingPointLiteral()
DILParser(llvm::StringRef dil_input_expr, DILLexer lexer, std::shared_ptr< StackFrame > frame_sp, lldb::DynamicValueType use_dynamic, bool use_synthetic, bool fragile_ivar, bool check_ptr_vs_member, llvm::Error &error)
Definition DILParser.cpp:65
void ExpectOneOf(std::vector< Token::Kind > kinds_vec)
std::optional< CompilerType > ParseBuiltinType()
std::shared_ptr< StackFrame > m_ctx_scope
Definition DILParser.h:126
void BailOut(const std::string &error, uint32_t loc, uint16_t err_len)
CompilerType ResolveTypeDeclarators(CompilerType type, const std::vector< Token > &ptr_operators)
lldb::DynamicValueType m_use_dynamic
Definition DILParser.h:135
llvm::StringRef m_input_expr
Definition DILParser.h:128
std::string ParseNestedNameSpecifier()
Class defining the tokens generated by the DIL lexer and used by the DIL parser.
Definition DILLexer.h:24
bool Is(Kind kind) const
Definition DILLexer.h:53
uint32_t GetLocation() const
Definition DILLexer.h:61
Kind GetKind() const
Definition DILLexer.h:49
std::string GetSpelling() const
Definition DILLexer.h:51
@ eNone
Invalid promotion type (results in error).
Definition DILAST.h:46
std::unique_ptr< ASTNode > ASTNodeUP
Definition DILAST.h:79
std::shared_ptr< lldb_private::Target > TargetSP
A source location consisting of a file name and position.