git @ Cat's Eye Technologies Argyle / 9fd2f1c
Count unclosed parentheses, even after a complete expression. Chris Pressey 6 months ago
2 changed file(s) with 24 addition(s) and 5 deletion(s). Raw diff Collapse all Expand all
3535 A well-formed S-expression must have an opening parenthesis.
3636
3737 add)
38 ???> Unexpected characters
38 ???> Incomplete expression
3939
4040 A well-formed S-expression must have an closing parenthesis.
4141
4242 (add
43 ???> Failed to parse
43 ???> Incomplete expression
4444
4545 A well-formed S-expression does parse to an AST and thence to an ABT.
4646
2727 parse input =
2828 if all isSpace input
2929 then Error EmptyInput
30 else case parseExpr (skipWhitespaceAndComments input) 0 of
31 Right (result, rest, 0) -> Complete result rest
32 Right (result, rest, count) -> Incomplete count input
30 else case parseFirstExpr (skipWhitespaceAndComments input) of
31 Right (result, rest) ->
32 -- After parsing a complete expression, check for any unclosed parens
33 case countUnclosedParens rest of
34 0 -> Complete result rest
35 n -> Incomplete n input
3336 Left (UnmatchedOpenParen count) -> Incomplete count input
3437 Left err -> Error err
38
39 -- Count unclosed parentheses in remaining input
40 countUnclosedParens :: String -> Int
41 countUnclosedParens = go 0
42 where
43 go count "" = count
44 go count (c:cs) = case c of
45 '(' -> go (count + 1) cs
46 ')' -> go (count - 1) cs
47 _ -> go count cs
48
49 -- Parse first expression without paren counting
50 parseFirstExpr :: String -> Either ParseError (ConsList, String)
51 parseFirstExpr input = case parseExpr input 0 of
52 Right (result, rest, _) -> Right (result, rest)
53 Left err -> Left err
3554
3655 -- Expression parser now tracks paren count
3756 parseExpr :: String -> Int -> Either ParseError (ConsList, String, Int)