1#include "gsc/scanner.hpp"
2#include "gsc/error.hpp"
4bool isDigit(
const char c) {
return c >=
'0' && c <=
'9'; }
7 return (c >=
'a' && c <=
'z') || (c >=
'A' && c <=
'Z') || c ==
'_';
12void Scanner::addToken(TokenType type) { addToken(type,
nullptr); }
14void Scanner::addToken(TokenType type, std::any literal) {
15 std::string text{program.substr(start, current - start)};
16 tokens.emplace_back(type, std::move(text), std::move(literal), line);
19void Scanner::scanToken() {
27 addToken(RIGHT_PAREN);
33 addToken(RIGHT_BRACE);
48 addToken(match(
'=') ? BANG_EQUAL : BANG);
51 addToken(match(
'=') ? EQUAL_EQUAL : EQUAL);
54 addToken(match(
'=') ? LESS_EQUAL : LESS);
57 addToken(match(
'=') ? GREATER_EQUAL : GREATER);
63 while (peek() !=
'\n' && !isAtEnd())
88 }
else if (isAlpha(c)) {
92 error(line,
"Unexpected character.");
98void Scanner::identifier() {
99 while (isAlphaNumeric(peek())) {
103 std::string text = std::string{program.substr(start, current - start)};
105 TokenType type = keywords.count(text) ? keywords.at(text) : IDENTIFIER;
109void Scanner::number() {
110 while (isDigit(peek())) {
115 std::stoi(std::string{program.substr(start, current - start)});
116 addToken(NUMBER, numberLiteral);
119void Scanner::string() {
120 while (peek() !=
'"' && !isAtEnd()) {
128 error(line,
"Unterminated string.");
134 std::string word{program.substr(start + 1, current - start - 2)};
135 addToken(STRING, std::move(word));
138bool Scanner::match(
const char &expected) {
139 if (isAtEnd() || program[current] != expected) {
147char Scanner::peek()
const {
151 return program[current];
154char Scanner::peekNext()
const {
155 if (current + 1 >=
static_cast<
int>(program.size())) {
158 return program[current + 1];
161bool Scanner::isAtEnd()
const {
162 return current >=
static_cast<
int>(program.size());
165char Scanner::advance() {
return program[current++]; }
167Scanner::Scanner(std::string_view program) : program{program} {
171void Scanner::scanTokens() {
177 tokens.emplace_back(END_OF_FILE,
"",
nullptr, line);
180std::vector<Token> Scanner::getTokens()
const {
return tokens; }
bool isDigit(const char c)
bool isAlpha(const char c)
bool isAlphaNumeric(const char c)