75 lines
2.3 KiB
Java
75 lines
2.3 KiB
Java
package speiger.src.builder.conditions;
|
|
|
|
import java.util.ArrayList;
|
|
import java.util.Arrays;
|
|
import java.util.HashSet;
|
|
import java.util.List;
|
|
import java.util.Set;
|
|
|
|
import speiger.src.builder.misc.RegexUtil;
|
|
import speiger.src.builder.processor.CompiledArguments;
|
|
|
|
public interface ICondition
|
|
{
|
|
public static final Set<Character> VALID_CHARACTERS = new HashSet<>(Arrays.asList('(', ')'));
|
|
public static final ICondition ALWAYS_TRUE = T -> true;
|
|
|
|
public boolean isValid(CompiledArguments args);
|
|
|
|
public static ICondition parse(List<String> elements) {
|
|
List<ICondition> conditions = new ArrayList<>();
|
|
AndCondition activeAnd = null;
|
|
for(int i = 0,m=elements.size();i<m;i++) {
|
|
String entry = elements.get(i);
|
|
if(entry.equalsIgnoreCase("(")) {
|
|
int endIndex = RegexUtil.lastIndexOf(elements, i, "(", ")");
|
|
if(endIndex == -1) throw new IllegalStateException("A Condition Closer [ ) ] is missing");
|
|
ICondition result = parse(elements.subList(i+1, endIndex));
|
|
if(activeAnd != null) activeAnd.addCondition(result);
|
|
else conditions.add(result);
|
|
i = endIndex+1;
|
|
}
|
|
else if(entry.equalsIgnoreCase("&&")) {
|
|
if(activeAnd != null) continue;
|
|
if(i != 0) {
|
|
ICondition prev = conditions.get(conditions.size()-1);
|
|
if(prev instanceof AndCondition) activeAnd = (AndCondition)prev;
|
|
else {
|
|
activeAnd = new AndCondition(prev);
|
|
conditions.set(conditions.size()-1, activeAnd);
|
|
}
|
|
}
|
|
else {
|
|
activeAnd = new AndCondition();
|
|
conditions.add(activeAnd);
|
|
}
|
|
}
|
|
else if(entry.equalsIgnoreCase("||")) {
|
|
activeAnd = null;
|
|
}
|
|
else {
|
|
if(activeAnd != null) activeAnd.addCondition(parseCondition(entry));
|
|
else conditions.add(parseCondition(entry));
|
|
}
|
|
}
|
|
switch(conditions.size())
|
|
{
|
|
case 0: throw new IllegalStateException("Empty Conditions are not allowed");
|
|
case 1: return conditions.get(0);
|
|
default: return new OrCondition(conditions);
|
|
}
|
|
}
|
|
|
|
public static ICondition parse(String condition)
|
|
{
|
|
return parse(Arrays.asList(RegexUtil.ensureWhitespaces(condition, VALID_CHARACTERS).split(" ")));
|
|
}
|
|
|
|
static ICondition parseCondition(String s)
|
|
{
|
|
ICondition numbers = NumberCondition.tryBuild(s);
|
|
if(numbers != null) return numbers;
|
|
return s.startsWith("!") ? new FlagCondition(s.substring(1), true) : new FlagCondition(s, false);
|
|
}
|
|
}
|