public abstract class SyntaxTreeNode implements Constants {

    private Parser _parser;

    static final SyntaxTreeNode Dummy = new AbsolutePathPattern(null);

    protected static final int IndentIncrement = 4;
    private static final char[] _spaces =
	"                                                       ".toCharArray();

    /**
     * Creates a new SyntaxTreeNode with a 'null' QName and no source file
     * line number reference.
     */
    public SyntaxTreeNode() {
	_line = 0;
	_qname = null;
    }

    /**
     * Creates a new SyntaxTreeNode with a 'null' QName.
     * @param line Source file line number reference
     */
    public SyntaxTreeNode(int line) {
	_line = line;
	_qname = null;
    }

    /**
     * Creates a new SyntaxTreeNode with no source file line number reference.
     * @param uri The element's namespace URI
     * @param prefix The element's namespace prefix
     * @param local The element's local name
     */
    public SyntaxTreeNode(String uri, String prefix, String local) {
	_line = 0;
	setQName(uri, prefix, local);
    }

    /**
     * Set the source file line number for this element
     * @param line The source file line number.
     */
    protected final void setLineNumber(int line) {
	_line = line;
    }

    /**
     * Get the source file line number for this element. If unavailable, lookup
     * in ancestors.
     *
     * @return The source file line number.
     */
    public final int getLineNumber() {
        if (_line > 0) return _line;
        SyntaxTreeNode parent = getParent();
        return (parent != null) ? parent.getLineNumber() : 0;
    }

    /**
     * Set the QName for the syntax tree node.
     * @param qname The QName for the syntax tree node
     */
    protected void setQName(QName qname) {
	_qname = qname;
    }

    /**
     * Set the QName for the SyntaxTreeNode
     * @param uri The element's namespace URI
     * @param prefix The element's namespace prefix
     * @param local The element's local name
     */
    protected void setQName(String uri, String prefix, String localname) {
	_qname = new QName(uri, prefix, localname);
    }

    /**
     * Set the QName for the SyntaxTreeNode
     * @param qname The QName for the syntax tree node
     */
    protected QName getQName() {
	return(_qname);
    }

    /**
     * Set the attributes for this SyntaxTreeNode.
     * @param attributes Attributes for the element. Must be passed in as an
     *                   implementation of org.xml.sax.Attributes.
     */
    protected void setAttributes(AttributeList attributes) {
	_attributes = attributes;
    }

    /**
     * Returns a value for an attribute from the source element.
     * @param qname The QName of the attribute to return.
     * @return The value of the attribute of name 'qname'.
     */
    protected String getAttribute(String qname) {
	if (_attributes == null) {
	    return EMPTYSTRING;
	}
	final String value = _attributes.getValue(qname);
	return (value == null || value.equals(EMPTYSTRING)) ?
	    EMPTYSTRING : value;
    }

    protected String getAttribute(String prefix, String localName) {
        return getAttribute(prefix + ':' + localName);
    }

    protected boolean hasAttribute(String qname) {
	return (_attributes != null && _attributes.getValue(qname) != null);
    }

    protected void addAttribute(String qname, String value) {
        _attributes.add(qname, value);
    }

    /**
     * Returns a list of all attributes declared for the element represented by
     * this syntax tree node.
     * @return Attributes for this syntax tree node
     */
    protected Attributes getAttributes() {
	return(_attributes);
    }

    /**
     * Sets the prefix mapping for the namespaces that were declared in this
     * element. This does not include all prefix mappings in scope, so one
     * may have to check ancestor elements to get all mappings that are in
     * in scope. The prefixes must be passed in as a Hashtable that maps
     * namespace prefixes (String objects) to namespace URIs (also String).
     * @param mapping The Hashtable containing the mappings.
     */
    protected void setPrefixMapping(Hashtable mapping) {
	_prefixMapping = mapping;
    }

    /**
     * Returns a Hashtable containing the prefix mappings that were declared
     * for this element. This does not include all prefix mappings in scope,
     * so one may have to check ancestor elements to get all mappings that are
     * in in scope.
     * @return Prefix mappings (for this element only).
     */
    protected Hashtable getPrefixMapping() {
	return _prefixMapping;
    }

    /**
     * Adds a single prefix mapping to this syntax tree node.
     * @param prefix Namespace prefix.
     * @param uri Namespace URI.
     */
    protected void addPrefixMapping(String prefix, String uri) {
	if (_prefixMapping == null)
	    _prefixMapping = new Hashtable();
	_prefixMapping.put(prefix, uri);
    }

    /**
     * Returns any namespace URI that is in scope for a given prefix. This
     * method checks namespace mappings for this element, and if necessary
     * for ancestor elements as well (ie. if the prefix maps to an URI in this
     * scope then you'll definately get the URI from this method).
     * @param prefix Namespace prefix.
     * @return Namespace URI.
     */
    protected String lookupNamespace(String prefix) {
	String uri = null;

	if (_prefixMapping != null)
	    uri = (String)_prefixMapping.get(prefix);
	if ((uri == null) && (_parent != null)) {
	    uri = _parent.lookupNamespace(prefix);
	    if ((prefix == Constants.EMPTYSTRING) && (uri == null))
		uri = Constants.EMPTYSTRING;
	}
	return(uri);
    }

    /**
     * Returns any namespace prefix that is mapped to a prefix in the current
     * scope. This method checks namespace mappings for this element, and if
     * necessary for ancestor elements as well (ie. if the URI is declared
     * within the current scope then you'll definately get the prefix from
     * this method). Note that this is a very slow method and consequentially
     * it should only be used strictly when needed.
     * @param uri Namespace URI.
     * @return Namespace prefix.
     */
    protected String lookupPrefix(String uri) {
	String prefix = null;

	if ((_prefixMapping != null) &&
	    (_prefixMapping.contains(uri))) {
	    Enumeration prefixes = _prefixMapping.keys();
	    while (prefixes.hasMoreElements()) {
		prefix = (String)prefixes.nextElement();
		String mapsTo = (String)_prefixMapping.get(prefix);
		if (mapsTo.equals(uri)) return(prefix);
	    }
	}
	else if (_parent != null) {
	    prefix = _parent.lookupPrefix(uri);
	    if ((uri == Constants.EMPTYSTRING) && (prefix == null))
		prefix = Constants.EMPTYSTRING;
	}
	return(prefix);
    }

    /**
     * Set this node's parser. The parser (the XSLT parser) gives this
     * syntax tree node access to the symbol table and XPath parser.
     * @param parser The XSLT parser.
     */
    protected void setParser(Parser parser) {
	_parser = parser;
    }

    /**
     * Returns this node's XSLT parser.
     * @return The XSLT parser.
     */
    public final Parser getParser() {
	return _parser;
    }

    /**
     * Set this syntax tree node's parent node
     * @param parent The parent node.
     */
    protected void setParent(SyntaxTreeNode parent) {
	if (_parent == null)
	    _parent = parent;
    }

    /**
     * Returns this syntax tree node's parent node.
     * @return The parent syntax tree node.
     */
    protected final SyntaxTreeNode getParent() {
	return _parent;
    }

    /**
     * Returns 'true' if this syntax tree node is the Sentinal node.
     * @return 'true' if this syntax tree node is the Sentinal node.
     */
    protected final boolean isDummy() {
        return this == Dummy;
    }

    /**
     * Get the import precedence of this element. The import precedence equals
     * the import precedence of the stylesheet in which this element occured.
     * @return The import precedence of this syntax tree node.
     */
    protected int getImportPrecedence() {
	Stylesheet stylesheet = getStylesheet();
	if (stylesheet == null) return Integer.MIN_VALUE;
	return stylesheet.getImportPrecedence();
    }

    /**
     * Get the Stylesheet node that represents the <xsl:stylesheet/> element
     * that this node occured under.
     * @return The Stylesheet ancestor node of this node.
     */
    public Stylesheet getStylesheet() {
	if (_stylesheet == null) {
	    SyntaxTreeNode parent = this;
	    while (parent != null) {
		if (parent instanceof Stylesheet)
		    return((Stylesheet)parent);
		parent = parent.getParent();
	    }
	    _stylesheet = (Stylesheet)parent;
	}
	return(_stylesheet);
    }

    /**
     * Get the Template node that represents the <xsl:template/> element
     * that this node occured under. Note that this method will return 'null'
     * for nodes that represent top-level elements.
     * @return The Template ancestor node of this node or 'null'.
     */
    protected Template getTemplate() {
	if (_template == null) {
	    SyntaxTreeNode parent = this;
	    while ((parent != null) && (!(parent instanceof Template)))
		parent = parent.getParent();
	    _template = (Template)parent;
	}
	return(_template);
    }

    /**
     * Returns a reference to the XSLTC (XSLT compiler) in use.
     * @return XSLTC - XSLT compiler.
     */
    protected final XSLTC getXSLTC() {
	return _parser.getXSLTC();
    }

    /**
     * Returns the XSLT parser's symbol table.
     * @return Symbol table.
     */
    protected final SymbolTable getSymbolTable() {
	return (_parser == null) ? null : _parser.getSymbolTable();
    }

    /**
     * Parse the contents of this syntax tree nodes (child nodes, XPath
     * expressions, patterns and functions). The default behaviour is to parser
     * the syntax tree node's children (since there are no common expressions,
     * patterns, etc. that can be handled in this base class.
     * @param parser reference to the XSLT parser
     */
    public void parseContents(Parser parser) {
	parseChildren(parser);
    }

    /**
     * Parse all children of this syntax tree node. This method is normally
     * called by the parseContents() method.
     * @param parser reference to the XSLT parser
     */
    protected final void parseChildren(Parser parser) {

	final int count = _contents.size();
	for (int i=0; i<count; i++) {
	    SyntaxTreeNode child = (SyntaxTreeNode)_contents.elementAt(i);
	    parser.getSymbolTable().setCurrentNode(child);
	    child.parseContents(parser);
	    final QName varOrParamName = updateScope(parser, child);
	    if (varOrParamName != null) {
		if (locals == null) {
		    locals = new Vector(2);
		}
		locals.addElement(varOrParamName);
	    }
	}

	parser.getSymbolTable().setCurrentNode(this);

	if (locals != null) {
	    final int nLocals = locals.size();
	    for (int i = 0; i < nLocals; i++) {
		parser.removeVariable((QName)locals.elementAt(i));
	    }
	}
    }

    /**
     * Add a node to the current scope and return name of a variable or
     * parameter if the node represents a variable or a parameter.
     */
    protected QName updateScope(Parser parser, SyntaxTreeNode node) {
	if (node instanceof Variable) {
	    final Variable var = (Variable)node;
	    parser.addVariable(var);
	    return var.getName();
	}
	else if (node instanceof Param) {
	    final Param param = (Param)node;
	    parser.addParameter(param);
	    return param.getName();
	}
	else {
	    return null;
	}
    }

    /**
     * Type check the children of this node. The type check phase may add
     * coercions (CastExpr) to the AST.
     * @param stable The compiler/parser's symbol table
     */
    public abstract Type typeCheck(SymbolTable stable) throws TypeCheckError;

    /**
     * Call typeCheck() on all child syntax tree nodes.
     * @param stable The compiler/parser's symbol table
     */
    protected Type typeCheckContents(SymbolTable stable) throws TypeCheckError {
	final int n = elementCount();
	for (int i = 0; i < n; i++) {
	    SyntaxTreeNode item = (SyntaxTreeNode)_contents.elementAt(i);
	    item.typeCheck(stable);
	}
	return Type.Void;
    }

    /**
     * Translate this abstract syntax tree node into JVM bytecodes.
     * @param classGen BCEL Java class generator
     * @param methodGen BCEL Java method generator
     */
    public abstract void translate(ClassGenerator classGen,
				   MethodGenerator methodGen);

    /**
     * Call translate() on all child syntax tree nodes.
     * @param classGen BCEL Java class generator
     * @param methodGen BCEL Java method generator
     */
    protected void translateContents(ClassGenerator classGen,
				     MethodGenerator methodGen) {
	final int n = elementCount();
	for (int i = 0; i < n; i++) {
	    final SyntaxTreeNode item = (SyntaxTreeNode)_contents.elementAt(i);
	    item.translate(classGen, methodGen);
	}

	for (int i = 0; i < n; i++) {
	    if( _contents.elementAt(i) instanceof VariableBase) {
		final VariableBase var = (VariableBase)_contents.elementAt(i);
		var.unmapRegister(methodGen);
	    }
	}
    }

    /**
     * Return true if the node represents a simple RTF.
     *
     * A node is a simple RTF if all children only produce Text value.
     *
     * @param node A node
     * @return true if the node content can be considered as a simple RTF.
     */
    private boolean isSimpleRTF(SyntaxTreeNode node) {

        Vector contents = node.getContents();
        for (int i = 0; i < contents.size(); i++) {
            SyntaxTreeNode item = (SyntaxTreeNode)contents.elementAt(i);
            if (!isTextElement(item, false))
                return false;
        }

        return true;
    }

     /**
     * Return true if the node represents an adaptive RTF.
     *
     * A node is an adaptive RTF if each children is a Text element
     * or it is <xsl:call-template> or <xsl:apply-templates>.
     *
     * @param node A node
     * @return true if the node content can be considered as an adaptive RTF.
     */
    private boolean isAdaptiveRTF(SyntaxTreeNode node) {

        Vector contents = node.getContents();
        for (int i = 0; i < contents.size(); i++) {
            SyntaxTreeNode item = (SyntaxTreeNode)contents.elementAt(i);
            if (!isTextElement(item, true))
                return false;
        }

        return true;
    }

    /**
     * Return true if the node only produces Text content.
     *
     * A node is a Text element if it is Text, xsl:value-of, xsl:number,
     * or a combination of these nested in a control instruction (xsl:if or
     * xsl:choose).
     *
     * If the doExtendedCheck flag is true, xsl:call-template and xsl:apply-templates
     * are also considered as Text elements.
     *
     * @param node A node
     * @param doExtendedCheck If this flag is true, <xsl:call-template> and
     * <xsl:apply-templates> are also considered as Text elements.
     *
     * @return true if the node of Text type
     */
    private boolean isTextElement(SyntaxTreeNode node, boolean doExtendedCheck) {
        if (node instanceof ValueOf || node instanceof Number
            || node instanceof Text)
        {
            return true;
        }
        else if (node instanceof If) {
            return doExtendedCheck ? isAdaptiveRTF(node) : isSimpleRTF(node);
        }
        else if (node instanceof Choose) {
            Vector contents = node.getContents();
            for (int i = 0; i < contents.size(); i++) {
                SyntaxTreeNode item = (SyntaxTreeNode)contents.elementAt(i);
                if (item instanceof Text ||
                     ((item instanceof When || item instanceof Otherwise)
                     && ((doExtendedCheck && isAdaptiveRTF(item))
                         || (!doExtendedCheck && isSimpleRTF(item)))))
                    continue;
                else
                    return false;
            }
            return true;
        }
        else if (doExtendedCheck &&
                  (node instanceof CallTemplate
                   || node instanceof ApplyTemplates))
            return true;
        else
            return false;
    }

    /**
     * Utility method used by parameters and variables to store result trees
     * @param classGen BCEL Java class generator
     * @param methodGen BCEL Java method generator
     */
    protected void compileResultTree(ClassGenerator classGen,
				     MethodGenerator methodGen)
    {
	final ConstantPoolGen cpg = classGen.getConstantPool();
	final InstructionList il = methodGen.getInstructionList();
	final Stylesheet stylesheet = classGen.getStylesheet();

	boolean isSimple = isSimpleRTF(this);
	boolean isAdaptive = false;
	if (!isSimple) {
	    isAdaptive = isAdaptiveRTF(this);
	}

	int rtfType = isSimple ? DOM.SIMPLE_RTF
	                       : (isAdaptive ? DOM.ADAPTIVE_RTF : DOM.TREE_RTF);

	il.append(methodGen.loadHandler());

	final String DOM_CLASS = classGen.getDOMClass();

	il.append(methodGen.loadDOM());
	int index = cpg.addInterfaceMethodref(DOM_INTF,
				 "getResultTreeFrag",
				 "(IIZ)" + DOM_INTF_SIG);
	il.append(new PUSH(cpg, RTF_INITIAL_SIZE));
	il.append(new PUSH(cpg, rtfType));
	il.append(new PUSH(cpg, stylesheet.callsNodeset()));
	il.append(new INVOKEINTERFACE(index,4));

	il.append(DUP);

	index = cpg.addInterfaceMethodref(DOM_INTF,
				 "getOutputDomBuilder",
				 "()" + TRANSLET_OUTPUT_SIG);

	il.append(new INVOKEINTERFACE(index,1));
	il.append(DUP);
	il.append(methodGen.storeHandler());

	il.append(methodGen.startDocument());

	translateContents(classGen, methodGen);

	il.append(methodGen.loadHandler());
	il.append(methodGen.endDocument());

	if (stylesheet.callsNodeset()
	    && !DOM_CLASS.equals(DOM_IMPL_CLASS)) {
	    index = cpg.addMethodref(DOM_ADAPTER_CLASS,
				     "<init>",
				     "("+DOM_INTF_SIG+
				     "["+STRING_SIG+
				     "["+STRING_SIG+
				     "[I"+
				     "["+STRING_SIG+")V");
	    il.append(new NEW(cpg.addClass(DOM_ADAPTER_CLASS)));
	    il.append(new DUP_X1());
	    il.append(SWAP);

	    /*
	     * Give the DOM adapter an empty type mapping if the nodeset
	     * extension function is never called.
	     */
	    if (!stylesheet.callsNodeset()) {
		il.append(new ICONST(0));
		il.append(new ANEWARRAY(cpg.addClass(STRING)));
		il.append(DUP);
		il.append(DUP);
		il.append(new ICONST(0));
		il.append(new NEWARRAY(BasicType.INT));
		il.append(SWAP);
		il.append(new INVOKESPECIAL(index));
	    }
	    else {
		il.append(ALOAD_0);
		il.append(new GETFIELD(cpg.addFieldref(TRANSLET_CLASS,
					   NAMES_INDEX,
					   NAMES_INDEX_SIG)));
		il.append(ALOAD_0);
		il.append(new GETFIELD(cpg.addFieldref(TRANSLET_CLASS,
					   URIS_INDEX,
					   URIS_INDEX_SIG)));
		il.append(ALOAD_0);
		il.append(new GETFIELD(cpg.addFieldref(TRANSLET_CLASS,
					   TYPES_INDEX,
					   TYPES_INDEX_SIG)));
		il.append(ALOAD_0);
		il.append(new GETFIELD(cpg.addFieldref(TRANSLET_CLASS,
					   NAMESPACE_INDEX,
					   NAMESPACE_INDEX_SIG)));

		il.append(new INVOKESPECIAL(index));

		il.append(DUP);
		il.append(methodGen.loadDOM());
		il.append(new CHECKCAST(cpg.addClass(classGen.getDOMClass())));
		il.append(SWAP);
		index = cpg.addMethodref(MULTI_DOM_CLASS,
					 "addDOMAdapter",
					 "(" + DOM_ADAPTER_SIG + ")I");
		il.append(new INVOKEVIRTUAL(index));
	    }
	}

	il.append(SWAP);
	il.append(methodGen.storeHandler());
    }

    /**
     * Returns true if this expression/instruction depends on the context. By
     * default, every expression/instruction depends on the context unless it
     * overrides this method. Currently used to determine if result trees are
     * compiled using procedures or little DOMs (result tree fragments).
     * @return 'true' if this node depends on the context.
     */
    protected boolean contextDependent() {
	return true;
    }

    /**
     * Return true if any of the expressions/instructions in the contents of
     * this node is context dependent.
     * @return 'true' if the contents of this node is context dependent.
     */
    protected boolean dependentContents() {
	final int n = elementCount();
	for (int i = 0; i < n; i++) {
	    final SyntaxTreeNode item = (SyntaxTreeNode)_contents.elementAt(i);
	    if (item.contextDependent()) {
		return true;
	    }
	}
	return false;
    }

    /**
     * Adds a child node to this syntax tree node.
     * @param element is the new child node.
     */
    protected final void addElement(SyntaxTreeNode element) {
	_contents.addElement(element);
	element.setParent(this);
    }

    /**
     * Inserts the first child node of this syntax tree node. The existing
     * children are shifted back one position.
     * @param element is the new child node.
     */
    protected final void setFirstElement(SyntaxTreeNode element) {
	_contents.insertElementAt(element,0);
	element.setParent(this);
    }

    /**
     * Removed a child node of this syntax tree node.
     * @param element is the child node to remove.
     */
    protected final void removeElement(SyntaxTreeNode element) {
	_contents.remove(element);
	element.setParent(null);
    }

    /**
     * Returns a Vector containing all the child nodes of this node.
     * @return A Vector containing all the child nodes of this node.
     */
    protected final Vector getContents() {
	return _contents;
    }

    /**
     * Tells you if this node has any child nodes.
     * @return 'true' if this node has any children.
     */
    protected final boolean hasContents() {
	return elementCount() > 0;
    }

    /**
     * Returns the number of children this node has.
     * @return Number of child nodes.
     */
    protected final int elementCount() {
	return _contents.size();
    }

    /**
     * Returns an Enumeration of all child nodes of this node.
     * @return An Enumeration of all child nodes of this node.
     */
    protected final Enumeration elements() {
	return _contents.elements();
    }

    /**
     * Returns a child node at a given position.
     * @param pos The child node's position.
     * @return The child node.
     */
    protected final Object elementAt(int pos) {
	return _contents.elementAt(pos);
    }

    /**
     * Returns this element's last child
     * @return The child node.
     */
    protected final SyntaxTreeNode lastChild() {
	if (_contents.size() == 0) return null;
	return (SyntaxTreeNode)_contents.lastElement();
    }

    /**
     * Displays the contents of this syntax tree node (to stdout).
     * This method is intended for debugging _only_, and should be overridden
     * by all syntax tree node implementations.
     * @param indent Indentation level for syntax tree levels.
     */
    public void display(int indent) {
	displayContents(indent);
    }

    /**
     * Displays the contents of this syntax tree node (to stdout).
     * This method is intended for debugging _only_ !!!
     * @param indent Indentation level for syntax tree levels.
     */
    protected void displayContents(int indent) {
	final int n = elementCount();
	for (int i = 0; i < n; i++) {
	    SyntaxTreeNode item = (SyntaxTreeNode)_contents.elementAt(i);
	    item.display(indent);
	}
    }

    /**
     * Set the indentation level for debug output.
     * @param indent Indentation level for syntax tree levels.
     */
    protected final void indent(int indent) {
	System.out.print(new String(_spaces, 0, indent));
    }

    /**
     * Report an error to the parser.
     * @param element The element in which the error occured (normally 'this'
     * but it could also be an expression/pattern/etc.)
     * @param parser The XSLT parser to report the error to.
     * @param error The error code (from util/ErrorMsg).
     * @param message Any additional error message.
     */
    protected void reportError(SyntaxTreeNode element, Parser parser,
			       String errorCode, String message) {
	final ErrorMsg error = new ErrorMsg(errorCode, message, element);
        parser.reportError(Constants.ERROR, error);
    }

    /**
     * Report a recoverable error to the parser.
     * @param element The element in which the error occured (normally 'this'
     * but it could also be an expression/pattern/etc.)
     * @param parser The XSLT parser to report the error to.
     * @param error The error code (from util/ErrorMsg).
     * @param message Any additional error message.
     */
    protected  void reportWarning(SyntaxTreeNode element, Parser parser,
				  String errorCode, String message) {
	final ErrorMsg error = new ErrorMsg(errorCode, message, element);
        parser.reportError(Constants.WARNING, error);

FUNC_DECL IF PARAM PARAM CALL BINARY_OP ASSIGN LITERAL_ANCHOR CALL

FUNC_DECL IF VAR_DECL VAR_DECL VAR_DECL IF VAR_DECL VAR_DECL VAR_DECL VAR_DECL VAR_DECL PARAM PARAM CALL CALL BINARY_OP CALL CALL CALL CALL CALL CALL CALL ASSIGN CALL CALL CALL CALL CALL CALL CALL CALL IF CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL COND_EXPR LITERAL_ANCHOR CALL CALL CALL CALL CALL CALL CALL CALL ASSIGN LITERAL_ANCHOR BINARY_OP LITERAL_ANCHOR LITERAL_ANCHOR CALL BINARY_OP LITERAL_ANCHOR COND_EXPR ASSIGN CALL CALL CALL LITERAL_ANCHOR LITERAL_ANCHOR CALL CALL ASSIGN CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL BINARY_OP LITERAL_ANCHOR CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL LITERAL_ANCHOR BINARY_OP BINARY_OP LITERAL_ANCHOR CALL CALL CALL CALL CALL LITERAL_ANCHOR CALL LITERAL_ANCHOR BINARY_OP LITERAL_ANCHOR BINARY_OP CALL LITERAL_ANCHOR BINARY_OP LITERAL_ANCHOR LITERAL_ANCHOR BINARY_OP BINARY_OP LITERAL_ANCHOR BINARY_OP BINARY_OP LITERAL_ANCHOR BINARY_OP LITERAL_ANCHOR

FUNC_DECL VAR_DECL PARAM PARAM PARAM PARAM CALL CALL

FUNC_DECL PARAM PARAM PARAM CALL ASSIGN LITERAL_ANCHOR


public interface CellValueRecordInterface
{

    /**
     * get the row this cell occurs on
     *
     * @return the row
     */

    public int getRow();

    /**
     * get the column this cell defines within the row
     *
     * @return the column
     */

    public short getColumn();

    /**
     * set the row this cell occurs on
     * @param row the row this cell occurs within
     */

    public void setRow(int row);

    /**
     * set the column this cell defines within the row
     *
     * @param col the column this cell defines
     */

    public void setColumn(short col);

    public void setXFIndex(short xf);

    public short getXFIndex();

    /**
     * returns whether this cell is before the passed in cell
     *
     * @param i  another cell interface record to compare
     * @return true if the cells is before, or false if not
     */

    public boolean isBefore(CellValueRecordInterface i);

    /**
     * returns whether this cell is after the passed in cell
     *
     * @param i  record to compare
     * @return true if the cell is after, false if not
     */

    public boolean isAfter(CellValueRecordInterface i);

    /**
     * returns whether this cell represents the same cell (NOT VALUE)
     *
     * @param i  record to compare
     * @return true if the cells are the same cell (positionally), false if not.
     */

    public boolean isEqual(CellValueRecordInterface i);

    public Object clone();


org.apache.xalan.xsltc.trax.Util

public final class Util {

    public static String baseName(String name) {
	return org.apache.xalan.xsltc.compiler.util.Util.baseName(name);
    }

    public static String noExtName(String name) {
	return org.apache.xalan.xsltc.compiler.util.Util.noExtName(name);
    }

    public static String toJavaName(String name) {
	return org.apache.xalan.xsltc.compiler.util.Util.toJavaName(name);
    }

    /**
     * Creates a SAX2 InputSource object from a TrAX Source object
     */
    public static InputSource getInputSource(XSLTC xsltc, Source source)
	throws TransformerConfigurationException
    {
	InputSource input = null;

	String systemId = source.getSystemId();

	try {
	    if (source instanceof SAXSource) {
		final SAXSource sax = (SAXSource)source;
		input = sax.getInputSource();
                try {
                    XMLReader reader = sax.getXMLReader();

                     /*
                      * Fix for bug 24695
                      * According to JAXP 1.2 specification if a SAXSource
                      * is created using a SAX InputSource the Transformer or
                      * TransformerFactory creates a reader via the
                      * XMLReaderFactory if setXMLReader is not used
                      */

                    if (reader == null) {
                       try {
                           reader= XMLReaderFactory.createXMLReader();
                       } catch (Exception e ) {
                           try {

                               SAXParserFactory parserFactory =
                                      SAXParserFactory.newInstance();
                               parserFactory.setNamespaceAware(true);
                               reader = parserFactory.newSAXParser()
                                     .getXMLReader();

                           } catch (ParserConfigurationException pce ) {
                               throw new TransformerConfigurationException
                                 ("ParserConfigurationException" ,pce);
                           }
                       }
                    }
                    reader.setFeature;
                    reader.setFeature;

                    xsltc.setXMLReader(reader);
                }catch (SAXNotRecognizedException snre ) {
                  throw new TransformerConfigurationException
                       ("SAXNotRecognizedException ",snre);
                }catch (SAXNotSupportedException snse ) {
                  throw new TransformerConfigurationException
                       ("SAXNotSupportedException ",snse);
                }catch (SAXException se ) {
                  throw new TransformerConfigurationException
                       ("SAXException ",se);
                }

	    }
	    else if (source instanceof DOMSource) {
		final DOMSource domsrc = (DOMSource)source;
		final Document dom = (Document)domsrc.getNode();
		final DOM2SAX dom2sax = new DOM2SAX(dom);
		xsltc.setXMLReader(dom2sax);

		input = SAXSource.sourceToInputSource(source);
		if (input == null){
		    input = new InputSource(domsrc.getSystemId());
		}
	    }
	    else if (source instanceof StreamSource) {
		final StreamSource stream = (StreamSource)source;
		final InputStream istream = stream.getInputStream();
		final Reader reader = stream.getReader();

		if (istream != null) {
		    input = new InputSource(istream);
		}
		else if (reader != null) {
		    input = new InputSource(reader);
		}
		else {
		    input = new InputSource(systemId);
		}
	    }
	    else {
		ErrorMsg err = new ErrorMsg(ErrorMsg.JAXP_UNKNOWN_SOURCE_ERR);
		throw new TransformerConfigurationException(err.toString());
	    }
	    input.setSystemId(systemId);
	}
	catch (NullPointerException e) {
 	    ErrorMsg err = new ErrorMsg(ErrorMsg.JAXP_NO_SOURCE_ERR,
					"TransformerFactory.newTemplates()");
	    throw new TransformerConfigurationException(err.toString());
	}
	catch (SecurityException e) {
 	    ErrorMsg err = new ErrorMsg(ErrorMsg.FILE_ACCESS_ERR, systemId);
	    throw new TransformerConfigurationException(err.toString());
	}
	return input;


org.gjt.sp.jedit.EditAction

public abstract class EditAction
{
	//{{{ EditAction constructor
	/**
	 * Creates a new edit action with the specified name.
	 * @param name The action name
	 */
	public EditAction(String name)
	{
		this.name = name;
	} //}}}

	//{{{ getName() method
	/**
	 * Returns the internal name of this action.
	 */
	public String getName()
	{
		return name;
	} //}}}

	//{{{ getLabel() method
	/**
	 * Returns the action's label. The default implementation returns the
	 * value of the property named by the action's internal name suffixed
	 * with .label.
	 */
	public String getLabel()
	{
		return jEdit.getProperty(name + ".label");
	} //}}}

	//{{{ getMouseOverText() method
	/**
	 * Returns the text that should be shown when the mouse is placed over
	 * this action's menu item or tool bar button. Currently only used by
	 * the macro system.
	 * @since jEdit 4.0pre5
	 */
	public String getMouseOverText()
	{
		return null;
	} //}}}

	//{{{ invoke() method
	/**
	 * Invokes the action.
	 * @param view The view
	 * @since jEdit 2.7pre2
	 */
	public abstract void invoke(View view);
	//}}}

	//{{{ getView() method
	/**
	 * @deprecated Call GUIUtilities.getView() instead.
	 */
	public static View getView(Component comp)
	{
		// moved to GUIUtilities as it makes no sense being here.
		return GUIUtilities.getView(comp);
	} //}}}

	//{{{ isToggle() method
	/**
	 * Returns if this edit action should be displayed as a check box
	 * in menus.
	 * @since jEdit 2.2pre4
	 */
	public boolean isToggle()
	{
		return false;
	} //}}}

	//{{{ isSelected() method
	/**
	 * If this edit action is a toggle, returns if it is selected or not.
	 * @param view The view
	 * @since jEdit 3.2pre5
	 */
	public boolean isSelected(View view)
	{
		return false;
	} //}}}

	//{{{ noRepeat() method
	/**
	 * Returns if this edit action should not be repeated. Returns false
	 * by default.
	 * @since jEdit 2.7pre2
	 */
	public boolean noRepeat()
	{
		return false;
	} //}}}

	//{{{ noRecord() method
	/**
	 * Returns if this edit action should not be recorded. Returns false
	 * by default.
	 * @since jEdit 2.7pre2
	 */
	public boolean noRecord()
	{
		return false;
	} //}}}

	//{{{ getCode() method
	/**
	 * Returns the BeanShell code that will replay this action.
	 * @since jEdit 2.7pre2
	 */
	public abstract String getCode();
	//}}}

	//{{{ toString() method
	public String toString()
	{
		return name;
	} //}}}

	//{{{ Private members
	private String name;
	//}}}

	//{{{ Wrapper class
	/**
	 * 'Wrap' EditActions in this class to turn them into AWT
	 * ActionListeners, that can be attached to buttons, menu items, etc.
	 */
	public static class Wrapper implements ActionListener
	{
		public Wrapper(EditAction action)
		{
			this.action = action;
		}

		/**
		 * Called when the user selects this action from a menu.
		 * It passes the action through the
		 * InputHandler.executeAction() method,
		 * which performs any recording or repeating. It also
		 * loads the action if necessary.
		 *
		 * @param evt The action event
		 */
		public void actionPerformed(ActionEvent evt)
		{
			// Let input handler do recording, repeating, etc
			GUIUtilities.getView((Component)evt.getSource())
				.getInputHandler().invokeAction(action);
		}

		private EditAction action;

	public String getName()
	{
		return name;

	public String toString()
	{
		return name;


public class Gcj extends DefaultCompilerAdapter {

    /**
     * Performs a compile using the gcj compiler.
     */
    public boolean execute() throws BuildException {
        Commandline cmd;
        attributes.log("Using gcj compiler", Project.MSG_VERBOSE);
        cmd = setupGCJCommand();

        int firstFileName = cmd.size();
        logAndAddFilesToCompile(cmd);

        return
            executeExternalCompile(cmd.getCommandline(), firstFileName) == 0;
    }

    protected Commandline setupGCJCommand() {
        Commandline cmd = new Commandline();
        Path classpath = new Path(project);

        if (bootclasspath != null) {
            classpath.append(bootclasspath);
        }

        classpath.addExtdirs(extdirs);

        classpath.append(getCompileClasspath());

        if (compileSourcepath != null) {
            classpath.append(compileSourcepath);
        } else {
            classpath.append(src);
        }

        String exec = getJavac().getExecutable();
        cmd.setExecutable(exec == null ? "gcj" : exec);

        if (destDir != null) {
            cmd.createArgument().setValue("-d");
            cmd.createArgument().setFile(destDir);

            if (!destDir.exists() && !destDir.mkdirs()) {
                throw new BuildException("Can't make output directories. "
                                         + "Maybe permission is wrong. ");
            }
        }

        cmd.createArgument().setValue("-classpath");
        cmd.createArgument().setPath(classpath);

        if (encoding != null) {
            cmd.createArgument().setValue("--encoding=" + encoding);
        }
        if (debug) {
            cmd.createArgument().setValue("-g1");
        }
        if (optimize) {
            cmd.createArgument().setValue("-O");
        }

        /**
         *  gcj should be set for generate class.
         * ... if no 'compile to native' argument is passed
         */
        if (!isNativeBuild()) {
            cmd.createArgument().setValue("-C");
        }

        addCurrentCompilerArgs(cmd);

        return cmd;
    }

    /**
     * Whether any of the arguments given via <compilerarg>
     * implies that compilation to native code is requested.
     *
     * @since Ant 1.6.2
     */
    public boolean isNativeBuild() {
        boolean nativeBuild = false;
        String[] additionalArguments = getJavac().getCurrentCompilerArgs();
        int argsLength = 0;
        while (!nativeBuild && argsLength < additionalArguments.length) {
            int conflictLength = 0;
            while (!nativeBuild
                   && conflictLength < CONFLICT_WITH_DASH_C.length) {
                nativeBuild = (additionalArguments[argsLength].startsWith
                               (CONFLICT_WITH_DASH_C[conflictLength]));
                conflictLength++;
            }
            argsLength++;
        }
        return nativeBuild;
    }

    private static final String [] CONFLICT_WITH_DASH_C = {
        "-o" , "--main=", "-D", "-fjni", "-L"


public class OrdFieldSource extends ValueSource {
  protected String field;

  /**
   * Contructor for a certain field.
   * @param field field whose values order is used.
   */
  public OrdFieldSource(String field) {
    this.field = field;
  }

  /*(non-Javadoc) @see org.apache.lucene.search.function.ValueSource#description() */
  public String description() {
    return "ord(" + field + ')';
  }

  /*(non-Javadoc) @see org.apache.lucene.search.function.ValueSource#getValues(org.apache.lucene.index.IndexReader) */
  public DocValues getValues(IndexReader reader) throws IOException {
    final int[] arr = FieldCache.DEFAULT.getStringIndex(reader, field).order;
    return new DocValues() {
      /*(non-Javadoc) @see org.apache.lucene.search.function.DocValues#floatVal(int) */
      public float floatVal(int doc) {
        return (float)arr[doc];
      }
      /*(non-Javadoc) @see org.apache.lucene.search.function.DocValues#strVal(int) */
      public String strVal(int doc) {
        return Integer.toString(arr[doc]);
      }
      /*(non-Javadoc) @see org.apache.lucene.search.function.DocValues#toString(int) */
      public String toString(int doc) {
        return description() + '=' + intVal(doc);
      }
      /*(non-Javadoc) @see org.apache.lucene.search.function.DocValues#getInnerArray() */
      Object getInnerArray() {
        return arr;
      }
    };
  }

  /*(non-Javadoc) @see java.lang.Object#equals(java.lang.Object) */
  public boolean equals(Object o) {
    if (o.getClass() !=  OrdFieldSource.class) return false;
    OrdFieldSource other = (OrdFieldSource)o;
    return this.field.equals(other.field);
  }

  private static final int hcode = OrdFieldSource.class.hashCode();

  /*(non-Javadoc) @see java.lang.Object#hashCode() */
  public int hashCode() {
    return hcode + field.hashCode();


public class ROFile {

  static Category cat = Category.getInstance(ROFile.class.getName());

  public
  static
  void main(String argv[]) {

    if(argv.length == 1)
      init(argv[0]);
    else
      Usage("Wrong number of arguments.");

    test();
  }

  static
  void Usage(String msg) {
    System.err.println(msg);
    System.err.println( "Usage: java " + ROFile.class.getName() +
			"configFile");
    System.exit(1);
  }

  static
  void init(String configFile) {
    PropertyConfigurator.configure(configFile);
  }

  static
  void test() {
    int i = -1;
    cat.debug("Message " + ++i);


public class DigestAlgorithm implements Algorithm {

    private static final int BYTE_MASK = 0xFF;
    private static final int BUFFER_SIZE = 8192;

    /**
     * MessageDigest algorithm to be used.
     */
    private String algorithm = "MD5";

    /**
     * MessageDigest Algorithm provider
     */
    private String provider = null;

    /**
     * Message Digest instance
     */
    private MessageDigest messageDigest = null;

    /**
     * Size of the read buffer to use.
     */
    private int readBufferSize = BUFFER_SIZE;

    /**
     * Specifies the algorithm to be used to compute the checksum.
     * Defaults to "MD5". Other popular algorithms like "SHA" may be used as well.
     * @param algorithm the digest algorithm to use
     */
    public void setAlgorithm(String algorithm) {
        this.algorithm = algorithm;
    }

    /**
     * Sets the MessageDigest algorithm provider to be used
     * to calculate the checksum.
     * @param provider provider to use
     */
    public void setProvider(String provider) {
        this.provider = provider;
    }

    /** Initialize the security message digest. */
    public void initMessageDigest() {
        if (messageDigest != null) {
            return;
        }

        if ((provider != null) && !"".equals(provider) && !"null".equals(provider)) {
            try {
                messageDigest = MessageDigest.getInstance(algorithm, provider);
            } catch (NoSuchAlgorithmException noalgo) {
                throw new BuildException(noalgo);
            } catch (NoSuchProviderException noprovider) {
                throw new BuildException(noprovider);
            }
        } else {
            try {
                messageDigest = MessageDigest.getInstance(algorithm);
            } catch (NoSuchAlgorithmException noalgo) {
                throw new BuildException(noalgo);
            }
        }
    }

    /**
     * This algorithm supports only MD5 and SHA.
     * @return true if all is ok, otherwise false.
     */
    public boolean isValid() {
        return "SHA".equalsIgnoreCase(algorithm) || "MD5".equalsIgnoreCase(algorithm);
    }

    /**
     * Computes a value for a file content with the specified digest algorithm.
     * @param file    File object for which the value should be evaluated.
     * @return        The value for that file
     */
    public String getValue(File file) {
        initMessageDigest();
        String checksum = null;
        try {
            if (!file.canRead()) {
                return null;
            }
            FileInputStream fis = null;

            byte[] buf = new byte[readBufferSize];
            try {
                messageDigest.reset();
                fis = new FileInputStream(file);
                DigestInputStream dis = new DigestInputStream(fis,
                                                              messageDigest);
                while (dis.read(buf, 0, readBufferSize) != -1) {
                }
                dis.close();
                fis.close();
                fis = null;
                byte[] fileDigest = messageDigest.digest();
                StringBuffer checksumSb = new StringBuffer();
                for (int i = 0; i < fileDigest.length; i++) {
                    String hexStr
                        = Integer.toHexString(BYTE_MASK & fileDigest[i]);
                    if (hexStr.length() < 2) {
                        checksumSb.append("0");
                    }
                    checksumSb.append(hexStr);
                }
                checksum = checksumSb.toString();
            } catch (Exception e) {
                return null;
            }
        } catch (Exception e) {
            return null;
        }
        return checksum;
    }

    /**
     * Override Object.toString().
     * @return some information about this algorithm.
     */
    public String toString() {
        StringBuffer buf = new StringBuffer();
        buf.append("<DigestAlgorithm:");
        buf.append("algorithm=").append(algorithm);
        buf.append(";provider=").append(provider);
        buf.append(">");
        return buf.toString();


public class MethodGenerator extends MethodGen
    implements org.apache.xalan.xsltc.compiler.Constants {
    protected static final int INVALID_INDEX   = -1;

    private static final String START_ELEMENT_SIG
	= "(" + STRING_SIG + ")V";
    private static final String END_ELEMENT_SIG
	= START_ELEMENT_SIG;

    private InstructionList _mapTypeSub;

    private static final int DOM_INDEX       = 1;
    private static final int ITERATOR_INDEX  = 2;
    private static final int HANDLER_INDEX   = 3;

    private Instruction       _iloadCurrent;
    private Instruction       _istoreCurrent;
    private final Instruction _astoreHandler;
    private final Instruction _aloadHandler;
    private final Instruction _astoreIterator;
    private final Instruction _aloadIterator;
    private final Instruction _aloadDom;
    private final Instruction _astoreDom;

    private final Instruction _startElement;
    private final Instruction _endElement;
    private final Instruction _startDocument;
    private final Instruction _endDocument;
    private final Instruction _attribute;
    private final Instruction _namespace;

    private final Instruction _setStartNode;
    private final Instruction _reset;
    private final Instruction _nextNode;
    private final Instruction _nextNodeId;

    private SlotAllocator _slotAllocator;
    private boolean _allocatorInit = false;

    public MethodGenerator(int access_flags, Type return_type,
			   Type[] arg_types, String[] arg_names,
			   String method_name, String class_name,
			   InstructionList il, ConstantPoolGen cpg) {
	super(access_flags, return_type, arg_types, arg_names, method_name,
	      class_name, il, cpg);

	_astoreHandler  = new ASTORE(HANDLER_INDEX);
	_aloadHandler   = new ALOAD(HANDLER_INDEX);
	_astoreIterator = new ASTORE(ITERATOR_INDEX);
	_aloadIterator  = new ALOAD(ITERATOR_INDEX);
	_aloadDom       = new ALOAD(DOM_INDEX);
	_astoreDom      = new ASTORE(DOM_INDEX);

	final int startElement =
	    cpg.addInterfaceMethodref(TRANSLET_OUTPUT_INTERFACE,
				      "startElement",
				      START_ELEMENT_SIG);
	_startElement = new INVOKEINTERFACE(startElement, 2);

	final int endElement =
	    cpg.addInterfaceMethodref(TRANSLET_OUTPUT_INTERFACE,
				      "endElement",
				      END_ELEMENT_SIG);
	_endElement = new INVOKEINTERFACE(endElement, 2);

	final int attribute =
	    cpg.addInterfaceMethodref(TRANSLET_OUTPUT_INTERFACE,
				      "addAttribute",
				      "("
				      + STRING_SIG
				      + STRING_SIG
				      + ")V");
	_attribute = new INVOKEINTERFACE(attribute, 3);

	final int namespace =
	    cpg.addInterfaceMethodref(TRANSLET_OUTPUT_INTERFACE,
				      "namespaceAfterStartElement",
				      "("
				      + STRING_SIG
				      + STRING_SIG
				      + ")V");
	_namespace = new INVOKEINTERFACE(namespace, 3);

	int index = cpg.addInterfaceMethodref(TRANSLET_OUTPUT_INTERFACE,
					      "startDocument",
					      "()V");
	_startDocument = new INVOKEINTERFACE(index, 1);

	index = cpg.addInterfaceMethodref(TRANSLET_OUTPUT_INTERFACE,
					  "endDocument",
					  "()V");
	_endDocument = new INVOKEINTERFACE(index, 1);

	index = cpg.addInterfaceMethodref(NODE_ITERATOR,
					  SET_START_NODE,
					  SET_START_NODE_SIG);
	_setStartNode = new INVOKEINTERFACE(index, 2);

	index = cpg.addInterfaceMethodref(NODE_ITERATOR,
					  "reset", "()"+NODE_ITERATOR_SIG);
	_reset = new INVOKEINTERFACE(index, 1);

	index = cpg.addInterfaceMethodref(NODE_ITERATOR, NEXT, NEXT_SIG);
	_nextNode = new INVOKEINTERFACE(index, 1);

	index = cpg.addInterfaceMethodref("org.apache.xalan.xsltc.dom.SAXImpl$SingletonNodeIDIterator", NEXTID, NEXT_SIG);
	_nextNodeId = new INVOKEINTERFACE(index, 1);

	_slotAllocator = new SlotAllocator();
	_slotAllocator.initialize(getLocalVariables());
	_allocatorInit = true;
    }

    /**
     * Allocates a local variable. If the slot allocator has already been
     * initialized, then call addLocalVariable2() so that the new variable
     * is known to the allocator. Failing to do this may cause the allocator
     * to return a slot that is already in use.
     */
    public LocalVariableGen addLocalVariable(String name, Type type,
					     InstructionHandle start,
					     InstructionHandle end)
    {
	return (_allocatorInit) ? addLocalVariable2(name, type, start)
	    : super.addLocalVariable(name, type, start, end);
    }

    public LocalVariableGen addLocalVariable2(String name, Type type,
					      InstructionHandle start)
    {
	return super.addLocalVariable(name, type,
				      _slotAllocator.allocateSlot(type),
				      start, null);
    }

    public void removeLocalVariable(LocalVariableGen lvg) {
	_slotAllocator.releaseSlot(lvg);
	super.removeLocalVariable(lvg);
    }

    public Instruction loadDOM() {
	return _aloadDom;
    }

    public Instruction storeDOM() {
	return _astoreDom;
    }

    public Instruction storeHandler() {
	return _astoreHandler;
    }

    public Instruction loadHandler() {
	return _aloadHandler;
    }

    public Instruction storeIterator() {
	return _astoreIterator;
    }

    public Instruction loadIterator() {
	return _aloadIterator;
    }

    public final Instruction setStartNode() {
	return _setStartNode;
    }

    public final Instruction reset() {
	return _reset;
    }

    public final Instruction nextNode() {
	return _nextNode;
    }

    public final Instruction nextNodeId() {
	return _nextNodeId;
    }

    public final Instruction startElement() {
	return _startElement;
    }

    public final Instruction endElement() {
	return _endElement;
    }

    public final Instruction startDocument() {
	return _startDocument;
    }

    public final Instruction endDocument() {
	return _endDocument;
    }

    public final Instruction attribute() {
	return _attribute;
    }

    public final Instruction namespace() {
	return _namespace;
    }

    public Instruction loadCurrentNode() {
	if (_iloadCurrent == null) {
	    int idx = getLocalIndex("current");
	    if (idx > 0)
		_iloadCurrent = new ILOAD(idx);
	    else
		_iloadCurrent = new ICONST(0);
	}
	return _iloadCurrent;
    }

    public Instruction storeCurrentNode() {
	return _istoreCurrent != null
	    ? _istoreCurrent
	    : (_istoreCurrent = new ISTORE(getLocalIndex("current")));
    }

    /** by default context node is the same as current node. MK437 */
    public Instruction loadContextNode() {
	return loadCurrentNode();
    }

    public Instruction storeContextNode() {
	return storeCurrentNode();
    }

    public int getLocalIndex(String name) {
	return getLocalVariable(name).getIndex();
    }

    public LocalVariableGen getLocalVariable(String name) {
	final LocalVariableGen[] vars = getLocalVariables();
	for (int i = 0; i < vars.length; i++)
	    if (vars[i].getName().equals(name))
		return vars[i];
	return null;
    }

    public void setMaxLocals() {

	int maxLocals = super.getMaxLocals();
	int prevLocals = maxLocals;

	final LocalVariableGen[] localVars = super.getLocalVariables();
	if (localVars != null) {
	    if (localVars.length > maxLocals)
		maxLocals = localVars.length;
	}

	if (maxLocals < 5) maxLocals = 5;

	super.setMaxLocals(maxLocals);

FUNC_DECL RETURN PARAM PARAM PARAM PARAM COND_EXPR CALL

FUNC_DECL RETURN PARAM PARAM PARAM LITERAL_ANCHOR CALL


gnu.regexp.CharIndexedString

class CharIndexedString implements CharIndexed, Serializable {
    private String s;
    private int anchor;
    private int len;

    CharIndexedString(String str, int index) {
	s = str;
	len = s.length();
	anchor = index;
    }

    public char charAt(int index) {
	int pos = anchor + index;
	return ((pos < len) && (pos >= 0)) ? s.charAt(pos) : OUT_OF_BOUNDS;
    }

    public boolean isValid() {
	return (anchor < len);
    }

    public boolean move(int index) {
	return ((anchor += index) < len);

FUNC_DECL PARAM PARAM ASSIGN ASSIGN ASSIGN CALL


bsh.BSHTypedVariableDeclaration

class BSHTypedVariableDeclaration extends SimpleNode
{
    public boolean isFinal;

    BSHTypedVariableDeclaration(int id) { super(id); }

	/**
		evaluate the type and one or more variable declarators, e.g.:
			int a, b=5, c;

	*/
    public Object eval( CallStack callstack, Interpreter interpreter)
		throws EvalError
    {
		try {
			NameSpace namespace = callstack.top();
			BSHType typeNode = ((BSHType)jjtGetChild(0));
			Class type = typeNode.getType( namespace );

			int n = jjtGetNumChildren();
			for (int i = 1; i < n; i++)
			{
				BSHVariableDeclarator dec =
					(BSHVariableDeclarator)jjtGetChild(i);

				// Type node is passed down the chain for array initializers
				// which need it under some circumstances
				Object value = dec.eval( typeNode, callstack, interpreter);

				// simple declaration with no value, e.g. int a;
				// null in value will prompt defaulting in setTypedVariable
				if ( value == Primitive.VOID )
					value = null;
				else
				// true null value being assigned
				if ( value == Primitive.NULL ) {
					// leave as Primitive.NULL
				}
				else
				// allow specific numeric conversions on declaration
				if ( canCastToDeclaredType( value, type ) )
					value = BSHCastExpression.castObject( value, type );
				else {
					// leave value alone
				}

				namespace.setTypedVariable( dec.name, type, value, isFinal );
			}
		} catch ( EvalError e ) {
			e.reThrow( "Typed variable declaration", this );
		}

        return Primitive.VOID;
    }

	/**
		Determine if a cast would be legitimate in order to handle the
		special cases where a numeric declared var is assigned a type larger
		than it can handle. (JLS cite??)

			byte b = 5;
			byte b1 = 5*10;

		Normally the above would be int types.
	*/
	/*
		Note: in theory this probably shouldn't be considered a cast, but
		should be taken into account during literal and expression evaluation
		where the result type is guided by the context.  However this is much
		simpler to deal with and there is no other use for the other that I'm
		aware of.
	*/
	boolean canCastToDeclaredType( Object value, Class toType ) {
		if ( !(value instanceof Primitive) )
			return false;
		Class fromType = ((Primitive)value).getType();

		if ( (toType==Byte.TYPE || toType==Short.TYPE || toType==Character.TYPE)
			&& fromType == Integer.TYPE
		)
			return true;
		else
			return false;


public class ReaderInputStream extends InputStream {
    private static final int BYTE_MASK = 0xFF;

    /** Source Reader */
    private Reader in;

    private String encoding = System.getProperty("file.encoding");

    private byte[] slack;

    private int begin;

    /**
     * Construct a ReaderInputStream
     * for the specified Reader.
     *
     * @param reader   Reader.  Must not be null.
     */
    public ReaderInputStream(Reader reader) {
        in = reader;
    }

    /**
     * Construct a ReaderInputStream
     * for the specified Reader,
     * with the specified encoding.
     *
     * @param reader     non-null Reader.
     * @param encoding   non-null String encoding.
     */
    public ReaderInputStream(Reader reader, String encoding) {
        this(reader);
        if (encoding == null) {
            throw new IllegalArgumentException("encoding must not be null");
        } else {
            this.encoding = encoding;
        }
    }

    /**
     * Reads from the Reader, returning the same value.
     *
     * @return the value of the next character in the Reader.
     *
     * @exception IOException if the original Reader fails to be read
     */
    public synchronized int read() throws IOException {
        if (in == null) {
            throw new IOException("Stream Closed");
        }

        byte result;
        if (slack != null && begin < slack.length) {
            result = slack[begin];
            if (++begin == slack.length) {
                slack = null;
            }
        } else {
            byte[] buf = new byte[1];
            if (read(buf, 0, 1) <= 0) {
                return -1;
            } else {
                result = buf[0];
            }
        }
        return result & BYTE_MASK;
    }

    /**
     * Reads from the Reader into a byte array
     *
     * @param b  the byte array to read into
     * @param off the offset in the byte array
     * @param len the length in the byte array to fill
     * @return the actual number read into the byte array, -1 at
     *         the end of the stream
     * @exception IOException if an error occurs
     */
    public synchronized int read(byte[] b, int off, int len)
        throws IOException {
        if (in == null) {
            throw new IOException("Stream Closed");
        }
        if (len == 0) {
            return 0;
        }
        while (slack == null) {
            int n = in.read(buf);
            if (n == -1) {
                return -1;
            }
            if (n > 0) {
                slack = new String(buf, 0, n).getBytes(encoding);
                begin = 0;
            }
        }

        if (len > slack.length - begin) {
            len = slack.length - begin;
        }

        System.arraycopy(slack, begin, b, off, len);

        if ((begin += len) >= slack.length) {
            slack = null;
        }

        return len;
    }

    /**
     * Marks the read limit of the Reader.
     *
     * @param limit the maximum limit of bytes that can be read before the
     *              mark position becomes invalid
     */
    public synchronized void mark(final int limit) {
        try {
            in.mark(limit);
        } catch (IOException ioe) {
            throw new RuntimeException(ioe.getMessage());
        }
    }

    /**
     * @return   the current number of bytes ready for reading
     * @exception IOException if an error occurs
     */
    public synchronized int available() throws IOException {
        if (in == null) {
            throw new IOException("Stream Closed");
        }
        if (slack != null) {
            return slack.length - begin;
        }
        if (in.ready()) {
            return 1;
        }
        return 0;
    }

    /**
     * @return false - mark is not supported
     */
    public boolean markSupported () {
    }

    /**
     * Resets the Reader.
     *
     * @exception IOException if the Reader fails to be reset
     */
    public synchronized void reset() throws IOException {
        if (in == null) {
            throw new IOException("Stream Closed");
        }
        slack = null;
        in.reset();
    }

    /**
     * Closes the Reader.
     *
     * @exception IOException if the original Reader fails to be closed
     */
    public synchronized void close() throws IOException {
        if (in != null) {
            in.close();
            slack = null;
            in = null;

FUNC_DECL TRY PARAM CATCH THROW_RAISE CALL CALL CALL


public interface IvyVariableContainer extends Cloneable {

    public void setVariable(String varName, String value, boolean overwrite);

    public String getVariable(String name);

    /**
     * Specifies the prefix used to indicate a variable is an environment
     * variable. If the prefix doesn't end with a '.', it will be added
     * automatically.
     *
     * @param prefix the prefix to use for the environment variables
     */
    public void setEnvironmentPrefix(String prefix);

    public Object clone();


org.apache.tools.ant.types.Assertions

public class Assertions extends DataType implements Cloneable {

    /**
     * enable/disable sys assertions; null means undefined
     */
    private Boolean enableSystemAssertions;

    /**
     * list of type BaseAssertion
     */
    private ArrayList assertionList = new ArrayList();

    /**
     * enable assertions
     * @param assertion an enable assertion nested element
     */
    public void addEnable(EnabledAssertion assertion) {
        checkChildrenAllowed();
        assertionList.add(assertion);
    }

    /**
     * disable assertions
     * @param assertion a disable assertion nested element
     */
    public void addDisable(DisabledAssertion assertion) {
        checkChildrenAllowed();
        assertionList.add(assertion);
    }

    /**
     * enable or disable system assertions.
     * Default is not set (neither -enablesystemassersions or -disablesytemassertions
     * are used on the command line).
     * @param enableSystemAssertions if true enable system assertions
     */
    public void setEnableSystemAssertions(Boolean enableSystemAssertions) {
        checkAttributesAllowed();
        this.enableSystemAssertions = enableSystemAssertions;
    }

    /**
     * Set the value of the refid attribute.
     *
     *
Subclasses may need to check whether any other attributes
     * have been set as well or child elements have been created and
     * thus override this method. if they do the must call
     * super.setRefid.

     * @param ref the reference to use
     */
    public void setRefid(Reference ref) {
        if (assertionList.size() > 0 || enableSystemAssertions != null) {
            throw tooManyAttributes();
        }
        super.setRefid(ref);
    }

    /**
     * get whatever we are referencing to. This could be ourself.
     * @return the object that contains the assertion info
     */
    private Assertions getFinalReference() {
        if (getRefid() == null) {
            return this;
        } else {
            Object o = getRefid().getReferencedObject(getProject());
            if (!(o instanceof Assertions)) {
                throw new BuildException("reference is of wrong type");
            }
            return (Assertions) o;
        }
    }

    /**
     * how many assertions are made...will resolve references before returning
     * @return total # of commands to make
     */
    public int size() {
        Assertions clause = getFinalReference();
        return clause.getFinalSize();
    }

    /**
     * what is the final size of this object
     * @return
     */
    private int getFinalSize() {
        return assertionList.size() + (enableSystemAssertions != null ? 1 : 0);
    }

    /**
     * add the assertions to a list in a format suitable
     * for adding to a command line
     * @param commandList the command line to format
     */
    public void applyAssertions(List commandList) {
        getProject().log("Applying assertions", Project.MSG_DEBUG);
        Assertions clause = getFinalReference();
        if (Boolean.TRUE.equals(clause.enableSystemAssertions)) {
            getProject().log("Enabling system assertions", Project.MSG_DEBUG);
            commandList.add("-enablesystemassertions");
        } else if (Boolean.FALSE.equals(clause.enableSystemAssertions)) {
            getProject().log("disabling system assertions", Project.MSG_DEBUG);
            commandList.add("-disablesystemassertions");
        }

        Iterator it = clause.assertionList.iterator();
        while (it.hasNext()) {
            BaseAssertion assertion = (BaseAssertion) it.next();
            String arg = assertion.toCommand();
            getProject().log("adding assertion " + arg, Project.MSG_DEBUG);
            commandList.add(arg);
        }
    }

    /**
     * apply all the assertions to the command.
     * @param command the command line to format
     */
    public void applyAssertions(CommandlineJava command) {
        Assertions clause = getFinalReference();
        if (Boolean.TRUE.equals(clause.enableSystemAssertions)) {
            addVmArgument(command, "-enablesystemassertions");
        } else if (Boolean.FALSE.equals(clause.enableSystemAssertions)) {
            addVmArgument(command, "-disablesystemassertions");
        }

        Iterator it = clause.assertionList.iterator();
        while (it.hasNext()) {
            BaseAssertion assertion = (BaseAssertion) it.next();
            String arg = assertion.toCommand();
            addVmArgument(command, arg);
        }
    }

    /**
     * add the assertions to a list in a format suitable
     * for adding to a command line
     * @param commandIterator list of commands
     */
    public void applyAssertions(final ListIterator commandIterator) {
        getProject().log("Applying assertions", Project.MSG_DEBUG);
        Assertions clause = getFinalReference();
        if (Boolean.TRUE.equals(clause.enableSystemAssertions)) {
            getProject().log("Enabling system assertions", Project.MSG_DEBUG);
            commandIterator.add("-enablesystemassertions");
        } else if (Boolean.FALSE.equals(clause.enableSystemAssertions)) {
            getProject().log("disabling system assertions", Project.MSG_DEBUG);
            commandIterator.add("-disablesystemassertions");
        }

        Iterator it = clause.assertionList.iterator();
        while (it.hasNext()) {
            BaseAssertion assertion = (BaseAssertion) it.next();
            String arg = assertion.toCommand();
            getProject().log("adding assertion " + arg, Project.MSG_DEBUG);
            commandIterator.add(arg);
        }
    }

    /**
     * helper method to add a string JVM argument to a command
     * @param command
     * @param arg
     */
    private static void addVmArgument(CommandlineJava command, String arg) {
        Commandline.Argument argument;
        argument = command.createVmArgument();
        argument.setValue(arg);
    }

    /**
     * clone the objects.
     * This is not a full depth clone; the list of assertions is cloned,
     * but it does not clone the underlying assertions.
     * @return a cli
     * @throws CloneNotSupportedException if the super class does not support cloning
     */
    public Object clone() throws CloneNotSupportedException {
        Assertions that = (Assertions) super.clone();
        that.assertionList = (ArrayList) assertionList.clone();
        return that;
    }

    /**
     * base class for our assertion elements.
     */

    public abstract static class BaseAssertion {
        private String packageName;
        private String className;

        /**
         * name a class
         * @param className a class name
         */
        public void setClass(String className) {
            this.className = className;
        }

        /**
         * name a package
         * @param packageName a package name
         */
        public void setPackage(String packageName) {
            this.packageName = packageName;
        }

        /**
         * what is the class name?
         * @return classname or null
         * @see #setClass
         */
        protected String getClassName() {
            return className;
        }

        /**
         * what is the package name?
         * @return package name or null
         * @see #setPackage
         */
        protected String getPackageName() {
            return packageName;
        }

        /**
         * get the prefix used to begin the command; -ea or -da.
         * @return prefix
         */
        public abstract String getCommandPrefix();

        /**
         * create a full command string from this class
         * @throws BuildException in case of trouble
         * @return The command string
         */
        public String toCommand() {
            if (getPackageName() != null && getClassName() != null) {
                throw new BuildException("Both package and class have been set");
            }
            StringBuffer command = new StringBuffer(getCommandPrefix());
            if (getPackageName() != null) {
                command.append(':');
                command.append(getPackageName());
                if (!command.toString().endsWith("...")) {
                    command.append("...");
                }
            } else if (getClassName() != null) {
                command.append(':');
                command.append(getClassName());
            }
            return command.toString();
        }
    }

    /**
     * an enabled assertion enables things
     */
    public static class EnabledAssertion extends BaseAssertion {
        /**
         * get the prefix used to begin the command; -ea or -da.
         * @return prefix
         */
        public String getCommandPrefix() {
            return "-ea";
        }

    }

    /**
     * A disabled assertion disables things
     */
    public static class DisabledAssertion extends BaseAssertion {
        /**
         * get the prefix used to begin the command; -ea or -da.
         * @return prefix
         */
        public String getCommandPrefix() {
            return "-da";

FUNC_DECL LOOP VAR_DECL IF VAR_DECL PARAM CALL IF CALL VAR_DECL VAR_DECL CALL CALL CALL CALL CALL CALL CALL LITERAL_ANCHOR CALL LITERAL_ANCHOR

FUNC_DECL VAR_DECL PARAM PARAM CALL ASSIGN CALL


public class BufferingHttpServiceHandler extends NHttpServiceHandlerBase
                                         implements NHttpServiceHandler {

    public BufferingHttpServiceHandler(
            final HttpProcessor httpProcessor,
            final HttpResponseFactory responseFactory,
            final ConnectionReuseStrategy connStrategy,
            final ByteBufferAllocator allocator,
            final HttpParams params) {
        super(httpProcessor, responseFactory, connStrategy, allocator, params);
    }

    public BufferingHttpServiceHandler(
            final HttpProcessor httpProcessor,
            final HttpResponseFactory responseFactory,
            final ConnectionReuseStrategy connStrategy,
            final HttpParams params) {
        this(httpProcessor, responseFactory, connStrategy,
                new HeapByteBufferAllocator(), params);
    }

    public void connected(final NHttpServerConnection conn) {
        HttpContext context = conn.getContext();

        ServerConnState connState = new ServerConnState(allocator);
        context.setAttribute(CONN_STATE, connState);

        if (this.eventListener != null) {
            this.eventListener.connectionOpen(conn);
        }
    }

    public void requestReceived(final NHttpServerConnection conn) {
        HttpContext context = conn.getContext();

        HttpRequest request = conn.getHttpRequest();
        request.setParams(this.params);

        ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE);

        connState.resetInput();
        connState.setRequest(request);
        connState.setInputState(ServerConnState.REQUEST_RECEIVED);

        ProtocolVersion ver = request.getRequestLine().getProtocolVersion();
        if (!ver.lessEquals(HttpVersion.HTTP_1_1)) {
            ver = HttpVersion.HTTP_1_1;
        }

        HttpResponse response;

        try {

            if (request instanceof HttpEntityEnclosingRequest) {
                if (((HttpEntityEnclosingRequest) request).expectContinue()) {
                    response = this.responseFactory.newHttpResponse(
                        ver, HttpStatus.SC_CONTINUE, context);
                    request.setParams(this.params);

                    if (this.expectationVerifier != null) {
                        try {
                            this.expectationVerifier.verify(request, response, context);
                        } catch (HttpException ex) {
                            response = this.responseFactory.newHttpResponse(
                                    HttpVersion.HTTP_1_0,
                                    HttpStatus.SC_INTERNAL_SERVER_ERROR,
                                    context);
                            request.setParams(this.params);
                            handleException(ex, response);
                        }
                    }

                    if (response.getStatusLine().getStatusCode() < 200) {
                        conn.submitResponse(response);
                    } else {
                        conn.resetInput();
                        connState.resetInput();
                        sendResponse(conn, response);
                    }
                }
            } else {
                conn.suspendInput();
                processRequest(conn, request);
            }

        } catch (IOException ex) {
            shutdownConnection(conn, ex);
            if (this.eventListener != null) {
                this.eventListener.fatalIOException(ex, conn);
            }
        } catch (HttpException ex) {
            closeConnection(conn, ex);
            if (this.eventListener != null) {
                this.eventListener.fatalProtocolException(ex, conn);
            }
        }
    }

    public void closed(final NHttpServerConnection conn) {
        if (this.eventListener != null) {
            this.eventListener.connectionClosed(conn);
        }
    }

    public void exception(final NHttpServerConnection conn, final HttpException httpex) {
        HttpContext context = conn.getContext();
        try {
            HttpResponse response = this.responseFactory.newHttpResponse(
                HttpVersion.HTTP_1_0, HttpStatus.SC_INTERNAL_SERVER_ERROR, context);
            response.setParams(this.params);
            handleException(httpex, response);
            response.setEntity(null);
            sendResponse(conn, response);

        } catch (IOException ex) {
            shutdownConnection(conn, ex);
            if (this.eventListener != null) {
                this.eventListener.fatalIOException(ex, conn);
            }
        } catch (HttpException ex) {
            closeConnection(conn, ex);
            if (this.eventListener != null) {
                this.eventListener.fatalProtocolException(ex, conn);
            }
        }
    }

    public void inputReady(final NHttpServerConnection conn, final ContentDecoder decoder) {
        HttpContext context = conn.getContext();
        HttpRequest request = conn.getHttpRequest();

        ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE);
        ContentInputBuffer buffer = connState.getInbuffer();

        connState.setInputState(ServerConnState.REQUEST_BODY_STREAM);

        try {
            buffer.consumeContent(decoder);
            if (decoder.isCompleted()) {
                connState.setInputState(ServerConnState.REQUEST_BODY_DONE);

                HttpEntityEnclosingRequest entityReq = (HttpEntityEnclosingRequest) request;
                if (entityReq.getEntity() != null) {
                    entityReq.setEntity(new ContentBufferEntity(
                            entityReq.getEntity(),
                            connState.getInbuffer()));
                }
                conn.suspendInput();
                processRequest(conn, request);
            }

        } catch (IOException ex) {
            shutdownConnection(conn, ex);
            if (this.eventListener != null) {
                this.eventListener.fatalIOException(ex, conn);
            }
        } catch (HttpException ex) {
            closeConnection(conn, ex);
            if (this.eventListener != null) {
                this.eventListener.fatalProtocolException(ex, conn);
            }
        }
    }

    public void responseReady(final NHttpServerConnection conn) {
    }

    public void outputReady(final NHttpServerConnection conn, final ContentEncoder encoder) {

        HttpContext context = conn.getContext();
        HttpResponse response = conn.getHttpResponse();

        ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE);
        ContentOutputBuffer buffer = connState.getOutbuffer();

        connState.setOutputState(ServerConnState.RESPONSE_BODY_STREAM);

        try {

            buffer.produceContent(encoder);
            if (encoder.isCompleted()) {
                connState.setOutputState(ServerConnState.RESPONSE_BODY_DONE);
                connState.resetOutput();
                if (!this.connStrategy.keepAlive(response, context)) {
                    conn.close();
                } else {
                    conn.requestInput();
                }
            }

        } catch (IOException ex) {
            shutdownConnection(conn, ex);
            if (this.eventListener != null) {
                this.eventListener.fatalIOException(ex, conn);
            }
        }
    }

    protected void handleException(final HttpException ex, final HttpResponse response) {
        int code = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        if (ex instanceof MethodNotSupportedException) {
            code = HttpStatus.SC_NOT_IMPLEMENTED;
        } else if (ex instanceof UnsupportedHttpVersionException) {
            code = HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED;
        } else if (ex instanceof ProtocolException) {
            code = HttpStatus.SC_BAD_REQUEST;
        }
        response.setStatusCode(code);

        byte[] msg = EncodingUtils.getAsciiBytes(ex.getMessage());
        ByteArrayEntity entity = new ByteArrayEntity(msg);
        entity.setContentType("text/plain; charset=US-ASCII");
        response.setEntity(entity);
    }

    protected void processRequest(
            final NHttpServerConnection conn,
            final HttpRequest request) throws IOException, HttpException {

        HttpContext context = conn.getContext();
        ProtocolVersion ver = request.getRequestLine().getProtocolVersion();

        if (!ver.lessEquals(HttpVersion.HTTP_1_1)) {
            ver = HttpVersion.HTTP_1_1;
        }

        HttpResponse response = this.responseFactory.newHttpResponse(
            ver, HttpStatus.SC_OK, conn.getContext());
        request.setParams(this.params);

        context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_RESPONSE, response);

        try {

            this.httpProcessor.process(request, context);

            HttpRequestHandler handler = null;
            if (this.handlerResolver != null) {
                String requestURI = request.getRequestLine().getUri();
                handler = this.handlerResolver.lookup(requestURI);
            }
            if (handler != null) {
                handler.handle(request, response, context);
            } else {
                response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED);
            }

        } catch (HttpException ex) {
            response = this.responseFactory.newHttpResponse(HttpVersion.HTTP_1_0,
                HttpStatus.SC_INTERNAL_SERVER_ERROR, context);
            request.setParams(this.params);
            handleException(ex, response);
        }

        sendResponse(conn, response);
    }

    protected void sendResponse(
            final NHttpServerConnection conn,
            final HttpResponse response) throws IOException, HttpException {

        HttpContext context = conn.getContext();

        ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE);
        ContentOutputBuffer buffer = connState.getOutbuffer();

        this.httpProcessor.process(response, context);

        if (!canResponseHaveBody(connState.getRequest(), response)) {
            response.setEntity(null);
        }

        conn.submitResponse(response);

        connState.setOutputState(ServerConnState.RESPONSE_SENT);

        HttpEntity entity = response.getEntity();
        if (entity != null) {
            OutputStream outstream = new ContentOutputStream(buffer);
            entity.writeTo(outstream);
            outstream.flush();
            outstream.close();
        } else {
            connState.resetOutput();
            if (!this.connStrategy.keepAlive(response, context)) {
                conn.close();
            } else {
                conn.requestInput();
            }
        }
    }

    static class ServerConnState {

        public static final int READY                      = 0;
        public static final int REQUEST_RECEIVED           = 1;
        public static final int REQUEST_BODY_STREAM        = 2;
        public static final int REQUEST_BODY_DONE          = 4;
        public static final int RESPONSE_SENT              = 8;
        public static final int RESPONSE_BODY_STREAM       = 16;
        public static final int RESPONSE_BODY_DONE         = 32;

        private SimpleInputBuffer inbuffer;
        private ContentOutputBuffer outbuffer;

        private int inputState;
        private int outputState;

        private HttpRequest request;
        private final ByteBufferAllocator allocator;

        public ServerConnState(final ByteBufferAllocator allocator) {
            super();
            this.inputState = READY;
            this.outputState = READY;
            this.allocator = allocator;
        }

        public ContentInputBuffer getInbuffer() {
            if (this.inbuffer == null) {
                this.inbuffer = new SimpleInputBuffer(2048, allocator);
            }
            return this.inbuffer;
        }

        public ContentOutputBuffer getOutbuffer() {
            if (this.outbuffer == null) {
                this.outbuffer = new SimpleOutputBuffer(2048, allocator);
            }
            return this.outbuffer;
        }

        public int getInputState() {
            return this.inputState;
        }

        public void setInputState(int inputState) {
            this.inputState = inputState;
        }

        public int getOutputState() {
            return this.outputState;
        }

        public void setOutputState(int outputState) {
            this.outputState = outputState;
        }

        public HttpRequest getRequest() {
            return this.request;
        }

        public void setRequest(final HttpRequest request) {
            this.request = request;
        }

        public void resetInput() {
            this.inbuffer = null;
            this.request = null;
            this.inputState = READY;
        }

        public void resetOutput() {
            this.outbuffer = null;
            this.outputState = READY;

FUNC_DECL TRY VAR_DECL IF VAR_DECL VAR_DECL VAR_DECL VAR_DECL PARAM CATCH CATCH IF CALL CALL CALL CALL CALL IF IF BINARY_OP CALL CALL CALL BINARY_OP CALL BINARY_OP CALL IF ASSIGN CALL CALL LITERAL_ANCHOR LITERAL_ANCHOR CALL CALL IF IF CALL CALL BINARY_OP BINARY_OP CALL ASSIGN LITERAL_ANCHOR CALL TRY LITERAL_ANCHOR CALL CALL CALL CALL CALL CATCH CALL CALL CALL ASSIGN CALL CALL

FUNC_DECL TRY VAR_DECL PARAM PARAM CATCH CATCH VAR_DECL IF IF CALL CALL CALL CALL CALL BINARY_OP CALL BINARY_OP CALL LITERAL_ANCHOR LITERAL_ANCHOR LITERAL_ANCHOR CALL CALL CALL

FUNC_DECL TRY VAR_DECL VAR_DECL VAR_DECL VAR_DECL PARAM PARAM CATCH CATCH IF CALL IF IF CALL CALL CALL CALL CALL BINARY_OP CALL BINARY_OP CALL IF VAR_DECL CALL LITERAL_ANCHOR LITERAL_ANCHOR CALL CALL BINARY_OP CALL LITERAL_ANCHOR CALL CALL CALL CALL CALL CALL CALL

FUNC_DECL TRY VAR_DECL VAR_DECL VAR_DECL VAR_DECL PARAM PARAM CATCH IF CALL IF CALL CALL CALL CALL CALL BINARY_OP CALL IF CALL LITERAL_ANCHOR CALL CALL CALL CALL CALL CALL

FUNC_DECL TRY VAR_DECL IF VAR_DECL VAR_DECL PARAM PARAM CALL CATCH IF IF VAR_DECL CALL CALL CALL CALL CALL BINARY_OP BINARY_OP CALL CALL CALL CALL ASSIGN LITERAL_ANCHOR VAR_DECL LITERAL_ANCHOR LITERAL_ANCHOR CALL CALL ASSIGN CALL CALL CALL ASSIGN CALL CALL CALL CALL CALL

FUNC_DECL IF VAR_DECL IF VAR_DECL VAR_DECL VAR_DECL PARAM PARAM BINARY_OP CALL CALL CALL IF VAR_DECL LITERAL_ANCHOR CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL LITERAL_ANCHOR CALL CALL


public final class ConcatFilter extends BaseParamFilterReader
    implements ChainableReader {

    /** File to add before the content. */
    private File prepend;

    /** File to add after the content. */
    private File append;

    /** Reader for prepend-file. */
    private Reader prependReader = null;

    /** Reader for append-file. */
    private Reader appendReader = null;

    /**
     * Constructor for "dummy" instances.
     *
     * @see BaseFilterReader#BaseFilterReader()
     */
    public ConcatFilter() {
        super();
    }

    /**
     * Creates a new filtered reader.
     *
     * @param in A Reader object providing the underlying stream.
     *           Must not be null.
     */
    public ConcatFilter(final Reader in) {
        super(in);
    }

    /**
     * Returns the next character in the filtered stream. If the desired
     * number of lines have already been read, the resulting stream is
     * effectively at an end. Otherwise, the next character from the
     * underlying stream is read and returned.
     *
     * @return the next character in the resulting stream, or -1
     * if the end of the resulting stream has been reached
     *
     * @exception IOException if the underlying stream throws an IOException
     * during reading
     */
    public int read() throws IOException {
        if (!getInitialized()) {
            initialize();
            setInitialized(true);
        }

        int ch = -1;

        if (prependReader != null) {
            ch = prependReader.read();
            if (ch == -1) {
                prependReader.close();
                prependReader = null;
            }
        }
        if (ch == -1) {
            ch = super.read();
        }
        if (ch == -1) {
            if (appendReader != null) {
                ch = appendReader.read();
                if (ch == -1) {
                    appendReader.close();
                    appendReader = null;
                }
            }
        }

        return ch;
    }

    /**
     * Sets prepend attribute.
     * @param prepend new value
     */
    public void setPrepend(final File prepend) {
        this.prepend = prepend;
    }

    /**
     * Returns prepend attribute.
     * @return prepend attribute
     */
    public File getPrepend() {
        return prepend;
    }

    /**
     * Sets append attribute.
     * @param append new value
     */
    public void setAppend(final File append) {
        this.append = append;
    }

    /**
     * Returns append attribute.
     * @return append attribute
     */
    public File getAppend() {
        return append;
    }

    /**
     * Creates a new ConcatReader using the passed in
     * Reader for instantiation.
     *
     * @param rdr A Reader object providing the underlying stream.
     *            Must not be null.
     *
     * @return a new filter based on this configuration, but filtering
     *         the specified reader
     */
    public Reader chain(final Reader rdr) {
        ConcatFilter newFilter = new ConcatFilter(rdr);
        newFilter.setPrepend(getPrepend());
        newFilter.setAppend(getAppend());
        return newFilter;
    }

    /**
     * Scans the parameters list for the "lines" parameter and uses
     * it to set the number of lines to be returned in the filtered stream.
     * also scan for skip parameter.
     */
    private void initialize() throws IOException {
        Parameter[] params = getParameters();
        if (params != null) {
            for (int i = 0; i < params.length; i++) {
                if ("prepend".equals(params[i].getName())) {
                    setPrepend(new File(params[i].getValue()));
                    continue;
                }
                if ("append".equals(params[i].getName())) {
                    setAppend(new File(params[i].getValue()));
                    continue;
                }
            }
        }
        if (prepend != null) {
            if (!prepend.isAbsolute()) {
                prepend = new File(getProject().getBaseDir(), prepend.getPath());
            }
            prependReader = new BufferedReader(new FileReader(prepend));
        }
        if (append != null) {
            if (!append.isAbsolute()) {
                append = new File(getProject().getBaseDir(), append.getPath());
            }
            appendReader = new BufferedReader(new FileReader(append));

FUNC_DECL RETURN VAR_DECL PARAM CALL CALL CALL CALL CALL

FUNC_DECL IF IF IF VAR_DECL BINARY_OP BINARY_OP BINARY_OP IF LITERAL_ANCHOR IF LITERAL_ANCHOR LOOP LITERAL_ANCHOR CALL ASSIGN CALL ASSIGN CALL BINARY_OP CALL CALL IF IF CALL ASSIGN CALL ASSIGN LITERAL_ANCHOR LITERAL_ANCHOR LITERAL_ANCHOR CALL CALL BREAK_CONTINUE CALL BREAK_CONTINUE CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL

    public ConcatFilter() {
        super();


final class Fallback extends Instruction {

    private boolean _active = false;

    /**
     * This element never produces any data on the stack
     */
    public Type typeCheck(SymbolTable stable) throws TypeCheckError {
	if (_active) {
	    return(typeCheckContents(stable));
	}
	else {
	    return Type.Void;
	}
    }

    /**
     * Activate this fallback element
     */
    public void activate() {
	_active = true;
    }

    public String toString() {
	return("fallback");
    }

    /**
     * Parse contents only if this fallback element is put in place of
     * some unsupported element or non-XSLTC extension element
     */
    public void parseContents(Parser parser) {
	if (_active) parseChildren(parser);
    }

    /**
     * Translate contents only if this fallback element is put in place of
     * some unsupported element or non-XSLTC extension element
     */
    public void translate(ClassGenerator classGen, MethodGenerator methodGen) {
	final ConstantPoolGen cpg = classGen.getConstantPool();
	final InstructionList il = methodGen.getInstructionList();

	if (_active) translateContents(classGen, methodGen);

FUNC_DECL IF VAR_DECL VAR_DECL PARAM PARAM CALL CALL CALL


final class Variable extends VariableBase {

    public int getIndex() {
	return (_local != null) ? _local.getIndex() : -1;
    }

    /**
     * Parse the contents of the variable
     */
    public void parseContents(Parser parser) {
	super.parseContents(parser);

	SyntaxTreeNode parent = getParent();
	if (parent instanceof Stylesheet) {
	    _isLocal = false;
	    Variable var = parser.getSymbolTable().lookupVariable(_name);
	    if (var != null) {
		final int us = this.getImportPrecedence();
		final int them = var.getImportPrecedence();
		if (us == them) {
		    final String name = _name.toString();
		    reportError(this, parser, ErrorMsg.VARIABLE_REDEF_ERR,name);
		}
		else if (them > us) {
		    _ignore = true;
		    return;
		}
		else {
		    var.disable();
		}
	    }
	    ((Stylesheet)parent).addVariable(this);
	    parser.getSymbolTable().addVariable(this);
	}
	else {
	    _isLocal = true;
	}
    }

    /**
     * Runs a type check on either the variable element body or the
     * expression in the 'select' attribute
     */
    public Type typeCheck(SymbolTable stable) throws TypeCheckError {

	if (_select != null) {
	    _type = _select.typeCheck(stable);
	}
	else if (hasContents()) {
	    typeCheckContents(stable);
	    _type = Type.ResultTree;
	}
	else {
	    _type = Type.Reference;
	}
	return Type.Void;
    }

    /**
     * This method is part of a little trick that is needed to use local
     * variables inside nested for-each loops. See the initializeVariables()
     * method in the ForEach class for an explanation
     */
    public void initialize(ClassGenerator classGen, MethodGenerator methodGen) {
	final ConstantPoolGen cpg = classGen.getConstantPool();
	final InstructionList il = methodGen.getInstructionList();

	if (isLocal() && !_refs.isEmpty()) {
	    if (_local == null) {
		_local = methodGen.addLocalVariable2(getEscapedName(),
						     _type.toJCType(),
						     il.getEnd());
	    }
	    if ((_type instanceof IntType) ||
		(_type instanceof NodeType) ||
		(_type instanceof BooleanType)){}
	    else if (_type instanceof RealType){}
	    else
	    il.append(_type.STORE(_local.getIndex()));
	}
    }

    public void translate(ClassGenerator classGen, MethodGenerator methodGen) {
	final ConstantPoolGen cpg = classGen.getConstantPool();
	final InstructionList il = methodGen.getInstructionList();

        if (_refs.isEmpty()) {
            _ignore = true;
        }

	if (_ignore) return;
	_ignore = true;

	final String name = getEscapedName();

	if (isLocal()) {
	    translateValue(classGen, methodGen);

	    if (_local == null) {
                mapRegister(methodGen);
            }
	    il.append(_type.STORE(_local.getIndex()));
	}
	else {
	    String signature = _type.toSignature();

	    if (classGen.containsField(name) == null) {
		classGen.addField(new Field(ACC_PUBLIC,
					    cpg.addUtf8(name),
					    cpg.addUtf8(signature),
					    null, cpg.getConstantPool()));

		il.append(classGen.loadTranslet());
		translateValue(classGen, methodGen);
		il.append(new PUTFIELD(cpg.addFieldref(classGen.getClassName(),
						       name, signature)));

FUNC_DECL RETURN IF PARAM IF BINARY_OP CALL LITERAL_ANCHOR ASSIGN ASSIGN ASSIGN CALL CALL

FUNC_DECL IF VAR_DECL IF IF VAR_DECL VAR_DECL PARAM PARAM CALL ASSIGN RETURN CALL IF VAR_DECL IF CALL LITERAL_ANCHOR CALL CALL BINARY_OP CALL BINARY_OP CALL ASSIGN LITERAL_ANCHOR CALL CALL CALL LITERAL_ANCHOR LITERAL_ANCHOR CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL CALL LITERAL_ANCHOR CALL CALL CALL