allow constant expressions in if statements

This commit is contained in:
dfsek
2020-12-20 01:50:41 -07:00
parent c4f927e72c
commit 8b97d74e0a
4 changed files with 37 additions and 3 deletions

View File

@@ -2,6 +2,8 @@ package com.dfsek.terra.api.structures.parser;
import com.dfsek.terra.api.structures.parser.exceptions.ParseException;
import com.dfsek.terra.api.structures.parser.lang.Block;
import com.dfsek.terra.api.structures.parser.lang.ConstantExpression;
import com.dfsek.terra.api.structures.parser.lang.Expression;
import com.dfsek.terra.api.structures.parser.lang.Function;
import com.dfsek.terra.api.structures.parser.lang.Item;
import com.dfsek.terra.api.structures.parser.lang.Keyword;
@@ -70,13 +72,13 @@ public class Parser {
checkType(functionAndArguments.remove(0), Token.Type.BODY_BEGIN);
Function<?> left = parseFunction(functionAndArguments, false);
Expression<?> left = parseExpression(functionAndArguments);
Statement statement = null;
Token comparator = functionAndArguments.remove(0);
checkType(comparator, Token.Type.BOOLEAN_OPERATOR);
Function<?> right = parseFunction(functionAndArguments, false);
Expression<?> right = parseExpression(functionAndArguments);
checkType(functionAndArguments.remove(0), Token.Type.BODY_END);
if(comparator.getContent().equals("==")) {
@@ -89,6 +91,12 @@ public class Parser {
return k;
}
private Expression<?> parseExpression(List<Token> tokens) throws ParseException {
if(tokens.get(0).isConstant()) {
return new ConstantExpression(tokens.remove(0));
} else return parseFunction(tokens, false);
}
private Block parseBlock(List<Token> tokens) throws ParseException {
List<Item<?>> parsedItems = new GlueList<>();
List<Token> functionArgs = new GlueList<>();

View File

@@ -0,0 +1,22 @@
package com.dfsek.terra.api.structures.parser.lang;
import com.dfsek.terra.api.math.vector.Location;
import com.dfsek.terra.api.platform.world.Chunk;
public class ConstantExpression implements Expression<Object> {
private final Object constant;
public ConstantExpression(Object constant) {
this.constant = constant;
}
@Override
public Object apply(Location location) {
return constant;
}
@Override
public Object apply(Location location, Chunk chunk) {
return constant;
}
}

View File

@@ -28,6 +28,10 @@ public class Token {
return type + ": '" + content + "'";
}
public boolean isConstant() {
return this.type.equals(Type.NUMBER) || this.type.equals(Type.STRING) || this.type.equals(Type.BOOLEAN);
}
public enum Type {
/**
* Function identifier or language keyword

View File

@@ -1,7 +1,7 @@
test("hello", 1);
test("ghgj{}()\"\\hgjhgj", 3.4);
if(test("hello", 1) == test("hello", 1)) {
if(test("hello", 1) == "a string literal") {
test("hello", 1);
}