fparsec OperatorPrecedenceParser:如何处理不完整的括号

时间:2017-12-20 08:15:20

标签: parsing f# dayofweek fparsec

此代码将读取此输入“(WEEKEND-SUNDAY)”然后返回“SATURDAY” 但输入“WEEKEND-SUNDAY”仍然返回“SATURDAY”=>这个解析器忽略了最后')'

let pDayOfWeekKeyWords = choice [ 
                          pstring "MONDAY" ;
                          pstring "TUESDAY" ;
                          pstring "WEDNESDAY" ;
                          pstring "THURSDAY" ;
                          pstring "FRIDAY" ;
                          pstring "SATURDAY" ;
                          pstring "SUNDAY" ;
                          pstring "WEEKEND" ;
                          pstring "WEEKDAY" ;
                          pstring "ALL" ] 

let betweenParentheses p =
    between (pstring "(") (pstring ")") p

let opp = new OperatorPrecedenceParser<Set<DayOfWeek>,unit,unit>()
let pExpr = opp.ExpressionParser 
let term = (betweenParentheses pExpr) <|> (pDayOfWeekKeyWords |>> ( fun x -> 
    match x with 
    | "MONDAY" ->  Set.ofList [DayOfWeek.Monday]
    | "TUESDAY" ->  Set.ofList [DayOfWeek.Tuesday]
    | "WEDNESDAY" ->  Set.ofList [DayOfWeek.Wednesday]
    | "THURSDAY" -> Set.ofList [DayOfWeek.Thursday]
    | "FRIDAY" -> Set.ofList [DayOfWeek.Friday]
    | "SATURDAY" -> Set.ofList [DayOfWeek.Saturday]
    | "SUNDAY" -> Set.ofList [DayOfWeek.Sunday]
    | "WEEKDAY" -> Set.ofList [DayOfWeek.Monday ; DayOfWeek.Tuesday ; DayOfWeek.Wednesday;DayOfWeek.Thursday;DayOfWeek.Friday]
    | "WEEKEND" -> Set.ofList [DayOfWeek.Saturday;DayOfWeek.Sunday]
    | "ALL"-> Set.ofList [DayOfWeek.Monday ; DayOfWeek.Tuesday ; DayOfWeek.Wednesday;DayOfWeek.Thursday;DayOfWeek.Friday;DayOfWeek.Saturday;DayOfWeek.Sunday]
    | _ -> failwith "ERROR MESSAGE") )
opp.TermParser <- term 
opp.AddOperator(InfixOperator<Set<DayOfWeek>,unit,unit>("+", skipString "", 1, Associativity.Left, fun x y -> x + y))
opp.AddOperator(InfixOperator<Set<DayOfWeek>,unit,unit>("-", skipString "" , 1, Associativity.Left, fun x y -> x - y))

运行

 run pExpr "MONDAY+(WEEKEND-SUNDAY)"

输出

 Success: set [Monday; Saturday]

问题是

 run pExpr "MONDAY+WEEKEND-SUNDAY)" or run pExpr "MONDAY)+WEEKEND-SUNDAY"

它仍然会返回

 Success: set [Monday; Saturday]

我希望它显示失败:某事......

我错过了什么吗?谢谢

1 个答案:

答案 0 :(得分:3)

在后两个示例中,pexpr在成功解析输入流直到不匹配的右括号后返回。因此,在最后一个示例中,结果实际上是Success: set [Monday]而不是Success: set [Monday; Saturday]

如果未完全使用输入流,您可以使用eof解析器强制出错:

> run (pExpr .>> eof) "MONDAY)+WEEKEND-SUNDAY"
Error in Ln: 1 Col: 7
MONDAY)+WEEKEND-SUNDAY
      ^
Expecting: end of input or infix operator