LLDB mainline
DILLexer.cpp
Go to the documentation of this file.
1//===-- DILLexer.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
15#include "lldb/Utility/Status.h"
17#include "llvm/ADT/StringSwitch.h"
18
19namespace lldb_private::dil {
20
21llvm::StringRef Token::GetTokenName(Kind kind) {
22 switch (kind) {
23 case Kind::amp:
24 return "amp";
25 case Kind::ampamp:
26 return "ampamp";
27 case Kind::ampequal:
28 return "ampequal";
29 case Kind::arrow:
30 return "arrow";
31 case Kind::caret:
32 return "caret";
34 return "caretequal";
35 case Kind::colon:
36 return "colon";
38 return "coloncolon";
39 case Kind::equal:
40 return "equal";
41 case Kind::exclaim:
42 return "exclaim";
43 case Kind::eof:
44 return "eof";
46 return "equalequal";
48 return "exclaimequal";
50 return "float_constant";
51 case Kind::greater:
52 return "greater";
54 return "greaterequal";
56 return "greatergreater";
58 return "greatergreaterequal";
60 return "identifier";
62 return "integer_constant";
63 case Kind::kw_false:
64 return "false";
65 case Kind::kw_true:
66 return "true";
67 case Kind::l_paren:
68 return "l_paren";
69 case Kind::l_square:
70 return "l_square";
71 case Kind::less:
72 return "less";
73 case Kind::lessequal:
74 return "lessequal";
75 case Kind::lessless:
76 return "lessless";
78 return "lesslessequal";
79 case Kind::minus:
80 return "minus";
82 return "minusequal";
84 return "minusminus";
85 case Token::percent:
86 return "percent";
88 return "percentequal";
89 case Kind::period:
90 return "period";
91 case Kind::pipe:
92 return "pipe";
93 case Kind::pipeequal:
94 return "pipeequal";
95 case Kind::pipepipe:
96 return "pipepipe";
97 case Kind::plus:
98 return "plus";
99 case Kind::plusequal:
100 return "plusequal";
101 case Kind::plusplus:
102 return "plusplus";
103 case Kind::question:
104 return "question";
105 case Kind::r_paren:
106 return "r_paren";
107 case Kind::r_square:
108 return "r_square";
109 case Token::slash:
110 return "slash";
112 return "slashequal";
113 case Token::star:
114 return "star";
115 case Token::starequal:
116 return "starequal";
117 case Token::tilde:
118 return "tilde";
119 }
120 llvm_unreachable("Unknown token name");
121}
122
123static bool IsLetter(char c) {
124 return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
125}
126
127static bool IsDigit(char c) { return '0' <= c && c <= '9'; }
128
129// A word starts with a letter, underscore, or dollar sign, followed by
130// letters ('a'..'z','A'..'Z'), digits ('0'..'9'), and/or underscores.
131static std::optional<llvm::StringRef> IsWord(llvm::StringRef expr,
132 llvm::StringRef &remainder) {
133 // Find the longest prefix consisting of letters, digits, underscors and
134 // '$'. If it doesn't start with a digit, then it's a word.
135 llvm::StringRef candidate = remainder.take_while(
136 [](char c) { return IsDigit(c) || IsLetter(c) || c == '_' || c == '$'; });
137 if (candidate.empty() || IsDigit(candidate[0]))
138 return std::nullopt;
139 remainder = remainder.drop_front(candidate.size());
140 return candidate;
141}
142
143static bool IsNumberBodyChar(char ch) {
144 return IsDigit(ch) || IsLetter(ch) || ch == '.';
145}
146
147static std::optional<llvm::StringRef> IsNumber(llvm::StringRef &remainder,
148 bool &isFloat) {
149 llvm::StringRef tail = remainder;
150 llvm::StringRef body = tail.take_while(IsNumberBodyChar);
151 size_t dots = body.count('.');
152 if (dots > 1 || dots == body.size())
153 return std::nullopt;
154 if (IsDigit(body.front()) || (body[0] == '.' && IsDigit(body[1]))) {
155 isFloat = dots == 1;
156 tail = tail.drop_front(body.size());
157 bool isHex = body.contains_insensitive('x');
158 bool hasExp = !isHex && body.contains_insensitive('e');
159 bool hasHexExp = isHex && body.contains_insensitive('p');
160 if (hasExp || hasHexExp) {
161 isFloat = true; // This marks numbers like 0x1p1 and 1e1 as float
162 if (body.ends_with_insensitive("e") || body.ends_with_insensitive("p"))
163 if (tail.consume_front("+") || tail.consume_front("-"))
164 tail = tail.drop_while(IsNumberBodyChar);
165 }
166 size_t number_length = remainder.size() - tail.size();
167 llvm::StringRef number = remainder.take_front(number_length);
168 remainder = remainder.drop_front(number_length);
169 return number;
170 }
171 return std::nullopt;
172}
173
174static llvm::Error IsNotAllowedByMode(llvm::StringRef expr, Token token,
175 lldb::DILMode mode) {
176 switch (mode) {
178 if (!token.IsOneOf({Token::identifier, Token::period, Token::eof})) {
179 return llvm::make_error<DILDiagnosticError>(
180 expr, llvm::formatv("{0} is not allowed in DIL simple mode", token),
181 token.GetLocation());
182 }
183 break;
185 if (!token.IsOneOf({Token::identifier, Token::integer_constant,
186 Token::period, Token::arrow, Token::star, Token::amp,
187 Token::l_square, Token::r_square, Token::eof})) {
188 return llvm::make_error<DILDiagnosticError>(
189 expr, llvm::formatv("{0} is not allowed in DIL legacy mode", token),
190 token.GetLocation());
191 }
192 break;
194 break;
195 }
196 return llvm::Error::success();
197}
198
199llvm::Expected<DILLexer> DILLexer::Create(llvm::StringRef expr,
200 lldb::DILMode mode) {
201 std::vector<Token> tokens;
202 llvm::StringRef remainder = expr;
203 do {
204 if (llvm::Expected<Token> t = Lex(expr, remainder)) {
205 Token token = *t;
206 if (llvm::Error error = IsNotAllowedByMode(expr, token, mode))
207 return error;
208 tokens.push_back(std::move(token));
209 } else {
210 return t.takeError();
211 }
212 } while (tokens.back().GetKind() != Token::eof);
213 return DILLexer(expr, std::move(tokens));
214}
215
216llvm::Expected<Token> DILLexer::Lex(llvm::StringRef expr,
217 llvm::StringRef &remainder) {
218 // Skip over whitespace (spaces).
219 remainder = remainder.ltrim();
220 llvm::StringRef::iterator cur_pos = remainder.begin();
221
222 // Check to see if we've reached the end of our input string.
223 if (remainder.empty())
224 return Token(Token::eof, "", (uint32_t)expr.size());
225
226 uint32_t position = cur_pos - expr.begin();
227 bool isFloat = false;
228 std::optional<llvm::StringRef> maybe_number = IsNumber(remainder, isFloat);
229 if (maybe_number) {
230 auto kind = isFloat ? Token::float_constant : Token::integer_constant;
231 return Token(kind, maybe_number->str(), position);
232 }
233 std::optional<llvm::StringRef> maybe_word = IsWord(expr, remainder);
234 if (maybe_word) {
235 llvm::StringRef word = *maybe_word;
236 Token::Kind kind = llvm::StringSwitch<Token::Kind>(word)
237 .Case("false", Token::kw_false)
238 .Case("true", Token::kw_true)
239 .Default(Token::identifier);
240 return Token(kind, word.str(), position);
241 }
242
243 // IMPORTANT: If two or more tokens share the same prefix, the tokens need to
244 // be ordered longest-to-shortest in the list below. E.g. '::' must come
245 // before ':', and '+=' must come before '+'.
246 constexpr std::pair<Token::Kind, const char *> operators[] = {
248 {Token::lesslessequal, "<<="},
249 {Token::ampamp, "&&"},
250 {Token::ampequal, "&="},
251 {Token::arrow, "->"},
252 {Token::caretequal, "^="},
253 {Token::coloncolon, "::"},
254 {Token::equalequal, "=="},
255 {Token::exclaimequal, "!="},
256 {Token::greaterequal, ">="},
257 {Token::greatergreater, ">>"},
258 {Token::lessequal, "<="},
259 {Token::lessless, "<<"},
260 {Token::minusequal, "-="},
261 {Token::minusminus, "--"},
262 {Token::percentequal, "%="},
263 {Token::pipeequal, "|="},
264 {Token::pipepipe, "||"},
265 {Token::plusequal, "+="},
266 {Token::plusplus, "++"},
267 {Token::slashequal, "/="},
268 {Token::starequal, "*="},
269 {Token::amp, "&"},
270 {Token::caret, "^"},
271 {Token::colon, ":"},
272 {Token::equal, "="},
273 {Token::exclaim, "!"},
274 {Token::greater, ">"},
275 {Token::l_paren, "("},
276 {Token::l_square, "["},
277 {Token::less, "<"},
278 {Token::minus, "-"},
279 {Token::percent, "%"},
280 {Token::period, "."},
281 {Token::pipe, "|"},
282 {Token::plus, "+"},
283 {Token::question, "?"},
284 {Token::r_paren, ")"},
285 {Token::r_square, "]"},
286 {Token::slash, "/"},
287 {Token::star, "*"},
288 {Token::tilde, "~"},
289 };
290 for (auto [kind, str] : operators) {
291 if (remainder.consume_front(str))
292 return Token(kind, str, position);
293 }
294
295 // Unrecognized character(s) in string; unable to lex it.
296 return llvm::make_error<DILDiagnosticError>(expr, "unrecognized token",
297 position);
298}
299
300} // namespace lldb_private::dil
static llvm::raw_ostream & error(Stream &strm)
static llvm::Expected< DILLexer > Create(llvm::StringRef expr, lldb::DILMode mode=lldb::eDILModeFull)
Lexes all the tokens in expr and calls the private constructor with the lexed tokens.
Definition DILLexer.cpp:199
DILLexer(llvm::StringRef dil_expr, std::vector< Token > lexed_tokens)
Definition DILLexer.h:147
static llvm::Expected< Token > Lex(llvm::StringRef expr, llvm::StringRef &remainder)
Definition DILLexer.cpp:216
Class defining the tokens generated by the DIL lexer and used by the DIL parser.
Definition DILLexer.h:25
static llvm::StringRef GetTokenName(Kind kind)
Definition DILLexer.cpp:21
uint32_t GetLocation() const
Definition DILLexer.h:93
bool IsOneOf(llvm::ArrayRef< Kind > kinds) const
Definition DILLexer.h:89
static std::optional< llvm::StringRef > IsWord(llvm::StringRef expr, llvm::StringRef &remainder)
Definition DILLexer.cpp:131
static bool IsNumberBodyChar(char ch)
Definition DILLexer.cpp:143
static llvm::Error IsNotAllowedByMode(llvm::StringRef expr, Token token, lldb::DILMode mode)
Definition DILLexer.cpp:174
static bool IsLetter(char c)
Definition DILLexer.cpp:123
static std::optional< llvm::StringRef > IsNumber(llvm::StringRef &remainder, bool &isFloat)
Definition DILLexer.cpp:147
static bool IsDigit(char c)
Definition DILLexer.cpp:127
DILMode
Data Inspection Language (DIL) evaluation modes.
@ eDILModeFull
Allowed: everything supported by DIL.
@ eDILModeLegacy
Allowed: identifiers, integers, operators: '.', '->', '*', '&', '[]'.
@ eDILModeSimple
Allowed: identifiers, operators: '.'.