Refactor precedence support

This commit is contained in:
Alexey Andreev 2015-10-11 17:30:28 +03:00
parent ce434fc4ea
commit 6d23626867
7 changed files with 445 additions and 177 deletions

View File

@ -19,7 +19,7 @@ package org.teavm.javascript;
* *
* @author Alexey Andreev * @author Alexey Andreev
*/ */
public enum Priority { public enum Precedence {
COMMA, COMMA,
ASSIGNMENT, ASSIGNMENT,
CONDITIONAL, CONDITIONAL,
@ -36,5 +36,21 @@ public enum Priority {
UNARY, UNARY,
FUNCTION_CALL, FUNCTION_CALL,
MEMBER_ACCESS, MEMBER_ACCESS,
GROUPING GROUPING;
private static Precedence[] cache = Precedence.values();
public Precedence next() {
int index = ordinal();
return index + 1 < cache.length ? cache[index + 1] : cache[index];
}
public Precedence previous() {
int index = ordinal();
return index > 0 ? cache[index - 1] : cache[index];
}
public static Precedence min() {
return Precedence.COMMA;
}
} }

View File

@ -18,7 +18,16 @@ package org.teavm.javascript;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.util.*; import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.teavm.codegen.NamingException; import org.teavm.codegen.NamingException;
import org.teavm.codegen.NamingOrderer; import org.teavm.codegen.NamingOrderer;
import org.teavm.codegen.NamingStrategy; import org.teavm.codegen.NamingStrategy;
@ -28,12 +37,68 @@ import org.teavm.debugging.information.DebugInformationEmitter;
import org.teavm.debugging.information.DeferredCallSite; import org.teavm.debugging.information.DeferredCallSite;
import org.teavm.debugging.information.DummyDebugInformationEmitter; import org.teavm.debugging.information.DummyDebugInformationEmitter;
import org.teavm.diagnostics.Diagnostics; import org.teavm.diagnostics.Diagnostics;
import org.teavm.javascript.ast.*; import org.teavm.javascript.ast.AssignmentStatement;
import org.teavm.javascript.ast.AsyncMethodNode;
import org.teavm.javascript.ast.AsyncMethodPart;
import org.teavm.javascript.ast.BinaryExpr;
import org.teavm.javascript.ast.BinaryOperation;
import org.teavm.javascript.ast.BlockStatement;
import org.teavm.javascript.ast.BreakStatement;
import org.teavm.javascript.ast.ClassNode;
import org.teavm.javascript.ast.ConditionalExpr;
import org.teavm.javascript.ast.ConditionalStatement;
import org.teavm.javascript.ast.ConstantExpr;
import org.teavm.javascript.ast.ContinueStatement;
import org.teavm.javascript.ast.Expr;
import org.teavm.javascript.ast.ExprVisitor;
import org.teavm.javascript.ast.FieldNode;
import org.teavm.javascript.ast.GotoPartStatement;
import org.teavm.javascript.ast.InitClassStatement;
import org.teavm.javascript.ast.InstanceOfExpr;
import org.teavm.javascript.ast.InvocationExpr;
import org.teavm.javascript.ast.InvocationType;
import org.teavm.javascript.ast.MethodNode;
import org.teavm.javascript.ast.MethodNodeVisitor;
import org.teavm.javascript.ast.MonitorEnterStatement;
import org.teavm.javascript.ast.MonitorExitStatement;
import org.teavm.javascript.ast.NativeMethodNode;
import org.teavm.javascript.ast.NewArrayExpr;
import org.teavm.javascript.ast.NewExpr;
import org.teavm.javascript.ast.NewMultiArrayExpr;
import org.teavm.javascript.ast.NodeLocation;
import org.teavm.javascript.ast.NodeModifier;
import org.teavm.javascript.ast.QualificationExpr;
import org.teavm.javascript.ast.RegularMethodNode;
import org.teavm.javascript.ast.ReturnStatement;
import org.teavm.javascript.ast.SequentialStatement;
import org.teavm.javascript.ast.Statement;
import org.teavm.javascript.ast.StatementVisitor;
import org.teavm.javascript.ast.StaticClassExpr;
import org.teavm.javascript.ast.SubscriptExpr;
import org.teavm.javascript.ast.SwitchClause;
import org.teavm.javascript.ast.SwitchStatement;
import org.teavm.javascript.ast.ThrowStatement;
import org.teavm.javascript.ast.TryCatchStatement;
import org.teavm.javascript.ast.UnaryExpr;
import org.teavm.javascript.ast.UnwrapArrayExpr;
import org.teavm.javascript.ast.VariableExpr;
import org.teavm.javascript.ast.WhileStatement;
import org.teavm.javascript.spi.GeneratorContext; import org.teavm.javascript.spi.GeneratorContext;
import org.teavm.javascript.spi.InjectedBy; import org.teavm.javascript.spi.InjectedBy;
import org.teavm.javascript.spi.Injector; import org.teavm.javascript.spi.Injector;
import org.teavm.javascript.spi.InjectorContext; import org.teavm.javascript.spi.InjectorContext;
import org.teavm.model.*; import org.teavm.model.AnnotationHolder;
import org.teavm.model.ClassHolder;
import org.teavm.model.ClassReader;
import org.teavm.model.ElementModifier;
import org.teavm.model.FieldReference;
import org.teavm.model.ListableClassHolderSource;
import org.teavm.model.ListableClassReaderSource;
import org.teavm.model.MethodDescriptor;
import org.teavm.model.MethodHolder;
import org.teavm.model.MethodReader;
import org.teavm.model.MethodReference;
import org.teavm.model.ValueType;
/** /**
* *
@ -60,22 +125,13 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
private Set<MethodReference> asyncFamilyMethods; private Set<MethodReference> asyncFamilyMethods;
private Diagnostics diagnostics; private Diagnostics diagnostics;
private boolean async; private boolean async;
private Priority priority; private Precedence precedence;
private Associativity associativity;
private boolean wasGrouped;
private Deque<OperatorPrecedence> precedenceStack = new ArrayDeque<>();
private Map<String, String> blockIdMap = new HashMap<>(); private Map<String, String> blockIdMap = new HashMap<>();
private List<Set<String>> debugNames = new ArrayList<>(); private List<Set<String>> debugNames = new ArrayList<>();
private List<String> cachedVariableNames = new ArrayList<>(); private List<String> cachedVariableNames = new ArrayList<>();
private boolean end; private boolean end;
private int currentPart; private int currentPart;
private static class OperatorPrecedence {
Priority priority;
Associativity associativity;
boolean wasGrouped;
}
private static class InjectorHolder { private static class InjectorHolder {
public final Injector injector; public final Injector injector;
@ -870,22 +926,19 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
if (statement.isAsync()) { if (statement.isAsync()) {
writer.append(tempVarName()); writer.append(tempVarName());
} else { } else {
priority = Priority.COMMA; precedence = Precedence.COMMA;
associativity = Associativity.NONE;
statement.getLeftValue().acceptVisitor(this); statement.getLeftValue().acceptVisitor(this);
} }
writer.ws().append("=").ws(); writer.ws().append("=").ws();
} }
priority = Priority.COMMA; precedence = Precedence.COMMA;
associativity = Associativity.NONE;
statement.getRightValue().acceptVisitor(this); statement.getRightValue().acceptVisitor(this);
debugEmitter.emitCallSite(); debugEmitter.emitCallSite();
writer.append(";").softNewLine(); writer.append(";").softNewLine();
if (statement.isAsync()) { if (statement.isAsync()) {
emitSuspendChecker(); emitSuspendChecker();
if (statement.getLeftValue() != null) { if (statement.getLeftValue() != null) {
priority = Priority.COMMA; precedence = Precedence.COMMA;
associativity = Associativity.NONE;
statement.getLeftValue().acceptVisitor(this); statement.getLeftValue().acceptVisitor(this);
writer.ws().append("=").ws().append(tempVarName()).append(";").softNewLine(); writer.ws().append("=").ws().append(tempVarName()).append(";").softNewLine();
} }
@ -918,8 +971,7 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
} }
prevCallSite = debugEmitter.emitCallSite(); prevCallSite = debugEmitter.emitCallSite();
writer.append("if").ws().append("("); writer.append("if").ws().append("(");
priority = Priority.COMMA; precedence = Precedence.COMMA;
associativity = Associativity.NONE;
statement.getCondition().acceptVisitor(this); statement.getCondition().acceptVisitor(this);
if (statement.getCondition().getLocation() != null) { if (statement.getCondition().getLocation() != null) {
popLocation(); popLocation();
@ -958,8 +1010,7 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
} }
prevCallSite = debugEmitter.emitCallSite(); prevCallSite = debugEmitter.emitCallSite();
writer.append("switch").ws().append("("); writer.append("switch").ws().append("(");
priority = Priority.COMMA; precedence = Precedence.min();
associativity = Associativity.NONE;
statement.getValue().acceptVisitor(this); statement.getValue().acceptVisitor(this);
if (statement.getValue().getLocation() != null) { if (statement.getValue().getLocation() != null) {
popLocation(); popLocation();
@ -1008,8 +1059,7 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
writer.append("while").ws().append("("); writer.append("while").ws().append("(");
if (statement.getCondition() != null) { if (statement.getCondition() != null) {
prevCallSite = debugEmitter.emitCallSite(); prevCallSite = debugEmitter.emitCallSite();
priority = Priority.COMMA; precedence = Precedence.min();
associativity = Associativity.NONE;
statement.getCondition().acceptVisitor(this); statement.getCondition().acceptVisitor(this);
debugEmitter.emitCallSite(); debugEmitter.emitCallSite();
if (statement.getCondition().getLocation() != null) { if (statement.getCondition().getLocation() != null) {
@ -1112,8 +1162,7 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
if (statement.getResult() != null) { if (statement.getResult() != null) {
writer.append(' '); writer.append(' ');
prevCallSite = debugEmitter.emitCallSite(); prevCallSite = debugEmitter.emitCallSite();
priority = Priority.COMMA; precedence = Precedence.min();
associativity = Associativity.NONE;
statement.getResult().acceptVisitor(this); statement.getResult().acceptVisitor(this);
debugEmitter.emitCallSite(); debugEmitter.emitCallSite();
} }
@ -1135,8 +1184,7 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
} }
writer.appendFunction("$rt_throw").append("("); writer.appendFunction("$rt_throw").append("(");
prevCallSite = debugEmitter.emitCallSite(); prevCallSite = debugEmitter.emitCallSite();
priority = Priority.COMMA; precedence = Precedence.min();
associativity = Associativity.NONE;
statement.getException().acceptVisitor(this); statement.getException().acceptVisitor(this);
writer.append(");").softNewLine(); writer.append(");").softNewLine();
debugEmitter.emitCallSite(); debugEmitter.emitCallSite();
@ -1224,17 +1272,61 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
return minifying ? "$T" : "$thread"; return minifying ? "$T" : "$thread";
} }
private void visitBinary(BinaryExpr expr, String op, Priority priority, Associativity associativity) { private void visitBinary(BinaryExpr expr, String op) {
try { try {
if (expr.getLocation() != null) { if (expr.getLocation() != null) {
pushLocation(expr.getLocation()); pushLocation(expr.getLocation());
} }
enterPriority(priority, associativity == Associativity.LEFT ? associativity : Associativity.NONE, true);
Precedence outerPrecedence = precedence;
Precedence innerPrecedence = getPrecedence(expr.getOperation());
if (innerPrecedence.ordinal() < outerPrecedence.ordinal()) {
writer.append('(');
}
switch (expr.getOperation()) {
case ADD:
case SUBTRACT:
case MULTIPLY:
case DIVIDE:
case MODULO:
case AND:
case OR:
case BITWISE_AND:
case BITWISE_OR:
case BITWISE_XOR:
case LEFT_SHIFT:
case RIGHT_SHIFT:
case UNSIGNED_RIGHT_SHIFT:
precedence = innerPrecedence;
break;
default:
precedence = innerPrecedence.next();
}
expr.getFirstOperand().acceptVisitor(this); expr.getFirstOperand().acceptVisitor(this);
writer.ws().append(op).ws(); writer.ws().append(op).ws();
this.associativity = associativity == Associativity.RIGHT ? associativity : Associativity.NONE;
switch (expr.getOperation()) {
case ADD:
case MULTIPLY:
case AND:
case OR:
case BITWISE_AND:
case BITWISE_OR:
case BITWISE_XOR:
precedence = innerPrecedence;
break;
default:
precedence = innerPrecedence.next();
break;
}
expr.getSecondOperand().acceptVisitor(this); expr.getSecondOperand().acceptVisitor(this);
exitPriority();
if (innerPrecedence.ordinal() < outerPrecedence.ordinal()) {
writer.append(')');
}
if (expr.getLocation() != null) { if (expr.getLocation() != null) {
popLocation(); popLocation();
} }
@ -1243,31 +1335,42 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
} }
} }
private void enterPriority(Priority priority, Associativity associativity, boolean autoGroup) throws IOException { private static Precedence getPrecedence(BinaryOperation op) {
OperatorPrecedence precedence = new OperatorPrecedence(); switch (op) {
precedence.wasGrouped = this.wasGrouped; case ADD:
precedence.priority = this.priority; case SUBTRACT:
precedence.associativity = this.associativity; return Precedence.ADDITION;
precedenceStack.push(precedence); case MULTIPLY:
wasGrouped = false; case DIVIDE:
if (autoGroup && (priority.ordinal() < this.priority.ordinal() case MODULO:
|| priority.ordinal() == this.priority.ordinal() return Precedence.MULTIPLICATION;
&& (associativity != this.associativity || associativity == Associativity.NONE))) { case AND:
wasGrouped = true; return Precedence.LOGICAL_AND;
writer.append('('); case OR:
return Precedence.LOGICAL_OR;
case STRICT_EQUALS:
case STRICT_NOT_EQUALS:
case EQUALS:
case NOT_EQUALS:
return Precedence.EQUALITY;
case GREATER:
case GREATER_OR_EQUALS:
case LESS:
case LESS_OR_EQUALS:
return Precedence.COMPARISON;
case BITWISE_AND:
return Precedence.BITWISE_AND;
case BITWISE_OR:
return Precedence.BITWISE_OR;
case BITWISE_XOR:
return Precedence.BITWISE_XOR;
case LEFT_SHIFT:
case RIGHT_SHIFT:
case UNSIGNED_RIGHT_SHIFT:
return Precedence.BITWISE_SHIFT;
default:
return Precedence.GROUPING;
} }
this.priority = priority;
this.associativity = associativity;
}
private void exitPriority() throws IOException {
if (wasGrouped) {
writer.append(')');
}
OperatorPrecedence precedence = precedenceStack.pop();
this.priority = precedence.priority;
this.associativity = precedence.associativity;
this.wasGrouped = precedence.wasGrouped;
} }
private void visitBinaryFunction(BinaryExpr expr, String function) { private void visitBinaryFunction(BinaryExpr expr, String function) {
@ -1275,14 +1378,14 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
if (expr.getLocation() != null) { if (expr.getLocation() != null) {
pushLocation(expr.getLocation()); pushLocation(expr.getLocation());
} }
enterPriority(Priority.COMMA, Associativity.NONE, false);
writer.append(function); writer.append(function);
writer.append('('); writer.append('(');
precedence = Precedence.min();
expr.getFirstOperand().acceptVisitor(this); expr.getFirstOperand().acceptVisitor(this);
writer.append(",").ws(); writer.append(",").ws();
precedence = Precedence.min();
expr.getSecondOperand().acceptVisitor(this); expr.getSecondOperand().acceptVisitor(this);
writer.append(')'); writer.append(')');
exitPriority();
if (expr.getLocation() != null) { if (expr.getLocation() != null) {
popLocation(); popLocation();
} }
@ -1295,58 +1398,58 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
public void visit(BinaryExpr expr) { public void visit(BinaryExpr expr) {
switch (expr.getOperation()) { switch (expr.getOperation()) {
case ADD: case ADD:
visitBinary(expr, "+", Priority.ADDITION, Associativity.LEFT); visitBinary(expr, "+");
break; break;
case ADD_LONG: case ADD_LONG:
visitBinaryFunction(expr, "Long_add"); visitBinaryFunction(expr, "Long_add");
break; break;
case SUBTRACT: case SUBTRACT:
visitBinary(expr, "-", Priority.ADDITION, Associativity.LEFT); visitBinary(expr, "-");
break; break;
case SUBTRACT_LONG: case SUBTRACT_LONG:
visitBinaryFunction(expr, "Long_sub"); visitBinaryFunction(expr, "Long_sub");
break; break;
case MULTIPLY: case MULTIPLY:
visitBinary(expr, "*", Priority.MULTIPLICATION, Associativity.LEFT); visitBinary(expr, "*");
break; break;
case MULTIPLY_LONG: case MULTIPLY_LONG:
visitBinaryFunction(expr, "Long_mul"); visitBinaryFunction(expr, "Long_mul");
break; break;
case DIVIDE: case DIVIDE:
visitBinary(expr, "/", Priority.MULTIPLICATION, Associativity.LEFT); visitBinary(expr, "/");
break; break;
case DIVIDE_LONG: case DIVIDE_LONG:
visitBinaryFunction(expr, "Long_div"); visitBinaryFunction(expr, "Long_div");
break; break;
case MODULO: case MODULO:
visitBinary(expr, "%", Priority.MULTIPLICATION, Associativity.LEFT); visitBinary(expr, "%");
break; break;
case MODULO_LONG: case MODULO_LONG:
visitBinaryFunction(expr, "Long_rem"); visitBinaryFunction(expr, "Long_rem");
break; break;
case EQUALS: case EQUALS:
visitBinary(expr, "==", Priority.EQUALITY, Associativity.LEFT); visitBinary(expr, "==");
break; break;
case NOT_EQUALS: case NOT_EQUALS:
visitBinary(expr, "!=", Priority.EQUALITY, Associativity.LEFT); visitBinary(expr, "!=");
break; break;
case GREATER: case GREATER:
visitBinary(expr, ">", Priority.COMPARISON, Associativity.LEFT); visitBinary(expr, ">");
break; break;
case GREATER_OR_EQUALS: case GREATER_OR_EQUALS:
visitBinary(expr, ">=", Priority.COMPARISON, Associativity.LEFT); visitBinary(expr, ">=");
break; break;
case LESS: case LESS:
visitBinary(expr, "<", Priority.COMPARISON, Associativity.LEFT); visitBinary(expr, "<");
break; break;
case LESS_OR_EQUALS: case LESS_OR_EQUALS:
visitBinary(expr, "<=", Priority.COMPARISON, Associativity.LEFT); visitBinary(expr, "<=");
break; break;
case STRICT_EQUALS: case STRICT_EQUALS:
visitBinary(expr, "===", Priority.COMPARISON, Associativity.LEFT); visitBinary(expr, "===");
break; break;
case STRICT_NOT_EQUALS: case STRICT_NOT_EQUALS:
visitBinary(expr, "!==", Priority.COMPARISON, Associativity.LEFT); visitBinary(expr, "!==");
break; break;
case COMPARE: case COMPARE:
visitBinaryFunction(expr, naming.getNameForFunction("$rt_compare")); visitBinaryFunction(expr, naming.getNameForFunction("$rt_compare"));
@ -1355,43 +1458,43 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
visitBinaryFunction(expr, "Long_compare"); visitBinaryFunction(expr, "Long_compare");
break; break;
case OR: case OR:
visitBinary(expr, "||", Priority.LOGICAL_OR, Associativity.LEFT); visitBinary(expr, "||");
break; break;
case AND: case AND:
visitBinary(expr, "&&", Priority.LOGICAL_AND, Associativity.LEFT); visitBinary(expr, "&&");
break; break;
case BITWISE_OR: case BITWISE_OR:
visitBinary(expr, "|", Priority.BITWISE_OR, Associativity.LEFT); visitBinary(expr, "|");
break; break;
case BITWISE_OR_LONG: case BITWISE_OR_LONG:
visitBinaryFunction(expr, "Long_or"); visitBinaryFunction(expr, "Long_or");
break; break;
case BITWISE_AND: case BITWISE_AND:
visitBinary(expr, "&", Priority.BITWISE_AND, Associativity.LEFT); visitBinary(expr, "&");
break; break;
case BITWISE_AND_LONG: case BITWISE_AND_LONG:
visitBinaryFunction(expr, "Long_and"); visitBinaryFunction(expr, "Long_and");
break; break;
case BITWISE_XOR: case BITWISE_XOR:
visitBinary(expr, "^", Priority.BITWISE_XOR, Associativity.LEFT); visitBinary(expr, "^");
break; break;
case BITWISE_XOR_LONG: case BITWISE_XOR_LONG:
visitBinaryFunction(expr, "Long_xor"); visitBinaryFunction(expr, "Long_xor");
break; break;
case LEFT_SHIFT: case LEFT_SHIFT:
visitBinary(expr, "<<", Priority.BITWISE_SHIFT, Associativity.LEFT); visitBinary(expr, "<<");
break; break;
case LEFT_SHIFT_LONG: case LEFT_SHIFT_LONG:
visitBinaryFunction(expr, "Long_shl"); visitBinaryFunction(expr, "Long_shl");
break; break;
case RIGHT_SHIFT: case RIGHT_SHIFT:
visitBinary(expr, ">>", Priority.BITWISE_SHIFT, Associativity.LEFT); visitBinary(expr, ">>");
break; break;
case RIGHT_SHIFT_LONG: case RIGHT_SHIFT_LONG:
visitBinaryFunction(expr, "Long_shr"); visitBinaryFunction(expr, "Long_shr");
break; break;
case UNSIGNED_RIGHT_SHIFT: case UNSIGNED_RIGHT_SHIFT:
visitBinary(expr, ">>>", Priority.BITWISE_SHIFT, Associativity.LEFT); visitBinary(expr, ">>>");
break; break;
case UNSIGNED_RIGHT_SHIFT_LONG: case UNSIGNED_RIGHT_SHIFT_LONG:
visitBinaryFunction(expr, "Long_shru"); visitBinaryFunction(expr, "Long_shru");
@ -1405,92 +1508,109 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
if (expr.getLocation() != null) { if (expr.getLocation() != null) {
pushLocation(expr.getLocation()); pushLocation(expr.getLocation());
} }
Precedence outerPrecedence = precedence;
switch (expr.getOperation()) { switch (expr.getOperation()) {
case NOT: case NOT: {
enterPriority(Priority.UNARY, Associativity.RIGHT, true); if (outerPrecedence.ordinal() > Precedence.UNARY.ordinal()) {
writer.append('(');
}
writer.append("!"); writer.append("!");
precedence = Precedence.UNARY;
expr.getOperand().acceptVisitor(this); expr.getOperand().acceptVisitor(this);
exitPriority(); if (outerPrecedence.ordinal() > Precedence.UNARY.ordinal()) {
writer.append(')');
}
break; break;
}
case NEGATE: case NEGATE:
enterPriority(Priority.MULTIPLICATION, Associativity.RIGHT, true); if (outerPrecedence.ordinal() > Precedence.UNARY.ordinal()) {
writer.append('(');
}
writer.append("-"); writer.append("-");
precedence = Precedence.UNARY;
expr.getOperand().acceptVisitor(this); expr.getOperand().acceptVisitor(this);
exitPriority(); if (outerPrecedence.ordinal() > Precedence.UNARY.ordinal()) {
writer.append(')');
}
break; break;
case LENGTH: case LENGTH:
enterPriority(Priority.MEMBER_ACCESS, Associativity.LEFT, true); precedence = Precedence.MEMBER_ACCESS;
expr.getOperand().acceptVisitor(this); expr.getOperand().acceptVisitor(this);
exitPriority();
writer.append(".length"); writer.append(".length");
break; break;
case INT_TO_LONG: case INT_TO_LONG:
enterPriority(Priority.COMMA, Associativity.NONE, false);
writer.append("Long_fromInt("); writer.append("Long_fromInt(");
precedence = Precedence.min();
expr.getOperand().acceptVisitor(this); expr.getOperand().acceptVisitor(this);
writer.append(')'); writer.append(')');
exitPriority();
break; break;
case NUM_TO_LONG: case NUM_TO_LONG:
enterPriority(Priority.COMMA, Associativity.NONE, false);
writer.append("Long_fromNumber("); writer.append("Long_fromNumber(");
precedence = Precedence.min();
expr.getOperand().acceptVisitor(this); expr.getOperand().acceptVisitor(this);
writer.append(')'); writer.append(')');
exitPriority();
break; break;
case LONG_TO_NUM: case LONG_TO_NUM:
enterPriority(Priority.COMMA, Associativity.NONE, false);
writer.append("Long_toNumber("); writer.append("Long_toNumber(");
precedence = Precedence.min();
expr.getOperand().acceptVisitor(this); expr.getOperand().acceptVisitor(this);
writer.append(')'); writer.append(')');
exitPriority();
break; break;
case LONG_TO_INT: case LONG_TO_INT:
enterPriority(Priority.MEMBER_ACCESS, Associativity.LEFT, false); precedence = Precedence.MEMBER_ACCESS;
expr.getOperand().acceptVisitor(this); expr.getOperand().acceptVisitor(this);
exitPriority();
writer.append(".lo"); writer.append(".lo");
break; break;
case NEGATE_LONG: case NEGATE_LONG:
enterPriority(Priority.COMMA, Associativity.NONE, false);
writer.append("Long_neg("); writer.append("Long_neg(");
precedence = Precedence.min();
expr.getOperand().acceptVisitor(this); expr.getOperand().acceptVisitor(this);
writer.append(')'); writer.append(')');
exitPriority();
break; break;
case NOT_LONG: case NOT_LONG:
enterPriority(Priority.COMMA, Associativity.NONE, false);
writer.append("Long_not("); writer.append("Long_not(");
precedence = Precedence.min();
expr.getOperand().acceptVisitor(this); expr.getOperand().acceptVisitor(this);
writer.append(')'); writer.append(')');
exitPriority();
break; break;
case INT_TO_BYTE: case INT_TO_BYTE:
enterPriority(Priority.BITWISE_SHIFT, Associativity.LEFT, true); if (outerPrecedence.ordinal() > Precedence.BITWISE_SHIFT.ordinal()) {
writer.append("("); writer.append('(');
}
precedence = Precedence.BITWISE_SHIFT;
expr.getOperand().acceptVisitor(this); expr.getOperand().acceptVisitor(this);
writer.ws().append("<<").ws().append("24)").ws().append(">>").ws().append("24"); writer.ws().append("<<").ws().append("24").ws().append(">>").ws().append("24");
exitPriority(); if (outerPrecedence.ordinal() > Precedence.BITWISE_SHIFT.ordinal()) {
writer.append(')');
}
break; break;
case INT_TO_SHORT: case INT_TO_SHORT:
enterPriority(Priority.BITWISE_SHIFT, Associativity.LEFT, true); if (outerPrecedence.ordinal() > Precedence.BITWISE_SHIFT.ordinal()) {
writer.append("("); writer.append('(');
}
precedence = Precedence.BITWISE_SHIFT;
expr.getOperand().acceptVisitor(this); expr.getOperand().acceptVisitor(this);
writer.ws().append("<<").ws().append("16)").ws().append(">>").ws().append("16"); writer.ws().append("<<").ws().append("16").ws().append(">>").ws().append("16");
exitPriority(); if (outerPrecedence.ordinal() > Precedence.BITWISE_SHIFT.ordinal()) {
writer.append(')');
}
break; break;
case INT_TO_CHAR: case INT_TO_CHAR:
enterPriority(Priority.BITWISE_AND, Associativity.LEFT, true); if (outerPrecedence.ordinal() > Precedence.BITWISE_AND.ordinal()) {
writer.append('(');
}
precedence = Precedence.BITWISE_AND;
expr.getOperand().acceptVisitor(this); expr.getOperand().acceptVisitor(this);
writer.ws().append("&").ws().append("65535"); writer.ws().append("&").ws().append("65535");
exitPriority(); if (outerPrecedence.ordinal() > Precedence.BITWISE_AND.ordinal()) {
writer.append('(');
}
break; break;
case NULL_CHECK: case NULL_CHECK:
enterPriority(Priority.COMMA, Associativity.NONE, false);
writer.appendFunction("$rt_nullCheck").append("("); writer.appendFunction("$rt_nullCheck").append("(");
precedence = Precedence.min();
expr.getOperand().acceptVisitor(this); expr.getOperand().acceptVisitor(this);
writer.append(')'); writer.append(')');
exitPriority();
break; break;
} }
if (expr.getLocation() != null) { if (expr.getLocation() != null) {
@ -1507,13 +1627,25 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
if (expr.getLocation() != null) { if (expr.getLocation() != null) {
pushLocation(expr.getLocation()); pushLocation(expr.getLocation());
} }
enterPriority(priority, Associativity.RIGHT, async);
Precedence outerPrecedence = precedence;
if (outerPrecedence.ordinal() > Precedence.CONDITIONAL.ordinal()) {
writer.append('(');
}
precedence = Precedence.CONDITIONAL.next();
expr.getCondition().acceptVisitor(this); expr.getCondition().acceptVisitor(this);
writer.ws().append("?").ws(); writer.ws().append("?").ws();
precedence = Precedence.CONDITIONAL.next();
expr.getConsequent().acceptVisitor(this); expr.getConsequent().acceptVisitor(this);
writer.ws().append(":").ws(); writer.ws().append(":").ws();
precedence = Precedence.CONDITIONAL;
expr.getAlternative().acceptVisitor(this); expr.getAlternative().acceptVisitor(this);
exitPriority();
if (outerPrecedence.ordinal() > Precedence.CONDITIONAL.ordinal()) {
writer.append('(');
}
if (expr.getLocation() != null) { if (expr.getLocation() != null) {
popLocation(); popLocation();
} }
@ -1529,12 +1661,12 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
pushLocation(expr.getLocation()); pushLocation(expr.getLocation());
} }
String str = constantToString(expr.getValue()); String str = constantToString(expr.getValue());
if (str.startsWith("-")) { if (str.startsWith("-") && precedence.ordinal() > Precedence.MULTIPLICATION.ordinal()) {
enterPriority(Priority.MULTIPLICATION, Associativity.NONE, true); writer.append('(');
} }
writer.append(str); writer.append(str);
if (str.startsWith("-")) { if (str.startsWith("-") && precedence.ordinal() > Precedence.MULTIPLICATION.ordinal()) {
exitPriority(); writer.append(')');
} }
if (expr.getLocation() != null) { if (expr.getLocation() != null) {
popLocation(); popLocation();
@ -1691,14 +1823,12 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
if (expr.getLocation() != null) { if (expr.getLocation() != null) {
pushLocation(expr.getLocation()); pushLocation(expr.getLocation());
} }
enterPriority(Priority.MEMBER_ACCESS, Associativity.LEFT, true); precedence = Precedence.MEMBER_ACCESS;
expr.getArray().acceptVisitor(this); expr.getArray().acceptVisitor(this);
writer.append('['); writer.append('[');
enterPriority(Priority.COMMA, Associativity.NONE, false); precedence = Precedence.min();
expr.getIndex().acceptVisitor(this); expr.getIndex().acceptVisitor(this);
exitPriority();
writer.append(']'); writer.append(']');
exitPriority();
if (expr.getLocation() != null) { if (expr.getLocation() != null) {
popLocation(); popLocation();
} }
@ -1713,13 +1843,12 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
if (expr.getLocation() != null) { if (expr.getLocation() != null) {
pushLocation(expr.getLocation()); pushLocation(expr.getLocation());
} }
enterPriority(Priority.MEMBER_ACCESS, Associativity.LEFT, true); precedence = Precedence.MEMBER_ACCESS;
expr.getArray().acceptVisitor(this); expr.getArray().acceptVisitor(this);
writer.append(".data"); writer.append(".data");
if (expr.getLocation() != null) { if (expr.getLocation() != null) {
popLocation(); popLocation();
} }
exitPriority();
} catch (IOException e) { } catch (IOException e) {
throw new RenderingException("IO error occured", e); throw new RenderingException("IO error occured", e);
} }
@ -1736,6 +1865,7 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
injector.generate(new InjectorContextImpl(expr.getArguments()), expr.getMethod()); injector.generate(new InjectorContextImpl(expr.getArguments()), expr.getMethod());
} else { } else {
if (expr.getType() == InvocationType.DYNAMIC) { if (expr.getType() == InvocationType.DYNAMIC) {
precedence = Precedence.MEMBER_ACCESS;
expr.getArguments().get(0).acceptVisitor(this); expr.getArguments().get(0).acceptVisitor(this);
} }
MethodReference method = expr.getMethod(); MethodReference method = expr.getMethod();
@ -1746,7 +1876,6 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
lastCallSite = callSite; lastCallSite = callSite;
} }
boolean virtual = false; boolean virtual = false;
enterPriority(Priority.COMMA, Associativity.NONE, false);
switch (expr.getType()) { switch (expr.getType()) {
case STATIC: case STATIC:
writer.append(naming.getFullNameFor(method)).append("("); writer.append(naming.getFullNameFor(method)).append("(");
@ -1755,15 +1884,18 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
if (i > 0) { if (i > 0) {
writer.append(",").ws(); writer.append(",").ws();
} }
precedence = Precedence.min();
expr.getArguments().get(i).acceptVisitor(this); expr.getArguments().get(i).acceptVisitor(this);
} }
break; break;
case SPECIAL: case SPECIAL:
writer.append(naming.getFullNameFor(method)).append("("); writer.append(naming.getFullNameFor(method)).append("(");
prevCallSite = debugEmitter.emitCallSite(); prevCallSite = debugEmitter.emitCallSite();
precedence = Precedence.min();
expr.getArguments().get(0).acceptVisitor(this); expr.getArguments().get(0).acceptVisitor(this);
for (int i = 1; i < expr.getArguments().size(); ++i) { for (int i = 1; i < expr.getArguments().size(); ++i) {
writer.append(",").ws(); writer.append(",").ws();
precedence = Precedence.min();
expr.getArguments().get(i).acceptVisitor(this); expr.getArguments().get(i).acceptVisitor(this);
} }
break; break;
@ -1774,6 +1906,7 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
if (i > 1) { if (i > 1) {
writer.append(",").ws(); writer.append(",").ws();
} }
precedence = Precedence.min();
expr.getArguments().get(i).acceptVisitor(this); expr.getArguments().get(i).acceptVisitor(this);
} }
virtual = true; virtual = true;
@ -1785,12 +1918,12 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
if (i > 0) { if (i > 0) {
writer.append(",").ws(); writer.append(",").ws();
} }
precedence = Precedence.min();
expr.getArguments().get(i).acceptVisitor(this); expr.getArguments().get(i).acceptVisitor(this);
} }
break; break;
} }
writer.append(')'); writer.append(')');
exitPriority();
if (lastCallSite != null) { if (lastCallSite != null) {
if (virtual) { if (virtual) {
lastCallSite.setVirtualMethod(expr.getMethod()); lastCallSite.setVirtualMethod(expr.getMethod());
@ -1817,13 +1950,12 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
if (expr.getLocation() != null) { if (expr.getLocation() != null) {
pushLocation(expr.getLocation()); pushLocation(expr.getLocation());
} }
enterPriority(Priority.MEMBER_ACCESS, Associativity.LEFT, true); precedence = Precedence.MEMBER_ACCESS;
expr.getQualified().acceptVisitor(this); expr.getQualified().acceptVisitor(this);
writer.append('.').appendField(expr.getField()); writer.append('.').appendField(expr.getField());
if (expr.getLocation() != null) { if (expr.getLocation() != null) {
popLocation(); popLocation();
} }
exitPriority();
} catch (IOException e) { } catch (IOException e) {
throw new RenderingException("IO error occured", e); throw new RenderingException("IO error occured", e);
} }
@ -1835,9 +1967,8 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
if (expr.getLocation() != null) { if (expr.getLocation() != null) {
pushLocation(expr.getLocation()); pushLocation(expr.getLocation());
} }
enterPriority(Priority.FUNCTION_CALL, Associativity.RIGHT, true); precedence = Precedence.FUNCTION_CALL;
writer.append("new ").append(naming.getNameFor(expr.getConstructedClass())); writer.append("new ").append(naming.getNameFor(expr.getConstructedClass()));
exitPriority();
if (expr.getLocation() != null) { if (expr.getLocation() != null) {
popLocation(); popLocation();
} }
@ -1853,46 +1984,53 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
pushLocation(expr.getLocation()); pushLocation(expr.getLocation());
} }
ValueType type = expr.getType(); ValueType type = expr.getType();
enterPriority(Priority.COMMA, Associativity.NONE, false);
if (type instanceof ValueType.Primitive) { if (type instanceof ValueType.Primitive) {
switch (((ValueType.Primitive) type).getKind()) { switch (((ValueType.Primitive) type).getKind()) {
case BOOLEAN: case BOOLEAN:
writer.append("$rt_createBooleanArray("); writer.append("$rt_createBooleanArray(");
precedence = Precedence.min();
expr.getLength().acceptVisitor(this); expr.getLength().acceptVisitor(this);
writer.append(")"); writer.append(")");
break; break;
case BYTE: case BYTE:
writer.append("$rt_createByteArray("); writer.append("$rt_createByteArray(");
precedence = Precedence.min();
expr.getLength().acceptVisitor(this); expr.getLength().acceptVisitor(this);
writer.append(")"); writer.append(")");
break; break;
case SHORT: case SHORT:
writer.append("$rt_createShortArray("); writer.append("$rt_createShortArray(");
precedence = Precedence.min();
expr.getLength().acceptVisitor(this); expr.getLength().acceptVisitor(this);
writer.append(")"); writer.append(")");
break; break;
case INTEGER: case INTEGER:
writer.append("$rt_createIntArray("); writer.append("$rt_createIntArray(");
precedence = Precedence.min();
expr.getLength().acceptVisitor(this); expr.getLength().acceptVisitor(this);
writer.append(")"); writer.append(")");
break; break;
case LONG: case LONG:
writer.append("$rt_createLongArray("); writer.append("$rt_createLongArray(");
precedence = Precedence.min();
expr.getLength().acceptVisitor(this); expr.getLength().acceptVisitor(this);
writer.append(")"); writer.append(")");
break; break;
case FLOAT: case FLOAT:
writer.append("$rt_createFloatArray("); writer.append("$rt_createFloatArray(");
precedence = Precedence.min();
expr.getLength().acceptVisitor(this); expr.getLength().acceptVisitor(this);
writer.append(")"); writer.append(")");
break; break;
case DOUBLE: case DOUBLE:
writer.append("$rt_createDoubleArray("); writer.append("$rt_createDoubleArray(");
precedence = Precedence.min();
expr.getLength().acceptVisitor(this); expr.getLength().acceptVisitor(this);
writer.append(")"); writer.append(")");
break; break;
case CHARACTER: case CHARACTER:
writer.append("$rt_createCharArray("); writer.append("$rt_createCharArray(");
precedence = Precedence.min();
expr.getLength().acceptVisitor(this); expr.getLength().acceptVisitor(this);
writer.append(")"); writer.append(")");
break; break;
@ -1900,10 +2038,10 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
} else { } else {
writer.appendFunction("$rt_createArray").append("(").append(typeToClsString(naming, expr.getType())) writer.appendFunction("$rt_createArray").append("(").append(typeToClsString(naming, expr.getType()))
.append(",").ws(); .append(",").ws();
precedence = Precedence.min();
expr.getLength().acceptVisitor(this); expr.getLength().acceptVisitor(this);
writer.append(")"); writer.append(")");
} }
exitPriority();
if (expr.getLocation() != null) { if (expr.getLocation() != null) {
popLocation(); popLocation();
} }
@ -1922,7 +2060,6 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
for (int i = 0; i < expr.getDimensions().size(); ++i) { for (int i = 0; i < expr.getDimensions().size(); ++i) {
type = ((ValueType.Array) type).getItemType(); type = ((ValueType.Array) type).getItemType();
} }
enterPriority(Priority.COMMA, Associativity.NONE, false);
if (type instanceof ValueType.Primitive) { if (type instanceof ValueType.Primitive) {
switch (((ValueType.Primitive) type).getKind()) { switch (((ValueType.Primitive) type).getKind()) {
case BOOLEAN: case BOOLEAN:
@ -1963,10 +2100,10 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
writer.append(",").ws(); writer.append(",").ws();
} }
first = false; first = false;
precedence = Precedence.min();
dimension.acceptVisitor(this); dimension.acceptVisitor(this);
} }
writer.append("])"); writer.append("])");
exitPriority();
if (expr.getLocation() != null) { if (expr.getLocation() != null) {
popLocation(); popLocation();
} }
@ -1985,21 +2122,19 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
String clsName = ((ValueType.Object) expr.getType()).getClassName(); String clsName = ((ValueType.Object) expr.getType()).getClassName();
ClassHolder cls = classSource.get(clsName); ClassHolder cls = classSource.get(clsName);
if (cls != null && !cls.getModifiers().contains(ElementModifier.INTERFACE)) { if (cls != null && !cls.getModifiers().contains(ElementModifier.INTERFACE)) {
enterPriority(Priority.COMPARISON, Associativity.LEFT, true); precedence = Precedence.COMPARISON.next();
expr.getExpr().acceptVisitor(this); expr.getExpr().acceptVisitor(this);
writer.append(" instanceof ").appendClass(clsName); writer.append(" instanceof ").appendClass(clsName);
exitPriority();
if (expr.getLocation() != null) { if (expr.getLocation() != null) {
popLocation(); popLocation();
} }
return; return;
} }
} }
enterPriority(Priority.COMMA, Associativity.NONE, false);
writer.appendFunction("$rt_isInstance").append("("); writer.appendFunction("$rt_isInstance").append("(");
precedence = Precedence.min();
expr.getExpr().acceptVisitor(this); expr.getExpr().acceptVisitor(this);
writer.append(",").ws().append(typeToClsString(naming, expr.getType())).append(")"); writer.append(",").ws().append(typeToClsString(naming, expr.getType())).append(")");
exitPriority();
if (expr.getLocation() != null) { if (expr.getLocation() != null) {
popLocation(); popLocation();
} }
@ -2095,6 +2230,7 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
MethodReference monitorEnterRef = new MethodReference( MethodReference monitorEnterRef = new MethodReference(
Object.class, "monitorEnter", Object.class, void.class); Object.class, "monitorEnter", Object.class, void.class);
writer.appendMethodBody(monitorEnterRef).append("("); writer.appendMethodBody(monitorEnterRef).append("(");
precedence = Precedence.min();
statement.getObjectRef().acceptVisitor(this); statement.getObjectRef().acceptVisitor(this);
writer.append(");").softNewLine(); writer.append(");").softNewLine();
emitSuspendChecker(); emitSuspendChecker();
@ -2102,6 +2238,7 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
MethodReference monitorEnterRef = new MethodReference( MethodReference monitorEnterRef = new MethodReference(
Object.class, "monitorEnterSync", Object.class, void.class); Object.class, "monitorEnterSync", Object.class, void.class);
writer.appendMethodBody(monitorEnterRef).append('('); writer.appendMethodBody(monitorEnterRef).append('(');
precedence = Precedence.min();
statement.getObjectRef().acceptVisitor(this); statement.getObjectRef().acceptVisitor(this);
writer.append(");").softNewLine(); writer.append(");").softNewLine();
} }
@ -2124,12 +2261,14 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
MethodReference monitorExitRef = new MethodReference( MethodReference monitorExitRef = new MethodReference(
Object.class, "monitorExit", Object.class, void.class); Object.class, "monitorExit", Object.class, void.class);
writer.appendMethodBody(monitorExitRef).append("("); writer.appendMethodBody(monitorExitRef).append("(");
precedence = Precedence.min();
statement.getObjectRef().acceptVisitor(this); statement.getObjectRef().acceptVisitor(this);
writer.append(");").softNewLine(); writer.append(");").softNewLine();
} else { } else {
MethodReference monitorEnterRef = new MethodReference( MethodReference monitorEnterRef = new MethodReference(
Object.class, "monitorExitSync", Object.class, void.class); Object.class, "monitorExitSync", Object.class, void.class);
writer.appendMethodBody(monitorEnterRef).append('('); writer.appendMethodBody(monitorEnterRef).append('(');
precedence = Precedence.min();
statement.getObjectRef().acceptVisitor(this); statement.getObjectRef().acceptVisitor(this);
writer.append(");").softNewLine(); writer.append(");").softNewLine();
} }
@ -2175,6 +2314,7 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
private class InjectorContextImpl implements InjectorContext { private class InjectorContextImpl implements InjectorContext {
private List<Expr> arguments; private List<Expr> arguments;
private Precedence precedence = Renderer.this.precedence;
public InjectorContextImpl(List<Expr> arguments) { public InjectorContextImpl(List<Expr> arguments) {
this.arguments = arguments; this.arguments = arguments;
@ -2207,6 +2347,12 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
@Override @Override
public void writeExpr(Expr expr) throws IOException { public void writeExpr(Expr expr) throws IOException {
writeExpr(expr, Precedence.GROUPING);
}
@Override
public void writeExpr(Expr expr, Precedence precedence) throws IOException {
Renderer.this.precedence = precedence;
expr.acceptVisitor(Renderer.this); expr.acceptVisitor(Renderer.this);
} }
@ -2224,6 +2370,11 @@ public class Renderer implements ExprVisitor, StatementVisitor, RenderingContext
public Properties getProperties() { public Properties getProperties() {
return new Properties(properties); return new Properties(properties);
} }
@Override
public Precedence getPrecedence() {
return precedence;
}
} }
@Override @Override

View File

@ -19,6 +19,7 @@ import java.io.IOException;
import java.util.Properties; import java.util.Properties;
import org.teavm.codegen.SourceWriter; import org.teavm.codegen.SourceWriter;
import org.teavm.common.ServiceRepository; import org.teavm.common.ServiceRepository;
import org.teavm.javascript.Precedence;
import org.teavm.javascript.ast.Expr; import org.teavm.javascript.ast.Expr;
import org.teavm.model.ValueType; import org.teavm.model.ValueType;
@ -42,4 +43,8 @@ public interface InjectorContext extends ServiceRepository {
void writeType(ValueType type) throws IOException; void writeType(ValueType type) throws IOException;
void writeExpr(Expr expr) throws IOException; void writeExpr(Expr expr) throws IOException;
void writeExpr(Expr expr, Precedence precedence) throws IOException;
Precedence getPrecedence();
} }

View File

@ -78,23 +78,23 @@ import org.teavm.model.MethodReference;
* @author Alexey Andreev * @author Alexey Andreev
*/ */
public class AstWriter { public class AstWriter {
private static final int PRECEDENCE_MEMBER = 2; public static final int PRECEDENCE_MEMBER = 2;
private static final int PRECEDENCE_FUNCTION = 3; public static final int PRECEDENCE_FUNCTION = 3;
private static final int PRECEDENCE_POSTFIX = 4; public static final int PRECEDENCE_POSTFIX = 4;
private static final int PRECEDENCE_PREFIX = 5; public static final int PRECEDENCE_PREFIX = 5;
private static final int PRECEDENCE_MUL = 6; public static final int PRECEDENCE_MUL = 6;
private static final int PRECEDENCE_ADD = 7; public static final int PRECEDENCE_ADD = 7;
private static final int PRECEDENCE_SHIFT = 8; public static final int PRECEDENCE_SHIFT = 8;
private static final int PRECEDENCE_RELATION = 9; public static final int PRECEDENCE_RELATION = 9;
private static final int PRECEDENCE_EQUALITY = 10; public static final int PRECEDENCE_EQUALITY = 10;
private static final int PRECEDENCE_BITWISE_AND = 11; public static final int PRECEDENCE_BITWISE_AND = 11;
private static final int PRECEDENCE_BITWISE_XOR = 12; public static final int PRECEDENCE_BITWISE_XOR = 12;
private static final int PRECEDENCE_BITWISE_OR = 13; public static final int PRECEDENCE_BITWISE_OR = 13;
private static final int PRECEDENCE_AND = 14; public static final int PRECEDENCE_AND = 14;
private static final int PRECEDENCE_OR = 15; public static final int PRECEDENCE_OR = 15;
private static final int PRECEDENCE_COND = 16; public static final int PRECEDENCE_COND = 16;
private static final int PRECEDENCE_ASSIGN = 17; public static final int PRECEDENCE_ASSIGN = 17;
private static final int PRECEDENCE_COMMA = 18; public static final int PRECEDENCE_COMMA = 18;
private SourceWriter writer; private SourceWriter writer;
private Map<String, NameEmitter> nameMap = new HashMap<>(); private Map<String, NameEmitter> nameMap = new HashMap<>();
private Set<String> aliases = new HashSet<>(); private Set<String> aliases = new HashSet<>();
@ -108,13 +108,13 @@ public class AstWriter {
return; return;
} }
if (aliases.add(name)) { if (aliases.add(name)) {
nameMap.put(name, () -> writer.append(name)); nameMap.put(name, p -> writer.append(name));
return; return;
} }
for (int i = 0;; ++i) { for (int i = 0;; ++i) {
String alias = name + "_" + i; String alias = name + "_" + i;
if (aliases.add(alias)) { if (aliases.add(alias)) {
nameMap.put(name, () -> writer.append(alias)); nameMap.put(name, p -> writer.append(alias));
return; return;
} }
} }
@ -124,12 +124,12 @@ public class AstWriter {
if (!aliases.add(alias)) { if (!aliases.add(alias)) {
throw new IllegalArgumentException("Alias " + alias + " is already occupied"); throw new IllegalArgumentException("Alias " + alias + " is already occupied");
} }
nameMap.put(name, () -> writer.append(alias)); nameMap.put(name, p -> writer.append(alias));
} }
public void reserveName(String name) { public void reserveName(String name) {
aliases.add(name); aliases.add(name);
nameMap.put(name, () -> writer.append(name)); nameMap.put(name, p -> writer.append(name));
} }
public void declareNameEmitter(String name, NameEmitter emitter) { public void declareNameEmitter(String name, NameEmitter emitter) {
@ -157,7 +157,7 @@ public class AstWriter {
print(node, PRECEDENCE_COMMA); print(node, PRECEDENCE_COMMA);
} }
private void print(AstNode node, int precedence) throws IOException { public void print(AstNode node, int precedence) throws IOException {
switch (node.getType()) { switch (node.getType()) {
case Token.SCRIPT: case Token.SCRIPT:
print((AstRoot) node); print((AstRoot) node);
@ -192,7 +192,7 @@ public class AstWriter {
break; break;
case Token.THIS: case Token.THIS:
if (nameMap.containsKey("this")) { if (nameMap.containsKey("this")) {
nameMap.get("this").emit(); nameMap.get("this").emit(precedence);
} else { } else {
writer.append("this"); writer.append("this");
} }
@ -201,7 +201,7 @@ public class AstWriter {
writer.append("null"); writer.append("null");
break; break;
case Token.NAME: case Token.NAME:
print((Name) node); print((Name) node, precedence);
break; break;
case Token.REGEXP: case Token.REGEXP:
print((RegExpLiteral) node); print((RegExpLiteral) node);
@ -633,12 +633,12 @@ public class AstWriter {
writer.append(node.getQuoteCharacter()); writer.append(node.getQuoteCharacter());
} }
private void print(Name node) throws IOException { private void print(Name node, int precedence) throws IOException {
NameEmitter alias = nameMap.get(node.getIdentifier()); NameEmitter alias = nameMap.get(node.getIdentifier());
if (alias == null) { if (alias == null) {
alias = () -> writer.append(node.getIdentifier()); alias = prec -> writer.append(node.getIdentifier());
} }
alias.emit(); alias.emit(precedence);
} }
private void print(RegExpLiteral node) throws IOException { private void print(RegExpLiteral node) throws IOException {

View File

@ -18,6 +18,7 @@ package org.teavm.jso.impl;
import java.io.IOException; import java.io.IOException;
import org.mozilla.javascript.ast.AstNode; import org.mozilla.javascript.ast.AstNode;
import org.teavm.codegen.SourceWriter; import org.teavm.codegen.SourceWriter;
import org.teavm.javascript.Precedence;
import org.teavm.javascript.spi.GeneratorContext; import org.teavm.javascript.spi.GeneratorContext;
import org.teavm.javascript.spi.InjectorContext; import org.teavm.javascript.spi.InjectorContext;
import org.teavm.model.MethodReference; import org.teavm.model.MethodReference;
@ -43,14 +44,97 @@ class JSBodyAstEmitter implements JSBodyEmitter {
int paramIndex = 0; int paramIndex = 0;
if (!isStatic) { if (!isStatic) {
int index = paramIndex++; int index = paramIndex++;
astWriter.declareNameEmitter("this", () -> context.writeExpr(context.getArgument(index))); astWriter.declareNameEmitter("this", prec -> context.writeExpr(context.getArgument(index)));
} }
for (int i = 0; i < parameterNames.length; ++i) { for (int i = 0; i < parameterNames.length; ++i) {
int index = paramIndex++; int index = paramIndex++;
astWriter.declareNameEmitter(parameterNames[i], () -> context.writeExpr(context.getArgument(index))); astWriter.declareNameEmitter(parameterNames[i],
prec -> context.writeExpr(context.getArgument(index), convert(prec)));
} }
astWriter.hoist(ast); astWriter.hoist(ast);
astWriter.print(ast); astWriter.print(ast, convert(context.getPrecedence()));
}
private static int convert(Precedence precedence) {
switch (precedence) {
case ADDITION:
return AstWriter.PRECEDENCE_ADD;
case ASSIGNMENT:
return AstWriter.PRECEDENCE_ASSIGN;
case BITWISE_AND:
return AstWriter.PRECEDENCE_BITWISE_AND;
case BITWISE_OR:
return AstWriter.PRECEDENCE_BITWISE_OR;
case BITWISE_XOR:
return AstWriter.PRECEDENCE_BITWISE_XOR;
case BITWISE_SHIFT:
return AstWriter.PRECEDENCE_SHIFT;
case COMMA:
return AstWriter.PRECEDENCE_COMMA;
case COMPARISON:
return AstWriter.PRECEDENCE_RELATION;
case CONDITIONAL:
return AstWriter.PRECEDENCE_COND;
case EQUALITY:
return AstWriter.PRECEDENCE_EQUALITY;
case FUNCTION_CALL:
return AstWriter.PRECEDENCE_FUNCTION;
case GROUPING:
return 1;
case LOGICAL_AND:
return AstWriter.PRECEDENCE_AND;
case LOGICAL_OR:
return AstWriter.PRECEDENCE_OR;
case MEMBER_ACCESS:
return AstWriter.PRECEDENCE_MEMBER;
case MULTIPLICATION:
return AstWriter.PRECEDENCE_MUL;
case UNARY:
return AstWriter.PRECEDENCE_PREFIX;
default:
return AstWriter.PRECEDENCE_COMMA;
}
}
private static Precedence convert(int precedence) {
switch (precedence) {
case AstWriter.PRECEDENCE_ADD:
return Precedence.ADDITION;
case AstWriter.PRECEDENCE_ASSIGN:
return Precedence.ASSIGNMENT;
case AstWriter.PRECEDENCE_BITWISE_AND:
return Precedence.BITWISE_AND;
case AstWriter.PRECEDENCE_BITWISE_OR:
return Precedence.BITWISE_OR;
case AstWriter.PRECEDENCE_BITWISE_XOR:
return Precedence.BITWISE_XOR;
case AstWriter.PRECEDENCE_SHIFT:
return Precedence.BITWISE_SHIFT;
case AstWriter.PRECEDENCE_COMMA:
return Precedence.COMMA;
case AstWriter.PRECEDENCE_RELATION:
return Precedence.COMPARISON;
case AstWriter.PRECEDENCE_COND:
return Precedence.CONDITIONAL;
case AstWriter.PRECEDENCE_EQUALITY:
return Precedence.EQUALITY;
case AstWriter.PRECEDENCE_FUNCTION:
return Precedence.FUNCTION_CALL;
case 1:
return Precedence.GROUPING;
case AstWriter.PRECEDENCE_AND:
return Precedence.LOGICAL_AND;
case AstWriter.PRECEDENCE_OR:
return Precedence.LOGICAL_OR;
case AstWriter.PRECEDENCE_MEMBER:
return Precedence.MEMBER_ACCESS;
case AstWriter.PRECEDENCE_MUL:
return Precedence.MULTIPLICATION;
case AstWriter.PRECEDENCE_PREFIX:
return Precedence.UNARY;
default:
return Precedence.min();
}
} }
@Override @Override
@ -59,11 +143,11 @@ class JSBodyAstEmitter implements JSBodyEmitter {
int paramIndex = 1; int paramIndex = 1;
if (!isStatic) { if (!isStatic) {
int index = paramIndex++; int index = paramIndex++;
astWriter.declareNameEmitter("this", () -> writer.append(context.getParameterName(index))); astWriter.declareNameEmitter("this", prec -> writer.append(context.getParameterName(index)));
} }
for (int i = 0; i < parameterNames.length; ++i) { for (int i = 0; i < parameterNames.length; ++i) {
int index = paramIndex++; int index = paramIndex++;
astWriter.declareNameEmitter(parameterNames[i], () -> writer.append(context.getParameterName(index))); astWriter.declareNameEmitter(parameterNames[i], prec -> writer.append(context.getParameterName(index)));
} }
astWriter.hoist(ast); astWriter.hoist(ast);
astWriter.print(ast); astWriter.print(ast);

View File

@ -22,5 +22,5 @@ import java.io.IOException;
* @author Alexey Andreev * @author Alexey Andreev
*/ */
interface NameEmitter { interface NameEmitter {
void emit() throws IOException; void emit(int precedence) throws IOException;
} }

View File

@ -13,14 +13,26 @@
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
*/ */
package org.teavm.javascript; package org.teavm.jso;
import static org.junit.Assert.*;
import org.junit.Test;
import org.teavm.jso.JSBody;
/** /**
* *
* @author Alexey Andreev * @author Alexey Andreev
*/ */
public enum Associativity { public class ImplementationTest {
LEFT, @Test
RIGHT, public void respectsPrecedence() {
NONE assertEquals(12, mul(add(2, 2), 3));
assertEquals(8, add(2, mul(2, 3)));
}
@JSBody(params = { "a", "b" }, script = "return a + b;")
static final native int add(int a, int b);
@JSBody(params = { "a", "b" }, script = "return a * b;")
static final native int mul(int a, int b);
} }