载入中...
搜索中...
未找到
DnutLexer.cpp
浏览该文件的文档.
2
3#include <cctype>
4#include <cstddef>
5#include <string>
6#include <utility>
7#include <vector>
8
9namespace eve::dnut {
10
11namespace {
12
13bool isIdentifierStart(char c) {
14 return std::isalpha(static_cast<unsigned char>(c)) != 0 || c == '_';
15}
16
17bool isIdentifierBody(char c) {
18 return std::isalnum(static_cast<unsigned char>(c)) != 0 || c == '_' || c == '.';
19}
20
21bool isDigit(char c) { return c >= '0' && c <= '9'; }
22
23eve::Result<std::vector<DnutToken>> lexFailure(const std::string& path, int line, int column,
24 std::string message) {
27 {{"line", std::to_string(line)}, {"column", std::to_string(column)}}, "dnut.lexer"));
28}
29
31std::size_t twoCharacterPunctuatorLength(std::string_view source, std::size_t i) {
32 if (i + 1 >= source.size()) return 0;
33 const std::string_view pair = source.substr(i, 2);
34 for (const std::string_view candidate : {"==", "!=", ">=", "<=", "&&", "||", "->"}) {
35 if (pair == candidate) return 2;
36 }
37 return 0;
38}
39
40bool isSingleCharacterPunctuator(char c) {
41 switch (c) {
42 case '{':
43 case '}':
44 case '(':
45 case ')':
46 case '[':
47 case ']':
48 case ':':
49 case ',':
50 case '=':
51 case '>':
52 case '<':
53 case '!':
54 case '-':
55 case '+':
56 case '*':
57 case '/':
58 case '|': return true;
59 default: return false;
60 }
61}
62
64bool appendEscape(char escape, std::string& out) {
65 switch (escape) {
66 case 'n': out += '\n'; return true;
67 case 't': out += '\t'; return true;
68 case 'r': out += '\r'; return true;
69 case '"': out += '"'; return true;
70 case '\'': out += '\''; return true;
71 case '\\': out += '\\'; return true;
72 case '{': out += '{'; return true;
73 case '}': out += '}'; return true;
74 default:
75 // The original dialogue lexer treated an unknown escape as the
76 // escaped character itself. Keep that accepted source set while
77 // still normalizing the known control escapes above.
78 out += escape;
79 return true;
80 }
81}
82
83} // namespace
84
85const char* dnutTokenKindName(DnutTokenKind kind) noexcept {
86 switch (kind) {
87 case DnutTokenKind::Identifier: return "identifier";
88 case DnutTokenKind::String: return "string";
89 case DnutTokenKind::Number: return "number";
90 case DnutTokenKind::Punctuator: return "punctuator";
91 case DnutTokenKind::EndOfFile: return "eof";
92 }
93 return "unknown";
94}
95
96eve::Result<std::vector<DnutToken>> lexDnut(std::string_view source, const std::string& path) {
97 std::vector<DnutToken> tokens;
98 std::size_t i = 0;
99 int line = 1;
100 int column = 1;
101 const std::size_t size = source.size();
102
103 const auto advanceOne = [&]() {
104 if (source[i] == '\n') {
105 ++line;
106 column = 1;
107 } else {
108 ++column;
109 }
110 ++i;
111 };
112
113 while (i < size) {
114 const char c = source[i];
115
116 if (c == '\n' || c == ' ' || c == '\t' || c == '\r') {
117 advanceOne();
118 continue;
119 }
120 if (c == '/' && i + 1 < size && source[i + 1] == '/') {
121 while (i < size && source[i] != '\n') ++i;
122 continue;
123 }
124 if (c == '/' && i + 1 < size && source[i + 1] == '*') {
125 const int startLine = line;
126 const int startColumn = column;
127 advanceOne();
128 advanceOne();
129 bool closed = false;
130 while (i < size) {
131 if (source[i] == '*' && i + 1 < size && source[i + 1] == '/') {
132 advanceOne();
133 advanceOne();
134 closed = true;
135 break;
136 }
137 advanceOne();
138 }
139 if (!closed)
140 return lexFailure(path, startLine, startColumn, "unterminated block comment");
141 continue;
142 }
143 if (c == '"' || c == '\'') {
144 const char quote = c;
145 const int startLine = line;
146 const int startColumn = column;
147 advanceOne();
148 std::string text;
149 bool terminated = false;
150 while (i < size) {
151 if (source[i] == quote) {
152 advanceOne();
153 terminated = true;
154 break;
155 }
156 if (source[i] == '\\') {
157 advanceOne();
158 if (i >= size) break;
159 if (!appendEscape(source[i], text))
160 return lexFailure(path, line, column,
161 std::string("unknown escape sequence '\\") + source[i] + "'");
162 advanceOne();
163 continue;
164 }
165 text += source[i];
166 advanceOne();
167 }
168 if (!terminated) return lexFailure(path, startLine, startColumn, "unterminated string literal");
169 tokens.push_back({DnutTokenKind::String, std::move(text), startLine, startColumn});
170 continue;
171 }
172 if (isDigit(c) || (c == '.' && i + 1 < size && isDigit(source[i + 1]))) {
173 const int startLine = line;
174 const int startColumn = column;
175 const std::size_t start = i;
176 while (i < size) {
177 const char d = source[i];
178 if (isDigit(d) || d == '.') {
179 advanceOne();
180 } else if ((d == 'e' || d == 'E') && i + 1 < size &&
181 (isDigit(source[i + 1]) || source[i + 1] == '+' || source[i + 1] == '-')) {
182 advanceOne();
183 advanceOne();
184 } else {
185 break;
186 }
187 }
188 tokens.push_back({DnutTokenKind::Number, std::string(source.substr(start, i - start)), startLine,
189 startColumn});
190 continue;
191 }
192 if (isIdentifierStart(c)) {
193 const int startLine = line;
194 const int startColumn = column;
195 const std::size_t start = i;
196 // A '-' joins an identifier only when a word character follows it, so
197 // dashed content ids (`iron-sword`) stay one token while arrow and
198 // minus punctuation (`->`, `-3`) are unaffected.
199 const auto continuesIdentifier = [&source, size](std::size_t position) {
200 if (isIdentifierBody(source[position])) return true;
201 return source[position] == '-' && position + 1 < size && isIdentifierBody(source[position + 1]);
202 };
203 while (i < size && continuesIdentifier(i)) advanceOne();
204 tokens.push_back(
205 {DnutTokenKind::Identifier, std::string(source.substr(start, i - start)), startLine, startColumn});
206 continue;
207 }
208 if (const std::size_t pairLength = twoCharacterPunctuatorLength(source, i); pairLength != 0) {
209 const int startLine = line;
210 const int startColumn = column;
211 const std::string text(source.substr(i, pairLength));
212 advanceOne();
213 advanceOne();
214 tokens.push_back({DnutTokenKind::Punctuator, text, startLine, startColumn});
215 continue;
216 }
217 if (isSingleCharacterPunctuator(c)) {
218 const int startLine = line;
219 const int startColumn = column;
220 const std::string text(1, c);
221 advanceOne();
222 tokens.push_back({DnutTokenKind::Punctuator, std::move(text), startLine, startColumn});
223 continue;
224 }
225 return lexFailure(path, line, column, std::string("unexpected character '") + c + "'");
226 }
227
228 tokens.push_back({DnutTokenKind::EndOfFile, std::string{}, line, column});
229 return eve::Result<std::vector<DnutToken>>::success(std::move(tokens));
230}
231
232bool hasErrors(const std::vector<DnutDiagnostic>& diagnostics) {
233 for (const auto& diagnostic : diagnostics) {
234 if (diagnostic.severity == DnutSeverity::Error) return true;
235 }
236 return false;
237}
238
239} // namespace eve::dnut
Duration start
Shared lexer for every `.dnut` dialect.
std::string message
std::int32_t c
char quote
std::array< float, 3 > position
std::string path
Definition PlayHost.cpp:111
float d
unsigned line
std::string text
ScriptStructure out
std::string_view source
unsigned column
std::string kind
std::vector< Token > tokens
float size
Definition TreeMesh.cpp:158
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Move-only operation result carrying either a value or Status.
Definition Result.h:176
EVENGINE_API_PLATFORM bool hasErrors(const std::vector< DnutDiagnostic > &diagnostics)
Return whether any diagnostic is an error.
eve::Result< std::vector< DnutToken > > lexDnut(std::string_view source, const std::string &path)
Lex one .dnut source buffer into owned tokens.
Definition DnutLexer.cpp:96
const char * dnutTokenKindName(DnutTokenKind kind) noexcept
Return the stable lowercase spelling of a token kind.
Definition DnutLexer.cpp:85
DnutTokenKind
Token classes produced by the shared .dnut lexer.
Definition DnutLexer.h:17
@ String
Quoted string with escapes already resolved.
@ Identifier
Bare word: keyword, field name, identifier, or bare enum value.
@ Punctuator
One- or two-character punctuator such as {, =, ==, ->.
@ EndOfFile
Synthetic terminal token; always the last element.
@ Number
Unsigned numeric literal; sign handling belongs to the parser.