 
 parse = (code) ->
 	try
-		esprima.parse code
+		esprima.parse code,
+			range: true
 	catch err
 		{ 'Parse error': err }
+		{}
 
 
 display = (data) ->
-	try
-		data = JSON.stringify(data, null, 2) unless typeof data == 'string'
-	catch err
-		data = { 'JSON error': err }
-	output.setValue(data)
+	# try
+	# 	data = JSON.stringify(data, null, 2) unless typeof data == 'string'
+	# catch err
+	# 	data = { 'JSON error': err }
+	output.setValue(JSON.stringify(data, null, 2))
 	output.clearSelection()
+
 
 
 Syntax =

		when 'ObjectExpression'
			for prop in block.properties
				treeify prop.value, scope
		when 'VariableDeclarator'
			treeify block.id, scope, true
			treeify block.init, scope

	#'YieldExpression': ['argument'] # Harmony


class Scope

	constructor: (@range) ->
		@range ?= [0, 0]
		@variables = []
		console.log "new Scope([#{@range[0]}, #{@range[1]}])"

	add: (variable) ->
		throw 'Variable must be an instance of Variable' unless variable instanceof Variable
		@variables.push variable

	has: (id) ->
		(variable.name for variable in @variables when variable.name == id).length > 0


class Variable

	constructor: (@name, @range) ->
		console.log "new Variable('#{@name}', [#{@range[0]}, #{@range[1]}])"



treeify = (block, scope, declaration) ->
	# In case block is optional in parent block
	if not block then return scope

	# In case block is an array of blocks
	if block instanceof Array
		treeify(el, scope, declaration) for el in block
		return scope

	switch block.type
		when 'Identifier'
			if declaration
				if not scope.root().has block.name
					scope.root().add new Variable block.name, block.range
				else
					console.log 'Variable %s already defined', block.name
		when 'FunctionDeclaration', 'FunctionExpression'
			local = new Tree scope, new Scope block.range
			treeify block.id, scope
			treeify block.params, local, true
			treeify block.defaults, local
