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

org.antlr.v4.tool.templates.codegen.Swift.Swift.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) 2015 Janyou
 *  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.
 */

SwiftTypeInitMap ::= [
	"Int":"0",
	"Int64":"0",
	"Float":"0.0",
	"Double":"0.0",
	"Bool":"false",
	default:"nil" // anything other than a primitive type is an object
]
SwiftTypeMap ::= [
	"int":"Int",
	"float":"Float",
	"long":"Int64",
	"double":"Double",
	"bool":"Bool",
	"boolean":"Bool",
	default : key
]
// args must be , 

accessLevelOpenOK(obj) ::= ""
accessLevelNotOpen(obj) ::= ""

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


;!>


import Antlr4


>>

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


;!>

import Antlr4 /** * This interface defines a complete listener for a parse tree produced by * {@link }. */ protocol Listener: ParseTreeListener { * Enter a parse tree produced by the {@code \} * labeled alternative in {@link #\}. * Enter a parse tree produced by {@link #\}. - Parameters: - ctx: the parse tree */ func enter(_ ctx: .Context) /** * Exit a parse tree produced by the {@code \} * labeled alternative in {@link #\}. * Exit a parse tree produced by {@link #\}. - Parameters: - ctx: the parse tree */ func exit(_ ctx: .Context)}; separator="\n"> } >> BaseListenerFile(file, header, namedActions) ::= << ;!>
import Antlr4 /** * This class provides an empty implementation of {@link Listener}, * which can be extended to create a listener which only needs to handle a subset * of the available methods. */ class BaseListener: Listener { init() { \} The default implementation does nothing.\

*/ func enter(_ ctx: .Context) { \} /** * {@inheritDoc\} * * \

The default implementation does nothing.\

*/ func exit(_ ctx: .Context) { \}}; separator="\n"> /** * {@inheritDoc\} * * \

The default implementation does nothing.\

*/ func enterEveryRule(_ ctx: ParserRuleContext) { } /** * {@inheritDoc\} * * \

The default implementation does nothing.\

*/ func exitEveryRule(_ ctx: ParserRuleContext) { } /** * {@inheritDoc\} * * \

The default implementation does nothing.\

*/ func visitTerminal(_ node: TerminalNode) { } /** * {@inheritDoc\} * * \

The default implementation does nothing.\

*/ func visitErrorNode(_ node: ErrorNode) { } } >> VisitorFile(file, header, namedActions) ::= << ;!>
import Antlr4 /** * This interface defines a complete generic visitor for a parse tree produced * by {@link }. * * @param \ The return type of the visit operation. Use {@link Void} for * operations with no return type. */ class Visitor\: ParseTreeVisitor\ { * Visit a parse tree produced by the {@code \} * labeled alternative in {@link #\}. * Visit a parse tree produced by {@link #\}. - Parameters: - ctx: the parse tree - returns: the visitor result */ func visit(_ ctx: .Context) -> T { fatalError(#function + " must be overridden") \} }; separator="\n"> } >> BaseVisitorFile(file, header, namedActions) ::= << ;!>
import Antlr4 /** * This class provides an empty implementation of {@link Visitor}, * which can be extended to create a visitor which only needs to handle a subset * of the available methods. * * @param \ The return type of the visit operation. Use {@link Void} for * operations with no return type. */ class BaseVisitor\: AbstractParseTreeVisitor\ { The default implementation returns the result of calling * {@link #visitChildren\} on {@code ctx\}.\

*/ func visit(_ ctx: .Context) -> T? { return visitChildren(ctx) \}}; separator="\n"> } >> fileHeader(grammarFileName, ANTLRVersion) ::= << // Generated from by ANTLR >> Parser(parser, funcs, atn, sempredFuncs, superClass) ::= << >> Parser_(parser, funcs, atn, sempredFuncs, ctor, superClass) ::= << class : { internal static var _decisionToDFA: [DFA] = { var decisionToDFA = [DFA]() let length = ._ATN.getNumberOfDecisions() for i in 0..\._ATN.getDecisionState(i)!, i);!> decisionToDFA.append(DFA(._ATN.getDecisionState(i)!, i)) } return decisionToDFA }() internal static let _sharedContextCache = PredictionContextCache() enum Tokens: Int { case EOF = -1, = }; separator=", ", wrap, anchor> } static let = }; separator=", ", wrap, anchor> static let ruleNames: [String] = [ "}; separator=", ", wrap, anchor> ] override func getGrammarFileName() -> String { return "" } override func getRuleNames() -> [String] { return .ruleNames } override func getSerializedATN() -> String { return ._serializedATN } override func getATN() -> ATN { return ._ATN } override func sempred(_ _localctx: RuleContext?, _ ruleIndex: Int, _ predIndex: Int)throws -> Bool { switch (ruleIndex) { : return try _sempred(_localctx?.castdown(.self), predIndex)}; separator="\n"> default: return true } } static let _serializedATN = ATN().jsonString static let _ATN = ATNDeserializer().deserializeFromJson(_serializedATN) } >> vocabulary(literalNames, symbolicNames, accessLevel) ::= << private static let _LITERAL_NAMES: [String?] = [ }; null="nil", separator=", ", wrap, anchor> ] private static let _SYMBOLIC_NAMES: [String?] = [ }; null="nil", separator=", ", wrap, anchor> ] static let VOCABULARY = Vocabulary(_LITERAL_NAMES, _SYMBOLIC_NAMES) >> dumpActions(recog, argFuncs, actionFuncs, sempredFuncs) ::= << override func action(_ _localctx: RuleContext?, _ ruleIndex: Int, _ actionIndex: Int) throws { switch (ruleIndex) { : _action((_localctx as ?), actionIndex) }; separator="\n"> default: break } } override func sempred(_ _localctx: RuleContext?, _ ruleIndex: Int,_ predIndex: Int) throws -> Bool { switch (ruleIndex) { : return try _sempred(_localctx?.castdown(.self), predIndex)}; separator="\n"> default: return true } } >> parser_ctor(p) ::= << override func getVocabulary() -> Vocabulary { return .VOCABULARY } override init(_ input:TokenStream) throws { RuntimeMetaData.checkVersion("4.7.2", RuntimeMetaData.VERSION) try super.init(input) _interp = ParserATNSimulator(self,._ATN,._decisionToDFA, ._sharedContextCache) } >> /* This generates a private method since the actionIndex is generated, making an * overriding implementation impossible to maintain. */ RuleActionFunction(r, actions) ::= << private func _action(_ _localctx: ?, _ actionIndex: Int) { switch (actionIndex) { : }; separator="\n"> default: break } } >> /* This generates a private method since the predIndex is generated, making an * overriding implementation impossible to maintain. */ RuleSempredFunction(r, actions) ::= << private func _sempred(_ _localctx: !, _ predIndex: Int) throws -> Bool { switch (predIndex) { :return }; separator="\n"> default: return true } } >> RuleFunction(currentRule,args,code,locals,ruleCtx,altLabelCtxs,namedActions,finallyAction,postamble,exceptions) ::= << }; separator="\n"> @discardableResult }> func (_ ) throws -> { var _localctx: = (_ctx, getState()}>) try enterRule(_localctx, , .RULE_) defer { try! exitRule() } do { var _alt:Int } catch ANTLRException.recognition(let re) { _localctx.exception = re _errHandler.reportError(self, re) try _errHandler.recover(self, re) } return _localctx } >> LeftRecursiveRuleFunction(currentRule,args,code,locals,ruleCtx,altLabelCtxs, namedActions,finallyAction,postamble) ::= << }; separator="\n"> }> final func ( _ ) throws -> { return try (0}>) } @discardableResult private func (_ _p}>: Int) throws -> { let _parentctx: ParserRuleContext? = _ctx var _parentState: Int = getState() var _localctx: = (_ctx, _parentState}>) var _prevctx: = _localctx var _startState: Int = try enterRecursionRule(_localctx, , .RULE_, _p) defer { try! unrollRecursionContexts(_parentctx) } do { var _alt: Int } catch ANTLRException.recognition(let re) { _localctx.exception = re _errHandler.reportError(self, re) try _errHandler.recover(self, re) } return _localctx; } >> CodeBlockForOuterMostAlt(currentOuterMostAltCodeBlock, locals, preamble, ops) ::= << _localctx = Context(_localctx); try enterOuterAlt(_localctx, ) >> CodeBlockForAlt(currentAltCodeBlock, locals, preamble, ops) ::= << >> LL1AltBlock(choice, preamble, alts, error) ::= << setState() try _errHandler.sync(self) = try _input.LT(1) switch (.Tokens(rawValue: try _input.LA(1))!) { break}; separator="\n"> default: } >> LL1OptionalBlock(choice, alts, error) ::= << setState() try _errHandler.sync(self) switch (.Tokens(rawValue: try _input.LA(1))!) { break}; separator="\n"> default: break } >> LL1OptionalBlockSingleAlt(choice, expr, alts, preamble, error, followExpr) ::= << setState() try _errHandler.sync(self) if () { } ) ) !> >> LL1StarBlockSingleAlt(choice, loopExpr, alts, preamble, iteration) ::= << setState() try _errHandler.sync(self) while () { setState() try _errHandler.sync(self) } >> LL1PlusBlockSingleAlt(choice, loopExpr, alts, preamble, iteration) ::= << setState() try _errHandler.sync(self) repeat { setState(); try _errHandler.sync(self) } while () >> // LL(*) stuff AltBlock(choice, preamble, alts, error) ::= << setState() try _errHandler.sync(self) = try _input.LT(1) switch(try getInterpreter().adaptivePredict(_input,, _ctx)) { : break}; separator="\n"> default: break } >> OptionalBlock(choice, alts, error) ::= << setState() try _errHandler.sync(self) switch (try getInterpreter().adaptivePredict(_input,,_ctx)) { +1: break}; separator="\n"> default: break } >> StarBlock(choice, alts, sync, iteration) ::= << setState() try _errHandler.sync(self) _alt = try getInterpreter().adaptivePredict(_input,,_ctx) while (_alt != && _alt != ATN.INVALID_ALT_NUMBER) { if ( _alt==1+1 ) { } setState() try _errHandler.sync(self) _alt = try getInterpreter().adaptivePredict(_input,,_ctx) } >> PlusBlock(choice, alts, error) ::= << setState(); try _errHandler.sync(self) _alt = 1+1; repeat { switch (_alt) { +1: break}; separator="\n"> default: } setState(); try _errHandler.sync(self) _alt = try getInterpreter().adaptivePredict(_input,,_ctx) } while (_alt != && _alt != ATN.INVALID_ALT_NUMBER) >> Sync(s) ::= "sync();" ThrowNoViableAlt(t) ::= "throw ANTLRException.recognition(e: NoViableAltException(self))" TestSetInline(s) ::= << }; separator=" || ">!> //closure { () -> Bool in varlet testSet: Bool = }> }; separator="\n"> return testSet }() >> // Java language spec 15.19 - shift operators mask operands rather than overflow to 0... need range test testShiftInRange(shiftAmount) ::= << (() & ~0x3f) == 0 >> // produces smaller bytecode only when bits.ttypes contains more than two items bitsetBitfieldComparison(s, bits) ::= << })> && ((1 \<\< ) & ()}; separator=" | ">)) != 0)!> { () -> Bool in })>)!> )!> )}>)!> )}; separator="\n">!> let testArray: [Int] = [, }; separator=",">] return Utils.testBitLeftShiftArray(testArray, ) }() >> isZero ::= [ "0": true, default: false ] parserName(ttype) ::= <% .Tokens..rawValue %> offsetShift(shiftAmount, offset) ::= <% ( - ) %> // produces more efficient bytecode when bits.ttypes contains at most two items bitsetInlineComparison(s, bits) ::= <% == .Tokens..rawValue}; separator=" || "> %> cases(ttypes) ::= << :fallthrough} ; separator="\n"> :} ; separator="\n"> >> InvokeRule(r, argExprsChunks) ::= << setState() try { let assignmentValue = try (,) = assignmentValue} ; separator="\n"> }() try (,) >> MatchToken(m) ::= << setState() try { let assignmentValue = try match(.Tokens..rawValue) = assignmentValue} ; separator="\n"> }() try match(.Tokens..rawValue) >> MatchSet(m, expr, capture) ::= "" MatchNotSet(m, expr, capture) ::= "" CommonSetStuff(m, expr, capture, invert) ::= << setState() = }>try _input.LT(1) if ( \<= 0 || !()) { = }>try _errHandler.recoverInline(self) as Token } else { _errHandler.reportMatch(self) try consume() } >> Wildcard(w) ::= << setState() = }>try matchWildcard(); >> // ACTION STUFF Action(a, foo, chunks) ::= "" ArgAction(a, chunks) ::= "" SemPred(p, chunks, failChunks) ::= << setState() if (!()) { throw ANTLRException.recognition(e:FailedPredicateException(self, , , )) } >> ExceptionClause(e, catchArg, catchAction) ::= << catch () { } >> // lexer actions are not associated with model objects LexerSkipCommand() ::= "skip()" LexerMoreCommand() ::= "more()" LexerPopModeCommand() ::= "popMode()" LexerTypeCommand(arg) ::= "_type = " LexerChannelCommand(arg) ::= "_channel = " LexerModeCommand(arg) ::= "_mode = " LexerPushModeCommand(arg) ::= "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) ::= "(. != nil ? .!.getText()! : \"\")" TokenPropertyRef_type(t) ::= "(. != nil ? .!.getType() : 0)" TokenPropertyRef_line(t) ::= "(. != nil ? .!.getLine() : 0)" TokenPropertyRef_pos(t) ::= "(. != nil ? .!.getCharPositionInLine() : 0)" TokenPropertyRef_channel(t) ::= "(. != nil ? .!.getChannel() : 0)" TokenPropertyRef_index(t) ::= "(. != nil ? .!.getTokenIndex() : 0)" TokenPropertyRef_int(t) ::= "(. != nil ? Int(.!.getText()!) : 0)" RulePropertyRef_start(r) ::= "(. != nil ? (.!.start?.description ?? \"\") : \"\")" RulePropertyRef_stop(r) ::= "(. != nil ? (.!.stop?.description ?? \"\") : \"\")" RulePropertyRef_text(r) ::= "(. != nil ? try _input.getText(.!.start,.!.stop) : \"\")" RulePropertyRef_ctx(r) ::= "." RulePropertyRef_parser(r) ::= "self" ThisRulePropertyRef_start(r) ::= "_localctx.start" ThisRulePropertyRef_stop(r) ::= "_localctx.stop" ThisRulePropertyRef_text(r) ::= "(try _input.getText(_localctx.start, try _input.LT(-1)))" ThisRulePropertyRef_ctx(r) ::= "_localctx" ThisRulePropertyRef_parser(r) ::= "self" NonLocalAttrRef(s) ::= "((Context)getInvokingContext())." SetNonLocalAttr(s, rhsChunks) ::= "((Context)getInvokingContext()). = " AddToLabelList(a) ::= "..append()" TokenDecl(t) ::= ": !" TokenTypeDecl(t) ::= "var : Int = 0" TokenListDecl(t) ::= ": [Token] = [Token]()" RuleContextDecl(r) ::= ": !" RuleContextListDecl(rdecl) ::= ": [] = []()" ContextTokenGetterDecl(t) ::= << func () -> TerminalNode? { return getToken(.Tokens..rawValue, 0) } >> ContextTokenListGetterDecl(t) ::= << func () -> [TerminalNode] { return getTokens(.Tokens..rawValue) } >> ContextTokenListIndexedGetterDecl(t) ::= << func (_ i:Int) -> TerminalNode? { return getToken(.Tokens..rawValue, i) } >> ContextRuleGetterDecl(r) ::= << func () -> ? { return getRuleContext(.self, 0) } >> ContextRuleListGetterDecl(r) ::= << func () -> [] { return getRuleContexts(.self) } >> ContextRuleListIndexedGetterDecl(r) ::= << func (_ i: Int) -> ? { return getRuleContext(.self, 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) ::= "