Created
August 17, 2020 10:03
-
-
Save kencoba/2ce7a43134d7907cd8165c5800681d2e to your computer and use it in GitHub Desktop.
Sample code of "Creating DSL With Antlr4 and Scala" for Scala2.13
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.ByteArrayInputStream | |
import org.antlr.v4.runtime.{CharStream, CharStreams, CommonTokenStream} | |
/** | |
* See original Saumitra's blog. | |
* https://saumitra.me/blog/creating-dsl-with-antlr4-and-scala/ | |
* | |
* This code is for Scala 2.13. | |
*/ | |
object Arithmetic { | |
def main(args: Array[String]): Unit = { | |
expressions.foreach(parse) | |
} | |
def parse(input:String) = { | |
println ("\nEvaluating expression " + input) | |
val charStream = CharStreams.fromStream(new ByteArrayInputStream(input.getBytes("utf-8"))) | |
val lexer = new ArithmeticLexer(charStream) | |
val tokens = new CommonTokenStream(lexer) | |
val parser = new ArithmeticParser(tokens) | |
val arithmeticListener = new ArithmeticListenerApp() | |
parser.expr.enterRule(arithmeticListener) | |
} | |
val expressions = List( | |
"127.1 + 2717", | |
"2674 - 4735", | |
"47 * 74.1", | |
"271 / 281", | |
"12 ^ 3" // unsupported expression | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment