01: /* *****************************************************************************
02: * ScriptElementCompiler.java
03: * ****************************************************************************/
04:
05: /* J_LZ_COPYRIGHT_BEGIN *******************************************************
06: * Copyright 2001-2007 Laszlo Systems, Inc. All Rights Reserved. *
07: * Use is subject to license terms. *
08: * J_LZ_COPYRIGHT_END *********************************************************/
09:
10: package org.openlaszlo.compiler;
11:
12: import org.openlaszlo.utils.FileUtils;
13: import java.io.File;
14: import java.io.IOException;
15: import org.jdom.Element;
16:
17: /** Compiler for <code>script</code> elements.
18: *
19: * @author Oliver Steele
20: */
21: class ScriptElementCompiler extends ElementCompiler {
22: private static final String SRC_ATTR_NAME = "src";
23:
24: ScriptElementCompiler(CompilationEnvironment env) {
25: super (env);
26: }
27:
28: /** Returns true iff this class applies to this element.
29: * @param element an element
30: * @return see doc
31: */
32: static boolean isElement(Element element) {
33: return element.getName().intern() == "script";
34: }
35:
36: public void compile(Element element) {
37: if (!element.getChildren().isEmpty()) {
38: throw new CompilationError(
39: "<script> elements can't have children", element);
40: }
41: String pathname = null;
42: String script = element.getText();
43: if (element.getAttribute(SRC_ATTR_NAME) != null) {
44: pathname = element.getAttributeValue(SRC_ATTR_NAME);
45: File file = mEnv.resolveReference(element, SRC_ATTR_NAME);
46: try {
47: script = "#file "
48: + element.getAttributeValue(SRC_ATTR_NAME)
49: + "\n" + "#line 1\n"
50: + FileUtils.readFileString(file);
51: } catch (IOException e) {
52: throw new CompilationError(e);
53: }
54: }
55: try {
56: // If it is when=immediate, emit code inline
57: if ("immediate".equals(element.getAttributeValue("when"))) {
58: mEnv.compileScript(CompilerUtils
59: .sourceLocationDirective(element, true)
60: + script, element);
61: } else {
62: // Compile scripts to run at construction time in the view
63: // instantiation queue.
64:
65: mEnv.compileScript(
66: // Provide file info for anonymous function name
67: CompilerUtils.sourceLocationDirective(element,
68: true)
69: + VIEW_INSTANTIATION_FNAME
70: + "({name: 'script', attrs: "
71: + "{script: function () {\n"
72: + "#beginContent\n"
73: + "#pragma 'scriptElement'\n"
74: + CompilerUtils
75: .sourceLocationDirective(
76: element, true)
77: + script
78: + "\n#endContent\n" +
79: // Scripts have no children
80: "}}}, 1)", element);
81: }
82: } catch (CompilationError e) {
83: // TODO: [2003-01-16] Instead of this, put the filename in ParseException,
84: // and modify CompilationError.initElement to copy it from there.
85: if (pathname != null) {
86: e.setPathname(pathname);
87: }
88: throw e;
89: }
90: }
91: }
|