Website Summary Files Commits Branches @commit @diff @stats
path: root / homework / 81709 / JSCompiler.Core / Lexer.cs
blob: 18df99808907b00bb660d03133df2796f6ef739d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
using JSCompiler.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JSCompiler.Core
{
    public class Lexer
    {
        public static readonly string UNCLOSED_MULTILINE_COMMENT = "Unclosed mulitline comment";

        public static readonly string UNCLOSED_STRING = "Unclosed string";

        public static readonly string UNCLOSED_STRING_NEWLINE = "Unclosed string newline";

        public static readonly string UNIDENTIFIED_SYMBOL = "Unidentified symbol";


        private Dictionary<string, TokenType> keywords;

        private Dictionary<string, TokenType> otherReserved;

        private IInputStream stream;

        public Lexer(IInputStream stream)
        {
            this.stream = stream;
            this.keywords = ReservedStrings.KeywordsAsMap();
            this.otherReserved = ReservedStrings.OthersAsMap();
        }

        public List<Token> Tokenize(Action<int, string> onError)
        {
            List<Token> tokens = new List<Token>();
            do
            {
                Token next = NextToken(onError);
                if(next.Type != TokenType.Skip)
                {
                    tokens.Add(next);
                }
            } while (!stream.IsEndOfStream());
            tokens.Add(new Token(TokenType.EOF));
            return tokens;
        }

        public Token NextToken(Action<int, string> onError)
        {
            char cur = stream.Next();

            if (Utils.IsCarriageReturn(cur))
                return new Token(TokenType.Skip);

            if (Utils.IsWhiteSpace(cur))
                return new Token(TokenType.Whitespace);

            if (Utils.IsTab(cur))
                return new Token(TokenType.Tab);

            if (Utils.IsNewLine(cur))
                return new Token(TokenType.NewLine);

            switch (cur)
            {
                case '=':
                    return Match('=') ? Match('=') ? new WordToken("===", TokenType.StrictEqual)
                        : new WordToken("==", TokenType.EqualEqual)
                        : new Token(TokenType.Equal);
                case '!':
                    return Match('=') ? Match('=') ? new WordToken("!==", TokenType.StrictNotEqual)
                        : new WordToken("!=", TokenType.NotEqual)
                        : new Token(TokenType.Bang);
                case '>':
                    return Match('=') ? new WordToken(">=", TokenType.GreaterEqual)
                        : Match('>') ? Match('=') ? new WordToken(">>=", TokenType.RightShiftEqual)
                        : new WordToken(">>", TokenType.RightShift)
                        : new Token(TokenType.Greater);
                case '<':
                    return Match('=') ? new WordToken("<=", TokenType.LessEqual)
                        : Match('<') ? Match('=') ? new WordToken("<<=", TokenType.LeftShiftEqual)
                        : new WordToken("<<", TokenType.LeftShift)
                        : new Token(TokenType.Less);
                case '+':
                    return Match('+') ? new WordToken("++", TokenType.PlusPlus)
                        : Match('=') ? new WordToken("+=", TokenType.PlusEqual)
                        : new Token(TokenType.Plus);
                case '-':
                    return Match('-') ? new WordToken("--", TokenType.MinusMinus)
                         : Match('=') ? new WordToken("-=", TokenType.MinusEqual)
                         : new Token(TokenType.Minus);
                case '*':
                    return Match('=') ? new WordToken("*=", TokenType.StarEqual)
                        : new Token(TokenType.Star);
                case '/':
                    return Match('/') ? ParseOneLineComment()
                        : Match('*') ? ParseMultilineToken(onError)
                        : Match('=') ? new WordToken("/=", TokenType.DivideEqual)
                        : new Token(TokenType.Division);
                case '%':
                    return Match('=') ? new WordToken("%=", TokenType.ModuloEqual)
                        : new Token(TokenType.Modulo);
                case '^':
                    return Match('=') ? new WordToken("^=", TokenType.BitwiseXorEqual)
                        : new Token(TokenType.BitwiseXor);
                case '|':
                    return Match('=') ? new WordToken("|=", TokenType.BitwiseOrEqual)
                        : Match('|') ? new WordToken("||", TokenType.LogicalOr)
                        : new Token(TokenType.BitwiseOr);
                case '&':
                    return Match('=') ? new WordToken("&=", TokenType.BitwiseAndEqual)
                        : Match('&') ? new WordToken("&&", TokenType.LogicalAnd)
                        : new Token(TokenType.BitwiseAnd);
                default:
                    break;
            }

            if (cur < 127 && Enum.IsDefined(typeof(TokenType), (int)cur))
                return new Token((TokenType)cur);

            if(Utils.IsStringSingleQuote(cur) || Utils.IsStringDoubleQuote(cur))
            {
                return ParseSingleQuoteString(cur, onError);
            }

            if (char.IsDigit(cur))
            {
                return ParseNumber(cur);
            }

            if (char.IsLetter(cur))
            {
                return ParseReservedOrIdentifier(cur);
            }

            onError(stream.Line, UNIDENTIFIED_SYMBOL);
            return new WordToken(cur.ToString(), TokenType.Error);
        }

        private bool Match(char ch)
        {
            if(stream.Peek() == ch)
            {
                stream.Next();
                return true;
            }
            return false;
        }

        private Token ParseOneLineComment()
        {
            string lexeme = "//";
            char peek = stream.Peek();
            while(!Utils.IsNewLine(peek) && !Utils.IsCarriageReturn(peek) && !stream.IsEndOfStream())
            {
                lexeme += stream.Next();
                peek = stream.Peek();
            }
            return new WordToken(lexeme, TokenType.Comment);
        }

        private Token ParseMultilineToken(Action<int, string> onError)
        {
            string lexeme = "/*";
            int lineBeg = stream.Line + 1;
            while (!stream.IsEndOfStream())
            {
                while (stream.Peek() != '*')
                {
                    if (stream.IsEndOfStream())
                    {
                        onError(lineBeg, UNCLOSED_MULTILINE_COMMENT);
                        return new WordToken(lexeme, TokenType.Comment);
                    }

                    lexeme += stream.Next();
                };
                lexeme += stream.Next();
                if (stream.Peek() == '/')
                {
                    lexeme += stream.Next();
                    return new WordToken(lexeme, TokenType.Comment);
                }
            }
            onError(lineBeg, UNCLOSED_MULTILINE_COMMENT);
            return new WordToken(lexeme, TokenType.Comment);
        }
       
        private Token ParseSingleQuoteString(char quote, Action<int, string> onError)
        {
            string lexeme = "" + quote;
            int startLine = stream.Line + 1;
            char peek = stream.Peek();
            while(peek != quote)
            {
                if (Utils.IsNewLine(peek) || Utils.IsCarriageReturn(peek))
                {
                    onError(startLine, UNCLOSED_STRING_NEWLINE);
                    return new WordToken(lexeme, TokenType.Error);
                }

                if (stream.IsEndOfStream())
                {
                    onError(startLine, UNCLOSED_STRING);
                    return new WordToken(lexeme, TokenType.Error);
                }

                lexeme += peek;
                stream.Next();

                if(peek == '\\')
                {
                    char next = stream.Peek();

                    if (next == quote || next == '\\')
                    {
                        lexeme += next;
                        stream.Next();
                    }
                    else
                    {
                        if (Utils.IsCarriageReturn(next)) //Skip Carriage return
                        {
                            lexeme += stream.Next();
                            next = stream.Peek();
                        }
                        if (Utils.IsNewLine(next))
                        {
                            lexeme += stream.Next();
                        }
                    }
                }

                peek = stream.Peek();
            }

            lexeme += stream.Next();
            return new WordToken(lexeme, TokenType.String);
        }

        private Token ParseNumber(char cur)
        {
            long num = cur - '0';
            char peek = stream.Peek();
            while (char.IsDigit(peek) && !stream.IsEndOfStream())
            {
                num = num * 10 + (stream.Next() - '0');
                peek = stream.Peek();
            }
            return new NumToken(num);
        }

        private Token ParseReservedOrIdentifier(char ch)
        {
            string lexeme = "" + ch;

            while (char.IsLetterOrDigit(stream.Peek()) && !stream.IsEndOfStream())
            {
                lexeme += stream.Next();
            }

            TokenType reservedType;

            keywords.TryGetValue(lexeme, out reservedType);
            if(reservedType != 0)
                return new WordToken(lexeme, reservedType);

            otherReserved.TryGetValue(lexeme, out reservedType);
            if(reservedType != 0)
                return new WordToken(lexeme, reservedType);

            return new WordToken(lexeme, TokenType.Identifier);
        }
    }
}