/*
Copyright (c) 2003-2009, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/

CKPACKAGER.load( 'ckpackager.includes.token' );

importPackage( org.mozilla.javascript );
importClass( java.io.File );
importClass( java.io.FileReader );

(function()
{
	var indentation,
		tree;

	var printNode = function( node )
	{
		var str,
			type = node.getType(),
			currentTree = tree;

		str =
			node instanceof Node.StringNode ?
				node.getString()
			: type == Token.NUMBER ?
				str = node.getDouble()
			:
				'';

		switch ( type )
		{
			case Token.FUNCTION :

				var fnIndex = node.getExistingIntProp( Node.FUNCTION_PROP ),
					fn		= tree.getFunctionNode(fnIndex),
					args	= [];

				if ( fn.symbolTable != null )
				{
					var iter = fn.symbolTable.keySet().iterator();
					while ( args.length < fn.getParamCount() )
						args.push( iter.next() );
				}

				str += '(' + args + ')';

				node = tree = fn;
				break;

			case Token.REGEXP :
				str = '/' + tree.getRegexpString( node.getExistingIntProp( Node.REGEXP_PROP ) ) + '/';
				str += tree.getRegexpFlags( node.getExistingIntProp( Node.REGEXP_PROP ) );
				break;

			case Token.CASE :
			case Token.GOTO :
				str = node.target.getNext();
				break;

			case Token.LOOP :
				str = node.target;
				break;

			case Token.TARGET :
				str = node.labelId();
				break;
		}

		try { str = node.getString(); } catch (e) {}

		print( indentation + node + ': ' + GetTokenName( type ) +
			' (' + node.getLineno() + ')' +
			( node instanceof Node.Scope ? ' (scope)' : '' ) +
			( str !== '' ? ' = ' + str : '' ) );

		indentation += '.';

		node = node.getFirstChild()

		while ( node )
		{
			printNode( node );
			node = node.getNext();
		}

		if ( type == Token.FUNCTION )
		{
			tree = currentTree;
		}

		// Uncomment to stop on a specific token type.
		/*
		if ( type == Token.USE_STACK )
			quit();
		*/

		indentation = indentation.substr( 1 );
	};

	CKPACKAGER.parser =
	{
		dumpThree : function( script )
		{
			// Setup the compiler environment, error reporter...
			var compilerEnv = new CompilerEnvirons();
			var errorReporter = compilerEnv.getErrorReporter();

			// Create an instance of the parser...
			var parser = new Parser(compilerEnv, errorReporter);

			var scriptOrFnNode = parser.parse(script, null, 1);
			tree = scriptOrFnNode;

			indentation = '';

			printNode( scriptOrFnNode );
		}
	};
})();
