Parsing JavaScript code using Mozilla Rhino

Last year I had blogged “Understanding AST created by Mozilla Rhino parser“, where I exaplained how to traverse AST to get all functions and variables. Since then I have received some comments, public and private, to provide sample code. So here is an example of how to parse JavaScript code and get all functions and variables using Mozilla Rhino.

Note that my intention here is not to build the complete symbol table for any given JavaScript code. And I have not run a lot of test cases on this code. The idea is to show how AST could be traversed and how hierarchy of symbols (functions and variables) be built .

So, for example, if you feed following JavaScript code to this program –

function func1()
{
	var local1 = 10;

	global1 = 20;
}

obj1 = {
	objFunc1 : function()
	{
		var local2 = 30;
	},
	objProp1 : "prop1"
}

You will get following output –

Function : func1
		local1
	global1
	obj1
	obj1
		objFunc1
		Function : objFunc1
			local2
		objProp1

Yes, I know there are duplicates for object and closure – because they are first processed as variable names and then object/closure. This can be easily fixed, but I am going to leave it that way to keep the code simple. Continue reading “Parsing JavaScript code using Mozilla Rhino”

Social