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

fparsec OperatorPrecedenceParser : How to deal with incomplete parentheses

此代码将读取此输入“(WEEKEND-SUNDAY)”,然后 return "SATURDAY" 但输入 "WEEKEND-SUNDAY)" 仍然 return "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"

它仍然return

 Success: set [Monday; Saturday]

我想让它显示 Failure: something..

我错过了什么吗?谢谢

在后两个示例中 pexpr returns 在成功解析输入流直到不匹配的右括号之后。所以,在最后一个例子中,结果实际上是 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