Add optional constructor to parser

This commit is contained in:
JanUlrich 2022-05-15 23:38:55 +02:00
parent 556995716f
commit d26363ec19
2 changed files with 14 additions and 4 deletions

View File

@ -45,13 +45,16 @@ object Parser {
def constructor[_: P]: P[ParserExpr] = P( kw("new") ~ methodCall).map(m => PConstructor(m.name,m.params))
def classDefinition[_: P]: P[ParserClass] = P(kw("class") ~ ident ~ genericParamList.? ~ kw("extends") ~ typeParser ~ "{" ~ field.rep(0) ~ method.rep(0) ~ "}")
.map(ite => ParserClass(ite._1, ite._2.getOrElse(List()),ite._3, ite._4.toList, ite._5.toList))
def classDefinition[_: P]: P[ParserClass] = P(kw("class") ~ ident ~ genericParamList.? ~ kw("extends") ~ typeParser ~ "{" ~ field.rep(0) ~ constructorDef.? ~ method.rep(0) ~ "}")
.map(ite => ParserClass(ite._1, ite._2.getOrElse(List()),ite._3, ite._4.toList, ite._6.toList))
def constructorDef[_:P] = P(ident ~ methodParameters ~ "{" ~ fieldAssign.rep ~ "}")
def fieldAssign[_:P]:P[_] = P("this." ~ ident.! ~"=" ~ ident.! ~ ";")
def field[_: P]: P[(NType, String)] = P(typeParser ~ ident ~ ";")
def parameterDef[_ : P]: P[(Option[NType], String)] = P((typeParser.? ~ ident) | ident.map((None, _)))
def methodParameters[_ : P] : P[List[(Option[NType],String)]] = ("("~")").map(it => List()) | ("(" ~ parameterDef ~ ("," ~ parameterDef).rep(0) ~ ")")
.map(ite => (ite._1, ite._2) +: ite._3.toList)
def method[_: P]: P[ParserMethod] =
P(parameterDef ~ (("("~")").map(it => List()) | ("(" ~ parameterDef ~ ("," ~ parameterDef).rep(0) ~ ")")
.map(ite => (ite._1, ite._2) +: ite._3.toList))
P(parameterDef ~ methodParameters
~ "{" ~ kw("return") ~ expr ~ ";" ~ "}")
.map(ite => ParserMethod(ite._1, ite._2, ite._3, ite._4))
def genericParamList[_: P]: P[List[(NType,NType)]] =

View File

@ -62,4 +62,11 @@ class ParserTest extends FunSuite {
println(fastparse.parse("class List<A extends Object> extends Object{asd(){ return this; }get(){ return this.head;}}"
, hb.dhbw.Parser.program(_)))
}
test("Konstruktor"){
val parsed = fastparse.parse("class Pair<X extends Object, Y extends Object> extends Object{\n X fst;\n Y snd;\n Pair(fst, snd) {\n this.fst=fst;\n this.snd=snd;\n }\n}"
, hb.dhbw.Parser.program(_))
assert(parsed.isSuccess)
println(parsed.get)
}
}