ocaml: phase 2 for/while loops (+5 tests, 194 total)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 52s

Parser: for i = lo to|downto hi do body done, while cond do body done.
AST: (:for NAME LO HI :ascend|:descend BODY) and (:while COND BODY).
Eval re-binds the loop var per iteration; both forms evaluate to unit.
This commit is contained in:
2026-05-08 08:11:13 +00:00
parent a11f3c33b6
commit 9b8b0b4325
4 changed files with 98 additions and 1 deletions

View File

@@ -573,6 +573,33 @@
(begin (advance-tok!) (one) (loop)))))
(loop)
(cons :match (cons scrut (list cases)))))))))
(define parse-for
(fn ()
(let ((name (ocaml-tok-value (consume! "ident" nil))))
(begin
(consume! "op" "=")
(let ((lo (parse-expr-no-seq)))
(let ((dir
(cond
((at-kw? "to") (begin (advance-tok!) :ascend))
((at-kw? "downto") (begin (advance-tok!) :descend))
(else (error "ocaml-parse: expected to/downto in for")))))
(let ((hi (parse-expr-no-seq)))
(begin
(consume! "keyword" "do")
(let ((body (parse-expr)))
(begin
(consume! "keyword" "done")
(list :for name lo hi dir body)))))))))))
(define parse-while
(fn ()
(let ((cond-expr (parse-expr-no-seq)))
(begin
(consume! "keyword" "do")
(let ((body (parse-expr)))
(begin
(consume! "keyword" "done")
(list :while cond-expr body)))))))
(set!
parse-expr-no-seq
(fn
@@ -582,6 +609,8 @@
((at-kw? "let") (begin (advance-tok!) (parse-let)))
((at-kw? "if") (begin (advance-tok!) (parse-if)))
((at-kw? "match") (begin (advance-tok!) (parse-match)))
((at-kw? "for") (begin (advance-tok!) (parse-for)))
((at-kw? "while") (begin (advance-tok!) (parse-while)))
(else (parse-tuple)))))
(set!
parse-expr