/*
 [The "BSD licence"]
 Copyright (c) 2005-2008 Terence Parr
 All rights reserved.

 Grammar conversion to ANTLR v3 and C#:
 Copyright (c) 2008 Sam Harwell, Pixel Mine, Inc.
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:
 1. Redistributions of source code must retain the above copyright
	notice, this list of conditions and the following disclaimer.
 2. Redistributions in binary form must reproduce the above copyright
	notice, this list of conditions and the following disclaimer in the
	documentation and/or other materials provided with the distribution.
 3. The name of the author may not be used to endorse or promote products
	derived from this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
tree grammar DefineGrammarItemsWalker;

options
{
	language = CSharp3;
	tokenVocab = ANTLR;
	ASTLabelType = GrammarAST;
}

scope AttributeScopeActions
{
	Dictionary<GrammarAST, GrammarAST> actions;
}

@header
{
using Antlr3.Tool;
}

@namespace{Antlr3.Grammars}

public
grammar_[Grammar g]
@init
{
grammar = $g;
root = $start;
}
@after
{
Finish();
}
	:	^(LEXER_GRAMMAR		grammarSpec)
	|	^(PARSER_GRAMMAR	grammarSpec)
	|	^(TREE_GRAMMAR		grammarSpec)
	|	^(COMBINED_GRAMMAR	grammarSpec)
	;

attrScope
scope AttributeScopeActions;
@init
{
	$AttributeScopeActions::actions = new Dictionary<GrammarAST, GrammarAST>();
}
	:	^( 'scope' name=ID attrScopeAction* attrs=ACTION )
		{HandleAttrScope($name, $attrs, $AttributeScopeActions::actions);}
	;

attrScopeAction
	:	^(AMPERSAND ID ACTION)
		{HandleAttrScopeAction($ID, $ACTION, $AttributeScopeActions::actions);}
	;

grammarSpec
	:	ID
		DOC_COMMENT?
		optionsSpec?
		delegateGrammars?
		tokensSpec?
		attrScope*
		actions?
		rules
	;

actions
	:	action+
	;

action
@init
{
	string scope = null;
	GrammarAST nameAST = null;
	GrammarAST actionAST = null;
}
	:	^(amp=AMPERSAND id1=ID
			( id2=ID a1=ACTION
			  {scope = $id1.text; nameAST = $id2; actionAST = $a1;}
			| a2=ACTION
			  {scope = null; nameAST = $id1; actionAST = $a2;}
			)
		 )
		 {HandleAction(scope, $amp, nameAST, actionAST);}
	;

optionsSpec
	:	^(OPTIONS .*)
	;

delegateGrammars
	:	^( 'import' ( ^(ASSIGN ID ID) | ID )+ )
	;

tokensSpec
	:	^(TOKENS tokenSpec*)
	;

tokenSpec
	:	TOKEN_REF
	|	^(	ASSIGN
			TOKEN_REF
			(	STRING_LITERAL
			|	CHAR_LITERAL
			)
		 )
	;

rules
	:	(rule | ^(PREC_RULE .*))+
	;

rule
@init
{
	string name = null;
	IDictionary<string, object> opts = null;
	Rule r = null;
}
	:	^(	RULE id=ID {opts = $RULE.BlockOptions;}
			modifier?
			^( ARG (args=ARG_ACTION)? )
			^( RET (ret=ARG_ACTION)? )
			throwsSpec?
			optionsSpec?				{HandleRuleAfterOptionsSpec(ref name, ref r, opts, $start, $id, $modifier.mod, $args, $ret, $throwsSpec.exceptions);}
			ruleScopeSpec[r]?
			ruleAction[r]*				{HandleRuleAfterRuleActions();}
			b=block
			exceptionGroup?
			EOR							{HandleRuleEnd($b.start, opts);}
		)
	;

ruleAction[Rule r]
	:	^(amp=AMPERSAND id=ID a=ACTION) {HandleRuleAction(r, $amp, $id, $a);}
	;

modifier returns [string mod]
@init
{
	$mod = $start.Token.Text;
}
	:	'protected'
	|	'public'
	|	'private'
	|	'fragment'
	;

throwsSpec returns [HashSet<string> exceptions = new HashSet<string>()]
	:	^('throws' (ID {$exceptions.Add($ID.text);})+ )
	;

ruleScopeSpec[Rule r]
scope AttributeScopeActions;
@init
{
	$AttributeScopeActions::actions = new Dictionary<GrammarAST, GrammarAST>();
}
	:	^(	'scope'
			(	attrScopeAction* attrs=ACTION	{HandleRuleScopeSpecAction(r, $attrs, $AttributeScopeActions::actions);}
			)?
			(	uses=ID							{HandleRuleScopeSpecUses(r, $uses);}
			)*
		)
	;

block
@init
{
	// must run during backtracking
	this.blockLevel++;
	if ( blockLevel == 1 )
		this.outerAltNum=1;
}
	:	^(	BLOCK
			(optionsSpec)?
			(blockAction)*
			(	alternative rewrite
				{{
					if ( this.blockLevel == 1 )
						this.outerAltNum++;
				}}
			)+
			EOB
		 )
	;
finally { blockLevel--; }

// TODO: this does nothing now! subrules cannot have init actions. :(
blockAction
	:	^(AMPERSAND ID ACTION)
	;

alternative
	:	^(ALT element+ EOA)
	;

exceptionGroup
	:	exceptionHandler+ finallyClause?
	|	finallyClause
	;

exceptionHandler
	:   ^('catch' ARG_ACTION ACTION) {TrackInlineAction($ACTION);}
	;

finallyClause
	:    ^('finally' ACTION) {TrackInlineAction($ACTION);}
	;

element
	:   ^(ROOT element)
	|   ^(BANG element)
	|   atom[null]
	|   ^(NOT element)
	|   ^(RANGE atom[null] atom[null])
	|   ^(CHAR_RANGE atom[null] atom[null])
	|	^(ASSIGN id=ID el=element)			{HandleElementAssign($id, $el.start);}
	|	^(PLUS_ASSIGN id=ID el=element)		{HandleElementPlusAssign($id, $el.start);}
	|   ebnf
	|   tree_
	|   ^(SYNPRED block)
	|   act=ACTION							{HandleInlineAction($act);}
	|   act=FORCED_ACTION					{HandleInlineAction($act);}
	|   act=SEMPRED							{HandleInlineAction($act);}
	|   SYN_SEMPRED
	|   ^(BACKTRACK_SEMPRED .*)
	|   act=GATED_SEMPRED					{HandleInlineAction($act);}
	|   EPSILON 
	;

ebnf
	:	(dotLoop) => dotLoop // .* or .+
	|	block
	|	^(OPTIONAL block)
	|	^(CLOSURE block)
	|	^(POSITIVE_CLOSURE block)
	;

/** Track the .* and .+ idioms and make them nongreedy by default.
 */
dotLoop
	:	(	^(CLOSURE dotBlock)
		|	^(POSITIVE_CLOSURE dotBlock)
		)
		{HandleDotLoop($start);}
	;

dotBlock
	:	^( BLOCK ^( ALT WILDCARD EOA ) EOB )
	;

tree_
	:	^(TREE_BEGIN element+)
	;

atom[GrammarAST scope_]
	:	^( t=RULE_REF (a=ARG_ACTION)? )		{HandleRuleReferenceAtom($scope_, $t, $a);}
	|	^( t=TOKEN_REF (a=ARG_ACTION )? )	{HandleTokenReferenceAtom($scope_, $t, $a);}
	|	t=CHAR_LITERAL						{HandleStringLiteralAtom($t);}
	|	t=STRING_LITERAL					{HandleStringLiteralAtom($t);}
	|	WILDCARD
	|	^(DOT ID atom[$ID]) // scope override on rule
	;

ast_suffix
	:	ROOT
	|	BANG
	;

rewrite
@init
{
	// track top level REWRITES node, store stuff there
	currentRewriteRule = $start; // has to execute during backtracking
	if ( state.backtracking == 0 )
	{
		if ( grammar.BuildAST )
			currentRewriteRule.rewriteRefsDeep = new HashSet<GrammarAST>(GrammarAST.TreeTokenEqualityComparer.Default);
	}
}
	:	^(	REWRITES
			(	^(	REWRITE
					(	pred=SEMPRED	{HandleInlineAction($pred);}
					)?
					rewrite_alternative
				)
			)*
		)
		//{System.out.println("-> refs = "+currentRewriteRule.rewriteRefsDeep);}
	|
	;

rewrite_block
@init
{
	GrammarAST enclosingBlock = currentRewriteBlock;
	if ( state.backtracking == 0 )
	{
		// don't do if guessing
		currentRewriteBlock=$start; // pts to BLOCK node
		currentRewriteBlock.rewriteRefsShallow = new HashSet<GrammarAST>(GrammarAST.TreeTokenEqualityComparer.Default);
		currentRewriteBlock.rewriteRefsDeep = new HashSet<GrammarAST>(GrammarAST.TreeTokenEqualityComparer.Default);
	}
}
	:   ^( BLOCK rewrite_alternative EOB )
		//{System.out.println("atoms="+currentRewriteBlock.rewriteRefs);}
		{
			// copy the element refs in this block to the surrounding block
			if ( enclosingBlock != null )
			{
				foreach ( var item in currentRewriteBlock.rewriteRefsShallow )
					enclosingBlock.rewriteRefsDeep.Add( item );
			}
		}
	;
finally { currentRewriteBlock = enclosingBlock; /* restore old BLOCK ptr */ }

rewrite_alternative
	:	{grammar.BuildAST}? => ^(ALT (rewrite_element+ | EPSILON) EOA)
	|	{grammar.BuildTemplate}? => rewrite_template
	|	ETC {this.blockLevel==1}? // only valid as outermost rewrite
	;

rewrite_element
	:	rewrite_atom
	|	rewrite_ebnf
	|	rewrite_tree
	;

rewrite_ebnf
	:	^( OPTIONAL rewrite_block )
	|	^( CLOSURE rewrite_block )
	|	^( POSITIVE_CLOSURE rewrite_block )
	;

rewrite_tree
	:   ^(TREE_BEGIN rewrite_atom rewrite_element*)
	;

rewrite_atom
@init
{
	if (state.backtracking == 0)
		HandleRewriteAtomStart($start);
}
	:	RULE_REF 
	|	(	^(	TOKEN_REF
				(	ARG_ACTION	{HandleInlineAction($ARG_ACTION);}
				)?
			)
		|	CHAR_LITERAL
		|	STRING_LITERAL
		)
	|	LABEL
	|	ACTION					{HandleInlineAction($ACTION);}
	;

rewrite_template
	:	^(	ALT EPSILON EOA )
	|	^(	TEMPLATE
			(	ID
			|	a=ACTION				{HandleInlineAction($a);}
			)
			^(	ARGLIST
				(	^(ARG ID a=ACTION)	{HandleInlineAction($a);}
				)*
			)
			(	DOUBLE_QUOTE_STRING_LITERAL
			|	DOUBLE_ANGLE_STRING_LITERAL
			)?
		)
	|	a=ACTION						{HandleInlineAction($a);}
	;
