Skip to content

Instantly share code, notes, and snippets.

@kencoba
Created August 17, 2020 10:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kencoba/2ce7a43134d7907cd8165c5800681d2e to your computer and use it in GitHub Desktop.
Save kencoba/2ce7a43134d7907cd8165c5800681d2e to your computer and use it in GitHub Desktop.
Sample code of "Creating DSL With Antlr4 and Scala" for Scala2.13
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