Search in sources :

Example 11 with TransformerException

use of lucee.transformer.TransformerException in project Lucee by lucee.

the class VT method getMatchingValueAndType.

private static VT getMatchingValueAndType(Factory factory, FunctionLibFunctionArg flfa, NamedArgument[] nargs, String[] names, Position line) throws TransformerException {
    String flfan = flfa.getName();
    // first search if a argument match
    for (int i = 0; i < nargs.length; i++) {
        if (names[i] != null && names[i].equalsIgnoreCase(flfan)) {
            nargs[i].setValue(nargs[i].getRawValue(), flfa.getTypeAsString());
            return new VT(nargs[i].getValue(), flfa.getTypeAsString(), i);
        }
    }
    // then check if a alias match
    String alias = flfa.getAlias();
    if (!StringUtil.isEmpty(alias)) {
        // String[] arrAlias = lucee.runtime.type.List.toStringArray(lucee.runtime.type.List.trimItems(lucee.runtime.type.List.listToArrayRemoveEmpty(alias, ',')));
        for (int i = 0; i < nargs.length; i++) {
            if (names[i] != null && lucee.runtime.type.util.ListUtil.listFindNoCase(alias, names[i], ",") != -1) {
                nargs[i].setValue(nargs[i].getRawValue(), flfa.getTypeAsString());
                return new VT(nargs[i].getValue(), flfa.getTypeAsString(), i);
            }
        }
    }
    // if not required return the default value
    if (!flfa.getRequired()) {
        return getDefaultValue(factory, flfa);
    }
    TransformerException be = new TransformerException("missing required argument [" + flfan + "] for function [" + flfa.getFunction().getName() + "]", line);
    UDFUtil.addFunctionDoc(be, flfa.getFunction());
    throw be;
}
Also used : LitString(lucee.transformer.expression.literal.LitString) ExprString(lucee.transformer.expression.ExprString) TransformerException(lucee.transformer.TransformerException)

Example 12 with TransformerException

use of lucee.transformer.TransformerException in project Lucee by lucee.

the class OPUnary method _writeOut.

@Override
public Type _writeOut(BytecodeContext bc, int mode) throws TransformerException {
    GeneratorAdapter adapter = bc.getAdapter();
    // convert value
    if (operation == CONCAT)
        value = CastString.toExprString(value);
    else
        value = CastDouble.toExprDouble(value);
    List<Member> members = var.getMembers();
    int size = members.size();
    String scope = VariableInterpreter.scopeInt2String(var.getScope());
    /*
		 *  (susi.sorglos++ or variables.susi++)
		 */
    if ((scope == null && size > 1) || (scope != null && size > 0)) {
        Member last = var.removeMember(members.size() - 1);
        if (!(last instanceof DataMember))
            throw new TransformerException("you cannot use a unary operator with a function " + last.getClass().getName(), getStart());
        // write the variable
        var.setAsCollection(Boolean.TRUE);
        var.writeOut(bc, mode);
        // write out last Key
        getFactory().registerKey(bc, ((DataMember) last).getName(), false);
        // write out value
        value.writeOut(bc, MODE_VALUE);
        if (type == POST) {
            if (operation != OpDouble.PLUS && operation != OpDouble.MINUS)
                throw new TransformerException("Post only possible with plus or minus " + operation, value.getStart());
            if (operation == PLUS)
                adapter.invokeStatic(Types.OPERATOR, UNARY_POST_PLUS2);
            else if (operation == MINUS)
                adapter.invokeStatic(Types.OPERATOR, UNARY_POST_MINUS2);
        } else if (type == PRE) {
            if (operation == PLUS)
                adapter.invokeStatic(Types.OPERATOR, UNARY_PRE_PLUS2);
            else if (operation == MINUS)
                adapter.invokeStatic(Types.OPERATOR, UNARY_PRE_MINUS2);
            else if (operation == DIVIDE)
                adapter.invokeStatic(Types.OPERATOR, UNARY_PRE_DIVIDE2);
            else if (operation == MULTIPLY)
                adapter.invokeStatic(Types.OPERATOR, UNARY_PRE_MULTIPLY2);
            else if (operation == CONCAT)
                adapter.invokeStatic(Types.OPERATOR, UNARY_PRE_CONCAT2);
        }
        if (operation == CONCAT)
            return Types.STRING;
        // convert from Double to double (if necessary)
        if (mode == MODE_REF) {
            adapter.invokeStatic(Types.CASTER, Methods.METHOD_TO_DOUBLE_FROM_DOUBLE);
            return Types.DOUBLE;
        }
        return Types.DOUBLE_VALUE;
    }
    /*
		 *  undefined scope only with one key (susi++;)
		 */
    // PageContext instance
    adapter.loadArg(0);
    // Collection key Array
    int arrSize = scope != null ? members.size() + 1 : members.size();
    boolean useArray = arrSize > 1 || scope != null;
    if (useArray) {
        ArrayVisitor av = new ArrayVisitor();
        int index = 0;
        av.visitBegin(adapter, Types.COLLECTION_KEY, arrSize);
        Iterator<Member> it = members.iterator();
        Member m;
        DataMember dm;
        if (scope != null) {
            av.visitBeginItem(adapter, index++);
            getFactory().registerKey(bc, getFactory().createLitString(scope), false);
            av.visitEndItem(adapter);
        }
        while (it.hasNext()) {
            av.visitBeginItem(adapter, index++);
            m = it.next();
            if (!(m instanceof DataMember))
                throw new TransformerException("you cannot use a unary operator with a function " + m.getClass().getName(), getStart());
            getFactory().registerKey(bc, ((DataMember) m).getName(), false);
            av.visitEndItem(adapter);
        }
        av.visitEnd();
    } else {
        Member m = members.iterator().next();
        if (!(m instanceof DataMember))
            throw new TransformerException("you cannot use a unary operator with a function " + m.getClass().getName(), getStart());
        getFactory().registerKey(bc, ((DataMember) m).getName(), false);
    }
    if (type == POST) {
        if (operation != OpDouble.PLUS && operation != OpDouble.MINUS)
            throw new TransformerException("Post only possible with plus or minus " + operation, value.getStart());
        value.writeOut(bc, MODE_VALUE);
        if (operation == PLUS)
            adapter.invokeStatic(Types.OPERATOR, useArray ? UNARY_POST_PLUS_N : UNARY_POST_PLUS_1);
        else if (operation == MINUS)
            adapter.invokeStatic(Types.OPERATOR, useArray ? UNARY_POST_MINUS_N : UNARY_POST_MINUS_1);
    } else if (type == PRE) {
        value.writeOut(bc, MODE_VALUE);
        if (operation == PLUS)
            adapter.invokeStatic(Types.OPERATOR, useArray ? UNARY_PRE_PLUS_N : UNARY_PRE_PLUS_1);
        else if (operation == MINUS)
            adapter.invokeStatic(Types.OPERATOR, useArray ? UNARY_PRE_MINUS_N : UNARY_PRE_MINUS_1);
        else if (operation == DIVIDE)
            adapter.invokeStatic(Types.OPERATOR, useArray ? UNARY_PRE_DIVIDE_N : UNARY_PRE_DIVIDE_1);
        else if (operation == MULTIPLY)
            adapter.invokeStatic(Types.OPERATOR, useArray ? UNARY_PRE_MULTIPLY_N : UNARY_PRE_MULTIPLY_1);
        else if (operation == CONCAT)
            adapter.invokeStatic(Types.OPERATOR, useArray ? UNARY_PRE_CONCAT_N : UNARY_PRE_CONCAT_1);
    }
    if (operation == CONCAT)
        return Types.STRING;
    // convert from double to Double (if necessary)
    if (mode == MODE_REF) {
        adapter.invokeStatic(Types.CASTER, Methods.METHOD_TO_DOUBLE_FROM_DOUBLE);
        return Types.DOUBLE;
    }
    return Types.DOUBLE_VALUE;
}
Also used : DataMember(lucee.transformer.expression.var.DataMember) GeneratorAdapter(org.objectweb.asm.commons.GeneratorAdapter) CastString(lucee.transformer.bytecode.cast.CastString) ArrayVisitor(lucee.transformer.bytecode.visitor.ArrayVisitor) DataMember(lucee.transformer.expression.var.DataMember) Member(lucee.transformer.expression.var.Member) TransformerException(lucee.transformer.TransformerException)

Example 13 with TransformerException

use of lucee.transformer.TransformerException in project Lucee by lucee.

the class AbstrCFMLScriptTransformer method tryStatement.

/**
 * Liest eine try Block ein
 * <br />
 * EBNF:<br />
 * <code>;</code>
 * @return Try Block
 * @throws TemplateException
 */
private final TryCatchFinally tryStatement(ExprData data) throws TemplateException {
    if (!data.srcCode.forwardIfCurrent("try", '{') && !data.srcCode.forwardIfCurrent("try ") && !data.srcCode.forwardIfCurrent("try", '/'))
        return null;
    data.srcCode.previous();
    Body body = new BodyBase(data.factory);
    TryCatchFinally tryCatchFinally = new TryCatchFinally(data.factory, body, data.srcCode.getPosition(), null);
    statement(data, body, CTX_TRY);
    comments(data);
    // catches
    short catchCount = 0;
    while (data.srcCode.forwardIfCurrent("catch", '(')) {
        catchCount++;
        comments(data);
        // type
        int pos = data.srcCode.getPos();
        Position line = data.srcCode.getPosition();
        Expression name = null, type = null;
        StringBuffer sbType = new StringBuffer();
        String id;
        while (true) {
            id = identifier(data, false);
            if (id == null)
                break;
            sbType.append(id);
            data.srcCode.removeSpace();
            if (!data.srcCode.forwardIfCurrent('.'))
                break;
            sbType.append('.');
            data.srcCode.removeSpace();
        }
        if (sbType.length() == 0) {
            type = string(data);
            if (type == null)
                throw new TemplateException(data.srcCode, "a catch statement must begin with the throwing type (query, application ...).");
        } else {
            type = data.factory.createLitString(sbType.toString());
        }
        // name = expression();
        comments(data);
        // name
        if (!data.srcCode.isCurrent(')')) {
            name = expression(data);
        } else {
            data.srcCode.setPos(pos);
            name = expression(data);
            type = data.factory.createLitString("any");
        }
        comments(data);
        Body b = new BodyBase(data.factory);
        try {
            tryCatchFinally.addCatch(type, name, b, line);
        } catch (TransformerException e) {
            throw new TemplateException(data.srcCode, e.getMessage());
        }
        comments(data);
        if (!data.srcCode.forwardIfCurrent(')'))
            throw new TemplateException(data.srcCode, "invalid catch statement, missing closing )");
        statement(data, b, CTX_CATCH);
        comments(data);
    }
    // finally
    if (finallyStatement(data, tryCatchFinally)) {
        comments(data);
    } else if (catchCount == 0)
        throw new TemplateException(data.srcCode, "a try statement must have at least one catch statement");
    // if(body.isEmpty()) return null;
    tryCatchFinally.setEnd(data.srcCode.getPosition());
    return tryCatchFinally;
}
Also used : Position(lucee.transformer.Position) FunctionAsExpression(lucee.transformer.bytecode.expression.FunctionAsExpression) Expression(lucee.transformer.expression.Expression) TemplateException(lucee.runtime.exp.TemplateException) Body(lucee.transformer.bytecode.Body) ScriptBody(lucee.transformer.bytecode.ScriptBody) FunctionBody(lucee.transformer.bytecode.FunctionBody) BodyBase(lucee.transformer.bytecode.BodyBase) TransformerException(lucee.transformer.TransformerException) TryCatchFinally(lucee.transformer.bytecode.statement.TryCatchFinally)

Example 14 with TransformerException

use of lucee.transformer.TransformerException in project Lucee by lucee.

the class CFMLCompilerImpl method _compile.

/*private byte[] _compiless(ConfigImpl config,PageSource ps,SourceCode sc,String className, TagLib[] tld, FunctionLib[] fld, 
			Resource classRootDir,TransfomerSettings settings) throws TemplateException {
		Factory factory = BytecodeFactory.getInstance(config);
		
		Page page=null;
		
		TagLib[][] _tlibs=new TagLib[][]{null,new TagLib[0]};
		_tlibs[CFMLTransformer.TAG_LIB_GLOBAL]=tld;
		// reset page tlds
		if(_tlibs[CFMLTransformer.TAG_LIB_PAGE].length>0) {
			_tlibs[CFMLTransformer.TAG_LIB_PAGE]=new TagLib[0];
		}
		
		CFMLScriptTransformer scriptTransformer = new CFMLScriptTransformer();
		scriptTransformer.transform(
				BytecodeFactory.getInstance(config)
				, page
				, new EvaluatorPool()
				, _tlibs, fld
				, null
				, config.getCoreTagLib(ps.getDialect()).getScriptTags()
				, sc
				, settings);
		
		//CFMLExprTransformer extr=new CFMLExprTransformer();
		//extr.transform(factory, page, ep, tld, fld, scriptTags, cfml, settings)
		
		return null;
	}*/
private Result _compile(ConfigImpl config, PageSource ps, SourceCode sc, String className, TagLib[] tld, FunctionLib[] fld, Resource classRootDir, boolean returnValue, boolean ignoreScopes) throws TemplateException, IOException {
    if (className == null)
        className = ps.getClassName();
    Result result = null;
    // byte[] barr = null;
    Page page = null;
    Factory factory = BytecodeFactory.getInstance(config);
    try {
        page = sc == null ? cfmlTransformer.transform(factory, config, ps, tld, fld, returnValue, ignoreScopes) : cfmlTransformer.transform(factory, config, sc, tld, fld, System.currentTimeMillis(), sc.getDialect() == CFMLEngine.DIALECT_CFML && config.getDotNotationUpperCase(), returnValue, ignoreScopes);
        page.setSplitIfNecessary(false);
        try {
            result = new Result(page, page.execute(className));
        } catch (RuntimeException re) {
            String msg = StringUtil.emptyIfNull(re.getMessage());
            if (StringUtil.indexOfIgnoreCase(msg, "Method code too large!") != -1) {
                page = sc == null ? cfmlTransformer.transform(factory, config, ps, tld, fld, returnValue, ignoreScopes) : cfmlTransformer.transform(factory, config, sc, tld, fld, System.currentTimeMillis(), sc.getDialect() == CFMLEngine.DIALECT_CFML && config.getDotNotationUpperCase(), returnValue, ignoreScopes);
                page.setSplitIfNecessary(true);
                result = new Result(page, page.execute(className));
            } else
                throw re;
        } catch (ClassFormatError cfe) {
            String msg = StringUtil.emptyIfNull(cfe.getMessage());
            if (StringUtil.indexOfIgnoreCase(msg, "Invalid method Code length") != -1) {
                page = ps != null ? cfmlTransformer.transform(factory, config, ps, tld, fld, returnValue, ignoreScopes) : cfmlTransformer.transform(factory, config, sc, tld, fld, System.currentTimeMillis(), sc.getDialect() == CFMLEngine.DIALECT_CFML && config.getDotNotationUpperCase(), returnValue, ignoreScopes);
                page.setSplitIfNecessary(true);
                result = new Result(page, page.execute(className));
            } else
                throw cfe;
        }
        // store
        if (classRootDir != null) {
            Resource classFile = classRootDir.getRealResource(page.getClassName() + ".class");
            Resource classFileDirectory = classFile.getParentResource();
            if (!classFileDirectory.exists())
                classFileDirectory.mkdirs();
            IOUtil.copy(new ByteArrayInputStream(result.barr), classFile, true);
        }
        return result;
    } catch (AlreadyClassException ace) {
        byte[] bytes = ace.getEncrypted() ? readEncrypted(ace) : readPlain(ace);
        result = new Result(null, bytes);
        String displayPath = ps != null ? "[" + ps.getDisplayPath() + "] " : "";
        String srcName = ASMUtil.getClassName(result.barr);
        int dialect = sc == null ? ps.getDialect() : sc.getDialect();
        // source is cfm and target cfc
        if (dialect == CFMLEngine.DIALECT_CFML && endsWith(srcName, Constants.getCFMLTemplateExtensions(), dialect) && className.endsWith("_" + Constants.getCFMLComponentExtension() + (dialect == CFMLEngine.DIALECT_CFML ? Constants.CFML_CLASS_SUFFIX : Constants.LUCEE_CLASS_SUFFIX))) {
            throw new TemplateException("source file " + displayPath + "contains the bytecode for a regular cfm template not for a component");
        }
        // source is cfc and target cfm
        if (dialect == CFMLEngine.DIALECT_CFML && srcName.endsWith("_" + Constants.getCFMLComponentExtension() + (dialect == CFMLEngine.DIALECT_CFML ? Constants.CFML_CLASS_SUFFIX : Constants.LUCEE_CLASS_SUFFIX)) && endsWith(className, Constants.getCFMLTemplateExtensions(), dialect))
            throw new TemplateException("source file " + displayPath + "contains a component not a regular cfm template");
        // rename class name when needed
        if (!srcName.equals(className))
            result = new Result(result.page, ClassRenamer.rename(result.barr, className));
        // store
        if (classRootDir != null) {
            Resource classFile = classRootDir.getRealResource(className + ".class");
            Resource classFileDirectory = classFile.getParentResource();
            if (!classFileDirectory.exists())
                classFileDirectory.mkdirs();
            result = new Result(result.page, Page.setSourceLastModified(result.barr, ps != null ? ps.getPhyscalFile().lastModified() : System.currentTimeMillis()));
            IOUtil.copy(new ByteArrayInputStream(result.barr), classFile, true);
        }
        return result;
    } catch (TransformerException bce) {
        Position pos = bce.getPosition();
        int line = pos == null ? -1 : pos.line;
        int col = pos == null ? -1 : pos.column;
        if (ps != null)
            bce.addContext(ps, line, col, null);
        throw bce;
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) TemplateException(lucee.runtime.exp.TemplateException) Position(lucee.transformer.Position) Resource(lucee.commons.io.res.Resource) BytecodeFactory(lucee.transformer.bytecode.BytecodeFactory) Factory(lucee.transformer.Factory) Page(lucee.transformer.bytecode.Page) AlreadyClassException(lucee.transformer.util.AlreadyClassException) TransformerException(lucee.transformer.TransformerException)

Example 15 with TransformerException

use of lucee.transformer.TransformerException in project Lucee by lucee.

the class ForEach method _writeOut.

@Override
public void _writeOut(BytecodeContext bc) throws TransformerException {
    GeneratorAdapter adapter = bc.getAdapter();
    final int it = adapter.newLocal(Types.ITERATOR);
    final int item = adapter.newLocal(Types.REFERENCE);
    // Value
    // ForEachUtil.toIterator(value)
    value.writeOut(bc, Expression.MODE_REF);
    adapter.invokeStatic(FOR_EACH_UTIL, FOR_EACH);
    // adapter.invokeStatic(COLLECTION_UTIL, TO_ITERATOR);
    // Iterator it=...
    adapter.storeLocal(it);
    TryFinallyVisitor tfv = new TryFinallyVisitor(new OnFinally() {

        @Override
        public void _writeOut(BytecodeContext bc) throws TransformerException {
            GeneratorAdapter a = bc.getAdapter();
            // if(fcf!=null && fcf.getAfterFinalGOTOLabel()!=null)ASMUtil.visitLabel(a,fcf.getFinalEntryLabel());
            a.loadLocal(it);
            a.invokeStatic(FOR_EACH_UTIL, RESET);
        /*if(fcf!=null){
						Label l=fcf.getAfterFinalGOTOLabel();
						if(l!=null)a.visitJumpInsn(Opcodes.GOTO, l);
					}*/
        }
    }, getFlowControlFinal());
    tfv.visitTryBegin(bc);
    // Key
    // new VariableReference(...)
    key.writeOut(bc, Expression.MODE_REF);
    // VariableReference item=...
    adapter.storeLocal(item);
    // while
    ExpressionUtil.visitLine(bc, getStart());
    adapter.visitLabel(begin);
    // hasNext
    adapter.loadLocal(it);
    adapter.invokeInterface(Types.ITERATOR, HAS_NEXT);
    adapter.ifZCmp(Opcodes.IFEQ, end);
    // item.set(pc,it.next());
    adapter.loadLocal(item);
    adapter.loadArg(0);
    adapter.loadLocal(it);
    adapter.invokeInterface(Types.ITERATOR, NEXT);
    adapter.invokeInterface(Types.REFERENCE, SET);
    adapter.pop();
    // Body
    body.writeOut(bc);
    adapter.visitJumpInsn(Opcodes.GOTO, begin);
    adapter.visitLabel(end);
    tfv.visitTryEnd(bc);
}
Also used : OnFinally(lucee.transformer.bytecode.visitor.OnFinally) GeneratorAdapter(org.objectweb.asm.commons.GeneratorAdapter) TryFinallyVisitor(lucee.transformer.bytecode.visitor.TryFinallyVisitor) TransformerException(lucee.transformer.TransformerException) BytecodeContext(lucee.transformer.bytecode.BytecodeContext)

Aggregations

TransformerException (lucee.transformer.TransformerException)24 GeneratorAdapter (org.objectweb.asm.commons.GeneratorAdapter)11 LitString (lucee.transformer.expression.literal.LitString)9 ExprString (lucee.transformer.expression.ExprString)7 Expression (lucee.transformer.expression.Expression)7 BytecodeContext (lucee.transformer.bytecode.BytecodeContext)5 OnFinally (lucee.transformer.bytecode.visitor.OnFinally)5 ArrayList (java.util.ArrayList)4 Iterator (java.util.Iterator)4 TemplateException (lucee.runtime.exp.TemplateException)4 Body (lucee.transformer.bytecode.Body)4 Page (lucee.transformer.bytecode.Page)4 TryCatchFinallyVisitor (lucee.transformer.bytecode.visitor.TryCatchFinallyVisitor)4 Literal (lucee.transformer.expression.literal.Literal)4 Label (org.objectweb.asm.Label)4 BodyBase (lucee.transformer.bytecode.BodyBase)3 Statement (lucee.transformer.bytecode.Statement)3 EvaluatorException (lucee.transformer.cfml.evaluator.EvaluatorException)3 DataMember (lucee.transformer.expression.var.DataMember)3 Member (lucee.transformer.expression.var.Member)3