Skip to content

Instantly share code, notes, and snippets.

@MasseGuillaume
Created July 7, 2012 05:30
Show Gist options
  • Save MasseGuillaume/3064906 to your computer and use it in GitHub Desktop.
Save MasseGuillaume/3064906 to your computer and use it in GitHub Desktop.
LOG3210 - TP1
import scala.util.parsing.combinator._
object Main
{
def main(args: Array[String])
{
println(TP1.parseAll(TP1.program, args(0)))
}
}
object TP1 extends JavaTokenParsers
{
def program: Parser[Any] = block
def block: Parser[Any] = rep( statement )
def statement: Parser[Any] = (
assignementStatement ~ ";"
| inputOutputStatement ~ ";"
| ifStatement
| whileStatement
)
def assignementStatement: Parser[Any] =
{
ident ~ {
"=" |
"+=" |
"-=" |
"*=" |
"/=" |
"^="
} ~ expression
}
def inputOutputStatement: Parser[Any] = {
"print" ~ "(" ~ expression ~ ")" |
"input"
}
def ifStatement: Parser[Any] =
{
"if" ~ "(" ~ expression ~ ")" ~ "{" ~ block ~ "}" ~ "else" ~ "{" ~ block ~ "}" |
"if" ~ "(" ~ expression ~ ")" ~ "{" ~ block ~ "}"
}
def whileStatement: Parser[Any] =
{
"while" ~ "(" ~ expression ~ ")" ~ "{" ~ block ~ "}"
}
def expression: Parser[Any] = addExpression
def addExpression: Parser[Any] =
{
multiplicationExpression ~
rep( ( "+" | "-" ) ~ multiplicationExpression )
}
def multiplicationExpression: Parser[Any] =
{
powerExpression ~
rep( ( "*" | "/" ) ~ powerExpression )
}
def powerExpression: Parser[Any] =
{
factorialExpression ~
rep( "^" ~ factorialExpression )
}
def factorialExpression: Parser[Any] =
{
unaryExpression ~ opt( "!" )
}
def unaryExpression: Parser[Any] =
{
rep( "-" ) ~ basicExpression
}
def basicExpression: Parser[Any] =
{
ident |
wholeNumber |
decimalNumber |
floatingPointNumber |
"(" ~ expression ~ ")"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment