Create a Programming Language with Scala Parser Combinators
Learn how to design your own interpreted programming language with the Scala parser library.
Join the DZone community and get the full member experience.
Join For FreeDesigning your own programming language is no small feat. With the Scala parser library, however, you can design a full-featured interpreted language very easily. In this article, I will demonstrate how to use Scala parser combinators to create a programming language that contains if-else conditions, loops, and even function calls. At the end of this article, I've included a link to the code on GitHub, for you to fork and do as you'd like. Let's get started!
There are three primary components to a language project using Scala parser combinators:
The parser itself, which defines the grammar of the language and performs the parsing.
The interpreter, which walks the abstract syntax tree (AST) that's created by Step 1.
Plain old Scala classes for each language construct. For example, we'll have a LoopStatement class that contains the number of iterations for the loop and a list of statements within the loop.
Let's start with the parser. The first step is to extend the StandardTokenParsers class and define the reserved words and delimiters in our language.
class SmallLanguageParser extends StandardTokenParsers {
lexical.reserved += ("var", "println", "loop", "times", "endloop", "if",
"then", "else", "endif", "func", "return", "endfunc", "main")
lexical.delimiters += ("*", "/", "%", "+", "-", "(", ")", "=",
"<", ">", "==", "!=", "<=", ">=", ",", ":")
}
Next, we add to our SmallLanguageParser class by adding each parser rule. This language will contain a "main" entry point that will serve as the main function of our application. Let's add a parser rule for this "main" construct.
class SmallLanguageParser extends StandardTokenParsers {
lexical.reserved += ("var", "println", "loop", "times", "endloop", "if",
"then", "else", "endif", "func", "return", "endfunc", "main")
lexical.delimiters += ("*", "/", "%", "+", "-", "(", ")", "=",
"<", ">", "==", "!=", "<=", ">=", ",", ":")
def program: Parser[Program] = (rep(function) <~ ("main" ~ ":")) ~ codeblock ^^ {
case f ~ c => new Program(f, c)
}
}
Let's examine this "program" function a bit. You'll notice that the return value is a Parser[Program]. Peeling away the complexity, this is really just returning an instance of the Program class, which we'll define later. This Program class is one of the plain old Scala classes that belong to Step 3. So, you'll notice that each of these rules will simply return an instance of one of these classes, each of which represent a construct in our programming language.
The next part of this rule says (rep(function) <~ ("main" ~ ":")). This means that we can have a repeated list of functions (i.e. rep(function) ) in our language. This list of functions is then followed by the main: reserved word. This is then followed by a codeblock. Note that codeblock and function are just parser rules that we'll define later in our parser.
The last part of this rule is ^^ { ... }. The ^^ operator in Scala simply tells the parser that what follows is the Scala code that we want to execute when this parser rule is triggered. The Scala code within the { ... } is simply returning an instance of the Program class, whose constructor takes a list of functions and the codeblock.
We can now repeat this process for each parser rule. Each rule will define the grammar (or allowed keywords and text), along with the return type. When you think of a programming language, it contains constructs such as loops, conditionals, function calls, etc. So, if we add parser rules for each of these constructs, we arrive at the following SmallLanguageParser:
class SmallLanguageParser extends StandardTokenParsers {
lexical.reserved += ("var", "println", "loop", "times", "endloop", "if",
"then", "else", "endif", "func", "return", "endfunc", "main")
lexical.delimiters += ("*", "/", "%", "+", "-", "(", ")", "=",
"<", ">", "==", "!=", "<=", ">=", ",", ":")
def program: Parser[Program] = (rep(function) <~ ("main" ~ ":")) ~ codeblock ^^ {
case f ~ c => new Program(f, c)
}
def function: Parser[Function] = ("func" ~> ident) ~ ("(" ~> arguments) ~
(")" ~> codeblock) ~ opt(returnStatement) <~ "endfunc" ^^ {
case a ~ b ~ c ~ None => new Function(a, b, c, Number(0))
case a ~ b ~ c ~ d => new Function(a, b, c, d.get)
}
def returnStatement: Parser[Expr] = "return" ~> expr ^^ {
e => e
}
def arguments: Parser[Map[String, Int]] = repsep(ident, ",") ^^ {
argumentList =>
{
(for (a <- argumentList) yield (a -> 0)) toMap
}
}
def codeblock: Parser[List[Statement]] = rep(statement) ^^ { a => a }
def statement: Parser[Statement] = positioned(variableAssignment | outStatement |
loopStatement | ifStatement | functionCall | outStatement) ^^ { a => a }
def variableAssignment: Parser[VariableDefinition] = "var" ~> ident ~ "=" ~
positioned(functionCall | expr) ^^ { case a ~ "=" ~ b => { new VariableDefinition(a, b) } }
def outStatement: Parser[PrintStatement] = "println" ~> positioned(expr) ^^ {
case a => new PrintStatement(a)
}
def loopStatement: Parser[LoopStatement] = ("loop" ~> iterations <~ "times") ~
codeblock <~ "endloop" ^^ {
case i ~ s => {
new LoopStatement(i, s)
}
}
def ifStatement: Parser[IfStatement] = conditional ~ codeblock ~
opt("else" ~> codeblock) <~ "endif" ^^ {
case a ~ b ~ c => {
c match {
case None => new IfStatement(a, b, List())
case _ => new IfStatement(a, b, c.get)
}
}
}
def conditional: Parser[Condition] = "if" ~ "(" ~> condition <~ ")" ~ "then"
def condition: Parser[Condition] = positioned(expr) ~
("<" | ">" | "==" | "!=" | "<=" | ">=") ~ positioned(expr) ^^ {
case a ~ b ~ c => {
new Condition(b, a, c)
}
}
def iterations: Parser[Int] = numericLit ^^ { _ toInt }
def functionCall: Parser[FunctionCall] = ((ident) <~ "(") ~
functionCallArguments <~ ")" ^^ {
case a ~ l => new FunctionCall(a, l)
}
def functionCallArguments: Parser[Map[String, Expr]] =
repsep(functionArgument, ",") ^^ {
_ toMap
}
def functionArgument: Parser[(String, Expr)] = (ident <~ "=") ~ expr ^^ {
case a ~ b => (a, b)
}
def expr: Parser[Expr] = term ~ rep(("+" | "-") ~ term) ^^ {
case a ~ List() => a
case a ~ b => {
def appendExpression(c: Operator, p: Operator): Operator = {
p.left = c
p
}
var root: Operator = new Operator(b.head._1, a, b.head._2)
for (f <- b.tail) {
var parent =
f._1 match {
case "+" => new Operator("+", null, f._2)
case "-" => Operator("-", null, f._2)
}
root = appendExpression(root, parent)
}
root
}
}
def term: Parser[Expr] = multiplydividemodulo ^^ { l => l } | factor ^^ {
a => a
}
// note that "rep" returns a List
def multiplydividemodulo: Parser[Expr] = factor ~ rep(("*" | "/" | "%") ~ factor) ^^ {
case a ~ List() => a
case a ~ b => {
def appendExpression(e: Operator, t: Operator): Operator = {
t.left = e.right
e.right = t
t
}
var root: Operator = new Operator(b.head._1, a, b.head._2)
var current = root
// for each of these, i'm just building up the parse tree
for (f <- b.tail) {
var rightOperator =
f._1 match {
case "*" => Operator("*", null, f._2)
case "/" => Operator("/", null, f._2)
case "%" => Operator("%", null, f._2)
}
current = appendExpression(current, rightOperator)
}
root
}
}
def factor: Parser[Expr] = numericLit ^^ { a => Number(a.toInt) } |
"(" ~> expr <~ ")" ^^ { e => e } |
ident ^^ { new Identifier(_) }
def parseAll[T](p: Parser[T], in: String): ParseResult[T] = {
phrase(p)(new lexical.Scanner(in))
}
}
The code is a bit long, but it's really just a parser rule for each language construct that our language will process. There's a rule for how to handle an if-statement, a rule for processing a loop, a rule for how to parse a function call, etc. The only thing that doesn't fit this description is the bottom function named "parseAll". This "parseAll" function is going to take an instance of our SmallLanguageParser and the input source code that we're going to run. It will return the result of the parse operation, which will be the abstract syntax tree (AST) for the source code. This AST can then be interpreted by our interpreter (which is step #2 from our list above).
Here is the code for the interpreter:
class Interpreter(program: Program) {
var currentScope = new Scope("global", null)
def run() {
walk(program.statements)
}
private def getVariable(ident: Identifier): Expr = {
var s: Scope = currentScope
while ((!s.name.equals("global")) && !s.variables.contains(ident.name)) {
s = s.parentScope
}
if (s.variables.contains(ident.name)) s.variables(ident.name)
else {
sys.error("Error: Undefined variable " + ident.name +
" at position [" +
ident.pos.column + "] on line: " +
ident.pos.line)
}
}
private def calculateExpr(e: Expr): Int = {
e match {
case Number(value) => value
case Identifier(name) => {
calculateExpr(getVariable(e.asInstanceOf[Identifier]))
}
case Operator(op, left, right) => {
op match {
case "*" => calculateExpr(left) * calculateExpr(right)
case "/" => calculateExpr(left) / calculateExpr(right)
case "%" => calculateExpr(left) % calculateExpr(right)
case "+" => calculateExpr(left) + calculateExpr(right)
case "-" => calculateExpr(left) - calculateExpr(right)
}
}
}
}
private def isConditionTrue(condition: Condition): Boolean = {
val a = calculateExpr(condition.left)
val b = calculateExpr(condition.right)
condition.op match {
case "==" => (a == b)
case "!=" => (a != b)
case "<=" => (a <= b)
case "<" => (a < b)
case ">=" => (a >= b)
case ">" => (a > b)
}
}
private def executeFunction(f: Function, arguments: Map[String, Expr]) {
currentScope = new Scope(f.name, currentScope)
for (v <- arguments) currentScope.variables(v._1) = v._2
walk(f.statements)
currentScope = currentScope.parentScope
}
private def walk(tree: List[Statement]) {
if (!tree.isEmpty) {
tree.head match {
case FunctionCall(name, values) => {
val f = program.functions.filter(x => x.name == name)
if (f.size < 1) sys.error("Error: Undefined function '" +
name + "' being called at position [" +
tree.head.pos.column + "] on line: " +
tree.head.pos.line)
else {
executeFunction(f(0), values)
walk(tree.tail)
}
}
case VariableDefinition(name, value) => {
// push this variable into scope
if (value.isInstanceOf[FunctionCall]) {
val functionCall = value.asInstanceOf[FunctionCall]
val function = program.functions.filter(x => x.name == functionCall.name)
// check if proc is defined and if not throw an error
if (function.size < 1) sys.error("Error: Undefined function '" +
functionCall.name + "' being called at position [" +
tree.head.pos.column + "] on line: " +
tree.head.pos.line)
else {
executeFunction(function(0), functionCall.values)
currentScope = currentScope.parentScope
// assign the return value of the function to the variable
currentScope.variables(name) = function(0).returnValue
}
} else {
currentScope.variables(name) = value
}
walk(tree.tail)
}
case PrintStatement(value) => {
println(calculateExpr(value))
walk(tree.tail)
}
case LoopStatement(iterations, statements) => {
currentScope = new Scope("", currentScope)
for (i <- 0 until iterations) walk(statements)
currentScope = currentScope.parentScope
walk(tree.tail)
}
case IfStatement(condition, trueBranch, falseBranch) => {
currentScope = new Scope("", currentScope)
if (isConditionTrue(condition)) walk(trueBranch) else walk(falseBranch)
currentScope = currentScope.parentScope
walk(tree.tail)
}
case _ => ()
}
}
}
}
This interpreter simply walks the AST and does something each time it encounters a node in the tree. Take the last case statement, for example. If the interpreter encounters an if-statement, the interpreter simply evaluates the condition. If the condition is true, the interpreter traverses the true branch of the code. If the condition evaluates to false, the interpreter traverses the false branch of the code.
At this point, we have steps #1 and #2 complete. We have a parser and we have an interpreter that will process our parse results. The last piece of the puzzle is the plain old Scala classes for each type of language construct. Rather than go through each class in this article (they are plain old Scala classes after all and I've included a link to all of the code on GitHub below), let's take a look at one of these classes, the "Condition". This is the class that you'll notice is being created and returned by the parser when a condition (or if-statement) is found in the source code.
class Condition(val op: String, val left: Expr, val right: Expr)
This class just stores the operation and the expression that evaluates to the left of the condition and to the right of the condition, which are the true and false branches, respectively. So, the relationship between these pieces looks something like this:
Source Code -> Parser -> {plain old Scala classes} -> Interpreter
The only thing missing is a driver application that handles this flow of events. Here's some Scala code that reads in an input source file, calls the parser, and then invokes the interpreter on the parse results:
object SmallLanguage {
def main(args: Array[String]) {
val inputFile = Source.fromFile("scripts/program.small")
val inputSource = inputFile.mkString
val parser = new SmallLanguageParser
parser.parseAll(parser.program, inputSource) match {
case parser.Success(r, n) => {
val interpreter = new Interpreter(r)
try {
interpreter.run
} catch {
case e: RuntimeException => println(e.getMessage)
}
}
case parser.Error(msg, n) => println("Error: " + msg)
case parser.Failure(msg, n) => println("Error: " + msg)
case _ =>
}
}
}
See, creating a programming language isn't that difficult after all! Granted, this is an interpreted language, which makes it simpler. However, this is a great way to become familiar with language design. The best part is, you can do it all in Scala.
Here is the link to all of the source code on GitHub: https://github.com/travisdazell/javaone-2013-BOF-small-language
I've also included a link to the slides on this topic, from my JavaOne 2013 BOF session: http://www.slideserve.com/manton/developing-small-languages-with-scala-parser-combinators
Opinions expressed by DZone contributors are their own.
Comments