picceler
Loading...
Searching...
No Matches
lexer.h
Go to the documentation of this file.
1
8
9#pragma once
10
11#include <cstdint>
12#include <fstream>
13#include <ostream>
14#include <string>
15#include <utility>
16#include <vector>
17#include <expected>
18
19#include "error.h"
20
21namespace picceler {
22
27struct Token {
29 enum class Type : size_t { IDENTIFIER, NUMBER, STRING, SYMBOL, EOF_TOKEN, UNKNOWN };
30
35 std::string typeToString() const;
36
41 std::string toString() const {
42 return std::format("Token(type: {}, value: '{}', line: {}, column: {})", typeToString(), _value, _line, _column);
43 }
44
46 std::string _value;
47 size_t _line;
48 size_t _column;
49};
50
55class Lexer {
56public:
60 Lexer();
61
66 Result<void> setSource(const std::string &source);
67
73
79
83 void skipWhitespace();
84
90
91private:
95 bool eof() const;
96
100 char peek() const;
101
105 char get();
106
112
113 bool isIdentifier(char ch) const;
119 bool isSymbol(char ch) const;
120
126 Result<Token> readIdentifier(std::pair<size_t, size_t> start);
127
133 Result<Token> readNumber(std::pair<size_t, size_t> start);
134
140 Result<Token> readString(std::pair<size_t, size_t> start);
141
147 Result<Token> readSymbol(std::pair<size_t, size_t> start);
148
149private:
150 std::ifstream _file;
151 std::string _buffer;
152 size_t _position;
153 size_t _line;
154 size_t _column;
155};
156
163std::ostream &operator<<(std::ostream &os, const Token &token);
164
165} // namespace picceler
Lexer()
Constructs a Lexer.
Definition lexer.cpp:30
Result< void > setSource(const std::string &source)
Sets the source file for the lexer.
Definition lexer.cpp:32
Result< Token > peekToken()
Returns the next token without advancing the input.
Definition lexer.cpp:75
Result< Token > nextToken()
Returns the next token from the input.
Definition lexer.cpp:49
void skipWhitespace()
Skips whitespace characters in the input.
Definition lexer.cpp:86
Result< std::vector< Token > > tokenizeAll()
Tokenizes the entire input.
Definition lexer.cpp:92
Definition ast.h:11
std::expected< T, CompileError > Result
Definition error.h:33
std::ostream & operator<<(std::ostream &os, const Token &token)
Outputs a token to the given output stream.
Definition lexer.cpp:181
Represents a token produced by the lexer.
Definition lexer.h:27
std::string _value
Definition lexer.h:46
std::string typeToString() const
Converts the token type to a string representation.
Definition lexer.cpp:10
std::string toString() const
Converts the token to a string representation.
Definition lexer.h:41
Type
The type of the token.
Definition lexer.h:29
@ NUMBER
Definition lexer.h:29
@ STRING
Definition lexer.h:29
@ UNKNOWN
Definition lexer.h:29
@ IDENTIFIER
Definition lexer.h:29
@ EOF_TOKEN
Definition lexer.h:29
@ SYMBOL
Definition lexer.h:29
size_t _line
Definition lexer.h:47
size_t _column
Definition lexer.h:48
Type _type
Definition lexer.h:45