use of org.mvel2.ast.And in project mvel by mvel.
the class AbstractParser method reduce.
/**
* This method is called when we reach the point where we must subEval a trinary operation in the expression.
* (ie. val1 op val2). This is not the same as a binary operation, although binary operations would appear
* to have 3 structures as well. A binary structure (or also a junction in the expression) compares the
* current state against 2 downrange structures (usually an op and a val).
*/
protected void reduce() {
Object v1, v2;
int operator;
try {
switch(operator = (Integer) stk.pop()) {
case ADD:
case SUB:
case DIV:
case MULT:
case MOD:
case EQUAL:
case NEQUAL:
case GTHAN:
case LTHAN:
case GETHAN:
case LETHAN:
case POWER:
stk.op(operator);
break;
case AND:
v1 = stk.pop();
stk.push(((Boolean) stk.pop()) && ((Boolean) v1));
break;
case OR:
v1 = stk.pop();
stk.push(((Boolean) stk.pop()) || ((Boolean) v1));
break;
case CHOR:
v1 = stk.pop();
if (!isEmpty(v2 = stk.pop()) || !isEmpty(v1)) {
stk.clear();
stk.push(!isEmpty(v2) ? v2 : v1);
return;
} else
stk.push(null);
break;
case REGEX:
stk.push(java.util.regex.Pattern.compile(java.lang.String.valueOf(stk.pop())).matcher(java.lang.String.valueOf(stk.pop())).matches());
break;
case INSTANCEOF:
stk.push(((Class) stk.pop()).isInstance(stk.pop()));
break;
case CONVERTABLE_TO:
stk.push(org.mvel2.DataConversion.canConvert(stk.peek2().getClass(), (Class) stk.pop2()));
break;
case CONTAINS:
stk.push(containsCheck(stk.peek2(), stk.pop2()));
break;
case SOUNDEX:
stk.push(soundex(java.lang.String.valueOf(stk.pop())).equals(soundex(java.lang.String.valueOf(stk.pop()))));
break;
case SIMILARITY:
stk.push(similarity(java.lang.String.valueOf(stk.pop()), java.lang.String.valueOf(stk.pop())));
break;
default:
reduceNumeric(operator);
}
} catch (ClassCastException e) {
throw new CompileException("syntax error or incompatable types", expr, st, e);
} catch (ArithmeticException e) {
throw new CompileException("arithmetic error: " + e.getMessage(), expr, st, e);
} catch (Exception e) {
throw new CompileException("failed to subEval expression", expr, st, e);
}
}
use of org.mvel2.ast.And in project mvel by mvel.
the class MVEL method analysisCompile.
/**
* Performs an analysis compileShared, which will populate the ParserContext with type, input and variable information,
* but will not produce a payload.
*
* @param expression - the expression to analyze
* @param ctx - the parser context
*/
public static void analysisCompile(char[] expression, ParserContext ctx) {
ExpressionCompiler compiler = new ExpressionCompiler(expression, ctx);
compiler.setVerifyOnly(true);
compiler.compile();
}
use of org.mvel2.ast.And in project mvel by mvel.
the class TemplateCompiler method compileFrom.
public Node compileFrom(Node root, ExecutionStack stack) {
line = 1;
Node n = root;
if (root == null) {
n = root = new TextNode(0, 0);
}
IfNode last;
Integer opcode;
String name;
int x;
try {
while (cursor < length) {
switch(template[cursor]) {
case '\n':
line++;
colStart = cursor + 1;
break;
case '@':
case '$':
if (isNext(template[cursor])) {
start = ++cursor;
(n = markTextNode(n)).setEnd(n.getEnd() + 1);
start = lastTextRangeEnding = ++cursor;
continue;
}
if ((x = captureOrbToken()) != -1) {
start = x;
switch((opcode = OPCODES.get(name = new String(capture()))) == null ? 0 : opcode) {
case Opcodes.IF:
/**
* Capture any residual text node, and push the if statement on the nesting stack.
*/
stack.push(n = markTextNode(n).next = codeCache ? new CompiledIfNode(start, name, template, captureOrbInternal(), start, parserContext) : new IfNode(start, name, template, captureOrbInternal(), start));
n.setTerminus(new TerminalNode());
break;
case Opcodes.ELSE:
if (!stack.isEmpty() && stack.peek() instanceof IfNode) {
markTextNode(n).next = (last = (IfNode) stack.pop()).getTerminus();
last.demarcate(last.getTerminus(), template);
last.next = n = codeCache ? new CompiledIfNode(start, name, template, captureOrbInternal(), start, parserContext) : new IfNode(start, name, template, captureOrbInternal(), start);
n.setTerminus(last.getTerminus());
stack.push(n);
}
break;
case Opcodes.FOREACH:
stack.push(n = markTextNode(n).next = codeCache ? new CompiledForEachNode(start, name, template, captureOrbInternal(), start, parserContext) : new ForEachNode(start, name, template, captureOrbInternal(), start));
n.setTerminus(new TerminalNode());
break;
case Opcodes.INCLUDE_FILE:
n = markTextNode(n).next = codeCache ? new CompiledIncludeNode(start, name, template, captureOrbInternal(), start = cursor + 1, parserContext) : new IncludeNode(start, name, template, captureOrbInternal(), start = cursor + 1);
break;
case Opcodes.INCLUDE_NAMED:
n = markTextNode(n).next = codeCache ? new CompiledNamedIncludeNode(start, name, template, captureOrbInternal(), start = cursor + 1, parserContext) : new NamedIncludeNode(start, name, template, captureOrbInternal(), start = cursor + 1);
break;
case Opcodes.CODE:
n = markTextNode(n).next = codeCache ? new CompiledCodeNode(start, name, template, captureOrbInternal(), start = cursor + 1, parserContext) : new CodeNode(start, name, template, captureOrbInternal(), start = cursor + 1);
break;
case Opcodes.EVAL:
n = markTextNode(n).next = codeCache ? new CompiledEvalNode(start, name, template, captureOrbInternal(), start = cursor + 1, parserContext) : new EvalNode(start, name, template, captureOrbInternal(), start = cursor + 1);
break;
case Opcodes.COMMENT:
n = markTextNode(n).next = new CommentNode(start, name, template, captureOrbInternal(), start = cursor + 1);
break;
case Opcodes.DECLARE:
stack.push(n = markTextNode(n).next = codeCache ? new CompiledDeclareNode(start, name, template, captureOrbInternal(), start = cursor + 1, parserContext) : new DeclareNode(start, name, template, captureOrbInternal(), start = cursor + 1));
n.setTerminus(new TerminalNode());
break;
case Opcodes.END:
n = markTextNode(n);
Node end = (Node) stack.pop();
Node terminal = end.getTerminus();
terminal.setCStart(captureOrbInternal());
terminal.setEnd((lastTextRangeEnding = start) - 1);
terminal.calculateContents(template);
if (end.demarcate(terminal, template))
n = n.next = terminal;
else
n = terminal;
break;
default:
if (name.length() == 0) {
n = markTextNode(n).next = codeCache ? new CompiledExpressionNode(start, name, template, captureOrbInternal(), start = cursor + 1, parserContext) : new ExpressionNode(start, name, template, captureOrbInternal(), start = cursor + 1);
} else if (customNodes != null && customNodes.containsKey(name)) {
Class<? extends Node> customNode = customNodes.get(name);
try {
(n = markTextNode(n).next = (customNode.newInstance())).setBegin(start);
n.setName(name);
n.setCStart(captureOrbInternal());
n.setCEnd(start = cursor + 1);
n.setEnd(n.getCEnd());
n.setContents(subset(template, n.getCStart(), n.getCEnd() - n.getCStart() - 1));
if (n.isOpenNode()) {
stack.push(n);
}
} catch (InstantiationException e) {
throw new RuntimeException("unable to instantiate custom node class: " + customNode.getName());
} catch (IllegalAccessException e) {
throw new RuntimeException("unable to instantiate custom node class: " + customNode.getName());
}
} else {
throw new RuntimeException("unknown token type: " + name);
}
}
}
break;
}
cursor++;
}
} catch (RuntimeException e) {
CompileException ce = new CompileException(e.getMessage(), template, cursor, e);
ce.setExpr(template);
if (e instanceof CompileException) {
CompileException ce2 = (CompileException) e;
if (ce2.getCursor() != -1) {
ce.setCursor(ce2.getCursor());
if (ce2.getColumn() == -1)
ce.setColumn(ce.getCursor() - colStart);
else
ce.setColumn(ce2.getColumn());
}
}
ce.setLineNumber(line);
throw ce;
}
if (!stack.isEmpty()) {
CompileException ce = new CompileException("unclosed @" + ((Node) stack.peek()).getName() + "{} block. expected @end{}", template, cursor);
ce.setColumn(cursor - colStart);
ce.setLineNumber(line);
throw ce;
}
if (start < template.length) {
n = n.next = new TextNode(start, template.length);
}
n.next = new EndNode();
n = root;
do {
if (n.getLength() != 0) {
break;
}
} while ((n = n.getNext()) != null);
if (n != null && n.getLength() == template.length - 1) {
if (n instanceof ExpressionNode) {
return codeCache ? new CompiledTerminalExpressionNode(n, parserContext) : new TerminalExpressionNode(n);
} else {
return n;
}
}
return root;
}
use of org.mvel2.ast.And in project mvel by mvel.
the class ProtoParser method parse.
public Proto parse() {
Proto proto = new Proto(protoName, pCtx);
Mainloop: while (cursor < endOffset) {
cursor = ParseTools.skipWhitespace(expr, cursor);
int start = cursor;
if (tk2 == null) {
while (cursor < endOffset && isIdentifierPart(expr[cursor])) cursor++;
if (cursor > start) {
tk1 = new String(expr, start, cursor - start);
if ("def".equals(tk1) || "function".equals(tk1)) {
cursor++;
cursor = ParseTools.skipWhitespace(expr, cursor);
start = cursor;
while (cursor < endOffset && isIdentifierPart(expr[cursor])) cursor++;
if (start == cursor) {
throw new CompileException("attempt to declare an anonymous function as a prototype member", expr, start);
}
FunctionParser parser = new FunctionParser(new String(expr, start, cursor - start), cursor, endOffset, expr, 0, pCtx, null);
proto.declareReceiver(parser.getName(), parser.parse());
cursor = parser.getCursor() + 1;
tk1 = null;
continue;
}
}
cursor = ParseTools.skipWhitespace(expr, cursor);
}
if (cursor > endOffset) {
throw new CompileException("unexpected end of statement in proto declaration: " + protoName, expr, start);
}
switch(expr[cursor]) {
case ';':
cursor++;
calculateDecl();
if (interpreted && type == DeferredTypeResolve.class) {
/**
* If this type could not be immediately resolved, it may be a look-ahead case, so
* we defer resolution of the type until later and place it in the wait queue.
*/
enqueueReceiverForLateResolution(deferredName, proto.declareReceiver(name, Proto.ReceiverType.DEFERRED, null), null);
} else {
proto.declareReceiver(name, type, null);
}
break;
case '=':
cursor++;
cursor = ParseTools.skipWhitespace(expr, cursor);
start = cursor;
Loop: while (cursor < endOffset) {
switch(expr[cursor]) {
case '{':
case '[':
case '(':
case '\'':
case '"':
cursor = balancedCaptureWithLineAccounting(expr, cursor, endOffset, expr[cursor], pCtx);
break;
case ';':
break Loop;
}
cursor++;
}
calculateDecl();
String initString = new String(expr, start, cursor++ - start);
if (interpreted && type == DeferredTypeResolve.class) {
enqueueReceiverForLateResolution(deferredName, proto.declareReceiver(name, Proto.ReceiverType.DEFERRED, null), initString);
} else {
proto.declareReceiver(name, type, (ExecutableStatement) subCompileExpression(initString, pCtx));
}
break;
default:
start = cursor;
while (cursor < endOffset && isIdentifierPart(expr[cursor])) cursor++;
if (cursor > start) {
tk2 = new String(expr, start, cursor - start);
}
}
}
cursor++;
/**
* Check if the function is manually terminated.
*/
if (splitAccumulator != null && ParseTools.isStatementNotManuallyTerminated(expr, cursor)) {
/**
* Add an EndOfStatement to the split accumulator in the parser.
*/
splitAccumulator.add(new EndOfStatement(pCtx));
}
return proto;
}
use of org.mvel2.ast.And in project mvel by mvel.
the class ASMAccessorOptimizer method getBeanProperty.
private Object getBeanProperty(Object ctx, String property) throws IllegalAccessException, InvocationTargetException {
assert debug("\n ** ENTER -> {bean: " + property + "; ctx=" + ctx + "}");
if ((pCtx == null ? currType : pCtx.getVarOrInputTypeOrNull(property)) == Object.class && !pCtx.isStrongTyping()) {
currType = null;
}
if (returnType != null && returnType.isPrimitive()) {
// noinspection unchecked
wrapPrimitive(returnType);
}
boolean classRef = false;
Class<?> cls;
if (ctx instanceof Class) {
if (MVEL.COMPILER_OPT_SUPPORT_JAVA_STYLE_CLASS_LITERALS && "class".equals(property)) {
ldcClassConstant((Class<?>) ctx);
return ctx;
}
cls = (Class<?>) ctx;
classRef = true;
} else if (ctx != null) {
cls = ctx.getClass();
} else {
cls = null;
}
if (hasPropertyHandler(cls)) {
PropertyHandler prop = getPropertyHandler(cls);
if (prop instanceof ProducesBytecode) {
((ProducesBytecode) prop).produceBytecodeGet(mv, property, variableFactory);
return prop.getProperty(property, ctx, variableFactory);
} else {
throw new RuntimeException("unable to compileShared: custom accessor does not support producing bytecode: " + prop.getClass().getName());
}
}
Member member = cls != null ? getFieldOrAccessor(cls, property) : null;
if (member != null && classRef && (member.getModifiers() & Modifier.STATIC) == 0) {
member = null;
}
if (member != null && hasGetListeners()) {
mv.visitVarInsn(ALOAD, 1);
mv.visitLdcInsn(member.getName());
mv.visitVarInsn(ALOAD, 3);
mv.visitMethodInsn(INVOKESTATIC, NAMESPACE + "integration/GlobalListenerFactory", "notifyGetListeners", "(Ljava/lang/Object;Ljava/lang/String;L" + NAMESPACE + "integration/VariableResolverFactory;)V");
notifyGetListeners(ctx, member.getName(), variableFactory);
}
if (first) {
if ("this".equals(property)) {
assert debug("ALOAD 2");
mv.visitVarInsn(ALOAD, 2);
return thisRef;
} else if (variableFactory != null && variableFactory.isResolveable(property)) {
if (variableFactory.isIndexedFactory() && variableFactory.isTarget(property)) {
int idx;
try {
loadVariableByIndex(idx = variableFactory.variableIndexOf(property));
} catch (Exception e) {
throw new OptimizationFailure(property);
}
return variableFactory.getIndexedVariableResolver(idx).getValue();
} else {
try {
loadVariableByName(property);
} catch (Exception e) {
throw new OptimizationFailure("critical error in JIT", e);
}
return variableFactory.getVariableResolver(property).getValue();
}
} else {
assert debug("ALOAD 1");
mv.visitVarInsn(ALOAD, 1);
}
}
if (member instanceof Field) {
return optimizeFieldMethodProperty(ctx, property, cls, member);
} else if (member != null) {
Object o;
if (first) {
assert debug("ALOAD 1 (B)");
mv.visitVarInsn(ALOAD, 1);
}
try {
o = ((Method) member).invoke(ctx, EMPTYARG);
if (returnType != member.getDeclaringClass()) {
assert debug("CHECKCAST " + getInternalName(member.getDeclaringClass()));
mv.visitTypeInsn(CHECKCAST, getInternalName(member.getDeclaringClass()));
}
returnType = ((Method) member).getReturnType();
assert debug("INVOKEVIRTUAL " + member.getName() + ":" + returnType);
mv.visitMethodInsn(INVOKEVIRTUAL, getInternalName(member.getDeclaringClass()), member.getName(), getMethodDescriptor((Method) member));
} catch (IllegalAccessException e) {
Method iFaceMeth = determineActualTargetMethod((Method) member);
if (iFaceMeth == null)
throw new PropertyAccessException("could not access field: " + cls.getName() + "." + property, expr, st, e, pCtx);
assert debug("CHECKCAST " + getInternalName(iFaceMeth.getDeclaringClass()));
mv.visitTypeInsn(CHECKCAST, getInternalName(iFaceMeth.getDeclaringClass()));
returnType = iFaceMeth.getReturnType();
assert debug("INVOKEINTERFACE " + member.getName() + ":" + returnType);
mv.visitMethodInsn(INVOKEINTERFACE, getInternalName(iFaceMeth.getDeclaringClass()), member.getName(), getMethodDescriptor((Method) member));
o = iFaceMeth.invoke(ctx, EMPTYARG);
} catch (IllegalArgumentException e) {
if (member.getDeclaringClass().equals(ctx)) {
try {
Class c = Class.forName(member.getDeclaringClass().getName() + "$" + property);
throw new CompileException("name collision between innerclass: " + c.getCanonicalName() + "; and bean accessor: " + property + " (" + member.toString() + ")", expr, tkStart);
} catch (ClassNotFoundException e2) {
// fallthru
}
}
throw e;
}
if (hasNullPropertyHandler()) {
if (o == null)
o = getNullPropertyHandler().getProperty(member.getName(), ctx, variableFactory);
writeOutNullHandler(member, 0);
}
currType = toNonPrimitiveType(returnType);
return o;
} else if (ctx instanceof Map && (((Map) ctx).containsKey(property) || nullSafe)) {
assert debug("CHECKCAST java/util/Map");
mv.visitTypeInsn(CHECKCAST, "java/util/Map");
assert debug("LDC: \"" + property + "\"");
mv.visitLdcInsn(property);
assert debug("INVOKEINTERFACE: get");
mv.visitMethodInsn(INVOKEINTERFACE, "java/util/Map", "get", "(Ljava/lang/Object;)Ljava/lang/Object;");
return ((Map) ctx).get(property);
} else if (first && "this".equals(property)) {
assert debug("ALOAD 2");
// load the thisRef value.
mv.visitVarInsn(ALOAD, 2);
return this.thisRef;
} else if ("length".equals(property) && ctx.getClass().isArray()) {
anyArrayCheck(ctx.getClass());
assert debug("ARRAYLENGTH");
mv.visitInsn(ARRAYLENGTH);
wrapPrimitive(int.class);
return getLength(ctx);
} else if (LITERALS.containsKey(property)) {
Object lit = LITERALS.get(property);
if (lit instanceof Class) {
ldcClassConstant((Class) lit);
}
return lit;
} else {
Object ts = tryStaticAccess();
if (ts != null) {
if (ts instanceof Class) {
ldcClassConstant((Class) ts);
return ts;
} else if (ts instanceof Method) {
writeFunctionPointerStub(((Method) ts).getDeclaringClass(), (Method) ts);
return ts;
} else {
Field f = (Field) ts;
return optimizeFieldMethodProperty(ctx, property, cls, f);
}
} else if (ctx instanceof Class) {
/**
* This is our ugly support for function pointers. This works but needs to be re-thought out at some
* point.
*/
Class c = (Class) ctx;
for (Method m : c.getMethods()) {
if (property.equals(m.getName())) {
if (pCtx != null && pCtx.getParserConfiguration() != null ? pCtx.getParserConfiguration().isAllowNakedMethCall() : MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL) {
assert debug("POP");
mv.visitInsn(POP);
assert debug("INVOKESTATIC " + m.getName());
mv.visitMethodInsn(INVOKESTATIC, getInternalName(m.getDeclaringClass()), m.getName(), getMethodDescriptor(m));
returnType = m.getReturnType();
return m.invoke(null, EMPTY_OBJ_ARR);
} else {
writeFunctionPointerStub(c, m);
return m;
}
}
}
try {
Class subClass = findClass(variableFactory, c.getName() + "$" + property, pCtx);
ldcClassConstant(subClass);
return subClass;
} catch (ClassNotFoundException cnfe) {
// fall through.
}
} else if (pCtx != null && pCtx.getParserConfiguration() != null ? pCtx.getParserConfiguration().isAllowNakedMethCall() : MVEL.COMPILER_OPT_ALLOW_NAKED_METH_CALL) {
return getMethod(ctx, property);
}
if (ctx == null) {
throw new PropertyAccessException("unresolvable property or identifier: " + property, expr, st, pCtx);
} else {
throw new PropertyAccessException("could not access: " + property + "; in class: " + ctx.getClass().getName(), expr, st, pCtx);
}
}
}
Aggregations