Search in sources :

Example 6 with Page

use of lucee.transformer.bytecode.Page 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 7 with Page

use of lucee.transformer.bytecode.Page in project Lucee by lucee.

the class TagCIObject method writeOut.

public void writeOut(Page p) throws TransformerException {
    Page page = new Page(p.getFactory(), p.getConfig(), p.getSourceCode(), this, CFMLEngineFactory.getInstance().getInfo().getFullVersionInfo(), p.getLastModifed(), p.writeLog(), p.getSupressWSbeforeArg(), p.getOutput(), p.returnValue(), p.ignoreScopes);
    // page.setIsComponent(true); // MUST can be a interface as well
    page.addStatement(this);
    byte[] barr = page.execute(p.getClassName());
    // ps.getMapping().getClassRootDirectory().getRealResource(page.getClassName()+".class");
    Resource classFile = null;
    try {
        IOUtil.copy(new ByteArrayInputStream(barr), classFile, true);
    } catch (IOException e) {
        new TransformerException(ExceptionUtil.getMessage(e), getStart());
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) Resource(lucee.commons.io.res.Resource) Page(lucee.transformer.bytecode.Page) IOException(java.io.IOException) TransformerException(lucee.transformer.TransformerException)

Example 8 with Page

use of lucee.transformer.bytecode.Page in project Lucee by lucee.

the class LitStringImpl method _writeOut.

/**
 * @see lucee.transformer.expression.Expression#_writeOut(org.objectweb.asm.commons.GeneratorAdapter, int)
 */
private static Type _writeOut(BytecodeContext bc, int mode, String str) throws TransformerException {
    // write to a file instead to the bytecode
    // str(0,10);
    // print.ds(str);
    int externalizeStringGTE = ((ConfigImpl) bc.getConfig()).getExternalizeStringGTE();
    if (externalizeStringGTE > -1 && str.length() > externalizeStringGTE && StringUtil.indexOfIgnoreCase(bc.getMethod().getName(), "call") != -1) {
        try {
            GeneratorAdapter ga = bc.getAdapter();
            Page page = bc.getPage();
            Range range = page.registerString(bc, str);
            if (range != null) {
                ga.visitVarInsn(Opcodes.ALOAD, 0);
                ga.visitVarInsn(Opcodes.ALOAD, 1);
                ga.push(range.from);
                ga.push(range.to);
                ga.visitMethodInsn(Opcodes.INVOKEVIRTUAL, bc.getClassName(), "str", "(Llucee/runtime/PageContext;II)Ljava/lang/String;");
                return Types.STRING;
            }
        } catch (Throwable t) {
            ExceptionUtil.rethrowIfNecessary(t);
        }
    }
    if (toBig(str)) {
        _toExpr(bc.getFactory(), str).writeOut(bc, mode);
    } else {
        bc.getAdapter().push(str);
    }
    return Types.STRING;
}
Also used : GeneratorAdapter(org.objectweb.asm.commons.GeneratorAdapter) Page(lucee.transformer.bytecode.Page) Range(lucee.transformer.bytecode.Range) ConfigImpl(lucee.runtime.config.ConfigImpl)

Example 9 with Page

use of lucee.transformer.bytecode.Page in project Lucee by lucee.

the class CFMLTransformer method transform.

/**
 * Startmethode zum transfomieren einer CFML Datei.
 * <br />
 * EBNF:<br />
 * <code>{body}</code>
 * @param config
 * @param ps CFML File
 * @param tlibs Tag Library Deskriptoren, nach denen innerhalb der CFML Datei geprueft werden soll.
 * @param flibs Function Library Deskriptoren, nach denen innerhalb der Expressions der CFML Datei geprueft werden soll.
 * @param returnValue if true the method returns the value of the last expression executed inside when you call the method "call"
 * @return uebersetztes CFXD Dokument Element.
 * @throws TemplateException
 * @throws IOException
 */
public Page transform(Factory factory, ConfigImpl config, PageSource ps, TagLib[] tlibs, FunctionLib[] flibs, boolean returnValue, boolean ignoreScopes) throws TemplateException, IOException {
    Page p;
    SourceCode sc;
    boolean writeLog = config.getExecutionLogEnabled();
    Charset charset = config.getTemplateCharset();
    boolean dotUpper = ps.getDialect() == CFMLEngine.DIALECT_CFML && ((MappingImpl) ps.getMapping()).getDotNotationUpperCase();
    // parse regular
    while (true) {
        try {
            sc = new PageSourceCode(ps, charset, writeLog);
            p = transform(factory, config, sc, tlibs, flibs, ps.getResource().lastModified(), dotUpper, returnValue, ignoreScopes);
            break;
        } catch (ProcessingDirectiveException pde) {
            if (pde.getWriteLog() != null)
                writeLog = pde.getWriteLog().booleanValue();
            if (pde.getDotNotationUpperCase() != null)
                dotUpper = pde.getDotNotationUpperCase().booleanValue();
            if (!StringUtil.isEmpty(pde.getCharset()))
                charset = pde.getCharset();
        }
    }
    // could it be a component?
    boolean isCFML = ps.getDialect() == CFMLEngine.DIALECT_CFML;
    boolean isCFMLCompExt = isCFML && Constants.isCFMLComponentExtension(ResourceUtil.getExtension(ps.getResource(), ""));
    boolean possibleUndetectedComponent = false;
    // we don't have a component or interface
    if (p.isPage()) {
        if (isCFML)
            possibleUndetectedComponent = isCFMLCompExt;
        else if (Constants.isLuceeComponentExtension(ResourceUtil.getExtension(ps.getResource(), ""))) {
            Expression expr;
            Statement stat;
            PrintOut po;
            LitString ls;
            List<Statement> statements = p.getStatements();
            // check the root statements for component
            Iterator<Statement> it = statements.iterator();
            String str;
            while (it.hasNext()) {
                stat = it.next();
                if (stat instanceof PrintOut && (expr = ((PrintOut) stat).getExpr()) instanceof LitString) {
                    ls = (LitString) expr;
                    str = ls.getString();
                    if (str.indexOf(Constants.LUCEE_COMPONENT_TAG_NAME) != -1 || str.indexOf(Constants.LUCEE_INTERFACE_TAG_NAME) != -1 || // cfml name is supported as alias
                    str.indexOf(Constants.CFML_COMPONENT_TAG_NAME) != -1) {
                        possibleUndetectedComponent = true;
                        break;
                    }
                }
            }
        }
    }
    /*if(p.isPage() && (isCFML?
				Constants.isCFMLComponentExtension(ResourceUtil.getExtension(ps.getResource(),"")):
				Constants.isLuceeComponentExtension(ResourceUtil.getExtension(ps.getResource(),""))) &&
				isPossibleRawScript(sc,config.getIdentification())){*/
    if (possibleUndetectedComponent) {
        Page _p;
        TagLibTag scriptTag = CFMLTransformer.getTLT(sc, isCFML ? Constants.CFML_SCRIPT_TAG_NAME : Constants.LUCEE_SCRIPT_TAG_NAME, config.getIdentification());
        sc.setPos(0);
        SourceCode original = sc;
        // try inside a cfscript
        String text = "<" + scriptTag.getFullName() + ">" + original.getText() + "\n</" + scriptTag.getFullName() + ">";
        sc = new PageSourceCode(ps, text, charset, writeLog);
        try {
            while (true) {
                if (sc == null) {
                    sc = new PageSourceCode(ps, charset, writeLog);
                    text = "<" + scriptTag.getFullName() + ">" + sc.getText() + "\n</" + scriptTag.getFullName() + ">";
                    sc = new PageSourceCode(ps, text, charset, writeLog);
                }
                try {
                    _p = transform(factory, config, sc, tlibs, flibs, ps.getResource().lastModified(), dotUpper, returnValue, ignoreScopes);
                    break;
                } catch (ProcessingDirectiveException pde) {
                    if (pde.getWriteLog() != null)
                        writeLog = pde.getWriteLog().booleanValue();
                    if (pde.getDotNotationUpperCase() != null)
                        dotUpper = pde.getDotNotationUpperCase().booleanValue();
                    if (!StringUtil.isEmpty(pde.getCharset()))
                        charset = pde.getCharset();
                    sc = null;
                }
            }
        } catch (ComponentTemplateException e) {
            throw e.getTemplateException();
        }
        // we only use that result if it is a component now
        if (_p != null && !_p.isPage())
            return _p;
    }
    if (isCFMLCompExt && !p.isComponent() && !p.isInterface()) {
        String msg = "template [" + ps.getDisplayPath() + "] must contain a component or an interface.";
        if (sc != null)
            throw new TemplateException(sc, msg);
        throw new TemplateException(msg);
    }
    return p;
}
Also used : TagLibTag(lucee.transformer.library.tag.TagLibTag) PageSourceCode(lucee.transformer.util.PageSourceCode) SourceCode(lucee.transformer.util.SourceCode) PageSourceCode(lucee.transformer.util.PageSourceCode) ComponentTemplateException(lucee.transformer.cfml.script.AbstrCFMLScriptTransformer.ComponentTemplateException) TemplateException(lucee.runtime.exp.TemplateException) Statement(lucee.transformer.bytecode.Statement) ComponentTemplateException(lucee.transformer.cfml.script.AbstrCFMLScriptTransformer.ComponentTemplateException) Charset(java.nio.charset.Charset) Page(lucee.transformer.bytecode.Page) ProcessingDirectiveException(lucee.transformer.cfml.evaluator.impl.ProcessingDirectiveException) LitString(lucee.transformer.expression.literal.LitString) LitString(lucee.transformer.expression.literal.LitString) PrintOut(lucee.transformer.bytecode.statement.PrintOut) Expression(lucee.transformer.expression.Expression) Iterator(java.util.Iterator) List(java.util.List) ArrayList(java.util.ArrayList)

Example 10 with Page

use of lucee.transformer.bytecode.Page in project Lucee by lucee.

the class Component method evaluate.

@Override
public void evaluate(Tag tag, TagLibTag tlt) throws EvaluatorException {
    /*if(tag instanceof TagOther) {
			print.e(((TagOther)tag).getFullname());
		}*/
    TagCIObject tc = (TagCIObject) tag;
    Statement pPage = tag.getParent();
    // String className=tag.getTagLibTag().getTagClassName();
    Page page;
    // move components inside script to root
    if (pPage instanceof Page) {
        page = (Page) pPage;
    } else {
        // is in script
        Tag p = ASMUtil.getParentTag(tag);
        if ((pPage = p.getParent()) instanceof Page && p.getTagLibTag().getName().equalsIgnoreCase(((Page) pPage).getSourceCode().getDialect() == CFMLEngine.DIALECT_CFML ? Constants.CFML_SCRIPT_TAG_NAME : Constants.LUCEE_SCRIPT_TAG_NAME)) {
            // chnaged order of the condition, not sure if this is ok
            page = (Page) pPage;
            // move imports from script to component body
            List<Statement> children = p.getBody().getStatements();
            Iterator<Statement> it = children.iterator();
            Statement stat;
            Tag t;
            while (it.hasNext()) {
                stat = it.next();
                if (!(stat instanceof Tag))
                    continue;
                t = (Tag) stat;
                if (t.getTagLibTag().getName().equals("import")) {
                    tag.getBody().addStatement(t);
                }
            }
            // move to page
            ASMUtil.move(tag, page);
        // if(!inline)ASMUtil.replace(p, tag, false);
        } else
            throw new EvaluatorException("Wrong Context, tag " + tlt.getFullName() + " can't be inside other tags, tag is inside tag " + p.getFullname());
    }
    // Page page=(Page) pPage;
    Boolean insideCITemplate = isInsideCITemplate(page);
    boolean main = isMainComponent(page, tc);
    // is a full grown component or a inline component
    if (insideCITemplate == Boolean.FALSE) {
        throw new EvaluatorException("Wrong Context, " + tlt.getFullName() + " tag must be inside a file with the extension " + Constants.getCFMLComponentExtension() + " or " + Constants.getLuceeComponentExtension());
    }
    // if(count>1)
    // throw new EvaluatorException("inside one cfc file only one tag "+tlt.getFullName()+" is allowed, now we have "+count);
    boolean isComponent = tlt.getTagClassDefinition().isClassNameEqualTo("lucee.runtime.tag.Component");
    /*boolean isInterface="lucee.runtime.tag.Interface".equals(tlt.getTagClassName());
		if(main) {
			if(isComponent)			page.setIsComponent(true);
			else if(isInterface)	page.setIsInterface(true);
		}*/
    tc.setMain(main);
    // Attributes
    // Name
    String name = null;
    if (!main) {
        Map<String, Attribute> attrs = tag.getAttributes();
        if (attrs.size() > 0) {
            Attribute first = attrs.values().iterator().next();
            if (first.isDefaultValue()) {
                name = first.getName();
            }
        }
        if (name == null) {
            Attribute attr = tag.getAttribute("name");
            if (attr != null) {
                Expression expr = tag.getFactory().toExprString(attr.getValue());
                if (!(expr instanceof LitString))
                    throw new EvaluatorException("Name of the component " + tlt.getFullName() + ", must be a literal string value");
                name = ((LitString) expr).getString();
            } else
                throw new EvaluatorException("Missing name of the component " + tlt.getFullName() + "");
        }
        tc.setName(name);
    }
    // output
    // "output=true" is handled in "lucee.transformer.cfml.attributes.impl.Function"
    Attribute attr = tag.getAttribute("output");
    if (attr != null) {
        Expression expr = tag.getFactory().toExprBoolean(attr.getValue());
        if (!(expr instanceof LitBoolean))
            throw new EvaluatorException("Attribute output of the Tag " + tlt.getFullName() + ", must contain a static boolean value (true or false, yes or no)");
    // boolean output = ((LitBoolean)expr).getBooleanValue();
    // if(!output) ASMUtil.removeLiterlChildren(tag, true);
    }
    // extends
    attr = tag.getAttribute("extends");
    if (attr != null) {
        Expression expr = tag.getFactory().toExprString(attr.getValue());
        if (!(expr instanceof LitString))
            throw new EvaluatorException("Attribute extends of the Tag " + tlt.getFullName() + ", must contain a literal string value");
    }
    // implements
    if (isComponent) {
        attr = tag.getAttribute("implements");
        if (attr != null) {
            Expression expr = tag.getFactory().toExprString(attr.getValue());
            if (!(expr instanceof LitString))
                throw new EvaluatorException("Attribute implements of the Tag " + tlt.getFullName() + ", must contain a literal string value");
        }
    }
    // modifier
    if (isComponent) {
        attr = tag.getAttribute("modifier");
        if (attr != null) {
            Expression expr = tag.getFactory().toExprString(attr.getValue());
            if (!(expr instanceof LitString))
                throw new EvaluatorException("Attribute modifier of the Tag " + tlt.getFullName() + ", must contain a literal string value");
            LitString ls = (LitString) expr;
            int mod = ComponentUtil.toModifier(ls.getString(), lucee.runtime.Component.MODIFIER_NONE, -1);
            if (mod == -1)
                throw new EvaluatorException("Value [" + ls.getString() + "] from attribute modifier of the Tag " + tlt.getFullName() + " is invalid,valid values are [none,abstract,final]");
        }
    }
}
Also used : Attribute(lucee.transformer.bytecode.statement.tag.Attribute) Statement(lucee.transformer.bytecode.Statement) Page(lucee.transformer.bytecode.Page) LitBoolean(lucee.transformer.expression.literal.LitBoolean) LitString(lucee.transformer.expression.literal.LitString) LitString(lucee.transformer.expression.literal.LitString) EvaluatorException(lucee.transformer.cfml.evaluator.EvaluatorException) Expression(lucee.transformer.expression.Expression) TagLibTag(lucee.transformer.library.tag.TagLibTag) Tag(lucee.transformer.bytecode.statement.tag.Tag) LitBoolean(lucee.transformer.expression.literal.LitBoolean) TagCIObject(lucee.transformer.bytecode.statement.tag.TagCIObject)

Aggregations

Page (lucee.transformer.bytecode.Page)11 Expression (lucee.transformer.expression.Expression)5 LitString (lucee.transformer.expression.literal.LitString)5 TemplateException (lucee.runtime.exp.TemplateException)4 TransformerException (lucee.transformer.TransformerException)4 Attribute (lucee.transformer.bytecode.statement.tag.Attribute)4 EvaluatorException (lucee.transformer.cfml.evaluator.EvaluatorException)4 SourceCode (lucee.transformer.util.SourceCode)4 TagLibTag (lucee.transformer.library.tag.TagLibTag)3 PageSourceCode (lucee.transformer.util.PageSourceCode)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 Resource (lucee.commons.io.res.Resource)2 ConfigImpl (lucee.runtime.config.ConfigImpl)2 Statement (lucee.transformer.bytecode.Statement)2 ComponentTemplateException (lucee.transformer.cfml.script.AbstrCFMLScriptTransformer.ComponentTemplateException)2 LitBoolean (lucee.transformer.expression.literal.LitBoolean)2 TagLib (lucee.transformer.library.tag.TagLib)2 IOException (java.io.IOException)1 Charset (java.nio.charset.Charset)1 ArrayList (java.util.ArrayList)1