| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543 |
- using System.Runtime.CompilerServices;
- using Lua.Internal;
- namespace Lua.CodeAnalysis.Syntax;
- public ref struct Lexer
- {
- public required ReadOnlyMemory<char> Source { get; init; }
- public string? ChunkName { get; init; }
- SyntaxToken current;
- SourcePosition position = new(1, 0);
- int offset;
- public Lexer()
- {
- }
- public readonly SyntaxToken Current => current;
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- void Advance(int count)
- {
- var span = Source.Span;
- for (int i = 0; i < count; i++)
- {
- if (offset >= span.Length)
- {
- LuaParseException.SyntaxError(ChunkName, position, null);
- }
- var c = span[offset];
- offset++;
- var isLF = c is '\n';
- var isCR = c is '\r' && (span.Length == offset || span[offset] is not '\n');
- if (isLF || isCR)
- {
- position.Column = 0;
- position.Line++;
- }
- else
- {
- position.Column++;
- }
- }
- }
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- bool TryRead(int offset, out char value)
- {
- if (Source.Length <= offset)
- {
- value = default;
- return false;
- }
- value = Source.Span[offset];
- return true;
- }
- public bool MoveNext()
- {
- if (Source.Length <= offset) return false;
- var span = Source.Span;
- var startOffset = offset;
- var position = this.position;
- var c1 = span[offset];
- Advance(1);
- var c2 = span.Length == offset ? char.MinValue : span[offset];
- switch (c1)
- {
- case ' ':
- case '\t':
- return MoveNext();
- case '\n':
- current = SyntaxToken.EndOfLine(position);
- return true;
- case '\r':
- if (c2 == '\n') Advance(1);
- current = SyntaxToken.EndOfLine(position);
- return true;
- case '(':
- current = SyntaxToken.LParen(position);
- return true;
- case ')':
- current = SyntaxToken.RParen(position);
- return true;
- case '{':
- current = SyntaxToken.LCurly(position);
- return true;
- case '}':
- current = SyntaxToken.RCurly(position);
- return true;
- case ']':
- current = SyntaxToken.RSquare(position);
- return true;
- case '+':
- current = SyntaxToken.Addition(position);
- return true;
- case '-':
- // comment
- if (c2 == '-')
- {
- var pos = position;
- Advance(1);
- // block comment
- if (span.Length > offset + 1 && span[offset] is '[' && span[offset + 1] is '[' or '=')
- {
- Advance(1);
- (_, _, var isTerminated) = ReadUntilLongBracketEnd(ref span);
- if (!isTerminated) LuaParseException.UnfinishedLongComment(ChunkName, pos);
- }
- else // line comment
- {
- ReadUntilEOL(ref span, ref offset, out _);
- }
- return MoveNext();
- }
- else
- {
- current = SyntaxToken.Subtraction(position);
- return true;
- }
- case '*':
- current = SyntaxToken.Multiplication(position);
- return true;
- case '/':
- current = SyntaxToken.Division(position);
- return true;
- case '%':
- current = SyntaxToken.Modulo(position);
- return true;
- case '^':
- current = SyntaxToken.Exponentiation(position);
- return true;
- case '=':
- if (c2 == '=')
- {
- current = SyntaxToken.Equality(position);
- Advance(1);
- }
- else
- {
- current = SyntaxToken.Assignment(position);
- }
- return true;
- case '~':
- if (c2 == '=')
- {
- current = SyntaxToken.Inequality(position);
- Advance(1);
- }
- else
- {
- throw new LuaParseException(ChunkName, position, $"error: Invalid '~' token");
- }
- return true;
- case '>':
- if (c2 == '=')
- {
- current = SyntaxToken.GreaterThanOrEqual(position);
- Advance(1);
- }
- else
- {
- current = SyntaxToken.GreaterThan(position);
- }
- return true;
- case '<':
- if (c2 == '=')
- {
- current = SyntaxToken.LessThanOrEqual(position);
- Advance(1);
- }
- else
- {
- current = SyntaxToken.LessThan(position);
- }
- return true;
- case '.':
- if (c2 == '.')
- {
- var c3 = span.Length == (offset + 1) ? char.MinValue : span[offset + 1];
- if (c3 == '.')
- {
- // vararg
- current = SyntaxToken.VarArg(position);
- Advance(2);
- }
- else
- {
- // concat
- current = SyntaxToken.Concat(position);
- Advance(1);
- }
- return true;
- }
- if (!StringHelper.IsNumber(c2))
- {
- current = SyntaxToken.Dot(position);
- return true;
- }
- break;
- case '#':
- current = SyntaxToken.Length(position);
- return true;
- case ',':
- current = SyntaxToken.Comma(position);
- return true;
- case ';':
- current = SyntaxToken.SemiColon(position);
- return true;
- }
- // numeric literal
- if (c1 is '.' || StringHelper.IsNumber(c1))
- {
- if (c1 is '0' && c2 is 'x' or 'X') // hex 0x
- {
- Advance(1);
- if (span[offset] is '.') Advance(1);
- ReadDigit(ref span, ref offset, out var readCount);
- if (span.Length > offset && span[offset] is '.')
- {
- Advance(1);
- ReadDigit(ref span, ref offset, out _);
- }
- if (span.Length > offset && span[offset] is 'p' or 'P')
- {
- Advance(1);
- if (span[offset] is '-' or '+') Advance(1);
- ReadDigit(ref span, ref offset, out _);
- }
- if (readCount == 0)
- {
- throw new LuaParseException(ChunkName, this.position, $"error: Illegal hexadecimal number");
- }
- }
- else
- {
- ReadNumber(ref span, ref offset, out _);
- if (span.Length > offset && span[offset] is '.')
- {
- Advance(1);
- ReadNumber(ref span, ref offset, out _);
- }
- if (span.Length > offset && span[offset] is 'e' or 'E')
- {
- Advance(1);
- if (span[offset] is '-' or '+') Advance(1);
- ReadNumber(ref span, ref offset, out _);
- }
- }
- current = new(SyntaxTokenType.Number, Source[startOffset..offset], position);
- return true;
- }
- // label
- if (c1 is ':')
- {
- if (c2 is ':')
- {
- var stringStartOffset = offset + 1;
- Advance(2);
- var prevC = char.MinValue;
- while (span.Length > offset)
- {
- var c = span[offset];
- if (prevC == ':' && c == ':') break;
- Advance(1);
- prevC = c;
- }
- current = SyntaxToken.Label(Source[stringStartOffset..(offset - 1)], position);
- Advance(1);
- }
- else
- {
- current = SyntaxToken.Colon(position);
- }
- return true;
- }
- // short string literal
- if (c1 is '"' or '\'')
- {
- var quote = c1;
- var stringStartOffset = offset;
- var isTerminated = false;
- while (span.Length > offset)
- {
- var c = span[offset];
- if (c is '\n' or '\r')
- {
- break;
- }
- if (c is '\\')
- {
- Advance(1);
- if (span.Length <= offset) break;
- if (span[offset] == '\r')
- {
- if (span.Length<=offset +1) continue;
- if (span[offset+1] == '\n')Advance(1);
- }
- }
- else if (c == quote)
- {
- isTerminated = true;
- break;
- }
- Advance(1);
- }
- if (!isTerminated)
- {
- throw new LuaParseException(ChunkName, this.position, "error: Unterminated string");
- }
- current = SyntaxToken.String(Source[stringStartOffset..offset], position);
- Advance(1);
- return true;
- }
- // long string literal
- if (c1 is '[')
- {
- if (c2 is '[' or '=')
- {
- (var start, var end, var isTerminated) = ReadUntilLongBracketEnd(ref span);
- if (!isTerminated)
- {
- throw new LuaParseException(ChunkName, this.position, "error: Unterminated string");
- }
- current = SyntaxToken.RawString(Source[start..end], position);
- return true;
- }
- else
- {
- current = SyntaxToken.LSquare(position);
- return true;
- }
- }
- // identifier
- if (IsIdentifier(c1))
- {
- while (span.Length > offset && IsIdentifier(span[offset]))
- {
- Advance(1);
- }
- var identifier = Source[startOffset..offset];
- current = identifier.Span switch
- {
- Keywords.Nil => SyntaxToken.Nil(position),
- Keywords.True => SyntaxToken.True(position),
- Keywords.False => SyntaxToken.False(position),
- Keywords.And => SyntaxToken.And(position),
- Keywords.Or => SyntaxToken.Or(position),
- Keywords.Not => SyntaxToken.Not(position),
- Keywords.End => SyntaxToken.End(position),
- Keywords.Then => SyntaxToken.Then(position),
- Keywords.If => SyntaxToken.If(position),
- Keywords.ElseIf => SyntaxToken.ElseIf(position),
- Keywords.Else => SyntaxToken.Else(position),
- Keywords.Local => SyntaxToken.Local(position),
- Keywords.Return => SyntaxToken.Return(position),
- Keywords.Goto => SyntaxToken.Goto(position),
- Keywords.Do => SyntaxToken.Do(position),
- Keywords.In => SyntaxToken.In(position),
- Keywords.While => SyntaxToken.While(position),
- Keywords.Repeat => SyntaxToken.Repeat(position),
- Keywords.For => SyntaxToken.For(position),
- Keywords.Until => SyntaxToken.Until(position),
- Keywords.Break => SyntaxToken.Break(position),
- Keywords.Function => SyntaxToken.Function(position),
- _ => new(SyntaxTokenType.Identifier, identifier, position),
- };
- return true;
- }
- throw new LuaParseException(ChunkName, position, $"unexpected symbol near '{c1}'");
- }
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- void ReadUntilEOL(ref ReadOnlySpan<char> span, ref int offset, out int readCount)
- {
- readCount = 0;
- var flag = true;
- while (flag)
- {
- if (span.Length <= offset) return;
- var c1 = span[offset];
- if (c1 is '\n')
- {
- flag = false;
- }
- else if (c1 is '\r')
- {
- var c2 = span.Length == offset + 1 ? char.MinValue : span[offset + 1];
- if (c2 is '\n')
- {
- Advance(1);
- readCount++;
- }
- flag = false;
- }
- Advance(1);
- readCount++;
- }
- }
- (int Start, int End, bool IsTerminated) ReadUntilLongBracketEnd(ref ReadOnlySpan<char> span)
- {
- var c = span[offset];
- var level = 0;
- while (c is '=')
- {
- level++;
- Advance(1);
- c = span[offset];
- }
- Advance(1);
- var startOffset = offset;
- var endOffset = 0;
- var isTerminated = false;
- var prevC = char.MinValue;
- while (span.Length > offset + level + 1)
- {
- var current = span[offset];
- // skip first newline
- if (offset == startOffset)
- {
- if (current == '\r')
- {
- startOffset += 2;
- Advance(span[offset + 1] == '\n' ? 2 : 1);
- continue;
- }
- else if (current == '\n')
- {
- startOffset++;
- Advance(1);
- continue;
- }
- }
- if (current is ']' && prevC is not '\\')
- {
- endOffset = offset;
- for (int i = 1; i <= level; i++)
- {
- if (span[offset + i] is not '=') goto CONTINUE;
- }
- if (span[offset + level + 1] is not ']') goto CONTINUE;
- Advance(level + 2);
- isTerminated = true;
- break;
- }
- CONTINUE:
- prevC = current;
- Advance(1);
- }
- return (startOffset, endOffset, isTerminated);
- }
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- void ReadDigit(ref ReadOnlySpan<char> span, ref int offset, out int readCount)
- {
- readCount = 0;
- while (span.Length > offset && StringHelper.IsDigit(span[offset]))
- {
- Advance(1);
- readCount++;
- }
- }
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- void ReadNumber(ref ReadOnlySpan<char> span, ref int offset, out int readCount)
- {
- readCount = 0;
- while (span.Length > offset && StringHelper.IsNumber(span[offset]))
- {
- Advance(1);
- readCount++;
- }
- }
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- static bool IsIdentifier(char c)
- {
- return c == '_' ||
- ('A' <= c && c <= 'Z') ||
- ('a' <= c && c <= 'z') ||
- StringHelper.IsNumber(c);
- }
- }
|