[Init&Scanning] - Chapter 4 follow up
- Chapter 4 follow up from the "crafting interpreters" book - Changing the package name ``com.craftinginterpreters.lox`` to ``com.lox``
This commit is contained in:
commit
1d38acda73
24
.gitignore
vendored
Normal file
24
.gitignore
vendored
Normal file
@ -0,0 +1,24 @@
|
||||
# Compiled class file
|
||||
*.class
|
||||
|
||||
# Log file
|
||||
*.log
|
||||
|
||||
# BlueJ files
|
||||
*.ctxt
|
||||
|
||||
# Mobile Tools for Java (J2ME)
|
||||
.mtj.tmp/
|
||||
|
||||
# Package Files #
|
||||
*.jar
|
||||
*.war
|
||||
*.nar
|
||||
*.ear
|
||||
*.zip
|
||||
*.tar.gz
|
||||
*.rar
|
||||
out/
|
||||
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
|
||||
hs_err_pid*
|
||||
replay_pid*
|
2
README.md
Normal file
2
README.md
Normal file
@ -0,0 +1,2 @@
|
||||
# jlox: the lox java implementation follow up from CraftingInterpreters
|
||||
The java implementation for the lox language from the reading of Crafting Interpreters
|
9
run.sh
Executable file
9
run.sh
Executable file
@ -0,0 +1,9 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Compile
|
||||
javac -d out src/com/lox/*.java
|
||||
|
||||
# Run
|
||||
|
||||
java -cp out com.lox.Lox
|
||||
|
13
shell.nix
Normal file
13
shell.nix
Normal file
@ -0,0 +1,13 @@
|
||||
{ pkgs ? import <nixpkgs> {} }:
|
||||
|
||||
pkgs.mkShell {
|
||||
buildInputs = [
|
||||
pkgs.openjdk
|
||||
];
|
||||
|
||||
shellHook = ''
|
||||
chmod +x run.sh
|
||||
echo "Java environment is ready. You can now compile and run your Java programs."
|
||||
'';
|
||||
}
|
||||
|
62
src/com/lox/Lox.java
Normal file
62
src/com/lox/Lox.java
Normal file
@ -0,0 +1,62 @@
|
||||
package com.lox;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.List;
|
||||
|
||||
public class Lox {
|
||||
static boolean hadError = false;
|
||||
public static void main(String[] args) throws IOException {
|
||||
if (args.length > 1) {
|
||||
System.out.println("Usage: jlox [script]");
|
||||
System.exit(64);
|
||||
} else if (args.length == 1) {
|
||||
runFile(args[0]);
|
||||
} else {
|
||||
runPrompt();
|
||||
}
|
||||
}
|
||||
|
||||
private static void run(String source) {
|
||||
Scanner scanner = new Scanner(source);
|
||||
List<Token> tokens = scanner.scanTokens();
|
||||
|
||||
// For now, just print the tokens.
|
||||
for (Token token : tokens) {
|
||||
System.out.println(token);
|
||||
}
|
||||
}
|
||||
static void error(int line, String message) {
|
||||
report(line, "", message);
|
||||
}
|
||||
|
||||
private static void report(int line, String where,
|
||||
String message) {
|
||||
System.err.println(
|
||||
"[line " + line + "] Error" + where + ": " + message);
|
||||
hadError = true;
|
||||
}
|
||||
|
||||
|
||||
private static void runFile(String path) throws IOException {
|
||||
byte[] bytes = Files.readAllBytes(Paths.get(path));
|
||||
run(new String(bytes, Charset.defaultCharset()));
|
||||
if(hadError) System.exit(65);
|
||||
}
|
||||
private static void runPrompt() throws IOException {
|
||||
InputStreamReader input = new InputStreamReader(System.in);
|
||||
BufferedReader reader = new BufferedReader(input);
|
||||
|
||||
for (;;) {
|
||||
System.out.print("> ");
|
||||
String line = reader.readLine();
|
||||
if (line == null) break;
|
||||
run(line);
|
||||
hadError = false;
|
||||
}
|
||||
}
|
||||
}
|
197
src/com/lox/Scanner.java
Normal file
197
src/com/lox/Scanner.java
Normal file
@ -0,0 +1,197 @@
|
||||
package com.lox;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static com.lox.TokenType.*;
|
||||
|
||||
class Scanner {
|
||||
private final String source;
|
||||
private final List<Token> tokens = new ArrayList<>();
|
||||
private int start = 0;
|
||||
private int current = 0;
|
||||
private int line = 1;
|
||||
private static final Map<String, TokenType> keywords;
|
||||
|
||||
static {
|
||||
keywords = new HashMap<>();
|
||||
keywords.put("and", AND);
|
||||
keywords.put("class", CLASS);
|
||||
keywords.put("else", ELSE);
|
||||
keywords.put("false", FALSE);
|
||||
keywords.put("for", FOR);
|
||||
keywords.put("fun", FUN);
|
||||
keywords.put("if", IF);
|
||||
keywords.put("nil", NIL);
|
||||
keywords.put("or", OR);
|
||||
keywords.put("print", PRINT);
|
||||
keywords.put("return", RETURN);
|
||||
keywords.put("super", SUPER);
|
||||
keywords.put("this", THIS);
|
||||
keywords.put("true", TRUE);
|
||||
keywords.put("var", VAR);
|
||||
keywords.put("while", WHILE);
|
||||
}
|
||||
Scanner(String source) {
|
||||
this.source = source;
|
||||
}
|
||||
List<Token> scanTokens() {
|
||||
while (!isAtEnd()) {
|
||||
// We are at the beginning of the next lexeme.
|
||||
start = current;
|
||||
scanToken();
|
||||
}
|
||||
|
||||
tokens.add(new Token(EOF, "", null, line));
|
||||
return tokens;
|
||||
}
|
||||
private void scanToken() {
|
||||
char c = advance();
|
||||
switch (c) {
|
||||
case '(': addToken(LEFT_PAREN); break;
|
||||
case ')': addToken(RIGHT_PAREN); break;
|
||||
case '{': addToken(LEFT_BRACE); break;
|
||||
case '}': addToken(RIGHT_BRACE); break;
|
||||
case ',': addToken(COMMA); break;
|
||||
case '.': addToken(DOT); break;
|
||||
case '-': addToken(MINUS); break;
|
||||
case '+': addToken(PLUS); break;
|
||||
case ';': addToken(SEMICOLON); break;
|
||||
case '*': addToken(STAR); break;
|
||||
case '!':
|
||||
addToken(match('=') ? BANG_EQUAL : BANG);
|
||||
break;
|
||||
case '=':
|
||||
addToken(match('=') ? EQUAL_EQUAL : EQUAL);
|
||||
break;
|
||||
case '<':
|
||||
addToken(match('=') ? LESS_EQUAL : LESS);
|
||||
break;
|
||||
case '>':
|
||||
addToken(match('=') ? GREATER_EQUAL : GREATER);
|
||||
break;
|
||||
case '/':
|
||||
if (match('/')) {
|
||||
// A comment goes until the end of the line.
|
||||
while (peek() != '\n' && !isAtEnd()) advance();
|
||||
} else {
|
||||
addToken(SLASH);
|
||||
}
|
||||
break;
|
||||
case ' ':
|
||||
case '\r':
|
||||
case '\t':
|
||||
// Ignore whitespace.
|
||||
break;
|
||||
|
||||
case '\n':
|
||||
line++;
|
||||
break;
|
||||
case '"': string(); break;
|
||||
case 'o':
|
||||
if (match('r')) {
|
||||
addToken(OR);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
if (isDigit(c)) {
|
||||
number();
|
||||
}
|
||||
else if(isAlpha(c)){
|
||||
identifier();
|
||||
}
|
||||
else {
|
||||
Lox.error(line, "Unexpected character.");
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
private void identifier() {
|
||||
while (isAlphaNumeric(peek())) advance();
|
||||
String text = source.substring(start, current);
|
||||
TokenType type = keywords.get(text);
|
||||
if (type == null) type = IDENTIFIER;
|
||||
addToken(type);
|
||||
}
|
||||
private void number() {
|
||||
while (isDigit(peek())) advance();
|
||||
|
||||
// Look for a fractional part.
|
||||
if (peek() == '.' && isDigit(peekNext())) {
|
||||
// Consume the "."
|
||||
advance();
|
||||
|
||||
while (isDigit(peek())) advance();
|
||||
}
|
||||
|
||||
addToken(NUMBER,
|
||||
Double.parseDouble(source.substring(start, current)));
|
||||
}
|
||||
private void string() {
|
||||
while (peek() != '"' && !isAtEnd()) {
|
||||
if (peek() == '\n') line++;
|
||||
advance();
|
||||
}
|
||||
|
||||
if (isAtEnd()) {
|
||||
Lox.error(line, "Unterminated string.");
|
||||
return;
|
||||
}
|
||||
|
||||
// The closing ".
|
||||
advance();
|
||||
|
||||
// Trim the surrounding quotes.
|
||||
String value = source.substring(start + 1, current - 1);
|
||||
addToken(STRING, value);
|
||||
}
|
||||
|
||||
private boolean match(char expected) {
|
||||
if (isAtEnd()) return false;
|
||||
if (source.charAt(current) != expected) return false;
|
||||
|
||||
current++;
|
||||
return true;
|
||||
}
|
||||
|
||||
private char peek() {
|
||||
if (isAtEnd()) return '\0';
|
||||
return source.charAt(current);
|
||||
}
|
||||
|
||||
private char peekNext() {
|
||||
if (current + 1 >= source.length()) return '\0';
|
||||
return source.charAt(current + 1);
|
||||
}
|
||||
|
||||
private boolean isAlpha(char c) {
|
||||
return (c >= 'a' && c <= 'z') ||
|
||||
(c >= 'A' && c <= 'Z') ||
|
||||
c == '_';
|
||||
}
|
||||
|
||||
private boolean isAlphaNumeric(char c) {
|
||||
return isAlpha(c) || isDigit(c);
|
||||
}
|
||||
|
||||
private boolean isDigit(char c) {
|
||||
return c >= '0' && c <= '9';
|
||||
}
|
||||
private boolean isAtEnd() {
|
||||
return current >= source.length();
|
||||
}
|
||||
private char advance() {
|
||||
return source.charAt(current++);
|
||||
}
|
||||
|
||||
private void addToken(TokenType type) {
|
||||
addToken(type, null);
|
||||
}
|
||||
|
||||
private void addToken(TokenType type, Object literal) {
|
||||
String text = source.substring(start, current);
|
||||
tokens.add(new Token(type, text, literal, line));
|
||||
}
|
||||
}
|
19
src/com/lox/Token.java
Normal file
19
src/com/lox/Token.java
Normal file
@ -0,0 +1,19 @@
|
||||
package com.lox;
|
||||
|
||||
class Token {
|
||||
final TokenType type;
|
||||
final String lexeme;
|
||||
final Object literal;
|
||||
final int line;
|
||||
|
||||
Token(TokenType type, String lexeme, Object literal, int line) {
|
||||
this.type = type;
|
||||
this.lexeme = lexeme;
|
||||
this.literal = literal;
|
||||
this.line = line;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return type + " " + lexeme + " " + literal;
|
||||
}
|
||||
}
|
23
src/com/lox/TokenType.java
Normal file
23
src/com/lox/TokenType.java
Normal file
@ -0,0 +1,23 @@
|
||||
package com.lox;
|
||||
|
||||
enum TokenType {
|
||||
// Single-character tokens.
|
||||
LEFT_PAREN, RIGHT_PAREN, LEFT_BRACE, RIGHT_BRACE,
|
||||
COMMA, DOT, MINUS, PLUS, SEMICOLON, SLASH, STAR,
|
||||
|
||||
// One or two character tokens.
|
||||
BANG, BANG_EQUAL,
|
||||
EQUAL, EQUAL_EQUAL,
|
||||
GREATER, GREATER_EQUAL,
|
||||
LESS, LESS_EQUAL,
|
||||
|
||||
// Literals.
|
||||
IDENTIFIER, STRING, NUMBER,
|
||||
|
||||
// Keywords.
|
||||
AND, CLASS, ELSE, FALSE, FUN, FOR, IF, NIL, OR,
|
||||
PRINT, RETURN, SUPER, THIS, TRUE, VAR, WHILE,
|
||||
|
||||
EOF
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user