AdvancedScripts/src/main/java/de/zonlykroks/advancedscripts/lexer/ScriptColorizer.java

117 Zeilen
4.2 KiB
Java

package de.zonlykroks.advancedscripts.lexer;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class ScriptColorizer {
private static final Set<String> KEYWORDS = Set.of(
"and", "break", "do", "else", "elseif", "end", "for", "function", "goto", "if", "in", "local", "nil", "not", "or", "repeat", "return", "then", "until", "while"
);
private ScriptColorizer() {
throw new IllegalStateException("Utility class");
}
public static List<Token> colorize(String line) {
List<Token> tokens = colorizeComment(line);
if (tokens != null) return tokens;
return colorizeLine(line);
}
private static List<Token> colorizeComment(String line) {
if (!line.startsWith("--")) return null;
return List.of(new Token(line, TokenTypeColors.COMMENT));
}
private static List<Token> colorizeLine(String line) {
List<Token> tokens = new ArrayList<>();
StringBuilder currentToken = new StringBuilder();
boolean inString = false;
boolean doubleQuoteString = false;
System.out.println('"' + line + '"');
for (char c : line.toCharArray()) {
switch (c) {
case '"' -> {
if (inString) {
currentToken.append(c);
if (doubleQuoteString) {
tokens.add(new Token(currentToken.toString(), TokenTypeColors.STRING));
currentToken = new StringBuilder();
inString = false;
doubleQuoteString = false;
}
} else {
inString = true;
doubleQuoteString = true;
if (currentToken.length() > 0) {
tokens.add(toToken(currentToken.toString()));
currentToken = new StringBuilder();
}
currentToken.append(c);
}
}
case '\'' -> {
if (inString) {
currentToken.append(c);
if (!doubleQuoteString) {
tokens.add(new Token(currentToken.toString(), TokenTypeColors.STRING));
currentToken = new StringBuilder();
inString = false;
}
} else {
inString = true;
doubleQuoteString = false;
if (currentToken.length() > 0) {
tokens.add(toToken(currentToken.toString()));
currentToken = new StringBuilder();
}
currentToken.append(c);
}
}
case '-', ';', '(', ')', ',', ' ', '{', '\t' -> {
if (inString) {
currentToken.append(c);
} else {
if(currentToken.length() > 0) {
tokens.add(toToken(currentToken.toString()));
}
tokens.add(new Token(String.valueOf(c), TokenTypeColors.OTHER));
currentToken = new StringBuilder();
}
}
default -> currentToken.append(c);
}
}
if (currentToken.length() > 0) {
tokens.add(toToken(currentToken.toString()));
}
System.out.println(tokens);
return tokens;
}
private static Token toToken(String text) {
if (text.length() > 0) {
if (KEYWORDS.contains(text)) {
return new Token(text, TokenTypeColors.CONSTANT);
} else if ("true".contentEquals(text) || "false".contentEquals(text)) {
return new Token(text, TokenTypeColors.BOOLEAN);
} else if (text.matches("[0-9]+")) {
return new Token(text, TokenTypeColors.NUMBER);
} else {
return new Token(text, TokenTypeColors.OTHER);
}
} else {
return Token.SPACE;
}
}
}