Scala - StdTokenParsers parse not exactly as expected - scala

I have an assignment to parse a demo language, this is the code that has problems in it, the other work as I expected:
def parse(s: String) = phrase(program)(new lexical.Scanner(s))
def program: Parser[Any] = rep(sttment)
//Operator
def expression: Parser[Any] = lv1 ~ rep(("<" | ">" | "<=" | ">=") ~ lv1)
def lv1: Parser[Any] = lv2 ~ rep(("<>" | "==") ~ lit)
def lv2: Parser[Any] = lit ~ opt("." ~ ident ~ opt("(" ~ repsep(expression, ",") ~ ")"))
def lit: Parser[Any] = ident | boollit | floatlit | intlit | stringlit
// Statements
def sttment: Parser[Any] = sttm | "{" ~ rep(sttment) ~ "}"
def sttm: Parser[Any] = (assignment ||| returnsttm ||| invokesttm ||| ifsttm ||| whilesttm |||
repeatsttm ||| forsttm ||| breaksttm ||| continuesttm ) ~ ";"
def assignment: Parser[Any] = lhs ~ ":=" ~ expression
def lhs: Parser[Any] = ( "self" ~ "." ~ ident )|||( ident ~ "." ~ ident )|||( ident ~ "[" ~ expression ~ "]")|||ident
def ifsttm: Parser[Any] = "if" ~ expression ~ "then" ~ sttment ~ opt("else" ~ sttment)
def whilesttm: Parser[Any] = "while" ~ expression ~ "do" ~ sttment
def repeatsttm: Parser[Any] = "repeat" ~ sttment ~ "until" ~ expression
def forsttm: Parser[Any] = "for" ~ ident ~ ":=" ~ expression ~ ("to" | "downto") ~ expression ~ "do" ~ sttment
def breaksttm: Parser[Any] = "break"
def continuesttm: Parser[Any] = "continue"
def returnsttm: Parser[Any] = "return" ~ expression
def invokesttm: Parser[Any] = expression ~ "." ~ ident ~ "(" ~ repsep(expression, ",") ~ ")"
def primtype: Parser[Any] = "integer" | "float" | "bool" | "string" | "void"
def boollit: Parser[Any] = elem("boolean", _.isInstanceOf[lexical.BooleanLit])
def floatlit: Parser[Any] = elem("real", _.isInstanceOf[lexical.FloatLit])
def intlit: Parser[Any] = elem("integer", _.isInstanceOf[lexical.IntLit])
def stringlit: Parser[Any] = elem("string", _.isInstanceOf[lexical.StringLit])
For example, when I parse this string:
io.writeFloatLn(s.getArea());
It return:
``.'' expected but `;' found"
at the "return 1". Can someone tell me what mistakes did I make?
Edit:
- I am sorry, because I didn't understand my problem enough, I have asked it the wrong way, now I write the exact error it make.
Delimiter and keywords list:
reserved ++= List("bool", "break", "continue", "do", "downto", "else", "float", "for",
"if", "integer", "new", "repeat", "string", "then", "to", "until", "while", "return",
"true", "false", "void", "null", "self", "final", "class", "extends", "abstract")
delimiters ++= List("[", "]", "(", ")", ":", ";", ".", ",", "{", "}", "+", "=",
"-", "*", "/", "\", "%", ":=", "==", "<", "<=", ">", ">=", "<>", "&&", "!", "||", "^")

Seems like they work as expected - io.writeFloatLn(s.getArea()) was parsed as expression inside statement - so parser just waiting for "." from your statement, something like:
io.writeFloatLn(s.getArea()).writeFloatLn()
I think you can use brackets only as a part of statement (call operation) or only as a part of expression (application), depending on which language do you need - imperative or functional. Same for ..

I would have to see more of your code to be sure but I don't see returnsttm in your sttm list. That would prevent sttment from matching returnsttm before looking for the opening brace.

Related

Scala combinator parsers: repetition and subsequent concatenated rules subsets of rule in repetition

I am parsing strings using scala combinators, I would like strings such as
"Ph" or "Ph." or "Ph. D" or "Ph.D." to be successfully parsed, among those, for the moment the three first one are successfully parsed, but when I execute println(parseAll(name, "Ph.D.")), I see the following:
[1.6] failure: string matching regex `\p{IsLatin}+' expected but end of source found
Ph.D.
^
My intuition is that because nameSepSubset is a rule used by nameSep, rep1(nameSub ~ nameSep) consumes everything in "Ph.D." and thus yields no input to nameSub ~ nameSepSubset.
Is there another operator than rep1 or another way of defining my grammar that would solve this problem?
The grammar:
lazy val nameSub = """[a-zA-Z]+""".r
lazy val nameSepSubset = (
rep1(" ")
||| "." ~ rep1(" ")
||| ".")
lazy val nameSep = (
nameSepSubset
||| rep(" ") ~ "," ~ rep(" ")
||| rep(" ") ~> "-" <~ rep(" ")
||| "'")
lazy val name = (rep1(nameSub ~ nameSep) ~ nameSub ~ nameSepSubset
||| nameSub ~ nameSepSubset)
One solution could be to redefine the rules for name, using a recursive definition of name:
lazy val name = nameSub ~ nameSep ~ name //(1)
||| nameSub ~ nameSepSubset /*(2)*/ ||| "" /*(3)*/
you can see that legal outputs would be:
nameSub ~ nameSepSubset from rule (2) which is equivalent to
nameSub ~ nameSepSubset ~ "" that can be derived from rule (3)
or
nameSub ~ nameSep ~ nameSub ~ nameSepSub
or
nameSub ~ nameSep ~ nameSub ~ nameSep ~ nameSub ~ nameSepSub
or
...

Scala Parser Combinators Matching Wrong Parser

I am writing an extremely simple programming language using scala's parsers. I am trying to allow users to have multi-word variables ie my variable and I want to allow them to assign variables in three ways: let var = 2, var =2, set var to 4. I have the first two working, but I cant get the latter to work.
Here is my code
lazy val line:PackratParser[Line] = (assignment | element | comment) <~ (";" | "[\n\r]*".r)
lazy val assignment:PackratParser[Assignment] = assignmentLHS ~ element ^^ {
case x ~ y => new Assignment(x,y)
}
lazy val assignmentLHS = "set" ~ "[" ~> identifier <~ "]" ~ "to" | ("let"?) ~> identifier <~ "="
lazy val identifier:Parser[String] = "([a-zA-Z]+[a-zA-Z0-9]* ?)+".r ^^ (X => if (X.charAt(X.length-1) == ' ') X.substring(0, X.length-1) else X)
lazy val element:PackratParser[Element] =(
functionDef
| comparison
| expression
| boolean
| controlStatement
| functionCall
| reference
| value
| codeBlock
)
lazy val reference: PackratParser[Reference] = identifier ^^ (x=>new Reference(x))
Elements are most things in the language.
I would like to replace the assignmentLHS parser with:
lazy val assignmentLHS = "set" ~> identifier <~ "to" | ("let"?) ~> identifier <~ "="
so that the user can write set my variable to 4 instead of `set [my variable] to 4. The problem is that it just parses that as a reference
Why do you have a space in the identifier before the 'optional' '?' symbol:
0-9]* ?)+
Maybe that is causing
set <identifier>
to change to
set other_chars
and set becomes part of the identifier. That would explain why your use of
"set" ~ "[" ~> identifier <~ "]"
works but
"set" ~> identifier <~ "to"
does not

scala parser combinators - constructor cannot be initiated to expected type

I am fairly new to Parser Combinators and am having the above error when compiling the following function:
def attachRoad = "attach" ~ ("primary" | "secondary") ~ "road" ~ ident ~ "with" ~ "length" ~ floatingPointNumber ~ "at" ~ floatingPointNumber ^^
{
case "attach" ~ "primary" ~ "road" ~ road ~ "with" ~ "length" ~ len ~ "at" ~ pos ~ "flow" ~ flow => attachRoadHelper(road, StreetType.PRIMARY, len, flow, pos)
case "attach" ~ "secondary" ~ "road" ~ road ~ "with" ~ "length" ~ len ~ "at" ~ pos ~ "flow" ~ flow => attachRoadHelper(road, StreetType.SECONDARY, len, flow, pos)
}
So that gives me
constructor cannot be initiated to expected type
in both cases as explained.
Having looked through the documentation once again and some threads on StackOverflow, I have failed to come to a solution or understand why this is happening as I don't see any constructors within the "case" statements. (Is that something that Scala does under the hood?)
I have also tried changing the "case" outcome to "None" to no avail.
Any insight is deeply appreciated.
It may be good idea to group all your significant capturing groups using parentheses and ignore all constant tokens using ~> or <~ operators. In this case you will need to match only significant results:
def attachRoad =
("attach" ~> ("primary" | "secondary")) ~
("road" ~> ident) ~
("with" ~> "length" ~> floatingPointNumber) ~
("at" ~> floatingPointNumber) ^^ {
case "primary" ~ road ~ len ~ pos =>
attachRoadHelper(road, StreetType.PRIMARY, len, ???, pos)
case "secondary" ~ road ~ len ~ pos =>
attachRoadHelper(road, StreetType.SECONDARY, len, ???, pos)
}
In you case it becomes clear that your parsing expression returns sequence of four results while you expect five.

How to use ~> and <~ in grammar rule definition in Scala?

How can I ignore all strings in these grammar rules using correct placement of ~> or <~ operators?
def typeDefBody = ident ~ ":" ~ ident ~ "{" ~ fieldBody ~ "}"
def fieldBody = "validation" ~ "{" ~ validationBody ~ "}"
def validationBody = length ~ pattern
def length = "length" ~ "=" ~ wholeNumber ~ "to" ~ wholeNumber
def pattern = "pattern" ~ "=" ~ stringLiteral
I found the solution, I should break typeDefBody to 3 None terminal rules as below
def typeDefBody = ident ~ typeDefBodySequence1
def typeDefBodySequence1 = ":" ~> ident ~ typeDefBodySequence2
def typeDefBodySequence2 = "{" ~> fieldBody <~ "}"
def fieldBody = "validation" ~ "{" ~> validationBody <~ "}"
def validationBody = length ~ pattern
def length = "length" ~ "=" ~> wholeNumber ~ "to" ~ wholeNumber
def pattern = "pattern" ~ "=" ~> stringLiteral

Scala. Difficult expression parser. OutOfMemoryError

I would like to create a parser for difficult expression with order of operations. I have some example but it works very slowly and throw exception OutOfMemoryError. How can I improve it?
def expr: Parser[Expression] = term5
def term5: Parser[Expression] =
(term4 ~ "OR" ~ term4) ^^ { case lhs~o~rhs => BinaryOp("OR", lhs, rhs) } |
term4
def term4: Parser[Expression] =
(term3 ~ "AND" ~ term3) ^^ { case lhs~a~rhs => BinaryOp("AND", lhs, rhs) } |
term3
def term3: Parser[Expression] =
(term2 ~ "<>" ~ term2) ^^ { case lhs~ne~rhs => BinaryOp("NE", lhs, rhs) } |
(term2 ~ "=" ~ term2) ^^ { case lhs~eq~rhs => BinaryOp("EQ", lhs, rhs) } |
(term2 ~ "NE" ~ term2) ^^ { case lhs~ne~rhs => BinaryOp("NE", lhs, rhs) } |
(term2 ~ "EQ" ~ term2) ^^ { case lhs~eq~rhs => BinaryOp("EQ", lhs, rhs) } |
term2
def term2: Parser[Expression] =
(term1 ~ "<" ~ term1) ^^ { case lhs~lt~rhs => BinaryOp("LT", lhs, rhs) } |
(term1 ~ ">" ~ term1) ^^ { case lhs~gt~rhs => BinaryOp("GT", lhs, rhs) } |
(term1 ~ "<=" ~ term1) ^^ { case lhs~le~rhs => BinaryOp("LE", lhs, rhs) } |
(term1 ~ ">=" ~ term1) ^^ { case lhs~ge~rhs => BinaryOp("GE", lhs, rhs) } |
(term1 ~ "LT" ~ term1) ^^ { case lhs~lt~rhs => BinaryOp("LT", lhs, rhs) } |
(term1 ~ "GT" ~ term1) ^^ { case lhs~gt~rhs => BinaryOp("GT", lhs, rhs) } |
(term1 ~ "LE" ~ term1) ^^ { case lhs~le~rhs => BinaryOp("LE", lhs, rhs) } |
(term1 ~ "GE" ~ term1) ^^ { case lhs~ge~rhs => BinaryOp("GE", lhs, rhs) } |
term1
def term1: Parser[Expression] =
(term ~ "+" ~ term) ^^ { case lhs~plus~rhs => BinaryOp("+", lhs, rhs) } |
(term ~ "-" ~ term) ^^ { case lhs~minus~rhs => BinaryOp("-", lhs, rhs) } |
(term ~ ":" ~ term) ^^ { case lhs~concat~rhs => BinaryOp(":", lhs, rhs) } |
term
def term: Parser[Expression] =
(factor ~ "*" ~ factor) ^^ { case lhs~times~rhs => BinaryOp("*", lhs, rhs) } |
(factor ~ "/" ~ factor) ^^ { case lhs~div~rhs => BinaryOp("/", lhs, rhs) } |
(factor ~ "MOD" ~ factor) ^^ { case lhs~div~rhs => BinaryOp("MOD", lhs, rhs) } |
factor
def factor: Parser[Expression] =
"(" ~> expr <~ ")" |
("+" | "-") ~ factor ^^ { case op~rhs => UnaryOp(op, rhs) } |
function |
numericLit ^^ { case x => Number(x/*.toFloat*/) } |
stringLit ^^ { case s => Literal(s) } |
ident ^^ { case id => Variable(id) }
Basically, it's slow and consumes too much memory because your grammar it is incredibly inefficient.
Let's consider the second line: B = A:(1+2). It will try to parse this line like this:
term4 OR term4 and then term4.
term3 AND term3 and then term3.
term2 <> term2, then =, then NE then EQ and then term2.
term1 8 different operators term1, then term1.
term + term, term - term, term : term and then term.
factor * factor, factor / factor, factor MOD factor and then factor.
parenthesis expression, unary factor, function, numeric literal, string literal, ident.
The first try is like this:
ident * factor + term < term1 <> term2 AND term3 OR term4
I'm skipping parenthesis, unary, function, numeric and string literals because they don't match A -- though function probably does, but it's definition isn't available. Now, since : doesn't match *, it will try next:
ident / factor + term < term1 <> term2 AND term3 OR term4
ident MOD factor + term < term1 <> term2 AND term3 OR term4
ident + term < term1 <> term2 AND term3 OR term4
Now it goes to the next term1:
ident * factor - term < term1 <> term2 AND term3 OR term4
ident / factor - term < term1 <> term2 AND term3 OR term4
ident MOD factor - term < term1 <> term2 AND term3 OR term4
ident - term < term1 <> term2 AND term3 OR term4
And next:
ident * factor : term < term1 <> term2 AND term3 OR term4
ident / factor : term < term1 <> term2 AND term3 OR term4
ident MOD factor : term < term1 <> term2 AND term3 OR term4
ident : term < term1 <> term2 AND term3 OR term4
Aha! We finally got a match on term1! But ( doesn't match <, so it has to try the next term2:
ident * factor + term > term1 <> term2 AND term3 OR term4
etc...
All because the first term in each line for each term will always match! To match a simple number it has to parse factor 2 * 2 * 5 * 9 * 4 * 4 = 2880 times!
But that's not half of the story! You see, because termX is repeated twice, it will repeat all this stuff on both sides. For example, the first match for A:(1+2) is this:
ident : term < term1 <> term2 AND term3 OR term4
where ident = A
and term = (1+2)
Which is incorrect, so it will try > instead of <, and then <=, etc, etc.
I'm putting a logging version of this parser below. Try to run it and see all the things it is trying to parse.
Meanwhile, there are good examples of how to write these parsers available. Using sbaz, try:
sbaz install scala-devel-docs
Then look inside the doc/scala-devel-docs/examples/parsing directory of the Scala distribution and you'll find several examples.
Here's a version of your parser (without function) that logs everything it tries:
sealed trait Expression
case class Variable(id: String) extends Expression
case class Literal(s: String) extends Expression
case class Number(x: String) extends Expression
case class UnaryOp(op: String, rhs: Expression) extends Expression
case class BinaryOp(op: String, lhs: Expression, rhs: Expression) extends Expression
object TestParser extends scala.util.parsing.combinator.syntactical.StdTokenParsers {
import scala.util.parsing.combinator.lexical.StdLexical
type Tokens = StdLexical
val lexical = new StdLexical
lexical.delimiters ++= List("(", ")", "+", "-", "*", "/", "=", "OR", "AND", "NE", "EQ", "LT", "GT", "LE", "GE", ":", "MOD")
def stmts: Parser[Any] = log(expr.*)("stmts")
def stmt: Parser[Expression] = log(expr <~ "\n")("stmt")
def expr: Parser[Expression] = log(term5)("expr")
def term5: Parser[Expression] = (
log((term4 ~ "OR" ~ term4) ^^ { case lhs~o~rhs => BinaryOp("OR", lhs, rhs) })("term5 OR")
| log(term4)("term5 term4")
)
def term4: Parser[Expression] = (
log((term3 ~ "AND" ~ term3) ^^ { case lhs~a~rhs => BinaryOp("AND", lhs, rhs) })("term4 AND")
| log(term3)("term4 term3")
)
def term3: Parser[Expression] = (
log((term2 ~ "<>" ~ term2) ^^ { case lhs~ne~rhs => BinaryOp("NE", lhs, rhs) })("term3 <>")
| log((term2 ~ "=" ~ term2) ^^ { case lhs~eq~rhs => BinaryOp("EQ", lhs, rhs) })("term3 =")
| log((term2 ~ "NE" ~ term2) ^^ { case lhs~ne~rhs => BinaryOp("NE", lhs, rhs) })("term3 NE")
| log((term2 ~ "EQ" ~ term2) ^^ { case lhs~eq~rhs => BinaryOp("EQ", lhs, rhs) })("term3 EQ")
| log(term2)("term3 term2")
)
def term2: Parser[Expression] = (
log((term1 ~ "<" ~ term1) ^^ { case lhs~lt~rhs => BinaryOp("LT", lhs, rhs) })("term2 <")
| log((term1 ~ ">" ~ term1) ^^ { case lhs~gt~rhs => BinaryOp("GT", lhs, rhs) })("term2 >")
| log((term1 ~ "<=" ~ term1) ^^ { case lhs~le~rhs => BinaryOp("LE", lhs, rhs) })("term2 <=")
| log((term1 ~ ">=" ~ term1) ^^ { case lhs~ge~rhs => BinaryOp("GE", lhs, rhs) })("term2 >=")
| log((term1 ~ "LT" ~ term1) ^^ { case lhs~lt~rhs => BinaryOp("LT", lhs, rhs) })("term2 LT")
| log((term1 ~ "GT" ~ term1) ^^ { case lhs~gt~rhs => BinaryOp("GT", lhs, rhs) })("term2 GT")
| log((term1 ~ "LE" ~ term1) ^^ { case lhs~le~rhs => BinaryOp("LE", lhs, rhs) })("term2 LE")
| log((term1 ~ "GE" ~ term1) ^^ { case lhs~ge~rhs => BinaryOp("GE", lhs, rhs) })("term2 GE")
| log(term1)("term2 term1")
)
def term1: Parser[Expression] = (
log((term ~ "+" ~ term) ^^ { case lhs~plus~rhs => BinaryOp("+", lhs, rhs) })("term1 +")
| log((term ~ "-" ~ term) ^^ { case lhs~minus~rhs => BinaryOp("-", lhs, rhs) })("term1 -")
| log((term ~ ":" ~ term) ^^ { case lhs~concat~rhs => BinaryOp(":", lhs, rhs) })("term1 :")
| log(term)("term1 term")
)
def term: Parser[Expression] = (
log((factor ~ "*" ~ factor) ^^ { case lhs~times~rhs => BinaryOp("*", lhs, rhs) })("term *")
| log((factor ~ "/" ~ factor) ^^ { case lhs~div~rhs => BinaryOp("/", lhs, rhs) })("term /")
| log((factor ~ "MOD" ~ factor) ^^ { case lhs~div~rhs => BinaryOp("MOD", lhs, rhs) })("term MOD")
| log(factor)("term factor")
)
def factor: Parser[Expression] = (
log("(" ~> expr <~ ")")("factor (expr)")
| log(("+" | "-") ~ factor ^^ { case op~rhs => UnaryOp(op, rhs) })("factor +-")
//| function |
| log(numericLit ^^ { case x => Number(x/*.toFloat*/) })("factor numericLit")
| log(stringLit ^^ { case s => Literal(s) })("factor stringLit")
| log(ident ^^ { case id => Variable(id) })("factor ident")
)
def parse(s: String) = stmts(new lexical.Scanner(s))
}
My first improvement was like that:
def term3: Parser[Expression] =
log((term2 ~ ("<>" | "=" | "NE" | "EQ") ~ term2) ^^ { case lhs~op~rhs => BinaryOp(op, lhs, rhs) })("term3 <>,=,NE,EQ") |
log(term2)("term3 term2")
It works without OutOfMemoryError but to slow. After viewing doc/scala-devel-docs/examples/parsing/lambda/TestParser.scala I got this source:
def expr: Parser[Expression] = term5
def term5: Parser[Expression] =
log(chainl1(term4, term5, "OR" ^^ {o => (a: Expression, b: Expression) => BinaryOp(o, a, b)}))("term5 OR")
def term4: Parser[Expression] =
log(chainl1(term3, term4, "AND" ^^ {o => (a: Expression, b: Expression) => BinaryOp(o, a, b)}))("term4 AND")
def term3: Parser[Expression] =
log(chainl1(term2, term3, ("<>" | "=" | "NE" | "EQ") ^^ {o => (a: Expression, b: Expression) => BinaryOp(o, a, b)}))("term3 <>,=,NE,EQ")
def term2: Parser[Expression] =
log(chainl1(term1, term2, ("<" | ">" | "<=" | ">=" | "LT" | "GT" | "LE" | "GE") ^^ {o => (a: Expression, b: Expression) => BinaryOp(o, a, b)}))("term2 <,>,...")
def term1: Parser[Expression] =
log(chainl1(term, term1, ("+" | "-" | ":") ^^ {o => (a: Expression, b: Expression) => BinaryOp(o, a, b)}))("term1 +,-,:")
def term: Parser[Expression] =
log(chainl1(factor, term, ("*" | "/" | "MOD") ^^ {o => (a: Expression, b: Expression) => BinaryOp(o, a, b)}))("term *,/,MOD")
def factor: Parser[Expression] =
log("(" ~> expr <~ ")")("factor ()") |
log(("+" | "-") ~ factor ^^ { case op~rhs => UnaryOp(op, rhs) })("factor unary") |
log(function)("factor function") |
log(numericLit ^^ { case x => Number(x/*.toFloat*/) })("factor numLit") |
log(stringLit ^^ { case s => Literal(s) })("factor strLit") |
log(ident ^^ { case id => Variable(id) })("factor ident")
It works fast. I'm sorry but I can not understand how chainl1 function improve my source. I don't understand how it works.