Serenity Operating System
1/*
2 * Copyright (c) 2020, Stephan Unverwerth <s.unverwerth@gmx.de>
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 *
8 * 1. Redistributions of source code must retain the above copyright notice, this
9 * list of conditions and the following disclaimer.
10 *
11 * 2. Redistributions in binary form must reproduce the above copyright notice,
12 * this list of conditions and the following disclaimer in the documentation
13 * and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
16 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
18 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
21 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
22 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
23 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
27#pragma once
28
29#include "Token.h"
30
31#include <AK/HashMap.h>
32#include <AK/String.h>
33#include <AK/StringView.h>
34
35namespace JS {
36
37class Lexer {
38public:
39 explicit Lexer(StringView source);
40 Lexer(StringView source, bool log_errors)
41 : Lexer(source)
42 {
43 m_log_errors = log_errors;
44 }
45
46 Token next();
47 bool has_errors() const { return m_has_errors; }
48
49private:
50 void consume();
51 void consume_exponent();
52 bool is_eof() const;
53 bool is_identifier_start() const;
54 bool is_identifier_middle() const;
55 bool is_line_comment_start() const;
56 bool is_block_comment_start() const;
57 bool is_block_comment_end() const;
58 bool is_numeric_literal_start() const;
59
60 void syntax_error(const char*);
61
62 StringView m_source;
63 size_t m_position = 0;
64 Token m_current_token;
65 int m_current_char = 0;
66 bool m_has_errors = false;
67 size_t m_line_number = 1;
68 size_t m_line_column = 1;
69 bool m_log_errors = true;
70
71 static HashMap<String, TokenType> s_keywords;
72 static HashMap<String, TokenType> s_three_char_tokens;
73 static HashMap<String, TokenType> s_two_char_tokens;
74 static HashMap<char, TokenType> s_single_char_tokens;
75};
76
77}