Serenity Operating System
at portability 100 lines 3.0 kB view raw
1/* 2 * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org> 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 <AK/StringView.h> 30#include <AK/Vector.h> 31 32namespace GUI { 33 34#define FOR_EACH_TOKEN_TYPE \ 35 __TOKEN(Unknown) \ 36 __TOKEN(Whitespace) \ 37 __TOKEN(PreprocessorStatement) \ 38 __TOKEN(LeftParen) \ 39 __TOKEN(RightParen) \ 40 __TOKEN(LeftCurly) \ 41 __TOKEN(RightCurly) \ 42 __TOKEN(LeftBracket) \ 43 __TOKEN(RightBracket) \ 44 __TOKEN(Comma) \ 45 __TOKEN(Asterisk) \ 46 __TOKEN(Semicolon) \ 47 __TOKEN(DoubleQuotedString) \ 48 __TOKEN(SingleQuotedString) \ 49 __TOKEN(Comment) \ 50 __TOKEN(Number) \ 51 __TOKEN(Keyword) \ 52 __TOKEN(KnownType) \ 53 __TOKEN(Identifier) 54 55struct CppPosition { 56 size_t line; 57 size_t column; 58}; 59 60struct CppToken { 61 enum class Type { 62#define __TOKEN(x) x, 63 FOR_EACH_TOKEN_TYPE 64#undef __TOKEN 65 }; 66 67 const char* to_string() const 68 { 69 switch (m_type) { 70#define __TOKEN(x) \ 71 case Type::x: \ 72 return #x; 73 FOR_EACH_TOKEN_TYPE 74#undef __TOKEN 75 } 76 ASSERT_NOT_REACHED(); 77 } 78 79 Type m_type { Type::Unknown }; 80 CppPosition m_start; 81 CppPosition m_end; 82}; 83 84class CppLexer { 85public: 86 CppLexer(const StringView&); 87 88 Vector<CppToken> lex(); 89 90private: 91 char peek(size_t offset = 0) const; 92 char consume(); 93 94 StringView m_input; 95 size_t m_index { 0 }; 96 CppPosition m_previous_position { 0, 0 }; 97 CppPosition m_position { 0, 0 }; 98}; 99 100}