cpp-programming

Simple C++ programs
git clone git://git.laack.co/cpp-programming.git
Log | Files | Refs | README

commit 7f61fcc2adcf4823a9325adb3031b23e6542f5a0
parent a5b70ff5ec49e8926f5eea753b938153bae552b5
Author: Andrew Laack <andrew@laack.co>
Date:   Wed, 21 Oct 2026 11:51:30 -0500

Handle keywords + identifiers

Diffstat:
Mlox/main.lox | 9++++++++-
Mlox/scanner.cpp | 53++++++++++++++++++++++++++++++++++++++++++++++++-----
Mlox/stub.cpp | 1+
3 files changed, 57 insertions(+), 6 deletions(-)

diff --git a/lox/main.lox b/lox/main.lox @@ -1 +1,8 @@ -2."test" +var something = "some value" +if(something == "some value") { + print something +} else { + print "what" +} +var nm = 10.10"this""is""a""test" "123" "456" +var nm = 10.10.101.1.13.2 diff --git a/lox/scanner.cpp b/lox/scanner.cpp @@ -46,9 +46,19 @@ class Scanner { bool isDigit() { return (peek() <= '9' && peek() >= '0'); } + char doublePeek() { + if(current + 1 < source.size()) { + return source[current+1]; + } + return '\0'; + } bool isDigit(char ch) { return (ch <= '9' && ch >= '0'); } + + bool isAlpha(char ch) { + return ( (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch == '_') ); + } bool match(char c) { if(source.size() > current) { @@ -60,25 +70,56 @@ class Scanner { } return false; } + + std::unordered_map<std::string, TokenType> idLookup { + {"and", TokenType::AND}, + {"class",TokenType::CLASS}, + {"else",TokenType::ELSE}, + {"false",TokenType::FALSE}, + {"for",TokenType::FOR}, + {"fun",TokenType::FUN}, + {"if",TokenType::IF}, + {"nil",TokenType::NIL}, + {"or",TokenType::OR}, + {"print",TokenType::PRINT}, + {"return",TokenType:: RETURN}, + {"super",TokenType::SUPER}, + {"this",TokenType::THIS}, + {"true",TokenType::TRUE}, + {"var",TokenType::VAR}, + {"while",TokenType::WHILE} + }; + + void identifier() { + std::string acc = ""; + acc += source[current-1]; + while (isAlpha(peek())) { + char ch = advance(); + acc += ch; + } + + if(idLookup.find(acc) == idLookup.end()) { + addToken(TokenType::IDENTIFIER); + } else { + addToken(idLookup[acc]); + } + } void number() { - std::string numStr = ""; - numStr += source[current-1]; - char ch = peek(); bool firstDot = false; - while(isDigit() || (ch == '.' && !firstDot && isDigit(peek()))) { + while(isDigit() || (peek() == '.' && !firstDot && isDigit(doublePeek()))) { if(ch == '.') { firstDot = true; } - numStr += ch; if(current < source.size()) { ch = advance(); } else { break; // eof } } + std::string numStr = source.substr(start,current-start); double res = std::stod(numStr); Literal lit = Literal("", res, false); addToken(TokenType::NUMBER,lit); @@ -203,6 +244,8 @@ class Scanner { default: if(isDigit(c)) { number(); + } else if(isAlpha(c)) { + identifier(); } else { lRef->error(line, "Unexpected character."); } diff --git a/lox/stub.cpp b/lox/stub.cpp @@ -1,4 +1,5 @@ #include <stdio.h> +#include <unordered_map> #include <iostream> #include <fstream> #include <filesystem>