megaparsack
megaparsack copied to clipboard
Unbound variable from mutual reference
Hi Alexis,
I've been playing with this wonderful tool you've made (thank you!) and run into something that is unexpected.
I was following the docs to parse "prefix" function calls, like f(x, y). And the code below worked like a charm.
(define num/p (syntax/p (token/p 'NUM)))
(define id/p (syntax/p (token/p 'ID)))
(define prefix/p
(syntax/p
(do [f <- id/p]
(token/p 'LPAREN)
[xs <- (many/p expr/p #:sep (token/p 'COMMA))]
(token/p 'RPAREN)
(pure (prefix f xs)))))
(define expr/p
(or/p (try/p prefix/p)
num/p
id/p))
Then, when I tried to parse infix function calls, like "x + y", however, things became confusing. Here's my code.
(define infix/p
(syntax/p
(do [l <- expr/p]
[f <- id/p]
[r <- expr/p]
(pure (infix f l r)))))
(define expr/p
(or/p (try/p prefix/p)
(try/p infix/p)
num/p
id/p))
It didn't compile and Racket yelled at me:
expr/p: undefined;
cannot reference an identifier before its definition
in module: "my-directory/parser.rkt"
Context (plain):
my-diretory.emacs.d/elpa/racket-mode-20240130.2013/racket/repl.rkt:322:0 configure/require/enter
The infix/p doesn't look very different from the prefix/p, which refers to expr/p as well. I wonder if it's by design or it might be a bug. Thanks a lot!