#include "lldb/ValueObject/DILParser.h"
#include "lldb/Host/common/DiagnosticsRendering.h"
#include "lldb/Target/ExecutionContextScope.h"
#include "lldb/ValueObject/DILAST.h"
#include "lldb/ValueObject/DILEval.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/FormatAdapters.h"
#include <cstdlib>
#include <limits.h>
#include <memory>
#include <sstream>
#include <string>
namespace lldb_private::dil {
DILDiagnosticError::DILDiagnosticError(llvm::StringRef expr,
const std::string &message, uint32_t loc,
uint16_t err_len)
: ErrorInfo(make_error_code(std::errc::invalid_argument)) {
DiagnosticDetail::SourceLocation sloc = {
FileSpec{}, 1, static_cast<uint16_t>(loc + 1),
err_len, false, true};
std::string rendered_msg =
llvm::formatv("<user expression 0>:1:{0}: {1}\n 1 | {2}\n | ^",
loc + 1, message, expr);
m_detail.source_location = sloc;
m_detail.severity = lldb::eSeverityError;
m_detail.message = message;
m_detail.rendered = std::move(rendered_msg);
}
llvm::Expected<ASTNodeUP>
DILParser::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) {
llvm::Error error = llvm::Error::success();
DILParser parser(dil_input_expr, lexer, frame_sp, use_dynamic, use_synthetic,
fragile_ivar, check_ptr_vs_member, error);
ASTNodeUP node_up = parser.Run();
if (error)
return error;
return node_up;
}
DILParser::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)
: m_ctx_scope(frame_sp), m_input_expr(dil_input_expr),
m_dil_lexer(std::move(lexer)), m_error(error), m_use_dynamic(use_dynamic),
m_use_synthetic(use_synthetic), m_fragile_ivar(fragile_ivar),
m_check_ptr_vs_member(check_ptr_vs_member) {}
ASTNodeUP DILParser::Run() {
ASTNodeUP expr = ParseExpression();
Expect(Token::Kind::eof);
return expr;
}
ASTNodeUP DILParser::ParseExpression() { return ParseUnaryExpression(); }
ASTNodeUP DILParser::ParseUnaryExpression() {
if (CurToken().IsOneOf(
{Token::amp, Token::star, Token::minus, Token::plus})) {
Token token = CurToken();
uint32_t loc = token.GetLocation();
m_dil_lexer.Advance();
auto rhs = ParseExpression();
switch (token.GetKind()) {
case Token::star:
return std::make_unique<UnaryOpNode>(loc, UnaryOpKind::Deref,
std::move(rhs));
case Token::amp:
return std::make_unique<UnaryOpNode>(loc, UnaryOpKind::AddrOf,
std::move(rhs));
case Token::minus:
return std::make_unique<UnaryOpNode>(loc, UnaryOpKind::Minus,
std::move(rhs));
case Token::plus:
return std::make_unique<UnaryOpNode>(loc, UnaryOpKind::Plus,
std::move(rhs));
default:
llvm_unreachable("invalid token kind");
}
}
return ParsePostfixExpression();
}
ASTNodeUP DILParser::ParsePostfixExpression() {
ASTNodeUP lhs = ParsePrimaryExpression();
while (CurToken().IsOneOf({Token::l_square, Token::period, Token::arrow})) {
uint32_t loc = CurToken().GetLocation();
Token token = CurToken();
switch (token.GetKind()) {
case Token::l_square: {
m_dil_lexer.Advance();
std::optional<int64_t> index = ParseIntegerConstant();
if (!index) {
BailOut(
llvm::formatv("failed to parse integer constant: {0}", CurToken()),
CurToken().GetLocation(), CurToken().GetSpelling().length());
return std::make_unique<ErrorNode>();
}
if (CurToken().GetKind() == Token::minus) {
m_dil_lexer.Advance();
std::optional<int64_t> last_index = ParseIntegerConstant();
if (!last_index) {
BailOut(llvm::formatv("failed to parse integer constant: {0}",
CurToken()),
CurToken().GetLocation(), CurToken().GetSpelling().length());
return std::make_unique<ErrorNode>();
}
lhs = std::make_unique<BitFieldExtractionNode>(
loc, std::move(lhs), std::move(*index), std::move(*last_index));
} else {
lhs = std::make_unique<ArraySubscriptNode>(loc, std::move(lhs),
std::move(*index));
}
Expect(Token::r_square);
m_dil_lexer.Advance();
break;
}
case Token::period:
case Token::arrow: {
m_dil_lexer.Advance();
Token member_token = CurToken();
std::string member_id = ParseIdExpression();
lhs = std::make_unique<MemberOfNode>(
member_token.GetLocation(), std::move(lhs),
token.GetKind() == Token::arrow, member_id);
break;
}
default:
llvm_unreachable("invalid token");
}
}
return lhs;
}
ASTNodeUP DILParser::ParsePrimaryExpression() {
if (CurToken().IsOneOf({Token::integer_constant, Token::float_constant}))
return ParseNumericLiteral();
if (CurToken().IsOneOf({Token::kw_true, Token::kw_false}))
return ParseBooleanLiteral();
if (CurToken().IsOneOf(
{Token::coloncolon, Token::identifier, Token::l_paren})) {
uint32_t loc = CurToken().GetLocation();
std::string identifier = ParseIdExpression();
if (!identifier.empty())
return std::make_unique<IdentifierNode>(loc, identifier);
}
if (CurToken().Is(Token::l_paren)) {
m_dil_lexer.Advance();
auto expr = ParseExpression();
Expect(Token::r_paren);
m_dil_lexer.Advance();
return expr;
}
BailOut(llvm::formatv("Unexpected token: {0}", CurToken()),
CurToken().GetLocation(), CurToken().GetSpelling().length());
return std::make_unique<ErrorNode>();
}
std::string DILParser::ParseNestedNameSpecifier() {
switch (CurToken().GetKind()) {
case Token::l_paren: {
if (m_dil_lexer.LookAhead(1).Is(Token::identifier) &&
(m_dil_lexer.LookAhead(1).GetSpelling() == "anonymous") &&
m_dil_lexer.LookAhead(2).Is(Token::identifier) &&
(m_dil_lexer.LookAhead(2).GetSpelling() == "namespace") &&
m_dil_lexer.LookAhead(3).Is(Token::r_paren) &&
m_dil_lexer.LookAhead(4).Is(Token::coloncolon)) {
m_dil_lexer.Advance(4);
Expect(Token::coloncolon);
m_dil_lexer.Advance();
if (!CurToken().Is(Token::identifier) && !CurToken().Is(Token::l_paren)) {
BailOut("Expected an identifier or anonymous namespace, but not found.",
CurToken().GetLocation(), CurToken().GetSpelling().length());
}
std::string identifier2 = ParseNestedNameSpecifier();
return "(anonymous namespace)::" + identifier2;
}
return "";
}
case Token::identifier: {
if (m_dil_lexer.LookAhead(1).Is(Token::coloncolon)) {
std::string identifier = CurToken().GetSpelling();
m_dil_lexer.Advance(1);
Expect(Token::coloncolon);
m_dil_lexer.Advance();
return identifier + "::" + ParseNestedNameSpecifier();
}
return "";
}
default:
return "";
}
}
std::string DILParser::ParseIdExpression() {
bool global_scope = false;
if (CurToken().Is(Token::coloncolon)) {
global_scope = true;
m_dil_lexer.Advance();
}
std::string nested_name_specifier = ParseNestedNameSpecifier();
if (!nested_name_specifier.empty()) {
auto unqualified_id = ParseUnqualifiedId();
return llvm::formatv("{0}{1}{2}", global_scope ? "::" : "",
nested_name_specifier, unqualified_id);
}
if (!CurToken().Is(Token::identifier))
return "";
if (global_scope) {
Expect(Token::identifier);
std::string identifier = CurToken().GetSpelling();
m_dil_lexer.Advance();
return llvm::formatv("{0}{1}", global_scope ? "::" : "", identifier);
}
return ParseUnqualifiedId();
}
std::string DILParser::ParseUnqualifiedId() {
Expect(Token::identifier);
std::string identifier = CurToken().GetSpelling();
m_dil_lexer.Advance();
return identifier;
}
ASTNodeUP DILParser::ParseBooleanLiteral() {
ExpectOneOf(std::vector<Token::Kind>{Token::kw_true, Token::kw_false});
uint32_t loc = CurToken().GetLocation();
bool literal_value = CurToken().Is(Token::kw_true);
m_dil_lexer.Advance();
return std::make_unique<BooleanLiteralNode>(loc, literal_value);
}
void DILParser::BailOut(const std::string &error, uint32_t loc,
uint16_t err_len) {
if (m_error)
return;
m_error =
llvm::make_error<DILDiagnosticError>(m_input_expr, error, loc, err_len);
m_dil_lexer.ResetTokenIdx(m_dil_lexer.NumLexedTokens() - 1);
}
std::optional<int64_t> DILParser::ParseIntegerConstant() {
std::string number_spelling;
if (CurToken().GetKind() == Token::minus) {
number_spelling = "-";
m_dil_lexer.Advance();
}
number_spelling.append(CurToken().GetSpelling());
llvm::StringRef spelling_ref = number_spelling;
int64_t raw_value;
if (!spelling_ref.getAsInteger<int64_t>(0, raw_value)) {
m_dil_lexer.Advance();
return raw_value;
}
return std::nullopt;
}
ASTNodeUP DILParser::ParseNumericLiteral() {
ASTNodeUP numeric_constant;
if (CurToken().Is(Token::integer_constant))
numeric_constant = ParseIntegerLiteral();
else
numeric_constant = ParseFloatingPointLiteral();
if (!numeric_constant) {
BailOut(llvm::formatv("Failed to parse token as numeric-constant: {0}",
CurToken()),
CurToken().GetLocation(), CurToken().GetSpelling().length());
return std::make_unique<ErrorNode>();
}
m_dil_lexer.Advance();
return numeric_constant;
}
ASTNodeUP DILParser::ParseIntegerLiteral() {
Token token = CurToken();
auto spelling = token.GetSpelling();
llvm::StringRef spelling_ref = spelling;
auto radix = llvm::getAutoSenseRadix(spelling_ref);
IntegerTypeSuffix type = IntegerTypeSuffix::None;
bool is_unsigned = false;
if (spelling_ref.consume_back_insensitive("u"))
is_unsigned = true;
if (spelling_ref.consume_back_insensitive("ll"))
type = IntegerTypeSuffix::LongLong;
else if (spelling_ref.consume_back_insensitive("l"))
type = IntegerTypeSuffix::Long;
if (!is_unsigned && spelling_ref.consume_back_insensitive("u"))
is_unsigned = true;
llvm::APInt raw_value;
if (!spelling_ref.getAsInteger(radix, raw_value))
return std::make_unique<IntegerLiteralNode>(token.GetLocation(), raw_value,
radix, is_unsigned, type);
return nullptr;
}
ASTNodeUP DILParser::ParseFloatingPointLiteral() {
Token token = CurToken();
auto spelling = token.GetSpelling();
llvm::StringRef spelling_ref = spelling;
llvm::APFloat raw_float(llvm::APFloat::IEEEdouble());
if (spelling_ref.consume_back_insensitive("f"))
raw_float = llvm::APFloat(llvm::APFloat::IEEEsingle());
auto StatusOrErr = raw_float.convertFromString(
spelling_ref, llvm::APFloat::rmNearestTiesToEven);
if (!errorToBool(StatusOrErr.takeError()))
return std::make_unique<FloatLiteralNode>(token.GetLocation(), raw_float);
return nullptr;
}
void DILParser::Expect(Token::Kind kind) {
if (CurToken().IsNot(kind)) {
BailOut(llvm::formatv("expected {0}, got: {1}", kind, CurToken()),
CurToken().GetLocation(), CurToken().GetSpelling().length());
}
}
void DILParser::ExpectOneOf(std::vector<Token::Kind> kinds_vec) {
if (!CurToken().IsOneOf(kinds_vec)) {
BailOut(llvm::formatv("expected any of ({0}), got: {1}",
llvm::iterator_range(kinds_vec), CurToken()),
CurToken().GetLocation(), CurToken().GetSpelling().length());
}
}
}