/******************************************************************************
 * Copyright (c) 2007 Stefan Franke, Robert Hanussek, Benjamin Keil,          *
 *                    Steffen Kieß, Johannes Langauf,                         *
 *                    Christoph Marian Müller, Igor Podolskiy,                *
 *                    Tilmann Scheller, Michael Starzmann, Markus Wittlinger  *
 * All rights reserved. This program and the accompanying materials           *
 * are made available under the terms of the Eclipse Public License v1.0      *
 * which accompanies this distribution, and is available at                   *
 * http://www.eclipse.org/legal/epl-v10.html                                  *
 ******************************************************************************/

package org.codecover.instrumentation.xampil.visitor;

import java.io.PrintWriter;

import org.codecover.instrumentation.xampil.syntaxtree.NodeToken;

/**
 * Dumps the syntax tree to a {@link PrintWriter} using
 * {@link NodeToken#getSourceFileImage()}.
 * 
 * @author Generated by JTB 1.3.2
 * @author Christoph Müller:<br>
 *         No line and column handling needed.
 */
public class TreeDumper extends DepthFirstVisitor {
    private PrintWriter targetWriter;

    private int lastEndOffset = -1;

    /**
     * Constructor of a new {@link TreeDumper}.
     * 
     * @param writer
     *            The {@link PrintWriter} to dump in.
     */
    public TreeDumper(PrintWriter writer) {
        this.targetWriter = writer;
    }

    /**
     * @return The targetWriter.
     */
    protected PrintWriter getTargetWriter() {
        return this.targetWriter;
    }

    /**
     * @return The last {@link NodeToken#endOffset}, that is print out.
     *         <code>-1</code> if none was printed.
     */
    protected int getLastEndOffset() {
        return this.lastEndOffset;
    }

    /**
     * Dumps the current NodeToken to the output stream being used.
     */
    @Override
    public void visit(NodeToken n) {
        if (n.numSpecials() > 0) {
            for (NodeToken nt : n.specialTokens) {
                this.targetWriter.write(nt.tokenImage);
            }
        }

        this.targetWriter.write(n.tokenImage);
        this.lastEndOffset = n.endOffset;
    }
}
