/*
 [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.
*/
grammar Group;

options
{
	language=CSharp3;
}

tokens
{
KWGROUP = 'group';
KWIMPLEMENTS = 'implements';
KWDEFAULT = 'default';
}

@lexer::namespace {Antlr3.ST.Language}
@parser::namespace {Antlr3.ST.Language}

public
group[StringTemplateGroup g]
@init
{
this._group = g;
}
	:	'group' name=ID {g.Name = $name.text;}
		( COLON s=ID {g.SetSuperGroup($s.text);} )?
		(	'implements' i=ID {g.ImplementInterface($i.text);}
			(COMMA i2=ID {g.ImplementInterface($i2.text);} )*
		)?
		SEMI
		( template[g] | mapdef[g] )+
		EOF
	;

template[StringTemplateGroup g]
@init
{
	StringTemplate st = null;
	string templateName=null;
	int line = input.LT(1).Line;
}
	:	(	AT scope2=ID DOT region=ID
			{
				templateName = $g.GetMangledRegionName($scope2.text,$region.text);
				if ( $g.IsDefinedInThisGroup(templateName) )
				{
					$g.Error("group "+$g.Name+" line "+line+": redefinition of template region: @"+
						$scope2.text+"."+$region.text);
					st = new StringTemplate(); // create bogus template to fill in
				}
				else
				{
					bool err = false;
					// @template.region() ::= "..."
					StringTemplate scopeST = $g.LookupTemplate($scope2.text);
					if ( scopeST == null )
					{
						$g.Error("group "+$g.Name+" line "+line+": reference to region within undefined template: "+
							$scope2.text);
						err=true;
					}
					else if ( !scopeST.ContainsRegionName($region.text) )
					{
						$g.Error("group "+$g.Name+" line "+line+": template "+$scope2.text+" has no region called "+
							$region.text);
						err=true;
					}
					if ( err )
					{
						st = new StringTemplate();
					}
					else
					{
						st = $g.DefineRegionTemplate($scope2.text,
													$region.text,
													null,
													RegionType.Explicit);
					}
				}
			}
		|	name=ID {templateName = $name.text;}
			{
				if ( $g.IsDefinedInThisGroup(templateName) )
				{
					$g.Error("redefinition of template: "+templateName);
					st = new StringTemplate(); // create bogus template to fill in
				}
				else
				{
					st = $g.DefineTemplate(templateName, null);
				}
			}
		)
		{if ( st!=null ) {st.GroupFileLine = line;}}
		LPAREN
			(args[st]|{st.DefineEmptyFormalArgumentList();})
		RPAREN
		DEFINED_TO_BE
		(	t=STRING     {st.Template = $t.text;}
		|	bt=BIGSTRING {st.Template = $bt.text;}
		)

	|   alias=ID DEFINED_TO_BE target=ID
		{g.DefineTemplateAlias($alias.text, $target.text);}
	;

args[StringTemplate st]
	:	arg[$st] ( COMMA arg[$st] )*
	;

arg[StringTemplate st]
@init
{
	StringTemplate defaultValue = null;
}
	:	name=ID
		(	ASSIGN s=STRING
			{
				defaultValue=new StringTemplate("\$_val_\$");
				defaultValue.SetAttribute("_val_", $s.text);
				defaultValue.DefineFormalArgument("_val_");
				defaultValue.Name = "<"+$st.Name+"'s arg "+$name.text+" default value subtemplate>";
			}
		|	ASSIGN bs=ANONYMOUS_TEMPLATE
			{
				defaultValue=new StringTemplate($st.Group, $bs.text);
				defaultValue.Name = "<"+$st.Name+"'s arg "+$name.text+" default value subtemplate>";
			}
		)?
		{$st.DefineFormalArgument($name.text, defaultValue);}
	;

mapdef[StringTemplateGroup g]
	:	name=ID
		DEFINED_TO_BE m=map
		{
			if ( $g.GetMap($name.text)!=null )
			{
				$g.Error("redefinition of map: "+$name.text);
			}
			else if ( $g.IsDefinedInThisGroup($name.text) )
			{
				$g.Error("redefinition of template as map: "+$name.text);
			}
			else
			{
				$g.DefineMap($name.text, $m.mapping);
			}
		}
	;

map returns [IDictionary<string, StringTemplate> mapping = new Dictionary<string, StringTemplate>()]
	:   LBRACK mapPairs[mapping] RBRACK
	;

mapPairs [IDictionary<string, StringTemplate> mapping]
	:	keyValuePair[mapping] (COMMA keyValuePair[mapping])*
		(COMMA defaultValuePair[mapping])?
	|	defaultValuePair[mapping] 
	;

defaultValuePair[IDictionary<string, StringTemplate> mapping]
	:	'default' COLON v=keyValue
		{$mapping[ASTExpr.DefaultMapValueName] = $v.value;}
	;

keyValuePair[IDictionary<string, StringTemplate> mapping]
	:	key=STRING COLON v=keyValue {$mapping[$key.text] = $v.value;}
	;

keyValue returns [StringTemplate value]
	:	s1=BIGSTRING	{$value = new StringTemplate(_group,$s1.text);}
	|	s2=STRING		{$value = new StringTemplate(_group,$s2.text);}
	|	k=ID			{$k.text == "key"}?
						{$value = ASTExpr.MapKeyValue;}
	|					//{$value = null;}
	;

//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
// LEXER

ID
	:	('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'-'|'_')*
	;

STRING
@init
{
	System.Text.StringBuilder builder = new System.Text.StringBuilder();
}
	:	'"'
		(	'\\'
			(	'"'		{builder.Append('"');}
			|	ch=~'"'	{builder.Append("\\" + (char)$ch);}
			)
		|	ch=~('\\'|'"') {builder.Append((char)$ch);}
		)*
		'"'
		{
			Text = builder.ToString();
		}
	;

BIGSTRING
	:	'<<' ('\\>' | '\\' ~'>' | '>' ~'>' | ~('\\'|'>'))* '>>'
		{
			System.Text.StringBuilder builder = new System.Text.StringBuilder( input.Substring( state.tokenStartCharIndex + 2, CharIndex - 3 - state.tokenStartCharIndex - 2 + 1 ) );
			$text = ProcessBigString( builder );
		}
	;

ANONYMOUS_TEMPLATE
	:	'{'
		(	'\\}'
		|	'\\' ~'}'
		|	~('\\' | '}')
		)*
		'}'
		{
			System.Text.StringBuilder builder = new System.Text.StringBuilder( input.Substring( state.tokenStartCharIndex + 1, CharIndex - 2 - state.tokenStartCharIndex - 1 + 1 ) );
			$text = ProcessAnonymousTemplate( builder );
		}
	;

AT	:	'@' ;
LPAREN: '(' ;
RPAREN: ')' ;
LBRACK: '[' ;
RBRACK: ']' ;
COMMA:  ',' ;
DOT:  '.' ;
DEFINED_TO_BE:  '::=';
SEMI:   ';' ;
COLON:  ':' ;
STAR:   '*' ;
PLUS:   '+' ;
ASSIGN:   '=' ;
OPTIONAL : '?' ;

// Single-line comments
SL_COMMENT
	:	'//'
		(~('\n'|'\r'))* (('\r')? '\n')?
		{ $channel = Hidden; }
	;

// multiple-line comments
ML_COMMENT
	:	'/*' .* '*/'
		{ $channel = Hidden; }
	;

// Whitespace -- ignored
WS  :   (   ' '
        |   '\t'
        |   '\f'
        |   ('\r')? '\n'
        )+
        { $channel = Hidden; }
    ;
