All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.antlr.codegen.templates.CSharp2.CSharp2.stg Maven / Gradle / Ivy

There is a newer version: 8.1.2
Show newest version
/*
 [The "BSD licence"]
 Copyright (c) 2007-2008 Johannes Luber
 Copyright (c) 2005-2007 Kunle Odutola
 Copyright (c) 2005 Terence Parr
 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.
*/
group CSharp2 implements ANTLRCore;
csharpVisibilityMap ::= [
	"private":"private",
	"protected":"protected",
	"public":"public",
	"fragment":"private",
	default:"private"
]

// System.Boolean.ToString() returns "True" and "False", but the proper C# literals are "true" and "false"
// The Java version of Boolean returns "true" and "false", so they map to themselves here.
booleanLiteral ::= [
	"True":"true",
	"False":"false",
	"true":"true",
	"false":"false",
	default:"false"
]

/** The overall file structure of a recognizer; stores methods for rules
 *  and cyclic DFAs plus support code.
 */
outputFile(	LEXER,PARSER,TREE_PARSER, actionScope, actions,
			docComment, recognizer,
			name, tokens, tokenNames, rules, cyclicDFAs,
			bitsets, buildTemplate, buildAST, rewriteMode, profile,
			backtracking, synpreds, memoize, numRules,
			fileName, ANTLRVersion, generatedTimestamp, trace,
			scopes, superClass, literals) ::=
<<
// $ANTLR   

<@debugPreprocessor()>
// The variable 'variable' is assigned but its value is never used.
#pragma warning disable 168, 219
// Unreachable code detected.
#pragma warning disable 162



<@imports>
using System;
using System.Collections.Generic;
using Antlr.Runtime;

using Antlr.Runtime.Tree;
using RewriteRuleITokenStream = Antlr.Runtime.Tree.RewriteRuleTokenStream;

using Stack = System.Collections.Generic.Stack\;
using List = System.Collections.IList;
using ArrayList = System.Collections.Generic.List\;

using Map = System.Collections.IDictionary;
using HashMap = System.Collections.Generic.Dictionary\;

<@end>


namespace 
{





}

>>

lexer(grammar, name, tokens, scopes, rules, numRules, labelType="CommonToken",
      filterMode, superClass={Antlr.Runtime.Lexer}) ::= <<
[System.CodeDom.Compiler.GeneratedCode("ANTLR", "")]
[System.CLSCompliant(false)]
public partial class  : <@superClassName><@end>
{
	=;}; separator="\n">
	}>
	

    // delegates
     ;}; separator="\n">
    // delegators
     ;}; separator="\n">
     gParent;}>

	public ()
	{
		OnCreated();
	}

	public (ICharStream input }> )
		: this(input, new RecognizerSharedState()}>)
	{
	}

	public (ICharStream input, RecognizerSharedState state }>)
		: base(input, state)
	{


		state.ruleMemo = new System.Collections.Generic.Dictionary\[+1];<\n>


		 = new (input, this.state}>, this);}; separator="\n">
		 = ;}; separator="\n">
		;}>

		OnCreated();
	}
	public override string GrammarFileName { get { return ""; } }

	private static readonly bool[] decisionCanBacktrack = new bool[0];


	public override ICharStream CharStream
	{
		get
		{
			return base.CharStream;
		}
		set
		{
			base.CharStream = value;
			 = new (input, state}>, this);}; separator="\n">
			 = ;}; separator="\n">
			;}>
		}
	}



	

 
	protected virtual void OnCreated() {}
	protected virtual void EnterRule(string ruleName, int ruleIndex) {}
	protected virtual void LeaveRule(string ruleName, int ruleIndex) {}

    

	

	#region DFA
	 dfa;}; separator="\n">

	protected override void InitDFAs()
	{
		base.InitDFAs();
		 = new DFA(this, SpecialStateTransition);}; separator="\n">
	}

	 
	#endregion

}
>>

/** A override of Lexer.nextToken() that backtracks over mTokens() looking
 *  for matches.  No error can be generated upon error; just rewind, consume
 *  a token and then try again.  backtracking needs to be set as well.
 *  Make rule memoization happen only at levels above 1 as we start mTokens
 *  at backtracking==1.
 */
filteringNextToken() ::= <<
public override IToken NextToken()
{
	while (true)
	{
		if (input.LA(1) == CharStreamConstants.EndOfFile)
		{
			IToken eof = new CommonToken((ICharStream)input, CharStreamConstants.EndOfFile, TokenChannels.Default, input.Index, input.Index);
			eof.Line = Line;
			eof.CharPositionInLine = CharPositionInLine;
			return eof;
		}
		state.token = null;
		state.channel = TokenChannels.Default;
		state.tokenStartCharIndex = input.Index;
		state.tokenStartCharPositionInLine = input.CharPositionInLine;
		state.tokenStartLine = input.Line;
		state.text = null;
		try
		{
			int m = input.Mark();
			state.backtracking=1;
			state.failed=false;
			mTokens();
			state.backtracking=0;
			
			if (state.failed)
			{
				input.Rewind(m);
				input.Consume();
			}
			else
			{
				Emit();
				return state.token;
			}
		}
		catch (RecognitionException re)
		{
			// shouldn't happen in backtracking mode, but...
			ReportError(re);
			Recover(re);
		}
	}
}

public override void Memoize(IIntStream input, int ruleIndex, int ruleStartIndex)
{
	if (state.backtracking > 1)
		base.Memoize(input, ruleIndex, ruleStartIndex);
}

public override bool AlreadyParsedRule(IIntStream input, int ruleIndex)
{
	if (state.backtracking > 1)
		return base.AlreadyParsedRule(input, ruleIndex);

	return false;
}
>>

actionGate() ::= "(state.backtracking==0)"

filteringActionGate() ::= "(state.backtracking == 1)"

/** How to generate a parser */
genericParser(grammar, name, scopes, tokens, tokenNames, rules, numRules,
              bitsets, inputStreamType, superClass,
              ASTLabelType="object", labelType, members, rewriteElementType,
              filterMode) ::= <<
[System.CodeDom.Compiler.GeneratedCode("ANTLR", "")]
[System.CLSCompliant(false)]
public partial class  : <@superClassName><@end>
{

	internal static readonly string[] tokenNames = new string[] {
		"\", "\", "\", "\", 
	};<\n>

	=;}; separator="\n">

	// delegates
	 ;}; separator="\n">
	// delegators
	 ;}; separator="\n">
	 gParent;}>

	}>
	<@members>
#if ANTLR_DEBUG
	private static readonly bool[] decisionCanBacktrack =
		new bool[]
		{
			false, // invalid decision
			}; wrap="\n", separator=", ">
		};
#else
	private static readonly bool[] decisionCanBacktrack = new bool[0];
#endif

public (  input }> )
	: this( input, new RecognizerSharedState()}> )
{
}
public ( input, RecognizerSharedState state }>)
	: base(input, state)
{
	
	 = new (input, state}>, this);}; separator="\n">
	 = .;}; separator="\n">
	;}>

	OnCreated();
}
	<@end>

	public override string[] TokenNames { get { return .tokenNames; } }
	public override string GrammarFileName { get { return ""; } }

	


 	protected virtual void OnCreated() {}
	protected virtual void EnterRule(string ruleName, int ruleIndex) {}
	protected virtual void LeaveRule(string ruleName, int ruleIndex) {}

    


	#region Delegated rules
 () \{ return .(}; separator=", ">); \}}; separator="\n">
	#endregion Delegated rules<\n>


	


	#region DFA
	 dfa;}; separator="\n">

	protected override void InitDFAs()
	{
		base.InitDFAs();
		 = new DFA( this, SpecialStateTransition );}; separator="\n">
	}

	
	#endregion DFA<\n>



	#region Follow sets
	private static class Follow
	{
		_in_},
							words64=it.bits)>
	}
	#endregion Follow sets<\n>

}
>>

parserCtorBody() ::= <<


this.state.ruleMemo = new System.Collections.Generic.Dictionary\[+1];<\n>


 = ;}; separator="\n">
>>

parser(grammar, name, scopes, tokens, tokenNames, rules, numRules, bitsets,
       ASTLabelType="object", superClass={Antlr.Runtime.Parser}, labelType="IToken",
       members={}) ::= <<

>>

/** How to generate a tree parser; same as parser except the input
 *  stream is a different type.
 */
treeParser(grammar, name, scopes, tokens, tokenNames, globalAction, rules,
           numRules, bitsets, labelType={}, ASTLabelType="object",
           superClass={Antlr.Runtime.Tree.TreeRewriter\<\>TreeFilterTreeParser},
           members={},
           filterMode) ::= <<

>>

/** A simpler version of a rule template that is specific to the imaginary
 *  rules created for syntactic predicates.  As they never have return values
 *  nor parameters etc..., just give simplest possible method.  Don't do
 *  any of the normal memoization stuff in here either; it's a waste.
 *  As predicates cannot be inlined into the invoking rule, they need to
 *  be in a rule by themselves.
 */
synpredRule(ruleName, ruleDescriptor, block, description, nakedBlock) ::=
<<
protected virtual void Enter__fragment() {}
protected virtual void Leave__fragment() {}

// $ANTLR start 
public void _fragment()
{
	

	Enter__fragment();
	EnterRule("_fragment", );
	TraceIn("_fragment", );
	try
	{
		
	}
	finally
	{
		TraceOut("_fragment", );
		LeaveRule("_fragment", );
		Leave__fragment();
	}

	

}
// $ANTLR end 
>>

insertLexerSynpreds(synpreds) ::= <<

>>

insertSynpreds(synpreds) ::= <<

#region Synpreds
private bool EvaluatePredicate(System.Action fragment)
{
	bool success = false;
	state.backtracking++;
	<@start()>
	try { DebugBeginBacktrack(state.backtracking);
	int start = input.Mark();
	try
	{
		fragment();
	}
	catch ( RecognitionException re )
	{
		System.Console.Error.WriteLine("impossible: "+re);
	}
	success = !state.failed;
	input.Rewind(start);
	} finally { DebugEndBacktrack(state.backtracking, success); }
	<@stop()>
	state.backtracking--;
	state.failed=false;
	return success;
}
#endregion Synpreds<\n>

>>

ruleMemoization(name) ::= <<

if (state.backtracking > 0 && AlreadyParsedRule(input, )) {  }

>>

/** How to test for failure and return from rule */
checkRuleBacktrackFailure() ::= <<
if (state.failed) 
>>

/** This rule has failed, exit indicating failure during backtrack */
ruleBacktrackFailure() ::= <<
if (state.backtracking>0) {state.failed=true; }
>>

/** How to generate code for a rule.  This includes any return type
 *  data aggregates required for multiple return values.
 */
rule(ruleName,ruleDescriptor,block,emptyRule,description,exceptions,finally,memoize) ::= <<



protected virtual void Enter_() {}
protected virtual void Leave_() {}

// $ANTLR start ""
// :
[GrammarRule("")]
  ()
{

	Enter_();
	EnterRule("", );
	TraceIn("", );

    
    
    
    
	try { DebugEnterRule(GrammarFileName, "");
	DebugLocation(, );
	<@preamble()>
	try
	{
		
		
		
		<(ruleDescriptor.actions.after):execAction()>
	}

	<\n>}>



	

	catch (RecognitionException re)
	{
		ReportError(re);
		Recover(input,re);
	<@setErrorReturnValue()>
	}<\n>



	finally
	{
    
		TraceOut("", );
		LeaveRule("", );
		Leave_();
	
        
        
        
    }
 	DebugLocation(, );
	} finally { DebugExitRule(GrammarFileName, ""); }
	<@postamble()>
	<\n>
}
// $ANTLR end ""
>>

catch(decl,action) ::= <<
catch ()
{
	
}
>>

ruleDeclarations() ::= <<

 retval = new ();
retval.Start = ()input.LT(1);<\n>

  = ;
}>


int _StartIndex = input.Index;

>>

ruleScopeSetUp() ::= <<
_stack.Push(new _scope());_scopeInit(_stack.Peek());}; separator="\n">
_stack.Push(new _scope());_scopeInit(_stack.Peek());}; separator="\n">
>>

ruleScopeCleanUp() ::= <<
_scopeAfter(_stack.Peek());_stack.Pop();}; separator="\n">
_scopeAfter(_stack.Peek());_stack.Pop();}; separator="\n">
>>

ruleLabelDefs() ::= <<
<[ruleDescriptor.tokenLabels,ruleDescriptor.tokenListLabels,ruleDescriptor.wildcardTreeLabels,ruleDescriptor.wildcardTreeListLabels]
    :{ =null;}; separator="\n"
>
<[ruleDescriptor.tokenListLabels,ruleDescriptor.ruleListLabels,ruleDescriptor.wildcardTreeListLabels]
    :{List list_=null;}; separator="\n"
>


>>

lexerRuleLabelDefs() ::= <<
<[ruleDescriptor.tokenLabels,
  ruleDescriptor.tokenListLabels,
  ruleDescriptor.ruleLabels]
    :{ =null;}; separator="\n"
>
;}; separator="\n">
<[ruleDescriptor.tokenListLabels,
  ruleDescriptor.ruleListLabels]
    :{List list_=null;}; separator="\n"
>
>>

returnFromRule() ::= <<
return


 

 retval



;
>>

ruleCleanUp() ::= <<


retval.Stop = ()input.LT(-1);<\n>


>>

memoize() ::= <<


if (state.backtracking > 0) { Memoize(input, , _StartIndex); }


>>

/** How to generate a rule in the lexer; naked blocks are used for
 *  fragment rules.
 */
lexerRule(ruleName,nakedBlock,ruleDescriptor,block,memoize) ::= <<
protected virtual void Enter_() {}
protected virtual void Leave_() {}

// $ANTLR start ""
[GrammarRule("")]
 void m()
{

	Enter_();
	EnterRule("", );
	TraceIn("", );

    
    
		try
		{

		
		
		
		<\n>

		int _type = ;
		int _channel = DefaultTokenChannel;
		
		
		
		
		
		state.type = _type;
		state.channel = _channel;
		<(ruleDescriptor.actions.after):execAction()>

	}
	finally
	{
    
		TraceOut("", );
		LeaveRule("", );
		Leave_();
	
        
        
    }
}
// $ANTLR end ""
>>

/** How to generate code for the implicitly-defined lexer grammar rule
 *  that chooses between lexer rules.
 */
tokensRule(ruleName,nakedBlock,args,block,ruleDescriptor) ::= <<
public override void mTokens()
{
	<\n>
}
>>

// S U B R U L E S

/** A (...) subrule with multiple alternatives */
block(alts,decls,decision,enclosingBlockLevel,blockLevel,decisionNumber,maxK,maxAlt,description) ::= <<
// :
int alt=;

<@predecision()>
try { DebugEnterSubRule();
try { DebugEnterDecision(, decisionCanBacktrack[]);

} finally { DebugExitDecision(); }
<@postdecision()>
<@prebranch()>
switch (alt)
{

}
} finally { DebugExitSubRule(); }
<@postbranch()>
>>

/** A rule block with multiple alternatives */
ruleBlock(alts,decls,decision,enclosingBlockLevel,blockLevel,decisionNumber,maxK,maxAlt,description) ::= <<
// :
int alt=;

<@predecision()>
try { DebugEnterDecision(, decisionCanBacktrack[]);

} finally { DebugExitDecision(); }
<@postdecision()>
switch (alt)
{

}
>>

ruleBlockSingleAlt(alts,decls,decision,enclosingBlockLevel,blockLevel,decisionNumber,description) ::= <<
// :

<@prealt()>
DebugEnterAlt(1);

<@postalt()>
>>

/** A special case of a (...) subrule with a single alternative */
blockSingleAlt(alts,decls,decision,enclosingBlockLevel,blockLevel,decisionNumber,description) ::= <<
// :

<@prealt()>
DebugEnterAlt(1);

<@postalt()>
>>

/** A (..)+ block with 1 or more alternatives */
positiveClosureBlock(alts,decls,decision,enclosingBlockLevel,blockLevel,decisionNumber,maxK,maxAlt,description) ::= <<
// :
int cnt=0;

<@preloop()>
try { DebugEnterSubRule();
while (true)
{
	int alt=;
	<@predecision()>
	try { DebugEnterDecision(, decisionCanBacktrack[]);
	
	} finally { DebugExitDecision(); }
	<@postdecision()>
	switch (alt)
	{
	
	default:
		if (cnt >= 1)
			goto loop;

		
		EarlyExitException eee = new EarlyExitException( , input );
		DebugRecognitionException(eee);
		<@earlyExitException()>
		throw eee;
	}
	cnt++;
}
loop:
	;

} finally { DebugExitSubRule(); }
<@postloop()>
>>

positiveClosureBlockSingleAlt ::= positiveClosureBlock

/** A (..)* block with 1 or more alternatives */
closureBlock(alts,decls,decision,enclosingBlockLevel,blockLevel,decisionNumber,maxK,maxAlt,description) ::= <<
// :

<@preloop()>
try { DebugEnterSubRule();
while (true)
{
	int alt=;
	<@predecision()>
	try { DebugEnterDecision(, decisionCanBacktrack[]);
	
	} finally { DebugExitDecision(); }
	<@postdecision()>
	switch ( alt )
	{
	
	default:
		goto loop;
	}
}

loop:
	;

} finally { DebugExitSubRule(); }
<@postloop()>
>>

closureBlockSingleAlt ::= closureBlock

/** Optional blocks (x)? are translated to (x|) by before code generation
 *  so we can just use the normal block template
 */
optionalBlock ::= block

optionalBlockSingleAlt ::= block

/** A case in a switch that jumps to an alternative given the alternative
 *  number.  A DFA predicts the alternative and then a simple switch
 *  does the jump to the code that actually matches that alternative.
 */
altSwitchCase() ::= <<
case :
	<@prealt()>
	DebugEnterAlt();
	
	break;<\n>
>>

/** An alternative is just a list of elements; at outermost level */
alt(elements,altNum,description,autoAST,outerAlt,treeLevel,rew) ::= <<
// :
{
<@declarations()>


<@cleanup()>
}
>>

/** What to emit when there is no rewrite.  For auto build
 *  mode, does nothing.
 */
noRewrite(rewriteBlockLevel, treeLevel) ::= ""

// E L E M E N T S

/** Dump the elements one per line */
element() ::= <<
<@prematch()>
DebugLocation(, );
<\n>
>>

/** match a token optionally with a label in front */
tokenRef(token,label,elementIndex,hetero) ::= <<