Debian Codegraph @

Source/Core/Common/Assembler/GekkoLexer.cpp

raw symbols SCIP
1 // Copyright 2023 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "Common/Assembler/GekkoLexer.h"
5
6 #include "Common/StringUtil.h"
7
8 #include <iterator>
9 #include <numeric>
10
11 namespace Common::GekkoAssembler::detail
12 {
13 namespace
14 {
15 constexpr bool IsOctal(char c)
16 {
17 return c >= '0' && c <= '7';
18 }
19
20 constexpr bool IsBinary(char c)
21 {
22 return c == '0' || c == '1';
23 }
24
25 template <typename T>
26 constexpr T ConvertNib(char c)
27 {
28 if (c >= 'a' && c <= 'f')
29 {
30 return static_cast<T>(c - 'a' + 10);
31 }
32 if (c >= 'A' && c <= 'F')
33 {
34 return static_cast<T>(c - 'A' + 10);
35 }
36 return static_cast<T>(c - '0');
37 }
38
39 constexpr TokenType SingleCharToken(char ch)
40 {
41 switch (ch)
42 {
43 case ',':
44 return TokenType::Comma;
45 case '(':
46 return TokenType::Lparen;
47 case ')':
48 return TokenType::Rparen;
49 case '|':
50 return TokenType::Pipe;
51 case '^':
52 return TokenType::Caret;
53 case '&':
54 return TokenType::Ampersand;
55 case '+':
56 return TokenType::Plus;
57 case '-':
58 return TokenType::Minus;
59 case '*':
60 return TokenType::Star;
61 case '/':
62 return TokenType::Slash;
63 case '~':
64 return TokenType::Tilde;
65 case '@':
66 return TokenType::At;
67 case ':':
68 return TokenType::Colon;
69 case '`':
70 return TokenType::Grave;
71 case '.':
72 return TokenType::Dot;
73 case '\0':
74 return TokenType::Eof;
75 case '\n':
76 return TokenType::Eol;
77 default:
78 return TokenType::Invalid;
79 }
80 }
81
82 // Convert a string literal into its raw-data form
83 template <typename Cont>
84 void ConvertStringLiteral(std::string_view literal, std::back_insert_iterator<Cont> out_it)
85 {
86 for (size_t i = 1; i < literal.size() - 1;)
87 {
88 if (literal[i] == '\\')
89 {
90 ++i;
91 if (IsOctal(literal[i]))
92 {
93 // Octal escape
94 char octal_escape = 0;
95 for (char c = literal[i]; IsOctal(c); c = literal[++i])
96 {
97 octal_escape = (octal_escape << 3) + (c - '0');
98 }
99 out_it = static_cast<u8>(octal_escape);
100 }
101 else if (literal[i] == 'x')
102 {
103 // Hex escape
104 char hex_escape = 0;
105 for (char c = literal[++i]; std::isxdigit(c); c = literal[++i])
106 {
107 hex_escape = (hex_escape << 4) + ConvertNib<char>(c);
108 }
109 out_it = static_cast<u8>(hex_escape);
110 }
111 else
112 {
113 char simple_escape;
114 switch (literal[i])
115 {
116 case '\'':
117 simple_escape = '\x27';
118 break;
119 case '"':
120 simple_escape = '\x22';
121 break;
122 case '?':
123 simple_escape = '\x3f';
124 break;
125 case '\\':
126 simple_escape = '\x5c';
127 break;
128 case 'a':
129 simple_escape = '\x07';
130 break;
131 case 'b':
132 simple_escape = '\x08';
133 break;
134 case 'f':
135 simple_escape = '\x0c';
136 break;
137 case 'n':
138 simple_escape = '\x0a';
139 break;
140 case 'r':
141 simple_escape = '\x0d';
142 break;
143 case 't':
144 simple_escape = '\x09';
145 break;
146 case 'v':
147 simple_escape = '\x0b';
148 break;
149 default:
150 simple_escape = literal[i];
151 break;
152 }
153 out_it = static_cast<u8>(simple_escape);
154 ++i;
155 }
156 }
157 else
158 {
159 out_it = static_cast<u8>(literal[i]);
160 ++i;
161 }
162 }
163 }
164
165 template <typename T>
166 std::optional<T> EvalIntegral(TokenType tp, std::string_view val)
167 {
168 constexpr auto hex_step = [](T acc, char c) { return acc << 4 | ConvertNib<T>(c); };
169 constexpr auto dec_step = [](T acc, char c) { return acc * 10 + (c - '0'); };
170 constexpr auto oct_step = [](T acc, char c) { return acc << 3 | (c - '0'); };
171 constexpr auto bin_step = [](T acc, char c) { return acc << 1 | (c - '0'); };
172
173 switch (tp)
174 {
175 case TokenType::HexadecimalLit:
176 return std::accumulate(val.begin() + 2, val.end(), T{0}, hex_step);
177 case TokenType::DecimalLit:
178 return std::accumulate(val.begin(), val.end(), T{0}, dec_step);
179 case TokenType::OctalLit:
180 return std::accumulate(val.begin() + 1, val.end(), T{0}, oct_step);
181 case TokenType::BinaryLit:
182 return std::accumulate(val.begin() + 2, val.end(), T{0}, bin_step);
183 case TokenType::GPR:
184 if (CaseInsensitiveEquals(val, "sp"))
185 return T{1};
186 if (CaseInsensitiveEquals(val, "rtoc"))
187 return T{2};
188 [[fallthrough]];
189 case TokenType::FPR:
190 return std::accumulate(val.begin() + 1, val.end(), T{0}, dec_step);
191 case TokenType::CRField:
192 return std::accumulate(val.begin() + 2, val.end(), T{0}, dec_step);
193 case TokenType::SPR:
194 return static_cast<T>(*sprg_map.Find(val));
195 case TokenType::Lt:
196 return T{0};
197 case TokenType::Gt:
198 return T{1};
199 case TokenType::Eq:
200 return T{2};
201 case TokenType::So:
202 return T{3};
203 case TokenType::NumLabFwd:
204 case TokenType::NumLabBwd:
205 return std::accumulate(val.begin(), val.end() - 1, T{0}, dec_step);
206 default:
207 return std::nullopt;
208 }
209 }
210 } // namespace
211
212 void ConvertStringLiteral(std::string_view literal, std::vector<u8>* out_vec)
213 {
214 ConvertStringLiteral(literal, std::back_inserter(*out_vec));
215 }
216
217 std::string_view TokenTypeToStr(TokenType tp)
218 {
219 switch (tp)
220 {
221 case TokenType::GPR:
222 return "GPR";
223 case TokenType::FPR:
224 return "FPR";
225 case TokenType::SPR:
226 return "SPR";
227 case TokenType::CRField:
228 return "CR Field";
229 case TokenType::Lt:
230 case TokenType::Gt:
231 case TokenType::Eq:
232 case TokenType::So:
233 return "CR Bit";
234 case TokenType::Identifier:
235 return "Identifier";
236 case TokenType::StringLit:
237 return "String Literal";
238 case TokenType::DecimalLit:
239 return "Decimal Literal";
240 case TokenType::BinaryLit:
241 return "Binary Literal";
242 case TokenType::HexadecimalLit:
243 return "Hexadecimal Literal";
244 case TokenType::OctalLit:
245 return "Octal Literal";
246 case TokenType::FloatLit:
247 return "Float Literal";
248 case TokenType::Invalid:
249 return "Invalid";
250 case TokenType::Lsh:
251 return "<<";
252 case TokenType::Rsh:
253 return ">>";
254 case TokenType::Comma:
255 return ",";
256 case TokenType::Lparen:
257 return "(";
258 case TokenType::Rparen:
259 return ")";
260 case TokenType::Pipe:
261 return "|";
262 case TokenType::Caret:
263 return "^";
264 case TokenType::Ampersand:
265 return "&";
266 case TokenType::Plus:
267 return "+";
268 case TokenType::Minus:
269 return "-";
270 case TokenType::Star:
271 return "*";
272 case TokenType::Slash:
273 return "/";
274 case TokenType::Tilde:
275 return "~";
276 case TokenType::At:
277 return "@";
278 case TokenType::Colon:
279 return ":";
280 case TokenType::Grave:
281 return "`";
282 case TokenType::Dot:
283 return ".";
284 case TokenType::Eof:
285 return "End of File";
286 case TokenType::Eol:
287 return "End of Line";
288 default:
289 return "";
290 }
291 }
292
293 std::string_view AssemblerToken::TypeStr() const
294 {
295 return TokenTypeToStr(token_type);
296 }
297
298 std::string_view AssemblerToken::ValStr() const
299 {
300 switch (token_type)
301 {
302 case TokenType::Eol:
303 return "<EOL>";
304 case TokenType::Eof:
305 return "<EOF>";
306 default:
307 return token_val;
308 }
309 }
310
311 template <>
312 std::optional<float> AssemblerToken::EvalToken() const
313 {
314 if (token_type == TokenType::FloatLit)
315 {
316 return std::stof(std::string(token_val));
317 }
318 return std::nullopt;
319 }
320
321 template <>
322 std::optional<double> AssemblerToken::EvalToken() const
323 {
324 if (token_type == TokenType::FloatLit)
325 {
326 return std::stod(std::string(token_val));
327 }
328 return std::nullopt;
329 }
330
331 template <>
332 std::optional<u8> AssemblerToken::EvalToken() const
333 {
334 return EvalIntegral<u8>(token_type, token_val);
335 }
336
337 template <>
338 std::optional<u16> AssemblerToken::EvalToken() const
339 {
340 return EvalIntegral<u16>(token_type, token_val);
341 }
342
343 template <>
344 std::optional<u32> AssemblerToken::EvalToken() const
345 {
346 return EvalIntegral<u32>(token_type, token_val);
347 }
348
349 template <>
350 std::optional<u64> AssemblerToken::EvalToken() const
351 {
352 return EvalIntegral<u64>(token_type, token_val);
353 }
354
355 size_t Lexer::LineNumber() const
356 {
357 return m_lexed_tokens.empty() ? m_pos.line : TagOf(m_lexed_tokens.front()).line;
358 }
359
360 size_t Lexer::ColNumber() const
361 {
362 return m_lexed_tokens.empty() ? m_pos.col : TagOf(m_lexed_tokens.front()).col;
363 }
364
365 std::string_view Lexer::CurrentLine() const
366 {
367 const size_t line_index =
368 m_lexed_tokens.empty() ? m_pos.index : TagOf(m_lexed_tokens.front()).index;
369 size_t begin_index = line_index == 0 ? 0 : line_index - 1;
370 for (; begin_index > 0; begin_index--)
371 {
372 if (m_lex_string[begin_index] == '\n')
373 {
374 begin_index++;
375 break;
376 }
377 }
378 size_t end_index = begin_index;
379 for (; end_index < m_lex_string.size(); end_index++)
380 {
381 if (m_lex_string[end_index] == '\n')
382 {
383 end_index++;
384 break;
385 }
386 }
387 return m_lex_string.substr(begin_index, end_index - begin_index);
388 }
389
390 void Lexer::SetIdentifierMatchRule(IdentifierMatchRule set)
391 {
392 FeedbackTokens();
393 m_match_rule = set;
394 }
395
396 const Tagged<CursorPosition, AssemblerToken>& Lexer::LookaheadTagRef(size_t num_fwd) const
397 {
398 while (m_lexed_tokens.size() < num_fwd)
399 {
400 LookaheadRef();
401 }
402 return m_lexed_tokens[num_fwd];
403 }
404
405 AssemblerToken Lexer::Lookahead() const
406 {
407 if (m_lexed_tokens.empty())
408 {
409 CursorPosition pos_pre = m_pos;
410 m_lexed_tokens.emplace_back(pos_pre, LexSingle());
411 }
412 return ValueOf(m_lexed_tokens.front());
413 }
414
415 const AssemblerToken& Lexer::LookaheadRef() const
416 {
417 if (m_lexed_tokens.empty())
418 {
419 CursorPosition pos_pre = m_pos;
420 m_lexed_tokens.emplace_back(pos_pre, LexSingle());
421 }
422 return ValueOf(m_lexed_tokens.front());
423 }
424
425 TokenType Lexer::LookaheadType() const
426 {
427 return LookaheadRef().token_type;
428 }
429
430 AssemblerToken Lexer::LookaheadFloat() const
431 {
432 FeedbackTokens();
433 SkipWs();
434
435 CursorPosition pos_pre = m_pos;
436 ScanStart();
437
438 std::optional<std::string_view> failure_reason = RunDfa(float_dfa);
439
440 // Special case: lex at least a single char for no matches for errors to make sense
441 if (m_scan_pos.index == pos_pre.index)
442 {
443 Step();
444 }
445
446 std::string_view tok_str = ScanFinishOut();
447 AssemblerToken tok;
448 if (!failure_reason)
449 {
450 tok = AssemblerToken{
451 TokenType::FloatLit,
452 tok_str,
453 "",
454 Interval{0, 0},
455 };
456 }
457 else
458 {
459 tok = AssemblerToken{
460 TokenType::Invalid,
461 tok_str,
462 *failure_reason,
463 Interval{0, tok_str.length()},
464 };
465 }
466
467 m_lexed_tokens.emplace_back(pos_pre, tok);
468 return tok;
469 }
470
471 void Lexer::Eat()
472 {
473 if (m_lexed_tokens.empty())
474 {
475 LexSingle();
476 }
477 else
478 {
479 m_lexed_tokens.pop_front();
480 }
481 }
482
483 void Lexer::EatAndReset()
484 {
485 Eat();
486 SetIdentifierMatchRule(IdentifierMatchRule::Typical);
487 }
488
489 std::optional<std::string_view> Lexer::RunDfa(std::span<const DfaNode> dfa) const
490 {
491 size_t dfa_index = 0;
492 bool transition_found;
493 do
494 {
495 transition_found = false;
496 if (Peek() == '\0')
497 {
498 break;
499 }
500
501 const DfaNode& n = dfa[dfa_index];
502 for (auto&& edge : n.edges)
503 {
504 if (edge.first(Peek()))
505 {
506 transition_found = true;
507 dfa_index = edge.second;
508 break;
509 }
510 }
511
512 if (transition_found)
513 {
514 Step();
515 }
516 } while (transition_found);
517
518 return dfa[dfa_index].match_failure_reason;
519 }
520
521 void Lexer::SkipWs() const
522 {
523 ScanStart();
524 for (char c = Peek(); std::isspace(c) && c != '\n'; c = Step().Peek())
525 {
526 }
527 if (Peek() == '#')
528 {
529 while (Peek() != '\n' && Peek() != '\0')
530 {
531 Step();
532 }
533 }
534 ScanFinish();
535 }
536
537 void Lexer::FeedbackTokens() const
538 {
539 if (m_lexed_tokens.empty())
540 {
541 return;
542 }
543 m_pos = m_scan_pos = TagOf(m_lexed_tokens.front());
544 m_lexed_tokens.clear();
545 }
546
547 bool Lexer::IdentifierHeadExtra(char h) const
548 {
549 switch (m_match_rule)
550 {
551 case IdentifierMatchRule::Typical:
552 case IdentifierMatchRule::Mnemonic:
553 return false;
554 case IdentifierMatchRule::Directive:
555 return std::isdigit(h);
556 }
557 return false;
558 }
559
560 bool Lexer::IdentifierExtra(char c) const
561 {
562 switch (m_match_rule)
563 {
564 case IdentifierMatchRule::Typical:
565 case IdentifierMatchRule::Directive:
566 return false;
567 case IdentifierMatchRule::Mnemonic:
568 return c == '+' || c == '-' || c == '.';
569 }
570 return false;
571 }
572
573 void Lexer::ScanStart() const
574 {
575 m_scan_pos = m_pos;
576 }
577
578 void Lexer::ScanFinish() const
579 {
580 m_pos = m_scan_pos;
581 }
582
583 std::string_view Lexer::ScanFinishOut() const
584 {
585 const size_t start = m_pos.index;
586 m_pos = m_scan_pos;
587 return m_lex_string.substr(start, m_scan_pos.index - start);
588 }
589
590 char Lexer::Peek() const
591 {
592 if (m_scan_pos.index >= m_lex_string.length())
593 {
594 return 0;
595 }
596 return m_lex_string[m_scan_pos.index];
597 }
598
599 const Lexer& Lexer::Step() const
600 {
601 if (m_scan_pos.index >= m_lex_string.length())
602 {
603 return *this;
604 }
605
606 if (Peek() == '\n')
607 {
608 m_scan_pos.line++;
609 m_scan_pos.col = 0;
610 }
611 else
612 {
613 m_scan_pos.col++;
614 }
615 m_scan_pos.index++;
616 return *this;
617 }
618
619 TokenType Lexer::LexStringLit(std::string_view& invalid_reason, Interval& invalid_region) const
620 {
621 // The open quote has already been matched
622 const size_t string_start = m_scan_pos.index - 1;
623 TokenType token_type = TokenType::StringLit;
624
625 std::optional<std::string_view> failure_reason = RunDfa(string_dfa);
626
627 if (failure_reason)
628 {
629 token_type = TokenType::Invalid;
630 invalid_reason = *failure_reason;
631 invalid_region = Interval{0, m_scan_pos.index - string_start};
632 }
633
634 return token_type;
635 }
636
637 TokenType Lexer::ClassifyAlnum() const
638 {
639 const std::string_view alnum = m_lex_string.substr(m_pos.index, m_scan_pos.index - m_pos.index);
640 constexpr auto valid_regnum = [](std::string_view rn) {
641 if (rn.length() == 1 && std::isdigit(rn[0]))
642 {
643 return true;
644 }
645 else if (rn.length() == 2 && std::isdigit(rn[0]) && std::isdigit(rn[1]))
646 {
647 if (rn[0] == '1' || rn[0] == '2')
648 {
649 return true;
650 }
651
652 if (rn[0] == '3')
653 {
654 return rn[1] < '2';
655 }
656 }
657
658 return false;
659 };
660
661 if (std::tolower(alnum[0]) == 'r' && valid_regnum(alnum.substr(1)))
662 {
663 return TokenType::GPR;
664 }
665 else if ((CaseInsensitiveEquals(alnum, "sp")) || (CaseInsensitiveEquals(alnum, "rtoc")))
666 {
667 return TokenType::GPR;
668 }
669 else if (std::tolower(alnum[0]) == 'f' && valid_regnum(alnum.substr(1)))
670 {
671 return TokenType::FPR;
672 }
673 else if (alnum.length() == 3 && CaseInsensitiveEquals(alnum.substr(0, 2), "cr") &&
674 alnum[2] >= '0' && alnum[2] <= '7')
675 {
676 return TokenType::CRField;
677 }
678 else if (CaseInsensitiveEquals(alnum, "lt"))
679 {
680 return TokenType::Lt;
681 }
682 else if (CaseInsensitiveEquals(alnum, "gt"))
683 {
684 return TokenType::Gt;
685 }
686 else if (CaseInsensitiveEquals(alnum, "eq"))
687 {
688 return TokenType::Eq;
689 }
690 else if (CaseInsensitiveEquals(alnum, "so"))
691 {
692 return TokenType::So;
693 }
694 else if (sprg_map.Find(alnum) != nullptr)
695 {
696 return TokenType::SPR;
697 }
698 return TokenType::Identifier;
699 }
700
701 AssemblerToken Lexer::LexSingle() const
702 {
703 SkipWs();
704
705 ScanStart();
706 const char h = Peek();
707
708 TokenType token_type;
709 std::string_view invalid_reason = "";
710 Interval invalid_region = Interval{0, 0};
711
712 Step();
713
714 if (std::isalpha(h) || h == '_' || IdentifierHeadExtra(h))
715 {
716 for (char c = Peek(); std::isalnum(c) || c == '_' || IdentifierExtra(c); c = Step().Peek())
717 {
718 }
719
720 token_type = ClassifyAlnum();
721 }
722 else if (h == '"')
723 {
724 token_type = LexStringLit(invalid_reason, invalid_region);
725 }
726 else if (h == '0')
727 {
728 const char nextch = Peek();
729
730 if (nextch == 'x')
731 {
732 token_type = TokenType::HexadecimalLit;
733 Step();
734 for (char c = Peek(); std::isxdigit(c); c = Step().Peek())
735 {
736 }
737 }
738 else if (nextch == 'b')
739 {
740 Step();
741 if (!IsBinary(Peek()))
742 {
743 token_type = TokenType::NumLabBwd;
744 }
745 else
746 {
747 token_type = TokenType::BinaryLit;
748 for (char c = Peek(); IsBinary(c); c = Step().Peek())
749 {
750 }
751 }
752 }
753 else if (IsOctal(nextch))
754 {
755 token_type = TokenType::OctalLit;
756 for (char c = Peek(); IsOctal(c); c = Step().Peek())
757 {
758 }
759 }
760 else if (nextch == 'f')
761 {
762 Step();
763 token_type = TokenType::NumLabFwd;
764 }
765 else
766 {
767 token_type = TokenType::DecimalLit;
768 }
769 }
770 else if (std::isdigit(h))
771 {
772 for (char c = Peek(); std::isdigit(c); c = Step().Peek())
773 {
774 }
775 switch (Peek())
776 {
777 case 'f':
778 token_type = TokenType::NumLabFwd;
779 Step();
780 break;
781
782 case 'b':
783 token_type = TokenType::NumLabBwd;
784 Step();
785 break;
786
787 default:
788 token_type = TokenType::DecimalLit;
789 break;
790 }
791 }
792 else if (h == '<' || h == '>')
793 {
794 // Special case for two-character operators
795 const char second_ch = Peek();
796 if (second_ch == h)
797 {
798 Step();
799 token_type = second_ch == '<' ? TokenType::Lsh : TokenType::Rsh;
800 }
801 else
802 {
803 token_type = TokenType::Invalid;
804 invalid_reason = "Unrecognized character";
805 invalid_region = Interval{0, 1};
806 }
807 }
808 else
809 {
810 token_type = SingleCharToken(h);
811 if (token_type == TokenType::Invalid)
812 {
813 invalid_reason = "Unrecognized character";
814 invalid_region = Interval{0, 1};
815 }
816 }
817
818 AssemblerToken new_tok = {token_type, ScanFinishOut(), invalid_reason, invalid_region};
819 SkipWs();
820 return new_tok;
821 }
822 } // namespace Common::GekkoAssembler::detail