Skip to content

Commit 728cada

Browse files
authored
[LLDB] Add type casting to DIL, part 1 of 3. (llvm#165199)
This is an alternative to llvm#159500, breaking that PR down into three separate PRs, to make it easier to review. This first PR of the three adds the basic framework for doing type casing to the DIL code, but it does not actually do any casting: In this PR the DIL parser only recognizes builtin type names, and the DIL interpreter does not do anything except return the original operand (no casting). The second and third PRs will add most of the type parsing, and do the actual type casting, respectively.
1 parent fbdf8ab commit 728cada

File tree

7 files changed

+244
-7
lines changed

7 files changed

+244
-7
lines changed

lldb/docs/dil-expr-lang.ebnf

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,13 @@
33
(* This is currently a subset of the final DIL Language, matching the current
44
DIL implementation. *)
55
6-
expression = unary_expression ;
6+
expression = cast_expression;
7+
8+
cast_expression = unary_expression
9+
| "(" type_id ")" cast_expression;
710
811
unary_expression = postfix_expression
9-
| unary_operator expression ;
12+
| unary_operator cast_expression ;
1013
1114
unary_operator = "*" | "&" | "+" | "-";
1215
@@ -44,10 +47,28 @@ nested_name_specifier = type_name "::"
4447
| namespace_name '::'
4548
| nested_name_specifier identifier "::" ;
4649
50+
type_id = type_specifier_seq [abstract_declarator] ;
51+
52+
type_specifier_seq = type_specifier [type_specifier];
53+
54+
type_specifier = ["::"] [nested_name_specifier] type_name
55+
| builtin_typename ;
56+
57+
nested_name_specifier = type_name "::"
58+
| namespace_name "::"
59+
| nested_name_specifier identifier "::" ;
60+
61+
abstract_declarator = ptr_operator [abstract_declarator] ;
62+
63+
ptr_operator = "*"
64+
| "&";
65+
4766
type_name = class_name
4867
| enum_name
4968
| typedef_name;
5069
70+
builtin_typename = identifier_seq;
71+
5172
class_name = identifier ;
5273
5374
enum_name = identifier ;
@@ -56,6 +77,7 @@ typedef_name = identifier ;
5677
5778
namespace_name = identifier ;
5879
59-
80+
identifier_seq = identifier
81+
| identifier identifier_seq;
6082
6183

lldb/include/lldb/ValueObject/DILAST.h

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ enum class NodeKind {
2121
eArraySubscriptNode,
2222
eBitExtractionNode,
2323
eBooleanLiteralNode,
24+
eCastNode,
2425
eErrorNode,
2526
eFloatLiteralNode,
2627
eIdentifierNode,
@@ -37,6 +38,14 @@ enum class UnaryOpKind {
3738
Plus, // "+"
3839
};
3940

41+
/// The type casts allowed by DIL.
42+
enum class CastKind {
43+
eEnumeration, ///< Casting from a scalar to an enumeration type
44+
eNullptr, ///< Casting to a nullptr type
45+
eReference, ///< Casting to a reference type
46+
eNone, ///< Type promotion casting
47+
};
48+
4049
/// Forward declaration, for use in DIL AST nodes. Definition is at the very
4150
/// end of this file.
4251
class Visitor;
@@ -246,6 +255,29 @@ class BooleanLiteralNode : public ASTNode {
246255
bool m_value;
247256
};
248257

258+
class CastNode : public ASTNode {
259+
public:
260+
CastNode(uint32_t location, CompilerType type, ASTNodeUP operand,
261+
CastKind kind)
262+
: ASTNode(location, NodeKind::eCastNode), m_type(type),
263+
m_operand(std::move(operand)), m_cast_kind(kind) {}
264+
265+
llvm::Expected<lldb::ValueObjectSP> Accept(Visitor *v) const override;
266+
267+
CompilerType GetType() const { return m_type; }
268+
ASTNode *GetOperand() const { return m_operand.get(); }
269+
CastKind GetCastKind() const { return m_cast_kind; }
270+
271+
static bool classof(const ASTNode *node) {
272+
return node->GetKind() == NodeKind::eCastNode;
273+
}
274+
275+
private:
276+
CompilerType m_type;
277+
ASTNodeUP m_operand;
278+
CastKind m_cast_kind;
279+
};
280+
249281
/// This class contains one Visit method for each specialized type of
250282
/// DIL AST node. The Visit methods are used to dispatch a DIL AST node to
251283
/// the correct function in the DIL expression evaluator for evaluating that
@@ -269,6 +301,7 @@ class Visitor {
269301
Visit(const FloatLiteralNode *node) = 0;
270302
virtual llvm::Expected<lldb::ValueObjectSP>
271303
Visit(const BooleanLiteralNode *node) = 0;
304+
virtual llvm::Expected<lldb::ValueObjectSP> Visit(const CastNode *node) = 0;
272305
};
273306

274307
} // namespace lldb_private::dil

lldb/include/lldb/ValueObject/DILEval.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ class Interpreter : Visitor {
6060
Visit(const FloatLiteralNode *node) override;
6161
llvm::Expected<lldb::ValueObjectSP>
6262
Visit(const BooleanLiteralNode *node) override;
63+
llvm::Expected<lldb::ValueObjectSP> Visit(const CastNode *node) override;
6364

6465
/// Perform usual unary conversions on a value. At the moment this
6566
/// includes array-to-pointer and integral promotion for eligible types.

lldb/include/lldb/ValueObject/DILParser.h

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,12 @@ class DILParser {
101101
ASTNodeUP ParseFloatingPointLiteral();
102102
ASTNodeUP ParseBooleanLiteral();
103103

104+
ASTNodeUP ParseCastExpression();
105+
std::optional<CompilerType> ParseBuiltinType();
106+
std::optional<CompilerType> ParseTypeId();
107+
CompilerType ResolveTypeDeclarators(CompilerType type,
108+
const std::vector<Token> &ptr_operators);
109+
104110
void BailOut(const std::string &error, uint32_t loc, uint16_t err_len);
105111

106112
void Expect(Token::Kind kind);

lldb/source/ValueObject/DILAST.cpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,4 +51,8 @@ BooleanLiteralNode::Accept(Visitor *v) const {
5151
return v->Visit(this);
5252
}
5353

54+
llvm::Expected<lldb::ValueObjectSP> CastNode::Accept(Visitor *v) const {
55+
return v->Visit(this);
56+
}
57+
5458
} // namespace lldb_private::dil

lldb/source/ValueObject/DILEval.cpp

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -740,4 +740,16 @@ Interpreter::Visit(const BooleanLiteralNode *node) {
740740
return ValueObject::CreateValueObjectFromBool(m_target, value, "result");
741741
}
742742

743+
llvm::Expected<lldb::ValueObjectSP> Interpreter::Visit(const CastNode *node) {
744+
auto operand_or_err = Evaluate(node->GetOperand());
745+
if (!operand_or_err)
746+
return operand_or_err;
747+
748+
lldb::ValueObjectSP operand = *operand_or_err;
749+
// Don't actually do the cast for now -- that code will be added later.
750+
// For now just return an error message.
751+
return llvm::make_error<DILDiagnosticError>(
752+
m_expr, "Type casting is not supported here.", node->GetLocation());
753+
}
754+
743755
} // namespace lldb_private::dil

lldb/source/ValueObject/DILParser.cpp

Lines changed: 163 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,9 @@
1313

1414
#include "lldb/ValueObject/DILParser.h"
1515
#include "lldb/Host/common/DiagnosticsRendering.h"
16+
#include "lldb/Symbol/CompileUnit.h"
1617
#include "lldb/Target/ExecutionContextScope.h"
18+
#include "lldb/Target/LanguageRuntime.h"
1719
#include "lldb/ValueObject/DILAST.h"
1820
#include "lldb/ValueObject/DILEval.h"
1921
#include "llvm/ADT/StringRef.h"
@@ -80,15 +82,63 @@ ASTNodeUP DILParser::Run() {
8082
// Parse an expression.
8183
//
8284
// expression:
83-
// unary_expression
85+
// cast_expression
8486
//
85-
ASTNodeUP DILParser::ParseExpression() { return ParseUnaryExpression(); }
87+
ASTNodeUP DILParser::ParseExpression() { return ParseCastExpression(); }
88+
89+
// Parse a cast_expression.
90+
//
91+
// cast_expression:
92+
// unary_expression
93+
// "(" type_id ")" cast_expression
94+
95+
ASTNodeUP DILParser::ParseCastExpression() {
96+
if (!CurToken().Is(Token::l_paren))
97+
return ParseUnaryExpression();
98+
99+
// This could be a type cast, try parsing the contents as a type declaration.
100+
Token token = CurToken();
101+
uint32_t loc = token.GetLocation();
102+
103+
// Enable lexer backtracking, so that we can rollback in case it's not
104+
// actually a type declaration.
105+
106+
// Start tentative parsing (save token location/idx, for possible rollback).
107+
uint32_t save_token_idx = m_dil_lexer.GetCurrentTokenIdx();
108+
109+
// Consume the token only after enabling the backtracking.
110+
m_dil_lexer.Advance();
111+
112+
// Try parsing the type declaration. If the returned value is not valid,
113+
// then we should rollback and try parsing the expression.
114+
auto type_id = ParseTypeId();
115+
if (type_id) {
116+
// Successfully parsed the type declaration. Commit the backtracked
117+
// tokens and parse the cast_expression.
118+
119+
if (!type_id.value().IsValid())
120+
return std::make_unique<ErrorNode>();
121+
122+
Expect(Token::r_paren);
123+
m_dil_lexer.Advance();
124+
auto rhs = ParseCastExpression();
125+
126+
return std::make_unique<CastNode>(loc, type_id.value(), std::move(rhs),
127+
CastKind::eNone);
128+
}
129+
130+
// Failed to parse the contents of the parentheses as a type declaration.
131+
// Rollback the lexer and try parsing it as unary_expression.
132+
TentativeParsingRollback(save_token_idx);
133+
134+
return ParseUnaryExpression();
135+
}
86136

87137
// Parse an unary_expression.
88138
//
89139
// unary_expression:
90140
// postfix_expression
91-
// unary_operator expression
141+
// unary_operator cast_expression
92142
//
93143
// unary_operator:
94144
// "&"
@@ -102,7 +152,7 @@ ASTNodeUP DILParser::ParseUnaryExpression() {
102152
Token token = CurToken();
103153
uint32_t loc = token.GetLocation();
104154
m_dil_lexer.Advance();
105-
auto rhs = ParseExpression();
155+
auto rhs = ParseCastExpression();
106156
switch (token.GetKind()) {
107157
case Token::star:
108158
return std::make_unique<UnaryOpNode>(loc, UnaryOpKind::Deref,
@@ -282,6 +332,81 @@ std::string DILParser::ParseNestedNameSpecifier() {
282332
}
283333
}
284334

335+
// Parse a type_id.
336+
//
337+
// type_id:
338+
// type_specifier_seq [abstract_declarator]
339+
//
340+
// type_specifier_seq:
341+
// type_specifier [type_specifier]
342+
//
343+
// type_specifier:
344+
// ["::"] [nested_name_specifier] type_name // not handled for now!
345+
// builtin_typename
346+
//
347+
std::optional<CompilerType> DILParser::ParseTypeId() {
348+
CompilerType type;
349+
// For now only allow builtin types -- will expand add to this later.
350+
auto maybe_builtin_type = ParseBuiltinType();
351+
if (maybe_builtin_type) {
352+
type = *maybe_builtin_type;
353+
} else
354+
return {};
355+
356+
//
357+
// abstract_declarator:
358+
// ptr_operator [abstract_declarator]
359+
//
360+
std::vector<Token> ptr_operators;
361+
while (CurToken().IsOneOf({Token::star, Token::amp})) {
362+
Token tok = CurToken();
363+
ptr_operators.push_back(std::move(tok));
364+
m_dil_lexer.Advance();
365+
}
366+
type = ResolveTypeDeclarators(type, ptr_operators);
367+
368+
return type;
369+
}
370+
371+
// Parse a built-in type
372+
//
373+
// builtin_typename:
374+
// identifer_seq
375+
//
376+
// identifier_seq
377+
// identifer [identifier_seq]
378+
//
379+
// A built-in type can be a single identifier or a space-separated
380+
// list of identifiers (e.g. "short" or "long long").
381+
std::optional<CompilerType> DILParser::ParseBuiltinType() {
382+
std::string type_name = "";
383+
uint32_t save_token_idx = m_dil_lexer.GetCurrentTokenIdx();
384+
bool first_word = true;
385+
while (CurToken().GetKind() == Token::identifier) {
386+
if (CurToken().GetSpelling() == "const" ||
387+
CurToken().GetSpelling() == "volatile")
388+
continue;
389+
if (!first_word)
390+
type_name.push_back(' ');
391+
else
392+
first_word = false;
393+
type_name.append(CurToken().GetSpelling());
394+
m_dil_lexer.Advance();
395+
}
396+
397+
if (type_name.size() > 0) {
398+
lldb::TargetSP target_sp = m_ctx_scope->CalculateTarget();
399+
ConstString const_type_name(type_name.c_str());
400+
for (auto type_system_sp : target_sp->GetScratchTypeSystems())
401+
if (auto compiler_type =
402+
type_system_sp->GetBuiltinTypeByName(const_type_name))
403+
return compiler_type;
404+
}
405+
406+
TentativeParsingRollback(save_token_idx);
407+
return {};
408+
}
409+
285410
// Parse an id_expression.
286411
//
287412
// id_expression:
@@ -347,6 +472,40 @@ std::string DILParser::ParseUnqualifiedId() {
347472
return identifier;
348473
}
349474

475+
CompilerType
476+
DILParser::ResolveTypeDeclarators(CompilerType type,
477+
const std::vector<Token> &ptr_operators) {
478+
// Resolve pointers/references.
479+
for (Token tk : ptr_operators) {
480+
uint32_t loc = tk.GetLocation();
481+
if (tk.GetKind() == Token::star) {
482+
// Pointers to reference types are forbidden.
483+
if (type.IsReferenceType()) {
484+
BailOut(llvm::formatv("'type name' declared as a pointer to a "
485+
"reference of type {0}",
486+
type.TypeDescription()),
487+
loc, CurToken().GetSpelling().length());
488+
return {};
489+
}
490+
// Get pointer type for the base type: e.g. int* -> int**.
491+
type = type.GetPointerType();
492+
493+
} else if (tk.GetKind() == Token::amp) {
494+
// References to references are forbidden.
495+
// FIXME: In future we may want to allow rvalue references (i.e. &&).
496+
if (type.IsReferenceType()) {
497+
BailOut("type name declared as a reference to a reference", loc,
498+
CurToken().GetSpelling().length());
499+
return {};
500+
}
501+
// Get reference type for the base type: e.g. int -> int&.
502+
type = type.GetLValueReferenceType();
503+
}
504+
}
505+
506+
return type;
507+
}
508+
350509
// Parse an boolean_literal.
351510
//
352511
// boolean_literal:

0 commit comments

Comments
 (0)