diff options
Diffstat (limited to 'test/files/run/packrat1.scala')
-rw-r--r-- | test/files/run/packrat1.scala | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/test/files/run/packrat1.scala b/test/files/run/packrat1.scala new file mode 100644 index 0000000000..69eb8c5fc9 --- /dev/null +++ b/test/files/run/packrat1.scala @@ -0,0 +1,48 @@ +import scala.util.parsing.combinator._ + +import scala.util.parsing.combinator.syntactical.StandardTokenParsers +import scala.util.parsing.input._ +import scala.util.parsing.syntax._ + +import scala.collection.mutable.HashMap + +object Test extends Application{ + import grammars._ + + val head = phrase(term) + + println(extractResult(head(new lexical.Scanner("1")))) + println(extractResult(head(new lexical.Scanner("1+2")))) + println(extractResult(head(new lexical.Scanner("9-4")))) + println(extractResult(head(new lexical.Scanner("9*9")))) + println(extractResult(head(new lexical.Scanner("8/2")))) + println(extractResult(head(new lexical.Scanner("4*9-0/7+9-8*1")))) + println(extractResult(head(new lexical.Scanner("(1+2)*3")))) +} + +object grammars extends StandardTokenParsers with PackratParsers{ + + def extractResult(r : ParseResult[_]) = r match{ + case Success(a,_) => a + case Failure(a,_) => a + case Error(a,_) => a + } + + lexical.delimiters ++= List("+","-","*","/","(",")") + lexical.reserved ++= List("Hello","World") + + /**** + * term = term + fact | term - fact | fact + * fact = fact * num | fact / num | num + */ + + + val term: PackratParser[Int] = (term~("+"~>fact) ^^ {case x~y => x+y} + |term~("-"~>fact) ^^ {case x~y => x-y} + |fact) + + val fact: PackratParser[Int] = (fact~("*"~>numericLit) ^^ {case x~y => x*y.toInt} + |fact~("/"~>numericLit) ^^ {case x~y => x/y.toInt} + |"("~>term<~")" + |numericLit ^^ {_.toInt}) + } |