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

org.antlr.v4.tool.templates.codegen.JavaScript.JavaScript.stg Maven / Gradle / Ivy

There is a newer version: 2.12.15
Show newest version
/*
 * [The "BSD license"]
 *  Copyright (c) 2012-2016 Terence Parr
 *  Copyright (c) 2012-2016 Sam Harwell
 *  Copyright (c) 2014 Eric Vergnaud
 *  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.
 */

/** ANTLR tool checks output templates are compatible with tool code generation.
 *  For now, a simple string match used on x.y of x.y.z scheme.
 *  Must match Tool.VERSION during load to templates.
 *
 *  REQUIRED.
 */

javascriptTypeInitMap ::= [
	"bool":"false",
	"int":"0",
	"float":"0.0",
	"str":"",
	default:"{}" // anything other than a primitive type is an object
]

// args must be , 

ParserFile(file, parser, namedActions, contextSuperClass) ::= <<

var antlr4 = require('antlr4/index');

var Listener = require('./Listener').Listener;


var Visitor = require('./Visitor').Visitor;




>>

ListenerFile(file, header, namedActions) ::= <<

var antlr4 = require('antlr4/index');

// This class defines a complete listener for a parse tree produced by .
function Listener() {
	antlr4.tree.ParseTreeListener.call(this);
	return this;
}

Listener.prototype = Object.create(antlr4.tree.ParseTreeListener.prototype);
Listener.prototype.constructor = Listener;

#.
Listener.prototype.enter = function(ctx) {
\};

// Exit a parse tree produced by #.
Listener.prototype.exit = function(ctx) {
\};

}; separator="\n">

exports.Listener = Listener;
>>


VisitorFile(file, header, namedActions) ::= <<

var antlr4 = require('antlr4/index');

// This class defines a complete generic visitor for a parse tree produced by .

function Visitor() {
	antlr4.tree.ParseTreeVisitor.call(this);
	return this;
}

Visitor.prototype = Object.create(antlr4.tree.ParseTreeVisitor.prototype);
Visitor.prototype.constructor = Visitor;

#.
Visitor.prototype.visit = function(ctx) {
  return this.visitChildren(ctx);
\};

}; separator="\n">

exports.Visitor = Visitor;
>>


fileHeader(grammarFileName, ANTLRVersion) ::= <<
// Generated from  by ANTLR 
// jshint ignore: start
>>

Parser(parser, funcs, atn, sempredFuncs, superClass) ::= <<

var  = require('./').;


var grammarFileName = "";



var atn = new antlr4.atn.ATNDeserializer().deserialize(serializedATN);

var decisionsToDFA = atn.decisionToState.map( function(ds, index) { return new antlr4.dfa.DFA(ds, index); });

var sharedContextCache = new antlr4.PredictionContextCache();

var literalNames = [ }; null="null", separator=", ", wrap, anchor> ];

var symbolicNames = [ }; null="null", separator=", ", wrap, anchor> ];

var ruleNames =  [ "}; separator=", ", wrap, anchor> ];

function  (input) {
	.call(this, input);
    this._interp = new antlr4.atn.ParserATNSimulator(this, atn, decisionsToDFA, sharedContextCache);
    this.ruleNames = ruleNames;
    this.literalNames = literalNames;
    this.symbolicNames = symbolicNames;
	
    return this;
}

.prototype = Object.create(.prototype);
.prototype.constructor = ;

Object.defineProperty(.prototype, "atn", {
	get : function() {
		return atn;
	}
});

.EOF = antlr4.Token.EOF;

. = ;}; separator="\n", wrap, anchor>


.RULE_ = ;}; separator="\n", wrap, anchor>




.prototype.sempred = function(localctx, ruleIndex, predIndex) {
	switch(ruleIndex) {
	:
		return this._sempred(localctx, predIndex);}; separator="\n">
    default:
        throw "No predicate with index:" + ruleIndex;
   }
};




exports. = ;

>>

dumpActions(recog, argFuncs, actionFuncs, sempredFuncs) ::= <<

.prototype.action = function(localctx, ruleIndex, actionIndex) {
	switch (ruleIndex) {
	:
	this._action(localctx, actionIndex);
	break;}; separator="\n">
	default:
		throw "No registered action for:" + ruleIndex;
	}
};




.prototype.sempred = function(localctx, ruleIndex, predIndex) {
	switch (ruleIndex) {
		:
	return this._sempred(localctx, predIndex);}; separator="\n">
    	default:
    		throw "No registered predicate for:" + ruleIndex;
    }
};



>>


/* This generates a private method since the actionIndex is generated, making an
 * overriding implementation impossible to maintain.
 */
RuleActionFunction(r, actions) ::= <<

.prototype._action = function(localctx , actionIndex) {
	switch (actionIndex) {
	:
	
	break;}; separator="\n">
	default:
		throw "No registered action for:" + actionIndex;
	}
};
>>

/* This generates a private method since the predIndex is generated, making an
 * overriding implementation impossible to maintain.
 */
RuleSempredFunction(r, actions) ::= <<
.prototype._sempred = function(localctx, predIndex) {
	switch(predIndex) {
		:
	return ;}; separator="\n">
		default:
			throw "No predicate with index:" + predIndex;
	}
};

>>

RuleFunction(currentRule,args,code,locals,ruleCtx,altLabelCtxs,namedActions,finallyAction,postamble,exceptions) ::= <<



}; separator="\n">


. = ;

.prototype. = function(}; separator=", ">) {

    var localctx = new (this, this._ctx, this.state}>);
    this.enterRule(localctx, , .RULE_);
    
    
    try {
        
        
        
    
    
    
    } catch (re) {
    	if(re instanceof antlr4.error.RecognitionException) {
	        localctx.exception = re;
	        this._errHandler.reportError(this, re);
	        this._errHandler.recover(this, re);
	    } else {
	    	throw re;
	    }
    } finally {
        
        this.exitRule();
    }
    return localctx;
};

>>

LeftRecursiveRuleFunction(currentRule,args,code,locals,ruleCtx,altLabelCtxs,
	namedActions,finallyAction,postamble) ::=
<<


}; separator="\n">

.prototype. = function(_p, }>) {
	if(_p===undefined) {
	    _p = 0;
	}
    var _parentctx = this._ctx;
    var _parentState = this.state;
    var localctx = new (this, this._ctx, _parentState}>);
    var _prevctx = localctx;
    var _startState = ;
    this.enterRecursionRule(localctx, , .RULE_, _p);
    
    
    try {
        
        
        
    } catch( error) {
        if(error instanceof antlr4.error.RecognitionException) {
	        localctx.exception = error;
	        this._errHandler.reportError(this, error);
	        this._errHandler.recover(this, error);
	    } else {
	    	throw error;
	    }
    } finally {
        
        this.unrollRecursionContexts(_parentctx)
    }
    return localctx;
};

>>

CodeBlockForOuterMostAlt(currentOuterMostAltCodeBlock, locals, preamble, ops) ::= <<
localctx = new Context(this, localctx);
this.enterOuterAlt(localctx, );

>>

CodeBlockForAlt(currentAltCodeBlock, locals, preamble, ops) ::= <<



>>

LL1AltBlock(choice, preamble, alts, error) ::= <<
this.state = ;
this._errHandler.sync(this);
 = this._input.LT(1);

switch(this._input.LA(1)) {

    
    break;}; separator="\n">
default:
    
}
>>

LL1OptionalBlock(choice, alts, error) ::= <<
this.state = ;
this._errHandler.sync(this);
switch (this._input.LA(1)) {

	
	break;}; separator="\n">
default:
	break;
}
>>

LL1OptionalBlockSingleAlt(choice, expr, alts, preamble, error, followExpr) ::= <<
this.state = ;
this._errHandler.sync(this);

if() {
    
}
) ) !>
>>

LL1StarBlockSingleAlt(choice, loopExpr, alts, preamble, iteration) ::= <<
this.state = ;
this._errHandler.sync(this);

while() {
    
    this.state = ;
    this._errHandler.sync(this);
    
}
>>

LL1PlusBlockSingleAlt(choice, loopExpr, alts, preamble, iteration) ::= <<
this.state = ; 
this._errHandler.sync(this);

do {
    
    this.state = ; 
    this._errHandler.sync(this);
    
} while();
>>

// LL(*) stuff

AltBlock(choice, preamble, alts, error) ::= <<
this.state = ;
this._errHandler.sync(this);
 = _input.LT(1)

var la_ = this._interp.adaptivePredict(this._input,,this._ctx);
switch(la_) {
:
    
    break;
}; separator="\n">
}
>>

OptionalBlock(choice, alts, error) ::= <<
this.state = ;
this._errHandler.sync(this);
var la_ = this._interp.adaptivePredict(this._input,,this._ctx);
+1) {
    
}; separator="\n} else ">
}
>>

StarBlock(choice, alts, sync, iteration) ::= <<
this.state = ;
this._errHandler.sync(this);
var _alt = this._interp.adaptivePredict(this._input,,this._ctx)
while(_alt!= && _alt!=antlr4.atn.ATN.INVALID_ALT_NUMBER) {
    if(_alt===1+1) {
        
         
    }
    this.state = ;
    this._errHandler.sync(this);
    _alt = this._interp.adaptivePredict(this._input,,this._ctx);
}

>>

PlusBlock(choice, alts, error) ::= <<
this.state = ; 
this._errHandler.sync(this);
var _alt = 1+1;
do {
	switch (_alt) {
	+1:
	
	break;}; separator="\n">
	default:
		
	}
	this.state = ; 
	this._errHandler.sync(this);
	_alt = this._interp.adaptivePredict(this._input,, this._ctx);
} while ( _alt!= && _alt!=antlr4.atn.ATN.INVALID_ALT_NUMBER );
>>

Sync(s) ::= "sync()"

ThrowNoViableAlt(t) ::= "throw new antlr4.error.NoViableAltException(this);"

TestSetInline(s) ::= <<
}; separator=" || ">
>>

// Javascript language spec - shift operators are 32 bits long max
testShiftInRange(shiftAmount) ::= <<
(() & ~0x1f) == 0
>>

// produces smaller bytecode only when bits.ttypes contains more than two items
bitsetBitfieldComparison(s, bits) ::= <%
(})> && ((1 \<\< ) & ()}; separator=" | ">)) !== 0)
%>

isZero ::= [
"0":true,
default:false
]

offsetShiftVar(shiftAmount, offset) ::= <%
( - )
%>

offsetShiftType(shiftAmount, offset) ::= <%
(. - ).
%>

// produces more efficient bytecode when bits.ttypes contains at most two items
bitsetInlineComparison(s, bits) ::= <%
===.}; separator=" || ">
%>

cases(ttypes) ::= <<
.:}; separator="\n">
>>

InvokeRule(r, argExprsChunks) ::= <<
this.state = ;
 = }>this.(,);
>>

MatchToken(m) ::= <<
this.state = ;
 = }>this.match(.);
>>

MatchSet(m, expr, capture) ::= ""

MatchNotSet(m, expr, capture) ::= ""

CommonSetStuff(m, expr, capture, invert) ::= <<
this.state = ;
 = }>this._input.LT(1);

if(\<=0 || )if(!()) {
     = }>this._errHandler.recoverInline(this);
}
else {
	this._errHandler.reportMatch(this);
    this.consume();
}
>>

Wildcard(w) ::= <<
this.state = ;
 = }>this.matchWildcard();
>>

// ACTION STUFF

Action(a, foo, chunks) ::= ""

ArgAction(a, chunks) ::= ""

SemPred(p, chunks, failChunks) ::= <<
this.state = ;
if (!( )) {
    throw new antlr4.error.FailedPredicateException(this, , , );
}
>>

ExceptionClause(e, catchArg, catchAction) ::= <<
catch () {
	
}
>>

// lexer actions are not associated with model objects

LexerSkipCommand()  ::= "this.skip()"
LexerMoreCommand()  ::= "this.more()"
LexerPopModeCommand() ::= "this.popMode()"
LexerTypeCommand(arg, grammar)      ::= "this._type = "
LexerChannelCommand(arg, grammar)   ::= "this._channel = "
LexerModeCommand(arg, grammar)      ::= "this._mode = "
LexerPushModeCommand(arg, grammar)  ::= "this.pushMode()"

ActionText(t) ::= ""
ActionTemplate(t) ::= ""
ArgRef(a) ::= "localctx."
LocalRef(a) ::= "localctx."
RetValueRef(a) ::= "localctx."
QRetValueRef(a) ::= ".."
/** How to translate $tokenLabel */
TokenRef(t) ::= "."
LabelRef(t) ::= "."
ListLabelRef(t) ::= "."
SetAttr(s,rhsChunks) ::= ". = "

TokenLabelType() ::= ""
InputSymbolType() ::= ""

TokenPropertyRef_text(t) ::= "(.===null ? null : ..text)"
TokenPropertyRef_type(t) ::= "(. === null ? 0 : ..type)"
TokenPropertyRef_line(t) ::= "(. === null ? 0 : ..line)"
TokenPropertyRef_pos(t) ::= "(. === null ? 0 : ..column)"
TokenPropertyRef_channel(t) ::= "(. === null ? 0 : ..channel)"
TokenPropertyRef_index(t) ::= "(. === null ? 0 : ..tokenIndex)"
TokenPropertyRef_int(t) ::= "(. === null ? 0 : parseInt(..text))"

RulePropertyRef_start(r) ::= "(.===null ? null : ..start)"
RulePropertyRef_stop(r)	 ::= "(.===null ? null : ..stop)"
RulePropertyRef_text(r)	 ::= "(.===null ? null : this._input.getText(new antlr4.Interval(..start,..stop)))"
RulePropertyRef_ctx(r)	 ::= "."
RulePropertyRef_parser(r)	 ::= "this"

ThisRulePropertyRef_start(r) ::= "localctx.start"
ThisRulePropertyRef_stop(r)	 ::= "localctx.stop"
ThisRulePropertyRef_text(r)	 ::= "this._input.getText(new antlr4.Interval(localctx.start, this._input.LT(-1)))"
ThisRulePropertyRef_ctx(r)	 ::= "localctx"
ThisRulePropertyRef_parser(r)	 ::= "this"

NonLocalAttrRef(s)		 	 ::= "getInvokingContext()."
SetNonLocalAttr(s, rhsChunks)  ::= "getInvokingContext(). = "

AddToLabelList(a) ::= "..push();"

TokenDecl(t) ::= "this. = null; // "
TokenTypeDecl(t) ::= "var  = 0; //  type"
TokenListDecl(t) ::= "this. = []; // of s"
RuleContextDecl(r) ::= "this. = null; // "
RuleContextListDecl(rdecl) ::= "this. = []; // of s"

ContextTokenGetterDecl(t)      ::= <<
 = function() {
    return this.getToken(., 0);
};
>>

// should never be called
ContextTokenListGetterDecl(t)  ::= <<
def _list(self):
    return self.getTokens(.)
>>

ContextTokenListIndexedGetterDecl(t)  ::= <<
 = function(i) {
	if(i===undefined) {
		i = null;
	}
    if(i===null) {
        return this.getTokens(.);
    } else {
        return this.getToken(., i);
    }
};

>>

ContextRuleGetterDecl(r)       ::= <<
 = function() {
    return this.getTypedRuleContext(,0);
};
>>

// should never be called
ContextRuleListGetterDecl(r)   ::= <<
def _list(self):
    return self.getTypedRuleContexts(.)

>>

ContextRuleListIndexedGetterDecl(r)   ::= <<
 = function(i) {
    if(i===undefined) {
        i = null;
    }
    if(i===null) {
        return this.getTypedRuleContexts();
    } else {
        return this.getTypedRuleContext(,i);
    }
};
>>

LexerRuleContext() ::= "RuleContext"

/** The rule context name is the rule followed by a suffix; e.g.,
 *	r becomes rContext.
 */
RuleContextNameSuffix() ::= "Context"

ImplicitTokenLabel(tokenName) ::= "_"
ImplicitRuleLabel(ruleName)	  ::= "_"
ImplicitSetLabel(id)		  ::= "_tset"
ListLabelName(label)		  ::= "