diff --git a/AGENTS.md b/AGENTS.md index 5255541ed83..4ccfd03058e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -50,6 +50,8 @@ The Makefile’s targets build on each other in this order: ## ⚠️ Critical Guidelines & Common Pitfalls +- **COMMIT YOUR CHANGES** - After completing ANY meaningful work (bug fix, feature, refactor, parity improvement), you MUST commit immediately. Do not leave work uncommitted. Do not move on to the next task without committing first. This is the most important rule. + - **We are NOT bound by OCaml compatibility** - The ReScript compiler originated as a fork of the OCaml compiler, but we maintain our own AST and can make breaking changes. Focus on what's best for ReScript's JavaScript compilation target. - **Never modify `parsetree0.ml`** - Existing PPX (parser extensions) rely on this frozen v0 version. When changing `parsetree.ml`, always update the mapping modules `ast_mapper_from0.ml` and `ast_mapper_to0.ml` to maintain PPX compatibility while allowing the main parsetree to evolve @@ -74,6 +76,14 @@ The Makefile’s targets build on each other in this order: - **Handle concurrent agent work gracefully** - If compilation fails due to errors in code you didn't touch, another agent may be actively working on that part of the codebase. Do NOT modify their files and NEVER use `git stash`. Simply wait 30 seconds and retry the build. Repeat this until compilation succeeds—the other agent will fix their changes shortly. +- **Do NOT revert large changes** - If a task impacts a large amount of code, do NOT revert and give up. Complete the large task as requested. The user is aware it's a big change and expects you to follow through. + +- **Do NOT switch tasks when things get hard** - If you're working on a difficult task, do NOT abandon it to work on something easier. Complete the current task FIRST, then move on to the next one. Switching tasks loses valuable context and leaves work incomplete. + +- **Embrace complexity - everything must be done** - Do not shy away from complex tasks or defer them hoping for an easier path. Every item on the task list must eventually be completed, so you might as well dig in now. Complex problems don't get easier by avoiding them—they just stay unsolved. Tackle the hard parts head-on with full attention. The satisfaction of solving a difficult problem far outweighs the temporary comfort of picking low-hanging fruit. + +- **ALWAYS commit before moving on** - Before starting a new task, before investigating a problem, before taking a break: COMMIT. Use `git add && git commit -m "description"`. No exceptions. + ## Compiler Architecture ### Compilation Pipeline @@ -642,81 +652,41 @@ When the Rust printer output differs from OCaml, common issues include: ### AST Parity Test Suite -The AST parity test suite (`scripts/test_parser_ast_parity.sh`) comprehensively compares the Rust and OCaml parser outputs across multiple dimensions: - -**Tests performed:** -1. **sexp parity** - AST structure matches between OCaml and Rust -2. **sexp-locs parity** - AST structure + locations match -3. **sexp0-locs parity** - parsetree→parsetree0→sexp output matches (single-trip) -4. **Roundtrip structure parity** - After parsetree→parsetree0→parsetree, both parsers produce same AST -5. **Roundtrip location parity** - Locations preserved correctly through parsetree0 conversion -6. **Binary parity** - Marshalled parsetree0 is byte-identical (critical for PPX compatibility) - -#### Running the AST Parity Tests +**This is the primary test for verifying Rust compiler parity with OCaml.** ```bash -# Run all tests (default: 16 parallel jobs) -./scripts/test_parser_ast_parity.sh - -# Test a single file (fastest for iteration) -./scripts/test_parser_ast_parity.sh tests/syntax_tests/data/printer/expr/apply.res - -# Test files matching a pattern -./scripts/test_parser_ast_parity.sh "printer/expr" - -# Quick mode - stop on first failure -./scripts/test_parser_ast_parity.sh --quick - -# Verbose mode - show each file being tested -./scripts/test_parser_ast_parity.sh -v tests/syntax_tests/data/printer/expr/apply.res - -# Adjust parallelism -./scripts/test_parser_ast_parity.sh -j8 +# See detailed usage information +./scripts/test_parser_ast_parity.sh --info ``` -#### Regression Tracking +**⚠️ Use `--binary-only` for most testing to save resources:** -The parity test suite tracks regressions using baseline files in `tests/parity_baselines/`. Each test type has its own baseline: - -- `sexp_locs.txt` - Files passing sexp-locs parity -- `binary.txt` - Files passing binary parity -- `sexp0_locs.txt` - Files passing sexp0-locs parity -- `binary0.txt` - Files passing binary0 parity -- `roundtrip_structure.txt` - Files passing roundtrip structure parity -- `roundtrip_locs.txt` - Files passing roundtrip location parity - -**How it works:** -1. When a file passes a test, it's added to the corresponding baseline (append-only) -2. On subsequent runs, if a file that's in the baseline fails, it's flagged as a **regression** -3. Regressions are reported prominently and cause the test to fail - -**Why this matters:** -- Prevents accidentally breaking files that were already working -- Makes it easy to see which files regressed after a change -- Baselines grow monotonically as parity improves -- Committed to git so regressions are caught in CI/PRs +```bash +# Test only bsc-ast output - USE THIS FOR ITERATION +./scripts/test_parser_ast_parity.sh --binary-only -**When you see a regression:** -1. The output will clearly list which files regressed for each test type -2. Fix the regression before moving on - don't let parity decrease -3. The baseline files should never be manually edited to remove entries +# Test a single file in binary-only mode (fastest) +./scripts/test_parser_ast_parity.sh -b tests/syntax_tests/data/printer/expr/apply.res -#### Quick Iteration Workflow +# Stop on first failure +./scripts/test_parser_ast_parity.sh -b --quick +``` -When fixing parity issues, use single-file mode for fast feedback: +Since AST (sexp) parity is already achieved, you only need to run the full test suite occasionally to verify nothing regressed. The `--binary-only` flag skips sexp tests, binary0, and roundtrip tests—only testing the production `bsc -bs-ast` output: ```bash -# 1. Find a failing file from the test output -# 2. Test just that file -./scripts/test_parser_ast_parity.sh tests/syntax_tests/data/printer/expr/apply.res +# Full test suite - run occasionally, not on every change +./scripts/test_parser_ast_parity.sh +``` -# 3. Make changes to Rust parser -# 4. Rebuild -cargo build --manifest-path compiler-rust/Cargo.toml --release +The test suite compares: +- **bsc-ast** - Full `bsc -bs-ast` output (production format with dependency extraction) +- **binary0** - Marshalled parsetree0 (byte-identical for PPX tools) +- **sexp-locs** - Parser AST with locations (readable diffs for debugging) +- **sexp0-locs** - Parsetree0 sexp output +- **roundtrip** - parsetree → parsetree0 → parsetree conversion -# 5. Re-test the single file -./scripts/test_parser_ast_parity.sh tests/syntax_tests/data/printer/expr/apply.res -``` +**Regression tracking**: Files that pass are added to baselines in `tests/parity_baselines/`. If a passing file starts failing, it's flagged as a regression and the test fails. This ensures parity can only increase. #### Known sexp-locs Parity Issues (5 files remaining at 99.5%) @@ -748,3 +718,118 @@ The following files have known location parity differences that require more com - **Explicit contexts** - `CompilationContext`, `TypeContext` passed through pipeline - **Arena-per-compilation** - Type arenas owned by `TypeContext`, not shared - **No `static mut`** - All mutable state in explicit contexts + +### Binary AST Parity (Completed for Current Parsetree) + +**Status:** ✅ Current parsetree format (the active AST format) has 100% binary parity. + +The binary AST format uses OCaml's Marshal serialization, which includes back-references for shared objects. When OCaml creates two references to the same memory object, Marshal writes a shared reference (CODE_SHARED8/16/32) instead of duplicating the data. + +**What's working:** +- Current parsetree binary: 100% parity (1049/1049 files identical) +- sexp-locs: 100% parity (1049/1049 files identical) + +**parsetree0 / binary0 - NOT A PRIORITY:** + +⚠️ **Do not work on parsetree0 or binary0 parity at this time.** These involve the frozen PPX-compatible format and will be addressed later. The code must still compile, but parity differences are expected and acceptable for now. + +- binary0 has 985 differing files (this is fine) +- roundtrip (parsetree→parsetree0→parsetree) has differences (this is fine) + +**Key implementation points:** + +- **ParseArena** (`compiler-rust/src/parse_arena.rs`): Arena for positions and locations. Same `PosIdx`/`LocIdx` = same object for marshalling purposes. + - The "none" position/location are pre-allocated at index 0 + +- **Marshal writer** (`compiler-rust/src/binary_ast/marshal.rs`): Tables for sharing: + - `position_idx_table`: Maps `PosIdx` to object counter for arena-based position sharing + - `location_idx_table`: Maps `LocIdx` to object counter for arena-based location sharing + +**Testing:** + +```bash +# Run full parity test suite +./scripts/test_parser_ast_parity.sh + +# Test a single file for quick iteration +./scripts/test_parser_ast_parity.sh tests/syntax_tests/data/printer/expr/apply.res + +# Compare binary output directly +./_build/install/default/bin/res_parser -print binary FILE > /tmp/ocaml.bin +./compiler-rust/target/release/res_parser_rust -print binary FILE > /tmp/rust.bin +diff <(xxd /tmp/ocaml.bin) <(xxd /tmp/rust.bin) +``` + +**Debugging tips:** + +- When binary differs, look at the hex dump: shared references show up as `04 XX` (CODE_SHARED8), `05 XX XX` (CODE_SHARED16) +- The offset after the opcode is the "distance back" in object counter terms +- If Rust has more bytes, it's likely not sharing something OCaml shares +- If Rust has fewer bytes, it's likely sharing something OCaml doesn't share +- Add debug prints in `marshal.rs` to trace object counter values + +**Understanding OCaml's value sharing (critical for parity):** + +OCaml's Marshal format uses **pointer identity** for sharing. When two AST nodes reference the same memory object (same pointer), Marshal writes a shared reference instead of duplicating the data. This is NOT about string interning or content equality—it's about whether the OCaml code constructs a NEW value or passes an EXISTING value by reference. + +**⚠️ CRITICAL: Explicit sharing, NOT automatic interning** + +The Rust implementation must **explicitly mirror OCaml's allocation patterns**. Do NOT try to automatically intern or deduplicate values based on content. Instead: + +1. **Study the OCaml code** to understand when it passes a reference vs. constructs a new value +2. **Explicitly share** in Rust when OCaml passes the same reference (use the same arena index) +3. **Explicitly allocate new** in Rust when OCaml constructs a new value (push a new arena entry) + +This means the Rust parser code must be structured to match OCaml's data flow: +- If OCaml binds a value to a variable and passes that variable to multiple places, Rust should do the same with an arena index +- If OCaml constructs a new record/value at each use site, Rust should push a new arena entry each time + +**Do NOT use content-based deduplication** (e.g., "if we've seen this string before, reuse the index"). OCaml doesn't do this—it uses pointer identity from the actual code flow. The only way to achieve parity is to replicate the exact same allocation patterns. + +**⚠️ STRING SHARING: Use StrIdx, NOT content-based interning** + +For strings in the AST (identifiers, labels, file names), use `StrIdx` arena indices to control sharing: +- **Same StrIdx = same object** - Will be shared in marshal output via back-references +- **Different StrIdx = different objects** - Even if content is identical, will NOT be shared +- **Do NOT intern strings automatically** - Don't use hash-based deduplication in the marshal writer +- **Pass StrIdx by reference** - When OCaml passes the same string reference, use the same StrIdx in Rust + +Example: For punned labeled arguments like `~compare`, the label and identifier should use the SAME `StrIdx` because OCaml reuses the same string pointer. Create the StrIdx once and pass it to both the `ArgLabel` and the `Longident`. + +To achieve binary parity, you MUST study the OCaml sources (tokenizer, parser, marshaller) to understand: +1. **When does OCaml construct NEW values?** - Look for `{...}` record literals, `::` cons operations, function calls that return new allocations +2. **When does OCaml pass EXISTING values by reference?** - Look for variables being passed directly, pattern match bindings that propagate references + +Examples of what to look for in OCaml: +```ocaml +(* NEW allocation - each call creates a fresh string *) +let lid = Longident.Lident name in ... + +(* SAME reference - passing the same variable *) +let loc = start_pos in +{ pexp_loc = loc; ... } (* loc is the SAME object as start_pos *) + +(* NEW allocation - record literal creates new record *) +{ txt = s; loc = l } (* This is always a new allocation *) +``` + +The Rust implementation must replicate these EXACT allocation patterns using the arena: +- When OCaml creates a new value, Rust should push a new entry to the arena +- When OCaml passes the same value, Rust should reuse the same arena index +- The arena index becomes the "pointer identity" for marshalling purposes + +**Do NOT assume values are always interned.** Some values may be shared in certain contexts but not others, depending on how the OCaml code flows. Always trace the exact code path in the OCaml implementation. + +**⚠️ CORE PRINCIPLE: Replicate OCaml's memory allocation, not content** + +OCaml constructs new values OR passes by reference. The Marshal implementation shares values according to how they were allocated by memory management—NOT based on content equality. We do NOT need content-based interning because that's not how OCaml works. Instead: + +1. **Study the OCaml source code** - Look at how values are constructed and passed. If a value is bound to a variable and that variable is passed to multiple places, those are all the same reference. + +2. **Create an arena for types that need sharing** - If the OCaml code shares values of a particular type (e.g., `Location.t`, `Longident.t`), ensure we have an arena for that type in `ParseArena`. + +3. **Pass by arena index, not by value** - When the OCaml code passes a reference, use the same arena index in Rust. Do NOT push a new value into the arena—reuse the existing index. + +4. **Push new values only when OCaml allocates** - When OCaml constructs a fresh value (record literal, function call returning new allocation), push a new entry to the arena. + +If we do this consistently—replicating OCaml's exact allocation and reference patterns—the binary AST WILL match byte-for-byte. diff --git a/CLAUDE.md b/CLAUDE.md index 7a64d8d92c9..a6f89b6f70d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,3 +1,67 @@ # Claude Code Instructions Please read and follow the instructions in [AGENTS.md](./AGENTS.md). + +## ⚠️ CRITICAL: COMMIT YOUR CHANGES + +**You MUST commit after completing any meaningful work.** This is non-negotiable. + +### When to commit: +- ✅ After fixing a bug or issue +- ✅ After implementing a feature or part of a feature +- ✅ After refactoring code +- ✅ After improving parity (even 1 more test passing) +- ✅ Before switching to a different task +- ✅ Before investigating a problem (commit WIP first) +- ✅ At natural stopping points + +### How to commit: +```bash +# Stage specific files (preferred) +git add path/to/changed/files + +# Commit with descriptive message +git commit -m "$(cat <<'EOF' +Short description of what changed + +Co-Authored-By: Claude +EOF +)" +``` + +**DO NOT** leave work uncommitted. If you made changes, commit them. + +## CRITICAL: Document Your Learnings + +**When you discover something useful, ALWAYS add it to CLAUDE.md or AGENTS.md.** + +This includes: +- Commands that work (or don't work) +- Solutions to problems you encountered +- Gotchas or edge cases you discovered +- Debugging techniques that helped +- Patterns that solved an issue + +**Don't let knowledge be lost.** If you figured something out the hard way, document it so you (or another agent) don't have to figure it out again. + +## CRITICAL: Protect Uncommitted Work + +**NEVER revert or discard uncommitted changes.** This has caused lost work multiple times. + +When you have uncommitted changes and encounter issues: + +1. **ALWAYS commit work-in-progress first** before any troubleshooting: + ```bash + git add -A && git commit -m "WIP: [description of current state]" + ``` + +2. **NEVER run these commands when there are uncommitted changes:** + - `git checkout -- ` + - `git checkout HEAD -- ` + - `git restore ` + - `git reset --hard` + - `git stash` (unless you immediately `git stash pop`) + +3. **Make small, frequent commits** - every meaningful change should be committed, even if incomplete. Use "WIP:" prefix for work-in-progress commits. + +4. **If tests fail or there are regressions**, commit the current state first, THEN investigate. You can always revert a commit, but you cannot recover uncommitted changes. diff --git a/RALPH_PROMPT.md b/RALPH_PROMPT.md new file mode 100644 index 00000000000..094d83ffc1e --- /dev/null +++ b/RALPH_PROMPT.md @@ -0,0 +1,209 @@ +# Ralph Loop: Syntax Parity + +You are working on achieving **byte-for-byte parity** between the Rust ReScript parser/printer and the OCaml reference implementation for ALL syntax tests. + +## Core Principle: 1:1 OCaml Port + +**This is a 1:1 rewrite of the OCaml implementation in idiomatic Rust.** + +- **Study the OCaml code first** - Before writing ANY code, read and understand the corresponding OCaml implementation. Don't guess or reverse-engineer from output. +- **Match the logic exactly** - The Rust code should follow the same algorithm, control flow, and edge case handling as OCaml. +- **Use idiomatic Rust** - Translate OCaml patterns to Rust equivalents (e.g., `Option` for `option`, `match` for pattern matching, `Vec` for lists). +- **NO global state** - This is the ONLY architectural difference from OCaml. Pass all state explicitly through function parameters and return values. Use `&mut` references or context structs instead of mutable global refs. + +**Reference files to study:** +| OCaml File | Purpose | +|------------|---------| +| `compiler/syntax/src/res_printer.ml` | Main printer (~6100 lines) | +| `compiler/syntax/src/res_comments_table.ml` | Comment attachment algorithm | +| `compiler/syntax/src/res_doc.ml` | Document pretty-printing | +| `compiler/syntax/src/res_parens.ml` | Parenthesization rules | + +When you encounter a parity issue: +1. Find the corresponding function in the OCaml code +2. Understand what it does and WHY +3. Ensure the Rust implementation matches that logic exactly +4. Only then make changes + +## Your Task + +Read `RALPH_TODO.md` and complete the next unchecked task. After completing a task: +1. Mark it `[x]` complete in `RALPH_TODO.md` +2. Update the status counts at the top +3. Commit your changes with an atomic commit +4. If all tasks are complete, output "RALPH_COMPLETE" + +## ⚠️ WARNING: Infinite Loop in Parser + +**There is currently an infinite loop somewhere in the parsing code.** When running the parser or tests, you MUST always use timeouts to prevent stalling: + +```bash +# Use timeout for all parser invocations +timeout 10s ./compiler-rust/target/release/res_parser_rust + +# Use timeout for test runs +timeout 120s bash -c 'PARSER=rust ./scripts/test_syntax.sh 2>&1 | tail -40' + +# Use timeout for cargo build (in case of proc macro issues) +timeout 60s cargo build --manifest-path compiler-rust/Cargo.toml --release +``` + +If a command hangs, it likely hit the infinite loop. Identify which file triggered it and investigate the parsing logic for that construct. + +## Critical Rules + +1. **ALWAYS read the OCaml implementation first** - Don't guess. Study the OCaml source to understand the correct behavior. The goal is a faithful port, not a reimagining. + +2. **Run tests frequently** - After each change: + ```bash + PARSER=rust ./scripts/test_syntax.sh 2>&1 | tail -40 + ``` + +3. **Commit after each fix** - Every time tests improve, commit immediately. Include the test results in the commit message: + ```bash + git add && git commit -m "Fix: + + Syntax tests: X/Y passed (Z%) + + Co-Authored-By: Claude " + ``` + + Get the current status by running: + ```bash + PARSER=rust ./scripts/test_syntax.sh 2>&1 | tail -20 + ``` + +4. **Focus on root causes** - Many failures share the same root cause (usually comment handling). Fix the underlying issue rather than individual symptoms. + +5. **Never modify expected files** - The `tests/syntax_tests/data/*/expected/` files contain the OCaml reference output. Fix the Rust implementation to match them. + +## Key Files + +| File | Purpose | +|------|---------| +| `compiler-rust/src/parser/printer2.rs` | Main printer implementation | +| `compiler-rust/src/parser/comment_table.rs` | Comment attachment logic | +| `compiler-rust/src/parser/ml_printer.rs` | ML AST printer (for `-print ml`) | +| `compiler-rust/src/parser/diagnostics.rs` | Error messages and recovery | +| `compiler/syntax/src/res_printer.ml` | OCaml reference (6100 lines) | +| `compiler/syntax/src/res_comments_table.ml` | OCaml comment handling | +| `compiler/syntax/src/res_diagnostics.ml` | OCaml error messages | +| `compiler/syntax/src/res_outcome_printer.ml` | OCaml ML printer | + +## Debugging Workflow + +```bash +# View diff for a specific failing test +diff tests/syntax_tests/data/printer/comments/expected/FILE.txt \ + tests/temp/syntax_tests/data/printer/comments/expected/FILE.txt + +# Test a single file (printer mode - default) +./compiler-rust/target/release/res_parser_rust tests/syntax_tests/data/printer/FILE.res + +# Test with error recovery mode (for parsing/errors tests) +./compiler-rust/target/release/res_parser_rust -recover -print ml tests/syntax_tests/data/parsing/errors/FILE.res + +# Test with AST conversion (for ast-mapping tests) +./compiler-rust/target/release/res_parser_rust -test-ast-conversion -jsx-version 4 tests/syntax_tests/data/ast-mapping/FILE.res + +# Test with JSX PPX (for ppx/react tests) +./compiler-rust/target/release/res_parser_rust -jsx-version 4 tests/syntax_tests/data/ppx/react/FILE.res + +# Compare with OCaml +./_build/install/default/bin/res_parser tests/syntax_tests/data/printer/FILE.res +./_build/install/default/bin/res_parser -recover -print ml tests/syntax_tests/data/parsing/errors/FILE.res + +# Build after changes +cargo build --manifest-path compiler-rust/Cargo.toml --release +``` + +## Common Issues to Fix + +### Printer Issues +1. **Comment placement** - Comments attach to wrong AST nodes or get lost +2. **Trailing comments** - Comments after expressions not preserved +3. **Blank line preservation** - Blank lines around comments should be kept +4. **JSX in expressions** - JSX elements inside switch/match arms +5. **Functor parameter comments** - Comments on module functor parameters + +### Error Recovery Issues +6. **Error message locations** - Line/column numbers in error messages must match OCaml +7. **Recovery AST output** - The recovered AST printed as ML must match exactly +8. **Error hole placement** - `[%rescript.exprhole]` placeholders for missing expressions +9. **Array access syntax** - OCaml uses `arr.(i)` syntax vs `Array.get arr i` + +### PPX/AST Issues +10. **JSX transformation** - React PPX output must match OCaml's `jsx-version 4` +11. **AST conversion** - `--test-ast-conversion` output must match + +## OCaml → Rust Translation Patterns + +When porting OCaml code, use these Rust equivalents: + +| OCaml | Rust | +|-------|------| +| `option` | `Option` | +| `list` | `Vec` (or `&[T]` for parameters) | +| `ref` | `&mut T` parameter or field in context struct | +| `Hashtbl.t` | `HashMap` or field in `CommentTable` | +| `match x with` | `match x { }` | +| `let rec` | Regular `fn` (Rust has no `rec` keyword) | +| `fun x -> ...` | `\|x\| ...` or `fn` | +| `x :: xs` | `if let [x, xs @ ..] = slice` or iterator | +| `List.iter` | `.iter().for_each()` or `for` loop | +| `List.map` | `.iter().map().collect()` | +| `Printf.sprintf` | `format!()` | +| `^` (string concat) | `format!()` or `.push_str()` | + +**Global state elimination example:** + +```ocaml +(* OCaml with global state *) +let comments_table = Hashtbl.create 100 +let attach_comment loc comment = + Hashtbl.add comments_table loc comment +``` + +```rust +// Rust with explicit state +struct CommentTable { + leading: HashMap>, + trailing: HashMap>, +} + +fn attach_comment(table: &mut CommentTable, loc: PosRange, comment: Comment) { + table.leading.entry(loc).or_default().push(comment); +} +``` + +## Progress Tracking + +The current status is tracked in `RALPH_TODO.md`. Update it as you complete tasks. + +Run the full test suite to see current parity: +```bash +PARSER=rust ./scripts/test_syntax.sh 2>&1 | tail -30 +``` + +The test categories are: +| Category | Description | +|----------|-------------| +| printer | Pretty-printing tests (187 files) | +| conversion | ML/Reason to ReScript conversion | +| parsing/errors | Error recovery mode tests | +| parsing/grammar | Grammar parsing tests | +| parsing/recovery | Recovery mode tests | +| parsing/infiniteLoops | Infinite loop prevention tests | +| ppx/react | JSX PPX transformation tests | +| ast-mapping | AST conversion tests | + +## Exit Condition + +When ALL syntax tests pass (not just printer tests), output exactly: +``` +RALPH_COMPLETE +``` + +This triggers the Ralph plugin's `--completion-promise` to stop the loop. + +**Do NOT stop when only printer tests pass.** Continue until `PARSER=rust ./scripts/test_syntax.sh` shows 0 failures across ALL categories. diff --git a/RALPH_SETUP.md b/RALPH_SETUP.md new file mode 100644 index 00000000000..1a1a22f94f4 --- /dev/null +++ b/RALPH_SETUP.md @@ -0,0 +1,341 @@ +# How to Create a Ralph Loop Setup + +Ralph is an autonomous AI agent loop that runs repeatedly until all tasks are complete. Each iteration starts with fresh context, so progress must be tracked in files and git history. + +## Core Concept + +```bash +while true; do claude --dangerously-skip-permissions --print "$(cat PROMPT.md)"; done +``` + +> **Note:** `code` is an alias for `claude` with all permissions enabled. + +The agent reads the same prompt each iteration, but sees different file state. Progress persists in: +1. **Files** - The TODO checklist, source code changes +2. **Git history** - Commits showing what's been done + +## Files You Need + +### 1. `RALPH_PROMPT.md` - Agent Instructions + +This tells the agent what to do, how to do it, and when to stop. + +```markdown +# Ralph Loop: [Task Name] + +[Brief description of the goal] + +## Core Principle + +[Key constraints or approach requirements] + +## Your Task + +Read `RALPH_TODO.md` and complete the next unchecked task. After completing a task: +1. Mark it `[x]` complete in `RALPH_TODO.md` +2. Commit your changes with an atomic commit +3. If all tasks are complete, output "RALPH_COMPLETE" + +## Critical Rules + +1. [Rule 1 - e.g., always read reference code first] +2. [Rule 2 - e.g., run tests after each change] +3. [Rule 3 - e.g., commit after each fix] + +## Key Files + +| File | Purpose | +|------|---------| +| `path/to/main/file.rs` | Main implementation | +| `path/to/reference.ml` | Reference to study | + +## Commands Reference + +```bash +# Build +[build command] + +# Test +[test command] + +# Debug +[debug command] +``` + +## Exit Condition + +When all tasks in `RALPH_TODO.md` are checked `[x]`, output: +``` +RALPH_COMPLETE +``` +``` + +### 2. `RALPH_TODO.md` - Progress Tracking + +A checklist that the agent updates as it works. Organize by priority/phase. + +```markdown +# [Task Name] TODO + +**Last Updated:** [date] +**Status:** X/Y tasks complete + +--- + +## Phase 1: [Category] (Highest Priority) + +Explanation of why this phase is first. + +- [ ] Task 1 description +- [ ] Task 2 description +- [ ] Task 3 description + +--- + +## Phase 2: [Category] + +- [ ] Task 4 description +- [ ] Task 5 description + +--- + +## Commands Reference + +```bash +[useful commands for the agent] +``` + +--- + +## Notes + +[Any context that helps the agent understand the work] +``` + +## Best Practices + +### 1. Organize by Root Cause, Not Symptoms + +Bad: +```markdown +- [ ] Fix test file A +- [ ] Fix test file B +- [ ] Fix test file C +``` + +Good: +```markdown +## Phase 1: Fix Comment Handling (Root Cause) +- [ ] Study OCaml comment attachment algorithm +- [ ] Fix trailing comment preservation + +## Phase 2: Test Files (Will Auto-Fix After Phase 1) +- [ ] test file A +- [ ] test file B +``` + +### 2. Include Reference Material + +Always point the agent to authoritative sources: + +```markdown +## Reference Implementation + +Study these files before making changes: +- `path/to/reference/implementation.ml` +- `path/to/tests/expected/output.txt` +``` + +### 3. Make Progress Measurable + +Include commands to measure progress: + +```markdown +## Measuring Progress + +```bash +# Run tests and count passing +./run_tests.sh 2>&1 | grep -E "passed|failed" + +# Current baseline: 45/100 passing +# Target: 100/100 passing +``` +``` + +### 4. Enforce Atomic Commits + +The agent should commit after every improvement: + +```markdown +## Commit Rules + +- Commit after EVERY test that starts passing +- Use descriptive messages: "Fix: [specific thing fixed]" +- Never batch multiple unrelated fixes in one commit +``` + +### 5. Provide Debugging Commands + +```markdown +## Debugging + +```bash +# View diff for failing test +diff expected.txt actual.txt + +# Test single file +./tool --test single_file.txt + +# Compare with reference +./reference_tool file.txt > expected.txt +./our_tool file.txt > actual.txt +diff expected.txt actual.txt +``` +``` + +### 6. Set Clear Exit Condition + +```markdown +## Exit Condition + +Output "RALPH_COMPLETE" when: +- All items in RALPH_TODO.md are checked [x] +- All tests pass (X/X) +- No regressions introduced +``` + +## Running the Loop + +### Recommended: Bash Loop + +Use the included `ralph.sh` script: + +```bash +./ralph.sh # Uses RALPH_PROMPT.md by default +./ralph.sh MY_PROMPT.md # Or specify a custom prompt file +``` + +The script: +- Tracks iteration count +- Logs timestamps for each iteration +- Detects `RALPH_COMPLETE` → exits successfully +- Detects `RALPH_BLOCKED` → exits with error for human intervention +- Fresh context each iteration (never fills up) + +**Manual version** (if you want to customize): + +```bash +while true; do + cat RALPH_PROMPT.md | claude --dangerously-skip-permissions --print | tee /tmp/ralph_output.txt + + if grep -q "RALPH_COMPLETE" /tmp/ralph_output.txt; then + echo "Ralph loop complete!" + break + fi +done +``` + +**Why bash loop over the plugin:** +- **Fresh context each iteration** - Escapes bad reasoning loops, never fills up +- **Unlimited iterations** - Can run for days on large task lists +- **Multiple exit conditions** - Can detect "COMPLETE" vs "BLOCKED" vs errors +- **Custom logic** - Add delays, notifications, logging between iterations +- **Progress in files** - All state is in RALPH_TODO.md + git, not in context + +### Alternative: Claude Code Ralph Plugin + +The plugin keeps context within a single session (doesn't clear between iterations): + +```bash +/ralph-loop "$(cat RALPH_PROMPT.md)" --max-iterations 50 --completion-promise "RALPH_COMPLETE" +``` + +**When to use the plugin:** +- Short task lists (< 10 tasks) that fit in one context window +- Tasks where remembering previous attempts helps +- When you want the agent to build on its own reasoning + +**Plugin limitations:** +- Context fills up on long tasks +- May get stuck in bad reasoning loops +- Only ONE completion string (exact match) + +### Manual Iteration + +For debugging or when you want full control: + +```bash +# Run one iteration +cat RALPH_PROMPT.md | claude --dangerously-skip-permissions --print + +# Check progress +cat RALPH_TODO.md | grep -E "^\- \[[ x]\]" | head -20 + +# Run another iteration +cat RALPH_PROMPT.md | claude --dangerously-skip-permissions --print +``` + +## Example: Setting Up a New Ralph Loop + +### Step 1: Identify the Work + +```bash +# Run tests to see what's failing +./run_tests.sh 2>&1 | tee test_output.txt + +# Count failures by category +grep "FAIL" test_output.txt | cut -d: -f1 | sort | uniq -c +``` + +### Step 2: Create TODO with Phases + +Group failures by root cause, not by file: + +```bash +# Create RALPH_TODO.md +cat > RALPH_TODO.md << 'EOF' +# Migration TODO + +**Status:** 0/50 complete + +## Phase 1: Core Infrastructure (fixes 30% of failures) +- [ ] Implement missing utility function X +- [ ] Fix edge case in parser + +## Phase 2: Individual Fixes +- [ ] Fix test A +- [ ] Fix test B +... +EOF +``` + +### Step 3: Create Prompt + +```bash +cat > RALPH_PROMPT.md << 'EOF' +# Ralph Loop: [Your Task] + +[Description and instructions...] + +## Your Task +Read RALPH_TODO.md and complete the next unchecked task... + +## Exit Condition +Output "RALPH_COMPLETE" when all tasks are done. +EOF +``` + +### Step 4: Run the Loop + +```bash +while true; do cat RALPH_PROMPT.md | claude --dangerously-skip-permissions --print; done +``` + +## Tips + +1. **Start small** - Test with 5-10 tasks before scaling up +2. **Monitor progress** - Check git log to see commits rolling in +3. **Intervene if stuck** - If the agent loops on the same task, add hints to the prompt +4. **Use phases** - Breaking work into phases helps the agent prioritize +5. **Trust git** - Progress is in commits, not in the agent's memory +6. **Fresh context is a feature** - Each iteration can approach problems fresh without being stuck in bad assumptions diff --git a/RALPH_TODO.md b/RALPH_TODO.md new file mode 100644 index 00000000000..eeb9703cb79 --- /dev/null +++ b/RALPH_TODO.md @@ -0,0 +1,1011 @@ +# Syntax Parity TODO + +**Last Updated:** 2026-02-03 +**Overall Status:** 423/506 tests passing (83%) + +**Category Breakdown:** +| Category | Passed | Failed | Total | Percent | +|----------|--------|--------|-------|---------| +| printer | 187 | 0 | 187 | 100% ✅ | +| ast-mapping | 3 | 0 | 3 | 100% ✅ | +| ppx/react | 31 | 0 | 31 | 100% ✅ | +| conversion | 27 | 0 | 27 | 100% ✅ | +| parsing/grammar | 93 | 42 | 135 | 68% | +| parsing/other | 12 | 2 | 14 | 85% | +| parsing/recovery | 14 | 6 | 20 | 70% | +| parsing/errors | 55 | 29 | 84 | 65% | +| parsing/infiniteLoops | 1 | 4 | 5 | 20% | + +**Remaining:** 83 tests to fix + +**Recent Fixes (this session):** +- **Added proper comma error handling in parameter and argument lists**: Added Grammar::ParameterList + and Grammar::ArgumentList breadcrumbs to parse_parameters and parse_call_args. When an unexpected + token (like `]`) is encountered in a comma-delimited list, now correctly generates "Did you forget + a `,` here?" instead of "Did you forget a `)` here?". Added handle_record_field_comma helper for + record field parsing. This matches OCaml's parse_comma_delimited_region behavior. +- **Fixed template literal pattern parsing for string interpolation errors**: Use start_pos from backtick + when reporting string interpolation error, matching OCaml's error location (3:5-7 instead of 3:6-7). + Skip all tokens then report one error, instead of reporting multiple errors. Use None delimiter in + error case (OCaml: Pconst_string("", None)). +- **Fixed semicolon spacing in inline record constructor fields**: OCaml's record_declaration uses + `sep:";@\n"` which places the semicolon AFTER each field. Changed to print ` ;` after each field, + matching OCaml's output format. +- **Fixed error location span in parse_atomic_expr**: OCaml uses `prev_end_pos` for start and `end_pos` + for end when reporting unexpected token errors. Rust was using `prev_end_pos` for both, causing spans + like "1:10" instead of "1:10-11". Now correctly matches OCaml's error location format. +- **Fixed scanner to preserve start_pos when skipping bad characters**: When the scanner encounters an + unknown character (like `$`), it reports an error and recursively scans. OCaml preserves the original + `start_pos` from before the bad character for the returned ScanResult, but Rust was returning the + recursive result directly. This caused error locations like "1:7" instead of "1:5-7". +- **Fixed exotic identifier handling to match OCaml**: For uppercase exotic identifiers, preserve the + full `\"...\"` wrapper in the scanner. For exotic identifiers with linebreaks, include the `\"` prefix + and actual newline character. Fixed `print_poly_var_ident` to just strip the leading backslash + (not add extra quotes) since the identifier already has quotes. +- **Used Lident diagnostic in parse_lident functions**: Changed pattern.rs and typ.rs parse_lident + functions to use Lident diagnostic instead of generic Message. This produces the correct + context-sensitive error message: "I'm expecting a lowercase name like \`user or \`age\`". +- **Added ExprSetField breadcrumb for record field mutation**: When parsing `expr.field = value`, + leave the ExprSetField breadcrumb before parsing the value expression. This enables the error + message "It seems that this record field mutation misses an expression" to be displayed. +- **Fixed value path error recovery for trailing dot**: When parsing a value path like `n.R.` where + the identifier after the last dot is missing, emit an error and recover by adding `_` as the + missing identifier. Fixes the `id.res` error test. +- **Added keyword field error handling for record fields**: When a reserved keyword is used as a record + field name (e.g., `{type: int}`, `{type: 1}`, `{type}`), emit appropriate error messages: + - In types: "Cannot use keyword `X` as a record field name. Suggestion: rename it (e.g. `X_`). + If you need the field to be "X" at runtime, annotate the field: `@as("X") X_ : ...`" + - In expressions: "Cannot use keyword `X` as a record field name. Suggestion: rename it (e.g. `X_`)" + - In patterns: "Cannot use keyword `X` here. Keywords are not allowed as record field names." + If keyword is followed by colon, recover by renaming field to `X_`. Fixes 6 tests. +- **Added dict spread error message**: When `...` is used in a dict literal, emit "Dict literals do not + support spread (`...`) yet." instead of the generic "Dict keys must be strings" error. +- **Added `let?` error messages for signatures and rec**: Added two checks matching OCaml: + 1. `let?` is not allowed in signatures - emit error and recover + 2. `let? rec` combination is not allowed - emit error and recover +- **Added second record spread error in expressions**: When a record has more than one `...` spread + (e.g., `{...x, ...y}`), emit "Records can only have one `...` spread, at the beginning." +- **Added missing tilde error for labeled type parameters**: When parsing function type parameters + like `(name: type)` without the tilde, emit "A labeled parameter starts with a `~`. Did you mean: `~name`?" +- **Fixed if-expression error recovery with regions/breadcrumbs**: Added proper `begin_region`/`end_region` + and breadcrumbs (`ExprIf`, `IfCondition`, `IfBranch`, `ElseBranch`) to if-expression parsing. + This matches OCaml's region-based error suppression: first error in then-branch silences subsequent + errors in that region, but else-branch starts a new region so its errors are reported. + Also fixed `parse_block_body` to check `is_block_expr_start` before continuing, which is critical + for error recovery (prevents `else` from being parsed as a block expression). +- **Added spread pattern error messages for array and record patterns**: Implemented `parse_non_spread_pattern` + helper that checks for `...` and emits "Array spread (`...`) is not supported in pattern matches" + with the full explanation. Also added spread detection in record pattern parsing. This fixes + error messages in tests like parsing/recovery/expression/list.res. +- **Added 'Did you mean ==?' error for = as binary operator**: When `=` is used as a binary operator + (e.g., `if a = b { ... }`), emit "Did you mean `==` here?" error. This matches OCaml's + `make_infix_operator` function which detects this common mistake. +- **Added string interpolation error in pattern matching**: When template literal patterns contain + interpolation (`${...}`), emit "String interpolation is not supported in pattern matching" error. +- **Added type definition in function error**: When `type t = ...` is used inside a block/function, + emit "Type definitions are not allowed inside functions. Move this `type` declaration to the + top level or into a module." Added `Token::Typ` to `is_block_expr_start` and proper parsing + to get the full span of the type definition for accurate error location. +- **Added external missing JS value name error**: When `external foo: T =` is not followed by a + string, emit "An external requires the name of the JS value you're referring to, like \"foo\"." +- **Fixed empty inline record parsing**: Empty constructor arguments like `Node({})` were being + parsed as object types (`< >`) instead of inline records (`{ }`). Removed `Token::Rbrace` from + the object type detection heuristic. Also fixed ML printer indentation for empty inline records. +- **Fixed pattern error recovery with skip_tokens_and_maybe_retry**: When an unexpected token is seen + where a pattern is expected, call `skip_tokens_and_maybe_retry` to try to find a valid pattern start + token. For example, `let = 2` now recovers to `let 2 = [%rescript.exprhole]` matching OCaml (skips `=`, + finds `2` as valid pattern start, parses `2` as pattern, then RHS is missing so returns exprhole). +- **Fixed switch case body to use exprhole for missing RHS**: When a switch case has a missing RHS + (pattern parsed but no expression after `=>`), return `[%rescript.exprhole]` instead of `()`. This + matches OCaml's behavior where `parse_expr_block` always tries to parse an expression, and + `parse_atomic_expr` returns exprhole via `skip_tokens_and_maybe_retry` when the token is `}`. + +- **Fixed type declaration error recovery**: When parsing `type` without a name (EOF or invalid token), + create a placeholder type declaration with name `_` instead of producing nothing. This matches OCaml's + `parse_lident` which returns `("_", loc)` for error recovery. +- **Added single-element tuple error**: Emit "A tuple needs at least two elements" when a tuple has + only one element (detected by trailing comma). Added to all three contexts: pattern, expression, + and type tuples. Fixed error location to use start_pos and prev_end_pos matching OCaml. +- **Added missing tilde labeled parameter error**: When a function parameter has `name=value` without + a `~` prefix, emit "A labeled parameter starts with a `~`. Did you mean: `~name`?" and recover by + treating it as an optional parameter. +- **Fixed Lident diagnostic message**: Match OCaml's typo in the error message for expected lowercase + identifiers: "I'm expecting a lowercase name like `user or `age`" (missing backtick after "user"). +- **Added parse_ident helper**: Replicate OCaml's parse_ident behavior which checks for keywords on + same line before emitting custom error message. Used for type variable parsing after `'`. +- **Fixed type variable keyword error**: For `'let`, emit "`let` is a reserved keyword. Keywords + need to be escaped: \"let\"" instead of generic type variable error. +- **Added skip_tokens_and_maybe_retry to type expression parsing**: When encountering an unexpected + token in parse_atomic_typ_expr, try to skip tokens and retry parsing if we find a valid type + expression start. This matches OCaml's error recovery behavior. Fixes garbage.res test. +- **Added MinusGreater error recovery in arrow types**: When -> is used instead of => in type + expressions, generate "Did you forget a `=>` here?" and continue parsing. Matches OCaml's + res_core.ml parse_arrow_type_rest behavior. +- **Added grammar context to expect(Colon) for type hints**: Pass Grammar::TypeExpression context + when expecting a colon in labeled parameters and object fields, adding the hint "It signals + the start of a type" to error messages. +- **Fixed type definition parsing - Bar before Equal**: When parsing type definitions, if Bar (`|`) is + seen instead of Equal, call expect(Equal) to generate "Did you forget a `=` here?" with proper + location span (from end of name to the Bar token). +- **Fixed type name parsing - Lident diagnostic**: When an uppercase identifier (like T1) is seen + where a type name is expected, emit Lident diagnostic: "Did you mean `t1` instead of `T1`?". + When a dotted path (like Foo.bar) is seen, emit: "A type declaration's name cannot contain a + module access. Did you mean `bar`?" +- **Fixed type extension uppercase names**: When parsing type extension paths like M.T2, the final + segment (the type name) should be lowercase. Emit Lident diagnostic for uppercase final segments. +- **Fixed exotic identifier error location**: When reporting errors for exotic identifiers (e.g., + empty string `\""` or linebreaks), the error location should start at the backslash, not the + opening quote. Now reports `1:6-8` instead of `1:7-8`. +- **Fixed EOF handling in type name parsing**: When EOF is encountered in type name context, use + Unexpected diagnostic instead of Lident. This generates the generic "I'm not sure what to parse + here when looking at 'eof'" message matching OCaml. +- **Fixed infinite loop in signature parsing**: When `parse_signature_item` returns None for unexpected + tokens (like `export type`), the parser now emits an "unexpected" error and advances the token, matching + OCaml's `parse_region` behavior. Also added proper breadcrumbs: `Grammar::Specification` for file-level + signatures and `Grammar::Signature` for braced signatures (inside module types). The key difference is + that `Signature` terminates on `Rbrace` but `Specification` doesn't. +- **Added PatternMatchCase and Pattern breadcrumbs for switch/try cases**: OCaml sets PatternMatchCase + breadcrumb before parsing each case, and Pattern breadcrumb before parsing the pattern. This enables + proper context-aware error messages like "I was expecting a pattern to match on before the `=>`". +- **Fixed catch token handling**: Changed from manual `Message("Expected 'catch'")` to using + `expect(Token::Lident("catch"))` to get proper "Did you forget a `catch` here?" error message. +- **Added sigitemhole recovery for signature items**: When attributes exist but no valid signature item + follows, OCaml reports "Did you forget to attach X to an item?" and returns a sigitemhole placeholder. + Added `default_signature_item()` and error handling in `parse_signature_item` to match. +- **Moved parse_newline_or_semicolon_structure inside structure item branches**: OCaml calls + parse_newline_or_semicolon_structure INSIDE each branch of parse_structure_item_region, before + calling end_region(). This allows errors to be reported within each item's region. For example, + `export type t = int and export s = string` now correctly emits 2 errors (one for `export type`, + one for `and export`) instead of just 1. +- **Added parse_newline_or_semicolon_signature for signature item parsing**: Similar fix for + signature items, with proper regions for Let, Typ, and Module branches matching OCaml. +- **Propagated scanner diagnostics to parser**: Scanner errors like unclosed strings were being + collected but never propagated to the parser's diagnostic list. Now scanner diagnostics are + taken and added to parser diagnostics after each scan operation. +- **Added skip_tokens_and_maybe_retry for error recovery**: Implemented OCaml's error recovery + mechanism that skips unexpected tokens and retries parsing. For example, `let foo = '2` now + correctly parses as `let foo = 2` (recovering after the invalid `'` character). +- **Added Implementation breadcrumb to parse_structure**: OCaml's `parse_implementation` uses + `parse_region` with `Grammar::Implementation` as the breadcrumb. This enables proper + `should_abort_list_parse` checks during error recovery. +- **Added error for empty exotic identifiers**: When scanning exotic identifiers like `\""`, + emit "A quoted identifier can't be empty string" error and preserve the full escaped form. +- **Fixed error reporting to match OCaml's region-based silencing**: Three key changes: + 1. Removed per-item regions in parse_structure - OCaml does NOT create a new region for each + structure item. The region is shared so that after one error, subsequent errors are silenced. + 2. Changed err_multiple to err_at in parse_newline_or_semicolon_structure to respect regions. + 3. Replaced "Unexpected token: {:?}" messages with err_unexpected() to use proper Unexpected + diagnostic category which runs through explain_unexpected() for context-aware messages. +- **Added begin_region/end_region to type and module parsing**: OCaml uses regions around specific + parsing operations (Token::Typ and Token::Module) to allow errors within one definition to be + de-duplicated while still reporting errors from different definitions. + +- **Fixed item_attribute line-breaking in ML printer**: Added HOV box with break hint after attribute name, + matching OCaml's "@[<2>[@@%s@ %a]@]" format. This enables proper line breaking for long attributes. +- **Fixed polyvariant line-breaking in ML printer**: Added proper box structure with break hints for + polyvariant types - outer box for entire type, inner boxes for each row field, use break_(-2) for + `|` separator to align with opening `[`. +- **Added specific error for dangling attrs/mutable in record fields**: When attributes or doc comments + appear without a field name, OCaml gives "Attributes and doc comments can only be used at the beginning + of a field declaration". Same for dangling `mutable` keyword. Fixed error location to use p.end_pos. +- **Added error recovery for = instead of : in record fields**: When user writes `{foo=string}` instead + of `{foo: string}`, emit "Record fields in type declarations use `:`. Example: `{field: string}`" + and continue parsing as if `:` was used. +- **Fixed empty record printing in ML printer**: When a record type has zero fields, the closing `}` was not + being printed because the loop over fields never executed. Added special case for empty records. +- **Fixed error location spans in expect_with_grammar**: OCaml's `expect` uses `prev_end_pos` for start and + `end_pos` for end, creating a span from previous token to current. Rust was using `prev_end_pos` for both. + This fixes error location format like `:1:15-2:3` instead of just `:1:15`. +- **Implemented context-aware error messages in explain_unexpected**: The `explain_unexpected` function now properly + uses the breadcrumbs (parsing context) to generate context-specific error messages matching OCaml's behavior. + Fixed breadcrumb order issue - OCaml prepends to list (most recent at head), Rust appends (most recent at end). + Now "I'm missing a type here" shows correctly for missing types in record field declarations. +- **DiagnosticCategory now uses Grammar enum** instead of strings for context (matching OCaml's res_diagnostics.ml): + - `DiagnosticCategory::Unexpected.context` changed from `Vec<(String, Position)>` to `Vec<(Grammar, Position)>` + - `DiagnosticCategory::Expected.context` changed from `Option` to `Option` + - `explain_unexpected` function can now pattern-match on `Grammar` variants directly + - Added `Serialize`/`Deserialize` derives to `Grammar` enum + - This enables proper context-aware error messages matching OCaml's breadcrumb-based diagnostics +- Empty polyvariant `[]` now generates TWO type holes (matching OCaml) +- Added begin_region/end_region around structure items so each can report errors +- Added polyvariant type error generation for error recovery mode: + - `parse_row_fields_with_required_first()` requires at least one row field for `[< ...]` and `[...]` + - `is_bar_or_doc_comment_then_bar()` handles doc comments before leading `|` + - Generates "I'm not sure what to parse here" errors for invalid syntax like `[< ]` and `[]` + - Recovered AST includes `[%rescript.typehole]` placeholders +- ML printer: add pipe context for match cases - wraps Pexp_fun/match/try/sequence in parens when + used as match case RHS (matching OCaml's under_pipe context) +- ML printer: use simple_expr for record field values (matching OCaml's longident_x_expression) +- ML printer: wrap alias types (Ptyp_alias) in parens when used as arrow arguments +- Parser: accept uppercase type variables ('X) in type constraints, not just lowercase ('a) +- Added consecutive statements/expressions error checking (`parse_newline_or_semicolon_expr_block`, + `parse_newline_or_semicolon_structure`) - detects missing ';' or newline between consecutive items +- Fixed ML printer Unicode escaping: non-ASCII bytes now escaped as decimal sequences (e.g., \226\156\133) +- Changed ML printer margin from 80 to 78 to match OCaml's Format module default +- Added HOV box with break hints to Ptyp_arrow for proper line wrapping at -> +- Fixed ML printer expression tier hierarchy (expression2 vs simple_expr) +- Fixed constrained pattern printing in value bindings (use simple_pattern for inner, add outer parens) +- Added pattern_is_simple function matching OCaml's simple_pattern behavior +- Fixed constructor attribute printing in type declarations (e.g., `@as(null)`) +- Fixed cons pattern parens in constraint patterns (don't wrap cons when not at binding top-level) +- Added trailing space after Ppat_unpack pattern (`(module Set) `) +- Added Pexp_send to simple expressions +- Fixed ML printer: add spaces between JSX children (matching OCaml's list separator) +- Fixed ML printer: avoid double parens in await expressions with attributed arguments +- Fixed ML printer: include `res.await` attribute in printed output (not filtered as internal) +- Fixed ML printer: record pattern punning only for simple Lident fields (not qualified Ldot) +- Added parens for alias/or patterns in record field patterns (pattern1 context) +- Fixed ML printer: complete list literals are now simple expressions (no extra parens around `[1; 2; 3]`) +- Implemented full JSX printing in ML printer (fragments, unary, container elements with props) +- Fixed package type constraint printing to use 'and' for subsequent constraints +- Fixed record field semicolon spacing when field has attributes +- Fixed type constraints in type declarations (ptype_cstrs) +- Fixed recursive module printing with constraint sugar and attributes +- Fixed module functor sugar (`module F(A:X) = ...`) and module application printing (`(F)(A)`) +- Fixed unit functor printing (`functor () ->` instead of `functor (*) ->`) + +**Root Causes of Remaining Failures (83 tests):** + +1. **parsing/grammar (42 failing)**: Almost entirely ML printer line wrapping differences. + OCaml's Format module wraps long lines at 78 columns with specific indentation rules. + The Rust Formatter doesn't match this behavior exactly. The actual AST content is correct. + Key issue: OCaml uses `@[` boxes with break hints (`@;`) that cause "all or nothing" + line breaking. The Rust formatter implements box-based formatting but the break decisions + don't always match. Example: for-loops should break after `do` with body indented, but + Rust keeps everything on one line until forced to break. + +2. **parsing/errors (29 failing)**: Multiple issues: + - Error message wording sometimes differs + - Error location spans differ in some cases + - Some errors report different context (e.g., different line numbers shown) + - ML printer line wrapping causes AST output formatting differences + - Record/braced expression disambiguation: OCaml has special case at line 3229-3247 of + res_core.ml that detects `{updateF value:...}` and generates "Did you forget a `,` here?" + when `Lident Lident` pattern appears on different lines vs "Did you forget a `:` here?" + when on same line. Rust's lookahead-based approach doesn't handle this case. + +3. **parsing/recovery (6 failing)**: Error recovery output differs from OCaml. + Both error messages and recovered AST formatting differ. + +4. **parsing/infiniteLoops (4 failing)**: Actually doesn't loop infinitely, but error messages + and AST output format differ from OCaml. + +5. **parsing/other (2 failing)**: Mixed issues including line wrapping differences. + +**Note:** The vast majority of failures (42/83 = 51%) are parsing/grammar tests which fail solely +due to ML printer line wrapping. If the Format module behavior matched OCaml exactly, many of +these would pass. The error message content itself is often correct, just the formatting differs. + +--- + +## ⚠️ CRITICAL: Format Module Must Be 1:1 Port from OCaml + +**The Rust formatting code is NOT an "emulation" - it must be a 1:1 PORT of OCaml's Format module.** + +Relevant Rust files: +- `compiler-rust/src/parser/format.rs` - Basic pretty printer with boxes +- `compiler-rust/src/parser/doc.rs` - Document-based formatting +- `compiler-rust/src/parser/formatter.rs` - Formatting logic + +When there are line-breaking or formatting differences: +1. **Look at the OCaml Format module source code** (`stdlib/format.ml` in the OCaml repo) +2. **Compare the algorithm step-by-step** with the Rust implementation +3. **Make the Rust code match OCaml exactly** - same box types, same break decisions, same indentation rules + +Common issues that indicate Format parity problems: +- Different line break points (OCaml wraps at 78 columns by default) +- Different indentation levels after line breaks +- HOV boxes packing differently than expected +- Break hints being ignored or applied differently + +**Do NOT try to "fix" or "improve" the algorithm** - match OCaml's behavior exactly, even if it seems suboptimal. + +Reference: https://github.com/ocaml/ocaml/blob/trunk/stdlib/format.ml + +--- + +## ⚠️ CRITICAL: Complete ALL Fixes, Not Just Easy Ones + +**The goal is 100% parity with the OCaml reference implementation.** There is no reason to stop at "low-hanging fruit" or avoid complex features. Every remaining test must eventually pass, so tackle the hard problems now rather than deferring them. + +**What this means:** +- **Spread array syntax** (`[...xs, a, b]`) - Implement the full reconstruction from `Belt.Array.concatMany` +- **Underscore apply rewriting** - DONE: Implemented `print_underscore_apply` and `print_underscore_apply_in_pipe` +- **Template literals** - Implement complete template literal printing +- **Any other missing feature** - If a test requires new infrastructure, build that infrastructure + +**Do NOT:** +- Skip tests because they're "too complex" +- Move on to easier tests when stuck on a hard one +- Assume someone else will fix the difficult parts later + +**The work is not done until ALL syntax tests pass (506/506).** Printer parity is complete (187/187), but parsing/errors, parsing/grammar, ppx, and conversion tests still need work. Study the OCaml implementation and implement equivalent Rust code. + +--- + +### Recent Progress +- Implemented spread array/list syntax printing (array.res now passes): + - Added `is_spread_belt_array_concat` and `is_spread_belt_list_concat` to detect Belt.Array/List.concatMany + - Added `print_belt_array_concat_apply` and `print_belt_list_concat_apply` to print `[...xs, a, b]` syntax + - Added special comment handling in comment_table for spread arrays/lists +- Fixed polyvariant row field comment handling (variant.res now passes): + - Wrap tag_doc with print_comments using label.loc to attach leading/trailing comments +- Fixed template literal printing (templateLiteral.res now passes): + - Implemented `print_template_literal` to reconstruct `foo ${bar}` from string concatenation + - Fixed `print_string_contents` to split strings on newlines and join with `Doc::literal_line()` + - This ensures proper position tracking for multiline strings (especially in template literals) +- Fixed JSX fragment arrow function placement (jsx.res now passes): + - Added `Pexp_jsx_element(JsxElement::Fragment(_))` to `should_indent` check in arrow function + - Now `let f = el => <> ... ` keeps the fragment on the same line as `=>` +- Fixed doc comment inline spacing in type expressions (DocComments.res now passes): + - Added `print_doc_comments_with_sep` with configurable separator (defaults to hard_line) + - Use `Doc::space()` separator for doc comments on types to keep them inline + - Remove extra spaces around doc comment content: use `/**` and `*/` directly +- Fixed binary.res printing (now passes): + - Right-associative operators (exponentiation `**`): Added `is_rhs_binary_operator` function and + flip the `is_lhs` parameter for these operators so `2. ** 3. ** 2.` and `(2. ** 3.) ** 2.` + are parenthesized correctly + - Single pipe expressions: Added `is_single_pipe_expr` function and `custom_layout` handling in + `print_value_binding` so `let x = switch z {...}->switch y {...}` prints on one line + - Attributed operands in flattening: When a binary operand has printable attributes, add outer + parens (e.g., `a && @attr b && c` → `a && (@attr b) && c`). Added `flatten_operand_rhs_without_attrs` + to handle the case where we've already partitioned printable attrs +- Fixed polyvariant tuple printing (polyvariant.res now passes): + - When a polyvariant constructor has a tuple with a single element that is itself a tuple, + e.g. `#Some((a, b))`, OCaml prints it hugged without indentation + - Added special case matching OCaml's `Pexp_tuple [({pexp_desc = Pexp_tuple _} as arg)]` +- Fixed switch/match case comment handling (switch.res now passes): + - Node::Case.get_loc() now uses braces attribute location if present for consistent key lookup + - print_cases uses braces attribute location for full_loc and prev_end_line + - This ensures trailing comments on same line as `}` appear correctly + - Leading comments before case patterns no longer cause extra blank lines +- Fixed attribute positioning in pipe expressions inside binary operators (asyncAwait.res now passes): + - When a binary expression with printable attributes appears as an operand of another binary operator + (e.g., `(@foo (server->start))->foo`), the attributes should be printed outside the expression + - Added `partition_printable_attributes` function to parsetree_viewer.rs + - In `flatten_binary_operand`, for non-flattenable binary expressions: partition printable attrs, + print the expression WITHOUT printable attrs (using print_binary_expression directly), wrap in + parens if needed for precedence, then prepend the printable attrs outside +- Fixed ternary expression indentation in value bindings (ternary.res now passes): + - When ternary condition is a binary expression or has attributes, indent the ternary on a new line + - Updated `should_indent` logic in `print_value_binding` to match OCaml's handling + - Added `has_tagged_template_attr` function for special handling of tagged templates +- Fixed binary expression flattening (binaryExpr.res now passes): + - Implemented `flatten_binary_operand` function matching OCaml's `flatten` logic in `print_operand` + - When printing a binary operand that is itself a flattenable binary expression (same precedence, + no attributes), recursively flatten instead of nesting with group/indent + - This prevents excessive indentation for chains like `a && b && c && d` + - Added `print_binary_operator_with_spacing` helper matching OCaml's `print_binary_operator` + - Handles special cases: setfield (parens only on LHS), #= operator, await expressions +- Fixed PPat payload printing (attributes.res now passes): use `if` instead of `when` for guard, + wrap in indent with soft_line matching OCaml's format +- Fixed typexpr.res comment handling (now passes): + - Fixed Ptyp_package constraint comments: use `make_combined_pos_range` and `print_comments_by_pos` + to wrap each package constraint with comments using a location spanning from name to type end + - Fixed Ptyp_poly type variable comments: use `visit_list_but_continue_with_remaining_comments` + to walk type variables, attaching leading/trailing comments to each variable's location + - Fixed empty record type with comments: handle `fields.is_empty()` case in Ptype_record by + printing `{ print_comments_inside(...) }` instead of calling `print_record_declaration` + - Fixed labeled arrow type parameter comments: OCaml uses type's location for partitioning but + combined location for `get_loc`. Comments between label and type (like `~a: /* c */ typ`) + become "before" comments attached as leading to the type + - Fixed Ptyp_object field comments: wrap label doc with `print_comments` for `label.loc`, + then wrap entire field with `print_comments_by_pos` using combined location (label to type end) +- Fixed value binding sugar comment handling (valueBindingSugar.res now passes): + - OCaml's comment_table.ml has special handling for value binding sugar forms where pattern + and expression have the same location (e.g., `let x: type t. ... = (type t) => ...`) + - Added `rewrite_value_binding_locs` function to adjust pattern location to end at the type + annotation, and use the inner expression (from Pexp_constraint) instead of outer Pexp_newtype + - This ensures comments for the function parameters are properly attributed to the expression, + not consumed by the pattern + - Also fixed Ptyp_arrow comment walking: now uses `parsetree_viewer::arrow_type` to flatten + the arrow type into a list of parameters before walking, matching OCaml's approach +- Added value binding sugar printing in printer2.rs: + - When pattern is `Ppat_constraint(pat, Ptyp_poly)` and expression is `Pexp_newtype`, + print the sugared form `let x: type t. T = expr` instead of desugared form +- Fixed stack overflow in arrow_type when arity is 0: + - The Rust code was checking `remaining_arity == 0` but OCaml checks `max_arity < 0` + - When external declarations have labeled @as parameters with arity=0, Rust returned immediately + with empty args and the original arrow type as return_type, causing infinite recursion + - Changed remaining_arity from usize to isize and check `< 0` like OCaml + - This fixes crashes on files like `printer/other/attributes.res` +- Fixed JSX comment handling in comment_table.rs (printer/comments/jsx.res now passes): + - Implemented proper JSX comment attachment logic matching OCaml's res_comments_table.ml + - For unary elements: calculate closing token location (/>), partition comments between tag name + and next token (first prop or />), attach comments appropriately + - For container elements: handle opening > token comments, children comments, and inside comments + for empty containers with space between opening and closing tags + - Use `partition_adjacent_trailing_before_next_token_on_same_line` for JSX tag name comments +- Implemented JSX printing in Rust printer: + - Added `print_jsx_element` with support for fragments, unary, and container elements + - Added `print_jsx_name` for lower, upper, and qualified tag names + - Added `print_jsx_prop` for punning, value, and spreading props + - Added `print_jsx_children` with proper line separation + - Fixed JSX parser to properly populate `closing_tag` field (was always None) +- Added `has_comment_below` function and fixed simple pipe (->) comment handling: + OCaml only adds `soft_line` before `->` when `has_comment_below` returns true (checking if the first + trailing comment starts on a line BELOW the expression's end). This ensures `compilation // after` + followed by `/* below */` on the next line followed by `->Plugin.buildAssets` prints as + `compilation->Plugin.buildAssets // after\n/* below */ // trailing` (comments at end of line). +- Fixed doc comment partition to only include res.doc, not ocaml.doc (valueBinding.res almost passes): + OCaml only treats "res.doc" as a doc comment (printed as /** ... */). "ocaml.doc" is a regular + attribute and should stay on the same line with other attributes, not get a hard_line. +- Fixed binary expression indentation using should_indent_binary_expr (jsObjectAccess.res passes): + OCaml's should_indent_binary_expr checks if LHS is a same-precedence sub-expression. Added + flattenable_operators and same_precedence_sub_expression helpers to properly determine when + the RHS of a binary expression should be indented. +- Fixed async detection for functions with leading (type a): The `is_async` flag was only checked + on the top-level expression, but for `async (type a, ()) => body`, the Pexp_newtype is outermost. + Now we check `is_async` on the FIRST Pexp_fun encountered, not just the top-level. +- Fixed newtype collection across function boundaries: OCaml's `fun_expr` only collects Pexp_newtype + at the BEGINNING, not during the collect_params loop. This means `(type a, ()) => (type b c, x) => 3` + keeps the two functions separate, not merging all newtypes into one. +- Fixed await expression to ignore braces for simple expressions: OCaml filters out `@res.braces` + before checking if parens are needed, so `await {x}` prints as `await x`. +- Implemented special callback printing for functions in last/first arg position (expr.res passes): + When a callback has a trailing comment between parameters and `=>` like `f(() // c1 => 1)`, + OCaml moves the comment AFTER the entire function call: `f(() => 1) // c1`. Implemented: + - `print_pexp_fun` with `in_callback` parameter that adds `soft_line` after return expression + - `print_arguments_with_callback_in_last_position` using `custom_layout` for different formats + - `print_arguments_with_callback_in_first_position` for callbacks as first argument + - Uses `CommentTable::copy` to handle printing the same subtree multiple times +- Fixed attribute printing on binary expressions: `@ann (x->foo)` was missing the `@ann` attribute + because the code only checked for printable attrs to add parens but never printed them. +- Fixed attribute printing in Pexp_apply special cases: Array.get, Array.set, and #= (send-set) + were relying on the generic attribute handler which was disabled for Pexp_apply. Added explicit + attribute printing to each special case. +- Fixed attribute duplication on function expressions: `@att x => 34` was printing as + `@att @att (@att x) => 34`. Two issues fixed: + 1. `fun_expr` was including `pexp_attributes` in each `FunParam::Parameter.attrs`, but OCaml + strips attributes by passing `{expr_ with pexp_attributes = []}` to `collect_params`. + 2. `print_expression` was always printing `e.pexp_attributes` at the end, but some expression + types (Pexp_fun, Pexp_apply, etc.) already print their own. Added `should_print_its_own_attributes` + check matching OCaml to skip double printing for those types. +- Fixed curried function printing: `(a, b, c) => (d, e, f) => 4` was being collapsed into + `(a, b, c, d, e, f) => 4`. The issue was that `fun_expr` was collecting ALL nested function + parameters without checking the `arity` field. OCaml's `fun_expr` has the condition + `arity = None || n_fun = 0` - it only collects params from nested functions if there's no + arity marker. Added this check to stop collecting when an arity marker is present. +- Fixed JS object set parenthesization in binary expressions (jsObjectSet.res passes): Similar to + setfield, the `#=` operator only needs parens when on the LHS of a binary expression. For + `(node["left"] = value)->pipe`, the parens around the assignment are now preserved. +- Fixed type extension attribute line breaking (typeExtension.res passes): Pass the path location + to print_attributes_with_loc so that attributes on a separate line preserve the line break. + `@attr\ntype t +=` now correctly prints with a line break between the attribute and the type. +- Fixed setfield parenthesization in binary expressions (setfield.res passes): OCaml's print_operand + handles Pexp_setfield specially - it only needs parens when on the LHS of a binary expression, + not when on the RHS. This means `a->@attr user.name = "steve"` doesn't need parens around the RHS. + Added special case in binary_operand_needs_parens to bypass the general binary_expr_operand check. +- Fixed recursive module constraint printing (recModules.res passes): Handle Pmod_constraint + in print_rec_module_bindings to print constraint before equals sign. +- Fixed try expression body parenthesization (try.res now passes): Match OCaml's printer which + uses parens::expr to check if the try body needs braces. +- Fixed Array.get/Array.set formatting for complex index expressions (arrayGet.res, arraySet.res now pass): + Match OCaml's printer which wraps non-trivial index expressions with soft_line and indent. + For simple expressions (constants, identifiers), the index is printed inline. +- Added special case for Array.get/Array.set in comment_table.rs: Match OCaml which walks + argument expressions directly instead of going through walk_apply_expr. This ensures + comments inside array access brackets are properly attached to the index expression. +- Fixed Pmty_functor parameter comments (modType.res now passes): The Rust code was walking + functor parameters one at a time recursively, which didn't properly handle comments between + parameters. Changed to match OCaml's approach: collect all parameters first using `functor_type_params`, + then walk them as a list with `visit_list_but_continue_with_remaining_comments`. Added + `walk_mod_type_parameter` to walk each parameter's label and optional module type. +- Fixed doc.rs `fits` function performance: The function was cloning the entire stack for each + `fits` check, causing O(n²) memory allocations with deeply nested structures. Changed to pass + the first item and rest of stack separately (avoiding clone). Also added iteration limit + (10000) to prevent exponential blowup with deeply nested custom layouts. This fixes the + infinite loop/timeout with `nestedCallbacks.res`. +- Fixed unit pattern printing inside braced expressions: `{ () => 1 }` was printing as + `{ (()) => 1 }`. The special case detection for simple params was using `attrs.is_empty()` + but the `res.braces` attribute made it non-empty. Fixed by using `filter_parsing_attrs()`. +- Fixed underscore apply sugar printing: `f(a => b, _)` now prints correctly as `f(a => b, _)` + instead of `__x => f(a => b, __x)`. Added `is_underscore_ident` and `print_underscore_apply` + functions to detect and print the underscore placeholder pattern. +- Fixed `hard_line` in `line_suffix` processing: The doc.rs line suffix loop wasn't properly + handling `LineStyle::Hard` in flat mode - it was outputting a space instead of a newline. +- Fixed block expression blank line handling (blockExpr.res now passes) + - For Pexp_let and Pexp_letexception: extend start_line to leading comment + - Match OCaml's location extension behavior for blank line calculation +- Fixed Pexp_field comment handling: added print_comments for field name +- Fixed BS object row comments: added cmt_loc wrapper for leading/trailing comments +- Fixed record spread comment placement: /* before */ now appears before ...spread +- Fixed if-else trailing comments: comments between `}` and `else if` cause line break +- Combined consecutive newtype parameters: (type t, type s) -> (type t s) +- Fixed type record spread comments: leading comments like "// spread a" before ...a +- Fixed inline module structure in include statements (include.res): single type alias force_break=false +- Fixed module binding parenthesization and empty structure comments (structure.res) +- Fixed type constraints in with clauses (withConstraints.res): add ptype_cstrs printing +- Fixed empty signature comment handling (signature.res): attach to mod_type loc, not LocIdx::none() +- Fixed functor module type printing: parens around functor in Pmty_with, empty signature formatting +- Fixed binary expression line breaking with `should_inline_rhs_binary_expr` (case.res now passes) +- Fixed binary expression comment attachment (e.g., `a /* c1 */ === /* c2 */ b` preserves comments) +- Fixed case guard block expression comment handling (comments inside `if { ... }` guards) +- Fixed case pattern comment handling (matching OCaml's List.concat [before; inside]) +- Fixed doc comment and attribute printing in value bindings (docComments.res) +- Fixed constructor declarations and record field comment handling (typeDefinition.res) +- Fixed recursive module declarations/bindings comment handling (signatureItem.resi) +- Fixed type declarations comment handling with print_listi (structureItem.res) +- Fixed setfield (record field assignment) comment handling +- Fixed record field name comment handling in label declarations +- Fixed module declaration name comment handling +- Fixed attribute payload comments (@@attr(/* c0 */ "here" /* c1 */)) +- Fixed exception GADT line breaks with proper constructor argument printing +- Added print_constructor_arguments helper matching OCaml behavior +- Fixed functor parameter comment attachment (leading and trailing) +- Fixed Pmod_apply argument comment handling (using mod_expr_apply) +- Fixed Pmod_constraint location-based comment ordering +- Fixed type extension path comment handling +- Fixed type declaration and external name comment handling +- Fixed exception rebind longident comment handling +- Fixed `@JSX` attribute preservation in braced expressions (braced.res now passes): + - Removed `"JSX"` from `is_printable_attribute` list - it should be printed, not filtered + - Fixed function body brace preservation: when extracting inner expr from Pexp_constraint, + merge attributes from constraint onto inner expression so `@res.braces` is preserved + +### Known Issues +- **blockExpr.res**: Fixed! The issue was that OCaml extends row locations to include leading + comments for Pexp_let and Pexp_letexception. This affects blank line calculation because + when the extended location is used for comment lookup, the comment isn't found (different key), + so start_pos falls back to the extended location's start (the comment's line). + +- **Binary expression line breaking**: Fixed! Implemented `should_inline_rhs_binary_expr` which + determines if the RHS of a binary expression can be on a new line. For example, switch + expressions (Pexp_match) are NOT inlined, so `heightGet(n) >= switch ...` now correctly + breaks after `>=`. (case.res now passes) + +- **expr.res - Newtype parameter comments**: FIXED! The comment_table.rs was computing a span + from first to last name for NewTypes param_loc, but OCaml uses just the first name's location. + Changed to use `first.loc` only, which properly attaches leading/trailing comments. + +- **expr.res - Callback trailing comments**: FIXED! Implemented special callback printing: + - `print_pexp_fun` with `in_callback` parameter adds `soft_line` after return expression + - `print_arguments_with_callback_in_last_position` and `print_arguments_with_callback_in_first_position` + - Uses `Doc::custom_layout` and `CommentTable::copy` to try different layouts + +- **modType.res - Pmty_functor parameter comments**: FIXED! The Rust comment_table was walking + Pmty_functor parameters one at a time recursively, which didn't properly handle comments + between parameters. Changed to match OCaml's approach: collect all parameters first using + `functor_type_params`, then walk them as a list with `visit_list_but_continue_with_remaining_comments`. + +- **modType.res - Pmty_typeof**: FIXED! Added partition_by_loc and attach leading/trailing + to mod_expr.pmod_loc before calling walk_module_expr. Now `module type of /* c4 */ {}` + keeps the comment before the brace. + +- **binaryExpr.res - Flattening**: FIXED! Implemented `flatten_binary_operand` function that + recursively flattens same-precedence binary operators without creating nested groups/indentation. + When a binary operand is itself a flattenable binary expression (same precedence, no attributes), + it recursively flattens instead of wrapping in a new group. This now correctly prints + `a == b && c == d && e == f` without indenting the middle operators. + +### Major Missing Features (blocking remaining ~40 tests) + +1. **JSX Printing**: IMPLEMENTED! Basic JSX printing works (fragments, unary elements, container + elements, props, children). JSX comment handling needs more work - OCaml has sophisticated + comment partitioning logic (`partition_adjacent_trailing_before_next_token_on_same_line`) that + determines whether comments attach to tag names, props, or closing tokens. + +2. **Callback Formatting**: IMPLEMENTED! Special callback printing that "hugs" callback arguments + is now working. The basic feature works for expr.res, but callback.res shows some remaining + layout differences (line breaking decisions for very long callbacks). + +3. **Underscore Apply Rewriting**: Need to implement: + - `rewrite_underscore_apply`: `(__x) => f(a, __x, c)` -> `f(a, _, c)` + - `rewrite_underscore_apply_in_pipe`: `(__x) => f(__x, a)` -> `f(a)` (omit first _) + +4. **Binary Expression Indentation**: Need `should_indent_binary_expr` function that checks: + - Is it an equality operator? + - Is the LHS NOT a same-precedence subexpression? + - Is the operator `:=`? + +5. **Inline Record Definitions**: Type declarations with `res.inlineRecordDefinition` attribute + need special handling - print record fields inline instead of as separate types. + +6. **Spread Array Syntax**: Currently prints desugared form `Belt.Array.concatMany([xs, [a, b]])` + instead of `[...xs, a, b]`. + +--- + +## Phase 1: Comment Handling (Root Cause) + +Most printer failures are caused by comment handling issues. Fix these first. + +### Core Comment Infrastructure +- [x] **Study OCaml comment attachment** - Read `res_comments_table.ml` thoroughly to understand the algorithm +- [x] **Fix trailing comment preservation** - Comments after expressions/statements get lost +- [x] **Fix blank line preservation around comments** - Blank lines before/after comments should be kept +- [x] **Fix comment placement in function arguments** - `/* c0 */ ~arg=/* c1 */ value /* c2 */` pattern +- [x] **Fix comment placement in function parameters** - Comments on function parameter definitions + +### Comment Test Files (1 failing, 16 passing) +- [x] `printer/comments/namedArgs.res` - Named argument comments +- [x] `printer/comments/trailingComments.res` - Trailing comment handling +- [x] `printer/comments/modExpr.res` - Module expression comments +- [x] `printer/comments/structureItem.res` - Structure item comments +- [x] `printer/comments/blockExpr.res` - Block expression comments +- [x] `printer/comments/expr.res` - General expression comments +- [x] `printer/comments/jsx.res` - JSX element comments +- [x] `printer/comments/binaryExpr.res` - Binary expression comments (flattening logic) +- [x] `printer/comments/case.res` - Match case comments +- [x] `printer/comments/array.res` - Array literal comments (spread syntax now implemented) +- [x] `printer/comments/docComments.res` - Doc comment handling +- [x] `printer/comments/typexpr.res` - Type expression comments +- [x] `printer/comments/modType.res` - Module type comments +- [x] `printer/comments/signatureItem.resi` - Signature item comments +- [x] `printer/comments/valueBindingSugar.res` - Value binding sugar comments +- [x] `printer/comments/typeDefinition.res` - Type definition comments +- [x] `printer/comments/extensionConstructor.res` - Extension constructor comments + +--- + +## Phase 2: Expression Printing (13 failing) + +### Passing (31 tests) +- [x] `printer/expr/apply.res` +- [x] `printer/expr/array.res` +- [x] `printer/expr/arrayGet.res` +- [x] `printer/expr/arraySet.res` +- [x] `printer/expr/assert.res` +- [x] `printer/expr/block.res` +- [x] `printer/expr/bsObj.res` +- [x] `printer/expr/coerce.res` +- [x] `printer/expr/constant.res` +- [x] `printer/expr/constraint.res` +- [x] `printer/expr/constructor.res` +- [x] `printer/expr/exoticIdent.res` +- [x] `printer/expr/extension.res` +- [x] `printer/expr/field.res` +- [x] `printer/expr/firstClassModule.res` +- [x] `printer/expr/for.res` +- [x] `printer/expr/fun.res` +- [x] `printer/expr/ident.res` +- [x] `printer/expr/if.res` +- [x] `printer/expr/jsObjectAccess.res` +- [x] `printer/expr/jsObjectSet.res` +- [x] `printer/expr/let.res` +- [x] `printer/expr/letexception.res` +- [x] `printer/expr/letmodule.res` +- [x] `printer/expr/letUnwrap.res` +- [x] `printer/expr/nestedCallbacks.res` +- [x] `printer/expr/newtype.res` +- [x] `printer/expr/open.res` +- [x] `printer/expr/pipe.res` +- [x] `printer/expr/record.res` +- [x] `printer/expr/RecordOrObject.res` +- [x] `printer/expr/sequence.res` +- [x] `printer/expr/setfield.res` +- [x] `printer/expr/sideEffects.res` +- [x] `printer/expr/smartPipe.res` +- [x] `printer/expr/ternary.res` +- [x] `printer/expr/try.res` +- [x] `printer/expr/tuple.res` +- [x] `printer/expr/unary.res` +- [x] `printer/expr/Uncurried.res` +- [x] `printer/expr/while.res` +- [x] `printer/expr/whitespace.res` + +### Failing (10 tests) +- [x] `printer/expr/asyncAwait.res` - Fixed: attribute positioning in pipe expressions +- [x] `printer/expr/binary.res` - Fixed: exponentiation, single pipe, attributed operands +- [x] `printer/expr/braced.res` - Fixed: @JSX attribute preservation, braces in constrained function bodies +- [ ] `printer/expr/callback.res` - Callback layout differences +- [ ] `printer/expr/dict.res` - Comment handling in dict entries +- [x] `printer/expr/DocComments.res` - Fixed: doc comment inline spacing +- [ ] `printer/expr/jsx.res` - JSX-specific issues +- [x] `printer/expr/list.res` - List spread syntax (fixed with spread list implementation) +- [x] `printer/expr/polyvariant.res` - Fixed: tuple hugging in polyvariant constructors +- [x] `printer/expr/switch.res` - Fixed: trailing comments on same line as `}` +- [ ] `printer/expr/templateLiteral.res` - Template literal printing +- [ ] `printer/expr/UncurriedByDefault.res` - Uncurried by default mode +- [ ] `printer/expr/underscoreApply.res` - Underscore apply rewriting + +--- + +## Phase 3: Module Printing (0 failing - COMPLETE!) + +### Module Expressions (all passing) +- [x] `printer/modExpr/apply.res` +- [x] `printer/modExpr/await.res` +- [x] `printer/modExpr/extension.res` +- [x] `printer/modExpr/functor.res` +- [x] `printer/modExpr/include.res` +- [x] `printer/modExpr/structure.res` +- [x] `printer/modExpr/unpack.res` + +### Module Types (all passing) +- [x] `printer/modType/exoticIdent.res` +- [x] `printer/modType/extension.res` +- [x] `printer/modType/functor.res` +- [x] `printer/modType/ident.res` +- [x] `printer/modType/moduleTypeOf.res` +- [x] `printer/modType/signature.res` +- [x] `printer/modType/withConstraints.res` + +--- + +## Phase 4: Structure Printing (1 failing) + +### Passing (12 tests) +- [x] `printer/structure/attribute.res` +- [x] `printer/structure/exception.res` +- [x] `printer/structure/expr.res` +- [x] `printer/structure/extension.res` +- [x] `printer/structure/external.res` +- [x] `printer/structure/moduleBinding.res` +- [x] `printer/structure/moduleTypeDeclaration.res` +- [x] `printer/structure/open.res` +- [x] `printer/structure/recModules.res` +- [x] `printer/structure/type.res` +- [x] `printer/structure/typeExtension.res` +- [x] `printer/structure/valueBinding.res` + +### Failing (1 test) +- [ ] `printer/structure/include.res` - Include with comment formatting + +--- + +## Phase 5: Other Categories + +### Signatures (0 failing, 11 passing - COMPLETE!) +- [x] `printer/signature/attributes.resi` +- [x] `printer/signature/exception.resi` +- [x] `printer/signature/extension.resi` +- [x] `printer/signature/include.resi` +- [x] `printer/signature/modtype.resi` +- [x] `printer/signature/module.resi` +- [x] `printer/signature/open.resi` +- [x] `printer/signature/recModule.resi` +- [x] `printer/signature/typext.resi` +- [x] `printer/signature/value.resi` +- [x] `printer/signature/type.resi` - Fixed: inline record definitions + +### Patterns (1 failing, 16 passing) +- [x] `printer/pattern/alias.res` +- [x] `printer/pattern/any.res` +- [x] `printer/pattern/array.res` +- [x] `printer/pattern/constant.res` +- [x] `printer/pattern/constraint.res` +- [x] `printer/pattern/construct.res` +- [x] `printer/pattern/exception.res` +- [x] `printer/pattern/exoticIdent.res` +- [x] `printer/pattern/extension.res` +- [x] `printer/pattern/firstClassModules.res` +- [x] `printer/pattern/interval.res` +- [x] `printer/pattern/list.res` +- [x] `printer/pattern/or.res` +- [x] `printer/pattern/record.res` +- [x] `printer/pattern/tuple.res` +- [x] `printer/pattern/type.res` +- [x] `printer/pattern/var.res` +- [x] `printer/pattern/variant.res` +- [ ] `printer/pattern/dict.res` - Dict pattern comments + +### Types (1 failing, all typeDef passing) +- [x] `printer/typeDef/abstract.res` +- [x] `printer/typeDef/attributes.res` +- [x] `printer/typeDef/constraint.res` +- [x] `printer/typeDef/exoticIdent.res` +- [x] `printer/typeDef/missingPipeBeforeConstructorAttribute.res` +- [x] `printer/typeDef/open.res` +- [x] `printer/typeDef/private.res` +- [x] `printer/typeDef/record.res` +- [x] `printer/typeDef/typeParams.res` +- [x] `printer/typeDef/variant.res` +- [x] `printer/typexpr/alias.res` +- [x] `printer/typexpr/any.res` +- [x] `printer/typexpr/arrow.res` +- [x] `printer/typexpr/bsObject.res` +- [x] `printer/typexpr/exoticIdent.res` +- [x] `printer/typexpr/extension.res` +- [x] `printer/typexpr/firstClassModule.res` +- [x] `printer/typexpr/objectTypeSpreading.res` +- [x] `printer/typexpr/polyTyp.res` +- [x] `printer/typexpr/tuple.res` +- [x] `printer/typexpr/typeConstr.res` +- [x] `printer/typexpr/var.res` +- [x] `printer/typexpr/variant.res` - Polyvariant comment handling (fixed: wrap tag_doc with print_comments) + +### Other (1 failing, 16 passing) +- [x] `printer/other/attributes.res` +- [x] `printer/other/case.res` +- [x] `printer/other/char.res` +- [x] `printer/other/comments.res` +- [x] `printer/other/fatSlider.res` +- [x] `printer/other/home.res` +- [x] `printer/other/lor.res` +- [x] `printer/other/moduleData.res` +- [x] `printer/other/number.res` +- [x] `printer/other/reasonArity.res` +- [x] `printer/other/reasonFile.res` +- [x] `printer/other/reasonInterfaceFile.resi` +- [x] `printer/other/reasonString.res` +- [x] `printer/other/signaturePicker.res` +- [x] `printer/other/StaticReactTypes.res` +- [x] `printer/other/string.res` +- [ ] `printer/other/nesting.res` - Complex nested callback layout + +--- + +## Phase 6: Parser Crashes (Priority!) + +Some tests cause the Rust parser to crash (Abort trap: 6). These must be fixed. + +- [ ] Investigate and fix parser crashes in infinite loop tests +- [ ] Add proper error handling for malformed input + +--- + +## Phase 7: Non-Printer Tests (CURRENT PRIORITY) + +Printer parity is complete (187/187). Now fix the remaining 191 failing tests. + +### Test Commands for Each Category + +```bash +# Error recovery tests (uses -recover -print ml) +./compiler-rust/target/release/res_parser_rust -recover -print ml tests/syntax_tests/data/parsing/errors/FILE.res + +# Grammar tests (uses -print ml without -recover) +./compiler-rust/target/release/res_parser_rust -print ml tests/syntax_tests/data/parsing/grammar/FILE.res + +# PPX/React tests (uses -jsx-version 4) +./compiler-rust/target/release/res_parser_rust -jsx-version 4 tests/syntax_tests/data/ppx/react/FILE.res + +# AST conversion tests +./compiler-rust/target/release/res_parser_rust -test-ast-conversion -jsx-version 4 tests/syntax_tests/data/ast-mapping/FILE.res + +# Compare with OCaml +./_build/install/default/bin/res_parser -recover -print ml tests/syntax_tests/data/parsing/errors/FILE.res +``` + +### parsing/errors - ~77 failing (error recovery mode) + +These tests run with `-recover -print ml` and test error recovery behavior. + +**CRITICAL MISSING FEATURE: Consecutive statement/expression error checking** + +OCaml has `parse_newline_or_semicolon_expr_block` and `parse_newline_or_semicolon_structure` +functions that check if statements/expressions on the same line are separated by `;` or newline. +If not, they emit "consecutive statements/expressions on a line must be separated by ';' or a newline". + +The Rust parser just uses `p.optional(&Token::Semicolon)` and doesn't perform this check. +This is a root cause for MANY of the 77 failing tests - error messages are simply missing. + +**Implementation needed:** +1. Add `is_block_expr_start()` function matching OCaml's `Grammar.is_block_expr_start` +2. Add `check_consecutive_expr_block(p)` that: + - If token is Semicolon -> consume it + - Else if `is_block_expr_start(token)` AND `p.prev_end_pos.line < p.start_pos.line` -> OK + - Else if `is_block_expr_start(token)` -> emit "consecutive expressions" error +3. Add `check_consecutive_structure(p)` with similar logic for structure items +4. Replace `p.optional(&Token::Semicolon)` with these functions in parse_block_body() etc. + +**OCaml reference:** +- `compiler/syntax/src/res_grammar.ml:266` - `is_block_expr_start` function +- `compiler/syntax/src/res_core.ml:3509` - `parse_newline_or_semicolon_expr_block` +- `compiler/syntax/src/res_core.ml:6335` - `parse_newline_or_semicolon_structure` + +**Other issues to fix:** +- [x] Array access syntax (OCaml uses `arr.(i)`, fixed in ML printer) +- [ ] Error message locations - different line:col positions due to different error recovery +- [ ] Recovered AST output - ML printer line breaking differs from OCaml +- [ ] Error hole placement - `[%rescript.exprhole]` vs `()` in recovered AST +- [ ] Error message wording - differs from OCaml's res_diagnostics.ml +- [ ] Path prefix in error locations - `syntax_tests/data/` vs `tests/syntax_tests/data/` + +**OCaml reference files:** +- `compiler/syntax/src/res_diagnostics.ml` - Error messages +- `compiler/syntax/src/res_core.ml` - Parser with recovery logic +- `compiler/syntax/src/res_outcome_printer.ml` - ML AST printer + +### parsing/grammar - 57 failing + +Grammar parsing tests without error recovery. + +**ROOT CAUSE: ML printer 80-column line wrapping** + +⚠️ **IMPORTANT**: The Rust formatting code (`format.rs`, `doc.rs`, `formatter.rs`) is NOT meant +to be an "emulation" of Format - it must be a **1:1 port** of OCaml's Format module. If there +are differences, look at the OCaml Format source (`stdlib/format.ml`) and make the Rust code +match exactly. Do not try to "fix" or "improve" - just match OCaml's behavior precisely. + +Most failures are because OCaml's Format module wraps long lines at 78 columns (not 80!), +but the Rust Formatter doesn't match this behavior exactly. For example: + +OCaml output (wraps at 80): +``` +include ((sig val s : string val y : int end)[@onSignature ])[@@onInclude + ] +``` + +Rust output (doesn't wrap): +``` +include ((sig val s : string val y : int end)[@onSignature ])[@@onInclude ] +``` + +The Rust Formatter implements box-based formatting, but the line-break decisions +don't always match OCaml's Format module. This affects: +- Long type declarations +- Attributes on long lines +- HOV box packing behavior + +**Other issues:** +- [ ] Record field punning - `{ a; b }` vs `{ a = a; b = b }` +- [ ] Optional field syntax - `x?` and `name?` printed differently +- [ ] Arrow type attributes - `[@attr]` position differs + +### parsing/recovery - 16 failing + +Additional recovery mode tests. + +### parsing/infiniteLoops - 5 failing + +Tests that previously caused infinite loops. May involve parser crashes. + +### parsing/other - 3 failing + +Miscellaneous parsing tests. + +### ppx/react - 0 failing ✅ + +JSX transformation tests using `-jsx-version 4`. All passing! + +### conversion - 0 failing ✅ + +ML/Reason to ReScript conversion tests. All passing! + +### ast-mapping - 0 failing ✅ + +AST conversion tests using `-test-ast-conversion`. All passing! + +--- + +## Commands Reference + +```bash +# Run all syntax tests (MUST PASS ALL for completion) +PARSER=rust ./scripts/test_syntax.sh 2>&1 | tail -50 + +# Build after changes +cargo build --manifest-path compiler-rust/Cargo.toml --release + +# Test single file - printer mode (default) +./compiler-rust/target/release/res_parser_rust FILE.res + +# Test single file - error recovery mode +./compiler-rust/target/release/res_parser_rust -recover -print ml FILE.res + +# Test single file - grammar mode (no recovery) +./compiler-rust/target/release/res_parser_rust -print ml FILE.res + +# Test single file - JSX PPX mode +./compiler-rust/target/release/res_parser_rust -jsx-version 4 FILE.res + +# Test single file - AST conversion mode +./compiler-rust/target/release/res_parser_rust -test-ast-conversion -jsx-version 4 FILE.res + +# Compare with OCaml (printer mode) +./_build/install/default/bin/res_parser FILE.res + +# Compare with OCaml (error recovery mode) +./_build/install/default/bin/res_parser -recover -print ml FILE.res + +# View diff for failing test +diff tests/syntax_tests/data/PATH/expected/FILE.txt \ + tests/temp/syntax_tests/data/PATH/expected/FILE.txt + +# List all failing tests +grep '^FAIL:' tests/temp/results.txt | cut -d: -f2 +``` + +--- + +## Notes + +- Focus on **root causes** not symptoms - many failures share the same underlying issue +- Printer tests (Phase 1-6) are COMPLETE - focus on Phase 7 (non-printer tests) +- Commit after EVERY improvement, even if just 1 more test passes +- Study the OCaml code, don't guess! +- **If a task is hard, don't skip it to find an easier one** - commit your progress and keep working on it +- **The task is NOT complete until ALL 506 syntax tests pass** +- Output `RALPH_COMPLETE` only when `PARSER=rust ./scripts/test_syntax.sh` shows 0 failures diff --git a/compiler-rust/src/arena.rs b/compiler-rust/src/arena.rs new file mode 100644 index 00000000000..35252eaa580 --- /dev/null +++ b/compiler-rust/src/arena.rs @@ -0,0 +1,211 @@ +//! Generic arena allocation. +//! +//! This module provides a simple arena for storing values and referencing them +//! by lightweight indices. Unlike traditional interning, there is no deduplication - +//! each push creates a new entry. +//! +//! # Example +//! +//! ```ignore +//! use rescript_compiler::arena::{Arena, ArenaIdx}; +//! +//! // Define a custom index type +//! #[derive(Clone, Copy, PartialEq, Eq)] +//! struct MyIdx(u32); +//! +//! impl ArenaIdx for MyIdx { +//! fn from_u32(idx: u32) -> Self { MyIdx(idx) } +//! fn to_u32(self) -> u32 { self.0 } +//! } +//! +//! let mut arena: Arena = Arena::new(); +//! let idx = arena.push("hello".to_string()); +//! assert_eq!(arena.get(idx), "hello"); +//! ``` + +use std::marker::PhantomData; + +// ============================================================================ +// Arena Index Trait +// ============================================================================ + +/// Trait for arena index types. +/// +/// This allows Arena to be generic over the index type, providing type safety. +/// Instead of using raw `u32` indices everywhere, you can define wrapper types +/// like `PosIdx` or `LocIdx` that implement this trait. +pub trait ArenaIdx: Copy { + /// Create an index from a raw u32 value. + fn from_u32(idx: u32) -> Self; + /// Convert the index to a raw u32 value. + fn to_u32(self) -> u32; +} + +impl ArenaIdx for u32 { + fn from_u32(idx: u32) -> Self { + idx + } + fn to_u32(self) -> u32 { + self + } +} + +// ============================================================================ +// Generic Arena +// ============================================================================ + +/// Simple arena for storing values and referencing them by index. +/// +/// Values are pushed and indices are returned. No automatic deduplication - +/// each push creates a new entry. +/// +/// The `Idx` type parameter allows using typed indices like `PosIdx` or `LocIdx` +/// instead of plain `u32`, which provides type safety and prevents mixing up +/// indices from different arenas. +#[derive(Debug)] +pub struct Arena { + items: Vec, + _phantom: PhantomData, +} + +impl Default for Arena { + fn default() -> Self { + Self { + items: Vec::new(), + _phantom: PhantomData, + } + } +} + +impl Arena { + /// Create a new empty arena. + pub fn new() -> Self { + Self::default() + } + + /// Create a new arena with pre-allocated capacity. + pub fn with_capacity(capacity: usize) -> Self { + Self { + items: Vec::with_capacity(capacity), + _phantom: PhantomData, + } + } + + /// Push a value into the arena and return its typed index. + pub fn push(&mut self, item: T) -> Idx { + let idx = self.items.len() as u32; + self.items.push(item); + Idx::from_u32(idx) + } + + /// Get a reference to a value by typed index. + pub fn get(&self, idx: Idx) -> &T { + &self.items[idx.to_u32() as usize] + } + + /// Get a mutable reference to a value by typed index. + pub fn get_mut(&mut self, idx: Idx) -> &mut T { + &mut self.items[idx.to_u32() as usize] + } + + /// Get the number of items in the arena. + pub fn len(&self) -> usize { + self.items.len() + } + + /// Check if the arena is empty. + pub fn is_empty(&self) -> bool { + self.items.is_empty() + } + + /// Get all items as a slice. + pub fn as_slice(&self) -> &[T] { + &self.items + } + + /// Iterate over all items with their indices. + pub fn iter(&self) -> impl Iterator { + self.items + .iter() + .enumerate() + .map(|(i, item)| (Idx::from_u32(i as u32), item)) + } +} + +// ============================================================================ +// Tests +// ============================================================================ + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_arena_basic() { + let mut arena: Arena = Arena::new(); + assert!(arena.is_empty()); + + let idx0 = arena.push(10); + let idx1 = arena.push(20); + let idx2 = arena.push(30); + + assert_eq!(idx0, 0); + assert_eq!(idx1, 1); + assert_eq!(idx2, 2); + + assert_eq!(*arena.get(0), 10); + assert_eq!(*arena.get(1), 20); + assert_eq!(*arena.get(2), 30); + + assert_eq!(arena.len(), 3); + } + + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + struct TestIdx(u32); + + impl ArenaIdx for TestIdx { + fn from_u32(idx: u32) -> Self { + TestIdx(idx) + } + fn to_u32(self) -> u32 { + self.0 + } + } + + #[test] + fn test_typed_arena() { + let mut arena: Arena = Arena::new(); + + let idx0 = arena.push(10); + let idx1 = arena.push(20); + + assert_eq!(idx0, TestIdx(0)); + assert_eq!(idx1, TestIdx(1)); + + assert_eq!(*arena.get(idx0), 10); + assert_eq!(*arena.get(idx1), 20); + } + + #[test] + fn test_arena_iter() { + let mut arena: Arena<&str, TestIdx> = Arena::new(); + arena.push("a"); + arena.push("b"); + arena.push("c"); + + let collected: Vec<_> = arena.iter().collect(); + assert_eq!(collected.len(), 3); + assert_eq!(collected[0], (TestIdx(0), &"a")); + assert_eq!(collected[1], (TestIdx(1), &"b")); + assert_eq!(collected[2], (TestIdx(2), &"c")); + } + + #[test] + fn test_arena_get_mut() { + let mut arena: Arena = Arena::new(); + let idx = arena.push(10); + + *arena.get_mut(idx) = 20; + assert_eq!(*arena.get(idx), 20); + } +} diff --git a/compiler-rust/src/bin/bsc.rs b/compiler-rust/src/bin/bsc.rs index 470a53a8a2b..574d9131cd0 100644 --- a/compiler-rust/src/bin/bsc.rs +++ b/compiler-rust/src/bin/bsc.rs @@ -132,10 +132,13 @@ fn run() -> Result<()> { } fn generate_ast(input: &Path, output: Option) -> Result<()> { - // Use lossy UTF-8 conversion (like OCaml) to handle files with invalid bytes + // Read file as raw bytes, converting each byte to a char (Latin-1 encoding). + // This matches OCaml's byte-level string handling where each byte is a character. + // In Latin-1 mode, char offset == original byte offset, which is critical for + // correct position tracking in the scanner. let bytes = fs::read(input).with_context(|| format!("Failed to read {}", input.display()))?; - let source = String::from_utf8_lossy(&bytes).into_owned(); + let source: String = bytes.iter().map(|&b| b as char).collect(); // Use the original path as provided (matching OCaml's behavior) // OCaml does not canonicalize paths - it uses them as-is @@ -173,7 +176,7 @@ fn generate_ast(input: &Path, output: Option) -> Result<()> { parser.diagnostics().len() )); } - write_signature_ast_current(&out_path, &source_path, &signature) + write_signature_ast_current(&out_path, &source_path, parser.arena(), &signature) .with_context(|| format!("Failed to write {}", out_path.display()))?; } else { // Parse structure (implementation file) @@ -184,7 +187,7 @@ fn generate_ast(input: &Path, output: Option) -> Result<()> { parser.diagnostics().len() )); } - write_structure_ast_current(&out_path, &source_path, &structure) + write_structure_ast_current(&out_path, &source_path, parser.arena(), &structure) .with_context(|| format!("Failed to write {}", out_path.display()))?; } diff --git a/compiler-rust/src/bin/res_parser.rs b/compiler-rust/src/bin/res_parser.rs index 00b620919c5..17bb5fa7230 100644 --- a/compiler-rust/src/bin/res_parser.rs +++ b/compiler-rust/src/bin/res_parser.rs @@ -20,8 +20,9 @@ use clap::Parser as ClapParser; use rescript_compiler::binary_ast::{mapper_from0, mapper_to0, Marshal, MarshalWriter}; +use rescript_compiler::parse_arena::ParseArena; use rescript_compiler::parser::{ - code_frame, jsx_ppx, ml_printer, module, print_signature, printer, printer2, sexp, sexp_locs, sexp_locs0, Parser, + code_frame, jsx_ppx, ml_printer, module, printer2, sexp, sexp_locs, sexp_locs0, Comment, Parser, ParserMode, Scanner, SignatureItem, Structure, }; use std::fs; @@ -136,7 +137,11 @@ fn main() { // Read file as raw bytes, converting each byte to a char (Latin-1 encoding). // This preserves the original byte sequence through the compilation pipeline, - // matching OCaml's behavior where strings are byte sequences, not Unicode. + // allowing the final output to convert back to bytes with `c as u8`. + // This approach handles both ASCII and UTF-8 files correctly because: + // - Each byte becomes a char with code point 0-255 + // - The ML printer's escape_string function properly escapes bytes > 127 + // - The output conversion `c as u8` recovers the original bytes let source = match fs::read(&args.file) { Ok(bytes) => bytes.iter().map(|&b| b as char).collect::(), Err(e) => { @@ -175,12 +180,12 @@ fn main() { } // Apply JSX PPX transformation - let signature = jsx_ppx::transform_signature(signature, args.jsx_version); + let signature = jsx_ppx::transform_signature(signature, args.jsx_version, parser.arena_mut()); // Apply AST conversion round-trip if requested (for testing) let signature = if args.test_ast_conversion { - let sig0 = mapper_to0::map_signature(&signature); - mapper_from0::map_signature(&sig0) + let sig0 = mapper_to0::map_signature(parser.arena_mut(), &signature); + mapper_from0::map_signature(parser.arena_mut(), &sig0) } else { signature }; @@ -191,17 +196,17 @@ fn main() { // Capture ML output using StringWriter, then convert chars to Latin-1 bytes. // This preserves the original file bytes through the round-trip. let mut writer = StringWriter::new(); - ml_printer::print_signature_ml(&signature, &mut writer); + ml_printer::print_signature_ml(&signature, parser.arena(), &mut writer); let output = writer.into_string(); let bytes: Vec = output.chars().map(|c| c as u8).collect(); let _ = io::stdout().write_all(&bytes); } - "res" => print_signature_res(&signature, &mut io::stdout()), - "sexp" => sexp::print_signature(&signature, &mut io::stdout()), - "sexp-locs" => sexp_locs::print_signature(&signature, &mut io::stdout()), + "res" => print_signature_res(&signature, parser.comments().to_vec(), parser.arena_mut(), &mut io::stdout()), + "sexp" => sexp::print_signature(parser.arena(), &signature, &mut io::stdout()), + "sexp-locs" => sexp_locs::print_signature(&signature, parser.arena(), &mut io::stdout()), "sexp0-locs" => { - let sig0 = mapper_to0::map_signature(&signature); - sexp_locs0::print_signature(&sig0, &mut io::stdout()); + let sig0 = mapper_to0::map_signature(parser.arena_mut(), &signature); + sexp_locs0::print_signature(parser.arena(), &sig0, &mut io::stdout()); } "ast" => print_signature_ast(&signature, &mut io::stdout()), "binary" => { @@ -220,6 +225,7 @@ fn main() { // Marshal signature let mut w = MarshalWriter::new(); + w.set_arena(parser.arena()); signature.marshal(&mut w); let _ = io::stdout().write_all(&w.finish()); } @@ -228,7 +234,7 @@ fn main() { // Same layout as binary but with parsetree0 types // Convert to parsetree0 - let sig0 = mapper_to0::map_signature(&signature); + let sig0 = mapper_to0::map_signature(parser.arena_mut(), &signature); // Write magic let _ = io::stdout().write_all(b"Caml1999N022"); @@ -240,6 +246,7 @@ fn main() { // Marshal parsetree0 signature let mut w = MarshalWriter::new(); + w.set_arena(parser.arena()); sig0.marshal(&mut w); let _ = io::stdout().write_all(&w.finish()); } @@ -262,12 +269,12 @@ fn main() { } // Apply JSX PPX transformation - let structure = jsx_ppx::transform_structure(structure, args.jsx_version); + let structure = jsx_ppx::transform_structure(structure, args.jsx_version, parser.arena_mut()); // Apply AST conversion round-trip if requested (for testing) let structure = if args.test_ast_conversion { - let str0 = mapper_to0::map_structure(&structure); - mapper_from0::map_structure(&str0) + let str0 = mapper_to0::map_structure(parser.arena_mut(), &structure); + mapper_from0::map_structure(parser.arena_mut(), &str0) } else { structure }; @@ -278,25 +285,25 @@ fn main() { // Capture ML output using StringWriter, then convert chars to Latin-1 bytes. // This preserves the original file bytes through the round-trip. let mut writer = StringWriter::new(); - ml_printer::print_structure_ml(&structure, &mut writer); + ml_printer::print_structure_ml(&structure, parser.arena(), &mut writer); let output = writer.into_string(); let bytes: Vec = output.chars().map(|c| c as u8).collect(); let _ = io::stdout().write_all(&bytes); } "res" => { let output = - printer2::print_structure_with_comments(&structure, parser.comments().to_vec()); + printer2::print_structure_with_comments(&structure, parser.comments().to_vec(), parser.arena_mut()); if !output.is_empty() { // Convert Latin-1 chars back to bytes to preserve original file encoding let bytes: Vec = output.chars().map(|c| c as u8).collect(); let _ = io::stdout().write_all(&bytes); } } - "sexp" => sexp::print_structure(&structure, &mut io::stdout()), - "sexp-locs" => sexp_locs::print_structure(&structure, &mut io::stdout()), + "sexp" => sexp::print_structure(parser.arena(), &structure, &mut io::stdout()), + "sexp-locs" => sexp_locs::print_structure(&structure, parser.arena(), &mut io::stdout()), "sexp0-locs" => { - let str0 = mapper_to0::map_structure(&structure); - sexp_locs0::print_structure(&str0, &mut io::stdout()); + let str0 = mapper_to0::map_structure(parser.arena_mut(), &structure); + sexp_locs0::print_structure(parser.arena(), &str0, &mut io::stdout()); } "ast" => print_structure_ast(&structure, &mut io::stdout()), "binary" => { @@ -315,6 +322,7 @@ fn main() { // Marshal structure let mut w = MarshalWriter::new(); + w.set_arena(parser.arena()); structure.marshal(&mut w); let _ = io::stdout().write_all(&w.finish()); } @@ -323,7 +331,7 @@ fn main() { // Same layout as binary but with parsetree0 types // Convert to parsetree0 - let str0 = mapper_to0::map_structure(&structure); + let str0 = mapper_to0::map_structure(parser.arena_mut(), &structure); // Write magic let _ = io::stdout().write_all(b"Caml1999M022"); @@ -335,6 +343,7 @@ fn main() { // Marshal parsetree0 structure let mut w = MarshalWriter::new(); + w.set_arena(parser.arena()); str0.marshal(&mut w); let _ = io::stdout().write_all(&w.finish()); } @@ -351,12 +360,13 @@ fn main() { /// Print parser diagnostics in OCaml-compatible format fn print_diagnostics(parser: &Parser, source: &str, filename: &str, out: &mut impl Write) { for diag in parser.diagnostics() { + // OCaml uses explain_with_source to detect old syntax like |> and [|...|] let error_msg = code_frame::format_error( filename, source, &diag.start_pos, &diag.end_pos, - &diag.explain(), + &diag.explain_with_source(Some(source)), ); let _ = out.write_all(error_msg.as_bytes()); } @@ -371,7 +381,10 @@ fn print_comments(parser: &Parser, out: &mut impl Write) { /// Print tokens from source fn print_tokens(source: &str, filename: &str, out: &mut impl Write) { - let mut scanner = Scanner::new(filename, source); + // Create a temporary arena to intern the filename + let mut arena = ParseArena::new(); + let filename_idx = arena.intern_string(filename); + let mut scanner = Scanner::new(filename_idx, source); loop { let result = scanner.scan(); let start_col = result.start_pos.cnum - result.start_pos.bol; @@ -395,14 +408,13 @@ fn print_tokens(source: &str, filename: &str, out: &mut impl Write) { // ReScript Printer // ============================================================================ -fn print_signature_res(signature: &[SignatureItem], out: &mut impl Write) { - // Use the built-in printer from the parser module - let output = print_signature(signature); +fn print_signature_res(signature: &[SignatureItem], comments: Vec, arena: &mut ParseArena, out: &mut impl Write) { + // Use printer2 to print signature + let output = printer2::print_signature_with_comments(signature, comments, arena); if !output.is_empty() { // Convert Latin-1 chars back to bytes to preserve original file encoding let bytes: Vec = output.chars().map(|c| c as u8).collect(); let _ = out.write_all(&bytes); - let _ = out.write_all(b"\n"); } } diff --git a/compiler-rust/src/binary_ast/current_marshal.rs b/compiler-rust/src/binary_ast/current_marshal.rs index 1dc1b2ab9b7..d797655f6c2 100644 --- a/compiler-rust/src/binary_ast/current_marshal.rs +++ b/compiler-rust/src/binary_ast/current_marshal.rs @@ -109,13 +109,17 @@ impl Marshal for ArgLabel { w.write_block_header(0, 1); // The string loc is block(tag=0, size=2) with txt and loc w.write_block_header(0, 2); - w.write_str(&s.txt); + // Look up string from arena via StrIdx + let str_val = w.get_arena().get_string(s.txt).to_string(); + w.write_str(&str_val); s.loc.marshal(w); } ArgLabel::Optional(s) => { w.write_block_header(1, 1); w.write_block_header(0, 2); - w.write_str(&s.txt); + // Look up string from arena via StrIdx + let str_val = w.get_arena().get_string(s.txt).to_string(); + w.write_str(&str_val); s.loc.marshal(w); } } @@ -159,7 +163,8 @@ impl Marshal for Constant { Constant::String(s, delim) => { w.write_block_header(2, 2); w.write_str(s); - delim.marshal(w); + // Use content-based sharing for string delimiters like Some("js") + w.write_option_string(delim); } Constant::Float(s, suffix) => { w.write_block_header(3, 2); diff --git a/compiler-rust/src/binary_ast/deps.rs b/compiler-rust/src/binary_ast/deps.rs index f2b7726e93b..844de82272b 100644 --- a/compiler-rust/src/binary_ast/deps.rs +++ b/compiler-rust/src/binary_ast/deps.rs @@ -17,33 +17,36 @@ use crate::parser::ast::{ Payload, RowField, SignatureItem, SignatureItemDesc, StructureItem, StructureItemDesc, TypeDeclaration, TypeExtension, TypeKind, ValueBinding, ValueDescription, WithConstraint, }; +use crate::parse_arena::{LidentIdx, ParseArena}; use crate::parser::longident::Longident; /// A set of module dependencies, sorted for deterministic output. pub type Dependencies = BTreeSet; /// Extract module dependencies from a structure (implementation). -pub fn extract_structure_deps(structure: &[StructureItem]) -> Dependencies { - let mut collector = DependencyCollector::new(); +pub fn extract_structure_deps(arena: &ParseArena, structure: &[StructureItem]) -> Dependencies { + let mut collector = DependencyCollector::new(arena); collector.add_structure(structure); collector.finish() } /// Extract module dependencies from a signature (interface). -pub fn extract_signature_deps(signature: &[SignatureItem]) -> Dependencies { - let mut collector = DependencyCollector::new(); +pub fn extract_signature_deps(arena: &ParseArena, signature: &[SignatureItem]) -> Dependencies { + let mut collector = DependencyCollector::new(arena); collector.add_signature(signature); collector.finish() } /// Collector for module dependencies. -struct DependencyCollector { +struct DependencyCollector<'a> { + arena: &'a ParseArena, deps: BTreeSet, } -impl DependencyCollector { - fn new() -> Self { +impl<'a> DependencyCollector<'a> { + fn new(arena: &'a ParseArena) -> Self { Self { + arena, deps: BTreeSet::new(), } } @@ -62,12 +65,14 @@ impl DependencyCollector { /// Add a module reference from a Longident. fn add_longident(&mut self, lid: &Longident) { // Get the root module name - let parts = lid.flatten(); + let parts = lid.flatten_idx(); if let Some(first) = parts.first() { + // Look up the string content + let first_str = self.arena.get_string(*first); // Only add if it starts with uppercase (module reference) // Lowercase identifiers are local bindings - if first.chars().next().is_some_and(|c| c.is_ascii_uppercase()) { - self.deps.insert((*first).to_string()); + if first_str.chars().next().is_some_and(|c| c.is_ascii_uppercase()) { + self.deps.insert(first_str.to_string()); } } @@ -78,6 +83,12 @@ impl DependencyCollector { } } + /// Add a module reference from a LidentIdx (arena-allocated longident). + fn add_lident_idx(&mut self, lid_idx: LidentIdx) { + let lid = self.arena.get_longident(lid_idx); + self.add_longident(lid); + } + // ========== Structure ========== fn add_structure(&mut self, structure: &[StructureItem]) { @@ -191,7 +202,7 @@ impl DependencyCollector { fn add_expression(&mut self, expr: &Expression) { match &expr.pexp_desc { ExpressionDesc::Pexp_ident(lid) => { - self.add_longident(&lid.txt); + self.add_lident_idx(lid.txt); } ExpressionDesc::Pexp_constant(_) => {} ExpressionDesc::Pexp_let(_rec_flag, bindings, body) => { @@ -230,7 +241,7 @@ impl DependencyCollector { } } ExpressionDesc::Pexp_construct(lid, arg) => { - self.add_longident(&lid.txt); + self.add_lident_idx(lid.txt); if let Some(arg) = arg { self.add_expression(arg); } @@ -242,7 +253,7 @@ impl DependencyCollector { } ExpressionDesc::Pexp_record(fields, spread) => { for field in fields { - self.add_longident(&field.lid.txt); + self.add_lident_idx(field.lid.txt); self.add_expression(&field.expr); } if let Some(spread) = spread { @@ -251,11 +262,11 @@ impl DependencyCollector { } ExpressionDesc::Pexp_field(expr, lid) => { self.add_expression(expr); - self.add_longident(&lid.txt); + self.add_lident_idx(lid.txt); } ExpressionDesc::Pexp_setfield(expr1, lid, expr2) => { self.add_expression(expr1); - self.add_longident(&lid.txt); + self.add_lident_idx(lid.txt); self.add_expression(expr2); } ExpressionDesc::Pexp_ifthenelse(cond, then_expr, else_expr) => { @@ -311,7 +322,7 @@ impl DependencyCollector { self.add_module_expr(me); } ExpressionDesc::Pexp_open(_override, lid, body) => { - self.add_longident(&lid.txt); + self.add_lident_idx(lid.txt); self.add_expression(body); } ExpressionDesc::Pexp_extension((_id, payload)) => { @@ -339,10 +350,10 @@ impl DependencyCollector { // Add dependency from tag name if it's a component match &elem.tag_name.txt { JsxTagName::Upper(lid) => { - self.add_longident(lid); + self.add_lident_idx(*lid); } JsxTagName::QualifiedLower { path, .. } => { - self.add_longident(path); + self.add_lident_idx(*path); } JsxTagName::Lower(_) | JsxTagName::Invalid(_) => {} } @@ -353,10 +364,10 @@ impl DependencyCollector { JsxElement::Container(elem) => { match &elem.tag_name_start.txt { JsxTagName::Upper(lid) => { - self.add_longident(lid); + self.add_lident_idx(*lid); } JsxTagName::QualifiedLower { path, .. } => { - self.add_longident(path); + self.add_lident_idx(*path); } JsxTagName::Lower(_) | JsxTagName::Invalid(_) => {} } @@ -398,7 +409,7 @@ impl DependencyCollector { } } PatternDesc::Ppat_construct(lid, arg) => { - self.add_longident(&lid.txt); + self.add_lident_idx(lid.txt); if let Some(arg) = arg { self.add_pattern(arg); } @@ -410,7 +421,7 @@ impl DependencyCollector { } PatternDesc::Ppat_record(fields, _closed) => { for field in fields { - self.add_longident(&field.lid.txt); + self.add_lident_idx(field.lid.txt); self.add_pattern(&field.pat); } } @@ -423,7 +434,7 @@ impl DependencyCollector { self.add_core_type(ty); } PatternDesc::Ppat_type(lid) => { - self.add_longident(&lid.txt); + self.add_lident_idx(lid.txt); } PatternDesc::Ppat_unpack(_name) => {} PatternDesc::Ppat_exception(pat) => { @@ -433,7 +444,7 @@ impl DependencyCollector { self.add_payload(payload); } PatternDesc::Ppat_open(lid, pat) => { - self.add_longident(&lid.txt); + self.add_lident_idx(lid.txt); self.add_pattern(pat); } } @@ -454,7 +465,7 @@ impl DependencyCollector { } } CoreTypeDesc::Ptyp_constr(lid, args) => { - self.add_longident(&lid.txt); + self.add_lident_idx(lid.txt); for arg in args { self.add_core_type(arg); } @@ -492,9 +503,9 @@ impl DependencyCollector { self.add_core_type(ty); } CoreTypeDesc::Ptyp_package((lid, constraints)) => { - self.add_longident(&lid.txt); + self.add_lident_idx(lid.txt); for (lid, ty) in constraints { - self.add_longident(&lid.txt); + self.add_lident_idx(lid.txt); self.add_core_type(ty); } } @@ -509,7 +520,7 @@ impl DependencyCollector { fn add_module_expr(&mut self, me: &ModuleExpr) { match &me.pmod_desc { ModuleExprDesc::Pmod_ident(lid) => { - self.add_longident(&lid.txt); + self.add_lident_idx(lid.txt); } ModuleExprDesc::Pmod_structure(str) => { self.add_structure(str); @@ -540,7 +551,7 @@ impl DependencyCollector { fn add_module_type(&mut self, mt: &ModuleType) { match &mt.pmty_desc { ModuleTypeDesc::Pmty_ident(lid) | ModuleTypeDesc::Pmty_alias(lid) => { - self.add_longident(&lid.txt); + self.add_lident_idx(lid.txt); } ModuleTypeDesc::Pmty_signature(sig) => { self.add_signature(sig); @@ -569,13 +580,13 @@ impl DependencyCollector { fn add_with_constraint(&mut self, constraint: &WithConstraint) { match constraint { WithConstraint::Pwith_type(lid, td) | WithConstraint::Pwith_typesubst(lid, td) => { - self.add_longident(&lid.txt); + self.add_lident_idx(lid.txt); self.add_type_declaration(td); } WithConstraint::Pwith_module(lid1, lid2) | WithConstraint::Pwith_modsubst(lid1, lid2) => { - self.add_longident(&lid1.txt); - self.add_longident(&lid2.txt); + self.add_lident_idx(lid1.txt); + self.add_lident_idx(lid2.txt); } } } @@ -640,7 +651,7 @@ impl DependencyCollector { } fn add_type_extension(&mut self, te: &TypeExtension) { - self.add_longident(&te.ptyext_path.txt); + self.add_lident_idx(te.ptyext_path.txt); for (ty, _variance) in &te.ptyext_params { self.add_core_type(ty); } @@ -658,7 +669,7 @@ impl DependencyCollector { } } ExtensionConstructorKind::Pext_rebind(lid) => { - self.add_longident(&lid.txt); + self.add_lident_idx(lid.txt); } } } @@ -678,7 +689,7 @@ impl DependencyCollector { } fn add_open_description(&mut self, od: &OpenDescription) { - self.add_longident(&od.popen_lid.txt); + self.add_lident_idx(od.popen_lid.txt); } fn add_include_declaration(&mut self, id: &IncludeDeclaration) { @@ -721,15 +732,26 @@ impl DependencyCollector { #[cfg(test)] mod tests { use super::*; - use crate::location::Location; + use crate::parse_arena::{LocIdx, Located}; + + /// Parse a dotted string like "Foo.Bar.baz" into a Longident using the arena. + fn parse_longident(arena: &mut ParseArena, s: &str) -> Longident { + let parts: Vec<&str> = s.split('.').collect(); + let mut lid = Longident::Lident(arena.intern_string(parts[0])); + for part in &parts[1..] { + lid = Longident::Ldot(Box::new(lid), arena.intern_string(part)); + } + lid + } - fn make_ident_expr(lid: Longident) -> Expression { + fn make_ident_expr(arena: &mut ParseArena, lid: Longident) -> Expression { + let lid_idx = arena.push_longident(lid); Expression { - pexp_desc: ExpressionDesc::Pexp_ident(crate::location::Located { - txt: lid, - loc: Location::none(), + pexp_desc: ExpressionDesc::Pexp_ident(Located { + txt: lid_idx, + loc: LocIdx::none(), }), - pexp_loc: Location::none(), + pexp_loc: LocIdx::none(), pexp_attributes: vec![], } } @@ -737,18 +759,19 @@ mod tests { fn make_eval_item(expr: Expression) -> StructureItem { StructureItem { pstr_desc: StructureItemDesc::Pstr_eval(expr, vec![]), - pstr_loc: Location::none(), + pstr_loc: LocIdx::none(), } } #[test] fn test_simple_module_reference() { // Test: Array.map extracts "Array" - let lid = Longident::parse("Array.map"); - let expr = make_ident_expr(lid); + let mut arena = ParseArena::default(); + let lid = parse_longident(&mut arena, "Array.map"); + let expr = make_ident_expr(&mut arena, lid); let structure = vec![make_eval_item(expr)]; - let deps = extract_structure_deps(&structure); + let deps = extract_structure_deps(&arena, &structure); assert_eq!(deps.len(), 1); assert!(deps.contains("Array")); } @@ -756,11 +779,12 @@ mod tests { #[test] fn test_nested_module_reference() { // Test: Belt.Array.map extracts "Belt" - let lid = Longident::parse("Belt.Array.map"); - let expr = make_ident_expr(lid); + let mut arena = ParseArena::default(); + let lid = parse_longident(&mut arena, "Belt.Array.map"); + let expr = make_ident_expr(&mut arena, lid); let structure = vec![make_eval_item(expr)]; - let deps = extract_structure_deps(&structure); + let deps = extract_structure_deps(&arena, &structure); assert_eq!(deps.len(), 1); assert!(deps.contains("Belt")); } @@ -768,24 +792,30 @@ mod tests { #[test] fn test_lowercase_identifier_ignored() { // Test: lowercase identifiers are not module references - let lid = Longident::lident("foo"); - let expr = make_ident_expr(lid); + let mut arena = ParseArena::default(); + let foo_idx = arena.intern_string("foo"); + let lid = Longident::lident(foo_idx); + let expr = make_ident_expr(&mut arena, lid); let structure = vec![make_eval_item(expr)]; - let deps = extract_structure_deps(&structure); + let deps = extract_structure_deps(&arena, &structure); assert!(deps.is_empty()); } #[test] fn test_multiple_modules() { // Test: multiple module references are collected + let mut arena = ParseArena::default(); + let lid1 = parse_longident(&mut arena, "Array.map"); + let lid2 = parse_longident(&mut arena, "Belt.Array.get"); + let lid3 = parse_longident(&mut arena, "Js.log"); let structure = vec![ - make_eval_item(make_ident_expr(Longident::parse("Array.map"))), - make_eval_item(make_ident_expr(Longident::parse("Belt.Array.get"))), - make_eval_item(make_ident_expr(Longident::parse("Js.log"))), + make_eval_item(make_ident_expr(&mut arena, lid1)), + make_eval_item(make_ident_expr(&mut arena, lid2)), + make_eval_item(make_ident_expr(&mut arena, lid3)), ]; - let deps = extract_structure_deps(&structure); + let deps = extract_structure_deps(&arena, &structure); assert_eq!(deps.len(), 3); assert!(deps.contains("Array")); assert!(deps.contains("Belt")); @@ -795,13 +825,17 @@ mod tests { #[test] fn test_sorted_output() { // Test: output is sorted alphabetically + let mut arena = ParseArena::default(); + let lid1 = parse_longident(&mut arena, "Zebra.x"); + let lid2 = parse_longident(&mut arena, "Alpha.y"); + let lid3 = parse_longident(&mut arena, "Middle.z"); let structure = vec![ - make_eval_item(make_ident_expr(Longident::parse("Zebra.x"))), - make_eval_item(make_ident_expr(Longident::parse("Alpha.y"))), - make_eval_item(make_ident_expr(Longident::parse("Middle.z"))), + make_eval_item(make_ident_expr(&mut arena, lid1)), + make_eval_item(make_ident_expr(&mut arena, lid2)), + make_eval_item(make_ident_expr(&mut arena, lid3)), ]; - let deps = extract_structure_deps(&structure); + let deps = extract_structure_deps(&arena, &structure); let deps_vec: Vec<_> = deps.into_iter().collect(); assert_eq!(deps_vec, vec!["Alpha", "Middle", "Zebra"]); } @@ -809,7 +843,8 @@ mod tests { #[test] fn test_predef_filtered() { // Test: *predef* is filtered out - let mut collector = DependencyCollector::new(); + let arena = ParseArena::default(); + let mut collector = DependencyCollector::new(&arena); collector.deps.insert("*predef*".to_string()); collector.deps.insert("Array".to_string()); @@ -822,7 +857,8 @@ mod tests { #[test] fn test_empty_string_filtered() { // Test: empty strings are filtered out - let mut collector = DependencyCollector::new(); + let arena = ParseArena::default(); + let mut collector = DependencyCollector::new(&arena); collector.deps.insert(String::new()); collector.deps.insert("Array".to_string()); @@ -834,26 +870,32 @@ mod tests { #[test] fn test_deduplicated() { // Test: duplicate modules are deduplicated + let mut arena = ParseArena::default(); + let lid1 = parse_longident(&mut arena, "Array.map"); + let lid2 = parse_longident(&mut arena, "Array.length"); + let lid3 = parse_longident(&mut arena, "Array.get"); let structure = vec![ - make_eval_item(make_ident_expr(Longident::parse("Array.map"))), - make_eval_item(make_ident_expr(Longident::parse("Array.length"))), - make_eval_item(make_ident_expr(Longident::parse("Array.get"))), + make_eval_item(make_ident_expr(&mut arena, lid1)), + make_eval_item(make_ident_expr(&mut arena, lid2)), + make_eval_item(make_ident_expr(&mut arena, lid3)), ]; - let deps = extract_structure_deps(&structure); + let deps = extract_structure_deps(&arena, &structure); assert_eq!(deps.len(), 1); assert!(deps.contains("Array")); } #[test] fn test_empty_structure() { - let deps = extract_structure_deps(&[]); + let arena = ParseArena::default(); + let deps = extract_structure_deps(&arena, &[]); assert!(deps.is_empty()); } #[test] fn test_empty_signature() { - let deps = extract_signature_deps(&[]); + let arena = ParseArena::default(); + let deps = extract_signature_deps(&arena, &[]); assert!(deps.is_empty()); } } diff --git a/compiler-rust/src/binary_ast/mapper_from0.rs b/compiler-rust/src/binary_ast/mapper_from0.rs index 9fe64c76df8..63a2b6ff921 100644 --- a/compiler-rust/src/binary_ast/mapper_from0.rs +++ b/compiler-rust/src/binary_ast/mapper_from0.rs @@ -13,35 +13,31 @@ //! //! This mirrors `compiler/ml/ast_mapper_from0.ml`. -use crate::location::{Located, Location}; +use crate::intern::StrIdx; +use crate::location::Location as FullLocation; +use crate::location::Located as OldLocated; +use crate::parse_arena::{Located, LocIdx, ParseArena}; use crate::parser::ast::{self as current}; use crate::parser::longident::Longident; use super::parsetree0 as pt0; +// ========== Public API ========== + /// Convert a structure from parsetree0 to current parsetree -pub fn map_structure(str: &[pt0::StructureItem]) -> Vec { - str.iter().map(map_structure_item).collect() +pub fn map_structure(arena: &mut ParseArena, str: &[pt0::StructureItem]) -> Vec { + let mut mapper = Mapper::new(arena); + mapper.map_structure(str) } /// Convert a signature from parsetree0 to current parsetree -pub fn map_signature(sig: &[pt0::SignatureItem]) -> Vec { - sig.iter().map(map_signature_item).collect() +pub fn map_signature(arena: &mut ParseArena, sig: &[pt0::SignatureItem]) -> Vec { + let mut mapper = Mapper::new(arena); + mapper.map_signature(sig) } // ========== Helper functions ========== -fn mkloc(txt: T, loc: &Location) -> Located { - Located { - txt, - loc: loc.clone(), - } -} - -fn map_opt U>(f: F, opt: &Option) -> Option { - opt.as_ref().map(f) -} - fn map_closed_flag(flag: &pt0::ClosedFlag) -> current::ClosedFlag { match flag { pt0::ClosedFlag::Closed => current::ClosedFlag::Closed, @@ -141,133 +137,6 @@ fn remove_jsx_attribute(attrs: &[pt0::Attribute]) -> Vec { .collect() } -/// Extracts JSX children from a cons-list expression -fn extract_jsx_children(expr: &pt0::Expression) -> Vec { - let mut children = Vec::new(); - let mut current = expr; - loop { - match ¤t.pexp_desc { - pt0::ExpressionDesc::Construct(lid, Some(arg)) - if matches!(&lid.txt, Longident::Lident(s) if s == "::") => - { - if let pt0::ExpressionDesc::Tuple(items) = &arg.pexp_desc { - if items.len() == 2 { - children.push(map_expression(&items[0])); - current = &items[1]; - continue; - } - } - break; - } - pt0::ExpressionDesc::Construct(lid, None) - if matches!(&lid.txt, Longident::Lident(s) if s == "[]") => - { - break; - } - _ => { - // If it's not a proper list, just include this as a child - children.push(map_expression(current)); - break; - } - } - } - children -} - -/// Tries to extract a JSX prop from a labeled argument -fn try_map_jsx_prop(label: &pt0::ArgLabel, expr: &pt0::Expression) -> Option { - match label { - pt0::ArgLabel::Labelled(name) if name == "_spreadProps" => { - Some(current::JsxProp::Spreading { - loc: expr.pexp_loc.clone(), - expr: map_expression(expr), - }) - } - pt0::ArgLabel::Labelled(name) => { - // Check for punning: labelled arg with ident of same name - if let pt0::ExpressionDesc::Ident(lid) = &expr.pexp_desc { - if let Longident::Lident(v) = &lid.txt { - if v == name { - return Some(current::JsxProp::Punning { - optional: false, - name: Located::new(name.clone(), lid.loc.clone()), - }); - } - } - } - Some(current::JsxProp::Value { - name: Located::new(name.clone(), Location::none()), - optional: false, - value: map_expression(expr), - }) - } - pt0::ArgLabel::Optional(name) => { - // Check for punning: optional arg with ident of same name - if let pt0::ExpressionDesc::Ident(lid) = &expr.pexp_desc { - if let Longident::Lident(v) = &lid.txt { - if v == name { - return Some(current::JsxProp::Punning { - optional: true, - name: Located::new(name.clone(), lid.loc.clone()), - }); - } - } - } - Some(current::JsxProp::Value { - name: Located::new(name.clone(), Location::none()), - optional: true, - value: map_expression(expr), - }) - } - pt0::ArgLabel::Nolabel => None, - } -} - -/// Extracts props and children from JSX apply arguments -fn extract_jsx_props_and_children( - args: &[(pt0::ArgLabel, pt0::Expression)], -) -> (Vec, Vec) { - let mut props = Vec::new(); - let mut children = Vec::new(); - - for (label, expr) in args { - match label { - pt0::ArgLabel::Labelled(name) if name == "children" => { - children = extract_jsx_children(expr); - } - pt0::ArgLabel::Nolabel => { - // Unit argument at the end, skip - } - _ => { - if let Some(prop) = try_map_jsx_prop(label, expr) { - props.push(prop); - } - } - } - } - - (props, children) -} - -/// Converts a longident to a JSX tag name -fn longident_to_jsx_tag(lid: &Longident) -> current::JsxTagName { - match lid { - Longident::Lident(s) if !s.is_empty() && s.chars().next().unwrap().is_lowercase() => { - current::JsxTagName::Lower(s.clone()) - } - Longident::Lident(s) => current::JsxTagName::Upper(Longident::Lident(s.clone())), - Longident::Ldot(path, name) - if !name.is_empty() && name.chars().next().unwrap().is_lowercase() => - { - current::JsxTagName::QualifiedLower { - path: (**path).clone(), - name: name.clone(), - } - } - other => current::JsxTagName::Upper(other.clone()), - } -} - // ========== Flag conversions ========== fn map_rec_flag(flag: pt0::RecFlag) -> current::RecFlag { @@ -313,15 +182,6 @@ fn map_variance(v: pt0::Variance) -> current::Variance { } } -fn map_arg_label(lbl: &pt0::ArgLabel) -> current::ArgLabel { - match lbl { - pt0::ArgLabel::Nolabel => current::ArgLabel::Nolabel, - // parsetree0 doesn't have location info, so use mknoloc - pt0::ArgLabel::Labelled(s) => current::ArgLabel::Labelled(Located::mknoloc(s.clone())), - pt0::ArgLabel::Optional(s) => current::ArgLabel::Optional(Located::mknoloc(s.clone())), - } -} - // ========== Constant conversion ========== fn map_constant(c: &pt0::Constant) -> current::Constant { @@ -342,68 +202,154 @@ fn map_constant(c: &pt0::Constant) -> current::Constant { } } -// ========== Location mapping ========== - -fn map_loc(loc: &Located) -> Located { - loc.clone() +/// Mapper from parsetree0 to current parsetree. +/// Holds a mutable reference to the arena for creating LocIdx values. +pub struct Mapper<'a> { + arena: &'a mut ParseArena, } -// ========== Type expressions ========== - -fn map_core_type(typ: &pt0::CoreType) -> current::CoreType { - let loc = typ.ptyp_loc.clone(); - let attrs = map_attributes(&typ.ptyp_attributes); - - let desc = match &typ.ptyp_desc { - pt0::CoreTypeDesc::Any => current::CoreTypeDesc::Ptyp_any, - pt0::CoreTypeDesc::Var(s) => current::CoreTypeDesc::Ptyp_var(s.clone()), - pt0::CoreTypeDesc::Arrow(lbl, t1, t2) => { - let lbl = map_arg_label(lbl); - // In parsetree0, the argument's attributes are merged with the outer type's attributes - // and placed on the outer type. When converting back, these outer attributes - // should go on the TypeArg (matching what OCaml's ast_mapper_from0 does). - // The resulting arrow type should have no attributes (they're now on TypeArg). - return current::CoreType { - ptyp_desc: current::CoreTypeDesc::Ptyp_arrow { - arg: Box::new(current::TypeArg { - attrs, // Use the outer type's attributes for the arg - lbl, - typ: map_core_type(t1), - }), - ret: Box::new(map_core_type(t2)), - arity: current::Arity::Unknown, - }, - ptyp_loc: loc, - ptyp_attributes: vec![], // Arrow type itself has no attributes - }; +impl<'a> Mapper<'a> { + pub fn new(arena: &'a mut ParseArena) -> Self { + Self { arena } + } + + /// Convert a full Location to LocIdx + fn loc(&mut self, loc: &FullLocation) -> LocIdx { + self.arena.from_location(loc) + } + + /// Create a Located value from old Located + fn map_loc(&mut self, old: &OldLocated) -> Located { + Located { + txt: old.txt.clone(), + loc: self.loc(&old.loc), } - pt0::CoreTypeDesc::Tuple(tl) => { - current::CoreTypeDesc::Ptyp_tuple(tl.iter().map(map_core_type).collect()) + } + + /// Map a Located to Located by pushing to arena + fn map_longident_loc(&mut self, old: &OldLocated) -> Located { + let lid_idx = self.arena.push_longident(old.txt.clone()); + Located { + txt: lid_idx, + loc: self.loc(&old.loc), + } + } + + /// Push a longident to the arena and get back an index + fn push_longident(&mut self, lid: Longident) -> crate::parse_arena::LidentIdx { + self.arena.push_longident(lid) + } + + /// Create a Located value with given text and location + fn mkloc(&mut self, txt: T, loc: &FullLocation) -> Located { + Located { + txt, + loc: self.loc(loc), + } + } + + /// Get a string from a StrIdx + fn get_str(&self, idx: StrIdx) -> &str { + self.arena.get_string(idx) + } + + // ========== Public API ========== + + /// Convert a structure from parsetree0 to current parsetree + pub fn map_structure(&mut self, str: &[pt0::StructureItem]) -> Vec { + str.iter().map(|item| self.map_structure_item(item)).collect() + } + + /// Convert a signature from parsetree0 to current parsetree + pub fn map_signature(&mut self, sig: &[pt0::SignatureItem]) -> Vec { + sig.iter().map(|item| self.map_signature_item(item)).collect() + } + + // ========== Arg label mapping ========== + + fn map_arg_label(&mut self, lbl: &pt0::ArgLabel) -> current::ArgLabel { + match lbl { + pt0::ArgLabel::Nolabel => current::ArgLabel::Nolabel, + // parsetree0 doesn't have location info, so use mknoloc + pt0::ArgLabel::Labelled(s) => current::ArgLabel::Labelled(Located::mknoloc(s.clone())), + pt0::ArgLabel::Optional(s) => current::ArgLabel::Optional(Located::mknoloc(s.clone())), + } + } + + // ========== Attribute mapping ========== + + fn map_attribute(&mut self, attr: &pt0::Attribute) -> current::Attribute { + (self.map_loc(&attr.0), self.map_payload(&attr.1)) + } + + fn map_attributes(&mut self, attrs: &[pt0::Attribute]) -> Vec { + attrs.iter().map(|a| self.map_attribute(a)).collect() + } + + fn map_extension(&mut self, ext: &pt0::Extension) -> current::Extension { + (self.map_loc(&ext.0), self.map_payload(&ext.1)) + } + + fn map_payload(&mut self, payload: &pt0::Payload) -> current::Payload { + match payload { + pt0::Payload::PStr(str) => current::Payload::PStr(self.map_structure(str)), + pt0::Payload::PSig(sig) => current::Payload::PSig(self.map_signature(sig)), + pt0::Payload::PTyp(t) => current::Payload::PTyp(Box::new(self.map_core_type(t))), + pt0::Payload::PPat(p, guard) => { + current::Payload::PPat(Box::new(self.map_pattern(p)), guard.as_ref().map(|g| Box::new(self.map_expression(g)))) + } } - pt0::CoreTypeDesc::Constr(lid, tl) => { - let mapped_types: Vec<_> = tl.iter().map(map_core_type).collect(); - - // Check for function$ type constructor (arity encoding) - if let Longident::Lident(name) = &lid.txt { - if name == "function$" && mapped_types.len() == 2 { - // function$(arrow_type, arity_type) -> arrow_type with arity - if let current::CoreTypeDesc::Ptyp_arrow { arg, ret, .. } = mapped_types[0].ptyp_desc.clone() { - // Extract arity from the second type argument - if let current::CoreTypeDesc::Ptyp_variant(rows, _, _) = &mapped_types[1].ptyp_desc { - if let Some(row) = rows.first() { - if let current::RowField::Rtag(tag, _, _, _) = row { - // Decode arity from tag like "Has_arity9" - if tag.txt.starts_with("Has_arity") { - if let Ok(arity) = tag.txt[9..].parse::() { - return current::CoreType { - ptyp_desc: current::CoreTypeDesc::Ptyp_arrow { - arg, - ret, - arity: current::Arity::Full(arity), - }, - ptyp_loc: loc, - ptyp_attributes: attrs, - }; + } + + // ========== Core type mapping ========== + + fn map_core_type(&mut self, typ: &pt0::CoreType) -> current::CoreType { + let loc = self.loc(&typ.ptyp_loc); + let attrs = self.map_attributes(&typ.ptyp_attributes); + + let desc = match &typ.ptyp_desc { + pt0::CoreTypeDesc::Any => current::CoreTypeDesc::Ptyp_any, + pt0::CoreTypeDesc::Var(s) => current::CoreTypeDesc::Ptyp_var(s.clone()), + pt0::CoreTypeDesc::Arrow(lbl, t1, t2) => { + let lbl = self.map_arg_label(lbl); + return current::CoreType { + ptyp_desc: current::CoreTypeDesc::Ptyp_arrow { + arg: Box::new(current::TypeArg { + attrs, + lbl, + typ: self.map_core_type(t1), + }), + ret: Box::new(self.map_core_type(t2)), + arity: current::Arity::Unknown, + }, + ptyp_loc: loc, + ptyp_attributes: vec![], + }; + } + pt0::CoreTypeDesc::Tuple(tl) => { + current::CoreTypeDesc::Ptyp_tuple(tl.iter().map(|t| self.map_core_type(t)).collect()) + } + pt0::CoreTypeDesc::Constr(lid, tl) => { + let mapped_types: Vec<_> = tl.iter().map(|t| self.map_core_type(t)).collect(); + + if let Longident::Lident(name) = &lid.txt { + if self.get_str(*name) == "function$" && mapped_types.len() == 2 { + if let current::CoreTypeDesc::Ptyp_arrow { arg, ret, .. } = mapped_types[0].ptyp_desc.clone() { + if let current::CoreTypeDesc::Ptyp_variant(rows, _, _) = &mapped_types[1].ptyp_desc { + if let Some(row) = rows.first() { + if let current::RowField::Rtag(tag, _, _, _) = row { + if tag.txt.starts_with("Has_arity") { + if let Ok(arity) = tag.txt[9..].parse::() { + return current::CoreType { + ptyp_desc: current::CoreTypeDesc::Ptyp_arrow { + arg, + ret, + arity: current::Arity::Full(arity), + }, + ptyp_loc: loc, + ptyp_attributes: attrs, + }; + } } } } @@ -411,306 +357,372 @@ fn map_core_type(typ: &pt0::CoreType) -> current::CoreType { } } } + + current::CoreTypeDesc::Ptyp_constr(self.map_longident_loc(lid), mapped_types) + } + pt0::CoreTypeDesc::Object(fields, closed) => { + let fields = fields.iter().map(|f| self.map_object_field(f)).collect(); + current::CoreTypeDesc::Ptyp_object(fields, map_closed_flag(closed)) + } + pt0::CoreTypeDesc::Alias(t, s) => { + current::CoreTypeDesc::Ptyp_alias(Box::new(self.map_core_type(t)), s.clone()) + } + pt0::CoreTypeDesc::Variant(rows, closed, labels) => { + let rows = rows.iter().map(|r| self.map_row_field(r)).collect(); + current::CoreTypeDesc::Ptyp_variant(rows, map_closed_flag(closed), labels.clone()) + } + pt0::CoreTypeDesc::Poly(vars, t) => { + current::CoreTypeDesc::Ptyp_poly( + vars.iter().map(|v| self.map_loc(v)).collect(), + Box::new(self.map_core_type(t)), + ) + } + pt0::CoreTypeDesc::Package(pkg) => { + let (lid, constraints) = pkg; + let constraints = constraints + .iter() + .map(|(l, t)| (self.map_longident_loc(l), self.map_core_type(t))) + .collect(); + current::CoreTypeDesc::Ptyp_package((self.map_longident_loc(lid), constraints)) } + pt0::CoreTypeDesc::Extension(ext) => { + current::CoreTypeDesc::Ptyp_extension(self.map_extension(ext)) + } + pt0::CoreTypeDesc::Class => { + current::CoreTypeDesc::Ptyp_any + } + }; - current::CoreTypeDesc::Ptyp_constr(map_loc(lid), mapped_types) - } - pt0::CoreTypeDesc::Object(fields, closed) => { - let fields = fields.iter().map(map_object_field).collect(); - current::CoreTypeDesc::Ptyp_object(fields, map_closed_flag(closed)) - } - pt0::CoreTypeDesc::Alias(t, s) => { - current::CoreTypeDesc::Ptyp_alias(Box::new(map_core_type(t)), s.clone()) - } - pt0::CoreTypeDesc::Variant(rows, closed, labels) => { - let rows = rows.iter().map(map_row_field).collect(); - current::CoreTypeDesc::Ptyp_variant(rows, map_closed_flag(closed), labels.clone()) + current::CoreType { + ptyp_desc: desc, + ptyp_loc: loc, + ptyp_attributes: attrs, } - pt0::CoreTypeDesc::Poly(vars, t) => { - current::CoreTypeDesc::Ptyp_poly( - vars.iter().map(map_loc).collect(), - Box::new(map_core_type(t)), - ) - } - pt0::CoreTypeDesc::Package(pkg) => { - let (lid, constraints) = pkg; - let constraints = constraints - .iter() - .map(|(l, t)| (map_loc(l), map_core_type(t))) - .collect(); - current::CoreTypeDesc::Ptyp_package((map_loc(lid), constraints)) - } - pt0::CoreTypeDesc::Extension(ext) => { - current::CoreTypeDesc::Ptyp_extension(map_extension(ext)) - } - pt0::CoreTypeDesc::Class => { - // Class types are not supported in ReScript - treat as any - current::CoreTypeDesc::Ptyp_any - } - }; - - current::CoreType { - ptyp_desc: desc, - ptyp_loc: loc, - ptyp_attributes: attrs, } -} -fn map_row_field(rf: &pt0::RowField) -> current::RowField { - match rf { - pt0::RowField::Rtag(label, attrs, empty, types) => current::RowField::Rtag( - map_loc(label), - map_attributes(attrs), - *empty, - types.iter().map(map_core_type).collect(), - ), - pt0::RowField::Rinherit(t) => current::RowField::Rinherit(map_core_type(t)), + fn map_row_field(&mut self, rf: &pt0::RowField) -> current::RowField { + match rf { + pt0::RowField::Rtag(label, attrs, empty, types) => current::RowField::Rtag( + self.map_loc(label), + self.map_attributes(attrs), + *empty, + types.iter().map(|t| self.map_core_type(t)).collect(), + ), + pt0::RowField::Rinherit(t) => current::RowField::Rinherit(self.map_core_type(t)), + } } -} -fn map_object_field(of: &pt0::ObjectField) -> current::ObjectField { - match of { - pt0::ObjectField::Otag(label, attrs, t) => { - current::ObjectField::Otag(map_loc(label), map_attributes(attrs), map_core_type(t)) + fn map_object_field(&mut self, of: &pt0::ObjectField) -> current::ObjectField { + match of { + pt0::ObjectField::Otag(label, attrs, t) => { + current::ObjectField::Otag(self.map_loc(label), self.map_attributes(attrs), self.map_core_type(t)) + } + pt0::ObjectField::Oinherit(t) => current::ObjectField::Oinherit(self.map_core_type(t)), } - pt0::ObjectField::Oinherit(t) => current::ObjectField::Oinherit(map_core_type(t)), } -} -// ========== Patterns ========== + // ========== Pattern mapping ========== -fn map_pattern(pat: &pt0::Pattern) -> current::Pattern { - let loc = pat.ppat_loc.clone(); - let attrs = map_attributes(&pat.ppat_attributes); + fn map_pattern(&mut self, pat: &pt0::Pattern) -> current::Pattern { + let loc = self.loc(&pat.ppat_loc); + let attrs = self.map_attributes(&pat.ppat_attributes); - let desc = match &pat.ppat_desc { - pt0::PatternDesc::Any => current::PatternDesc::Ppat_any, - pt0::PatternDesc::Var(s) => current::PatternDesc::Ppat_var(map_loc(s)), - pt0::PatternDesc::Alias(p, s) => { - current::PatternDesc::Ppat_alias(Box::new(map_pattern(p)), map_loc(s)) - } - pt0::PatternDesc::Constant(c) => current::PatternDesc::Ppat_constant(map_constant(c)), - pt0::PatternDesc::Interval(c1, c2) => { - current::PatternDesc::Ppat_interval(map_constant(c1), map_constant(c2)) - } - pt0::PatternDesc::Tuple(pl) => { - current::PatternDesc::Ppat_tuple(pl.iter().map(map_pattern).collect()) - } - pt0::PatternDesc::Construct(lid, arg) => { - current::PatternDesc::Ppat_construct(map_loc(lid), map_opt(|p| Box::new(map_pattern(p)), arg)) - } - pt0::PatternDesc::Variant(label, arg) => { - current::PatternDesc::Ppat_variant(label.clone(), map_opt(|p| Box::new(map_pattern(p)), arg)) - } - pt0::PatternDesc::Record(fields, closed) => { - let fields = fields - .iter() - .map(|pt0::RecordElement { lid, x: p, opt }| { - let mapped_pat = map_pattern(p); - // Preserve opt from parsetree0 if present, or check for optional attribute - let optional = *opt || has_optional_attribute(&mapped_pat.ppat_attributes); - let pat_attrs = if has_optional_attribute(&mapped_pat.ppat_attributes) { - remove_optional_attribute(&mapped_pat.ppat_attributes) + let desc = match &pat.ppat_desc { + pt0::PatternDesc::Any => current::PatternDesc::Ppat_any, + pt0::PatternDesc::Var(s) => current::PatternDesc::Ppat_var(self.map_loc(s)), + pt0::PatternDesc::Alias(p, s) => { + current::PatternDesc::Ppat_alias(Box::new(self.map_pattern(p)), self.map_loc(s)) + } + pt0::PatternDesc::Constant(c) => current::PatternDesc::Ppat_constant(map_constant(c)), + pt0::PatternDesc::Interval(c1, c2) => { + current::PatternDesc::Ppat_interval(map_constant(c1), map_constant(c2)) + } + pt0::PatternDesc::Tuple(pl) => { + current::PatternDesc::Ppat_tuple(pl.iter().map(|p| self.map_pattern(p)).collect()) + } + pt0::PatternDesc::Construct(lid, arg) => { + current::PatternDesc::Ppat_construct( + self.map_longident_loc(lid), + arg.as_ref().map(|p| Box::new(self.map_pattern(p))) + ) + } + pt0::PatternDesc::Variant(tag, arg) => { + current::PatternDesc::Ppat_variant(tag.clone(), arg.as_ref().map(|p| Box::new(self.map_pattern(p)))) + } + pt0::PatternDesc::Record(fields, closed) => { + let fields = fields.iter().map(|pt0::RecordElement { lid, x: pat, opt }| { + let lid = self.map_longident_loc(lid); + let mapped_attrs = self.map_attributes(&pat.ppat_attributes); + let optional = *opt || has_optional_attribute(&mapped_attrs); + let pat = if has_optional_attribute(&mapped_attrs) { + let mut mapped = self.map_pattern(pat); + mapped.ppat_attributes = remove_optional_attribute(&mapped.ppat_attributes); + mapped } else { - mapped_pat.ppat_attributes.clone() + self.map_pattern(pat) }; - current::PatternRecordField { - lid: map_loc(lid), - pat: current::Pattern { - ppat_desc: mapped_pat.ppat_desc, - ppat_loc: mapped_pat.ppat_loc, - ppat_attributes: pat_attrs, - }, - opt: optional, - } - }) - .collect(); - current::PatternDesc::Ppat_record(fields, map_closed_flag(closed)) - } - pt0::PatternDesc::Array(pl) => { - current::PatternDesc::Ppat_array(pl.iter().map(map_pattern).collect()) - } - pt0::PatternDesc::Or(p1, p2) => { - current::PatternDesc::Ppat_or(Box::new(map_pattern(p1)), Box::new(map_pattern(p2))) - } - pt0::PatternDesc::Constraint(p, t) => { - current::PatternDesc::Ppat_constraint(Box::new(map_pattern(p)), map_core_type(t)) - } - pt0::PatternDesc::Type(lid) => current::PatternDesc::Ppat_type(map_loc(lid)), - pt0::PatternDesc::Unpack(s) => current::PatternDesc::Ppat_unpack(map_loc(s)), - pt0::PatternDesc::Open(lid, p) => { - current::PatternDesc::Ppat_open(map_loc(lid), Box::new(map_pattern(p))) - } - pt0::PatternDesc::Exception(p) => { - current::PatternDesc::Ppat_exception(Box::new(map_pattern(p))) - } - pt0::PatternDesc::Extension(ext) => { - current::PatternDesc::Ppat_extension(map_extension(ext)) - } - pt0::PatternDesc::Lazy(_) => { - panic!("OCaml 'lazy' patterns are not supported in ReScript") - } - }; + current::PatternRecordField { lid, pat, opt: optional } + }).collect(); + current::PatternDesc::Ppat_record(fields, map_closed_flag(closed)) + } + pt0::PatternDesc::Array(pl) => { + current::PatternDesc::Ppat_array(pl.iter().map(|p| self.map_pattern(p)).collect()) + } + pt0::PatternDesc::Or(p1, p2) => { + current::PatternDesc::Ppat_or(Box::new(self.map_pattern(p1)), Box::new(self.map_pattern(p2))) + } + pt0::PatternDesc::Constraint(p, t) => { + current::PatternDesc::Ppat_constraint(Box::new(self.map_pattern(p)), self.map_core_type(t)) + } + pt0::PatternDesc::Type(lid) => { + current::PatternDesc::Ppat_type(self.map_longident_loc(lid)) + } + pt0::PatternDesc::Unpack(name) => { + current::PatternDesc::Ppat_unpack(self.map_loc(name)) + } + pt0::PatternDesc::Open(lid, p) => { + current::PatternDesc::Ppat_open(self.map_longident_loc(lid), Box::new(self.map_pattern(p))) + } + pt0::PatternDesc::Exception(p) => { + current::PatternDesc::Ppat_exception(Box::new(self.map_pattern(p))) + } + pt0::PatternDesc::Extension(ext) => { + current::PatternDesc::Ppat_extension(self.map_extension(ext)) + } + pt0::PatternDesc::Lazy(_) => { + panic!("OCaml 'lazy' patterns are not supported in ReScript") + } + }; - current::Pattern { - ppat_desc: desc, - ppat_loc: loc, - ppat_attributes: attrs, + current::Pattern { + ppat_desc: desc, + ppat_loc: loc, + ppat_attributes: attrs, + } } -} -// ========== Expressions ========== + // ========== Expression mapping ========== -fn map_expression(expr: &pt0::Expression) -> current::Expression { - let loc = expr.pexp_loc.clone(); - let attrs = map_attributes(&expr.pexp_attributes); + /// Check if a Longident is a simple identifier with given name + fn is_lident(&self, lid: &Longident, name: &str) -> bool { + if let Longident::Lident(s) = lid { + self.get_str(*s) == name + } else { + false + } + } - // Check for res.await attribute - convert to Pexp_await - if has_await_attribute(&expr.pexp_attributes) { - let new_attrs = remove_await_attribute(&expr.pexp_attributes); - let inner_expr = pt0::Expression { - pexp_desc: expr.pexp_desc.clone(), - pexp_loc: expr.pexp_loc.clone(), - pexp_attributes: new_attrs, - }; - return current::Expression { - pexp_desc: current::ExpressionDesc::Pexp_await(Box::new(map_expression(&inner_expr))), - pexp_loc: loc, - pexp_attributes: vec![], - }; + /// Extracts JSX children from a cons-list expression + fn extract_jsx_children(&mut self, expr: &pt0::Expression) -> Vec { + let mut children = Vec::new(); + let mut current_expr = expr; + loop { + match ¤t_expr.pexp_desc { + pt0::ExpressionDesc::Construct(lid, Some(arg)) + if self.is_lident(&lid.txt, "::") => + { + if let pt0::ExpressionDesc::Tuple(items) = &arg.pexp_desc { + if items.len() == 2 { + children.push(self.map_expression(&items[0])); + current_expr = &items[1]; + continue; + } + } + break; + } + pt0::ExpressionDesc::Construct(lid, None) + if self.is_lident(&lid.txt, "[]") => + { + break; + } + _ => { + // If it's not a proper list, just include this as a child + children.push(self.map_expression(current_expr)); + break; + } + } + } + children } - let desc = match &expr.pexp_desc { - pt0::ExpressionDesc::Ident(lid) => current::ExpressionDesc::Pexp_ident(map_loc(lid)), - pt0::ExpressionDesc::Constant(c) => current::ExpressionDesc::Pexp_constant(map_constant(c)), - pt0::ExpressionDesc::Let(rec_flag, bindings, body) => current::ExpressionDesc::Pexp_let( - map_rec_flag(*rec_flag), - bindings.iter().map(map_value_binding).collect(), - Box::new(map_expression(body)), - ), - pt0::ExpressionDesc::Fun { arg_label: lbl, default, lhs: pat, rhs: body, arity, is_async } => { - current::ExpressionDesc::Pexp_fun { - arg_label: map_arg_label(lbl), - default: map_opt(|e| Box::new(map_expression(e)), default), - lhs: map_pattern(pat), - rhs: Box::new(map_expression(body)), - arity: map_arity(arity), - is_async: *is_async, + /// Tries to extract a JSX prop from a labeled argument + fn try_map_jsx_prop(&mut self, label: &pt0::ArgLabel, expr: &pt0::Expression) -> Option { + match label { + pt0::ArgLabel::Labelled(name_idx) if self.get_str(*name_idx) == "_spreadProps" => { + let expr_loc = self.loc(&expr.pexp_loc); + Some(current::JsxProp::Spreading { + loc: expr_loc, + expr: self.map_expression(expr), + }) } + pt0::ArgLabel::Labelled(name_idx) => { + let name_str = self.get_str(*name_idx).to_string(); + // Check for punning: labelled arg with ident of same name + if let pt0::ExpressionDesc::Ident(lid) = &expr.pexp_desc { + if let Longident::Lident(v) = &lid.txt { + if self.get_str(*v) == name_str { + return Some(current::JsxProp::Punning { + optional: false, + name: self.mkloc(name_str, &lid.loc), + }); + } + } + } + Some(current::JsxProp::Value { + name: Located::mknoloc(name_str), + optional: false, + value: self.map_expression(expr), + }) + } + pt0::ArgLabel::Optional(name_idx) => { + let name_str = self.get_str(*name_idx).to_string(); + // Check for punning: optional arg with ident of same name + if let pt0::ExpressionDesc::Ident(lid) = &expr.pexp_desc { + if let Longident::Lident(v) = &lid.txt { + if self.get_str(*v) == name_str { + return Some(current::JsxProp::Punning { + optional: true, + name: self.mkloc(name_str, &lid.loc), + }); + } + } + } + Some(current::JsxProp::Value { + name: Located::mknoloc(name_str), + optional: true, + value: self.map_expression(expr), + }) + } + pt0::ArgLabel::Nolabel => None, } - pt0::ExpressionDesc::Apply { funct: func, args, partial: pt0_partial, transformed_jsx } => { - // Check for JSX attribute - convert back to JSX element - if has_jsx_attribute(&expr.pexp_attributes) { - if let pt0::ExpressionDesc::Ident(tag_lid) = &func.pexp_desc { - let jsx_attrs = map_attributes(&remove_jsx_attribute(&expr.pexp_attributes)); - let (props, children) = extract_jsx_props_and_children(args); - let tag_name = longident_to_jsx_tag(&tag_lid.txt); - let tag_loc = Located::new(tag_name, tag_lid.loc.clone()); - - let jsx_element = if children.is_empty() { - current::JsxElement::Unary(current::JsxUnaryElement { - tag_name: tag_loc, - props, - }) - } else { - current::JsxElement::Container(current::JsxContainerElement { - tag_name_start: tag_loc.clone(), - opening_end: loc.loc_start.clone(), - props, - children, - closing_tag: Some(current::JsxClosingTag { - start: loc.loc_end.clone(), - name: tag_loc, - end: loc.loc_end.clone(), - }), - }) - }; + } - return current::Expression { - pexp_desc: current::ExpressionDesc::Pexp_jsx_element(jsx_element), - pexp_loc: loc, - pexp_attributes: jsx_attrs, - }; + /// Extracts props and children from JSX apply arguments + fn extract_jsx_props_and_children( + &mut self, + args: &[(pt0::ArgLabel, pt0::Expression)], + ) -> (Vec, Vec) { + let mut props = Vec::new(); + let mut children = Vec::new(); + + for (label, expr) in args { + match label { + pt0::ArgLabel::Labelled(name_idx) if self.get_str(*name_idx) == "children" => { + children = self.extract_jsx_children(expr); + } + pt0::ArgLabel::Nolabel => { + // Unit argument at the end, skip + } + _ => { + if let Some(prop) = self.try_map_jsx_prop(label, expr) { + props.push(prop); + } } } + } - // Check for partial application attribute (legacy) or use pt0_partial - let partial = *pt0_partial || has_partial_attribute(&expr.pexp_attributes); - let attrs = if has_partial_attribute(&expr.pexp_attributes) { - map_attributes(&remove_partial_attribute(&expr.pexp_attributes)) - } else { - attrs.clone() - }; + (props, children) + } - // Map operator names - let func = if let pt0::ExpressionDesc::Ident(lid) = &func.pexp_desc { - match &lid.txt { - Longident::Lident(name) => { - let new_name = match name.as_str() { - "|." => "->", - "^" => "++", - "<>" => "!=", - "!=" => "!==", - "=" => "==", - "==" => "===", - _ => name.as_str(), - }; - if new_name != name { - pt0::Expression { - pexp_desc: pt0::ExpressionDesc::Ident(Located { - txt: Longident::Lident(new_name.to_string()), - loc: lid.loc.clone(), - }), - pexp_loc: func.pexp_loc.clone(), - pexp_attributes: func.pexp_attributes.clone(), - } - } else { - func.as_ref().clone() - } - } - _ => func.as_ref().clone(), + /// Helper to check if a string starts with lowercase + fn starts_with_lowercase(&self, idx: StrIdx) -> bool { + let s = self.get_str(idx); + !s.is_empty() && s.chars().next().unwrap().is_lowercase() + } + + /// Converts a longident to a JSX tag name + fn longident_to_jsx_tag(&mut self, lid: &Longident) -> current::JsxTagName { + match lid { + Longident::Lident(s) if self.starts_with_lowercase(*s) => { + current::JsxTagName::Lower(self.get_str(*s).to_string()) + } + Longident::Lident(s) => { + let lid_idx = self.push_longident(Longident::Lident(*s)); + current::JsxTagName::Upper(lid_idx) + } + Longident::Ldot(path, name) if self.starts_with_lowercase(*name) => { + let path_idx = self.push_longident((**path).clone()); + current::JsxTagName::QualifiedLower { + path: path_idx, + name: self.get_str(*name).to_string(), } - } else { - func.as_ref().clone() - }; + } + other => { + let lid_idx = self.push_longident(other.clone()); + current::JsxTagName::Upper(lid_idx) + } + } + } + fn map_expression(&mut self, expr: &pt0::Expression) -> current::Expression { + let loc = self.loc(&expr.pexp_loc); + let attrs = self.map_attributes(&expr.pexp_attributes); + + // Check for res.await attribute - convert to Pexp_await + if has_await_attribute(&expr.pexp_attributes) { + let new_attrs = remove_await_attribute(&expr.pexp_attributes); + let inner_expr = pt0::Expression { + pexp_desc: expr.pexp_desc.clone(), + pexp_loc: expr.pexp_loc.clone(), + pexp_attributes: new_attrs, + }; return current::Expression { - pexp_desc: current::ExpressionDesc::Pexp_apply { - funct: Box::new(map_expression(&func)), - args: args - .iter() - .map(|(lbl, e)| (map_arg_label(lbl), map_expression(e))) - .collect(), - partial, - transformed_jsx: *transformed_jsx, - }, + pexp_desc: current::ExpressionDesc::Pexp_await(Box::new(self.map_expression(&inner_expr))), pexp_loc: loc, - pexp_attributes: attrs, + pexp_attributes: vec![], }; } - pt0::ExpressionDesc::Match(e, cases) => current::ExpressionDesc::Pexp_match( - Box::new(map_expression(e)), - cases.iter().map(map_case).collect(), - ), - pt0::ExpressionDesc::Try(e, cases) => current::ExpressionDesc::Pexp_try( - Box::new(map_expression(e)), - cases.iter().map(map_case).collect(), - ), - pt0::ExpressionDesc::Tuple(el) => { - current::ExpressionDesc::Pexp_tuple(el.iter().map(map_expression).collect()) - } - pt0::ExpressionDesc::Construct(lid, arg) => { - // Check for JSX fragment (list with [@JSX] attribute) - if has_jsx_attribute(&expr.pexp_attributes) { - if let Longident::Lident(name) = &lid.txt { - if name == "[]" || name == "::" { - let jsx_attrs = map_attributes(&remove_jsx_attribute(&expr.pexp_attributes)); - let children = extract_jsx_children(expr); - let jsx_element = current::JsxElement::Fragment(current::JsxFragment { - opening: loc.loc_start.clone(), - children, - closing: loc.loc_end.clone(), - }); + + let desc = match &expr.pexp_desc { + pt0::ExpressionDesc::Ident(lid) => current::ExpressionDesc::Pexp_ident(self.map_longident_loc(lid)), + pt0::ExpressionDesc::Constant(c) => current::ExpressionDesc::Pexp_constant(map_constant(c)), + pt0::ExpressionDesc::Let(rec_flag, bindings, body) => current::ExpressionDesc::Pexp_let( + map_rec_flag(*rec_flag), + bindings.iter().map(|vb| self.map_value_binding(vb)).collect(), + Box::new(self.map_expression(body)), + ), + pt0::ExpressionDesc::Fun { arg_label: lbl, default, lhs: pat, rhs: body, arity, is_async } => { + current::ExpressionDesc::Pexp_fun { + arg_label: self.map_arg_label(lbl), + default: default.as_ref().map(|e| Box::new(self.map_expression(e))), + lhs: self.map_pattern(pat), + rhs: Box::new(self.map_expression(body)), + arity: map_arity(arity), + is_async: *is_async, + } + } + pt0::ExpressionDesc::Apply { funct: func, args, partial: pt0_partial, transformed_jsx } => { + // Check for JSX attribute - convert back to JSX element + if has_jsx_attribute(&expr.pexp_attributes) { + if let pt0::ExpressionDesc::Ident(tag_lid) = &func.pexp_desc { + let jsx_attrs = self.map_attributes(&remove_jsx_attribute(&expr.pexp_attributes)); + let (props, children) = self.extract_jsx_props_and_children(args); + let tag_name = self.longident_to_jsx_tag(&tag_lid.txt); + let tag_loc = Located::new(tag_name, self.loc(&tag_lid.loc)); + + // Get positions for JSX element structure + let loc_start = self.arena.loc_start(loc).clone(); + let loc_end = self.arena.loc_end(loc).clone(); + + let jsx_element = if children.is_empty() { + current::JsxElement::Unary(current::JsxUnaryElement { + tag_name: tag_loc, + props, + }) + } else { + current::JsxElement::Container(current::JsxContainerElement { + tag_name_start: tag_loc.clone(), + opening_end: loc_start.clone(), + props, + children, + closing_tag: Some(current::JsxClosingTag { + start: loc_end.clone(), + name: tag_loc, + end: loc_end, + }), + }) + }; + return current::Expression { pexp_desc: current::ExpressionDesc::Pexp_jsx_element(jsx_element), pexp_loc: loc, @@ -718,600 +730,667 @@ fn map_expression(expr: &pt0::Expression) -> current::Expression { }; } } - } - // Check for Function$ wrapper (arity encoding) - if let Longident::Lident(name) = &lid.txt { - if name == "Function$" { - if let Some(inner) = arg { - let mapped = map_expression(inner); - if let current::ExpressionDesc::Pexp_fun { arg_label, default, lhs, rhs, is_async, .. } = mapped.pexp_desc { - // Extract arity from attributes - let arity_opt = get_arity_from_attributes(&attrs); - let arity = match arity_opt { - Some(n) => current::Arity::Full(n as usize), - None => current::Arity::Unknown, + // Check for partial application attribute (legacy) or use pt0_partial + let partial = *pt0_partial || has_partial_attribute(&expr.pexp_attributes); + let attrs = if has_partial_attribute(&expr.pexp_attributes) { + self.map_attributes(&remove_partial_attribute(&expr.pexp_attributes)) + } else { + attrs.clone() + }; + + // Map operator names + let func = if let pt0::ExpressionDesc::Ident(lid) = &func.pexp_desc { + match &lid.txt { + Longident::Lident(name) => { + let name_str = self.get_str(*name); + let new_name = match name_str { + "|." => Some("->"), + "^" => Some("++"), + "<>" => Some("!="), + "!=" => Some("!=="), + "=" => Some("=="), + "==" => Some("==="), + _ => None, }; - let new_attrs = remove_arity_attribute(&attrs); + if let Some(new_name) = new_name { + let new_str_idx = self.arena.intern_string(new_name); + pt0::Expression { + pexp_desc: pt0::ExpressionDesc::Ident(OldLocated { + txt: Longident::Lident(new_str_idx), + loc: lid.loc.clone(), + }), + pexp_loc: func.pexp_loc.clone(), + pexp_attributes: func.pexp_attributes.clone(), + } + } else { + func.as_ref().clone() + } + } + _ => func.as_ref().clone(), + } + } else { + func.as_ref().clone() + }; + + return current::Expression { + pexp_desc: current::ExpressionDesc::Pexp_apply { + funct: Box::new(self.map_expression(&func)), + args: args + .iter() + .map(|(lbl, e)| (self.map_arg_label(lbl), self.map_expression(e))) + .collect(), + partial, + transformed_jsx: *transformed_jsx, + }, + pexp_loc: loc, + pexp_attributes: attrs, + }; + } + pt0::ExpressionDesc::Match(e, cases) => current::ExpressionDesc::Pexp_match( + Box::new(self.map_expression(e)), + cases.iter().map(|c| self.map_case(c)).collect(), + ), + pt0::ExpressionDesc::Try(e, cases) => current::ExpressionDesc::Pexp_try( + Box::new(self.map_expression(e)), + cases.iter().map(|c| self.map_case(c)).collect(), + ), + pt0::ExpressionDesc::Tuple(el) => { + current::ExpressionDesc::Pexp_tuple(el.iter().map(|e| self.map_expression(e)).collect()) + } + pt0::ExpressionDesc::Construct(lid, arg) => { + // Check for JSX fragment (list with [@JSX] attribute) + if has_jsx_attribute(&expr.pexp_attributes) { + if let Longident::Lident(name) = &lid.txt { + let name_str = self.get_str(*name); + if name_str == "[]" || name_str == "::" { + let jsx_attrs = self.map_attributes(&remove_jsx_attribute(&expr.pexp_attributes)); + let children = self.extract_jsx_children(expr); + let loc_start = self.arena.loc_start(loc).clone(); + let loc_end = self.arena.loc_end(loc).clone(); + let jsx_element = current::JsxElement::Fragment(current::JsxFragment { + opening: loc_start, + children, + closing: loc_end, + }); return current::Expression { - pexp_desc: current::ExpressionDesc::Pexp_fun { - arg_label, - default, - lhs, - rhs, - arity, - is_async, - }, + pexp_desc: current::ExpressionDesc::Pexp_jsx_element(jsx_element), pexp_loc: loc, - pexp_attributes: new_attrs, + pexp_attributes: jsx_attrs, }; } } } - } - current::ExpressionDesc::Pexp_construct( - map_loc(lid), - map_opt(|e| Box::new(map_expression(e)), arg), - ) - } - pt0::ExpressionDesc::Variant(label, arg) => current::ExpressionDesc::Pexp_variant( - label.clone(), - map_opt(|e| Box::new(map_expression(e)), arg), - ), - pt0::ExpressionDesc::Record(fields, base) => { - let fields = fields - .iter() - .map(|pt0::RecordElement { lid, x: e, opt }| { - let mapped_expr = map_expression(e); - // Preserve opt from parsetree0 if present, or check for optional attribute - let optional = *opt || has_optional_attribute(&mapped_expr.pexp_attributes); - let expr_attrs = if has_optional_attribute(&mapped_expr.pexp_attributes) { - remove_optional_attribute(&mapped_expr.pexp_attributes) - } else { - mapped_expr.pexp_attributes.clone() - }; - current::ExpressionRecordField { - lid: map_loc(lid), - expr: current::Expression { - pexp_desc: mapped_expr.pexp_desc, - pexp_loc: mapped_expr.pexp_loc, - pexp_attributes: expr_attrs, - }, - opt: optional, + + // Check for Function$ wrapper (arity encoding) + if let Longident::Lident(name) = &lid.txt { + if self.get_str(*name) == "Function$" { + if let Some(inner) = arg { + let mapped = self.map_expression(inner); + if let current::ExpressionDesc::Pexp_fun { arg_label, default, lhs, rhs, is_async, .. } = mapped.pexp_desc { + // Extract arity from attributes + let arity_opt = get_arity_from_attributes(&attrs); + let arity = match arity_opt { + Some(n) => current::Arity::Full(n as usize), + None => current::Arity::Unknown, + }; + let new_attrs = remove_arity_attribute(&attrs); + return current::Expression { + pexp_desc: current::ExpressionDesc::Pexp_fun { + arg_label, + default, + lhs, + rhs, + arity, + is_async, + }, + pexp_loc: loc, + pexp_attributes: new_attrs, + }; + } + } } - }) - .collect(); - current::ExpressionDesc::Pexp_record( - fields, - map_opt(|e| Box::new(map_expression(e)), base), - ) - } - pt0::ExpressionDesc::Field(e, lid) => { - current::ExpressionDesc::Pexp_field(Box::new(map_expression(e)), map_loc(lid)) - } - pt0::ExpressionDesc::Setfield(e1, lid, e2) => current::ExpressionDesc::Pexp_setfield( - Box::new(map_expression(e1)), - map_loc(lid), - Box::new(map_expression(e2)), - ), - pt0::ExpressionDesc::Array(el) => { - current::ExpressionDesc::Pexp_array(el.iter().map(map_expression).collect()) - } - pt0::ExpressionDesc::Ifthenelse(e1, e2, e3) => current::ExpressionDesc::Pexp_ifthenelse( - Box::new(map_expression(e1)), - Box::new(map_expression(e2)), - map_opt(|e| Box::new(map_expression(e)), e3), - ), - pt0::ExpressionDesc::Sequence(e1, e2) => current::ExpressionDesc::Pexp_sequence( - Box::new(map_expression(e1)), - Box::new(map_expression(e2)), - ), - pt0::ExpressionDesc::While(e1, e2) => current::ExpressionDesc::Pexp_while( - Box::new(map_expression(e1)), - Box::new(map_expression(e2)), - ), - pt0::ExpressionDesc::For(pat, e1, e2, dir, e3) => current::ExpressionDesc::Pexp_for( - map_pattern(pat), - Box::new(map_expression(e1)), - Box::new(map_expression(e2)), - map_direction_flag(*dir), - Box::new(map_expression(e3)), - ), - pt0::ExpressionDesc::Coerce(e, _, t) => { - current::ExpressionDesc::Pexp_coerce(Box::new(map_expression(e)), None, map_core_type(t)) - } - pt0::ExpressionDesc::Constraint(e, t) => { - current::ExpressionDesc::Pexp_constraint(Box::new(map_expression(e)), map_core_type(t)) - } - pt0::ExpressionDesc::Send(e, method) => { - current::ExpressionDesc::Pexp_send(Box::new(map_expression(e)), map_loc(method)) - } - pt0::ExpressionDesc::Letmodule(name, me, body) => current::ExpressionDesc::Pexp_letmodule( - map_loc(name), - map_module_expr(me), - Box::new(map_expression(body)), - ), - pt0::ExpressionDesc::Letexception(ec, body) => current::ExpressionDesc::Pexp_letexception( - map_extension_constructor(ec), - Box::new(map_expression(body)), - ), - pt0::ExpressionDesc::Assert(e) => { - current::ExpressionDesc::Pexp_assert(Box::new(map_expression(e))) - } - pt0::ExpressionDesc::Newtype(name, body) => { - current::ExpressionDesc::Pexp_newtype(map_loc(name), Box::new(map_expression(body))) - } - pt0::ExpressionDesc::Pack(me) => current::ExpressionDesc::Pexp_pack(map_module_expr(me)), - pt0::ExpressionDesc::Open(ovf, lid, body) => current::ExpressionDesc::Pexp_open( - map_override_flag(*ovf), - map_loc(lid), - Box::new(map_expression(body)), - ), - pt0::ExpressionDesc::Extension(ext) => { - current::ExpressionDesc::Pexp_extension(map_extension(ext)) - } - // OCaml-specific expressions that don't exist in ReScript - pt0::ExpressionDesc::New(_) => { - panic!("OCaml 'new' expressions are not supported in ReScript") - } - pt0::ExpressionDesc::Setinstvar(_, _) => { - panic!("OCaml 'setinstvar' expressions are not supported in ReScript") - } - pt0::ExpressionDesc::Override(_) => { - panic!("OCaml 'override' expressions are not supported in ReScript") - } - pt0::ExpressionDesc::Lazy(_) => { - panic!("OCaml 'lazy' expressions are not supported in ReScript") - } - pt0::ExpressionDesc::Poly(_, _) => { - panic!("OCaml 'poly' expressions are not supported in ReScript") - } - pt0::ExpressionDesc::Object => { - panic!("OCaml 'object' expressions are not supported in ReScript") - } - pt0::ExpressionDesc::Unreachable => { - // Unreachable is represented by a `.` pattern - // Map to an extension point that represents unreachable - current::ExpressionDesc::Pexp_extension(( - mkloc("rescript.exprhole".to_string(), &loc), - current::Payload::PStr(vec![]), - )) - } - }; + } + current::ExpressionDesc::Pexp_construct( + self.map_longident_loc(lid), + arg.as_ref().map(|e| Box::new(self.map_expression(e))), + ) + } + pt0::ExpressionDesc::Variant(label, arg) => current::ExpressionDesc::Pexp_variant( + label.clone(), + arg.as_ref().map(|e| Box::new(self.map_expression(e))), + ), + pt0::ExpressionDesc::Record(fields, base) => { + let fields = fields + .iter() + .map(|pt0::RecordElement { lid, x: e, opt }| { + let mapped_expr = self.map_expression(e); + // Preserve opt from parsetree0 if present, or check for optional attribute + let optional = *opt || has_optional_attribute(&mapped_expr.pexp_attributes); + let expr_attrs = if has_optional_attribute(&mapped_expr.pexp_attributes) { + remove_optional_attribute(&mapped_expr.pexp_attributes) + } else { + mapped_expr.pexp_attributes.clone() + }; + current::ExpressionRecordField { + lid: self.map_longident_loc(lid), + expr: current::Expression { + pexp_desc: mapped_expr.pexp_desc, + pexp_loc: mapped_expr.pexp_loc, + pexp_attributes: expr_attrs, + }, + opt: optional, + } + }) + .collect(); + current::ExpressionDesc::Pexp_record( + fields, + base.as_ref().map(|e| Box::new(self.map_expression(e))), + ) + } + pt0::ExpressionDesc::Field(e, lid) => { + current::ExpressionDesc::Pexp_field(Box::new(self.map_expression(e)), self.map_longident_loc(lid)) + } + pt0::ExpressionDesc::Setfield(e1, lid, e2) => current::ExpressionDesc::Pexp_setfield( + Box::new(self.map_expression(e1)), + self.map_longident_loc(lid), + Box::new(self.map_expression(e2)), + ), + pt0::ExpressionDesc::Array(el) => { + current::ExpressionDesc::Pexp_array(el.iter().map(|e| self.map_expression(e)).collect()) + } + pt0::ExpressionDesc::Ifthenelse(e1, e2, e3) => current::ExpressionDesc::Pexp_ifthenelse( + Box::new(self.map_expression(e1)), + Box::new(self.map_expression(e2)), + e3.as_ref().map(|e| Box::new(self.map_expression(e))), + ), + pt0::ExpressionDesc::Sequence(e1, e2) => current::ExpressionDesc::Pexp_sequence( + Box::new(self.map_expression(e1)), + Box::new(self.map_expression(e2)), + ), + pt0::ExpressionDesc::While(e1, e2) => current::ExpressionDesc::Pexp_while( + Box::new(self.map_expression(e1)), + Box::new(self.map_expression(e2)), + ), + pt0::ExpressionDesc::For(pat, e1, e2, dir, e3) => current::ExpressionDesc::Pexp_for( + self.map_pattern(pat), + Box::new(self.map_expression(e1)), + Box::new(self.map_expression(e2)), + map_direction_flag(*dir), + Box::new(self.map_expression(e3)), + ), + pt0::ExpressionDesc::Coerce(e, _, t) => { + current::ExpressionDesc::Pexp_coerce(Box::new(self.map_expression(e)), None, self.map_core_type(t)) + } + pt0::ExpressionDesc::Constraint(e, t) => { + current::ExpressionDesc::Pexp_constraint(Box::new(self.map_expression(e)), self.map_core_type(t)) + } + pt0::ExpressionDesc::Send(e, method) => { + current::ExpressionDesc::Pexp_send(Box::new(self.map_expression(e)), self.map_loc(method)) + } + pt0::ExpressionDesc::Letmodule(name, me, body) => current::ExpressionDesc::Pexp_letmodule( + self.map_loc(name), + self.map_module_expr(me), + Box::new(self.map_expression(body)), + ), + pt0::ExpressionDesc::Letexception(ec, body) => current::ExpressionDesc::Pexp_letexception( + self.map_extension_constructor(ec), + Box::new(self.map_expression(body)), + ), + pt0::ExpressionDesc::Assert(e) => { + current::ExpressionDesc::Pexp_assert(Box::new(self.map_expression(e))) + } + pt0::ExpressionDesc::Newtype(name, body) => { + current::ExpressionDesc::Pexp_newtype(self.map_loc(name), Box::new(self.map_expression(body))) + } + pt0::ExpressionDesc::Pack(me) => current::ExpressionDesc::Pexp_pack(self.map_module_expr(me)), + pt0::ExpressionDesc::Open(ovf, lid, body) => current::ExpressionDesc::Pexp_open( + map_override_flag(*ovf), + self.map_longident_loc(lid), + Box::new(self.map_expression(body)), + ), + pt0::ExpressionDesc::Extension(ext) => { + current::ExpressionDesc::Pexp_extension(self.map_extension(ext)) + } + // OCaml-specific expressions that don't exist in ReScript + pt0::ExpressionDesc::New(_) => { + panic!("OCaml 'new' expressions are not supported in ReScript") + } + pt0::ExpressionDesc::Setinstvar(_, _) => { + panic!("OCaml 'setinstvar' expressions are not supported in ReScript") + } + pt0::ExpressionDesc::Override(_) => { + panic!("OCaml 'override' expressions are not supported in ReScript") + } + pt0::ExpressionDesc::Lazy(_) => { + panic!("OCaml 'lazy' expressions are not supported in ReScript") + } + pt0::ExpressionDesc::Poly(_, _) => { + panic!("OCaml 'poly' expressions are not supported in ReScript") + } + pt0::ExpressionDesc::Object => { + panic!("OCaml 'object' expressions are not supported in ReScript") + } + pt0::ExpressionDesc::Unreachable => { + // Unreachable is represented by a `.` pattern + // Map to an extension point that represents unreachable + current::ExpressionDesc::Pexp_extension(( + self.mkloc("rescript.exprhole".to_string(), &expr.pexp_loc), + current::Payload::PStr(vec![]), + )) + } + }; - current::Expression { - pexp_desc: desc, - pexp_loc: loc, - pexp_attributes: attrs, + current::Expression { + pexp_desc: desc, + pexp_loc: loc, + pexp_attributes: attrs, + } } -} -fn map_case(c: &pt0::Case) -> current::Case { - current::Case { - pc_bar: None, - pc_lhs: map_pattern(&c.pc_lhs), - pc_guard: map_opt(map_expression, &c.pc_guard), - pc_rhs: map_expression(&c.pc_rhs), + fn map_case(&mut self, c: &pt0::Case) -> current::Case { + current::Case { + pc_bar: None, + pc_lhs: self.map_pattern(&c.pc_lhs), + pc_guard: c.pc_guard.as_ref().map(|g| self.map_expression(g)), + pc_rhs: self.map_expression(&c.pc_rhs), + } } -} -fn map_value_binding(vb: &pt0::ValueBinding) -> current::ValueBinding { - current::ValueBinding { - pvb_pat: map_pattern(&vb.pvb_pat), - pvb_expr: map_expression(&vb.pvb_expr), - pvb_attributes: map_attributes(&vb.pvb_attributes), - pvb_loc: vb.pvb_loc.clone(), + fn map_value_binding(&mut self, vb: &pt0::ValueBinding) -> current::ValueBinding { + current::ValueBinding { + pvb_pat: self.map_pattern(&vb.pvb_pat), + pvb_expr: self.map_expression(&vb.pvb_expr), + pvb_attributes: self.map_attributes(&vb.pvb_attributes), + pvb_loc: self.loc(&vb.pvb_loc), + } } -} -// ========== Module expressions ========== + // ========== Module expressions ========== -fn map_module_expr(me: &pt0::ModuleExpr) -> current::ModuleExpr { - let loc = me.pmod_loc.clone(); - let attrs = map_attributes(&me.pmod_attributes); + fn map_module_expr(&mut self, me: &pt0::ModuleExpr) -> current::ModuleExpr { + let loc = self.loc(&me.pmod_loc); + let attrs = self.map_attributes(&me.pmod_attributes); - let desc = match &me.pmod_desc { - pt0::ModuleExprDesc::Ident(lid) => current::ModuleExprDesc::Pmod_ident(map_loc(lid)), - pt0::ModuleExprDesc::Structure(str) => { - current::ModuleExprDesc::Pmod_structure(map_structure(str)) - } - pt0::ModuleExprDesc::Functor(name, mt, body) => current::ModuleExprDesc::Pmod_functor( - map_loc(name), - mt.as_ref().map(|mt| Box::new(map_module_type(mt))), - Box::new(map_module_expr(body)), - ), - pt0::ModuleExprDesc::Apply(m1, m2) => current::ModuleExprDesc::Pmod_apply( - Box::new(map_module_expr(m1)), - Box::new(map_module_expr(m2)), - ), - pt0::ModuleExprDesc::Constraint(m, mt) => { - current::ModuleExprDesc::Pmod_constraint(Box::new(map_module_expr(m)), Box::new(map_module_type(mt))) - } - pt0::ModuleExprDesc::Unpack(e) => { - current::ModuleExprDesc::Pmod_unpack(Box::new(map_expression(e))) - } - pt0::ModuleExprDesc::Extension(ext) => { - current::ModuleExprDesc::Pmod_extension(map_extension(ext)) - } - }; + let desc = match &me.pmod_desc { + pt0::ModuleExprDesc::Ident(lid) => current::ModuleExprDesc::Pmod_ident(self.map_longident_loc(lid)), + pt0::ModuleExprDesc::Structure(str) => { + current::ModuleExprDesc::Pmod_structure(self.map_structure(str)) + } + pt0::ModuleExprDesc::Functor(name, mt, body) => current::ModuleExprDesc::Pmod_functor( + self.map_loc(name), + mt.as_ref().map(|mt| Box::new(self.map_module_type(mt))), + Box::new(self.map_module_expr(body)), + ), + pt0::ModuleExprDesc::Apply(m1, m2) => current::ModuleExprDesc::Pmod_apply( + Box::new(self.map_module_expr(m1)), + Box::new(self.map_module_expr(m2)), + ), + pt0::ModuleExprDesc::Constraint(m, mt) => { + current::ModuleExprDesc::Pmod_constraint(Box::new(self.map_module_expr(m)), Box::new(self.map_module_type(mt))) + } + pt0::ModuleExprDesc::Unpack(e) => { + current::ModuleExprDesc::Pmod_unpack(Box::new(self.map_expression(e))) + } + pt0::ModuleExprDesc::Extension(ext) => { + current::ModuleExprDesc::Pmod_extension(self.map_extension(ext)) + } + }; - current::ModuleExpr { - pmod_desc: desc, - pmod_loc: loc, - pmod_attributes: attrs, + current::ModuleExpr { + pmod_desc: desc, + pmod_loc: loc, + pmod_attributes: attrs, + } } -} -// ========== Module types ========== + // ========== Module types ========== -fn map_module_type(mt: &pt0::ModuleType) -> current::ModuleType { - let loc = mt.pmty_loc.clone(); - let attrs = map_attributes(&mt.pmty_attributes); + fn map_module_type(&mut self, mt: &pt0::ModuleType) -> current::ModuleType { + let loc = self.loc(&mt.pmty_loc); + let attrs = self.map_attributes(&mt.pmty_attributes); - let desc = match &mt.pmty_desc { - pt0::ModuleTypeDesc::Ident(lid) => current::ModuleTypeDesc::Pmty_ident(map_loc(lid)), - pt0::ModuleTypeDesc::Alias(lid) => current::ModuleTypeDesc::Pmty_alias(map_loc(lid)), - pt0::ModuleTypeDesc::Signature(sig) => { - current::ModuleTypeDesc::Pmty_signature(map_signature(sig)) - } - pt0::ModuleTypeDesc::Functor(name, mt1, mt2) => current::ModuleTypeDesc::Pmty_functor( - map_loc(name), - map_opt(|m| Box::new(map_module_type(m)), mt1), - Box::new(map_module_type(mt2)), - ), - pt0::ModuleTypeDesc::With(mt, constraints) => current::ModuleTypeDesc::Pmty_with( - Box::new(map_module_type(mt)), - constraints.iter().map(map_with_constraint).collect(), - ), - pt0::ModuleTypeDesc::Typeof(me) => { - current::ModuleTypeDesc::Pmty_typeof(Box::new(map_module_expr(me))) - } - pt0::ModuleTypeDesc::Extension(ext) => { - current::ModuleTypeDesc::Pmty_extension(map_extension(ext)) - } - }; + let desc = match &mt.pmty_desc { + pt0::ModuleTypeDesc::Ident(lid) => current::ModuleTypeDesc::Pmty_ident(self.map_longident_loc(lid)), + pt0::ModuleTypeDesc::Alias(lid) => current::ModuleTypeDesc::Pmty_alias(self.map_longident_loc(lid)), + pt0::ModuleTypeDesc::Signature(sig) => { + current::ModuleTypeDesc::Pmty_signature(self.map_signature(sig)) + } + pt0::ModuleTypeDesc::Functor(name, mt1, mt2) => current::ModuleTypeDesc::Pmty_functor( + self.map_loc(name), + mt1.as_ref().map(|m| Box::new(self.map_module_type(m))), + Box::new(self.map_module_type(mt2)), + ), + pt0::ModuleTypeDesc::With(mt, constraints) => current::ModuleTypeDesc::Pmty_with( + Box::new(self.map_module_type(mt)), + constraints.iter().map(|wc| self.map_with_constraint(wc)).collect(), + ), + pt0::ModuleTypeDesc::Typeof(me) => { + current::ModuleTypeDesc::Pmty_typeof(Box::new(self.map_module_expr(me))) + } + pt0::ModuleTypeDesc::Extension(ext) => { + current::ModuleTypeDesc::Pmty_extension(self.map_extension(ext)) + } + }; - current::ModuleType { - pmty_desc: desc, - pmty_loc: loc, - pmty_attributes: attrs, + current::ModuleType { + pmty_desc: desc, + pmty_loc: loc, + pmty_attributes: attrs, + } } -} -fn map_with_constraint(wc: &pt0::WithConstraint) -> current::WithConstraint { - match wc { - pt0::WithConstraint::Type(lid, td) => { - current::WithConstraint::Pwith_type(map_loc(lid), map_type_declaration(td)) - } - pt0::WithConstraint::Module(lid1, lid2) => { - current::WithConstraint::Pwith_module(map_loc(lid1), map_loc(lid2)) - } - pt0::WithConstraint::TypeSubst(lid, td) => { - current::WithConstraint::Pwith_typesubst(map_loc(lid), map_type_declaration(td)) - } - pt0::WithConstraint::ModSubst(lid1, lid2) => { - current::WithConstraint::Pwith_modsubst(map_loc(lid1), map_loc(lid2)) + fn map_with_constraint(&mut self, wc: &pt0::WithConstraint) -> current::WithConstraint { + match wc { + pt0::WithConstraint::Type(lid, td) => { + current::WithConstraint::Pwith_type(self.map_longident_loc(lid), self.map_type_declaration(td)) + } + pt0::WithConstraint::Module(lid1, lid2) => { + current::WithConstraint::Pwith_module(self.map_longident_loc(lid1), self.map_longident_loc(lid2)) + } + pt0::WithConstraint::TypeSubst(lid, td) => { + current::WithConstraint::Pwith_typesubst(self.map_longident_loc(lid), self.map_type_declaration(td)) + } + pt0::WithConstraint::ModSubst(lid1, lid2) => { + current::WithConstraint::Pwith_modsubst(self.map_longident_loc(lid1), self.map_longident_loc(lid2)) + } } } -} -// ========== Structure items ========== + // ========== Structure items ========== -fn map_structure_item(item: &pt0::StructureItem) -> current::StructureItem { - let loc = item.pstr_loc.clone(); + fn map_structure_item(&mut self, item: &pt0::StructureItem) -> current::StructureItem { + let loc = self.loc(&item.pstr_loc); - let desc = match &item.pstr_desc { - pt0::StructureItemDesc::Eval(e, attrs) => { - current::StructureItemDesc::Pstr_eval(map_expression(e), map_attributes(attrs)) - } - pt0::StructureItemDesc::Value(rec_flag, bindings) => current::StructureItemDesc::Pstr_value( - map_rec_flag(*rec_flag), - bindings.iter().map(map_value_binding).collect(), - ), - pt0::StructureItemDesc::Primitive(vd) => { - current::StructureItemDesc::Pstr_primitive(map_value_description(vd)) - } - pt0::StructureItemDesc::Type(rec_flag, decls) => current::StructureItemDesc::Pstr_type( - map_rec_flag(*rec_flag), - decls.iter().map(map_type_declaration).collect(), - ), - pt0::StructureItemDesc::Typext(te) => { - current::StructureItemDesc::Pstr_typext(map_type_extension(te)) - } - pt0::StructureItemDesc::Exception(ec) => { - current::StructureItemDesc::Pstr_exception(map_extension_constructor(ec)) - } - pt0::StructureItemDesc::Module(mb) => { - current::StructureItemDesc::Pstr_module(map_module_binding(mb)) - } - pt0::StructureItemDesc::Recmodule(mbs) => { - current::StructureItemDesc::Pstr_recmodule(mbs.iter().map(map_module_binding).collect()) - } - pt0::StructureItemDesc::Modtype(mtd) => { - current::StructureItemDesc::Pstr_modtype(map_module_type_declaration(mtd)) - } - pt0::StructureItemDesc::Open(od) => { - current::StructureItemDesc::Pstr_open(map_open_description(od)) - } - pt0::StructureItemDesc::Include(id) => { - current::StructureItemDesc::Pstr_include(map_include_declaration(id)) - } - pt0::StructureItemDesc::Extension(ext, attrs) => { - current::StructureItemDesc::Pstr_extension(map_extension(ext), map_attributes(attrs)) - } - pt0::StructureItemDesc::Attribute(attr) => { - current::StructureItemDesc::Pstr_attribute(map_attribute(attr)) - } - pt0::StructureItemDesc::Class => { - panic!("OCaml 'class' definitions are not supported in ReScript") - } - pt0::StructureItemDesc::ClassType => { - panic!("OCaml 'class type' definitions are not supported in ReScript") - } - }; + let desc = match &item.pstr_desc { + pt0::StructureItemDesc::Eval(e, attrs) => { + current::StructureItemDesc::Pstr_eval(self.map_expression(e), self.map_attributes(attrs)) + } + pt0::StructureItemDesc::Value(rec_flag, bindings) => current::StructureItemDesc::Pstr_value( + map_rec_flag(*rec_flag), + bindings.iter().map(|vb| self.map_value_binding(vb)).collect(), + ), + pt0::StructureItemDesc::Primitive(vd) => { + current::StructureItemDesc::Pstr_primitive(self.map_value_description(vd)) + } + pt0::StructureItemDesc::Type(rec_flag, decls) => current::StructureItemDesc::Pstr_type( + map_rec_flag(*rec_flag), + decls.iter().map(|td| self.map_type_declaration(td)).collect(), + ), + pt0::StructureItemDesc::Typext(te) => { + current::StructureItemDesc::Pstr_typext(self.map_type_extension(te)) + } + pt0::StructureItemDesc::Exception(ec) => { + current::StructureItemDesc::Pstr_exception(self.map_extension_constructor(ec)) + } + pt0::StructureItemDesc::Module(mb) => { + current::StructureItemDesc::Pstr_module(self.map_module_binding(mb)) + } + pt0::StructureItemDesc::Recmodule(mbs) => { + current::StructureItemDesc::Pstr_recmodule(mbs.iter().map(|mb| self.map_module_binding(mb)).collect()) + } + pt0::StructureItemDesc::Modtype(mtd) => { + current::StructureItemDesc::Pstr_modtype(self.map_module_type_declaration(mtd)) + } + pt0::StructureItemDesc::Open(od) => { + current::StructureItemDesc::Pstr_open(self.map_open_description(od)) + } + pt0::StructureItemDesc::Include(id) => { + current::StructureItemDesc::Pstr_include(self.map_include_declaration(id)) + } + pt0::StructureItemDesc::Extension(ext, attrs) => { + current::StructureItemDesc::Pstr_extension(self.map_extension(ext), self.map_attributes(attrs)) + } + pt0::StructureItemDesc::Attribute(attr) => { + current::StructureItemDesc::Pstr_attribute(self.map_attribute(attr)) + } + pt0::StructureItemDesc::Class => { + panic!("OCaml 'class' definitions are not supported in ReScript") + } + pt0::StructureItemDesc::ClassType => { + panic!("OCaml 'class type' definitions are not supported in ReScript") + } + }; - current::StructureItem { - pstr_desc: desc, - pstr_loc: loc, + current::StructureItem { + pstr_desc: desc, + pstr_loc: loc, + } } -} -// ========== Signature items ========== + // ========== Signature items ========== -fn map_signature_item(item: &pt0::SignatureItem) -> current::SignatureItem { - let loc = item.psig_loc.clone(); + fn map_signature_item(&mut self, item: &pt0::SignatureItem) -> current::SignatureItem { + let loc = self.loc(&item.psig_loc); - let desc = match &item.psig_desc { - pt0::SignatureItemDesc::Value(vd) => { - current::SignatureItemDesc::Psig_value(map_value_description(vd)) - } - pt0::SignatureItemDesc::Type(rec_flag, decls) => current::SignatureItemDesc::Psig_type( - map_rec_flag(*rec_flag), - decls.iter().map(map_type_declaration).collect(), - ), - pt0::SignatureItemDesc::Typext(te) => { - current::SignatureItemDesc::Psig_typext(map_type_extension(te)) - } - pt0::SignatureItemDesc::Exception(ec) => { - current::SignatureItemDesc::Psig_exception(map_extension_constructor(ec)) - } - pt0::SignatureItemDesc::Module(md) => { - current::SignatureItemDesc::Psig_module(map_module_declaration(md)) - } - pt0::SignatureItemDesc::Recmodule(mds) => current::SignatureItemDesc::Psig_recmodule( - mds.iter().map(map_module_declaration).collect(), - ), - pt0::SignatureItemDesc::Modtype(mtd) => { - current::SignatureItemDesc::Psig_modtype(map_module_type_declaration(mtd)) - } - pt0::SignatureItemDesc::Open(od) => { - current::SignatureItemDesc::Psig_open(map_open_description(od)) - } - pt0::SignatureItemDesc::Include(id) => { - current::SignatureItemDesc::Psig_include(map_include_description(id)) - } - pt0::SignatureItemDesc::Extension(ext, attrs) => { - current::SignatureItemDesc::Psig_extension(map_extension(ext), map_attributes(attrs)) - } - pt0::SignatureItemDesc::Attribute(attr) => { - current::SignatureItemDesc::Psig_attribute(map_attribute(attr)) - } - pt0::SignatureItemDesc::Class => { - panic!("OCaml 'class' declarations are not supported in ReScript") - } - pt0::SignatureItemDesc::ClassType => { - panic!("OCaml 'class type' declarations are not supported in ReScript") - } - }; + let desc = match &item.psig_desc { + pt0::SignatureItemDesc::Value(vd) => { + current::SignatureItemDesc::Psig_value(self.map_value_description(vd)) + } + pt0::SignatureItemDesc::Type(rec_flag, decls) => current::SignatureItemDesc::Psig_type( + map_rec_flag(*rec_flag), + decls.iter().map(|td| self.map_type_declaration(td)).collect(), + ), + pt0::SignatureItemDesc::Typext(te) => { + current::SignatureItemDesc::Psig_typext(self.map_type_extension(te)) + } + pt0::SignatureItemDesc::Exception(ec) => { + current::SignatureItemDesc::Psig_exception(self.map_extension_constructor(ec)) + } + pt0::SignatureItemDesc::Module(md) => { + current::SignatureItemDesc::Psig_module(self.map_module_declaration(md)) + } + pt0::SignatureItemDesc::Recmodule(mds) => current::SignatureItemDesc::Psig_recmodule( + mds.iter().map(|md| self.map_module_declaration(md)).collect(), + ), + pt0::SignatureItemDesc::Modtype(mtd) => { + current::SignatureItemDesc::Psig_modtype(self.map_module_type_declaration(mtd)) + } + pt0::SignatureItemDesc::Open(od) => { + current::SignatureItemDesc::Psig_open(self.map_open_description(od)) + } + pt0::SignatureItemDesc::Include(id) => { + current::SignatureItemDesc::Psig_include(self.map_include_description(id)) + } + pt0::SignatureItemDesc::Extension(ext, attrs) => { + current::SignatureItemDesc::Psig_extension(self.map_extension(ext), self.map_attributes(attrs)) + } + pt0::SignatureItemDesc::Attribute(attr) => { + current::SignatureItemDesc::Psig_attribute(self.map_attribute(attr)) + } + pt0::SignatureItemDesc::Class => { + panic!("OCaml 'class' declarations are not supported in ReScript") + } + pt0::SignatureItemDesc::ClassType => { + panic!("OCaml 'class type' declarations are not supported in ReScript") + } + }; - current::SignatureItem { - psig_desc: desc, - psig_loc: loc, + current::SignatureItem { + psig_desc: desc, + psig_loc: loc, + } } -} -// ========== Type declarations ========== - -fn map_type_declaration(td: &pt0::TypeDeclaration) -> current::TypeDeclaration { - current::TypeDeclaration { - ptype_name: map_loc(&td.ptype_name), - ptype_params: td - .ptype_params - .iter() - .map(|(t, v)| (map_core_type(t), map_variance(*v))) - .collect(), - ptype_cstrs: td - .ptype_cstrs - .iter() - .map(|(t1, t2, loc)| (map_core_type(t1), map_core_type(t2), loc.clone())) - .collect(), - ptype_kind: map_type_kind(&td.ptype_kind), - ptype_private: map_private_flag(td.ptype_private), - ptype_manifest: map_opt(map_core_type, &td.ptype_manifest), - ptype_attributes: map_attributes(&td.ptype_attributes), - ptype_loc: td.ptype_loc.clone(), - } -} + // ========== Type declarations ========== -fn map_type_kind(tk: &pt0::TypeKind) -> current::TypeKind { - match tk { - pt0::TypeKind::Abstract => current::TypeKind::Ptype_abstract, - pt0::TypeKind::Variant(cds) => { - current::TypeKind::Ptype_variant(cds.iter().map(map_constructor_declaration).collect()) - } - pt0::TypeKind::Record(lds) => { - current::TypeKind::Ptype_record(lds.iter().map(map_label_declaration).collect()) + fn map_type_declaration(&mut self, td: &pt0::TypeDeclaration) -> current::TypeDeclaration { + current::TypeDeclaration { + ptype_name: self.map_loc(&td.ptype_name), + ptype_params: td + .ptype_params + .iter() + .map(|(t, v)| (self.map_core_type(t), map_variance(*v))) + .collect(), + ptype_cstrs: td + .ptype_cstrs + .iter() + .map(|(t1, t2, loc)| (self.map_core_type(t1), self.map_core_type(t2), self.loc(loc))) + .collect(), + ptype_kind: self.map_type_kind(&td.ptype_kind), + ptype_private: map_private_flag(td.ptype_private), + ptype_manifest: td.ptype_manifest.as_ref().map(|t| self.map_core_type(t)), + ptype_attributes: self.map_attributes(&td.ptype_attributes), + ptype_loc: self.loc(&td.ptype_loc), } - pt0::TypeKind::Open => current::TypeKind::Ptype_open, } -} -fn map_constructor_declaration(cd: &pt0::ConstructorDeclaration) -> current::ConstructorDeclaration { - current::ConstructorDeclaration { - pcd_name: map_loc(&cd.pcd_name), - pcd_args: map_constructor_arguments(&cd.pcd_args), - pcd_res: map_opt(map_core_type, &cd.pcd_res), - pcd_loc: cd.pcd_loc.clone(), - pcd_attributes: map_attributes(&cd.pcd_attributes), + fn map_type_kind(&mut self, tk: &pt0::TypeKind) -> current::TypeKind { + match tk { + pt0::TypeKind::Abstract => current::TypeKind::Ptype_abstract, + pt0::TypeKind::Variant(cds) => { + current::TypeKind::Ptype_variant(cds.iter().map(|cd| self.map_constructor_declaration(cd)).collect()) + } + pt0::TypeKind::Record(lds) => { + current::TypeKind::Ptype_record(lds.iter().map(|ld| self.map_label_declaration(ld)).collect()) + } + pt0::TypeKind::Open => current::TypeKind::Ptype_open, + } } -} -fn map_constructor_arguments(ca: &pt0::ConstructorArguments) -> current::ConstructorArguments { - match ca { - pt0::ConstructorArguments::Tuple(tl) => { - current::ConstructorArguments::Pcstr_tuple(tl.iter().map(map_core_type).collect()) - } - pt0::ConstructorArguments::Record(lds) => { - current::ConstructorArguments::Pcstr_record(lds.iter().map(map_label_declaration).collect()) + fn map_constructor_declaration(&mut self, cd: &pt0::ConstructorDeclaration) -> current::ConstructorDeclaration { + current::ConstructorDeclaration { + pcd_name: self.map_loc(&cd.pcd_name), + pcd_args: self.map_constructor_arguments(&cd.pcd_args), + pcd_res: cd.pcd_res.as_ref().map(|t| self.map_core_type(t)), + pcd_loc: self.loc(&cd.pcd_loc), + pcd_attributes: self.map_attributes(&cd.pcd_attributes), } } -} -fn map_label_declaration(ld: &pt0::LabelDeclaration) -> current::LabelDeclaration { - let attrs = map_attributes(&ld.pld_attributes); - let optional = has_optional_attribute(&attrs); - let final_attrs = if optional { - remove_optional_attribute(&attrs) - } else { - attrs - }; - - current::LabelDeclaration { - pld_name: map_loc(&ld.pld_name), - pld_mutable: map_mutable_flag(ld.pld_mutable), - pld_type: map_core_type(&ld.pld_type), - pld_loc: ld.pld_loc.clone(), - pld_attributes: final_attrs, - pld_optional: optional, + fn map_constructor_arguments(&mut self, ca: &pt0::ConstructorArguments) -> current::ConstructorArguments { + match ca { + pt0::ConstructorArguments::Tuple(tl) => { + current::ConstructorArguments::Pcstr_tuple(tl.iter().map(|t| self.map_core_type(t)).collect()) + } + pt0::ConstructorArguments::Record(lds) => { + current::ConstructorArguments::Pcstr_record(lds.iter().map(|ld| self.map_label_declaration(ld)).collect()) + } + } } -} -fn map_type_extension(te: &pt0::TypeExtension) -> current::TypeExtension { - current::TypeExtension { - ptyext_path: map_loc(&te.ptyext_path), - ptyext_params: te - .ptyext_params - .iter() - .map(|(t, v)| (map_core_type(t), map_variance(*v))) - .collect(), - ptyext_constructors: te - .ptyext_constructors - .iter() - .map(map_extension_constructor) - .collect(), - ptyext_private: map_private_flag(te.ptyext_private), - ptyext_attributes: map_attributes(&te.ptyext_attributes), - } -} + fn map_label_declaration(&mut self, ld: &pt0::LabelDeclaration) -> current::LabelDeclaration { + let attrs = self.map_attributes(&ld.pld_attributes); + let optional = has_optional_attribute(&attrs); + let final_attrs = if optional { + remove_optional_attribute(&attrs) + } else { + attrs + }; -fn map_extension_constructor(ec: &pt0::ExtensionConstructor) -> current::ExtensionConstructor { - current::ExtensionConstructor { - pext_name: map_loc(&ec.pext_name), - pext_kind: map_extension_constructor_kind(&ec.pext_kind), - pext_loc: ec.pext_loc.clone(), - pext_attributes: map_attributes(&ec.pext_attributes), + current::LabelDeclaration { + pld_name: self.map_loc(&ld.pld_name), + pld_mutable: map_mutable_flag(ld.pld_mutable), + pld_type: self.map_core_type(&ld.pld_type), + pld_loc: self.loc(&ld.pld_loc), + pld_attributes: final_attrs, + pld_optional: optional, + } } -} -fn map_extension_constructor_kind( - eck: &pt0::ExtensionConstructorKind, -) -> current::ExtensionConstructorKind { - match eck { - pt0::ExtensionConstructorKind::Decl(args, ret) => current::ExtensionConstructorKind::Pext_decl( - map_constructor_arguments(args), - map_opt(map_core_type, ret), - ), - pt0::ExtensionConstructorKind::Rebind(lid) => { - current::ExtensionConstructorKind::Pext_rebind(map_loc(lid)) + fn map_type_extension(&mut self, te: &pt0::TypeExtension) -> current::TypeExtension { + current::TypeExtension { + ptyext_path: self.map_longident_loc(&te.ptyext_path), + ptyext_params: te + .ptyext_params + .iter() + .map(|(t, v)| (self.map_core_type(t), map_variance(*v))) + .collect(), + ptyext_constructors: te + .ptyext_constructors + .iter() + .map(|ec| self.map_extension_constructor(ec)) + .collect(), + ptyext_private: map_private_flag(te.ptyext_private), + ptyext_attributes: self.map_attributes(&te.ptyext_attributes), } } -} - -// ========== Other declarations ========== -fn map_value_description(vd: &pt0::ValueDescription) -> current::ValueDescription { - current::ValueDescription { - pval_name: map_loc(&vd.pval_name), - pval_type: map_core_type(&vd.pval_type), - pval_prim: vd.pval_prim.clone(), - pval_attributes: map_attributes(&vd.pval_attributes), - pval_loc: vd.pval_loc.clone(), + fn map_extension_constructor(&mut self, ec: &pt0::ExtensionConstructor) -> current::ExtensionConstructor { + current::ExtensionConstructor { + pext_name: self.map_loc(&ec.pext_name), + pext_kind: self.map_extension_constructor_kind(&ec.pext_kind), + pext_loc: self.loc(&ec.pext_loc), + pext_attributes: self.map_attributes(&ec.pext_attributes), + } } -} -fn map_module_declaration(md: &pt0::ModuleDeclaration) -> current::ModuleDeclaration { - current::ModuleDeclaration { - pmd_name: map_loc(&md.pmd_name), - pmd_type: map_module_type(&md.pmd_type), - pmd_attributes: map_attributes(&md.pmd_attributes), - pmd_loc: md.pmd_loc.clone(), + fn map_extension_constructor_kind( + &mut self, + eck: &pt0::ExtensionConstructorKind, + ) -> current::ExtensionConstructorKind { + match eck { + pt0::ExtensionConstructorKind::Decl(args, ret) => current::ExtensionConstructorKind::Pext_decl( + self.map_constructor_arguments(args), + ret.as_ref().map(|t| self.map_core_type(t)), + ), + pt0::ExtensionConstructorKind::Rebind(lid) => { + current::ExtensionConstructorKind::Pext_rebind(self.map_longident_loc(lid)) + } + } } -} -fn map_module_type_declaration(mtd: &pt0::ModuleTypeDeclaration) -> current::ModuleTypeDeclaration { - current::ModuleTypeDeclaration { - pmtd_name: map_loc(&mtd.pmtd_name), - pmtd_type: map_opt(map_module_type, &mtd.pmtd_type), - pmtd_attributes: map_attributes(&mtd.pmtd_attributes), - pmtd_loc: mtd.pmtd_loc.clone(), - } -} + // ========== Other declarations ========== -fn map_module_binding(mb: &pt0::ModuleBinding) -> current::ModuleBinding { - current::ModuleBinding { - pmb_name: map_loc(&mb.pmb_name), - pmb_expr: map_module_expr(&mb.pmb_expr), - pmb_attributes: map_attributes(&mb.pmb_attributes), - pmb_loc: mb.pmb_loc.clone(), + fn map_value_description(&mut self, vd: &pt0::ValueDescription) -> current::ValueDescription { + current::ValueDescription { + pval_name: self.map_loc(&vd.pval_name), + pval_type: self.map_core_type(&vd.pval_type), + pval_prim: vd.pval_prim.clone(), + pval_attributes: self.map_attributes(&vd.pval_attributes), + pval_loc: self.loc(&vd.pval_loc), + } } -} -fn map_open_description(od: &pt0::OpenDescription) -> current::OpenDescription { - current::OpenDescription { - popen_lid: map_loc(&od.popen_lid), - popen_override: map_override_flag(od.popen_override), - popen_loc: od.popen_loc.clone(), - popen_attributes: map_attributes(&od.popen_attributes), + fn map_module_declaration(&mut self, md: &pt0::ModuleDeclaration) -> current::ModuleDeclaration { + current::ModuleDeclaration { + pmd_name: self.map_loc(&md.pmd_name), + pmd_type: self.map_module_type(&md.pmd_type), + pmd_attributes: self.map_attributes(&md.pmd_attributes), + pmd_loc: self.loc(&md.pmd_loc), + } } -} -fn map_include_declaration(id: &pt0::IncludeDeclaration) -> current::IncludeDeclaration { - current::IncludeDeclaration { - pincl_mod: map_module_expr(&id.pincl_mod), - pincl_loc: id.pincl_loc.clone(), - pincl_attributes: map_attributes(&id.pincl_attributes), + fn map_module_type_declaration(&mut self, mtd: &pt0::ModuleTypeDeclaration) -> current::ModuleTypeDeclaration { + current::ModuleTypeDeclaration { + pmtd_name: self.map_loc(&mtd.pmtd_name), + pmtd_type: mtd.pmtd_type.as_ref().map(|mt| self.map_module_type(mt)), + pmtd_attributes: self.map_attributes(&mtd.pmtd_attributes), + pmtd_loc: self.loc(&mtd.pmtd_loc), + } } -} -fn map_include_description(id: &pt0::IncludeDescription) -> current::IncludeDescription { - current::IncludeDescription { - pincl_mod: map_module_type(&id.pincl_mod), - pincl_loc: id.pincl_loc.clone(), - pincl_attributes: map_attributes(&id.pincl_attributes), + fn map_module_binding(&mut self, mb: &pt0::ModuleBinding) -> current::ModuleBinding { + current::ModuleBinding { + pmb_name: self.map_loc(&mb.pmb_name), + pmb_expr: self.map_module_expr(&mb.pmb_expr), + pmb_attributes: self.map_attributes(&mb.pmb_attributes), + pmb_loc: self.loc(&mb.pmb_loc), + } } -} - -// ========== Attributes and extensions ========== - -fn map_attribute(attr: &pt0::Attribute) -> current::Attribute { - (map_loc(&attr.0), map_payload(&attr.1)) -} -fn map_attributes(attrs: &[pt0::Attribute]) -> Vec { - attrs.iter().map(map_attribute).collect() -} + fn map_open_description(&mut self, od: &pt0::OpenDescription) -> current::OpenDescription { + current::OpenDescription { + popen_lid: self.map_longident_loc(&od.popen_lid), + popen_override: map_override_flag(od.popen_override), + popen_loc: self.loc(&od.popen_loc), + popen_attributes: self.map_attributes(&od.popen_attributes), + } + } -fn map_extension(ext: &pt0::Extension) -> current::Extension { - (map_loc(&ext.0), map_payload(&ext.1)) -} + fn map_include_declaration(&mut self, id: &pt0::IncludeDeclaration) -> current::IncludeDeclaration { + current::IncludeDeclaration { + pincl_mod: self.map_module_expr(&id.pincl_mod), + pincl_loc: self.loc(&id.pincl_loc), + pincl_attributes: self.map_attributes(&id.pincl_attributes), + } + } -fn map_payload(payload: &pt0::Payload) -> current::Payload { - match payload { - pt0::Payload::PStr(str) => current::Payload::PStr(map_structure(str)), - pt0::Payload::PSig(sig) => current::Payload::PSig(map_signature(sig)), - pt0::Payload::PTyp(t) => current::Payload::PTyp(Box::new(map_core_type(t))), - pt0::Payload::PPat(p, guard) => { - current::Payload::PPat(Box::new(map_pattern(p)), guard.as_ref().map(|g| Box::new(map_expression(g)))) + fn map_include_description(&mut self, id: &pt0::IncludeDescription) -> current::IncludeDescription { + current::IncludeDescription { + pincl_mod: self.map_module_type(&id.pincl_mod), + pincl_loc: self.loc(&id.pincl_loc), + pincl_attributes: self.map_attributes(&id.pincl_attributes), } } } diff --git a/compiler-rust/src/binary_ast/mapper_to0.rs b/compiler-rust/src/binary_ast/mapper_to0.rs index 0796a541b55..1d60ef9114f 100644 --- a/compiler-rust/src/binary_ast/mapper_to0.rs +++ b/compiler-rust/src/binary_ast/mapper_to0.rs @@ -14,1246 +14,1363 @@ //! //! This mirrors `compiler/common/ast_mapper_to0.ml`. -use crate::location::{Located, Location}; +use crate::intern::StrIdx; +use crate::location::{Location as FullLocation, Located as OldLocated}; +use crate::parse_arena::{Located, LocIdx, ParseArena}; use crate::parser::ast::{self as current}; +use crate::parser::longident::Longident; use super::parsetree0 as pt0; +// ========== Public API ========== + /// Convert a structure from current parsetree to parsetree0 -pub fn map_structure(str: &[current::StructureItem]) -> pt0::Structure { - str.iter().map(map_structure_item).collect() +pub fn map_structure(arena: &mut ParseArena, str: &[current::StructureItem]) -> pt0::Structure { + let mut mapper = Mapper::new(arena); + mapper.map_structure(str) } /// Convert a signature from current parsetree to parsetree0 -pub fn map_signature(sig: &[current::SignatureItem]) -> pt0::Signature { - sig.iter().map(map_signature_item).collect() +pub fn map_signature(arena: &mut ParseArena, sig: &[current::SignatureItem]) -> pt0::Signature { + let mut mapper = Mapper::new(arena); + mapper.map_signature(sig) } -// ========== Helper functions ========== - -fn mkloc(txt: T, loc: &Location) -> Located { - Located { - txt, - loc: loc.clone(), - } -} +// ========== Mapper struct ========== -fn mk_optional_attr(loc: &Location) -> pt0::Attribute { - ( - Located::new("res.optional".to_string(), loc.clone()), - pt0::Payload::PStr(vec![]), - ) +/// Mapper from current parsetree (with LocIdx) to parsetree0 (with full Location). +/// Holds a reference to the arena for converting LocIdx values to Location. +pub struct Mapper<'a> { + arena: &'a mut ParseArena, } -fn mk_async_attr(loc: &Location) -> pt0::Attribute { - ( - Located::new("res.async".to_string(), loc.clone()), - pt0::Payload::PStr(vec![]), - ) -} +impl<'a> Mapper<'a> { + pub fn new(arena: &'a mut ParseArena) -> Self { + Self { arena } + } -fn mk_await_attr(loc: &Location) -> pt0::Attribute { - ( - Located::new("res.await".to_string(), loc.clone()), - pt0::Payload::PStr(vec![]), - ) -} + /// Intern a string to get a StrIdx (for creating synthetic Longidents) + fn intern(&mut self, s: &str) -> StrIdx { + self.arena.intern_string(s) + } -fn mk_partial_attr(loc: &Location) -> pt0::Attribute { - ( - Located::new("res.partial".to_string(), loc.clone()), - pt0::Payload::PStr(vec![]), - ) -} + /// Get the string content for a StrIdx + fn get_str(&self, idx: StrIdx) -> &str { + self.arena.get_string(idx) + } -#[allow(dead_code)] -fn mk_arity_attr(arity: usize, loc: &Location) -> pt0::Attribute { - ( - Located::new("res.arity".to_string(), loc.clone()), - pt0::Payload::PStr(vec![pt0::StructureItem { - pstr_desc: pt0::StructureItemDesc::Eval( - pt0::Expression { - pexp_desc: pt0::ExpressionDesc::Constant(pt0::Constant::Integer( - arity.to_string(), - None, - )), - pexp_loc: loc.clone(), - pexp_attributes: vec![], - }, - vec![], - ), - pstr_loc: loc.clone(), - }]), - ) -} + /// Convert a LocIdx to full Location + fn loc(&mut self, idx: LocIdx) -> FullLocation { + self.arena.to_location(idx) + } -// ========== JSX helpers ========== + /// Convert an arena-based Located to a full Located + fn map_loc(&mut self, located: &Located) -> OldLocated { + OldLocated { + txt: located.txt.clone(), + loc: self.loc(located.loc), + } + } -fn mk_jsx_attr(loc: &Location) -> pt0::Attribute { - ( - Located::new("JSX".to_string(), loc.clone()), - pt0::Payload::PStr(vec![]), - ) -} + /// Convert a Located to OldLocated by looking up in arena + fn map_longident_loc(&mut self, located: &Located) -> OldLocated { + OldLocated { + txt: self.arena.get_longident(located.txt).clone(), + loc: self.loc(located.loc), + } + } -fn mk_unit_expr(loc: &Location) -> pt0::Expression { - pt0::Expression { - pexp_desc: pt0::ExpressionDesc::Construct( - Located::new( - crate::parser::longident::Longident::Lident("()".to_string()), - loc.clone(), - ), - None, - ), - pexp_loc: loc.clone(), - pexp_attributes: vec![], + /// Get the longident for a LidentIdx + fn get_longident(&mut self, idx: crate::parse_arena::LidentIdx) -> &crate::parser::longident::Longident { + self.arena.get_longident(idx) } -} -fn mk_nil_expr(loc: &Location) -> pt0::Expression { - pt0::Expression { - pexp_desc: pt0::ExpressionDesc::Construct( - Located::new( - crate::parser::longident::Longident::Lident("[]".to_string()), - loc.clone(), - ), - None, - ), - pexp_loc: loc.clone(), - pexp_attributes: vec![], + /// Create an OldLocated from text and location index + #[allow(dead_code)] + fn mkloc(&mut self, txt: T, loc: LocIdx) -> OldLocated { + OldLocated { + txt, + loc: self.loc(loc), + } } -} -fn map_jsx_props(props: &[current::JsxProp], _loc: &Location) -> Vec<(pt0::ArgLabel, pt0::Expression)> { - props - .iter() - .map(|prop| match prop { - current::JsxProp::Punning { optional, name } => { - let ident_expr = pt0::Expression { - pexp_desc: pt0::ExpressionDesc::Ident(Located::new( - crate::parser::longident::Longident::Lident(name.txt.clone()), - name.loc.clone(), - )), - pexp_loc: name.loc.clone(), - pexp_attributes: vec![], - }; - let label = if *optional { - pt0::ArgLabel::Optional(name.txt.clone()) - } else { - pt0::ArgLabel::Labelled(name.txt.clone()) - }; - (label, ident_expr) - } - current::JsxProp::Value { name, optional, value } => { - let label = if *optional { - pt0::ArgLabel::Optional(name.txt.clone()) - } else { - pt0::ArgLabel::Labelled(name.txt.clone()) - }; - (label, map_expression(value)) - } - current::JsxProp::Spreading { expr, .. } => { - (pt0::ArgLabel::Labelled("_spreadProps".to_string()), map_expression(expr)) - } - }) - .collect() -} + // ========== Public API methods ========== -fn jsx_tag_to_longident(tag: ¤t::JsxTagName) -> crate::parser::longident::Longident { - match tag { - current::JsxTagName::Lower(name) => { - crate::parser::longident::Longident::Lident(name.clone()) - } - current::JsxTagName::QualifiedLower { path, name } => { - crate::parser::longident::Longident::Ldot(Box::new(path.clone()), name.clone()) - } - current::JsxTagName::Upper(lid) => lid.clone(), - current::JsxTagName::Invalid(name) => { - crate::parser::longident::Longident::Lident(name.clone()) - } + /// Convert a structure from current parsetree to parsetree0 + pub fn map_structure(&mut self, str: &[current::StructureItem]) -> pt0::Structure { + str.iter().map(|item| self.map_structure_item(item)).collect() } -} -fn map_jsx_children_to_list(children: &[current::Expression], loc: &Location) -> pt0::Expression { - // Convert children to a list expression (cons cells ending with []) - let nil = mk_nil_expr(loc); - children.iter().rev().fold(nil, |acc, child| { - let child_expr = map_expression(child); - pt0::Expression { - pexp_desc: pt0::ExpressionDesc::Construct( - Located::new( - crate::parser::longident::Longident::Lident("::".to_string()), - loc.clone(), - ), - Some(Box::new(pt0::Expression { - pexp_desc: pt0::ExpressionDesc::Tuple(vec![child_expr, acc]), - pexp_loc: loc.clone(), - pexp_attributes: vec![], - })), - ), - pexp_loc: loc.clone(), - pexp_attributes: vec![], - } - }) -} + /// Convert a signature from current parsetree to parsetree0 + pub fn map_signature(&mut self, sig: &[current::SignatureItem]) -> pt0::Signature { + sig.iter().map(|item| self.map_signature_item(item)).collect() + } -// ========== Flag conversions ========== + // ========== Helper functions ========== -fn map_rec_flag(flag: current::RecFlag) -> pt0::RecFlag { - match flag { - current::RecFlag::Nonrecursive => pt0::RecFlag::Nonrecursive, - current::RecFlag::Recursive => pt0::RecFlag::Recursive, + #[allow(dead_code)] + fn mk_optional_attr(&mut self, loc: LocIdx) -> pt0::Attribute { + ( + OldLocated::new("res.optional".to_string(), self.loc(loc)), + pt0::Payload::PStr(vec![]), + ) } -} -fn map_direction_flag(flag: current::DirectionFlag) -> pt0::DirectionFlag { - match flag { - current::DirectionFlag::Upto => pt0::DirectionFlag::Upto, - current::DirectionFlag::Downto => pt0::DirectionFlag::Downto, + #[allow(dead_code)] + fn mk_async_attr(&mut self, loc: LocIdx) -> pt0::Attribute { + ( + OldLocated::new("res.async".to_string(), self.loc(loc)), + pt0::Payload::PStr(vec![]), + ) } -} -fn map_closed_flag(flag: current::ClosedFlag) -> pt0::ClosedFlag { - match flag { - current::ClosedFlag::Closed => pt0::ClosedFlag::Closed, - current::ClosedFlag::Open => pt0::ClosedFlag::Open, + fn mk_await_attr(&mut self, loc: LocIdx) -> pt0::Attribute { + ( + OldLocated::new("res.await".to_string(), self.loc(loc)), + pt0::Payload::PStr(vec![]), + ) } -} -fn map_override_flag(flag: current::OverrideFlag) -> pt0::OverrideFlag { - match flag { - current::OverrideFlag::Fresh => pt0::OverrideFlag::Fresh, - current::OverrideFlag::Override => pt0::OverrideFlag::Override, + #[allow(dead_code)] + fn mk_partial_attr(&mut self, loc: LocIdx) -> pt0::Attribute { + ( + OldLocated::new("res.partial".to_string(), self.loc(loc)), + pt0::Payload::PStr(vec![]), + ) } -} -fn map_mutable_flag(flag: current::MutableFlag) -> pt0::MutableFlag { - match flag { - current::MutableFlag::Immutable => pt0::MutableFlag::Immutable, - current::MutableFlag::Mutable => pt0::MutableFlag::Mutable, + #[allow(dead_code)] + fn mk_arity_attr(&mut self, arity: usize, loc: LocIdx) -> pt0::Attribute { + let full_loc = self.loc(loc); + ( + OldLocated::new("res.arity".to_string(), full_loc.clone()), + pt0::Payload::PStr(vec![pt0::StructureItem { + pstr_desc: pt0::StructureItemDesc::Eval( + pt0::Expression { + pexp_desc: pt0::ExpressionDesc::Constant(pt0::Constant::Integer( + arity.to_string(), + None, + )), + pexp_loc: full_loc.clone(), + pexp_attributes: vec![], + }, + vec![], + ), + pstr_loc: full_loc, + }]), + ) } -} -fn map_private_flag(flag: current::PrivateFlag) -> pt0::PrivateFlag { - match flag { - current::PrivateFlag::Private => pt0::PrivateFlag::Private, - current::PrivateFlag::Public => pt0::PrivateFlag::Public, + // ========== JSX helpers ========== + + fn mk_jsx_attr(&mut self, loc: LocIdx) -> pt0::Attribute { + ( + OldLocated::new("JSX".to_string(), self.loc(loc)), + pt0::Payload::PStr(vec![]), + ) } -} -fn map_variance(var: current::Variance) -> pt0::Variance { - match var { - current::Variance::Covariant => pt0::Variance::Covariant, - current::Variance::Contravariant => pt0::Variance::Contravariant, - current::Variance::Invariant => pt0::Variance::Invariant, + fn mk_unit_expr(&mut self, loc: LocIdx) -> pt0::Expression { + let full_loc = self.loc(loc); + let unit_idx = self.intern("()"); + pt0::Expression { + pexp_desc: pt0::ExpressionDesc::Construct( + OldLocated::new( + Longident::Lident(unit_idx), + full_loc.clone(), + ), + None, + ), + pexp_loc: full_loc, + pexp_attributes: vec![], + } } -} -fn map_arg_label(label: ¤t::ArgLabel) -> pt0::ArgLabel { - match label { - current::ArgLabel::Nolabel => pt0::ArgLabel::Nolabel, - // parsetree0 doesn't have location info, so extract just the string - current::ArgLabel::Labelled(s) => pt0::ArgLabel::Labelled(s.txt.clone()), - current::ArgLabel::Optional(s) => pt0::ArgLabel::Optional(s.txt.clone()), + fn mk_nil_expr(&mut self, loc: LocIdx) -> pt0::Expression { + let full_loc = self.loc(loc); + let nil_idx = self.intern("[]"); + pt0::Expression { + pexp_desc: pt0::ExpressionDesc::Construct( + OldLocated::new( + Longident::Lident(nil_idx), + full_loc.clone(), + ), + None, + ), + pexp_loc: full_loc, + pexp_attributes: vec![], + } } -} -// ========== Constant ========== - -fn map_constant(c: ¤t::Constant) -> pt0::Constant { - match c { - current::Constant::Integer(s, opt) => pt0::Constant::Integer(s.clone(), *opt), - current::Constant::Char(i) => pt0::Constant::Char(*i), - current::Constant::String(s, opt) => { - // OCaml maps None (regular strings) to Some("js") in parsetree0. - // The "*j" transformation happens later in Ast_config.process_str during compilation, - // NOT during parsetree0 conversion. - // For parsetree0 parity, we just need to convert None -> Some("js"). - let mapped_delim = match opt { - None => Some("js".to_string()), - other => other.clone(), + fn map_jsx_props(&mut self, props: &[current::JsxProp], _loc: LocIdx) -> Vec<(pt0::ArgLabel, pt0::Expression)> { + let mut result = Vec::with_capacity(props.len()); + for prop in props { + let item = match prop { + current::JsxProp::Punning { optional, name } => { + let name_loc = self.loc(name.loc); + // Intern once and reuse for both label and identifier - enables sharing + let name_idx = self.intern(&name.txt); + let ident_expr = pt0::Expression { + pexp_desc: pt0::ExpressionDesc::Ident(OldLocated::new( + Longident::Lident(name_idx), + name_loc.clone(), + )), + pexp_loc: name_loc, + pexp_attributes: vec![], + }; + let label = if *optional { + pt0::ArgLabel::Optional(name_idx) + } else { + pt0::ArgLabel::Labelled(name_idx) + }; + (label, ident_expr) + } + current::JsxProp::Value { name, optional, value } => { + let name_idx = self.intern(&name.txt); + let label = if *optional { + pt0::ArgLabel::Optional(name_idx) + } else { + pt0::ArgLabel::Labelled(name_idx) + }; + (label, self.map_expression(value)) + } + current::JsxProp::Spreading { expr, .. } => { + let spread_idx = self.intern("_spreadProps"); + (pt0::ArgLabel::Labelled(spread_idx), self.map_expression(expr)) + } }; - pt0::Constant::String(s.clone(), mapped_delim) + result.push(item); } - current::Constant::Float(s, opt) => pt0::Constant::Float(s.clone(), *opt), + result } -} - -// ========== Attributes ========== - -fn map_attribute(attr: ¤t::Attribute) -> pt0::Attribute { - let (name, payload) = attr; - ( - Located::new(name.txt.clone(), name.loc.clone()), - map_payload(payload), - ) -} -fn map_attributes(attrs: ¤t::Attributes) -> pt0::Attributes { - attrs.iter().map(map_attribute).collect() -} - -fn map_payload(payload: ¤t::Payload) -> pt0::Payload { - match payload { - current::Payload::PStr(items) => pt0::Payload::PStr(items.iter().map(map_structure_item).collect()), - current::Payload::PSig(items) => pt0::Payload::PSig(items.iter().map(map_signature_item).collect()), - current::Payload::PTyp(ty) => pt0::Payload::PTyp(Box::new(map_core_type(ty))), - current::Payload::PPat(pat, guard) => { - pt0::Payload::PPat( - Box::new(map_pattern(pat)), - guard.as_ref().map(|e| Box::new(map_expression(e))), - ) + fn jsx_tag_to_longident(&mut self, tag: ¤t::JsxTagName) -> Longident { + match tag { + current::JsxTagName::Lower(name) => { + let idx = self.intern(name); + Longident::Lident(idx) + } + current::JsxTagName::QualifiedLower { path, name } => { + let name_idx = self.intern(name); + Longident::Ldot(Box::new(self.get_longident(*path).clone()), name_idx) + } + current::JsxTagName::Upper(lid_idx) => self.get_longident(*lid_idx).clone(), + current::JsxTagName::Invalid(name) => { + let idx = self.intern(name); + Longident::Lident(idx) + } } } -} -// ========== Core Types ========== - -pub fn map_core_type(ty: ¤t::CoreType) -> pt0::CoreType { - // Handle arrow types specially to support arity wrapping - if let current::CoreTypeDesc::Ptyp_arrow { arg, ret, arity } = &ty.ptyp_desc { - let loc = ty.ptyp_loc.clone(); - // Merge outer type's attributes with arg's attributes (OCaml does this) - let arrow_attrs: Vec = map_attributes(&ty.ptyp_attributes) - .into_iter() - .chain(map_attributes(&arg.attrs)) - .collect(); - - // Create the base arrow type - let arrow_type = pt0::CoreType { - ptyp_desc: pt0::CoreTypeDesc::Arrow( - map_arg_label(&arg.lbl), - Box::new(map_core_type(&arg.typ)), - Box::new(map_core_type(ret)), - ), - ptyp_loc: loc.clone(), - ptyp_attributes: arrow_attrs, - }; - - match arity { - current::Arity::Unknown => arrow_type, - current::Arity::Full(n) => { - // Wrap in function$ type constructor with arity variant - // Creates: function$ - let arity_string = format!("Has_arity{}", n); - let arity_type = pt0::CoreType { - ptyp_desc: pt0::CoreTypeDesc::Variant( - vec![pt0::RowField::Rtag( - Located::new(arity_string, loc.clone()), - vec![], // no attributes - true, // constant (no payload) - vec![], // no types - )], - pt0::ClosedFlag::Closed, - None, - ), - ptyp_loc: loc.clone(), - ptyp_attributes: vec![], - }; - pt0::CoreType { - ptyp_desc: pt0::CoreTypeDesc::Constr( - Located::new( - crate::parser::longident::Longident::Lident("function$".to_string()), - loc.clone(), - ), - vec![arrow_type, arity_type], + fn map_jsx_children_to_list(&mut self, children: &[current::Expression], loc: LocIdx) -> pt0::Expression { + // Convert children to a list expression (cons cells ending with []) + let mut result = self.mk_nil_expr(loc); + let full_loc = self.loc(loc); + let cons_idx = self.intern("::"); + for child in children.iter().rev() { + let child_expr = self.map_expression(child); + result = pt0::Expression { + pexp_desc: pt0::ExpressionDesc::Construct( + OldLocated::new( + Longident::Lident(cons_idx), + full_loc.clone(), ), - ptyp_loc: loc, - ptyp_attributes: vec![], - } - } - } - } else { - pt0::CoreType { - ptyp_desc: map_core_type_desc(&ty.ptyp_desc), - ptyp_loc: ty.ptyp_loc.clone(), - ptyp_attributes: map_attributes(&ty.ptyp_attributes), + Some(Box::new(pt0::Expression { + pexp_desc: pt0::ExpressionDesc::Tuple(vec![child_expr, result]), + pexp_loc: full_loc.clone(), + pexp_attributes: vec![], + })), + ), + pexp_loc: full_loc.clone(), + pexp_attributes: vec![], + }; } + result } -} -fn map_core_type_desc(desc: ¤t::CoreTypeDesc) -> pt0::CoreTypeDesc { - match desc { - current::CoreTypeDesc::Ptyp_any => pt0::CoreTypeDesc::Any, - current::CoreTypeDesc::Ptyp_var(s) => pt0::CoreTypeDesc::Var(s.clone()), - current::CoreTypeDesc::Ptyp_arrow { arg, ret, arity: _ } => { - // This branch should not normally be reached since map_core_type handles arrows - // But keep it for completeness - treat as no arity - pt0::CoreTypeDesc::Arrow( - map_arg_label(&arg.lbl), - Box::new(map_core_type(&arg.typ)), - Box::new(map_core_type(ret)), - ) - } - current::CoreTypeDesc::Ptyp_tuple(types) => { - pt0::CoreTypeDesc::Tuple(types.iter().map(map_core_type).collect()) - } - current::CoreTypeDesc::Ptyp_constr(lid, types) => { - pt0::CoreTypeDesc::Constr( - mkloc(lid.txt.clone(), &lid.loc), - types.iter().map(map_core_type).collect(), - ) - } - current::CoreTypeDesc::Ptyp_object(fields, flag) => { - pt0::CoreTypeDesc::Object( - fields.iter().map(map_object_field).collect(), - map_closed_flag(*flag), - ) + // ========== Flag conversions ========== + + fn map_rec_flag(&mut self, flag: current::RecFlag) -> pt0::RecFlag { + match flag { + current::RecFlag::Nonrecursive => pt0::RecFlag::Nonrecursive, + current::RecFlag::Recursive => pt0::RecFlag::Recursive, } - current::CoreTypeDesc::Ptyp_alias(ty, s) => { - pt0::CoreTypeDesc::Alias(Box::new(map_core_type(ty)), s.clone()) + } + + fn map_direction_flag(&mut self, flag: current::DirectionFlag) -> pt0::DirectionFlag { + match flag { + current::DirectionFlag::Upto => pt0::DirectionFlag::Upto, + current::DirectionFlag::Downto => pt0::DirectionFlag::Downto, } - current::CoreTypeDesc::Ptyp_variant(fields, flag, labels) => { - pt0::CoreTypeDesc::Variant( - fields.iter().map(map_row_field).collect(), - map_closed_flag(*flag), - labels.clone(), - ) + } + + fn map_closed_flag(&mut self, flag: current::ClosedFlag) -> pt0::ClosedFlag { + match flag { + current::ClosedFlag::Closed => pt0::ClosedFlag::Closed, + current::ClosedFlag::Open => pt0::ClosedFlag::Open, } - current::CoreTypeDesc::Ptyp_poly(vars, ty) => { - pt0::CoreTypeDesc::Poly( - vars.iter() - .map(|v| Located::new(v.txt.clone(), v.loc.clone())) - .collect(), - Box::new(map_core_type(ty)), - ) + } + + fn map_override_flag(&mut self, flag: current::OverrideFlag) -> pt0::OverrideFlag { + match flag { + current::OverrideFlag::Fresh => pt0::OverrideFlag::Fresh, + current::OverrideFlag::Override => pt0::OverrideFlag::Override, } - current::CoreTypeDesc::Ptyp_package(pkg) => { - pt0::CoreTypeDesc::Package(map_package_type(pkg)) + } + + fn map_mutable_flag(&mut self, flag: current::MutableFlag) -> pt0::MutableFlag { + match flag { + current::MutableFlag::Immutable => pt0::MutableFlag::Immutable, + current::MutableFlag::Mutable => pt0::MutableFlag::Mutable, } - current::CoreTypeDesc::Ptyp_extension(ext) => { - pt0::CoreTypeDesc::Extension(map_extension(ext)) + } + + fn map_private_flag(&mut self, flag: current::PrivateFlag) -> pt0::PrivateFlag { + match flag { + current::PrivateFlag::Private => pt0::PrivateFlag::Private, + current::PrivateFlag::Public => pt0::PrivateFlag::Public, } } -} -fn map_package_type(pkg: ¤t::PackageType) -> pt0::PackageType { - let (lid, constraints) = pkg; - ( - mkloc(lid.txt.clone(), &lid.loc), - constraints - .iter() - .map(|(lid, ty)| (mkloc(lid.txt.clone(), &lid.loc), map_core_type(ty))) - .collect(), - ) -} + fn map_variance(&mut self, var: current::Variance) -> pt0::Variance { + match var { + current::Variance::Covariant => pt0::Variance::Covariant, + current::Variance::Contravariant => pt0::Variance::Contravariant, + current::Variance::Invariant => pt0::Variance::Invariant, + } + } -fn map_row_field(field: ¤t::RowField) -> pt0::RowField { - match field { - current::RowField::Rtag(label, attrs, b, types) => { - pt0::RowField::Rtag( - mkloc(label.txt.clone(), &label.loc), - map_attributes(attrs), - *b, - types.iter().map(map_core_type).collect(), - ) + fn map_arg_label(&mut self, label: ¤t::ArgLabel) -> pt0::ArgLabel { + match label { + current::ArgLabel::Nolabel => pt0::ArgLabel::Nolabel, + // Current parsetree already uses StrIdx, just pass it through + current::ArgLabel::Labelled(s) => pt0::ArgLabel::Labelled(s.txt), + current::ArgLabel::Optional(s) => pt0::ArgLabel::Optional(s.txt), } - current::RowField::Rinherit(ty) => pt0::RowField::Rinherit(map_core_type(ty)), } -} -fn map_object_field(field: ¤t::ObjectField) -> pt0::ObjectField { - match field { - current::ObjectField::Otag(label, attrs, ty) => { - pt0::ObjectField::Otag( - mkloc(label.txt.clone(), &label.loc), - map_attributes(attrs), - map_core_type(ty), - ) + // ========== Constant ========== + + fn map_constant(&mut self, c: ¤t::Constant) -> pt0::Constant { + match c { + current::Constant::Integer(s, opt) => pt0::Constant::Integer(s.clone(), *opt), + current::Constant::Char(i) => pt0::Constant::Char(*i), + current::Constant::String(s, opt) => { + // OCaml maps None (regular strings) to Some("js") in parsetree0. + // The "*j" transformation happens later in Ast_config.process_str during compilation, + // NOT during parsetree0 conversion. + // For parsetree0 parity, we just need to convert None -> Some("js"). + let mapped_delim = match opt { + None => Some("js".to_string()), + other => other.clone(), + }; + pt0::Constant::String(s.clone(), mapped_delim) + } + current::Constant::Float(s, opt) => pt0::Constant::Float(s.clone(), *opt), } - current::ObjectField::Oinherit(ty) => pt0::ObjectField::Oinherit(map_core_type(ty)), } -} -fn map_extension(ext: ¤t::Extension) -> pt0::Extension { - let (name, payload) = ext; - ( - Located::new(name.txt.clone(), name.loc.clone()), - map_payload(payload), - ) -} + // ========== Attributes ========== -// ========== Patterns ========== + fn map_attribute(&mut self, attr: ¤t::Attribute) -> pt0::Attribute { + let (name, payload) = attr; + ( + self.map_loc(name), + self.map_payload(payload), + ) + } -pub fn map_pattern(pat: ¤t::Pattern) -> pt0::Pattern { - pt0::Pattern { - ppat_desc: map_pattern_desc(&pat.ppat_desc), - ppat_loc: pat.ppat_loc.clone(), - ppat_attributes: map_attributes(&pat.ppat_attributes), + fn map_attributes(&mut self, attrs: ¤t::Attributes) -> pt0::Attributes { + attrs.iter().map(|a| self.map_attribute(a)).collect() } -} -fn map_pattern_desc(desc: ¤t::PatternDesc) -> pt0::PatternDesc { - match desc { - current::PatternDesc::Ppat_any => pt0::PatternDesc::Any, - current::PatternDesc::Ppat_var(s) => { - pt0::PatternDesc::Var(mkloc(s.txt.clone(), &s.loc)) - } - current::PatternDesc::Ppat_alias(pat, s) => { - pt0::PatternDesc::Alias(Box::new(map_pattern(pat)), mkloc(s.txt.clone(), &s.loc)) - } - current::PatternDesc::Ppat_constant(c) => pt0::PatternDesc::Constant(map_constant(c)), - current::PatternDesc::Ppat_interval(c1, c2) => { - pt0::PatternDesc::Interval(map_constant(c1), map_constant(c2)) - } - current::PatternDesc::Ppat_tuple(pats) => { - pt0::PatternDesc::Tuple(pats.iter().map(map_pattern).collect()) - } - current::PatternDesc::Ppat_construct(lid, opt) => { - pt0::PatternDesc::Construct( - mkloc(lid.txt.clone(), &lid.loc), - opt.as_ref().map(|p| Box::new(map_pattern(p))), - ) - } - current::PatternDesc::Ppat_variant(label, opt) => { - pt0::PatternDesc::Variant(label.clone(), opt.as_ref().map(|p| Box::new(map_pattern(p)))) - } - current::PatternDesc::Ppat_record(fields, flag) => { - // Use RecordElement with 3 fields (lid, x, opt) for current parsetree format - pt0::PatternDesc::Record( - fields - .iter() - .map(|f| pt0::RecordElement { - lid: mkloc(f.lid.txt.clone(), &f.lid.loc), - x: map_pattern(&f.pat), - opt: f.opt, - }) - .collect(), - map_closed_flag(*flag), - ) - } - current::PatternDesc::Ppat_array(pats) => { - pt0::PatternDesc::Array(pats.iter().map(map_pattern).collect()) - } - current::PatternDesc::Ppat_or(p1, p2) => { - pt0::PatternDesc::Or(Box::new(map_pattern(p1)), Box::new(map_pattern(p2))) - } - current::PatternDesc::Ppat_constraint(pat, ty) => { - pt0::PatternDesc::Constraint(Box::new(map_pattern(pat)), Box::new(map_core_type(ty))) - } - current::PatternDesc::Ppat_type(lid) => { - pt0::PatternDesc::Type(mkloc(lid.txt.clone(), &lid.loc)) + fn map_payload(&mut self, payload: ¤t::Payload) -> pt0::Payload { + match payload { + current::Payload::PStr(items) => pt0::Payload::PStr(items.iter().map(|i| self.map_structure_item(i)).collect()), + current::Payload::PSig(items) => pt0::Payload::PSig(items.iter().map(|i| self.map_signature_item(i)).collect()), + current::Payload::PTyp(ty) => pt0::Payload::PTyp(Box::new(self.map_core_type(ty))), + current::Payload::PPat(pat, guard) => { + pt0::Payload::PPat( + Box::new(self.map_pattern(pat)), + guard.as_ref().map(|e| Box::new(self.map_expression(e))), + ) + } } - current::PatternDesc::Ppat_unpack(s) => { - pt0::PatternDesc::Unpack(mkloc(s.txt.clone(), &s.loc)) + } + + // ========== Core Types ========== + + pub fn map_core_type(&mut self, ty: ¤t::CoreType) -> pt0::CoreType { + // Handle arrow types specially to support arity wrapping + if let current::CoreTypeDesc::Ptyp_arrow { arg, ret, arity } = &ty.ptyp_desc { + let loc = self.loc(ty.ptyp_loc); + // Merge outer type's attributes with arg's attributes (OCaml does this) + let arrow_attrs: Vec = self.map_attributes(&ty.ptyp_attributes) + .into_iter() + .chain(self.map_attributes(&arg.attrs)) + .collect(); + + // Create the base arrow type + let arrow_type = pt0::CoreType { + ptyp_desc: pt0::CoreTypeDesc::Arrow( + self.map_arg_label(&arg.lbl), + Box::new(self.map_core_type(&arg.typ)), + Box::new(self.map_core_type(ret)), + ), + ptyp_loc: loc.clone(), + ptyp_attributes: arrow_attrs, + }; + + match arity { + current::Arity::Unknown => arrow_type, + current::Arity::Full(n) => { + // Wrap in function$ type constructor with arity variant + // Creates: function$ + let arity_string = format!("Has_arity{}", n); + let function_idx = self.intern("function$"); + let arity_type = pt0::CoreType { + ptyp_desc: pt0::CoreTypeDesc::Variant( + vec![pt0::RowField::Rtag( + OldLocated::new(arity_string, loc.clone()), + vec![], // no attributes + true, // constant (no payload) + vec![], // no types + )], + pt0::ClosedFlag::Closed, + None, + ), + ptyp_loc: loc.clone(), + ptyp_attributes: vec![], + }; + pt0::CoreType { + ptyp_desc: pt0::CoreTypeDesc::Constr( + OldLocated::new( + Longident::Lident(function_idx), + loc.clone(), + ), + vec![arrow_type, arity_type], + ), + ptyp_loc: loc, + ptyp_attributes: vec![], + } + } + } + } else { + pt0::CoreType { + ptyp_desc: self.map_core_type_desc(&ty.ptyp_desc), + ptyp_loc: self.loc(ty.ptyp_loc), + ptyp_attributes: self.map_attributes(&ty.ptyp_attributes), + } } - current::PatternDesc::Ppat_exception(pat) => { - pt0::PatternDesc::Exception(Box::new(map_pattern(pat))) + } + + fn map_core_type_desc(&mut self, desc: ¤t::CoreTypeDesc) -> pt0::CoreTypeDesc { + match desc { + current::CoreTypeDesc::Ptyp_any => pt0::CoreTypeDesc::Any, + current::CoreTypeDesc::Ptyp_var(s) => pt0::CoreTypeDesc::Var(s.clone()), + current::CoreTypeDesc::Ptyp_arrow { arg, ret, arity: _ } => { + // This branch should not normally be reached since map_core_type handles arrows + // But keep it for completeness - treat as no arity + pt0::CoreTypeDesc::Arrow( + self.map_arg_label(&arg.lbl), + Box::new(self.map_core_type(&arg.typ)), + Box::new(self.map_core_type(ret)), + ) + } + current::CoreTypeDesc::Ptyp_tuple(types) => { + pt0::CoreTypeDesc::Tuple(types.iter().map(|t| self.map_core_type(t)).collect()) + } + current::CoreTypeDesc::Ptyp_constr(lid, types) => { + pt0::CoreTypeDesc::Constr( + self.map_longident_loc(lid), + types.iter().map(|t| self.map_core_type(t)).collect(), + ) + } + current::CoreTypeDesc::Ptyp_object(fields, flag) => { + pt0::CoreTypeDesc::Object( + fields.iter().map(|f| self.map_object_field(f)).collect(), + self.map_closed_flag(*flag), + ) + } + current::CoreTypeDesc::Ptyp_alias(ty, s) => { + pt0::CoreTypeDesc::Alias(Box::new(self.map_core_type(ty)), s.clone()) + } + current::CoreTypeDesc::Ptyp_variant(fields, flag, labels) => { + pt0::CoreTypeDesc::Variant( + fields.iter().map(|f| self.map_row_field(f)).collect(), + self.map_closed_flag(*flag), + labels.clone(), + ) + } + current::CoreTypeDesc::Ptyp_poly(vars, ty) => { + pt0::CoreTypeDesc::Poly( + vars.iter() + .map(|v| self.map_loc(v)) + .collect(), + Box::new(self.map_core_type(ty)), + ) + } + current::CoreTypeDesc::Ptyp_package(pkg) => { + pt0::CoreTypeDesc::Package(self.map_package_type(pkg)) + } + current::CoreTypeDesc::Ptyp_extension(ext) => { + pt0::CoreTypeDesc::Extension(self.map_extension(ext)) + } } - current::PatternDesc::Ppat_extension(ext) => pt0::PatternDesc::Extension(map_extension(ext)), - current::PatternDesc::Ppat_open(lid, pat) => { - pt0::PatternDesc::Open(mkloc(lid.txt.clone(), &lid.loc), Box::new(map_pattern(pat))) + } + + fn map_package_type(&mut self, pkg: ¤t::PackageType) -> pt0::PackageType { + let (lid, constraints) = pkg; + ( + self.map_longident_loc(lid), + constraints + .iter() + .map(|(lid, ty)| (self.map_longident_loc(lid), self.map_core_type(ty))) + .collect(), + ) + } + + fn map_row_field(&mut self, field: ¤t::RowField) -> pt0::RowField { + match field { + current::RowField::Rtag(label, attrs, b, types) => { + pt0::RowField::Rtag( + self.map_loc(label), + self.map_attributes(attrs), + *b, + types.iter().map(|t| self.map_core_type(t)).collect(), + ) + } + current::RowField::Rinherit(ty) => pt0::RowField::Rinherit(self.map_core_type(ty)), } } -} -// ========== Expressions ========== + fn map_object_field(&mut self, field: ¤t::ObjectField) -> pt0::ObjectField { + match field { + current::ObjectField::Otag(label, attrs, ty) => { + pt0::ObjectField::Otag( + self.map_loc(label), + self.map_attributes(attrs), + self.map_core_type(ty), + ) + } + current::ObjectField::Oinherit(ty) => pt0::ObjectField::Oinherit(self.map_core_type(ty)), + } + } -pub fn map_expression(expr: ¤t::Expression) -> pt0::Expression { - // Check if this is a JSX element that needs the [@JSX] attribute - let is_jsx = matches!(&expr.pexp_desc, current::ExpressionDesc::Pexp_jsx_element(_)); - let mut attrs = map_attributes(&expr.pexp_attributes); - if is_jsx { - attrs.insert(0, mk_jsx_attr(&expr.pexp_loc)); + fn map_extension(&mut self, ext: ¤t::Extension) -> pt0::Extension { + let (name, payload) = ext; + ( + self.map_loc(name), + self.map_payload(payload), + ) } - pt0::Expression { - pexp_desc: map_expression_desc(&expr.pexp_desc, &expr.pexp_loc), - pexp_loc: expr.pexp_loc.clone(), - pexp_attributes: attrs, + + // ========== Patterns ========== + + pub fn map_pattern(&mut self, pat: ¤t::Pattern) -> pt0::Pattern { + pt0::Pattern { + ppat_desc: self.map_pattern_desc(&pat.ppat_desc), + ppat_loc: self.loc(pat.ppat_loc), + ppat_attributes: self.map_attributes(&pat.ppat_attributes), + } } -} -fn map_expression_desc(desc: ¤t::ExpressionDesc, loc: &Location) -> pt0::ExpressionDesc { - match desc { - current::ExpressionDesc::Pexp_ident(lid) => { - pt0::ExpressionDesc::Ident(mkloc(lid.txt.clone(), &lid.loc)) + fn map_pattern_desc(&mut self, desc: ¤t::PatternDesc) -> pt0::PatternDesc { + match desc { + current::PatternDesc::Ppat_any => pt0::PatternDesc::Any, + current::PatternDesc::Ppat_var(s) => { + pt0::PatternDesc::Var(self.map_loc(s)) + } + current::PatternDesc::Ppat_alias(pat, s) => { + pt0::PatternDesc::Alias(Box::new(self.map_pattern(pat)), self.map_loc(s)) + } + current::PatternDesc::Ppat_constant(c) => pt0::PatternDesc::Constant(self.map_constant(c)), + current::PatternDesc::Ppat_interval(c1, c2) => { + pt0::PatternDesc::Interval(self.map_constant(c1), self.map_constant(c2)) + } + current::PatternDesc::Ppat_tuple(pats) => { + pt0::PatternDesc::Tuple(pats.iter().map(|p| self.map_pattern(p)).collect()) + } + current::PatternDesc::Ppat_construct(lid, opt) => { + pt0::PatternDesc::Construct( + self.map_longident_loc(lid), + opt.as_ref().map(|p| Box::new(self.map_pattern(p))), + ) + } + current::PatternDesc::Ppat_variant(label, opt) => { + pt0::PatternDesc::Variant(label.clone(), opt.as_ref().map(|p| Box::new(self.map_pattern(p)))) + } + current::PatternDesc::Ppat_record(fields, flag) => { + // Use RecordElement with 3 fields (lid, x, opt) for current parsetree format + pt0::PatternDesc::Record( + fields + .iter() + .map(|f| pt0::RecordElement { + lid: self.map_longident_loc(&f.lid), + x: self.map_pattern(&f.pat), + opt: f.opt, + }) + .collect(), + self.map_closed_flag(*flag), + ) + } + current::PatternDesc::Ppat_array(pats) => { + pt0::PatternDesc::Array(pats.iter().map(|p| self.map_pattern(p)).collect()) + } + current::PatternDesc::Ppat_or(p1, p2) => { + pt0::PatternDesc::Or(Box::new(self.map_pattern(p1)), Box::new(self.map_pattern(p2))) + } + current::PatternDesc::Ppat_constraint(pat, ty) => { + pt0::PatternDesc::Constraint(Box::new(self.map_pattern(pat)), Box::new(self.map_core_type(ty))) + } + current::PatternDesc::Ppat_type(lid) => { + pt0::PatternDesc::Type(self.map_longident_loc(lid)) + } + current::PatternDesc::Ppat_unpack(s) => { + pt0::PatternDesc::Unpack(self.map_loc(s)) + } + current::PatternDesc::Ppat_exception(pat) => { + pt0::PatternDesc::Exception(Box::new(self.map_pattern(pat))) + } + current::PatternDesc::Ppat_extension(ext) => pt0::PatternDesc::Extension(self.map_extension(ext)), + current::PatternDesc::Ppat_open(lid, pat) => { + pt0::PatternDesc::Open(self.map_longident_loc(lid), Box::new(self.map_pattern(pat))) + } } - current::ExpressionDesc::Pexp_constant(c) => { - pt0::ExpressionDesc::Constant(map_constant(c)) + } + + // ========== Expressions ========== + + pub fn map_expression(&mut self, expr: ¤t::Expression) -> pt0::Expression { + // Check if this is a JSX element that needs the [@JSX] attribute + let is_jsx = matches!(&expr.pexp_desc, current::ExpressionDesc::Pexp_jsx_element(_)); + let mut attrs = self.map_attributes(&expr.pexp_attributes); + if is_jsx { + attrs.insert(0, self.mk_jsx_attr(expr.pexp_loc)); } - current::ExpressionDesc::Pexp_let(flag, bindings, body) => { - pt0::ExpressionDesc::Let( - map_rec_flag(*flag), - bindings.iter().map(map_value_binding).collect(), - Box::new(map_expression(body)), - ) + pt0::Expression { + pexp_desc: self.map_expression_desc(&expr.pexp_desc, expr.pexp_loc), + pexp_loc: self.loc(expr.pexp_loc), + pexp_attributes: attrs, } - current::ExpressionDesc::Pexp_fun { - arg_label, - default, - lhs, - rhs, - arity, - is_async, - } => { - // Output current parsetree format with arity and is_async fields - // Convert Arity enum to Option - let arity_opt = match arity { - current::Arity::Full(n) => Some(*n as i32), - current::Arity::Unknown => None, - }; - pt0::ExpressionDesc::Fun { - arg_label: map_arg_label(arg_label), - default: default.as_ref().map(|e| Box::new(map_expression(e))), - lhs: Box::new(map_pattern(lhs)), - rhs: Box::new(map_expression(rhs)), - arity: arity_opt, - is_async: *is_async, + } + + fn map_expression_desc(&mut self, desc: ¤t::ExpressionDesc, loc: LocIdx) -> pt0::ExpressionDesc { + match desc { + current::ExpressionDesc::Pexp_ident(lid) => { + pt0::ExpressionDesc::Ident(self.map_longident_loc(lid)) } - } - current::ExpressionDesc::Pexp_apply { - funct, - args, - partial, - transformed_jsx, - } => { - // Convert operators for parsetree0 compatibility - let mapped_funct = match &funct.pexp_desc { - current::ExpressionDesc::Pexp_ident(lid) - if args.len() == 2 - && matches!(&args[0].0, current::ArgLabel::Nolabel) - && matches!(&args[1].0, current::ArgLabel::Nolabel) => + current::ExpressionDesc::Pexp_constant(c) => { + pt0::ExpressionDesc::Constant(self.map_constant(c)) + } + current::ExpressionDesc::Pexp_let(flag, bindings, body) => { + pt0::ExpressionDesc::Let( + self.map_rec_flag(*flag), + bindings.iter().map(|vb| self.map_value_binding(vb)).collect(), + Box::new(self.map_expression(body)), + ) + } + current::ExpressionDesc::Pexp_fun { + arg_label, + default, + lhs, + rhs, + arity, + is_async, + } => { + // Output current parsetree format with arity and is_async fields + // Convert Arity enum to Option + let arity_opt = match arity { + current::Arity::Full(n) => Some(*n as i32), + current::Arity::Unknown => None, + }; + pt0::ExpressionDesc::Fun { + arg_label: self.map_arg_label(arg_label), + default: default.as_ref().map(|e| Box::new(self.map_expression(e))), + lhs: Box::new(self.map_pattern(lhs)), + rhs: Box::new(self.map_expression(rhs)), + arity: arity_opt, + is_async: *is_async, + } + } + current::ExpressionDesc::Pexp_apply { + funct, + args, + partial, + transformed_jsx, + } => { + // Convert operators for parsetree0 compatibility + // Check if this is a binary operator application that needs conversion + let converted_funct = if args.len() == 2 + && matches!(&args[0].0, current::ArgLabel::Nolabel) + && matches!(&args[1].0, current::ArgLabel::Nolabel) { - if let crate::parser::longident::Longident::Lident(op) = &lid.txt { - let new_op = match op.as_str() { - "->" => Some("|."), - "++" => Some("^"), - "!=" => Some("<>"), - "!==" => Some("!="), - "===" => Some("=="), - "==" => Some("="), - _ => None, + if let current::ExpressionDesc::Pexp_ident(lid) = &funct.pexp_desc { + // Get the StrIdx first to avoid borrow conflicts + let op_idx = if let Longident::Lident(op) = self.get_longident(lid.txt) { + Some(*op) + } else { + None }; - if let Some(new_name) = new_op { - let new_lid = Located { - txt: crate::parser::longident::Longident::Lident(new_name.to_string()), - loc: lid.loc.clone(), - }; - current::Expression { - pexp_desc: current::ExpressionDesc::Pexp_ident(new_lid), - pexp_loc: funct.pexp_loc.clone(), - pexp_attributes: funct.pexp_attributes.clone(), + if let Some(op) = op_idx { + let op_str = self.get_str(op); + match op_str { + "->" => Some("|."), + "++" => Some("^"), + "!=" => Some("<>"), + "!==" => Some("!="), + "===" => Some("=="), + "==" => Some("="), + _ => None, } } else { - funct.as_ref().clone() + None } } else { - funct.as_ref().clone() + None } - } - _ => funct.as_ref().clone(), - }; - pt0::ExpressionDesc::Apply { - funct: Box::new(map_expression(&mapped_funct)), - args: args - .iter() - .map(|(label, e)| (map_arg_label(label), map_expression(e))) - .collect(), - partial: *partial, - transformed_jsx: *transformed_jsx, - } - } - current::ExpressionDesc::Pexp_match(e, cases) => { - pt0::ExpressionDesc::Match( - Box::new(map_expression(e)), - cases.iter().map(map_case).collect(), - ) - } - current::ExpressionDesc::Pexp_try(e, cases) => { - pt0::ExpressionDesc::Try( - Box::new(map_expression(e)), - cases.iter().map(map_case).collect(), - ) - } - current::ExpressionDesc::Pexp_tuple(exprs) => { - pt0::ExpressionDesc::Tuple(exprs.iter().map(map_expression).collect()) - } - current::ExpressionDesc::Pexp_construct(lid, opt) => { - pt0::ExpressionDesc::Construct( - mkloc(lid.txt.clone(), &lid.loc), - opt.as_ref().map(|e| Box::new(map_expression(e))), - ) - } - current::ExpressionDesc::Pexp_variant(label, opt) => { - pt0::ExpressionDesc::Variant( - label.clone(), - opt.as_ref().map(|e| Box::new(map_expression(e))), - ) - } - current::ExpressionDesc::Pexp_record(fields, spread) => { - // Use RecordElement with 3 fields (lid, x, opt) for current parsetree format - pt0::ExpressionDesc::Record( - fields - .iter() - .map(|f| pt0::RecordElement { - lid: mkloc(f.lid.txt.clone(), &f.lid.loc), - x: map_expression(&f.expr), - opt: f.opt, - }) - .collect(), - spread.as_ref().map(|e| Box::new(map_expression(e))), - ) - } - current::ExpressionDesc::Pexp_field(e, lid) => { - pt0::ExpressionDesc::Field( - Box::new(map_expression(e)), - mkloc(lid.txt.clone(), &lid.loc), - ) - } - current::ExpressionDesc::Pexp_setfield(e1, lid, e2) => { - pt0::ExpressionDesc::Setfield( - Box::new(map_expression(e1)), - mkloc(lid.txt.clone(), &lid.loc), - Box::new(map_expression(e2)), - ) - } - current::ExpressionDesc::Pexp_array(exprs) => { - pt0::ExpressionDesc::Array(exprs.iter().map(map_expression).collect()) - } - current::ExpressionDesc::Pexp_ifthenelse(e1, e2, e3) => { - pt0::ExpressionDesc::Ifthenelse( - Box::new(map_expression(e1)), - Box::new(map_expression(e2)), - e3.as_ref().map(|e| Box::new(map_expression(e))), - ) - } - current::ExpressionDesc::Pexp_sequence(e1, e2) => { - pt0::ExpressionDesc::Sequence( - Box::new(map_expression(e1)), - Box::new(map_expression(e2)), - ) - } - current::ExpressionDesc::Pexp_while(e1, e2) => { - pt0::ExpressionDesc::While(Box::new(map_expression(e1)), Box::new(map_expression(e2))) - } - current::ExpressionDesc::Pexp_for(pat, e1, e2, flag, e3) => { - pt0::ExpressionDesc::For( - Box::new(map_pattern(pat)), - Box::new(map_expression(e1)), - Box::new(map_expression(e2)), - map_direction_flag(*flag), - Box::new(map_expression(e3)), - ) - } - current::ExpressionDesc::Pexp_constraint(e, ty) => { - pt0::ExpressionDesc::Constraint( - Box::new(map_expression(e)), - Box::new(map_core_type(ty)), - ) - } - current::ExpressionDesc::Pexp_coerce(e, _, ty) => { - // parsetree0 has unit instead of Option for the middle arg - pt0::ExpressionDesc::Coerce(Box::new(map_expression(e)), (), Box::new(map_core_type(ty))) - } - current::ExpressionDesc::Pexp_send(e, label) => { - pt0::ExpressionDesc::Send(Box::new(map_expression(e)), mkloc(label.txt.clone(), &label.loc)) - } - current::ExpressionDesc::Pexp_letmodule(name, me, body) => { - pt0::ExpressionDesc::Letmodule( - mkloc(name.txt.clone(), &name.loc), - Box::new(map_module_expr(me)), - Box::new(map_expression(body)), - ) - } - current::ExpressionDesc::Pexp_letexception(ext, body) => { - pt0::ExpressionDesc::Letexception( - map_extension_constructor(ext), - Box::new(map_expression(body)), - ) - } - current::ExpressionDesc::Pexp_assert(e) => { - pt0::ExpressionDesc::Assert(Box::new(map_expression(e))) - } - current::ExpressionDesc::Pexp_newtype(name, body) => { - pt0::ExpressionDesc::Newtype(mkloc(name.txt.clone(), &name.loc), Box::new(map_expression(body))) - } - current::ExpressionDesc::Pexp_pack(me) => { - pt0::ExpressionDesc::Pack(Box::new(map_module_expr(me))) - } - current::ExpressionDesc::Pexp_open(flag, lid, body) => { - pt0::ExpressionDesc::Open( - map_override_flag(*flag), - mkloc(lid.txt.clone(), &lid.loc), - Box::new(map_expression(body)), - ) - } - current::ExpressionDesc::Pexp_extension(ext) => { - pt0::ExpressionDesc::Extension(map_extension(ext)) - } - current::ExpressionDesc::Pexp_await(e) => { - // Convert await to inner expression with [@res.await] attribute - let mut inner = map_expression(e); - inner.pexp_attributes.insert(0, mk_await_attr(loc)); - inner.pexp_desc - } - current::ExpressionDesc::Pexp_jsx_element(jsx) => { - // Convert JSX element to old-style function application with [@JSX] attribute - match jsx { - current::JsxElement::Fragment(fragment) => { - // Fragment becomes a list with JSX attribute - let list_expr = map_jsx_children_to_list(&fragment.children, loc); - // The JSX attribute will be added by the caller - list_expr.pexp_desc - } - current::JsxElement::Unary(unary) => { - // Unary element: -> Tag(~props, ~children=[], ()) - let tag_ident = jsx_tag_to_longident(&unary.tag_name.txt); - let mapped_props = map_jsx_props(&unary.props, loc); - let children_expr = mk_nil_expr(loc); - let unit_expr = mk_unit_expr(loc); - - let mut args = mapped_props; - args.push((pt0::ArgLabel::Labelled("children".to_string()), children_expr)); - args.push((pt0::ArgLabel::Nolabel, unit_expr)); - - pt0::ExpressionDesc::Apply { - funct: Box::new(pt0::Expression { - pexp_desc: pt0::ExpressionDesc::Ident(Located::new( - tag_ident, - unary.tag_name.loc.clone(), + } else { + None + }; + + let mapped_funct = if let Some(new_name) = converted_funct { + if let current::ExpressionDesc::Pexp_ident(lid) = &funct.pexp_desc { + let full_loc = self.loc(lid.loc); + let new_name_idx = self.intern(new_name); + pt0::Expression { + pexp_desc: pt0::ExpressionDesc::Ident(OldLocated::new( + Longident::Lident(new_name_idx), + full_loc, )), - pexp_loc: unary.tag_name.loc.clone(), - pexp_attributes: vec![], - }), - args, - partial: false, - transformed_jsx: false, + pexp_loc: self.loc(funct.pexp_loc), + pexp_attributes: self.map_attributes(&funct.pexp_attributes), + } + } else { + self.map_expression(funct) } + } else { + self.map_expression(funct) + }; + + let mut mapped_args = Vec::with_capacity(args.len()); + for (label, e) in args { + mapped_args.push((self.map_arg_label(label), self.map_expression(e))); } - current::JsxElement::Container(container) => { - // Container element: children -> Tag(~props, ~children=list{...}, ()) - let tag_ident = jsx_tag_to_longident(&container.tag_name_start.txt); - let mapped_props = map_jsx_props(&container.props, loc); - let children_expr = map_jsx_children_to_list(&container.children, loc); - let unit_expr = mk_unit_expr(loc); - - let mut args = mapped_props; - args.push((pt0::ArgLabel::Labelled("children".to_string()), children_expr)); - args.push((pt0::ArgLabel::Nolabel, unit_expr)); - - pt0::ExpressionDesc::Apply { - funct: Box::new(pt0::Expression { - pexp_desc: pt0::ExpressionDesc::Ident(Located::new( - tag_ident, - container.tag_name_start.loc.clone(), - )), - pexp_loc: container.tag_name_start.loc.clone(), - pexp_attributes: vec![], - }), - args, - partial: false, - transformed_jsx: false, + + pt0::ExpressionDesc::Apply { + funct: Box::new(mapped_funct), + args: mapped_args, + partial: *partial, + transformed_jsx: *transformed_jsx, + } + } + current::ExpressionDesc::Pexp_match(e, cases) => { + pt0::ExpressionDesc::Match( + Box::new(self.map_expression(e)), + cases.iter().map(|c| self.map_case(c)).collect(), + ) + } + current::ExpressionDesc::Pexp_try(e, cases) => { + pt0::ExpressionDesc::Try( + Box::new(self.map_expression(e)), + cases.iter().map(|c| self.map_case(c)).collect(), + ) + } + current::ExpressionDesc::Pexp_tuple(exprs) => { + pt0::ExpressionDesc::Tuple(exprs.iter().map(|e| self.map_expression(e)).collect()) + } + current::ExpressionDesc::Pexp_construct(lid, opt) => { + pt0::ExpressionDesc::Construct( + self.map_longident_loc(lid), + opt.as_ref().map(|e| Box::new(self.map_expression(e))), + ) + } + current::ExpressionDesc::Pexp_variant(label, opt) => { + pt0::ExpressionDesc::Variant( + label.clone(), + opt.as_ref().map(|e| Box::new(self.map_expression(e))), + ) + } + current::ExpressionDesc::Pexp_record(fields, spread) => { + // Use RecordElement with 3 fields (lid, x, opt) for current parsetree format + pt0::ExpressionDesc::Record( + fields + .iter() + .map(|f| pt0::RecordElement { + lid: self.map_longident_loc(&f.lid), + x: self.map_expression(&f.expr), + opt: f.opt, + }) + .collect(), + spread.as_ref().map(|e| Box::new(self.map_expression(e))), + ) + } + current::ExpressionDesc::Pexp_field(e, lid) => { + pt0::ExpressionDesc::Field( + Box::new(self.map_expression(e)), + self.map_longident_loc(lid), + ) + } + current::ExpressionDesc::Pexp_setfield(e1, lid, e2) => { + pt0::ExpressionDesc::Setfield( + Box::new(self.map_expression(e1)), + self.map_longident_loc(lid), + Box::new(self.map_expression(e2)), + ) + } + current::ExpressionDesc::Pexp_array(exprs) => { + pt0::ExpressionDesc::Array(exprs.iter().map(|e| self.map_expression(e)).collect()) + } + current::ExpressionDesc::Pexp_ifthenelse(e1, e2, e3) => { + pt0::ExpressionDesc::Ifthenelse( + Box::new(self.map_expression(e1)), + Box::new(self.map_expression(e2)), + e3.as_ref().map(|e| Box::new(self.map_expression(e))), + ) + } + current::ExpressionDesc::Pexp_sequence(e1, e2) => { + pt0::ExpressionDesc::Sequence( + Box::new(self.map_expression(e1)), + Box::new(self.map_expression(e2)), + ) + } + current::ExpressionDesc::Pexp_while(e1, e2) => { + pt0::ExpressionDesc::While(Box::new(self.map_expression(e1)), Box::new(self.map_expression(e2))) + } + current::ExpressionDesc::Pexp_for(pat, e1, e2, flag, e3) => { + pt0::ExpressionDesc::For( + Box::new(self.map_pattern(pat)), + Box::new(self.map_expression(e1)), + Box::new(self.map_expression(e2)), + self.map_direction_flag(*flag), + Box::new(self.map_expression(e3)), + ) + } + current::ExpressionDesc::Pexp_constraint(e, ty) => { + pt0::ExpressionDesc::Constraint( + Box::new(self.map_expression(e)), + Box::new(self.map_core_type(ty)), + ) + } + current::ExpressionDesc::Pexp_coerce(e, _, ty) => { + // parsetree0 has unit instead of Option for the middle arg + pt0::ExpressionDesc::Coerce(Box::new(self.map_expression(e)), (), Box::new(self.map_core_type(ty))) + } + current::ExpressionDesc::Pexp_send(e, label) => { + pt0::ExpressionDesc::Send(Box::new(self.map_expression(e)), self.map_loc(label)) + } + current::ExpressionDesc::Pexp_letmodule(name, me, body) => { + pt0::ExpressionDesc::Letmodule( + self.map_loc(name), + Box::new(self.map_module_expr(me)), + Box::new(self.map_expression(body)), + ) + } + current::ExpressionDesc::Pexp_letexception(ext, body) => { + pt0::ExpressionDesc::Letexception( + self.map_extension_constructor(ext), + Box::new(self.map_expression(body)), + ) + } + current::ExpressionDesc::Pexp_assert(e) => { + pt0::ExpressionDesc::Assert(Box::new(self.map_expression(e))) + } + current::ExpressionDesc::Pexp_newtype(name, body) => { + pt0::ExpressionDesc::Newtype(self.map_loc(name), Box::new(self.map_expression(body))) + } + current::ExpressionDesc::Pexp_pack(me) => { + pt0::ExpressionDesc::Pack(Box::new(self.map_module_expr(me))) + } + current::ExpressionDesc::Pexp_open(flag, lid, body) => { + pt0::ExpressionDesc::Open( + self.map_override_flag(*flag), + self.map_longident_loc(lid), + Box::new(self.map_expression(body)), + ) + } + current::ExpressionDesc::Pexp_extension(ext) => { + pt0::ExpressionDesc::Extension(self.map_extension(ext)) + } + current::ExpressionDesc::Pexp_await(e) => { + // Convert await to inner expression with [@res.await] attribute + let mut inner = self.map_expression(e); + inner.pexp_attributes.insert(0, self.mk_await_attr(loc)); + inner.pexp_desc + } + current::ExpressionDesc::Pexp_jsx_element(jsx) => { + // Convert JSX element to old-style function application with [@JSX] attribute + let full_loc = self.loc(loc); + match jsx { + current::JsxElement::Fragment(fragment) => { + // Fragment becomes a list with JSX attribute + let list_expr = self.map_jsx_children_to_list(&fragment.children, loc); + // The JSX attribute will be added by the caller + list_expr.pexp_desc + } + current::JsxElement::Unary(unary) => { + // Unary element: -> Tag(~props, ~children=[], ()) + let tag_ident = self.jsx_tag_to_longident(&unary.tag_name.txt); + let tag_loc = self.loc(unary.tag_name.loc); + let mapped_props = self.map_jsx_props(&unary.props, loc); + let children_expr = self.mk_nil_expr(loc); + let unit_expr = self.mk_unit_expr(loc); + let children_idx = self.intern("children"); + + let mut args = mapped_props; + args.push((pt0::ArgLabel::Labelled(children_idx), children_expr)); + args.push((pt0::ArgLabel::Nolabel, unit_expr)); + + pt0::ExpressionDesc::Apply { + funct: Box::new(pt0::Expression { + pexp_desc: pt0::ExpressionDesc::Ident(OldLocated::new( + tag_ident, + tag_loc.clone(), + )), + pexp_loc: tag_loc, + pexp_attributes: vec![], + }), + args, + partial: false, + transformed_jsx: false, + } + } + current::JsxElement::Container(container) => { + // Container element: children -> Tag(~props, ~children=list{...}, ()) + let tag_ident = self.jsx_tag_to_longident(&container.tag_name_start.txt); + let tag_loc = self.loc(container.tag_name_start.loc); + let mapped_props = self.map_jsx_props(&container.props, loc); + let children_expr = self.map_jsx_children_to_list(&container.children, loc); + let unit_expr = self.mk_unit_expr(loc); + let children_idx = self.intern("children"); + + let mut args = mapped_props; + args.push((pt0::ArgLabel::Labelled(children_idx), children_expr)); + args.push((pt0::ArgLabel::Nolabel, unit_expr)); + + pt0::ExpressionDesc::Apply { + funct: Box::new(pt0::Expression { + pexp_desc: pt0::ExpressionDesc::Ident(OldLocated::new( + tag_ident, + tag_loc.clone(), + )), + pexp_loc: tag_loc, + pexp_attributes: vec![], + }), + args, + partial: false, + transformed_jsx: false, + } } } } } } -} -fn map_case(case: ¤t::Case) -> pt0::Case { - pt0::Case { - pc_lhs: map_pattern(&case.pc_lhs), - pc_guard: case.pc_guard.as_ref().map(map_expression), - pc_rhs: map_expression(&case.pc_rhs), + fn map_case(&mut self, case: ¤t::Case) -> pt0::Case { + pt0::Case { + pc_lhs: self.map_pattern(&case.pc_lhs), + pc_guard: case.pc_guard.as_ref().map(|e| self.map_expression(e)), + pc_rhs: self.map_expression(&case.pc_rhs), + } } -} -fn map_value_binding(vb: ¤t::ValueBinding) -> pt0::ValueBinding { - pt0::ValueBinding { - pvb_pat: map_pattern(&vb.pvb_pat), - pvb_expr: map_expression(&vb.pvb_expr), - pvb_attributes: map_attributes(&vb.pvb_attributes), - pvb_loc: vb.pvb_loc.clone(), + fn map_value_binding(&mut self, vb: ¤t::ValueBinding) -> pt0::ValueBinding { + pt0::ValueBinding { + pvb_pat: self.map_pattern(&vb.pvb_pat), + pvb_expr: self.map_expression(&vb.pvb_expr), + pvb_attributes: self.map_attributes(&vb.pvb_attributes), + pvb_loc: self.loc(vb.pvb_loc), + } } -} -// ========== Type declarations ========== - -fn map_type_declaration(td: ¤t::TypeDeclaration) -> pt0::TypeDeclaration { - pt0::TypeDeclaration { - ptype_name: mkloc(td.ptype_name.txt.clone(), &td.ptype_name.loc), - ptype_params: td - .ptype_params - .iter() - .map(|(ty, var)| (map_core_type(ty), map_variance(*var))) - .collect(), - ptype_cstrs: td - .ptype_cstrs - .iter() - .map(|(ty1, ty2, loc)| (map_core_type(ty1), map_core_type(ty2), loc.clone())) - .collect(), - ptype_kind: map_type_kind(&td.ptype_kind), - ptype_private: map_private_flag(td.ptype_private), - ptype_manifest: td.ptype_manifest.as_ref().map(map_core_type), - ptype_attributes: map_attributes(&td.ptype_attributes), - ptype_loc: td.ptype_loc.clone(), + // ========== Type declarations ========== + + fn map_type_declaration(&mut self, td: ¤t::TypeDeclaration) -> pt0::TypeDeclaration { + pt0::TypeDeclaration { + ptype_name: self.map_loc(&td.ptype_name), + ptype_params: td + .ptype_params + .iter() + .map(|(ty, var)| (self.map_core_type(ty), self.map_variance(*var))) + .collect(), + ptype_cstrs: td + .ptype_cstrs + .iter() + .map(|(ty1, ty2, loc)| (self.map_core_type(ty1), self.map_core_type(ty2), self.loc(*loc))) + .collect(), + ptype_kind: self.map_type_kind(&td.ptype_kind), + ptype_private: self.map_private_flag(td.ptype_private), + ptype_manifest: td.ptype_manifest.as_ref().map(|t| self.map_core_type(t)), + ptype_attributes: self.map_attributes(&td.ptype_attributes), + ptype_loc: self.loc(td.ptype_loc), + } } -} -fn map_type_kind(kind: ¤t::TypeKind) -> pt0::TypeKind { - match kind { - current::TypeKind::Ptype_abstract => pt0::TypeKind::Abstract, - current::TypeKind::Ptype_variant(ctors) => { - pt0::TypeKind::Variant(ctors.iter().map(map_constructor_declaration).collect()) - } - current::TypeKind::Ptype_record(labels) => { - pt0::TypeKind::Record(labels.iter().map(map_label_declaration).collect()) + fn map_type_kind(&mut self, kind: ¤t::TypeKind) -> pt0::TypeKind { + match kind { + current::TypeKind::Ptype_abstract => pt0::TypeKind::Abstract, + current::TypeKind::Ptype_variant(ctors) => { + pt0::TypeKind::Variant(ctors.iter().map(|c| self.map_constructor_declaration(c)).collect()) + } + current::TypeKind::Ptype_record(labels) => { + pt0::TypeKind::Record(labels.iter().map(|l| self.map_label_declaration(l)).collect()) + } + current::TypeKind::Ptype_open => pt0::TypeKind::Open, } - current::TypeKind::Ptype_open => pt0::TypeKind::Open, } -} -fn map_label_declaration(ld: ¤t::LabelDeclaration) -> pt0::LabelDeclaration { - pt0::LabelDeclaration { - pld_name: mkloc(ld.pld_name.txt.clone(), &ld.pld_name.loc), - pld_mutable: map_mutable_flag(ld.pld_mutable), - pld_type: map_core_type(&ld.pld_type), - pld_loc: ld.pld_loc.clone(), - pld_attributes: map_attributes(&ld.pld_attributes), + fn map_label_declaration(&mut self, ld: ¤t::LabelDeclaration) -> pt0::LabelDeclaration { + pt0::LabelDeclaration { + pld_name: self.map_loc(&ld.pld_name), + pld_mutable: self.map_mutable_flag(ld.pld_mutable), + pld_type: self.map_core_type(&ld.pld_type), + pld_loc: self.loc(ld.pld_loc), + pld_attributes: self.map_attributes(&ld.pld_attributes), + } } -} -fn map_constructor_declaration(cd: ¤t::ConstructorDeclaration) -> pt0::ConstructorDeclaration { - pt0::ConstructorDeclaration { - pcd_name: mkloc(cd.pcd_name.txt.clone(), &cd.pcd_name.loc), - pcd_args: map_constructor_arguments(&cd.pcd_args), - pcd_res: cd.pcd_res.as_ref().map(map_core_type), - pcd_loc: cd.pcd_loc.clone(), - pcd_attributes: map_attributes(&cd.pcd_attributes), + fn map_constructor_declaration(&mut self, cd: ¤t::ConstructorDeclaration) -> pt0::ConstructorDeclaration { + pt0::ConstructorDeclaration { + pcd_name: self.map_loc(&cd.pcd_name), + pcd_args: self.map_constructor_arguments(&cd.pcd_args), + pcd_res: cd.pcd_res.as_ref().map(|t| self.map_core_type(t)), + pcd_loc: self.loc(cd.pcd_loc), + pcd_attributes: self.map_attributes(&cd.pcd_attributes), + } } -} -fn map_constructor_arguments(args: ¤t::ConstructorArguments) -> pt0::ConstructorArguments { - match args { - current::ConstructorArguments::Pcstr_tuple(types) => { - pt0::ConstructorArguments::Tuple(types.iter().map(map_core_type).collect()) - } - current::ConstructorArguments::Pcstr_record(labels) => { - pt0::ConstructorArguments::Record(labels.iter().map(map_label_declaration).collect()) + fn map_constructor_arguments(&mut self, args: ¤t::ConstructorArguments) -> pt0::ConstructorArguments { + match args { + current::ConstructorArguments::Pcstr_tuple(types) => { + pt0::ConstructorArguments::Tuple(types.iter().map(|t| self.map_core_type(t)).collect()) + } + current::ConstructorArguments::Pcstr_record(labels) => { + pt0::ConstructorArguments::Record(labels.iter().map(|l| self.map_label_declaration(l)).collect()) + } } } -} -fn map_extension_constructor(ec: ¤t::ExtensionConstructor) -> pt0::ExtensionConstructor { - pt0::ExtensionConstructor { - pext_name: mkloc(ec.pext_name.txt.clone(), &ec.pext_name.loc), - pext_kind: map_extension_constructor_kind(&ec.pext_kind), - pext_loc: ec.pext_loc.clone(), - pext_attributes: map_attributes(&ec.pext_attributes), + fn map_extension_constructor(&mut self, ec: ¤t::ExtensionConstructor) -> pt0::ExtensionConstructor { + pt0::ExtensionConstructor { + pext_name: self.map_loc(&ec.pext_name), + pext_kind: self.map_extension_constructor_kind(&ec.pext_kind), + pext_loc: self.loc(ec.pext_loc), + pext_attributes: self.map_attributes(&ec.pext_attributes), + } } -} -fn map_extension_constructor_kind(kind: ¤t::ExtensionConstructorKind) -> pt0::ExtensionConstructorKind { - match kind { - current::ExtensionConstructorKind::Pext_decl(args, res) => { - pt0::ExtensionConstructorKind::Decl( - map_constructor_arguments(args), - res.as_ref().map(map_core_type), - ) - } - current::ExtensionConstructorKind::Pext_rebind(lid) => { - pt0::ExtensionConstructorKind::Rebind(mkloc(lid.txt.clone(), &lid.loc)) + fn map_extension_constructor_kind(&mut self, kind: ¤t::ExtensionConstructorKind) -> pt0::ExtensionConstructorKind { + match kind { + current::ExtensionConstructorKind::Pext_decl(args, res) => { + pt0::ExtensionConstructorKind::Decl( + self.map_constructor_arguments(args), + res.as_ref().map(|t| self.map_core_type(t)), + ) + } + current::ExtensionConstructorKind::Pext_rebind(lid) => { + pt0::ExtensionConstructorKind::Rebind(self.map_longident_loc(lid)) + } } } -} -fn map_type_extension(te: ¤t::TypeExtension) -> pt0::TypeExtension { - pt0::TypeExtension { - ptyext_path: mkloc(te.ptyext_path.txt.clone(), &te.ptyext_path.loc), - ptyext_params: te - .ptyext_params - .iter() - .map(|(ty, var)| (map_core_type(ty), map_variance(*var))) - .collect(), - ptyext_constructors: te - .ptyext_constructors - .iter() - .map(map_extension_constructor) - .collect(), - ptyext_private: map_private_flag(te.ptyext_private), - ptyext_attributes: map_attributes(&te.ptyext_attributes), + fn map_type_extension(&mut self, te: ¤t::TypeExtension) -> pt0::TypeExtension { + pt0::TypeExtension { + ptyext_path: self.map_longident_loc(&te.ptyext_path), + ptyext_params: te + .ptyext_params + .iter() + .map(|(ty, var)| (self.map_core_type(ty), self.map_variance(*var))) + .collect(), + ptyext_constructors: te + .ptyext_constructors + .iter() + .map(|ec| self.map_extension_constructor(ec)) + .collect(), + ptyext_private: self.map_private_flag(te.ptyext_private), + ptyext_attributes: self.map_attributes(&te.ptyext_attributes), + } } -} -// ========== Module types ========== + // ========== Module types ========== -fn map_module_type(mt: ¤t::ModuleType) -> pt0::ModuleType { - pt0::ModuleType { - pmty_desc: map_module_type_desc(&mt.pmty_desc), - pmty_loc: mt.pmty_loc.clone(), - pmty_attributes: map_attributes(&mt.pmty_attributes), + fn map_module_type(&mut self, mt: ¤t::ModuleType) -> pt0::ModuleType { + pt0::ModuleType { + pmty_desc: self.map_module_type_desc(&mt.pmty_desc), + pmty_loc: self.loc(mt.pmty_loc), + pmty_attributes: self.map_attributes(&mt.pmty_attributes), + } } -} -fn map_module_type_desc(desc: ¤t::ModuleTypeDesc) -> pt0::ModuleTypeDesc { - match desc { - current::ModuleTypeDesc::Pmty_ident(lid) => { - pt0::ModuleTypeDesc::Ident(mkloc(lid.txt.clone(), &lid.loc)) - } - current::ModuleTypeDesc::Pmty_signature(items) => { - pt0::ModuleTypeDesc::Signature(items.iter().map(map_signature_item).collect()) - } - current::ModuleTypeDesc::Pmty_functor(name, mty, body) => { - pt0::ModuleTypeDesc::Functor( - mkloc(name.txt.clone(), &name.loc), - mty.as_ref().map(|m| Box::new(map_module_type(m))), - Box::new(map_module_type(body)), - ) - } - current::ModuleTypeDesc::Pmty_with(mty, constraints) => { - pt0::ModuleTypeDesc::With( - Box::new(map_module_type(mty)), - constraints.iter().map(map_with_constraint).collect(), - ) - } - current::ModuleTypeDesc::Pmty_typeof(me) => { - pt0::ModuleTypeDesc::Typeof(Box::new(map_module_expr(me))) - } - current::ModuleTypeDesc::Pmty_extension(ext) => { - pt0::ModuleTypeDesc::Extension(map_extension(ext)) - } - current::ModuleTypeDesc::Pmty_alias(lid) => { - pt0::ModuleTypeDesc::Alias(mkloc(lid.txt.clone(), &lid.loc)) + fn map_module_type_desc(&mut self, desc: ¤t::ModuleTypeDesc) -> pt0::ModuleTypeDesc { + match desc { + current::ModuleTypeDesc::Pmty_ident(lid) => { + pt0::ModuleTypeDesc::Ident(self.map_longident_loc(lid)) + } + current::ModuleTypeDesc::Pmty_signature(items) => { + pt0::ModuleTypeDesc::Signature(items.iter().map(|i| self.map_signature_item(i)).collect()) + } + current::ModuleTypeDesc::Pmty_functor(name, mty, body) => { + pt0::ModuleTypeDesc::Functor( + self.map_loc(name), + mty.as_ref().map(|m| Box::new(self.map_module_type(m))), + Box::new(self.map_module_type(body)), + ) + } + current::ModuleTypeDesc::Pmty_with(mty, constraints) => { + pt0::ModuleTypeDesc::With( + Box::new(self.map_module_type(mty)), + constraints.iter().map(|wc| self.map_with_constraint(wc)).collect(), + ) + } + current::ModuleTypeDesc::Pmty_typeof(me) => { + pt0::ModuleTypeDesc::Typeof(Box::new(self.map_module_expr(me))) + } + current::ModuleTypeDesc::Pmty_extension(ext) => { + pt0::ModuleTypeDesc::Extension(self.map_extension(ext)) + } + current::ModuleTypeDesc::Pmty_alias(lid) => { + pt0::ModuleTypeDesc::Alias(self.map_longident_loc(lid)) + } } } -} -fn map_with_constraint(wc: ¤t::WithConstraint) -> pt0::WithConstraint { - match wc { - current::WithConstraint::Pwith_type(lid, td) => { - pt0::WithConstraint::Type(mkloc(lid.txt.clone(), &lid.loc), map_type_declaration(td)) - } - current::WithConstraint::Pwith_module(lid1, lid2) => { - pt0::WithConstraint::Module( - mkloc(lid1.txt.clone(), &lid1.loc), - mkloc(lid2.txt.clone(), &lid2.loc), - ) - } - current::WithConstraint::Pwith_typesubst(lid, td) => { - pt0::WithConstraint::TypeSubst(mkloc(lid.txt.clone(), &lid.loc), map_type_declaration(td)) - } - current::WithConstraint::Pwith_modsubst(lid1, lid2) => { - pt0::WithConstraint::ModSubst( - mkloc(lid1.txt.clone(), &lid1.loc), - mkloc(lid2.txt.clone(), &lid2.loc), - ) + fn map_with_constraint(&mut self, wc: ¤t::WithConstraint) -> pt0::WithConstraint { + match wc { + current::WithConstraint::Pwith_type(lid, td) => { + pt0::WithConstraint::Type(self.map_longident_loc(lid), self.map_type_declaration(td)) + } + current::WithConstraint::Pwith_module(lid1, lid2) => { + pt0::WithConstraint::Module( + self.map_longident_loc(lid1), + self.map_longident_loc(lid2), + ) + } + current::WithConstraint::Pwith_typesubst(lid, td) => { + pt0::WithConstraint::TypeSubst(self.map_longident_loc(lid), self.map_type_declaration(td)) + } + current::WithConstraint::Pwith_modsubst(lid1, lid2) => { + pt0::WithConstraint::ModSubst( + self.map_longident_loc(lid1), + self.map_longident_loc(lid2), + ) + } } } -} -// ========== Module expressions ========== + // ========== Module expressions ========== -fn map_module_expr(me: ¤t::ModuleExpr) -> pt0::ModuleExpr { - pt0::ModuleExpr { - pmod_desc: map_module_expr_desc(&me.pmod_desc), - pmod_loc: me.pmod_loc.clone(), - pmod_attributes: map_attributes(&me.pmod_attributes), + fn map_module_expr(&mut self, me: ¤t::ModuleExpr) -> pt0::ModuleExpr { + pt0::ModuleExpr { + pmod_desc: self.map_module_expr_desc(&me.pmod_desc), + pmod_loc: self.loc(me.pmod_loc), + pmod_attributes: self.map_attributes(&me.pmod_attributes), + } } -} -fn map_module_expr_desc(desc: ¤t::ModuleExprDesc) -> pt0::ModuleExprDesc { - match desc { - current::ModuleExprDesc::Pmod_ident(lid) => { - pt0::ModuleExprDesc::Ident(mkloc(lid.txt.clone(), &lid.loc)) - } - current::ModuleExprDesc::Pmod_structure(items) => { - pt0::ModuleExprDesc::Structure(items.iter().map(map_structure_item).collect()) - } - current::ModuleExprDesc::Pmod_functor(name, mty, body) => { - pt0::ModuleExprDesc::Functor( - mkloc(name.txt.clone(), &name.loc), - mty.as_ref().map(|m| Box::new(map_module_type(m))), - Box::new(map_module_expr(body)), - ) - } - current::ModuleExprDesc::Pmod_apply(me1, me2) => { - pt0::ModuleExprDesc::Apply( - Box::new(map_module_expr(me1)), - Box::new(map_module_expr(me2)), - ) - } - current::ModuleExprDesc::Pmod_constraint(me, mty) => { - pt0::ModuleExprDesc::Constraint( - Box::new(map_module_expr(me)), - Box::new(map_module_type(mty)), - ) - } - current::ModuleExprDesc::Pmod_unpack(e) => { - pt0::ModuleExprDesc::Unpack(Box::new(map_expression(e))) - } - current::ModuleExprDesc::Pmod_extension(ext) => { - pt0::ModuleExprDesc::Extension(map_extension(ext)) + fn map_module_expr_desc(&mut self, desc: ¤t::ModuleExprDesc) -> pt0::ModuleExprDesc { + match desc { + current::ModuleExprDesc::Pmod_ident(lid) => { + pt0::ModuleExprDesc::Ident(self.map_longident_loc(lid)) + } + current::ModuleExprDesc::Pmod_structure(items) => { + pt0::ModuleExprDesc::Structure(items.iter().map(|i| self.map_structure_item(i)).collect()) + } + current::ModuleExprDesc::Pmod_functor(name, mty, body) => { + pt0::ModuleExprDesc::Functor( + self.map_loc(name), + mty.as_ref().map(|m| Box::new(self.map_module_type(m))), + Box::new(self.map_module_expr(body)), + ) + } + current::ModuleExprDesc::Pmod_apply(me1, me2) => { + pt0::ModuleExprDesc::Apply( + Box::new(self.map_module_expr(me1)), + Box::new(self.map_module_expr(me2)), + ) + } + current::ModuleExprDesc::Pmod_constraint(me, mty) => { + pt0::ModuleExprDesc::Constraint( + Box::new(self.map_module_expr(me)), + Box::new(self.map_module_type(mty)), + ) + } + current::ModuleExprDesc::Pmod_unpack(e) => { + pt0::ModuleExprDesc::Unpack(Box::new(self.map_expression(e))) + } + current::ModuleExprDesc::Pmod_extension(ext) => { + pt0::ModuleExprDesc::Extension(self.map_extension(ext)) + } } } -} -fn map_module_binding(mb: ¤t::ModuleBinding) -> pt0::ModuleBinding { - pt0::ModuleBinding { - pmb_name: mkloc(mb.pmb_name.txt.clone(), &mb.pmb_name.loc), - pmb_expr: map_module_expr(&mb.pmb_expr), - pmb_attributes: map_attributes(&mb.pmb_attributes), - pmb_loc: mb.pmb_loc.clone(), + fn map_module_binding(&mut self, mb: ¤t::ModuleBinding) -> pt0::ModuleBinding { + pt0::ModuleBinding { + pmb_name: self.map_loc(&mb.pmb_name), + pmb_expr: self.map_module_expr(&mb.pmb_expr), + pmb_attributes: self.map_attributes(&mb.pmb_attributes), + pmb_loc: self.loc(mb.pmb_loc), + } } -} -fn map_module_declaration(md: ¤t::ModuleDeclaration) -> pt0::ModuleDeclaration { - pt0::ModuleDeclaration { - pmd_name: mkloc(md.pmd_name.txt.clone(), &md.pmd_name.loc), - pmd_type: map_module_type(&md.pmd_type), - pmd_attributes: map_attributes(&md.pmd_attributes), - pmd_loc: md.pmd_loc.clone(), + fn map_module_declaration(&mut self, md: ¤t::ModuleDeclaration) -> pt0::ModuleDeclaration { + pt0::ModuleDeclaration { + pmd_name: self.map_loc(&md.pmd_name), + pmd_type: self.map_module_type(&md.pmd_type), + pmd_attributes: self.map_attributes(&md.pmd_attributes), + pmd_loc: self.loc(md.pmd_loc), + } } -} -fn map_module_type_declaration(mtd: ¤t::ModuleTypeDeclaration) -> pt0::ModuleTypeDeclaration { - pt0::ModuleTypeDeclaration { - pmtd_name: mkloc(mtd.pmtd_name.txt.clone(), &mtd.pmtd_name.loc), - pmtd_type: mtd.pmtd_type.as_ref().map(map_module_type), - pmtd_attributes: map_attributes(&mtd.pmtd_attributes), - pmtd_loc: mtd.pmtd_loc.clone(), + fn map_module_type_declaration(&mut self, mtd: ¤t::ModuleTypeDeclaration) -> pt0::ModuleTypeDeclaration { + pt0::ModuleTypeDeclaration { + pmtd_name: self.map_loc(&mtd.pmtd_name), + pmtd_type: mtd.pmtd_type.as_ref().map(|mt| self.map_module_type(mt)), + pmtd_attributes: self.map_attributes(&mtd.pmtd_attributes), + pmtd_loc: self.loc(mtd.pmtd_loc), + } } -} -fn map_open_description(od: ¤t::OpenDescription) -> pt0::OpenDescription { - pt0::OpenDescription { - popen_lid: mkloc(od.popen_lid.txt.clone(), &od.popen_lid.loc), - popen_override: map_override_flag(od.popen_override), - popen_loc: od.popen_loc.clone(), - popen_attributes: map_attributes(&od.popen_attributes), + fn map_open_description(&mut self, od: ¤t::OpenDescription) -> pt0::OpenDescription { + pt0::OpenDescription { + popen_lid: self.map_longident_loc(&od.popen_lid), + popen_override: self.map_override_flag(od.popen_override), + popen_loc: self.loc(od.popen_loc), + popen_attributes: self.map_attributes(&od.popen_attributes), + } } -} -fn map_include_declaration(id: ¤t::IncludeDeclaration) -> pt0::IncludeDeclaration { - pt0::IncludeInfos { - pincl_mod: map_module_expr(&id.pincl_mod), - pincl_loc: id.pincl_loc.clone(), - pincl_attributes: map_attributes(&id.pincl_attributes), + fn map_include_declaration(&mut self, id: ¤t::IncludeDeclaration) -> pt0::IncludeDeclaration { + pt0::IncludeInfos { + pincl_mod: self.map_module_expr(&id.pincl_mod), + pincl_loc: self.loc(id.pincl_loc), + pincl_attributes: self.map_attributes(&id.pincl_attributes), + } } -} -fn map_include_description(id: ¤t::IncludeDescription) -> pt0::IncludeDescription { - pt0::IncludeInfos { - pincl_mod: map_module_type(&id.pincl_mod), - pincl_loc: id.pincl_loc.clone(), - pincl_attributes: map_attributes(&id.pincl_attributes), + fn map_include_description(&mut self, id: ¤t::IncludeDescription) -> pt0::IncludeDescription { + pt0::IncludeInfos { + pincl_mod: self.map_module_type(&id.pincl_mod), + pincl_loc: self.loc(id.pincl_loc), + pincl_attributes: self.map_attributes(&id.pincl_attributes), + } } -} -fn map_value_description(vd: ¤t::ValueDescription) -> pt0::ValueDescription { - pt0::ValueDescription { - pval_name: mkloc(vd.pval_name.txt.clone(), &vd.pval_name.loc), - pval_type: map_core_type(&vd.pval_type), - pval_prim: vd.pval_prim.clone(), - pval_attributes: map_attributes(&vd.pval_attributes), - pval_loc: vd.pval_loc.clone(), + fn map_value_description(&mut self, vd: ¤t::ValueDescription) -> pt0::ValueDescription { + pt0::ValueDescription { + pval_name: self.map_loc(&vd.pval_name), + pval_type: self.map_core_type(&vd.pval_type), + pval_prim: vd.pval_prim.clone(), + pval_attributes: self.map_attributes(&vd.pval_attributes), + pval_loc: self.loc(vd.pval_loc), + } } -} -// ========== Structure items ========== + // ========== Structure items ========== -fn map_structure_item(item: ¤t::StructureItem) -> pt0::StructureItem { - pt0::StructureItem { - pstr_desc: map_structure_item_desc(&item.pstr_desc), - pstr_loc: item.pstr_loc.clone(), + fn map_structure_item(&mut self, item: ¤t::StructureItem) -> pt0::StructureItem { + pt0::StructureItem { + pstr_desc: self.map_structure_item_desc(&item.pstr_desc), + pstr_loc: self.loc(item.pstr_loc), + } } -} -fn map_structure_item_desc(desc: ¤t::StructureItemDesc) -> pt0::StructureItemDesc { - match desc { - current::StructureItemDesc::Pstr_eval(e, attrs) => { - pt0::StructureItemDesc::Eval(map_expression(e), map_attributes(attrs)) - } - current::StructureItemDesc::Pstr_value(flag, bindings) => { - pt0::StructureItemDesc::Value( - map_rec_flag(*flag), - bindings.iter().map(map_value_binding).collect(), - ) - } - current::StructureItemDesc::Pstr_primitive(vd) => { - pt0::StructureItemDesc::Primitive(map_value_description(vd)) - } - current::StructureItemDesc::Pstr_type(flag, decls) => { - pt0::StructureItemDesc::Type( - map_rec_flag(*flag), - decls.iter().map(map_type_declaration).collect(), - ) - } - current::StructureItemDesc::Pstr_typext(te) => { - pt0::StructureItemDesc::Typext(map_type_extension(te)) - } - current::StructureItemDesc::Pstr_exception(ec) => { - pt0::StructureItemDesc::Exception(map_extension_constructor(ec)) - } - current::StructureItemDesc::Pstr_module(mb) => { - pt0::StructureItemDesc::Module(map_module_binding(mb)) - } - current::StructureItemDesc::Pstr_recmodule(mbs) => { - pt0::StructureItemDesc::Recmodule(mbs.iter().map(map_module_binding).collect()) - } - current::StructureItemDesc::Pstr_modtype(mtd) => { - pt0::StructureItemDesc::Modtype(map_module_type_declaration(mtd)) - } - current::StructureItemDesc::Pstr_open(od) => { - pt0::StructureItemDesc::Open(map_open_description(od)) - } - current::StructureItemDesc::Pstr_include(ii) => { - pt0::StructureItemDesc::Include(map_include_declaration(ii)) - } - current::StructureItemDesc::Pstr_attribute(attr) => { - pt0::StructureItemDesc::Attribute(map_attribute(attr)) - } - current::StructureItemDesc::Pstr_extension(ext, attrs) => { - pt0::StructureItemDesc::Extension(map_extension(ext), map_attributes(attrs)) + fn map_structure_item_desc(&mut self, desc: ¤t::StructureItemDesc) -> pt0::StructureItemDesc { + match desc { + current::StructureItemDesc::Pstr_eval(e, attrs) => { + pt0::StructureItemDesc::Eval(self.map_expression(e), self.map_attributes(attrs)) + } + current::StructureItemDesc::Pstr_value(flag, bindings) => { + pt0::StructureItemDesc::Value( + self.map_rec_flag(*flag), + bindings.iter().map(|vb| self.map_value_binding(vb)).collect(), + ) + } + current::StructureItemDesc::Pstr_primitive(vd) => { + pt0::StructureItemDesc::Primitive(self.map_value_description(vd)) + } + current::StructureItemDesc::Pstr_type(flag, decls) => { + pt0::StructureItemDesc::Type( + self.map_rec_flag(*flag), + decls.iter().map(|td| self.map_type_declaration(td)).collect(), + ) + } + current::StructureItemDesc::Pstr_typext(te) => { + pt0::StructureItemDesc::Typext(self.map_type_extension(te)) + } + current::StructureItemDesc::Pstr_exception(ec) => { + pt0::StructureItemDesc::Exception(self.map_extension_constructor(ec)) + } + current::StructureItemDesc::Pstr_module(mb) => { + pt0::StructureItemDesc::Module(self.map_module_binding(mb)) + } + current::StructureItemDesc::Pstr_recmodule(mbs) => { + pt0::StructureItemDesc::Recmodule(mbs.iter().map(|mb| self.map_module_binding(mb)).collect()) + } + current::StructureItemDesc::Pstr_modtype(mtd) => { + pt0::StructureItemDesc::Modtype(self.map_module_type_declaration(mtd)) + } + current::StructureItemDesc::Pstr_open(od) => { + pt0::StructureItemDesc::Open(self.map_open_description(od)) + } + current::StructureItemDesc::Pstr_include(ii) => { + pt0::StructureItemDesc::Include(self.map_include_declaration(ii)) + } + current::StructureItemDesc::Pstr_attribute(attr) => { + pt0::StructureItemDesc::Attribute(self.map_attribute(attr)) + } + current::StructureItemDesc::Pstr_extension(ext, attrs) => { + pt0::StructureItemDesc::Extension(self.map_extension(ext), self.map_attributes(attrs)) + } } } -} -// ========== Signature items ========== + // ========== Signature items ========== -fn map_signature_item(item: ¤t::SignatureItem) -> pt0::SignatureItem { - pt0::SignatureItem { - psig_desc: map_signature_item_desc(&item.psig_desc), - psig_loc: item.psig_loc.clone(), + fn map_signature_item(&mut self, item: ¤t::SignatureItem) -> pt0::SignatureItem { + pt0::SignatureItem { + psig_desc: self.map_signature_item_desc(&item.psig_desc), + psig_loc: self.loc(item.psig_loc), + } } -} -fn map_signature_item_desc(desc: ¤t::SignatureItemDesc) -> pt0::SignatureItemDesc { - match desc { - current::SignatureItemDesc::Psig_value(vd) => { - pt0::SignatureItemDesc::Value(map_value_description(vd)) - } - current::SignatureItemDesc::Psig_type(flag, decls) => { - pt0::SignatureItemDesc::Type( - map_rec_flag(*flag), - decls.iter().map(map_type_declaration).collect(), - ) - } - current::SignatureItemDesc::Psig_typext(te) => { - pt0::SignatureItemDesc::Typext(map_type_extension(te)) - } - current::SignatureItemDesc::Psig_exception(ec) => { - pt0::SignatureItemDesc::Exception(map_extension_constructor(ec)) - } - current::SignatureItemDesc::Psig_module(md) => { - pt0::SignatureItemDesc::Module(map_module_declaration(md)) - } - current::SignatureItemDesc::Psig_recmodule(mds) => { - pt0::SignatureItemDesc::Recmodule(mds.iter().map(map_module_declaration).collect()) - } - current::SignatureItemDesc::Psig_modtype(mtd) => { - pt0::SignatureItemDesc::Modtype(map_module_type_declaration(mtd)) - } - current::SignatureItemDesc::Psig_open(od) => { - pt0::SignatureItemDesc::Open(map_open_description(od)) - } - current::SignatureItemDesc::Psig_include(ii) => { - pt0::SignatureItemDesc::Include(map_include_description(ii)) - } - current::SignatureItemDesc::Psig_attribute(attr) => { - pt0::SignatureItemDesc::Attribute(map_attribute(attr)) - } - current::SignatureItemDesc::Psig_extension(ext, attrs) => { - pt0::SignatureItemDesc::Extension(map_extension(ext), map_attributes(attrs)) + fn map_signature_item_desc(&mut self, desc: ¤t::SignatureItemDesc) -> pt0::SignatureItemDesc { + match desc { + current::SignatureItemDesc::Psig_value(vd) => { + pt0::SignatureItemDesc::Value(self.map_value_description(vd)) + } + current::SignatureItemDesc::Psig_type(flag, decls) => { + pt0::SignatureItemDesc::Type( + self.map_rec_flag(*flag), + decls.iter().map(|td| self.map_type_declaration(td)).collect(), + ) + } + current::SignatureItemDesc::Psig_typext(te) => { + pt0::SignatureItemDesc::Typext(self.map_type_extension(te)) + } + current::SignatureItemDesc::Psig_exception(ec) => { + pt0::SignatureItemDesc::Exception(self.map_extension_constructor(ec)) + } + current::SignatureItemDesc::Psig_module(md) => { + pt0::SignatureItemDesc::Module(self.map_module_declaration(md)) + } + current::SignatureItemDesc::Psig_recmodule(mds) => { + pt0::SignatureItemDesc::Recmodule(mds.iter().map(|md| self.map_module_declaration(md)).collect()) + } + current::SignatureItemDesc::Psig_modtype(mtd) => { + pt0::SignatureItemDesc::Modtype(self.map_module_type_declaration(mtd)) + } + current::SignatureItemDesc::Psig_open(od) => { + pt0::SignatureItemDesc::Open(self.map_open_description(od)) + } + current::SignatureItemDesc::Psig_include(ii) => { + pt0::SignatureItemDesc::Include(self.map_include_description(ii)) + } + current::SignatureItemDesc::Psig_attribute(attr) => { + pt0::SignatureItemDesc::Attribute(self.map_attribute(attr)) + } + current::SignatureItemDesc::Psig_extension(ext, attrs) => { + pt0::SignatureItemDesc::Extension(self.map_extension(ext), self.map_attributes(attrs)) + } } } } @@ -1264,33 +1381,47 @@ mod tests { #[test] fn test_map_rec_flag() { - assert!(matches!(map_rec_flag(current::RecFlag::Nonrecursive), pt0::RecFlag::Nonrecursive)); - assert!(matches!(map_rec_flag(current::RecFlag::Recursive), pt0::RecFlag::Recursive)); + let arena = ParseArena::new(); + let mapper = Mapper::new(&arena); + assert!(matches!(mapper.map_rec_flag(current::RecFlag::Nonrecursive), pt0::RecFlag::Nonrecursive)); + assert!(matches!(mapper.map_rec_flag(current::RecFlag::Recursive), pt0::RecFlag::Recursive)); } #[test] fn test_map_arg_label() { - use crate::location::Located; + let arena = ParseArena::new(); + let mut mapper = Mapper::new(&arena); - assert!(matches!(map_arg_label(¤t::ArgLabel::Nolabel), pt0::ArgLabel::Nolabel)); + assert!(matches!(mapper.map_arg_label(¤t::ArgLabel::Nolabel), pt0::ArgLabel::Nolabel)); - let label = map_arg_label(¤t::ArgLabel::Labelled(Located::mknoloc("x".to_string()))); - assert!(matches!(label, pt0::ArgLabel::Labelled(s) if s == "x")); + let label = mapper.map_arg_label(¤t::ArgLabel::Labelled(Located::mknoloc("x".to_string()))); + if let pt0::ArgLabel::Labelled(idx) = label { + assert_eq!(arena.get_string(idx), "x"); + } else { + panic!("Expected Labelled"); + } - let opt = map_arg_label(¤t::ArgLabel::Optional(Located::mknoloc("y".to_string()))); - assert!(matches!(opt, pt0::ArgLabel::Optional(s) if s == "y")); + let opt = mapper.map_arg_label(¤t::ArgLabel::Optional(Located::mknoloc("y".to_string()))); + if let pt0::ArgLabel::Optional(idx) = opt { + assert_eq!(arena.get_string(idx), "y"); + } else { + panic!("Expected Optional"); + } } #[test] fn test_map_constant() { - let c1 = map_constant(¤t::Constant::Integer("42".to_string(), None)); + let arena = ParseArena::new(); + let mapper = Mapper::new(&arena); + + let c1 = mapper.map_constant(¤t::Constant::Integer("42".to_string(), None)); assert!(matches!(c1, pt0::Constant::Integer(s, None) if s == "42")); - let c2 = map_constant(¤t::Constant::Char(65)); + let c2 = mapper.map_constant(¤t::Constant::Char(65)); assert!(matches!(c2, pt0::Constant::Char(65))); // Note: None delimiter is mapped to Some("js") for OCaml parsetree0 parity - let c3 = map_constant(¤t::Constant::String("hello".to_string(), None)); + let c3 = mapper.map_constant(¤t::Constant::String("hello".to_string(), None)); assert!(matches!(c3, pt0::Constant::String(s, Some(d)) if s == "hello" && d == "js")); } } diff --git a/compiler-rust/src/binary_ast/marshal.rs b/compiler-rust/src/binary_ast/marshal.rs index 01f90d31e59..39e450b19fb 100644 --- a/compiler-rust/src/binary_ast/marshal.rs +++ b/compiler-rust/src/binary_ast/marshal.rs @@ -14,8 +14,8 @@ //! //! OCaml's Marshal format uses pointer-based sharing - when two positions //! are the SAME object in memory, they get a shared reference (CODE_SHARED8/16/32). -//! We mimic this using PositionId: positions with the same ID are considered -//! "the same object" and get shared. +//! We mimic this using arena indices (PosIdx/LocIdx): positions with the same +//! index are considered "the same object" and get shared. //! //! This is critical for byte-for-byte parity with OCaml's parser output. //! @@ -26,7 +26,8 @@ use std::collections::HashMap; -use crate::location::{LocationId, PositionId}; +use crate::parse_arena::{LidentIdx, LocIdx, ParseArena, PosIdx, StrIdx}; +use crate::parser::longident::Longident; /// Magic number for small Marshal format const MAGIC_NUMBER_SMALL: u32 = 0x8495A6BE; @@ -70,10 +71,6 @@ const CODE_STRING64: u8 = 0x15; /// let bytes = writer.finish(); /// ``` -/// Key for Location-based sharing (start_id, end_id, ghost) -/// Uses PositionId for identity-based sharing like OCaml -pub type LocationKey = (PositionId, PositionId, bool); - #[derive(Debug)] pub struct MarshalWriter { /// The output buffer containing encoded data @@ -82,28 +79,30 @@ pub struct MarshalWriter { /// Maps pointer identity to object counter at time of serialization (for sharing) obj_table: HashMap, - /// Maps string content to object counter (for content-based string sharing) - string_table: HashMap, + /// Maps StrIdx to object counter (for arena-based string sharing) + /// Same StrIdx = same object, will be shared in output + str_idx_table: HashMap, - /// Maps Position ID to object counter (for identity-based Position sharing) - /// Uses PositionId instead of content to mimic OCaml's pointer-based sharing - position_table: HashMap, + /// Maps PosIdx to object counter (for arena-based Position sharing) + /// Same index = same object, will be shared in output + position_idx_table: HashMap, - /// Maps Position content to object counter (for content-based Position sharing) - /// Key is (line, bol, cnum) - filename is always shared separately - position_content_table: HashMap<(i32, i32, i32), u32>, + /// Maps LocIdx to object counter (for arena-based Location sharing) + /// Same index = same object, will be shared in output + location_idx_table: HashMap, - /// Maps Location content to object counter (for content-based Location sharing) - /// Key is (start_line, start_bol, start_cnum, end_line, end_bol, end_cnum, ghost) - location_content_table: HashMap<(i32, i32, i32, i32, i32, i32, bool), u32>, + /// Maps LidentIdx to object counter (for arena-based Longident sharing) + /// Same index = same object, will be shared in output + lident_idx_table: HashMap, - /// Maps Location identity to object counter (for identity-based Location sharing) - /// Uses PositionIds of start/end positions to determine identity - location_table: HashMap, + /// Maps Option values to object counter (for content-based sharing) + /// This enables sharing of common delimiter values like Some("js") + option_string_table: HashMap, u32>, - /// Maps LocationId to object counter (for identity-based Location sharing) - /// Uses LocationId to determine when locations should be shared (like OCaml's pointer sharing) - pub location_id_table: HashMap, + /// Optional reference to ParseArena for LocIdx marshalling. + /// Set via `set_arena()` before marshalling AST with LocIdx fields. + /// Uses raw pointer to avoid lifetime constraints. + arena: Option<*const ParseArena>, /// Current object counter (incremented each time we record a sharable object) obj_counter: u32, @@ -127,12 +126,12 @@ impl MarshalWriter { Self { buffer: Vec::with_capacity(4096), obj_table: HashMap::new(), - string_table: HashMap::new(), - position_table: HashMap::new(), - position_content_table: HashMap::new(), - location_content_table: HashMap::new(), - location_table: HashMap::new(), - location_id_table: HashMap::new(), + str_idx_table: HashMap::new(), + position_idx_table: HashMap::new(), + location_idx_table: HashMap::new(), + lident_idx_table: HashMap::new(), + option_string_table: HashMap::new(), + arena: None, obj_counter: 0, size_32: 0, size_64: 0, @@ -144,18 +143,39 @@ impl MarshalWriter { Self { buffer: Vec::with_capacity(capacity), obj_table: HashMap::new(), - string_table: HashMap::new(), - position_table: HashMap::new(), - position_content_table: HashMap::new(), - location_content_table: HashMap::new(), - location_table: HashMap::new(), - location_id_table: HashMap::new(), + str_idx_table: HashMap::new(), + position_idx_table: HashMap::new(), + location_idx_table: HashMap::new(), + lident_idx_table: HashMap::new(), + option_string_table: HashMap::new(), + arena: None, obj_counter: 0, size_32: 0, size_64: 0, } } + /// Set the ParseArena to use for LocIdx marshalling. + /// Must be called before marshalling AST with LocIdx fields. + /// + /// # Safety + /// The arena must remain valid for the duration of marshalling. + pub fn set_arena(&mut self, arena: &ParseArena) { + self.arena = Some(arena as *const ParseArena); + } + + /// Get the arena reference, panics if not set. + pub fn get_arena(&self) -> &ParseArena { + // SAFETY: We trust that set_arena was called with a valid arena + // and that the arena remains valid during marshalling. + unsafe { + self.arena + .expect("MarshalWriter::set_arena must be called before marshalling LocIdx") + .as_ref() + .unwrap() + } + } + /// Get the current object counter value pub fn obj_counter(&self) -> u32 { self.obj_counter @@ -165,9 +185,11 @@ impl MarshalWriter { pub fn reset(&mut self) { self.buffer.clear(); self.obj_table.clear(); - self.string_table.clear(); - self.position_table.clear(); - self.location_table.clear(); + self.str_idx_table.clear(); + self.position_idx_table.clear(); + self.location_idx_table.clear(); + self.lident_idx_table.clear(); + self.option_string_table.clear(); self.obj_counter = 0; self.size_32 = 0; self.size_64 = 0; @@ -322,209 +344,153 @@ impl MarshalWriter { self.write_string(s.as_bytes()); } - /// Write a string with content-based sharing + /// Write a string by StrIdx with arena-based sharing. /// - /// If this string content has been written before, writes a shared reference. - /// Otherwise writes the string and records it for future sharing. + /// If a string with the same StrIdx has been written before, writes a shared + /// reference. Otherwise looks up the string in the arena and writes it. /// - /// This is useful for strings that appear multiple times in the AST, - /// such as file names in locations. - pub fn write_string_shared(&mut self, s: &str) { - // Check if we've seen this string content before - if let Some(&obj_idx) = self.string_table.get(s) { - // Write a shared reference + /// Same StrIdx = same object, will be shared in output. + /// This matches OCaml's pointer-based sharing for interned strings. + pub fn write_str_idx(&mut self, idx: StrIdx) { + // Check if this string index was already written + if let Some(&obj_idx) = self.str_idx_table.get(&idx) { let d = self.obj_counter - obj_idx; self.write_shared_ref(d); - } else { - // Record the object index BEFORE incrementing (OCaml assigns before increment) - let obj_idx = self.obj_counter; + return; + } + + // Record the object index BEFORE writing + let obj_idx = self.obj_counter; - // Write the string (this increments obj_counter after assigning index) - self.write_string(s.as_bytes()); + // Look up the string in the arena and write it + let s = self.get_arena().get_string(idx).to_string(); + self.write_string(s.as_bytes()); - // Record for future sharing - self.string_table.insert(s.to_string(), obj_idx); - } + // Record for future sharing + self.str_idx_table.insert(idx, obj_idx); } - /// Write a string for an identifier - NO sharing. - /// - /// In OCaml, each identifier token creates a fresh string allocation on the heap. - /// Multiple occurrences of the same identifier (like "x" appearing twice) are - /// DIFFERENT objects with different pointers, so they are NOT shared during - /// Marshal serialization. - /// - /// Only filename strings (which are literal constants in the parser) and certain - /// constant token strings get shared in OCaml. - pub fn write_identifier_string(&mut self, s: &str) { - // Identifiers are NOT shared - each occurrence is a fresh string - self.write_str(s); - } + // ========== Arena-based position/location methods ========== - /// Write a Position with content-based sharing - /// - /// Positions with the same content (line, bol, cnum) are shared. - /// This approximates OCaml's pointer-based sharing behavior. + /// Write a Position by arena index with sharing. /// - /// NOTE: The PositionId is currently NOT used for sharing because Rust's - /// clone semantics differ from OCaml's pointer semantics. In Rust, cloning - /// preserves the ID, but every call site that uses a position creates a clone. - /// In OCaml, assignment copies a pointer, so only explicit pointer reuse - /// creates sharing. + /// If a Position with the same PosIdx has been written before, writes a shared + /// reference. Otherwise looks up the position in the arena and writes it. /// - /// Returns true if the position was written (not shared), false if a shared ref was written. - pub fn write_position_shared( - &mut self, - id: PositionId, - file_name: &str, - line: i32, - bol: i32, - cnum: i32, - ) -> bool { - // Use identity-based sharing: positions with the same PositionId are shared. - // This mimics OCaml's pointer-based sharing. - // Skip sharing for default ID (0) which is used for dummy/uninitialized positions. - if id.raw() != 0 { - if let Some(&obj_idx) = self.position_table.get(&id) { - // Write a shared reference - let d = self.obj_counter - obj_idx; - self.write_shared_ref(d); - return false; - } + /// Same index = same object, will be shared in output. + pub fn write_pos_idx(&mut self, idx: PosIdx) -> bool { + // Check if this position index was already written + if let Some(&obj_idx) = self.position_idx_table.get(&idx) { + let d = self.obj_counter - obj_idx; + self.write_shared_ref(d); + return false; } + // Look up the position in the arena and copy it to end the borrow + let pos = *self.get_arena().get_position(idx); + // Record the object index BEFORE writing let obj_idx = self.obj_counter; // Write the Position block self.write_block_header(0, 4); - self.write_string_shared(file_name); - self.write_int(line as i64); - self.write_int(bol as i64); - self.write_int(cnum as i64); - - // Record for future identity-based sharing (only for non-default IDs) - if id.raw() != 0 { - self.position_table.insert(id, obj_idx); - } + // Use write_str_idx for file name to enable sharing + self.write_str_idx(pos.file_name); + self.write_int(pos.line as i64); + self.write_int(pos.bol as i64); + self.write_int(pos.cnum as i64); + + // Record for future sharing + self.position_idx_table.insert(idx, obj_idx); true } - /// Write a Location with identity-based sharing + /// Write a Location by arena index with sharing. /// - /// If a Location with the same start/end PositionIds has been written before, - /// writes a shared reference. Otherwise writes the full Location block. + /// If a Location with the same LocIdx has been written before, writes a shared + /// reference. Otherwise looks up the location in the arena and writes it as + /// a new block. /// - /// This mimics OCaml's pointer-based sharing - locations are considered - /// "the same object" if their start and end positions have the same identities. - /// - /// Returns true if the location was written (not shared), false if a shared ref was written. - #[allow(clippy::too_many_arguments)] - pub fn write_location_shared( - &mut self, - start_id: PositionId, - start_file: &str, - start_line: i32, - start_bol: i32, - start_cnum: i32, - end_id: PositionId, - end_file: &str, - end_line: i32, - end_bol: i32, - end_cnum: i32, - ghost: bool, - ) -> bool { - let loc_key: LocationKey = (start_id, end_id, ghost); - - if let Some(&obj_idx) = self.location_table.get(&loc_key) { - // Write a shared reference + /// This matches OCaml's behavior where: + /// - Same pointer = same object, will be shared in output + /// - The positions within are also shared via PosIdx + pub fn write_loc_idx(&mut self, idx: LocIdx) { + // Check if this location index was already written + if let Some(&obj_idx) = self.location_idx_table.get(&idx) { let d = self.obj_counter - obj_idx; self.write_shared_ref(d); - false - } else { - // Record the object index BEFORE writing (OCaml assigns before increment) - let obj_idx = self.obj_counter; + return; + } - // Write the Location block (this increments obj_counter after writing) - self.write_block_header(0, 3); - self.write_position_shared(start_id, start_file, start_line, start_bol, start_cnum); - self.write_position_shared(end_id, end_file, end_line, end_bol, end_cnum); - self.write_int(if ghost { 1 } else { 0 }); + // Look up the location in the arena and clone it to end the borrow + let loc = self.get_arena().get_location(idx).clone(); - // Record for future sharing - self.location_table.insert(loc_key, obj_idx); - true - } - } + // Record the object index BEFORE writing + let obj_idx = self.obj_counter; - /// Check if a Location with this LocationId has been written before. - /// Returns the object index if found, None otherwise. - pub fn get_location_by_id(&self, id: LocationId) -> Option { - self.location_id_table.get(&id).copied() - } + // Write the Location block + self.write_block_header(0, 3); + // Write start and end positions (with sharing by their indices) + self.write_pos_idx(loc.loc_start); + self.write_pos_idx(loc.loc_end); + self.write_int(if loc.loc_ghost { 1 } else { 0 }); - /// Record a LocationId with its object index for future sharing. - pub fn record_location_id(&mut self, id: LocationId, obj_idx: u32) { - self.location_id_table.insert(id, obj_idx); + // Record for future sharing + self.location_idx_table.insert(idx, obj_idx); } - /// Write a Location with content-based sharing + /// Write a Longident by arena index with sharing. /// - /// If a Location with the same content (start/end positions, ghost) has been written before, - /// writes a shared reference. Otherwise writes the full Location block with its Positions. + /// If a Longident with the same LidentIdx has been written before, writes a shared + /// reference. Otherwise looks up the longident in the arena and writes it. /// - /// This approximates OCaml's pointer-based sharing - locations with identical content - /// are likely to be the same object in OCaml's parser. - /// - /// Returns true if the location was written (not shared), false if a shared ref was written. - #[allow(clippy::too_many_arguments)] - pub fn write_location_content_shared( - &mut self, - _start_id: PositionId, - start_file: &str, - start_line: i32, - start_bol: i32, - start_cnum: i32, - _end_id: PositionId, - end_file: &str, - end_line: i32, - end_bol: i32, - end_cnum: i32, - ghost: bool, - ) -> bool { - // Content-based key for the entire location - let content_key = ( - start_line, start_bol, start_cnum, - end_line, end_bol, end_cnum, - ghost, - ); - - if let Some(&obj_idx) = self.location_content_table.get(&content_key) { - // Write a shared reference to the previously written Location + /// Same index = same object, will be shared in output. + pub fn write_lident_idx(&mut self, idx: LidentIdx) -> bool { + // Check if this longident index was already written + if let Some(&obj_idx) = self.lident_idx_table.get(&idx) { let d = self.obj_counter - obj_idx; self.write_shared_ref(d); return false; } - // Record the object index BEFORE writing the Location block + // Look up the longident in the arena and clone it to end the borrow + let lid = self.get_arena().get_longident(idx).clone(); + + // Record the object index BEFORE writing let obj_idx = self.obj_counter; - // Write the Location block - self.write_block_header(0, 3); - // Write start position (with content-based sharing) - self.write_position_shared(_start_id, start_file, start_line, start_bol, start_cnum); - // Write end position (with content-based sharing) - self.write_position_shared(_end_id, end_file, end_line, end_bol, end_cnum); - // Write ghost flag - self.write_int(if ghost { 1 } else { 0 }); + // Write the Longident + self.write_longident(&lid); - // Record for future content-based sharing - self.location_content_table.insert(content_key, obj_idx); + // Record for future sharing + self.lident_idx_table.insert(idx, obj_idx); true } + /// Write a Longident value directly (internal helper). + /// This writes the structure without any index-based sharing. + /// Uses StrIdx-based sharing for the string components. + fn write_longident(&mut self, lid: &Longident) { + match lid { + Longident::Lident(s) => { + self.write_block_header(0, 1); + self.write_str_idx(*s); + } + Longident::Ldot(prefix, name) => { + self.write_block_header(1, 2); + self.write_longident(prefix); + self.write_str_idx(*name); + } + Longident::Lapply(func, arg) => { + self.write_block_header(2, 2); + self.write_longident(func); + self.write_longident(arg); + } + } + } + /// Write a block header in Marshal format /// /// Blocks represent OCaml heap objects: records, tuples, and variant constructors @@ -708,6 +674,41 @@ impl MarshalWriter { pub fn payload_len(&self) -> usize { self.buffer.len() } + + /// Write an Option with content-based sharing. + /// + /// This enables sharing of common delimiter values like Some("js") that appear + /// multiple times in the AST. OCaml shares these because they're often the same + /// pointer (constant values defined at module level). + /// + /// - None → integer 0 + /// - Some(s) → Block(tag=0, [s]) with content-based sharing + pub fn write_option_string(&mut self, opt: &Option) { + // Check if we've written this exact Option before + if let Some(&obj_idx) = self.option_string_table.get(opt) { + let d = self.obj_counter - obj_idx; + self.write_shared_ref(d); + return; + } + + match opt { + None => { + // None is encoded as integer 0, not a block, so no sharing needed + self.write_int(0); + } + Some(s) => { + // Record the object index BEFORE writing the block + let obj_idx = self.obj_counter; + + // Write Some(s) as Block(tag=0, [s]) + self.write_block_header(0, 1); + self.write_str(s); + + // Record for future sharing + self.option_string_table.insert(opt.clone(), obj_idx); + } + } + } } #[cfg(test)] @@ -973,16 +974,22 @@ mod tests { } #[test] - fn test_string_sharing() { + fn test_str_idx_sharing() { + use crate::parse_arena::ParseArena; + + let mut arena = ParseArena::default(); + let idx = arena.intern_string("test.res"); + let mut w = MarshalWriter::new(); + w.set_arena(&arena); // First occurrence: write the string - w.write_string_shared("test.res"); + w.write_str_idx(idx); let after_first = w.payload().len(); assert_eq!(w.obj_counter(), 1); // String recorded // Second occurrence: should write shared reference - w.write_string_shared("test.res"); + w.write_str_idx(idx); let after_second = w.payload().len(); assert_eq!(w.obj_counter(), 1); // No new object recorded @@ -999,18 +1006,25 @@ mod tests { } #[test] - fn test_string_sharing_different_strings() { + fn test_str_idx_sharing_different_strings() { + use crate::parse_arena::ParseArena; + + let mut arena = ParseArena::default(); + let idx_a = arena.intern_string("a.res"); + let idx_b = arena.intern_string("b.res"); + let mut w = MarshalWriter::new(); + w.set_arena(&arena); // Write two different strings - w.write_string_shared("a.res"); - w.write_string_shared("b.res"); + w.write_str_idx(idx_a); + w.write_str_idx(idx_b); // Both should be recorded as objects assert_eq!(w.obj_counter(), 2); - // Now reference the first one again - w.write_string_shared("a.res"); + // Now reference the first one again (same StrIdx) + w.write_str_idx(idx_a); // Should still be 2 objects (first one is shared) assert_eq!(w.obj_counter(), 2); @@ -1020,4 +1034,29 @@ mod tests { // - shared ref to "a.res" (2 bytes: CODE_SHARED8 + distance) assert_eq!(w.payload().len(), 14); } + + #[test] + fn test_str_idx_no_sharing_for_different_idx() { + use crate::parse_arena::ParseArena; + + let mut arena = ParseArena::default(); + // Create two different StrIdx with the same content + let idx1 = arena.intern_string("same"); + let idx2 = arena.push_string("same"); // Different idx, same content + + let mut w = MarshalWriter::new(); + w.set_arena(&arena); + + // Write first string + w.write_str_idx(idx1); + assert_eq!(w.obj_counter(), 1); + + // Write second string - different idx so NO sharing, even with same content + w.write_str_idx(idx2); + assert_eq!(w.obj_counter(), 2); + + // Payload should have both strings written fully (no sharing) + // "same" = 5 bytes each (0x24 + 4 chars) + assert_eq!(w.payload().len(), 10); + } } diff --git a/compiler-rust/src/binary_ast/parsetree0.rs b/compiler-rust/src/binary_ast/parsetree0.rs index 85076fc731f..48a9c645cd8 100644 --- a/compiler-rust/src/binary_ast/parsetree0.rs +++ b/compiler-rust/src/binary_ast/parsetree0.rs @@ -6,6 +6,7 @@ //! The types here mirror `compiler/ml/parsetree0.ml` exactly. use crate::location::{Located, Location}; +use crate::parse_arena::StrIdx; use crate::parser::longident::Longident; // ========== Asttypes (flags and labels) ========== @@ -71,14 +72,16 @@ pub enum Variance { pub type Label = String; /// Argument label for function parameters (parsetree0 uses Noloc version) -#[derive(Debug, Clone, PartialEq, Eq)] +/// Uses StrIdx to allow sharing with Longident::Lident when the same +/// identifier is used for both label and value (punning). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ArgLabel { /// Unlabeled argument Nolabel, /// Labeled argument (~label) - Labelled(String), + Labelled(StrIdx), /// Optional argument (?label) - Optional(String), + Optional(StrIdx), } /// Arity annotation for functions (None = inferred, Some(n) = explicit arity) diff --git a/compiler-rust/src/binary_ast/parsetree0_marshal.rs b/compiler-rust/src/binary_ast/parsetree0_marshal.rs index ad3171b4e0d..e7d22af0715 100644 --- a/compiler-rust/src/binary_ast/parsetree0_marshal.rs +++ b/compiler-rust/src/binary_ast/parsetree0_marshal.rs @@ -66,16 +66,19 @@ impl Marshal for ArgLabel { /// - Nolabel: int 0 (constant constructor) /// - Labelled(s): Block(tag=0, [s]) /// - Optional(s): Block(tag=1, [s]) + /// + /// Uses StrIdx-based sharing to match OCaml's behavior where the same + /// string (e.g., in punned ~compare) shares memory. fn marshal(&self, w: &mut MarshalWriter) { match self { ArgLabel::Nolabel => w.write_int(0), ArgLabel::Labelled(s) => { w.write_block_header(0, 1); - w.write_str(s); + w.write_str_idx(*s); } ArgLabel::Optional(s) => { w.write_block_header(1, 1); - w.write_str(s); + w.write_str_idx(*s); } } } @@ -115,7 +118,8 @@ impl Marshal for Constant { Constant::String(s, opt) => { w.write_block_header(2, 2); w.write_str(s); - opt.marshal(w); + // Use content-based sharing for string delimiters like Some("js") + w.write_option_string(opt); } Constant::Float(s, opt) => { w.write_block_header(3, 2); @@ -1203,12 +1207,16 @@ mod tests { #[test] fn test_expression_ident() { + use crate::parse_arena::ParseArena; use crate::parser::longident::Longident; + let mut arena = ParseArena::default(); + let x_idx = arena.intern_string("x"); let mut w = MarshalWriter::new(); + w.set_arena(&arena); let expr = Expression { pexp_desc: ExpressionDesc::Ident(crate::location::Located::new( - Longident::Lident("x".to_string()), + Longident::Lident(x_idx), crate::location::Location::none(), )), pexp_loc: crate::location::Location::none(), diff --git a/compiler-rust/src/binary_ast/serialize.rs b/compiler-rust/src/binary_ast/serialize.rs index 5c1664e2379..62981de4807 100644 --- a/compiler-rust/src/binary_ast/serialize.rs +++ b/compiler-rust/src/binary_ast/serialize.rs @@ -81,6 +81,9 @@ impl Marshal for Option { /// Options are encoded as: /// - None → integer 0 (constant constructor, index 0) /// - Some(v) → Block(tag=0, [v]) (non-constant constructor, tag 0) + /// + /// Note: For Option string delimiters, use write_option_string() + /// directly to enable content-based sharing of common values like Some("js"). fn marshal(&self, w: &mut MarshalWriter) { match self { None => w.write_int(0), diff --git a/compiler-rust/src/binary_ast/types.rs b/compiler-rust/src/binary_ast/types.rs index b3c9318fb7c..fdd78dd71c9 100644 --- a/compiler-rust/src/binary_ast/types.rs +++ b/compiler-rust/src/binary_ast/types.rs @@ -6,12 +6,13 @@ use super::marshal::MarshalWriter; use super::serialize::Marshal; use crate::location::{Located, Location, Position}; +use crate::parse_arena::{self, LidentIdx, LocIdx, PosIdx}; use crate::parser::longident::Longident; // ========== Position (Lexing.position) ========== impl Marshal for Position { - /// Serialize a Position to Marshal format with identity-based sharing. + /// Serialize a Position to Marshal format. /// /// OCaml type: /// ```ocaml @@ -24,22 +25,22 @@ impl Marshal for Position { /// ``` /// /// Encoded as a block with tag 0 and 4 fields. - /// Uses PositionId for identity-based sharing to match OCaml's pointer-based sharing. + /// + /// Uses StrIdx-based sharing for file names: the same StrIdx will be shared + /// in the marshal output via back-references. fn marshal(&self, w: &mut MarshalWriter) { - w.write_position_shared( - self.id, - &self.file_name, - self.line, - self.bol, - self.cnum, - ); + w.write_block_header(0, 4); + w.write_str_idx(self.file_name); + w.write_int(self.line as i64); + w.write_int(self.bol as i64); + w.write_int(self.cnum as i64); } } // ========== Location (Location.t) ========== impl Marshal for Location { - /// Serialize a Location to Marshal format with LocationId-based sharing. + /// Serialize a Location to Marshal format. /// /// OCaml type: /// ```ocaml @@ -51,43 +52,18 @@ impl Marshal for Location { /// ``` /// /// Encoded as a block with tag 0 and 3 fields. - /// Locations are shared when they have the same LocationId, which happens when: - /// - The same Location object is used in multiple places (clone preserves ID) - /// This mimics OCaml's pointer-based sharing. /// - /// NOTE: Locations with ID 0 (default_id) are special "uninitialized" locations - /// and are NOT shared - each occurrence is written as a new object. + /// NOTE: This impl is for the standalone Location struct which has no identity. + /// For proper sharing, use arena-based LocIdx instead. fn marshal(&self, w: &mut MarshalWriter) { - // Check if we've seen this Location before (by ID) - // Skip sharing for ID 0 (default_id) - these are uninitialized locations - // that shouldn't be shared (like Location::none(), Location::merge(), etc.) - if self.id.raw() != 0 { - if let Some(obj_idx) = w.get_location_by_id(self.id) { - // Write shared reference to previously written Location - let d = w.obj_counter() - obj_idx; - w.write_shared_ref(d); - return; - } - } - - // Record this Location's index BEFORE writing (OCaml assigns then increments) - let obj_idx = w.obj_counter(); - - // Write a new Location block w.write_block_header(0, 3); - // Positions are shared by identity (PositionId) self.loc_start.marshal(w); self.loc_end.marshal(w); w.write_int(if self.loc_ghost { 1 } else { 0 }); - - // Record for future sharing (only if not default_id) - if self.id.raw() != 0 { - w.record_location_id(self.id, obj_idx); - } } } -// ========== Located ('a loc) ========== +// ========== Located ('a loc) from crate::location ========== impl Marshal for Located { /// Serialize a Located to Marshal format. @@ -105,8 +81,51 @@ impl Marshal for Located { } } +// ========== Arena-based types ========== + +impl Marshal for PosIdx { + /// Serialize a PosIdx by looking up the position in the arena. + /// Requires that MarshalWriter::set_arena() was called first. + fn marshal(&self, w: &mut MarshalWriter) { + w.write_pos_idx(*self); + } +} + +impl Marshal for LocIdx { + /// Serialize a LocIdx by looking up the location in the arena. + /// Requires that MarshalWriter::set_arena() was called first. + fn marshal(&self, w: &mut MarshalWriter) { + w.write_loc_idx(*self); + } +} + +impl Marshal for parse_arena::Located { + /// Serialize a parse_arena::Located to Marshal format. + /// + /// OCaml type: + /// ```ocaml + /// type 'a loc = { txt: 'a; loc: t } + /// ``` + /// + /// Encoded as a block with tag 0 and 2 fields. + /// Uses arena-based LocIdx for the location. + fn marshal(&self, w: &mut MarshalWriter) { + w.write_block_header(0, 2); + self.txt.marshal(w); + self.loc.marshal(w); + } +} + // ========== Longident ========== +impl Marshal for LidentIdx { + /// Serialize a LidentIdx by looking up the longident in the arena. + /// Requires that MarshalWriter::set_arena() was called first. + fn marshal(&self, w: &mut MarshalWriter) { + w.write_lident_idx(*self); + } +} + impl Marshal for Longident { /// Serialize a Longident to Marshal format. /// @@ -119,19 +138,18 @@ impl Marshal for Longident { /// ``` /// /// All constructors are non-constant (have data), so they all use block tags. - /// Operator strings (like "-", "+") are shared by content to match OCaml's - /// behavior (OCaml's parser interns operator tokens). Regular identifiers - /// are NOT shared since OCaml creates new string objects for each occurrence. + /// Uses StrIdx-based sharing to match OCaml's behavior where the same + /// string (e.g., "compare" in both a label and identifier) shares memory. fn marshal(&self, w: &mut MarshalWriter) { match self { Longident::Lident(s) => { w.write_block_header(0, 1); - w.write_identifier_string(s); + w.write_str_idx(*s); } Longident::Ldot(prefix, name) => { w.write_block_header(1, 2); prefix.marshal(w); - w.write_identifier_string(name); + w.write_str_idx(*name); } Longident::Lapply(func, arg) => { w.write_block_header(2, 2); @@ -145,6 +163,7 @@ impl Marshal for Longident { #[cfg(test)] mod tests { use super::*; + use crate::parse_arena::ParseArena; #[test] fn test_position_marshal() { @@ -196,8 +215,12 @@ mod tests { #[test] fn test_longident_lident() { + let mut arena = ParseArena::default(); + let foo_idx = arena.intern_string("foo"); + let lid = Longident::Lident(foo_idx); + let mut w = MarshalWriter::new(); - let lid = Longident::Lident("foo".to_string()); + w.set_arena(&arena); lid.marshal(&mut w); let payload = w.payload(); @@ -210,11 +233,16 @@ mod tests { #[test] fn test_longident_ldot() { - let mut w = MarshalWriter::new(); + let mut arena = ParseArena::default(); + let foo_idx = arena.intern_string("Foo"); + let bar_idx = arena.intern_string("bar"); let lid = Longident::Ldot( - Box::new(Longident::Lident("Foo".to_string())), - "bar".to_string(), + Box::new(Longident::Lident(foo_idx)), + bar_idx, ); + + let mut w = MarshalWriter::new(); + w.set_arena(&arena); lid.marshal(&mut w); let payload = w.payload(); @@ -231,11 +259,16 @@ mod tests { #[test] fn test_longident_lapply() { - let mut w = MarshalWriter::new(); + let mut arena = ParseArena::default(); + let f_idx = arena.intern_string("F"); + let x_idx = arena.intern_string("X"); let lid = Longident::Lapply( - Box::new(Longident::Lident("F".to_string())), - Box::new(Longident::Lident("X".to_string())), + Box::new(Longident::Lident(f_idx)), + Box::new(Longident::Lident(x_idx)), ); + + let mut w = MarshalWriter::new(); + w.set_arena(&arena); lid.marshal(&mut w); let payload = w.payload(); @@ -255,15 +288,21 @@ mod tests { #[test] fn test_nested_longident() { - let mut w = MarshalWriter::new(); + let mut arena = ParseArena::default(); + let foo_idx = arena.intern_string("Foo"); + let bar_idx = arena.intern_string("Bar"); + let baz_idx = arena.intern_string("baz"); // Foo.Bar.baz let lid = Longident::Ldot( Box::new(Longident::Ldot( - Box::new(Longident::Lident("Foo".to_string())), - "Bar".to_string(), + Box::new(Longident::Lident(foo_idx)), + bar_idx, )), - "baz".to_string(), + baz_idx, ); + + let mut w = MarshalWriter::new(); + w.set_arena(&arena); lid.marshal(&mut w); let payload = w.payload(); diff --git a/compiler-rust/src/binary_ast/writer.rs b/compiler-rust/src/binary_ast/writer.rs index 0061baae6dc..072945e549f 100644 --- a/compiler-rust/src/binary_ast/writer.rs +++ b/compiler-rust/src/binary_ast/writer.rs @@ -35,13 +35,10 @@ use std::path::Path; use super::deps::{extract_signature_deps, extract_structure_deps}; use super::mapper_to0::{map_signature, map_structure}; use super::marshal::MarshalWriter; -use super::parsetree0 as pt0; use super::serialize::Marshal; +use crate::parse_arena::ParseArena; use crate::parser::ast::{Signature, Structure}; -// Import current parsetree marshal implementations -use super::current_marshal; - /// The separator character used in the binary AST format. const MAGIC_SEP_CHAR: u8 = b'\n'; @@ -51,6 +48,7 @@ const MAGIC_SEP_CHAR: u8 = b'\n'; /// /// * `output_path` - Path to the output .ast file /// * `source_path` - Absolute path to the source file +/// * `arena` - The parse arena containing location data /// * `ast` - The parsed structure AST /// /// # Returns @@ -59,16 +57,17 @@ const MAGIC_SEP_CHAR: u8 = b'\n'; pub fn write_structure_ast( output_path: &Path, source_path: &str, + arena: &mut ParseArena, ast: &Structure, ) -> io::Result<()> { // 1. Extract dependencies - let deps = extract_structure_deps(ast); + let deps = extract_structure_deps(arena, ast); // 2. Convert AST to parsetree0 format - let ast0 = map_structure(ast); + let ast0 = map_structure(arena, ast); - // 3. Write the binary AST file - write_ast_file(output_path, source_path, &deps, &ast0) + // 3. Write the binary AST file (parsetree0 doesn't need arena for marshalling) + write_ast_file(output_path, source_path, arena, &deps, &ast0) } /// Write a binary AST file for a signature (interface, .iast file). @@ -77,6 +76,7 @@ pub fn write_structure_ast( /// /// * `output_path` - Path to the output .iast file /// * `source_path` - Absolute path to the source file +/// * `arena` - The parse arena containing location data /// * `ast` - The parsed signature AST /// /// # Returns @@ -85,16 +85,17 @@ pub fn write_structure_ast( pub fn write_signature_ast( output_path: &Path, source_path: &str, + arena: &mut ParseArena, ast: &Signature, ) -> io::Result<()> { // 1. Extract dependencies - let deps = extract_signature_deps(ast); + let deps = extract_signature_deps(arena, ast); // 2. Convert AST to parsetree0 format - let ast0 = map_signature(ast); + let ast0 = map_signature(arena, ast); - // 3. Write the binary AST file - write_ast_file(output_path, source_path, &deps, &ast0) + // 3. Write the binary AST file (parsetree0 doesn't need arena for marshalling) + write_ast_file(output_path, source_path, arena, &deps, &ast0) } /// Write a binary AST file for a structure in the CURRENT parsetree format. @@ -104,32 +105,35 @@ pub fn write_signature_ast( pub fn write_structure_ast_current( output_path: &Path, source_path: &str, + arena: &crate::parse_arena::ParseArena, ast: &Structure, ) -> io::Result<()> { // 1. Extract dependencies - let deps = extract_structure_deps(ast); + let deps = extract_structure_deps(arena, ast); // 2. Write the binary AST file directly (no conversion to parsetree0) - write_ast_file(output_path, source_path, &deps, ast) + write_ast_file(output_path, source_path, arena, &deps, ast) } /// Write a binary AST file for a signature in the CURRENT parsetree format. pub fn write_signature_ast_current( output_path: &Path, source_path: &str, + arena: &crate::parse_arena::ParseArena, ast: &Signature, ) -> io::Result<()> { // 1. Extract dependencies - let deps = extract_signature_deps(ast); + let deps = extract_signature_deps(arena, ast); // 2. Write the binary AST file directly (no conversion to parsetree0) - write_ast_file(output_path, source_path, &deps, ast) + write_ast_file(output_path, source_path, arena, &deps, ast) } /// Write a binary AST file with the given dependencies and AST. fn write_ast_file( output_path: &Path, source_path: &str, + arena: &crate::parse_arena::ParseArena, deps: &std::collections::BTreeSet, ast: &A, ) -> io::Result<()> { @@ -143,6 +147,7 @@ fn write_ast_file( // Marshal the AST let mut marshal_writer = MarshalWriter::new(); + marshal_writer.set_arena(arena); ast.marshal(&mut marshal_writer); let marshal_data = marshal_writer.finish(); @@ -169,16 +174,16 @@ fn write_ast_file( } /// Write a structure AST to a Vec (for testing). -pub fn write_structure_ast_to_vec(source_path: &str, ast: &Structure) -> Vec { - let deps = extract_structure_deps(ast); - let ast0 = map_structure(ast); +pub fn write_structure_ast_to_vec(source_path: &str, arena: &mut ParseArena, ast: &Structure) -> Vec { + let deps = extract_structure_deps(arena, ast); + let ast0 = map_structure(arena, ast); write_ast_to_vec(source_path, &deps, &ast0) } /// Write a signature AST to a Vec (for testing). -pub fn write_signature_ast_to_vec(source_path: &str, ast: &Signature) -> Vec { - let deps = extract_signature_deps(ast); - let ast0 = map_signature(ast); +pub fn write_signature_ast_to_vec(source_path: &str, arena: &mut ParseArena, ast: &Signature) -> Vec { + let deps = extract_signature_deps(arena, ast); + let ast0 = map_signature(arena, ast); write_ast_to_vec(source_path, &deps, &ast0) } @@ -223,7 +228,7 @@ fn write_ast_to_vec( #[cfg(test)] mod tests { use super::*; - use crate::location::Location; + use crate::parse_arena::{LocIdx, Located}; use crate::parser::ast::{ Constant, Expression, ExpressionDesc, Pattern, PatternDesc, RecFlag, StructureItem, StructureItemDesc, ValueBinding, @@ -236,11 +241,11 @@ mod tests { RecFlag::Nonrecursive, vec![ValueBinding { pvb_pat: Pattern { - ppat_desc: PatternDesc::Ppat_var(crate::location::Located { + ppat_desc: PatternDesc::Ppat_var(Located { txt: name.to_string(), - loc: Location::none(), + loc: LocIdx::none(), }), - ppat_loc: Location::none(), + ppat_loc: LocIdx::none(), ppat_attributes: vec![], }, pvb_expr: Expression { @@ -248,32 +253,38 @@ mod tests { value.to_string(), None, )), - pexp_loc: Location::none(), + pexp_loc: LocIdx::none(), pexp_attributes: vec![], }, pvb_attributes: vec![], - pvb_loc: Location::none(), + pvb_loc: LocIdx::none(), }], ), - pstr_loc: Location::none(), + pstr_loc: LocIdx::none(), } } - fn make_module_ref_expr(module: &str, name: &str) -> Expression { + fn make_module_ref_expr(arena: &mut crate::parse_arena::ParseArena, module: &str, name: &str) -> Expression { + let lid_idx = arena.push_longident(Longident::ldot(Longident::lident(module), name)); Expression { - pexp_desc: ExpressionDesc::Pexp_ident(crate::location::Located { - txt: Longident::ldot(Longident::lident(module), name), - loc: Location::none(), + pexp_desc: ExpressionDesc::Pexp_ident(Located { + txt: lid_idx, + loc: LocIdx::none(), }), - pexp_loc: Location::none(), + pexp_loc: LocIdx::none(), pexp_attributes: vec![], } } + fn make_test_arena() -> crate::parse_arena::ParseArena { + crate::parse_arena::ParseArena::new() + } + #[test] fn test_empty_structure() { + let arena = make_test_arena(); let ast: Structure = vec![]; - let result = write_structure_ast_to_vec("/test/empty.res", &ast); + let result = write_structure_ast_to_vec("/test/empty.res", &arena, &ast); // Check header let dep_size = u32::from_be_bytes([result[0], result[1], result[2], result[3]]); @@ -300,8 +311,9 @@ mod tests { #[test] fn test_simple_binding() { + let arena = make_test_arena(); let ast = vec![make_simple_let_binding("x", 42)]; - let result = write_structure_ast_to_vec("/test/simple.res", &ast); + let result = write_structure_ast_to_vec("/test/simple.res", &arena, &ast); // Should have marshal magic number let dep_size = u32::from_be_bytes([result[0], result[1], result[2], result[3]]) as usize; @@ -316,12 +328,13 @@ mod tests { #[test] fn test_with_dependencies() { + let mut arena = make_test_arena(); let ast = vec![StructureItem { - pstr_desc: StructureItemDesc::Pstr_eval(make_module_ref_expr("Array", "map"), vec![]), - pstr_loc: Location::none(), + pstr_desc: StructureItemDesc::Pstr_eval(make_module_ref_expr(&mut arena, "Array", "map"), vec![]), + pstr_loc: LocIdx::none(), }]; - let result = write_structure_ast_to_vec("/test/deps.res", &ast); + let result = write_structure_ast_to_vec("/test/deps.res", &arena, &ast); // Check dependency section let dep_size = u32::from_be_bytes([result[0], result[1], result[2], result[3]]) as usize; @@ -337,21 +350,22 @@ mod tests { #[test] fn test_multiple_dependencies() { + let mut arena = make_test_arena(); let ast = vec![ StructureItem { pstr_desc: StructureItemDesc::Pstr_eval( - make_module_ref_expr("Array", "map"), + make_module_ref_expr(&mut arena, "Array", "map"), vec![], ), - pstr_loc: Location::none(), + pstr_loc: LocIdx::none(), }, StructureItem { - pstr_desc: StructureItemDesc::Pstr_eval(make_module_ref_expr("Js", "log"), vec![]), - pstr_loc: Location::none(), + pstr_desc: StructureItemDesc::Pstr_eval(make_module_ref_expr(&mut arena, "Js", "log"), vec![]), + pstr_loc: LocIdx::none(), }, ]; - let result = write_structure_ast_to_vec("/test/multi.res", &ast); + let result = write_structure_ast_to_vec("/test/multi.res", &arena, &ast); let dep_size = u32::from_be_bytes([result[0], result[1], result[2], result[3]]) as usize; @@ -361,9 +375,10 @@ mod tests { #[test] fn test_source_path_preserved() { + let arena = make_test_arena(); let ast: Structure = vec![]; let source_path = "/Users/dev/project/src/Main.res"; - let result = write_structure_ast_to_vec(source_path, &ast); + let result = write_structure_ast_to_vec(source_path, &arena, &ast); let dep_size = u32::from_be_bytes([result[0], result[1], result[2], result[3]]) as usize; let path_start = 4 + dep_size; @@ -383,8 +398,9 @@ mod tests { // Use a temp file in the target directory let output_path = std::path::Path::new("target/test_binary_ast_writer.ast"); + let arena = make_test_arena(); let ast = vec![make_simple_let_binding("x", 1)]; - write_structure_ast(output_path, "/test/test.res", &ast).unwrap(); + write_structure_ast(output_path, "/test/test.res", &arena, &ast).unwrap(); // Verify file exists and has content let content = fs::read(output_path).unwrap(); @@ -404,8 +420,9 @@ mod tests { #[test] fn test_empty_signature() { + let arena = make_test_arena(); let ast: Signature = vec![]; - let result = write_signature_ast_to_vec("/test/empty.resi", &ast); + let result = write_signature_ast_to_vec("/test/empty.resi", &arena, &ast); // Should have valid structure let dep_size = u32::from_be_bytes([result[0], result[1], result[2], result[3]]); diff --git a/compiler-rust/src/context.rs b/compiler-rust/src/context.rs index 0b2d73d64cc..627cfe8b9ca 100644 --- a/compiler-rust/src/context.rs +++ b/compiler-rust/src/context.rs @@ -204,8 +204,9 @@ impl SourceContext { } /// Create a location in this source file. + /// Note: Uses placeholder StrIdx for file name since SourceContext doesn't have arena access. pub fn location(&self, start: usize, end: usize) -> Location { - Location::new(&self.input_name, start, end) + Location::new_for_error(&self.input_name, start, end) } } diff --git a/compiler-rust/src/driver.rs b/compiler-rust/src/driver.rs index a2dc11ea0ae..1a42f75660e 100644 --- a/compiler-rust/src/driver.rs +++ b/compiler-rust/src/driver.rs @@ -49,23 +49,23 @@ pub fn compile_source_to_js_with_options( // Type check let id_gen = IdGenerator::new(); let type_ctx = TypeContext::new(&id_gen); - let mut tctx = TypeCheckContext::new(&type_ctx); + let mut tctx = TypeCheckContext::new(&type_ctx, parser.arena()); let env = initial_env(&type_ctx); - let (typed_structure, _env) = type_structure(&mut tctx, &env, &structure) + let (typed_structure, _env) = type_structure(&mut tctx, &env, parser.arena(), &structure) .map_err(|e| anyhow!("Type checking failed: {e:?}"))?; // Print typed tree if requested if options.dump_typed_sexp { let mut stderr = std::io::stderr(); - let _ = print_typed_structure(&type_ctx, &typed_structure, &mut stderr); + let _ = print_typed_structure(parser.arena(), &type_ctx, &typed_structure, &mut stderr); } if options.dump_typed_sexp_locs { let mut stderr = std::io::stderr(); - let _ = print_typed_structure_with_locs(&type_ctx, &typed_structure, &mut stderr); + let _ = print_typed_structure_with_locs(parser.arena(), &type_ctx, &typed_structure, &mut stderr); } // Typedtree -> Lambda - let mut converter = LambdaConverter::new(); + let mut converter = LambdaConverter::new(parser.arena()); let lambda = converter.convert_structure(&typed_structure); // Print Lambda IR if requested @@ -105,10 +105,13 @@ pub fn compile_file_to_js_with_options( path: &std::path::Path, options: &CompilerOptions, ) -> Result { - // Use lossy UTF-8 conversion (like OCaml) to handle files with invalid bytes + // Read file as raw bytes, converting each byte to a char (Latin-1 encoding). + // This matches OCaml's byte-level string handling where each byte is a character. + // In Latin-1 mode, char offset == original byte offset, which is critical for + // correct position tracking in the scanner. let bytes = std::fs::read(path) .with_context(|| format!("Failed to read {}", path.display()))?; - let source = String::from_utf8_lossy(&bytes).into_owned(); + let source: String = bytes.iter().map(|&b| b as char).collect(); let filename = path.to_string_lossy(); compile_source_to_js_with_options(&source, &filename, options) } diff --git a/compiler-rust/src/intern.rs b/compiler-rust/src/intern.rs new file mode 100644 index 00000000000..d9558dca64c --- /dev/null +++ b/compiler-rust/src/intern.rs @@ -0,0 +1,206 @@ +//! String interning for efficient storage and sharing. +//! +//! This module provides string interning, which stores each unique string +//! only once and returns a lightweight index. When the same string is +//! interned multiple times, the same index is returned. +//! +//! This is critical for matching OCaml's behavior where identifier strings +//! are interned, causing Marshal to share them via back-references. +//! +//! # Example +//! +//! ```ignore +//! use rescript_compiler::intern::Interner; +//! +//! let mut interner = Interner::new(); +//! let idx1 = interner.intern("hello"); +//! let idx2 = interner.intern("hello"); +//! assert_eq!(idx1, idx2); // Same string = same index +//! +//! let idx3 = interner.intern("world"); +//! assert_ne!(idx1, idx3); // Different string = different index +//! +//! assert_eq!(interner.get(idx1), "hello"); +//! ``` + +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; + +// ============================================================================ +// String Index +// ============================================================================ + +/// Index into the string interner. +/// +/// This is a lightweight 4-byte value that can be copied freely. +/// Two StrIdx values are equal if and only if they refer to the same string. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)] +pub struct StrIdx(pub u32); + +impl StrIdx { + /// Create a StrIdx from a raw u32 value. + #[inline] + pub fn from_raw(idx: u32) -> Self { + StrIdx(idx) + } + + /// Get the raw u32 value. + #[inline] + pub fn raw(self) -> u32 { + self.0 + } +} + +// ============================================================================ +// String Interner +// ============================================================================ + +/// String interner that stores unique strings and returns indices. +/// +/// This provides O(1) lookup of previously interned strings and guarantees +/// that identical strings get the same index. +#[derive(Debug)] +pub struct Interner { + /// Maps string content to its index + map: HashMap, + /// Stores the actual strings, indexed by StrIdx + strings: Vec, +} + +impl Default for Interner { + fn default() -> Self { + Self::new() + } +} + +impl Interner { + /// Create a new empty interner. + pub fn new() -> Self { + Self { + map: HashMap::new(), + strings: Vec::new(), + } + } + + /// Create a new interner with pre-allocated capacity. + pub fn with_capacity(capacity: usize) -> Self { + Self { + map: HashMap::with_capacity(capacity), + strings: Vec::with_capacity(capacity), + } + } + + /// Intern a string, returning its index. + /// + /// If the string was previously interned, returns the existing index. + /// Otherwise, stores the string and returns a new index. + pub fn intern(&mut self, s: &str) -> StrIdx { + if let Some(&idx) = self.map.get(s) { + return idx; + } + + let idx = StrIdx(self.strings.len() as u32); + self.strings.push(s.to_string()); + self.map.insert(s.to_string(), idx); + idx + } + + /// Intern an owned string, returning its index. + /// + /// This avoids an allocation if the string is not already interned. + pub fn intern_owned(&mut self, s: String) -> StrIdx { + if let Some(&idx) = self.map.get(&s) { + return idx; + } + + let idx = StrIdx(self.strings.len() as u32); + self.map.insert(s.clone(), idx); + self.strings.push(s); + idx + } + + /// Push a string without deduplication, always creating a new entry. + /// + /// Use this for dynamic strings (from user input/tokens) that should NOT + /// be shared during marshalling. Each call returns a unique index. + /// + /// For static strings that should be shared, use `intern()` instead. + pub fn push(&mut self, s: String) -> StrIdx { + let idx = StrIdx(self.strings.len() as u32); + self.strings.push(s); + // Note: We don't add to the map, so this string won't be found by intern() + idx + } + + /// Get the string for an index. + /// + /// # Panics + /// + /// Panics if the index is invalid. + pub fn get(&self, idx: StrIdx) -> &str { + &self.strings[idx.0 as usize] + } + + /// Get the string for an index, returning None if invalid. + pub fn try_get(&self, idx: StrIdx) -> Option<&str> { + self.strings.get(idx.0 as usize).map(|s| s.as_str()) + } + + /// Return the number of unique strings interned. + pub fn len(&self) -> usize { + self.strings.len() + } + + /// Check if the interner is empty. + pub fn is_empty(&self) -> bool { + self.strings.is_empty() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_intern_returns_same_idx_for_same_string() { + let mut interner = Interner::new(); + let idx1 = interner.intern("hello"); + let idx2 = interner.intern("hello"); + assert_eq!(idx1, idx2); + } + + #[test] + fn test_intern_returns_different_idx_for_different_string() { + let mut interner = Interner::new(); + let idx1 = interner.intern("hello"); + let idx2 = interner.intern("world"); + assert_ne!(idx1, idx2); + } + + #[test] + fn test_get_returns_interned_string() { + let mut interner = Interner::new(); + let idx = interner.intern("hello"); + assert_eq!(interner.get(idx), "hello"); + } + + #[test] + fn test_intern_owned() { + let mut interner = Interner::new(); + let idx1 = interner.intern_owned("hello".to_string()); + let idx2 = interner.intern("hello"); + assert_eq!(idx1, idx2); + } + + #[test] + fn test_len() { + let mut interner = Interner::new(); + assert_eq!(interner.len(), 0); + interner.intern("a"); + assert_eq!(interner.len(), 1); + interner.intern("b"); + assert_eq!(interner.len(), 2); + interner.intern("a"); // Already interned + assert_eq!(interner.len(), 2); + } +} diff --git a/compiler-rust/src/lambda/convert.rs b/compiler-rust/src/lambda/convert.rs index e64a68a1caf..313ced62857 100644 --- a/compiler-rust/src/lambda/convert.rs +++ b/compiler-rust/src/lambda/convert.rs @@ -7,7 +7,7 @@ use crate::context::IdGenerator; use crate::ident::Ident; use crate::lambda::compat::{Comparison, FieldDbgInfo, LetKind, SetFieldDbgInfo}; -use crate::lambda::constant::{Constant, PointerInfo, StringDelim}; +use crate::lambda::constant::{Constant, StringDelim}; use crate::lambda::primitive::{ExternalArgSpec, ExternalFfiSpec, Mutable, Primitive}; use crate::lambda::tag_info::TagInfo; use crate::lambda::{ @@ -15,6 +15,7 @@ use crate::lambda::{ Lambda, }; use crate::location::Location; +use crate::parse_arena::{LidentIdx, LocIdx, Located, ParseArena}; use crate::parser::ast::{DirectionFlag, MutableFlag as ParserMutableFlag, RecFlag}; use crate::types::asttypes::MutableFlag as TypeMutableFlag; use crate::types::decl::{ConstructorDescription, ConstructorTag, LabelDescription, ValueKind}; @@ -25,24 +26,26 @@ use crate::types::typedtree::{ }; /// Lambda conversion state. -pub struct LambdaConverter { +pub struct LambdaConverter<'a> { id_gen: IdGenerator, + arena: &'a ParseArena, } -impl Default for LambdaConverter { - fn default() -> Self { - Self::new() - } -} - -impl LambdaConverter { +impl<'a> LambdaConverter<'a> { /// Create a new converter with its own id generator. - pub fn new() -> Self { + pub fn new(arena: &'a ParseArena) -> Self { Self { id_gen: IdGenerator::new(), + arena, } } + /// Helper to convert a LocIdx to a Location. + #[inline] + fn loc(&self, idx: LocIdx) -> Location { + self.arena.to_location(idx) + } + /// Convert a structure into a Lambda expression. pub fn convert_structure(&mut self, structure: &Structure) -> Lambda { let items: Vec = structure @@ -87,8 +90,8 @@ impl LambdaConverter { pub fn convert_expr(&mut self, expr: &Expression) -> Lambda { match &expr.exp_desc { ExpressionDesc::Texp_ident(path, _, desc) => match &desc.val_kind { - ValueKind::ValPrim(prim) => self.translate_primitive(expr.exp_loc.clone(), prim), - ValueKind::ValReg => Self::translate_value_path(&expr.exp_loc, path), + ValueKind::ValPrim(prim) => self.translate_primitive(self.loc(expr.exp_loc), prim), + ValueKind::ValReg => self.translate_value_path(expr.exp_loc, path), }, ExpressionDesc::Texp_constant(cst) => Lambda::const_(self.convert_constant(cst)), ExpressionDesc::Texp_let(rec_flag, bindings, body) => { @@ -101,20 +104,20 @@ impl LambdaConverter { partial, arity, async_: _, - } => self.convert_function(expr.exp_loc.clone(), params, body, *partial, *arity), + } => self.convert_function(params, body, *partial, *arity), ExpressionDesc::Texp_apply { funct, args, partial: _, transformed_jsx: _ } => { - self.convert_apply(expr.exp_loc.clone(), funct, args) + self.convert_apply(self.loc(expr.exp_loc), funct, args) } ExpressionDesc::Texp_match(scrut, cases, _exn_cases, partial) => { let scrut_lam = self.convert_expr(scrut); - self.compile_match(expr.exp_loc.clone(), scrut_lam, cases, *partial) + self.compile_match(self.loc(expr.exp_loc), scrut_lam, cases, *partial) } ExpressionDesc::Texp_try(body, cases) => { let body_lam = self.convert_expr(body); let exn_id = self.id_gen.create("exn"); let handler_scrut = Lambda::var(exn_id.clone()); let handler = self.compile_match( - expr.exp_loc.clone(), + self.loc(expr.exp_loc), handler_scrut, cases, crate::types::typedtree::Partial::Partial, @@ -126,17 +129,17 @@ impl LambdaConverter { Lambda::prim( Primitive::Pmakeblock(0, TagInfo::Tuple, Mutable::Immutable), elems, - expr.exp_loc.clone(), + self.loc(expr.exp_loc), ) } ExpressionDesc::Texp_construct(_, cstr, args) => { - self.convert_construct(expr.exp_loc.clone(), cstr, args) + self.convert_construct(self.loc(expr.exp_loc), cstr, args) } ExpressionDesc::Texp_variant(tag, arg) => self.convert_poly_variant(tag, arg), ExpressionDesc::Texp_record { fields, extended_expression, - } => self.convert_record(expr.exp_loc.clone(), fields, extended_expression.as_deref()), + } => self.convert_record(self.loc(expr.exp_loc), fields, extended_expression.as_deref()), ExpressionDesc::Texp_field(record, _, lbl) => { let rec_lam = self.convert_expr(record); let primitive = Primitive::Pfield( @@ -146,7 +149,7 @@ impl LambdaConverter { mutable_flag: to_parser_mutable(lbl.lbl_mut), }, ); - Lambda::prim(primitive, vec![rec_lam], expr.exp_loc.clone()) + Lambda::prim(primitive, vec![rec_lam], self.loc(expr.exp_loc)) } ExpressionDesc::Texp_setfield(record, _, lbl, value) => { let rec_lam = self.convert_expr(record); @@ -155,11 +158,11 @@ impl LambdaConverter { lbl.lbl_pos, SetFieldDbgInfo::RecordSet(lbl.lbl_name.clone()), ); - Lambda::prim(primitive, vec![rec_lam, val_lam], expr.exp_loc.clone()) + Lambda::prim(primitive, vec![rec_lam, val_lam], self.loc(expr.exp_loc)) } ExpressionDesc::Texp_array(items) => { let elems = items.iter().map(|e| self.convert_expr(e)).collect(); - Lambda::prim(Primitive::Pmakearray, elems, expr.exp_loc.clone()) + Lambda::prim(Primitive::Pmakearray, elems, self.loc(expr.exp_loc)) } ExpressionDesc::Texp_ifthenelse(cond, then_, else_) => { let cond_lam = self.convert_expr(cond); @@ -193,9 +196,9 @@ impl LambdaConverter { ExpressionDesc::Texp_send(_, _) => Lambda::unit(), ExpressionDesc::Texp_letmodule(_, _, _, body) => self.convert_expr(body), ExpressionDesc::Texp_letexception(_, body) => self.convert_expr(body), - ExpressionDesc::Texp_assert(expr) => { - let cond = self.convert_expr(expr); - let failure = self.match_failure(expr.exp_loc.clone()); + ExpressionDesc::Texp_assert(inner_expr) => { + let cond = self.convert_expr(inner_expr); + let failure = self.match_failure(self.loc(inner_expr.exp_loc)); Lambda::if_(cond, Lambda::unit(), failure) } ExpressionDesc::Texp_pack(_) => Lambda::unit(), @@ -229,7 +232,7 @@ impl LambdaConverter { RecFlag::Nonrecursive => { bindings.iter().rev().fold(body, |acc, binding| { let value = self.convert_expr(&binding.vb_expr); - let failure = self.match_failure(binding.vb_loc.clone()); + let failure = self.match_failure(self.loc(binding.vb_loc)); self.bind_pattern(&binding.vb_pat, value, acc, failure) }) } @@ -244,7 +247,7 @@ impl LambdaConverter { // Fallback to non-recursive handling for complex patterns. return bindings.iter().rev().fold(body, |acc, b| { let value = self.convert_expr(&b.vb_expr); - let failure = self.match_failure(b.vb_loc.clone()); + let failure = self.match_failure(self.loc(b.vb_loc)); self.bind_pattern(&b.vb_pat, value, acc, failure) }); } @@ -292,7 +295,6 @@ impl LambdaConverter { fn convert_function( &mut self, - loc: Location, params: &[FunctionParam], cases: &[Case], partial: crate::types::typedtree::Partial, @@ -300,7 +302,7 @@ impl LambdaConverter { ) -> Lambda { // Use arity to flatten nested functions into a single multi-param function // e.g., `(x, y) => x + y` has arity 2 but is represented as nested functions - let (all_params, final_body, final_partial) = + let (all_params, final_body, _final_partial) = self.flatten_function_by_arity(params, cases, partial, arity); let mut param_ids = Vec::new(); @@ -383,20 +385,20 @@ impl LambdaConverter { /// /// We use the arity to know how many nested functions to flatten into /// a single multi-parameter function. - fn flatten_function_by_arity<'a>( + fn flatten_function_by_arity<'b>( &self, - params: &'a [FunctionParam], - cases: &'a [Case], + params: &'b [FunctionParam], + cases: &'b [Case], partial: crate::types::typedtree::Partial, arity: crate::parser::ast::Arity, - ) -> (Vec<&'a FunctionParam>, Option<&'a Expression>, crate::types::typedtree::Partial) { + ) -> (Vec<&'b FunctionParam>, Option<&'b Expression>, crate::types::typedtree::Partial) { use crate::parser::ast::Arity; let target_arity = match arity { Arity::Full(n) => n, Arity::Unknown => params.len(), }; - let mut all_params: Vec<&'a FunctionParam> = params.iter().collect(); + let mut all_params: Vec<&'b FunctionParam> = params.iter().collect(); let mut current_partial = partial; // We need exactly one case with no guard to flatten @@ -405,7 +407,7 @@ impl LambdaConverter { return (all_params, cases.first().map(|c| &c.c_rhs), current_partial); } - let mut current_body: &'a Expression = &cases[0].c_rhs; + let mut current_body: &'b Expression = &cases[0].c_rhs; // Keep flattening while we haven't reached the target arity while all_params.len() < target_arity { @@ -442,7 +444,7 @@ impl LambdaConverter { if patterns.is_empty() { Pattern::new( PatternDesc::Tpat_any, - Location::none(), + LocIdx::none(), crate::types::TypeExprRef(0), crate::types::typedtree::EnvRef(0), vec![], @@ -452,7 +454,7 @@ impl LambdaConverter { } else { Pattern::new( PatternDesc::Tpat_tuple(patterns), - Location::none(), + LocIdx::none(), crate::types::TypeExprRef(0), crate::types::typedtree::EnvRef(0), vec![], @@ -529,18 +531,19 @@ impl LambdaConverter { let cond = Lambda::prim( Primitive::Pjscomp(Comparison::Eq), vec![scrut, cst_lam], - pat.pat_loc.clone(), + self.loc(pat.pat_loc), ); Lambda::if_(cond, body, failure) } PatternDesc::Tpat_tuple(items) => { let tmp = self.id_gen.create("tuple"); + let pat_loc = self.loc(pat.pat_loc); let mut result = body; for (idx, item) in items.iter().enumerate().rev() { let field = Lambda::prim( Primitive::Pfield(idx as i32, FieldDbgInfo::Tuple), vec![Lambda::var(tmp.clone())], - pat.pat_loc.clone(), + pat_loc.clone(), ); result = self.bind_pattern(item, field, result, failure.clone()); } @@ -551,24 +554,25 @@ impl LambdaConverter { } PatternDesc::Tpat_variant(tag, arg, _) => { let tmp = self.id_gen.create("poly"); + let pat_loc = self.loc(pat.pat_loc); let tag_check = Lambda::prim( Primitive::Pjscomp(Comparison::Eq), vec![ Lambda::prim( Primitive::Pfield(0, FieldDbgInfo::PolyVarTag), vec![Lambda::var(tmp.clone())], - pat.pat_loc.clone(), + pat_loc.clone(), ), Lambda::const_(Constant::Pointer(tag.clone())), ], - pat.pat_loc.clone(), + pat_loc.clone(), ); let mut body_with_arg = body; if let Some(arg_pat) = arg { let payload = Lambda::prim( Primitive::Pfield(1, FieldDbgInfo::PolyVarContent), vec![Lambda::var(tmp.clone())], - pat.pat_loc.clone(), + pat_loc.clone(), ); body_with_arg = self.bind_pattern(arg_pat, payload, body_with_arg, failure.clone()); @@ -579,7 +583,7 @@ impl LambdaConverter { PatternDesc::Tpat_record(fields, _closed) => { let tmp = self.id_gen.create("record"); let mut result = body; - for (lid, lbl, pat, _optional) in fields.iter().rev() { + for (lid, lbl, inner_pat, _optional) in fields.iter().rev() { let field = Lambda::prim( Primitive::Pfield( lbl.lbl_pos, @@ -589,24 +593,25 @@ impl LambdaConverter { }, ), vec![Lambda::var(tmp.clone())], - lid.loc.clone(), + self.loc(lid.loc), ); - result = self.bind_pattern(pat, field, result, failure.clone()); + result = self.bind_pattern(inner_pat, field, result, failure.clone()); } Lambda::let_(LetKind::Strict, tmp, scrut, result) } PatternDesc::Tpat_array(items) => { let tmp = self.id_gen.create("array"); + let pat_loc = self.loc(pat.pat_loc); let len_expr = Lambda::prim( Primitive::Parraylength, vec![Lambda::var(tmp.clone())], - pat.pat_loc.clone(), + pat_loc.clone(), ); let len_cst = Lambda::const_(Constant::int(items.len() as i32)); let len_cond = Lambda::prim( Primitive::Pjscomp(Comparison::Eq), vec![len_expr, len_cst], - pat.pat_loc.clone(), + pat_loc.clone(), ); let mut result = body; for (idx, item) in items.iter().enumerate().rev() { @@ -616,7 +621,7 @@ impl LambdaConverter { Lambda::var(tmp.clone()), Lambda::const_(Constant::int(idx as i32)), ], - pat.pat_loc.clone(), + pat_loc.clone(), ); result = self.bind_pattern(item, field, result, failure.clone()); } @@ -639,6 +644,7 @@ impl LambdaConverter { cstr: &ConstructorDescription, args: &[Pattern], ) -> Lambda { + let pat_loc = self.loc(pat.pat_loc); match &cstr.cstr_tag { ConstructorTag::CstrConstant(_tag) => { // Compare against the same value we'd generate: string for variants, bool for true/false @@ -650,7 +656,7 @@ impl LambdaConverter { let cond = Lambda::prim( Primitive::Pjscomp(Comparison::Eq), vec![scrut, Lambda::const_(tag_const)], - pat.pat_loc.clone(), + pat_loc, ); Lambda::if_(cond, body, failure) } @@ -660,19 +666,19 @@ impl LambdaConverter { let tag_expr = Lambda::prim( Primitive::Pfield(0, FieldDbgInfo::VariantTag), vec![Lambda::var(tmp.clone())], - pat.pat_loc.clone(), + pat_loc.clone(), ); let tag_cond = Lambda::prim( Primitive::Pjscomp(Comparison::Eq), vec![tag_expr, Lambda::const_(Constant::Pointer(cstr.cstr_name.clone()))], - pat.pat_loc.clone(), + pat_loc.clone(), ); let mut result = body; for (idx, arg_pat) in args.iter().enumerate().rev() { let field = Lambda::prim( Primitive::Pfield(idx as i32, FieldDbgInfo::Variant), vec![Lambda::var(tmp.clone())], - pat.pat_loc.clone(), + pat_loc.clone(), ); result = self.bind_pattern(arg_pat, field, result, failure.clone()); } @@ -737,7 +743,7 @@ impl LambdaConverter { Lambda::prim( Primitive::Pmakeblock(0, TagInfo::PolyVar(tag.to_string()), Mutable::Immutable), vec![Lambda::const_(Constant::Pointer(tag.to_string())), arg_lam], - expr.exp_loc.clone(), + self.loc(expr.exp_loc), ) } } @@ -746,7 +752,7 @@ impl LambdaConverter { fn convert_record( &mut self, loc: Location, - fields: &[(crate::types::typedtree::Loc, LabelDescription, RecordLabelDefinition)], + fields: &[(Located, LabelDescription, RecordLabelDefinition)], base: Option<&Expression>, ) -> Lambda { let mut values = vec![None; fields.len()]; @@ -766,7 +772,7 @@ impl LambdaConverter { }, ), vec![base_expr.clone()], - lid.loc.clone(), + self.loc(lid.loc), ) } else { Lambda::unit() @@ -802,7 +808,7 @@ impl LambdaConverter { ) } - fn translate_value_path(loc: &Location, path: &crate::types::Path) -> Lambda { + fn translate_value_path(&self, loc_idx: LocIdx, path: &crate::types::Path) -> Lambda { match path { crate::types::Path::Pident(id) => { if id.is_global() { @@ -812,7 +818,7 @@ impl LambdaConverter { } } crate::types::Path::Pdot(prefix, name, _) => { - let prefix_lam = Self::translate_value_path(loc, prefix); + let prefix_lam = self.translate_value_path(loc_idx, prefix); Lambda::prim( Primitive::Pfield( 0, @@ -821,7 +827,7 @@ impl LambdaConverter { }, ), vec![prefix_lam], - loc.clone(), + self.loc(loc_idx), ) } crate::types::Path::Papply(_, _) => Lambda::unit(), @@ -1008,16 +1014,17 @@ fn to_parser_mutable(flag: TypeMutableFlag) -> ParserMutableFlag { mod tests { use super::*; use crate::ident::Ident; - use crate::location::Located; + use crate::parse_arena::{Located, ParseArena}; use crate::parser::longident::Longident; use crate::types::typedtree::{Expression, ExpressionDesc}; #[test] fn test_convert_constant_int() { - let mut conv = LambdaConverter::new(); + let arena = ParseArena::new(); + let mut conv = LambdaConverter::new(&arena); let expr = Expression::new( ExpressionDesc::Texp_constant(TConstant::Int(42)), - Location::none(), + LocIdx::none(), crate::types::TypeExprRef(0), crate::types::typedtree::EnvRef(0), vec![], @@ -1031,11 +1038,14 @@ mod tests { #[test] fn test_convert_let_var() { - let mut conv = LambdaConverter::new(); + use crate::parser::longident::Longident; + let mut arena = ParseArena::new(); + let lid_idx = arena.push_longident(Longident::Lident("x".to_string())); + let mut conv = LambdaConverter::new(&arena); let id = Ident::create_local("x"); let pat = Pattern::new( PatternDesc::Tpat_var(id.clone(), Located::mknoloc("x".to_string())), - Location::none(), + LocIdx::none(), crate::types::TypeExprRef(0), crate::types::typedtree::EnvRef(0), vec![], @@ -1044,18 +1054,18 @@ mod tests { vb_pat: pat, vb_expr: Expression::new( ExpressionDesc::Texp_constant(TConstant::Int(1)), - Location::none(), + LocIdx::none(), crate::types::TypeExprRef(0), crate::types::typedtree::EnvRef(0), vec![], ), vb_attributes: vec![], - vb_loc: Location::none(), + vb_loc: LocIdx::none(), }; let body = Expression::new( ExpressionDesc::Texp_ident( crate::types::Path::pident(id.clone()), - Located::mknoloc(Longident::Lident("x".to_string())), + Located::mknoloc(lid_idx), crate::types::ValueDescription { val_type: crate::types::TypeExprRef(0), val_kind: ValueKind::ValReg, @@ -1064,7 +1074,7 @@ mod tests { val_path: None, }, ), - Location::none(), + LocIdx::none(), crate::types::TypeExprRef(0), crate::types::typedtree::EnvRef(0), vec![], @@ -1075,7 +1085,7 @@ mod tests { vec![vb], Box::new(body), ), - Location::none(), + LocIdx::none(), crate::types::TypeExprRef(0), crate::types::typedtree::EnvRef(0), vec![], diff --git a/compiler-rust/src/lib.rs b/compiler-rust/src/lib.rs index bb3b8b43f21..e98becccf72 100644 --- a/compiler-rust/src/lib.rs +++ b/compiler-rust/src/lib.rs @@ -44,8 +44,11 @@ pub mod context; pub mod diagnostics; #[allow(unsafe_code)] // FFI requires unsafe pub mod ffi; +pub mod arena; pub mod ident; +pub mod intern; pub mod js_ir; +pub mod parse_arena; pub mod lambda; pub mod location; pub mod parser; diff --git a/compiler-rust/src/location.rs b/compiler-rust/src/location.rs index 7ab329c37a0..6e86b38d479 100644 --- a/compiler-rust/src/location.rs +++ b/compiler-rust/src/location.rs @@ -4,178 +4,86 @@ //! and diagnostics. Unlike the OCaml `location.ml` which uses global //! `input_name` ref, all location information is self-contained. //! -//! # Position Identity +//! # Position and Location Identity //! -//! Positions have a unique `PositionId` for identity-based sharing in the -//! Marshal format. This mimics OCaml's pointer-based object sharing: -//! - Scanner creates NEW positions with unique IDs (via its internal counter) -//! - Parser assigns `prev_end_pos = end_pos` which COPIES the ID (same identity) -//! - Marshal uses PositionId to determine sharing (not content equality) +//! Identity-based sharing for positions and locations is handled by the +//! `ParseArena` module using `PosIdx` and `LocIdx` indices. The Position +//! and Location structs here are pure value types without identity. //! -//! The Scanner owns the ID counter, so each parser instance has independent IDs. -//! This avoids global state and supports concurrent parsing. -//! -//! # Example -//! -//! ```rust -//! use rescript_compiler::location::{Location, Position}; -//! -//! let start = Position::new("test.res", 1, 0, 0); -//! let end_pos = Position::new("test.res", 1, 0, 10); -//! let loc = Location::from_positions(start, end_pos); -//! -//! assert_eq!(loc.file_name(), "test.res"); -//! assert_eq!(loc.start_line(), 1); -//! ``` +//! File names are stored as `StrIdx` to enable pointer-based sharing in +//! marshal output. The same StrIdx passed to all positions in a file will +//! result in shared references in the binary output. +use crate::intern::StrIdx; use serde::{Deserialize, Serialize}; use std::fmt; -/// Unique identifier for a Position, used for identity-based sharing. -/// -/// This mimics OCaml's pointer-based object identity: -/// - Each call to `Scanner::position()` creates a NEW position with a unique ID -/// - Assigning `prev_end_pos = end_pos` copies the ID (same identity) -/// - Marshal uses PositionId (not content) to determine if positions should be shared -/// -/// ID 0 is reserved for default/uninitialized positions. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub struct PositionId(u32); - -impl PositionId { - /// Create a PositionId from a raw value. - /// Used by Scanner which owns the counter. - pub fn from_raw(id: u32) -> Self { - Self(id) - } - - /// Create a default/uninitialized PositionId (ID 0). - pub fn default_id() -> Self { - Self(0) - } - - /// Get the raw ID value (for debugging/testing/serialization). - pub fn raw(&self) -> u32 { - self.0 - } -} - -impl Default for PositionId { - fn default() -> Self { - Self::default_id() - } -} - -/// Unique identifier for a Location, used for identity-based sharing. -/// -/// This mimics OCaml's pointer-based object identity: -/// - Each call to `mk_loc()` creates a NEW location with a unique ID -/// - Cloning a Location preserves the ID (same identity, will be shared in Marshal) -/// - Marshal uses LocationId (not content) to determine if locations should be shared -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] -pub struct LocationId(u32); - -impl LocationId { - /// Create a LocationId from a raw value. - pub fn from_raw(id: u32) -> Self { - Self(id) - } - - /// Create a default/uninitialized LocationId (ID 0). - pub fn default_id() -> Self { - Self(0) - } - - /// Get the raw ID value (for debugging/testing/serialization). - pub fn raw(&self) -> u32 { - self.0 - } -} - -impl Default for LocationId { - fn default() -> Self { - Self::default_id() +impl fmt::Display for Location { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // Note: file_name is StrIdx so we can't display the actual name without arena access. + // Display coordinates only. + match self.normalize_range() { + None => write!(f, "(unknown location)"), + Some((start_line, start_col, end_line, end_col)) => { + if start_line == end_line { + if start_col == end_col { + write!(f, "line {}:{}", start_line, start_col) + } else { + write!(f, "line {}:{}-{}", start_line, start_col, end_col) + } + } else { + write!(f, "line {}:{}-{}:{}", start_line, start_col, end_line, end_col) + } + } + } } } /// A position in a source file. /// /// This corresponds to `Lexing.position` in OCaml. -/// -/// # Identity -/// -/// Each Position has a unique `id` field for identity-based sharing in the -/// Marshal format. When you clone a Position, the id is copied (same identity). -/// To create a truly NEW position, use `Position::new()` or `Position::new_with_id()`. -#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] +/// File name is stored as StrIdx for efficient sharing in marshal output. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct Position { - /// File name. - pub file_name: String, + /// File name (interned string index). + pub file_name: StrIdx, /// Line number (1-indexed). pub line: i32, /// Column offset from beginning of line (0-indexed). pub bol: i32, /// Character offset from beginning of file (0-indexed). pub cnum: i32, - /// Unique identity for sharing in Marshal format. - /// When cloning, this ID is preserved (same identity as original). - pub id: PositionId, } impl Default for Position { fn default() -> Self { Self { - file_name: String::new(), + file_name: StrIdx::default(), line: 0, bol: 0, cnum: 0, - id: PositionId::default_id(), } } } impl Position { - /// Create a new position with a default (uninitialized) ID. - /// - /// For positions with proper identity tracking, use `new_with_id()` or - /// let the Scanner create positions (which assigns unique IDs). - pub fn new(file_name: impl Into, line: i32, bol: i32, cnum: i32) -> Self { + /// Create a new position with an interned file name. + pub fn new(file_name: StrIdx, line: i32, bol: i32, cnum: i32) -> Self { Self { - file_name: file_name.into(), + file_name, line, bol, cnum, - id: PositionId::default_id(), } } - /// Create a new position with a specific ID. - /// - /// Used by Scanner to create positions with unique IDs. - pub fn new_with_id( - file_name: impl Into, - line: i32, - bol: i32, - cnum: i32, - id: PositionId, - ) -> Self { + /// Create a position at the start of a file. + pub fn at_file_start(file_name: StrIdx) -> Self { Self { - file_name: file_name.into(), - line, - bol, - cnum, - id, - } - } - - /// Create a position at the start of a file with a default ID. - pub fn at_file_start(file_name: impl Into) -> Self { - Self { - file_name: file_name.into(), + file_name, line: 1, bol: 0, cnum: 0, - id: PositionId::default_id(), } } @@ -193,14 +101,7 @@ impl Position { /// A location span in source code. /// /// This corresponds to `Location.t` in OCaml. -/// -/// # Identity -/// -/// Each Location has a unique `id` field for identity-based sharing in the -/// Marshal format. When you clone a Location, the id is copied (same identity). -/// This mostly matches OCaml's behavior where assigning a location to multiple -/// fields shares the same object. -#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct Location { /// Start position. pub loc_start: Position, @@ -208,98 +109,86 @@ pub struct Location { pub loc_end: Position, /// Whether this is a "ghost" location (compiler-generated). pub loc_ghost: bool, - /// Unique identity for sharing in Marshal format. - /// When cloning, this ID is preserved (same identity as original). - #[serde(default)] - pub id: LocationId, } impl Default for Location { fn default() -> Self { - Self::none() + Self { + loc_start: Position::default(), + loc_end: Position::default(), + loc_ghost: true, + } } } impl Location { - /// Create a new location from start and end positions with default ID. - /// For locations with proper identity tracking, use `from_positions_with_id()`. + /// Create a new location from start and end positions. pub fn from_positions(start: Position, end: Position) -> Self { Self { loc_start: start, loc_end: end, loc_ghost: false, - id: LocationId::default_id(), - } - } - - /// Create a new location from start and end positions with a specific ID. - /// Used by mk_loc() to create locations with unique IDs. - pub fn from_positions_with_id(start: Position, end: Position, id: LocationId) -> Self { - Self { - loc_start: start, - loc_end: end, - loc_ghost: false, - id, } } /// Create a location from character offsets in a file. /// /// This is a convenience constructor when you don't have full position info. - /// Positions get default (uninitialized) IDs. - pub fn new(file_name: &str, start_offset: usize, end_offset: usize) -> Self { + pub fn new(file_name: StrIdx, start_offset: usize, end_offset: usize) -> Self { Self { loc_start: Position { - file_name: file_name.to_string(), + file_name, line: 1, bol: 0, cnum: start_offset as i32, - id: PositionId::default_id(), }, loc_end: Position { - file_name: file_name.to_string(), + file_name, line: 1, bol: 0, cnum: end_offset as i32, - id: PositionId::default_id(), }, loc_ghost: false, - id: LocationId::default_id(), } } + /// Create a location for error reporting contexts where we don't have an arena. + /// Uses StrIdx(0) as a placeholder - the file name won't be resolved correctly + /// but this is only used for error display, not marshalling. + pub fn new_for_error(_file_name: &str, start_offset: usize, end_offset: usize) -> Self { + Self::new(StrIdx::default(), start_offset, end_offset) + } + /// Create a ghost location at the start of a file. - /// Positions get default (uninitialized) IDs. - pub fn in_file(name: impl Into) -> Self { - let name = name.into(); + pub fn in_file(file_name: StrIdx) -> Self { let pos = Position { - file_name: name, + file_name, line: 1, bol: 0, cnum: -1, - id: PositionId::default_id(), }; Self { - loc_start: pos.clone(), + loc_start: pos, loc_end: pos, loc_ghost: true, - id: LocationId::default_id(), } } /// Create a "none" location (placeholder). + /// Note: This creates a location with default StrIdx (0). + /// For proper "none" locations, use ParseArena::none_loc(). pub fn none() -> Self { - Self::in_file("_none_") + Self::default() } - /// Check if this is a "none" location. + /// Check if this is a "none" location (has default file name index). pub fn is_none(&self) -> bool { - self.loc_start.file_name == "_none_" + self.loc_start.file_name == StrIdx::default() } - /// Get the file name. - pub fn file_name(&self) -> &str { - &self.loc_start.file_name + /// Get the file name index. + pub fn file_name_idx(&self) -> StrIdx { + self.loc_start.file_name } /// Get the start line number. @@ -328,24 +217,20 @@ impl Location { } /// Create a ghost version of this location. - /// Note: Creates a new LocationId (different identity). pub fn ghostify(&self) -> Self { Self { - loc_start: self.loc_start.clone(), - loc_end: self.loc_end.clone(), + loc_start: self.loc_start, + loc_end: self.loc_end, loc_ghost: true, - id: LocationId::default_id(), } } /// Merge two locations into a span covering both. - /// Note: Creates a new LocationId (different identity). pub fn merge(&self, other: &Location) -> Self { Self { - loc_start: self.loc_start.clone(), - loc_end: other.loc_end.clone(), + loc_start: self.loc_start, + loc_end: other.loc_end, loc_ghost: self.loc_ghost && other.loc_ghost, - id: LocationId::default_id(), } } @@ -376,39 +261,10 @@ impl Location { } } -impl fmt::Display for Location { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let file = if self.file_name() == "_none_" { - "(unknown)" - } else { - self.file_name() - }; - - match self.normalize_range() { - None => write!(f, "{}", file), - Some((start_line, start_col, end_line, end_col)) => { - if start_line == end_line { - if start_col == end_col { - write!(f, "{}:{}:{}", file, start_line, start_col) - } else { - write!(f, "{}:{}:{}-{}", file, start_line, start_col, end_col) - } - } else { - write!( - f, - "{}:{}:{}-{}:{}", - file, start_line, start_col, end_line, end_col - ) - } - } - } - } -} - /// A value with an associated location. /// /// This corresponds to `'a Location.loc` in OCaml. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] pub struct Located { /// The value. pub txt: T, @@ -445,7 +301,8 @@ mod tests { #[test] fn test_position() { - let pos = Position::new("test.res", 5, 40, 45); + let file_name = StrIdx::default(); + let pos = Position::new(file_name, 5, 40, 45); assert_eq!(pos.column(), 5); assert_eq!(pos.column_1indexed(), 6); } @@ -459,18 +316,20 @@ mod tests { #[test] fn test_location_in_file() { - let loc = Location::in_file("test.res"); - assert_eq!(loc.file_name(), "test.res"); + let file_name = StrIdx(1); // Non-default index + let loc = Location::in_file(file_name); + assert_eq!(loc.file_name_idx(), file_name); assert!(loc.is_ghost()); } #[test] fn test_location_merge() { - let start = Position::new("test.res", 1, 0, 0); - let mid = Position::new("test.res", 1, 0, 5); - let end_pos = Position::new("test.res", 2, 10, 20); + let file_name = StrIdx::default(); + let start = Position::new(file_name, 1, 0, 0); + let mid = Position::new(file_name, 1, 0, 5); + let end_pos = Position::new(file_name, 2, 10, 20); - let loc1 = Location::from_positions(start, mid.clone()); + let loc1 = Location::from_positions(start, mid); let loc2 = Location::from_positions(mid, end_pos); let merged = loc1.merge(&loc2); @@ -478,29 +337,13 @@ mod tests { assert_eq!(merged.end_line(), 2); } - #[test] - fn test_location_display() { - let start = Position::new("test.res", 5, 40, 45); - let end_pos = Position::new("test.res", 5, 40, 50); - let loc = Location::from_positions(start, end_pos); - - assert_eq!(format!("{}", loc), "test.res:5:6-10"); - } - #[test] fn test_located() { - let located = Located::new("hello", Location::in_file("test.res")); + let file_name = StrIdx::default(); + let located = Located::new("hello", Location::in_file(file_name)); assert_eq!(located.txt, "hello"); let mapped = located.map(|s| s.to_uppercase()); assert_eq!(mapped.txt, "HELLO"); } - - #[test] - fn test_location_is_send_sync() { - fn assert_send_sync() {} - assert_send_sync::(); - assert_send_sync::(); - assert_send_sync::>(); - } } diff --git a/compiler-rust/src/parse_arena.rs b/compiler-rust/src/parse_arena.rs new file mode 100644 index 00000000000..3e5accfcb70 --- /dev/null +++ b/compiler-rust/src/parse_arena.rs @@ -0,0 +1,757 @@ +//! Arena for positions and locations during parsing. +//! +//! This module provides efficient storage for source locations in the AST. +//! Instead of storing full Position/Location values everywhere, we store +//! lightweight indices that can be compared cheaply. +//! +//! # Architecture +//! +//! - `PosIdx` and `LocIdx` are lightweight index types (4 bytes each) +//! - `ParseArena` contains arenas for positions and locations +//! - When parsing, positions are pushed to get indices +//! - During marshalling, indices are looked up to get actual values +//! +//! # Example +//! +//! ```ignore +//! use rescript_compiler::parse_arena::{ParseArena, LocIdx, Located}; +//! use rescript_compiler::location::Position; +//! +//! let mut arena = ParseArena::new(); +//! let start = arena.push_pos("test.res", 1, 0, 0); +//! let end = arena.push_pos("test.res", 1, 0, 10); +//! let loc = arena.mk_loc(start, end); +//! +//! let located = Located::new("hello", loc); +//! assert_eq!(located.txt, "hello"); +//! ``` + +use std::collections::HashMap; + +use serde::{Deserialize, Serialize}; + +use crate::arena::{Arena, ArenaIdx}; +use crate::intern::Interner; +use crate::location::{Location, Position}; +use crate::parser::longident::Longident; + +/// Key for position deduplication. +/// Two positions with the same (file_name, line, bol, cnum) are the same position. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +struct PosKey { + file_name: StrIdx, + line: i32, + bol: i32, + cnum: i32, +} + +impl PosKey { + fn from_position(pos: &Position) -> Self { + Self { + file_name: pos.file_name, + line: pos.line, + bol: pos.bol, + cnum: pos.cnum, + } + } +} + +// Re-export StrIdx for convenience +pub use crate::intern::StrIdx; + +// ============================================================================ +// Index Types +// ============================================================================ + +/// Index into the position arena. +/// +/// This is a lightweight handle (4 bytes) that can be copied and compared +/// cheaply. Two PosIdx values are equal if and only if they refer to the +/// same arena slot. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)] +pub struct PosIdx(pub u32); + +impl ArenaIdx for PosIdx { + fn from_u32(idx: u32) -> Self { + PosIdx(idx) + } + fn to_u32(self) -> u32 { + self.0 + } +} + +/// Index into the location arena. +/// +/// This is a lightweight handle (4 bytes) that can be copied and compared +/// cheaply. Two LocIdx values are equal if and only if they refer to the +/// same arena slot. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)] +pub struct LocIdx(pub u32); + +impl ArenaIdx for LocIdx { + fn from_u32(idx: u32) -> Self { + LocIdx(idx) + } + fn to_u32(self) -> u32 { + self.0 + } +} + +impl LocIdx { + /// Check if this is the "none" location (index 0). + /// The "none" location is pre-allocated at index 0 in every ParseArena. + pub fn is_none(&self) -> bool { + self.0 == 0 + } + + /// Create the "none" location index (same as default). + pub fn none() -> Self { + Self(0) + } +} + +/// Index into the longident arena. +/// +/// This is a lightweight handle (4 bytes) that can be copied and compared +/// cheaply. Two LidentIdx values are equal if and only if they refer to the +/// same arena slot. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)] +pub struct LidentIdx(pub u32); + +impl ArenaIdx for LidentIdx { + fn from_u32(idx: u32) -> Self { + LidentIdx(idx) + } + fn to_u32(self) -> u32 { + self.0 + } +} + +// ============================================================================ +// InternedLocation (stored in arena) +// ============================================================================ + +/// A location in a source file (stored in arena). +/// +/// This is stored in the ParseArena. Users work with `LocIdx` handles. +/// Note that `loc_start` and `loc_end` are `PosIdx`, not `Position`, so +/// locations reference positions by index rather than storing them inline. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct InternedLocation { + /// Start position index. + pub loc_start: PosIdx, + /// End position index. + pub loc_end: PosIdx, + /// Whether this is a "ghost" location (synthesized, not from source). + pub loc_ghost: bool, +} + +impl InternedLocation { + /// Create a new location from position indices. + pub fn new(start: PosIdx, end: PosIdx, ghost: bool) -> Self { + Self { + loc_start: start, + loc_end: end, + loc_ghost: ghost, + } + } +} + +impl Default for InternedLocation { + fn default() -> Self { + // Default to the "none" location (position index 0, ghost = true) + Self { + loc_start: PosIdx(0), + loc_end: PosIdx(0), + loc_ghost: true, + } + } +} + +// ============================================================================ +// ParseArena +// ============================================================================ + +/// Arena for positions and locations during parsing. +/// +/// This provides: +/// - Efficient storage: positions/locations stored once, referenced by index +/// - Lightweight handles: indices are 4 bytes, cheap to copy/compare +/// - Identity for marshalling: same index = same object +/// +/// This arena deduplicates positions by content - two positions with the same +/// (file_name, line, bol, cnum) will get the same index. This matches OCaml's +/// behavior where the same position captured at different times gets shared. +#[derive(Debug)] +pub struct ParseArena { + /// Arena of positions (returns PosIdx). + positions: Arena, + /// Arena of locations (returns LocIdx). + locations: Arena, + /// Arena of longidents (returns LidentIdx). + longidents: Arena, + /// Position deduplication table - maps position content to its index. + position_dedup: HashMap, + /// String arena for all identifier strings. + /// + /// Strings can be added in two ways: + /// - `intern(s)`: deduplicated, for static strings (same content = same StrIdx) + /// - `push_string(s)`: NOT deduplicated, for dynamic strings (each call = new StrIdx) + /// + /// At marshal time, same StrIdx = same object = shared via back-references. + strings: Interner, +} + +impl Default for ParseArena { + fn default() -> Self { + Self { + positions: Arena::default(), + locations: Arena::default(), + longidents: Arena::default(), + position_dedup: HashMap::new(), + strings: Interner::new(), + } + } +} + +impl ParseArena { + /// Create a new arena with the "none" position and location pre-allocated at index 0. + /// + /// This ensures that `LocIdx::default()` (which is `LocIdx(0)`) always refers to + /// a valid "none" location, even without calling `none_loc()` first. + pub fn new() -> Self { + let mut arena = Self::default(); + // Pre-allocate none file name and position at index 0 + // This way LocIdx::default() == LocIdx(0) is always valid + let none_file_idx = arena.strings.intern("_none_"); + let none_pos = Position::new(none_file_idx, 1, 0, -1); + let pos_idx = arena.positions.push(none_pos); + let none_loc = InternedLocation::new(pos_idx, pos_idx, true); + arena.locations.push(none_loc); + // Pre-allocate placeholder longident at index 0 + // This way LidentIdx(0) is always a valid "placeholder" identifier + let placeholder_idx = arena.strings.intern("placeholder"); + arena.longidents.push(Longident::Lident(placeholder_idx)); + arena + } + + /// Get the placeholder longident index (pre-allocated at index 0). + /// This is useful for creating placeholder AST nodes without mutating the arena. + pub fn placeholder_lid(&self) -> LidentIdx { + LidentIdx(0) + } + + /// Create a Located with the placeholder longident and given location. + pub fn placeholder_located(&self, loc: LocIdx) -> Located { + Located { + txt: self.placeholder_lid(), + loc, + } + } + + // ========== Position methods ========== + + /// Push a position into the arena and return its index. + /// Creates a fresh entry each time - sharing is achieved by passing the same + /// PosIdx through code paths (reference sharing), not by value deduplication. + pub fn push_position(&mut self, pos: Position) -> PosIdx { + let key = PosKey::from_position(&pos); + let idx = self.positions.push(pos); + // Register in dedup table only if not already there (for lookup purposes) + self.position_dedup.entry(key).or_insert(idx); + idx + } + + /// Get the index of a position if it exists in the dedup table. + /// Returns None if this position content hasn't been seen before. + #[allow(dead_code)] + pub fn get_position_idx(&self, pos: &Position) -> Option { + let key = PosKey::from_position(pos); + self.position_dedup.get(&key).copied() + } + + /// Push a position with deduplication - reuses an existing index if the position + /// content matches. + pub fn push_position_dedup(&mut self, pos: Position) -> PosIdx { + let key = PosKey::from_position(&pos); + if let Some(&idx) = self.position_dedup.get(&key) { + return idx; + } + let idx = self.positions.push(pos); + self.position_dedup.insert(key, idx); + idx + } + + /// Push a position from components. + /// Creates a fresh position each time (no deduplication). + /// This matches OCaml's behavior where each position is a separate object. + /// file_name should be an interned StrIdx (from arena.intern_string). + pub fn push_pos(&mut self, file_name: StrIdx, line: i32, bol: i32, cnum: i32) -> PosIdx { + self.positions.push(Position::new(file_name, line, bol, cnum)) + } + + /// Get the "none" position index (for _none_ file). + /// Returns the pre-allocated index 0. + pub fn none_pos(&self) -> PosIdx { + PosIdx(0) + } + + /// Look up a position by index. + pub fn get_position(&self, idx: PosIdx) -> &Position { + self.positions.get(idx) + } + + /// Get all positions (for marshalling). + pub fn positions(&self) -> &[Position] { + self.positions.as_slice() + } + + /// Get total number of positions. + pub fn position_count(&self) -> usize { + self.positions.len() + } + + // ========== Location methods ========== + + /// Push a location into the arena and return its index. + pub fn push_location(&mut self, loc: InternedLocation) -> LocIdx { + self.locations.push(loc) + } + + /// Push a location from position indices. + pub fn push_loc(&mut self, start: PosIdx, end: PosIdx, ghost: bool) -> LocIdx { + self.push_location(InternedLocation::new(start, end, ghost)) + } + + /// Create a location from two position indices and push it (non-ghost). + pub fn mk_loc(&mut self, start: PosIdx, end: PosIdx) -> LocIdx { + self.push_loc(start, end, false) + } + + /// Create a location from two raw positions (push both positions first). + /// Creates fresh positions - sharing is achieved by passing PosIdx through code paths. + pub fn mk_loc_from_positions(&mut self, start: &Position, end: &Position) -> LocIdx { + let start_idx = self.push_position(*start); + let end_idx = self.push_position(*end); + self.mk_loc(start_idx, end_idx) + } + + /// Create a location spanning from one location's start to another's end. + /// Reuses the existing PosIdx values to maintain position sharing. + pub fn mk_loc_spanning(&mut self, start_loc: LocIdx, end_loc: LocIdx) -> LocIdx { + let start_pos_idx = self.get_location(start_loc).loc_start; + let end_pos_idx = self.get_location(end_loc).loc_end; + self.mk_loc(start_pos_idx, end_pos_idx) + } + + /// Like mk_loc_spanning, but preserves the ghost flag from the start location. + /// Use this when the spanning location should inherit ghostness, e.g., for + /// sequence expressions in braced blocks where the first expression is ghost. + pub fn mk_loc_spanning_preserve_ghost(&mut self, start_loc: LocIdx, end_loc: LocIdx) -> LocIdx { + let start_info = self.get_location(start_loc); + let start_pos_idx = start_info.loc_start; + let is_ghost = start_info.loc_ghost; + let end_pos_idx = self.get_location(end_loc).loc_end; + self.push_loc(start_pos_idx, end_pos_idx, is_ghost) + } + + /// Get the "none" location index (ghost location with none positions). + /// Returns the pre-allocated index 0. + pub fn none_loc(&self) -> LocIdx { + LocIdx(0) + } + + /// Look up a location by index. + pub fn get_location(&self, idx: LocIdx) -> &InternedLocation { + self.locations.get(idx) + } + + /// Get all locations (for marshalling). + pub fn locations(&self) -> &[InternedLocation] { + self.locations.as_slice() + } + + /// Get total number of locations. + pub fn location_count(&self) -> usize { + self.locations.len() + } + + // ========== Location accessor helpers ========== + + /// Get the start position of a location. + pub fn loc_start(&self, idx: LocIdx) -> &Position { + let loc = self.get_location(idx); + self.get_position(loc.loc_start) + } + + /// Get the end position of a location. + pub fn loc_end(&self, idx: LocIdx) -> &Position { + let loc = self.get_location(idx); + self.get_position(loc.loc_end) + } + + /// Get the start position index of a location. + pub fn loc_start_idx(&self, idx: LocIdx) -> PosIdx { + self.get_location(idx).loc_start + } + + /// Get the end position index of a location. + pub fn loc_end_idx(&self, idx: LocIdx) -> PosIdx { + self.get_location(idx).loc_end + } + + /// Check if a location is ghost. + pub fn loc_ghost(&self, idx: LocIdx) -> bool { + self.get_location(idx).loc_ghost + } + + /// Create a ghost version of an existing location. + /// Returns a new LocIdx with the same positions but loc_ghost=true. + pub fn mk_ghost_loc(&mut self, idx: LocIdx) -> LocIdx { + let loc = self.get_location(idx); + let start = loc.loc_start; + let end = loc.loc_end; + self.push_loc(start, end, true) + } + + /// Reconstruct a full Location struct from a LocIdx. + /// Useful for code that needs the full Location type (e.g., printer). + pub fn to_location(&self, idx: LocIdx) -> Location { + let loc = self.get_location(idx); + Location { + loc_start: self.get_position(loc.loc_start).clone(), + loc_end: self.get_position(loc.loc_end).clone(), + loc_ghost: loc.loc_ghost, + } + } + + /// Convert a full Location to a LocIdx by pushing its positions to the arena. + /// Useful for migrating code that creates Location values. + /// Creates fresh positions to match OCaml behavior. + pub fn from_location(&mut self, loc: &Location) -> LocIdx { + let start_idx = self.positions.push(loc.loc_start); + let end_idx = self.positions.push(loc.loc_end); + self.push_loc(start_idx, end_idx, loc.loc_ghost) + } + + /// Convert a Located using crate::location::Location to one using LocIdx. + pub fn from_located(&mut self, located: &crate::location::Located) -> Located { + Located { + txt: located.txt.clone(), + loc: self.from_location(&located.loc), + } + } + + /// Convert a Located using LocIdx to one using crate::location::Location. + pub fn to_located(&self, located: &Located) -> crate::location::Located { + crate::location::Located { + txt: located.txt.clone(), + loc: self.to_location(located.loc), + } + } + + // ======================================================================== + // String interning + // ======================================================================== + + /// Intern a string, returning its index. + /// + /// If the string was previously interned, returns the existing index. + /// Otherwise, stores the string and returns a new index. + /// + /// Use this for strings that should be shared in Marshal output + /// (matching OCaml's interning behavior). + pub fn intern(&mut self, s: &str) -> StrIdx { + self.strings.intern(s) + } + + /// Get an interned string by index. + pub fn get_interned(&self, idx: StrIdx) -> &str { + self.strings.get(idx) + } + + // ======================================================================== + // Longident arena + // ======================================================================== + + /// Push a longident into the arena and return its index. + pub fn push_longident(&mut self, lid: Longident) -> LidentIdx { + self.longidents.push(lid) + } + + /// Push a simple identifier (Lident) with a dynamic string (from tokens). + /// + /// Each call creates a new StrIdx, so same content != same identity. + /// Use for user identifiers parsed from source (variable names, etc.). + pub fn push_lident(&mut self, name: impl Into) -> LidentIdx { + let str_idx = self.strings.push(name.into()); + self.longidents.push(Longident::Lident(str_idx)) + } + + /// Push a simple identifier (Lident) with a static string (interned). + /// + /// For static strings (literals in Rust source code), this deduplicates: + /// same content = same StrIdx = shared during marshalling. + /// + /// Use for operators from Token::to_string and hardcoded identifiers + /// in the parser like "not", "::", "()", etc. + pub fn push_lident_static(&mut self, name: &'static str) -> LidentIdx { + let str_idx = self.strings.intern(name); + self.longidents.push(Longident::Lident(str_idx)) + } + + /// Push a dotted identifier (Ldot) with a dynamic string. + pub fn push_ldot(&mut self, prefix: LidentIdx, name: impl Into) -> LidentIdx { + let str_idx = self.strings.push(name.into()); + let prefix_lid = self.get_longident(prefix).clone(); + self.longidents.push(Longident::Ldot(Box::new(prefix_lid), str_idx)) + } + + /// Push a dotted identifier (Ldot) with a static string. + pub fn push_ldot_static(&mut self, prefix: LidentIdx, name: &'static str) -> LidentIdx { + let str_idx = self.strings.intern(name); + let prefix_lid = self.get_longident(prefix).clone(); + self.longidents.push(Longident::Ldot(Box::new(prefix_lid), str_idx)) + } + + /// Push a functor application (Lapply) into the arena. + pub fn push_lapply(&mut self, functor: LidentIdx, arg: LidentIdx) -> LidentIdx { + let func_lid = self.get_longident(functor).clone(); + let arg_lid = self.get_longident(arg).clone(); + self.longidents.push(Longident::Lapply(Box::new(func_lid), Box::new(arg_lid))) + } + + /// Look up a longident by index. + pub fn get_longident(&self, idx: LidentIdx) -> &Longident { + self.longidents.get(idx) + } + + /// Get total number of longidents. + pub fn longident_count(&self) -> usize { + self.longidents.len() + } + + /// Get the string content for a StrIdx. + pub fn get_string(&self, idx: StrIdx) -> &str { + self.strings.get(idx) + } + + /// Intern a string (returns existing idx if already interned). + pub fn intern_string(&mut self, s: &str) -> StrIdx { + self.strings.intern(s) + } + + /// Push a string without deduplication (for dynamic user-input strings). + pub fn push_string(&mut self, s: String) -> StrIdx { + self.strings.push(s) + } + + /// Check if a longident is a simple Lident with the given name. + pub fn is_lident(&self, idx: LidentIdx, name: &str) -> bool { + match self.get_longident(idx) { + Longident::Lident(str_idx) => self.strings.get(*str_idx) == name, + _ => false, + } + } + + /// Check if a longident is a simple Lident (not dotted). + pub fn is_simple_lident(&self, idx: LidentIdx) -> bool { + matches!(self.get_longident(idx), Longident::Lident(_)) + } + + /// Check if a longident is an Ldot (qualified/dotted identifier). + pub fn is_ldot(&self, idx: LidentIdx) -> bool { + matches!(self.get_longident(idx), Longident::Ldot(..)) + } + + /// Get the last component of a longident as a string. + pub fn lident_last(&self, idx: LidentIdx) -> &str { + let str_idx = self.get_longident(idx).last_idx(); + self.strings.get(str_idx) + } + + /// Convert a Located to Located. + /// Useful when you need to match on the Longident structure. + pub fn to_longident_loc(&self, loc: &Located) -> crate::location::Located { + crate::location::Located { + txt: self.get_longident(loc.txt).clone(), + loc: self.to_location(loc.loc), + } + } +} + +// ============================================================================ +// Located - A value with its source location +// ============================================================================ + +/// A value annotated with its source location (using LocIdx). +/// +/// This is equivalent to OCaml's `'a loc` type, but uses `LocIdx` for efficiency. +/// This is the type to use in the AST for minimal memory footprint. +/// +/// Note: There is also `crate::location::Located` which stores a full +/// `Location` instead of `LocIdx`. Use that when you don't have access to +/// a ParseArena or need the full location data inline. +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct Located { + /// The value. + pub txt: T, + /// Location in source (as index). + pub loc: LocIdx, +} + +// Implement Copy for Located when T: Copy (e.g., Located) +impl Copy for Located {} + +impl Located { + /// Create a new located value. + pub fn new(txt: T, loc: LocIdx) -> Self { + Self { txt, loc } + } + + /// Create a located value with the default "none" location. + /// + /// This uses `LocIdx::default()` which is `LocIdx(0)`, the pre-allocated + /// none location in every ParseArena. + pub fn mknoloc(txt: T) -> Self { + Self { + txt, + loc: LocIdx::default(), + } + } + + /// Map the value while keeping the location. + pub fn map U>(self, f: F) -> Located { + Located { + txt: f(self.txt), + loc: self.loc, + } + } + + /// Get a reference to the text. + pub fn as_ref(&self) -> Located<&T> { + Located { + txt: &self.txt, + loc: self.loc, + } + } +} + +// ============================================================================ +// Tests +// ============================================================================ + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_position_push() { + let mut arena = ParseArena::new(); + let base_count = arena.position_count(); + assert_eq!(base_count, 1); // Pre-allocated none position + + let idx1 = arena.push_pos("test.res", 1, 0, 5); + let idx2 = arena.push_pos("test.res", 1, 0, 5); + let idx3 = arena.push_pos("test.res", 1, 0, 10); + + // Each push creates a new entry (no deduplication) + assert_ne!(idx1, idx2); + assert_ne!(idx1, idx3); + assert_ne!(idx2, idx3); + + assert_eq!(arena.position_count(), base_count + 3); + } + + #[test] + fn test_location_push() { + let mut arena = ParseArena::new(); + let base_count = arena.location_count(); + assert_eq!(base_count, 1); // Pre-allocated none location + + let start = arena.push_pos("test.res", 1, 0, 0); + let end = arena.push_pos("test.res", 1, 0, 10); + + let loc1 = arena.mk_loc(start, end); + let loc2 = arena.mk_loc(start, end); + + // Each push creates a new entry (no deduplication) + assert_ne!(loc1, loc2); + + assert_eq!(arena.location_count(), base_count + 2); + } + + #[test] + fn test_none_at_index_zero() { + let arena = ParseArena::new(); + + let none_pos = arena.none_pos(); + let none_loc = arena.none_loc(); + + assert_eq!(none_pos, PosIdx(0)); + assert_eq!(none_loc, LocIdx(0)); + assert_eq!(LocIdx::default(), none_loc); + + let pos = arena.get_position(none_pos); + assert_eq!(pos.file_name, "_none_"); + assert!(arena.loc_ghost(none_loc)); + } + + #[test] + fn test_located() { + let arena = ParseArena::new(); + let loc = arena.none_loc(); + + let located = Located::new("hello".to_string(), loc); + assert_eq!(located.txt, "hello"); + assert_eq!(located.loc, loc); + } + + #[test] + fn test_mk_loc_from_positions() { + let mut arena = ParseArena::new(); + + let start = Position::new("test.res", 1, 0, 0); + let end = Position::new("test.res", 1, 0, 10); + + let loc = arena.mk_loc_from_positions(&start, &end); + + assert_eq!(arena.loc_start(loc).line, 1); + assert_eq!(arena.loc_end(loc).cnum, 10); + } + + #[test] + fn test_to_location() { + let mut arena = ParseArena::new(); + + let start = Position::new("test.res", 1, 0, 0); + let end = Position::new("test.res", 1, 0, 10); + + let loc_idx = arena.mk_loc_from_positions(&start, &end); + let loc = arena.to_location(loc_idx); + + assert_eq!(loc.loc_start.line, 1); + assert_eq!(loc.loc_end.cnum, 10); + assert!(!loc.loc_ghost); + } + + #[test] + fn test_mk_loc_spanning() { + let mut arena = ParseArena::new(); + + let pos1 = arena.push_pos("test.res", 1, 0, 0); + let pos2 = arena.push_pos("test.res", 1, 0, 5); + let pos3 = arena.push_pos("test.res", 2, 20, 25); + let pos4 = arena.push_pos("test.res", 2, 20, 30); + + let loc1 = arena.mk_loc(pos1, pos2); + let loc2 = arena.mk_loc(pos3, pos4); + + let spanning = arena.mk_loc_spanning(loc1, loc2); + + assert_eq!(arena.loc_start(spanning).line, 1); + assert_eq!(arena.loc_start(spanning).cnum, 0); + assert_eq!(arena.loc_end(spanning).line, 2); + assert_eq!(arena.loc_end(spanning).cnum, 30); + } +} diff --git a/compiler-rust/src/parser/ast.rs b/compiler-rust/src/parser/ast.rs index a33d724fd02..d3ed4049dac 100644 --- a/compiler-rust/src/parser/ast.rs +++ b/compiler-rust/src/parser/ast.rs @@ -9,14 +9,19 @@ #![allow(non_camel_case_types)] #![allow(missing_docs)] -use crate::location::{Located, Location, Position}; +use crate::location::Position; +use crate::parse_arena::{LidentIdx, Located, LocIdx, StrIdx}; use serde::{Deserialize, Serialize}; use super::longident::Longident; /// Re-export Located for convenience. +/// Note: Located uses LocIdx for efficient arena-based storage. pub type Loc = Located; +/// Location type alias - uses arena index for efficient storage. +pub type Location = LocIdx; + /// A string with location information. pub type StringLoc = Located; @@ -96,15 +101,17 @@ pub enum Variance { } /// Argument label for function parameters. -/// Note: Labelled and Optional include a location to match OCaml's `Labelled of string loc`. -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +/// Uses Located to allow sharing with Longident::Lident when the same +/// identifier is used for both label and value (punning). +/// The location matches OCaml's `Labelled of string loc`. +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] pub enum ArgLabel { /// No label. Nolabel, /// Labeled argument: `~foo` with location. - Labelled(Located), + Labelled(Located), /// Optional argument: `?foo` with location. - Optional(Located), + Optional(Located), } impl ArgLabel { @@ -118,16 +125,16 @@ impl ArgLabel { matches!(self, ArgLabel::Optional(_)) } - /// Get the label name, if any. - pub fn name(&self) -> Option<&str> { + /// Get the label StrIdx, if any. + pub fn name_idx(&self) -> Option { match self { ArgLabel::Nolabel => None, - ArgLabel::Labelled(s) | ArgLabel::Optional(s) => Some(&s.txt), + ArgLabel::Labelled(s) | ArgLabel::Optional(s) => Some(s.txt), } } - /// Get the located string, if any. - pub fn located(&self) -> Option<&Located> { + /// Get the located StrIdx, if any. + pub fn located(&self) -> Option<&Located> { match self { ArgLabel::Nolabel => None, ArgLabel::Labelled(s) | ArgLabel::Optional(s) => Some(s), @@ -223,7 +230,7 @@ pub enum CoreTypeDesc { /// Tuple type: `(T1, T2, ..., Tn)`. Ptyp_tuple(Vec), /// Type constructor: `tconstr` or `T tconstr` or `(T1, ..., Tn) tconstr`. - Ptyp_constr(Loc, Vec), + Ptyp_constr(Loc, Vec), /// Object type: `{. field: T, ... }`. Ptyp_object(Vec, ClosedFlag), /// Type alias: `T as 'a`. @@ -239,7 +246,7 @@ pub enum CoreTypeDesc { } /// Package type: `module S with type t = T`. -pub type PackageType = (Loc, Vec<(Loc, CoreType)>); +pub type PackageType = (Loc, Vec<(Loc, CoreType)>); /// Row field in a polymorphic variant. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -290,7 +297,7 @@ pub enum PatternDesc { /// Tuple: `(P1, P2, ..., Pn)`. Ppat_tuple(Vec), /// Constructor: `C` or `C(P)`. - Ppat_construct(Loc, Option>), + Ppat_construct(Loc, Option>), /// Variant: `\`A` or `\`A(P)`. Ppat_variant(Label, Option>), /// Record: `{l1: P1, ..., ln: Pn}`. @@ -302,7 +309,7 @@ pub enum PatternDesc { /// Constraint: `(P: T)`. Ppat_constraint(Box, CoreType), /// Type pattern: `#tconstr`. - Ppat_type(Loc), + Ppat_type(Loc), /// Unpack: `module(P)`. Ppat_unpack(StringLoc), /// Exception: `exception P`. @@ -310,14 +317,14 @@ pub enum PatternDesc { /// Extension: `[%id]`. Ppat_extension(Extension), /// Open: `M.(P)`. - Ppat_open(Loc, Box), + Ppat_open(Loc, Box), } /// A record field in a pattern. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct PatternRecordField { /// Field name. - pub lid: Loc, + pub lid: Loc, /// Pattern. pub pat: Pattern, /// Whether this is optional. @@ -343,7 +350,7 @@ pub struct Expression { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub enum ExpressionDesc { /// Identifier: `x` or `M.x`. - Pexp_ident(Loc), + Pexp_ident(Loc), /// Constant: `1`, `'a'`, `"hello"`. Pexp_constant(Constant), /// Let binding: `let P = E in E'`. @@ -371,15 +378,15 @@ pub enum ExpressionDesc { /// Tuple: `(E1, E2, ..., En)`. Pexp_tuple(Vec), /// Constructor: `C` or `C(E)`. - Pexp_construct(Loc, Option>), + Pexp_construct(Loc, Option>), /// Variant: `\`A` or `\`A(E)`. Pexp_variant(Label, Option>), /// Record: `{l1: E1, ..., ln: En}` or `{...E, l1: E1, ...}`. Pexp_record(Vec, Option>), /// Field access: `E.l`. - Pexp_field(Box, Loc), + Pexp_field(Box, Loc), /// Field set: `E.l = E'`. - Pexp_setfield(Box, Loc, Box), + Pexp_setfield(Box, Loc, Box), /// Array: `[E1, ..., En]`. Pexp_array(Vec), /// If-then-else: `if E1 { E2 } else { E3 }`. @@ -413,7 +420,7 @@ pub enum ExpressionDesc { /// Pack: `module(ME)`. Pexp_pack(ModuleExpr), /// Open: `M.{ E }` or `open M; E`. - Pexp_open(OverrideFlag, Loc, Box), + Pexp_open(OverrideFlag, Loc, Box), /// Extension: `[%id]`. Pexp_extension(Extension), /// Await: `await E`. @@ -426,7 +433,7 @@ pub enum ExpressionDesc { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ExpressionRecordField { /// Field name. - pub lid: Loc, + pub lid: Loc, /// Expression. pub expr: Expression, /// Whether this is optional. @@ -481,9 +488,9 @@ pub enum JsxTagName { /// Lowercase tag: `div`. Lower(String), /// Qualified lowercase: `Mod.div`. - QualifiedLower { path: Longident, name: String }, + QualifiedLower { path: LidentIdx, name: String }, /// Uppercase tag (component): `Button`. - Upper(Longident), + Upper(LidentIdx), /// Invalid tag name (for error recovery). Invalid(String), } @@ -568,7 +575,7 @@ pub struct ModuleExpr { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub enum ModuleExprDesc { /// Module identifier: `M`. - Pmod_ident(Loc), + Pmod_ident(Loc), /// Module structure: `{ ... }`. Pmod_structure(Vec), /// Functor: `(X: S) => ME`. @@ -598,7 +605,7 @@ pub struct ModuleType { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub enum ModuleTypeDesc { /// Module type identifier: `S`. - Pmty_ident(Loc), + Pmty_ident(Loc), /// Signature: `{ ... }`. Pmty_signature(Vec), /// Functor type: `(X: S) => MT`. @@ -610,20 +617,20 @@ pub enum ModuleTypeDesc { /// Extension: `[%id]`. Pmty_extension(Extension), /// Alias: `module M`. - Pmty_alias(Loc), + Pmty_alias(Loc), } /// With constraint. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub enum WithConstraint { /// Type constraint: `type t = T`. - Pwith_type(Loc, TypeDeclaration), + Pwith_type(Loc, TypeDeclaration), /// Module constraint: `module M = M'`. - Pwith_module(Loc, Loc), + Pwith_module(Loc, Loc), /// Type substitution: `type t := T`. - Pwith_typesubst(Loc, TypeDeclaration), + Pwith_typesubst(Loc, TypeDeclaration), /// Module substitution: `module M := M'`. - Pwith_modsubst(Loc, Loc), + Pwith_modsubst(Loc, Loc), } // ============================================================================ @@ -804,7 +811,7 @@ pub struct LabelDeclaration { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct TypeExtension { /// Extended type. - pub ptyext_path: Loc, + pub ptyext_path: Loc, /// Type parameters. pub ptyext_params: Vec<(CoreType, Variance)>, /// Constructors. @@ -834,7 +841,7 @@ pub enum ExtensionConstructorKind { /// Declaration: `C of T`. Pext_decl(ConstructorArguments, Option), /// Rebind: `C = D`. - Pext_rebind(Loc), + Pext_rebind(Loc), } /// Module binding: `module M = ME`. @@ -880,7 +887,7 @@ pub struct ModuleTypeDeclaration { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct OpenDescription { /// Opened module. - pub popen_lid: Loc, + pub popen_lid: Loc, /// Override flag. pub popen_override: OverrideFlag, /// Location. diff --git a/compiler-rust/src/parser/benchmark.rs b/compiler-rust/src/parser/benchmark.rs index e781d690a9e..dc61a439d32 100644 --- a/compiler-rust/src/parser/benchmark.rs +++ b/compiler-rust/src/parser/benchmark.rs @@ -89,9 +89,10 @@ fn benchmark_ocaml_parser(file_path: &str, iterations: u32) -> Option /// Run a benchmark comparing Rust and OCaml parsers pub fn run_benchmark(name: &str, file_path: &str) -> Option { - // Use lossy UTF-8 conversion (like OCaml) to handle files with invalid bytes + // Read file as raw bytes, converting each byte to a char (Latin-1 encoding). + // This matches OCaml's byte-level string handling where each byte is a character. let bytes = std::fs::read(file_path).ok()?; - let source = String::from_utf8_lossy(&bytes).into_owned(); + let source: String = bytes.iter().map(|&b| b as char).collect(); let source_size = source.len(); // Warm up diff --git a/compiler-rust/src/parser/code_frame.rs b/compiler-rust/src/parser/code_frame.rs index b70e631a05f..0ef3798d025 100644 --- a/compiler-rust/src/parser/code_frame.rs +++ b/compiler-rust/src/parser/code_frame.rs @@ -65,6 +65,26 @@ fn leading_space_count(s: &str) -> usize { s.chars().take_while(|&c| c == ' ').count() } +/// Break a long line into chunks of max_width characters. +/// Matches OCaml's `break_long_line` in code_frame.ml. +fn break_long_line(max_width: usize, line: &str) -> Vec<&str> { + if max_width == 0 || line.is_empty() { + return vec![line]; + } + let mut result = Vec::new(); + let mut pos = 0; + let len = line.len(); + while pos < len { + let chunk_length = max_width.min(len - pos); + result.push(&line[pos..pos + chunk_length]); + pos += chunk_length; + } + if result.is_empty() { + result.push(line); + } + result +} + /// Gutter content - either a line number or elided marker. #[derive(Clone)] enum Gutter { @@ -104,7 +124,7 @@ pub fn print(src: &str, start_pos: &Position, end_pos: &Position) -> String { let max_line_digits = digits_count(last_shown_line); // 3 for separator + the 2 spaces around it - let _line_width = 78 - max_line_digits - indent - 3; + let line_width = 78 - max_line_digits - indent - 3; // Extract the relevant portion of source let lines: Vec<(Gutter, &str)> = if start_offset < end_offset && end_offset <= src.len() { @@ -149,7 +169,7 @@ pub fn print(src: &str, start_pos: &Position, end_pos: &Position) -> String { let separator = if leading_space_to_cut == 0 { "│" } else { "┆" }; - // Process lines with highlighting info + // Process lines with highlighting info, breaking long lines into chunks let processed_lines: Vec = lines .iter() .map(|(gutter, line)| { @@ -159,48 +179,58 @@ pub fn print(src: &str, start_pos: &Position, end_pos: &Position) -> String { "" }; - let content = match gutter { - Gutter::Elided => vec![HighlightedString { - s: stripped.to_string(), - start: 0, - end: 0, - }], - Gutter::Number(line_number) => { - let highlight_start_col = - (start_pos.cnum - start_pos.bol) as usize; - let highlight_end_col = (end_pos.cnum - end_pos.bol) as usize; - - let start = if *line_number == highlight_line_start { - highlight_start_col.saturating_sub(leading_space_to_cut) - } else { - 0 - }; - - let end = if *line_number < highlight_line_start { - 0 - } else if *line_number == highlight_line_start - && *line_number == highlight_line_end - { - highlight_end_col.saturating_sub(leading_space_to_cut) - } else if *line_number == highlight_line_start { - stripped.len() - } else if *line_number > highlight_line_start - && *line_number < highlight_line_end - { - stripped.len() - } else if *line_number == highlight_line_end { - highlight_end_col.saturating_sub(leading_space_to_cut) - } else { - 0 - }; - - vec![HighlightedString { - s: stripped.to_string(), - start, - end, - }] - } - }; + // Break long lines into chunks matching OCaml's break_long_line + let chunks = break_long_line(line_width, stripped); + + let content: Vec = chunks + .iter() + .enumerate() + .map(|(i, chunk)| { + match gutter { + Gutter::Elided => HighlightedString { + s: chunk.to_string(), + start: 0, + end: 0, + }, + Gutter::Number(line_number) => { + let highlight_start_col = + (start_pos.cnum - start_pos.bol) as usize; + let highlight_end_col = (end_pos.cnum - end_pos.bol) as usize; + + // OCaml: start only applies to first chunk (i = 0) + let start = if i == 0 && *line_number == highlight_line_start { + highlight_start_col.saturating_sub(leading_space_to_cut) + } else { + 0 + }; + + let end = if *line_number < highlight_line_start { + 0 + } else if *line_number == highlight_line_start + && *line_number == highlight_line_end + { + highlight_end_col.saturating_sub(leading_space_to_cut) + } else if *line_number == highlight_line_start { + chunk.len() + } else if *line_number > highlight_line_start + && *line_number < highlight_line_end + { + chunk.len() + } else if *line_number == highlight_line_end { + highlight_end_col.saturating_sub(leading_space_to_cut) + } else { + 0 + }; + + HighlightedString { + s: chunk.to_string(), + start, + end, + } + } + } + }) + .collect(); Line { gutter: gutter.clone(), @@ -225,13 +255,17 @@ pub fn print(src: &str, start_pos: &Position, end_pos: &Position) -> String { buf.push_str(" ...\n"); } Gutter::Number(line_number) => { - for hs in &line.content { - // Draw gutter with line number - let num_str = line_number.to_string(); - for _ in 0..(max_line_digits + indent - num_str.len()) { + for (i, hs) in line.content.iter().enumerate() { + // OCaml: first chunk shows line number, continuation chunks show empty gutter + let gutter_content = if i == 0 { + line_number.to_string() + } else { + String::new() + }; + for _ in 0..(max_line_digits + indent - gutter_content.len()) { buf.push(' '); } - buf.push_str(&num_str); + buf.push_str(&gutter_content); buf.push(' '); buf.push_str(separator); buf.push(' '); @@ -249,8 +283,9 @@ pub fn print(src: &str, start_pos: &Position, end_pos: &Position) -> String { /// Format a location as "filename:line:col" or "filename:line:col-endcol" pub fn format_location(filename: &str, start_pos: &Position, end_pos: &Position) -> String { + // OCaml uses 1-indexed columns: col = pos_cnum - pos_bol + 1 let start_col = start_pos.cnum - start_pos.bol + 1; - let end_col = end_pos.cnum - end_pos.bol; + let end_col = end_pos.cnum - end_pos.bol; // OCaml doesn't add +1 for end (it's exclusive) if start_pos.line == end_pos.line && end_col > start_col { format!("{}:{}:{}-{}", filename, start_pos.line, start_col, end_col) diff --git a/compiler-rust/src/parser/comment_table.rs b/compiler-rust/src/parser/comment_table.rs index bd18cd89e82..67165ac2feb 100644 --- a/compiler-rust/src/parser/comment_table.rs +++ b/compiler-rust/src/parser/comment_table.rs @@ -6,21 +6,69 @@ //! This is a 1:1 port of OCaml's `res_comments_table.ml`. use crate::location::Location; -use crate::parser::ast::*; +use crate::parse_arena::{LidentIdx, LocIdx, ParseArena}; +use crate::parser::ast::{ + ArgLabel, Attribute, Case, ConstructorArguments, ConstructorDeclaration, CoreType, + CoreTypeDesc, Expression, ExpressionDesc, Extension, + ExtensionConstructor, ExtensionConstructorKind, IncludeDeclaration, IncludeDescription, + JsxElement, JsxProp, + LabelDeclaration, Loc, ModuleBinding, ModuleDeclaration, ModuleExpr, ModuleExprDesc, + ModuleType, ModuleTypeDeclaration, ModuleTypeDesc, ObjectField, OpenDescription, Pattern, + PatternDesc, RowField, SignatureItem, + SignatureItemDesc, StructureItem, StructureItemDesc, TypeDeclaration, + TypeExtension, TypeKind, ValueBinding, ValueDescription, WithConstraint, +}; use crate::parser::ast::Payload::{PPat, PSig, PStr, PTyp}; use crate::parser::comment::Comment; use crate::parser::longident::Longident; +use crate::parser::parsetree_viewer; use std::collections::HashMap; +/// Position-based key for comment lookup. +/// Uses (start_cnum, end_cnum) to uniquely identify a location span. +/// This allows looking up comments by position even when LocIdx values differ. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct PosRange { + pub start: i32, + pub end: i32, +} + +impl PosRange { + pub fn from_loc(loc: LocIdx, arena: &ParseArena) -> Self { + let start = arena.loc_start(loc); + let end = arena.loc_end(loc); + Self { + start: start.cnum, + end: end.cnum, + } + } + + pub fn from_location(loc: &Location) -> Self { + Self { + start: loc.loc_start.cnum, + end: loc.loc_end.cnum, + } + } + + /// Special "none" range for file-level comments + pub fn none() -> Self { + Self { start: -1, end: -1 } + } +} + /// A comment table that maps locations to their associated comments. +/// +/// Uses position-based keys (PosRange) like OCaml's Location.t hash keys. +/// This ensures locations with the same positions hash to the same key, +/// regardless of which LocIdx they were created from. #[derive(Debug, Clone, Default)] pub struct CommentTable { - /// Comments that appear before a location. - pub leading: HashMap>, - /// Comments that appear inside a location (e.g., inside a block). - pub inside: HashMap>, - /// Comments that appear after a location. - pub trailing: HashMap>, + /// Comments that appear before a location (indexed by position). + pub leading: HashMap>, + /// Comments that appear inside a location (indexed by position). + pub inside: HashMap>, + /// Comments that appear after a location (indexed by position). + pub trailing: HashMap>, } impl CommentTable { @@ -42,120 +90,113 @@ impl CommentTable { } } - /// Attach comments to a location in the given table. - fn attach(table: &mut HashMap>, loc: Location, comments: Vec) { - if !comments.is_empty() { - table.insert(loc, comments); - } + /// Remove and return leading comments for a location. + /// Like OCaml's Hashtbl.find/remove, this uses position-based keys. + pub fn remove_leading_comments_by_loc(&mut self, loc: LocIdx, arena: &ParseArena) -> Vec { + let pos_range = PosRange::from_loc(loc, arena); + self.leading.remove(&pos_range).unwrap_or_default() } - /// Check if there are leading comments for a location. - pub fn has_leading_comments(&self, loc: &Location) -> bool { - self.leading.contains_key(loc) + /// Remove and return trailing comments for a location. + /// Like OCaml's Hashtbl.find/remove, this uses position-based keys. + pub fn remove_trailing_comments_by_loc(&mut self, loc: LocIdx, arena: &ParseArena) -> Vec { + let pos_range = PosRange::from_loc(loc, arena); + self.trailing.remove(&pos_range).unwrap_or_default() } - /// Check if there are trailing comments for a location. - pub fn has_trailing_comments(&self, loc: &Location) -> bool { - self.trailing.contains_key(loc) + /// Remove and return inside comments for a location. + /// Like OCaml's Hashtbl.find/remove, this uses position-based keys. + pub fn remove_inside_comments_by_loc(&mut self, loc: LocIdx, arena: &ParseArena) -> Vec { + let pos_range = PosRange::from_loc(loc, arena); + self.inside.remove(&pos_range).unwrap_or_default() } - /// Check if there are inside comments for a location. - pub fn has_inside_comments(&self, loc: &Location) -> bool { - self.inside.contains_key(loc) + /// Remove and return leading comments by position range. + pub fn remove_leading_comments_by_pos(&mut self, pos_range: PosRange) -> Vec { + self.leading.remove(&pos_range).unwrap_or_default() } - /// Get leading comments for a location. - pub fn get_leading_comments(&self, loc: &Location) -> Option<&Vec> { - self.leading.get(loc) + /// Remove and return trailing comments by position range. + pub fn remove_trailing_comments_by_pos(&mut self, pos_range: PosRange) -> Vec { + self.trailing.remove(&pos_range).unwrap_or_default() } - /// Get trailing comments for a location. - pub fn get_trailing_comments(&self, loc: &Location) -> Option<&Vec> { - self.trailing.get(loc) + /// Remove and return inside comments by position range. + pub fn remove_inside_comments_by_pos(&mut self, pos_range: PosRange) -> Vec { + self.inside.remove(&pos_range).unwrap_or_default() } - /// Get inside comments for a location. - pub fn get_inside_comments(&self, loc: &Location) -> Option<&Vec> { - self.inside.get(loc) + /// Attach leading comments to a location (position-based, like OCaml). + pub fn attach_leading(&mut self, loc: LocIdx, comments: Vec, arena: &ParseArena) { + if !comments.is_empty() { + let pos_range = PosRange::from_loc(loc, arena); + self.leading.insert(pos_range, comments); + } } - /// Remove and return leading comments for a location. - pub fn remove_leading_comments(&mut self, loc: &Location) -> Vec { - self.leading.remove(loc).unwrap_or_default() + /// Attach trailing comments to a location (position-based, like OCaml). + pub fn attach_trailing(&mut self, loc: LocIdx, comments: Vec, arena: &ParseArena) { + if !comments.is_empty() { + let pos_range = PosRange::from_loc(loc, arena); + self.trailing.insert(pos_range, comments); + } } - /// Remove and return trailing comments for a location. - pub fn remove_trailing_comments(&mut self, loc: &Location) -> Vec { - self.trailing.remove(loc).unwrap_or_default() + /// Attach inside comments to a location (position-based, like OCaml). + pub fn attach_inside(&mut self, loc: LocIdx, comments: Vec, arena: &ParseArena) { + if !comments.is_empty() { + let pos_range = PosRange::from_loc(loc, arena); + self.inside.insert(pos_range, comments); + } } - /// Remove and return inside comments for a location. - pub fn remove_inside_comments(&mut self, loc: &Location) -> Vec { - self.inside.remove(loc).unwrap_or_default() + /// Check if there are leading comments for a location. + pub fn has_leading_comments(&self, loc: LocIdx, arena: &ParseArena) -> bool { + let pos_range = PosRange::from_loc(loc, arena); + self.leading.contains_key(&pos_range) } - /// Get the first leading comment for a location (if any). - pub fn get_first_leading_comment(&self, loc: &Location) -> Option<&Comment> { - self.leading.get(loc).and_then(|comments| comments.first()) - } - - /// Walk a structure and attach comments to appropriate AST nodes. - /// - /// This is a simplified implementation that attaches comments based on position. - /// A full implementation would walk the entire AST tree. - pub fn walk_structure(&mut self, structure: &[StructureItem], comments: Vec) { - if comments.is_empty() || structure.is_empty() { - if !comments.is_empty() { - // Attach remaining comments to "inside" of the file - Self::attach(&mut self.inside, Location::none(), comments); - } - return; - } - - // Simple implementation: attach comments to the nearest structure item - let mut remaining_comments = comments; - - for (i, item) in structure.iter().enumerate() { - let loc = &item.pstr_loc; - - // Find comments that belong to this item - let (leading, rest): (Vec, Vec) = remaining_comments - .into_iter() - .partition(|c| c.loc().loc_end.cnum <= loc.loc_start.cnum); + /// Check if there are trailing comments for a location. + pub fn has_trailing_comments(&self, loc: LocIdx, arena: &ParseArena) -> bool { + let pos_range = PosRange::from_loc(loc, arena); + self.trailing.contains_key(&pos_range) + } - // Find comments that are after this item but before the next - let next_start = if i + 1 < structure.len() { - structure[i + 1].pstr_loc.loc_start.cnum - } else { - i32::MAX - }; + /// Check if there are inside comments for a location. + pub fn has_inside_comments(&self, loc: LocIdx, arena: &ParseArena) -> bool { + let pos_range = PosRange::from_loc(loc, arena); + self.inside.contains_key(&pos_range) + } - let (trailing, rest): (Vec<_>, Vec<_>) = rest - .into_iter() - .partition(|c| { - c.loc().loc_start.cnum >= loc.loc_end.cnum - && c.loc().loc_end.cnum <= next_start - && c.loc().loc_start.line == loc.loc_end.line - }); + /// Get leading comments for a location. + pub fn get_leading_comments(&self, loc: LocIdx, arena: &ParseArena) -> Option<&Vec> { + let pos_range = PosRange::from_loc(loc, arena); + self.leading.get(&pos_range) + } - // Attach leading comments - if !leading.is_empty() { - Self::attach(&mut self.leading, loc.clone(), leading); - } + /// Get trailing comments for a location. + pub fn get_trailing_comments(&self, loc: LocIdx, arena: &ParseArena) -> Option<&Vec> { + let pos_range = PosRange::from_loc(loc, arena); + self.trailing.get(&pos_range) + } - // Attach trailing comments - if !trailing.is_empty() { - Self::attach(&mut self.trailing, loc.clone(), trailing); - } + /// Get inside comments for a location. + pub fn get_inside_comments(&self, loc: LocIdx, arena: &ParseArena) -> Option<&Vec> { + let pos_range = PosRange::from_loc(loc, arena); + self.inside.get(&pos_range) + } - remaining_comments = rest; - } + /// Get the first leading comment for a location (if any). + pub fn get_first_leading_comment(&self, loc: LocIdx, arena: &ParseArena) -> Option<&Comment> { + let pos_range = PosRange::from_loc(loc, arena); + self.leading.get(&pos_range).and_then(|comments| comments.first()) + } - // Any remaining comments go to "inside" at end of file - if !remaining_comments.is_empty() { - Self::attach(&mut self.inside, Location::none(), remaining_comments); - } + /// Get the first leading comment for a position range (if any). + pub fn get_first_leading_comment_by_pos(&self, pos_range: PosRange) -> Option<&Comment> { + self.leading.get(&pos_range).and_then(|comments| comments.first()) } + } /// Partitions a list of comments into three groups based on their position relative to a location: @@ -164,8 +205,10 @@ impl CommentTable { /// - trailing: comments that start after the location's end position pub fn partition_by_loc( comments: Vec, - loc: &Location, + loc: LocIdx, + arena: &mut ParseArena, ) -> (Vec, Vec, Vec) { + let loc = arena.to_location(loc); let mut leading = Vec::new(); let mut inside = Vec::new(); let mut trailing = Vec::new(); @@ -189,8 +232,10 @@ pub fn partition_by_loc( /// - trailing: comments that start at or after the location's start pub fn partition_leading_trailing( comments: Vec, - loc: &Location, + loc: LocIdx, + arena: &mut ParseArena, ) -> (Vec, Vec) { + let loc = arena.to_location(loc); let mut leading = Vec::new(); let mut trailing = Vec::new(); @@ -208,9 +253,11 @@ pub fn partition_leading_trailing( /// Splits comments into two groups based on whether they start on the same line as a location's end position. pub fn partition_by_on_same_line( - loc: &Location, + loc: LocIdx, comments: Vec, + arena: &mut ParseArena, ) -> (Vec, Vec) { + let loc = arena.to_location(loc); let mut on_same_line = Vec::new(); let mut on_other_line = Vec::new(); @@ -228,9 +275,11 @@ pub fn partition_by_on_same_line( /// Partitions comments that are adjacent to a location (appear right after it without blank lines). pub fn partition_adjacent_trailing( - loc: &Location, + loc: LocIdx, comments: Vec, + arena: &mut ParseArena, ) -> (Vec, Vec) { + let loc = arena.to_location(loc); let mut after_loc = Vec::new(); let mut remaining = Vec::new(); let mut prev_end_pos = loc.loc_end.cnum; @@ -256,10 +305,13 @@ pub fn partition_adjacent_trailing( /// Splits comments that follow a location but come before another token on the same line. pub fn partition_adjacent_trailing_before_next_token_on_same_line( - loc: &Location, - next_token: &Location, + loc: LocIdx, + next_token: LocIdx, comments: Vec, + arena: &mut ParseArena, ) -> (Vec, Vec) { + let loc = arena.to_location(loc); + let next_token = arena.to_location(next_token); let mut after_loc = Vec::new(); let mut rest = Vec::new(); let mut done = false; @@ -319,18 +371,18 @@ pub fn partition_between_lines( pub enum Node<'a> { Case(&'a Case), CoreType(&'a CoreType), - ExprArgument { expr: &'a Expression, loc: Location }, + ExprArgument { expr: &'a Expression, loc: LocIdx }, Expression(&'a Expression), - ExprRecordRow(&'a Loc, &'a Expression), + ExprRecordRow(&'a Loc, &'a Expression), ExtensionConstructor(&'a ExtensionConstructor), LabelDeclaration(&'a LabelDeclaration), ModuleBinding(&'a ModuleBinding), ModuleDeclaration(&'a ModuleDeclaration), ModuleExpr(&'a ModuleExpr), ObjectField(&'a ObjectField), - PackageConstraint(&'a Loc, &'a CoreType), + PackageConstraint(&'a Loc, &'a CoreType), Pattern(&'a Pattern), - PatternRecordRow(&'a Loc, &'a Pattern), + PatternRecordRow(&'a Loc, &'a Pattern), RowField(&'a RowField), SignatureItem(&'a SignatureItem), StructureItem(&'a StructureItem), @@ -341,77 +393,88 @@ pub enum Node<'a> { impl<'a> Node<'a> { /// Get the location of a node. - pub fn get_loc(&self) -> Location { + pub fn get_loc(&self, arena: &mut ParseArena) -> LocIdx { match self { Node::Case(case) => { // The case location extends from pattern to the end of the expression - let mut loc = case.pc_lhs.ppat_loc.clone(); - loc.loc_end = case.pc_rhs.pexp_loc.loc_end.clone(); - loc + // Check for braces attribute on RHS - if present, use its end location + // This must match the logic in printer2.rs:get_case_pos_range + let start = arena.loc_start(case.pc_lhs.ppat_loc); + let end = match parsetree_viewer::process_braces_attr(&case.pc_rhs) { + Some(attr) => arena.loc_end(attr.0.loc), + None => arena.loc_end(case.pc_rhs.pexp_loc), + }; + arena.from_location(&Location::from_positions(start.clone(), end.clone())) } - Node::CoreType(ct) => ct.ptyp_loc.clone(), - Node::ExprArgument { loc, .. } => loc.clone(), + Node::CoreType(ct) => ct.ptyp_loc, + Node::ExprArgument { loc, .. } => *loc, Node::Expression(e) => { // Check for braces attribute for attr in &e.pexp_attributes { if attr.0.txt == "res.braces" || attr.0.txt == "ns.braces" { - return attr.0.loc.clone(); + return attr.0.loc; } } - e.pexp_loc.clone() + e.pexp_loc } Node::ExprRecordRow(li, e) => { - let mut loc = li.loc.clone(); - loc.loc_end = e.pexp_loc.loc_end.clone(); - loc + let start = arena.loc_start(li.loc); + let end = arena.loc_end(e.pexp_loc); + arena.from_location(&Location::from_positions(start.clone(), end.clone())) } - Node::ExtensionConstructor(ec) => ec.pext_loc.clone(), - Node::LabelDeclaration(ld) => ld.pld_loc.clone(), - Node::ModuleBinding(mb) => mb.pmb_loc.clone(), - Node::ModuleDeclaration(md) => md.pmd_loc.clone(), - Node::ModuleExpr(me) => me.pmod_loc.clone(), + Node::ExtensionConstructor(ec) => ec.pext_loc, + Node::LabelDeclaration(ld) => ld.pld_loc, + Node::ModuleBinding(mb) => mb.pmb_loc, + Node::ModuleDeclaration(md) => md.pmd_loc, + Node::ModuleExpr(me) => me.pmod_loc, Node::ObjectField(field) => match field { ObjectField::Otag(lbl, _attrs, typ) => { - let mut loc = lbl.loc.clone(); - loc.loc_end = typ.ptyp_loc.loc_end.clone(); - loc + let start = arena.loc_start(lbl.loc); + let end = arena.loc_end(typ.ptyp_loc); + arena.from_location(&Location::from_positions(start.clone(), end.clone())) } - ObjectField::Oinherit(typ) => typ.ptyp_loc.clone(), + ObjectField::Oinherit(typ) => typ.ptyp_loc, }, Node::PackageConstraint(li, te) => { - let mut loc = li.loc.clone(); - loc.loc_end = te.ptyp_loc.loc_end.clone(); - loc + let start = arena.loc_start(li.loc); + let end = arena.loc_end(te.ptyp_loc); + arena.from_location(&Location::from_positions(start.clone(), end.clone())) } - Node::Pattern(p) => p.ppat_loc.clone(), + Node::Pattern(p) => p.ppat_loc, Node::PatternRecordRow(li, p) => { - let mut loc = li.loc.clone(); - loc.loc_end = p.ppat_loc.loc_end.clone(); - loc + // For punned patterns, li.loc and p.ppat_loc are the same + // Use li.loc directly to avoid creating a new LocIdx that won't match during printing + if li.loc == p.ppat_loc { + li.loc + } else { + let start = arena.loc_start(li.loc); + let end = arena.loc_end(p.ppat_loc); + arena.from_location(&Location::from_positions(start.clone(), end.clone())) + } } Node::RowField(rf) => match rf { - RowField::Rtag(tag, _attrs, _flag, _args) => tag.loc.clone(), - RowField::Rinherit(typ) => typ.ptyp_loc.clone(), + RowField::Rtag(tag, _attrs, _flag, _args) => tag.loc, + RowField::Rinherit(typ) => typ.ptyp_loc, }, - Node::SignatureItem(si) => si.psig_loc.clone(), - Node::StructureItem(si) => si.pstr_loc.clone(), - Node::TypeDeclaration(td) => td.ptype_loc.clone(), - Node::ValueBinding(vb) => vb.pvb_loc.clone(), - Node::JsxProp(prop) => get_jsx_prop_loc(prop), + Node::SignatureItem(si) => si.psig_loc, + Node::StructureItem(si) => si.pstr_loc, + Node::TypeDeclaration(td) => td.ptype_loc, + Node::ValueBinding(vb) => vb.pvb_loc, + Node::JsxProp(prop) => get_jsx_prop_loc(prop, arena), } } } /// Get the location of a JSX prop. -fn get_jsx_prop_loc(prop: &JsxProp) -> Location { +fn get_jsx_prop_loc(prop: &JsxProp, arena: &mut ParseArena) -> LocIdx { match prop { - JsxProp::Punning { name, .. } => name.loc.clone(), + JsxProp::Punning { name, .. } => name.loc, JsxProp::Value { name, value, .. } => { - let mut loc = name.loc.clone(); - loc.loc_end = value.pexp_loc.loc_end.clone(); - loc + let start = arena.loc_start(name.loc); + let end = arena.loc_end(value.pexp_loc); + arena.from_location(&Location::from_positions(start.clone(), end.clone())) } - JsxProp::Spreading { loc, .. } => loc.clone(), + JsxProp::Spreading { loc, .. } => *loc, } } @@ -437,14 +500,14 @@ fn is_if_then_else_expr(expr: &Expression) -> bool { } /// Collect list patterns from a cons pattern. -fn collect_list_patterns<'a>(pattern: &'a Pattern) -> Vec<&'a Pattern> { +fn collect_list_patterns<'a>(arena: &ParseArena, pattern: &'a Pattern) -> Vec<&'a Pattern> { let mut acc = Vec::new(); let mut current = pattern; loop { match ¤t.ppat_desc { PatternDesc::Ppat_construct(name, Some(args)) - if name.txt == Longident::Lident("::".to_string()) => + if arena.is_lident(name.txt, "::") => { if let PatternDesc::Ppat_tuple(tuple) = &args.ppat_desc { if tuple.len() == 2 { @@ -457,7 +520,7 @@ fn collect_list_patterns<'a>(pattern: &'a Pattern) -> Vec<&'a Pattern> { break; } PatternDesc::Ppat_construct(name, None) - if name.txt == Longident::Lident("[]".to_string()) => + if arena.is_lident(name.txt, "[]") => { break; } @@ -472,14 +535,14 @@ fn collect_list_patterns<'a>(pattern: &'a Pattern) -> Vec<&'a Pattern> { } /// Collect list expressions from a cons expression. -fn collect_list_exprs<'a>(expr: &'a Expression) -> Vec<&'a Expression> { +fn collect_list_exprs<'a>(arena: &ParseArena, expr: &'a Expression) -> Vec<&'a Expression> { let mut acc = Vec::new(); let mut current = expr; loop { match ¤t.pexp_desc { ExpressionDesc::Pexp_construct(name, Some(args)) - if name.txt == Longident::Lident("::".to_string()) => + if arena.is_lident(name.txt, "::") => { if let ExpressionDesc::Pexp_tuple(tuple) = &args.pexp_desc { if tuple.len() == 2 { @@ -492,7 +555,7 @@ fn collect_list_exprs<'a>(expr: &'a Expression) -> Vec<&'a Expression> { break; } ExpressionDesc::Pexp_construct(name, _) - if name.txt == Longident::Lident("[]".to_string()) => + if arena.is_lident(name.txt, "[]") => { break; } @@ -511,176 +574,180 @@ fn collect_list_exprs<'a>(expr: &'a Expression) -> Vec<&'a Expression> { // ============================================================================ /// Walk a structure and attach comments to AST nodes. -pub fn walk_structure(structure: &Structure, t: &mut CommentTable, comments: Vec) { +pub fn walk_structure(structure: &[StructureItem], t: &mut CommentTable, comments: Vec, arena: &mut ParseArena) { if comments.is_empty() { return; } if structure.is_empty() { - CommentTable::attach(&mut t.inside, Location::none(), comments); + t.attach_inside(LocIdx::none(), comments, arena); return; } let nodes: Vec> = structure.iter().map(|si| Node::StructureItem(si)).collect(); - walk_list(&nodes, t, comments); + walk_list(&nodes, t, comments, arena); } /// Walk a signature and attach comments to AST nodes. -pub fn walk_signature(signature: &Signature, t: &mut CommentTable, comments: Vec) { +pub fn walk_signature(signature: &[SignatureItem], t: &mut CommentTable, comments: Vec, arena: &mut ParseArena) { if comments.is_empty() { return; } if signature.is_empty() { - CommentTable::attach(&mut t.inside, Location::none(), comments); + t.attach_inside(LocIdx::none(), comments, arena); return; } let nodes: Vec> = signature.iter().map(|si| Node::SignatureItem(si)).collect(); - walk_list(&nodes, t, comments); + walk_list(&nodes, t, comments, arena); } /// Walk a list of nodes. -fn walk_list(nodes: &[Node<'_>], t: &mut CommentTable, comments: Vec) { - walk_list_impl(nodes, t, comments, None); +fn walk_list(nodes: &[Node<'_>], t: &mut CommentTable, comments: Vec, arena: &mut ParseArena) { + walk_list_impl(nodes, t, comments, None, arena); } -fn walk_list_impl(nodes: &[Node<'_>], t: &mut CommentTable, comments: Vec, prev_loc: Option) { +fn walk_list_impl(nodes: &[Node<'_>], t: &mut CommentTable, comments: Vec, prev_loc: Option, arena: &mut ParseArena) { if comments.is_empty() { return; } if nodes.is_empty() { if let Some(loc) = prev_loc { - CommentTable::attach(&mut t.trailing, loc, comments); + t.attach_trailing(loc, comments, arena); } return; } let node = &nodes[0]; let rest_nodes = &nodes[1..]; - let curr_loc = node.get_loc(); + let curr_loc = node.get_loc(arena); + + let (leading, inside, trailing) = partition_by_loc(comments, curr_loc, arena); - let (leading, inside, trailing) = partition_by_loc(comments, &curr_loc); + let prev_loc_resolved = prev_loc.map(|l| arena.to_location(l)); + let curr_loc_resolved = arena.to_location(curr_loc); match &prev_loc { None => { // First node, all leading comments attach here - CommentTable::attach(&mut t.leading, curr_loc.clone(), leading); + t.attach_leading(curr_loc, leading, arena); } - Some(prev_loc) => { + Some(prev_loc_idx) => { + let prev_loc_resolved = prev_loc_resolved.as_ref().unwrap(); // Check if on same line - if prev_loc.loc_end.line == curr_loc.loc_start.line { - let (after_prev, before_curr) = partition_adjacent_trailing(prev_loc, leading); - CommentTable::attach(&mut t.trailing, prev_loc.clone(), after_prev); - CommentTable::attach(&mut t.leading, curr_loc.clone(), before_curr); + if prev_loc_resolved.loc_end.line == curr_loc_resolved.loc_start.line { + let (after_prev, before_curr) = partition_adjacent_trailing(*prev_loc_idx, leading, arena); + t.attach_trailing(*prev_loc_idx, after_prev, arena); + t.attach_leading(curr_loc, before_curr, arena); } else { - let (on_same_line_as_prev, after_prev) = partition_by_on_same_line(prev_loc, leading); - CommentTable::attach(&mut t.trailing, prev_loc.clone(), on_same_line_as_prev); - let (before_curr, _, _) = partition_by_loc(after_prev, &curr_loc); - CommentTable::attach(&mut t.leading, curr_loc.clone(), before_curr); + let (on_same_line_as_prev, after_prev) = partition_by_on_same_line(*prev_loc_idx, leading, arena); + t.attach_trailing(*prev_loc_idx, on_same_line_as_prev, arena); + let (before_curr, _, _) = partition_by_loc(after_prev, curr_loc, arena); + t.attach_leading(curr_loc, before_curr, arena); } } } - walk_node(node, t, inside); - walk_list_impl(rest_nodes, t, trailing, Some(curr_loc)); + walk_node(node, t, inside, arena); + walk_list_impl(rest_nodes, t, trailing, Some(curr_loc), arena); } /// Walk a node and its children. -fn walk_node(node: &Node<'_>, t: &mut CommentTable, comments: Vec) { +fn walk_node(node: &Node<'_>, t: &mut CommentTable, comments: Vec, arena: &mut ParseArena) { match node { - Node::Case(c) => walk_case(c, t, comments), - Node::CoreType(ct) => walk_core_type(ct, t, comments), - Node::ExprArgument { expr, loc } => walk_expr_argument(expr, loc, t, comments), - Node::Expression(e) => walk_expression(e, t, comments), - Node::ExprRecordRow(li, e) => walk_expr_record_row(li, e, t, comments), - Node::ExtensionConstructor(ec) => walk_extension_constructor(ec, t, comments), - Node::LabelDeclaration(ld) => walk_label_declaration(ld, t, comments), - Node::ModuleBinding(mb) => walk_module_binding(mb, t, comments), - Node::ModuleDeclaration(md) => walk_module_declaration(md, t, comments), - Node::ModuleExpr(me) => walk_module_expr(me, t, comments), - Node::ObjectField(f) => walk_object_field(f, t, comments), - Node::PackageConstraint(li, te) => walk_package_constraint(li, te, t, comments), - Node::Pattern(p) => walk_pattern(p, t, comments), - Node::PatternRecordRow(li, p) => walk_pattern_record_row(li, p, t, comments), - Node::RowField(rf) => walk_row_field(rf, t, comments), - Node::SignatureItem(si) => walk_signature_item(si, t, comments), - Node::StructureItem(si) => walk_structure_item(si, t, comments), - Node::TypeDeclaration(td) => walk_type_declaration(td, t, comments), - Node::ValueBinding(vb) => walk_value_binding(vb, t, comments), - Node::JsxProp(prop) => walk_jsx_prop(prop, t, comments), - } -} - -fn walk_structure_item(si: &StructureItem, t: &mut CommentTable, comments: Vec) { + Node::Case(c) => walk_case(c, t, comments, arena), + Node::CoreType(ct) => walk_core_type(ct, t, comments, arena), + Node::ExprArgument { expr, loc } => walk_expr_argument(expr, loc, t, comments, arena), + Node::Expression(e) => walk_expression(e, t, comments, arena), + Node::ExprRecordRow(li, e) => walk_expr_record_row(li, e, t, comments, arena), + Node::ExtensionConstructor(ec) => walk_extension_constructor(ec, t, comments, arena), + Node::LabelDeclaration(ld) => walk_label_declaration(ld, t, comments, arena), + Node::ModuleBinding(mb) => walk_module_binding(mb, t, comments, arena), + Node::ModuleDeclaration(md) => walk_module_declaration(md, t, comments, arena), + Node::ModuleExpr(me) => walk_module_expr(me, t, comments, arena), + Node::ObjectField(f) => walk_object_field(f, t, comments, arena), + Node::PackageConstraint(li, te) => walk_package_constraint(li, te, t, comments, arena), + Node::Pattern(p) => walk_pattern(p, t, comments, arena), + Node::PatternRecordRow(li, p) => walk_pattern_record_row(li, p, t, comments, arena), + Node::RowField(rf) => walk_row_field(rf, t, comments, arena), + Node::SignatureItem(si) => walk_signature_item(si, t, comments, arena), + Node::StructureItem(si) => walk_structure_item(si, t, comments, arena), + Node::TypeDeclaration(td) => walk_type_declaration(td, t, comments, arena), + Node::ValueBinding(vb) => walk_value_binding(vb, t, comments, arena), + Node::JsxProp(prop) => walk_jsx_prop(prop, t, comments, arena), + } +} + +fn walk_structure_item(si: &StructureItem, t: &mut CommentTable, comments: Vec, arena: &mut ParseArena) { if comments.is_empty() { return; } match &si.pstr_desc { - StructureItemDesc::Pstr_primitive(vd) => walk_value_description(vd, t, comments), - StructureItemDesc::Pstr_open(od) => walk_open_description(od, t, comments), - StructureItemDesc::Pstr_value(_, bindings) => walk_value_bindings(bindings, t, comments), + StructureItemDesc::Pstr_primitive(vd) => walk_value_description(vd, t, comments, arena), + StructureItemDesc::Pstr_open(od) => walk_open_description(od, t, comments, arena), + StructureItemDesc::Pstr_value(_, bindings) => walk_value_bindings(bindings, t, comments, arena), StructureItemDesc::Pstr_type(_, declarations) => { - walk_type_declarations(declarations, t, comments) + walk_type_declarations(declarations, t, comments, arena) } - StructureItemDesc::Pstr_eval(expr, _) => walk_expression(expr, t, comments), - StructureItemDesc::Pstr_module(mb) => walk_module_binding(mb, t, comments), + StructureItemDesc::Pstr_eval(expr, _) => walk_expression(expr, t, comments, arena), + StructureItemDesc::Pstr_module(mb) => walk_module_binding(mb, t, comments, arena), StructureItemDesc::Pstr_recmodule(mbs) => { let nodes: Vec> = mbs.iter().map(|mb| Node::ModuleBinding(mb)).collect(); - walk_list(&nodes, t, comments); - } - StructureItemDesc::Pstr_modtype(mtd) => walk_module_type_declaration(mtd, t, comments), - StructureItemDesc::Pstr_attribute(attr) => walk_attribute(attr, t, comments), - StructureItemDesc::Pstr_extension(ext, _) => walk_extension(ext, t, comments), - StructureItemDesc::Pstr_include(id) => walk_include_declaration(id, t, comments), - StructureItemDesc::Pstr_exception(ec) => walk_extension_constructor(ec, t, comments), - StructureItemDesc::Pstr_typext(te) => walk_type_extension(te, t, comments), + walk_list(&nodes, t, comments, arena); + } + StructureItemDesc::Pstr_modtype(mtd) => walk_module_type_declaration(mtd, t, comments, arena), + StructureItemDesc::Pstr_attribute(attr) => walk_attribute(attr, t, comments, arena), + StructureItemDesc::Pstr_extension(ext, _) => walk_extension(ext, t, comments, arena), + StructureItemDesc::Pstr_include(id) => walk_include_declaration(id, t, comments, arena), + StructureItemDesc::Pstr_exception(ec) => walk_extension_constructor(ec, t, comments, arena), + StructureItemDesc::Pstr_typext(te) => walk_type_extension(te, t, comments, arena), } } -fn walk_signature_item(si: &SignatureItem, t: &mut CommentTable, comments: Vec) { +fn walk_signature_item(si: &SignatureItem, t: &mut CommentTable, comments: Vec, arena: &mut ParseArena) { if comments.is_empty() { return; } match &si.psig_desc { - SignatureItemDesc::Psig_value(vd) => walk_value_description(vd, t, comments), + SignatureItemDesc::Psig_value(vd) => walk_value_description(vd, t, comments, arena), SignatureItemDesc::Psig_type(_, declarations) => { - walk_type_declarations(declarations, t, comments) + walk_type_declarations(declarations, t, comments, arena) } - SignatureItemDesc::Psig_typext(te) => walk_type_extension(te, t, comments), - SignatureItemDesc::Psig_exception(ec) => walk_extension_constructor(ec, t, comments), - SignatureItemDesc::Psig_module(md) => walk_module_declaration(md, t, comments), + SignatureItemDesc::Psig_typext(te) => walk_type_extension(te, t, comments, arena), + SignatureItemDesc::Psig_exception(ec) => walk_extension_constructor(ec, t, comments, arena), + SignatureItemDesc::Psig_module(md) => walk_module_declaration(md, t, comments, arena), SignatureItemDesc::Psig_recmodule(mds) => { let nodes: Vec> = mds.iter().map(|md| Node::ModuleDeclaration(md)).collect(); - walk_list(&nodes, t, comments); + walk_list(&nodes, t, comments, arena); } - SignatureItemDesc::Psig_modtype(mtd) => walk_module_type_declaration(mtd, t, comments), - SignatureItemDesc::Psig_open(od) => walk_open_description(od, t, comments), - SignatureItemDesc::Psig_include(id) => walk_include_description(id, t, comments), - SignatureItemDesc::Psig_attribute(attr) => walk_attribute(attr, t, comments), - SignatureItemDesc::Psig_extension(ext, _) => walk_extension(ext, t, comments), + SignatureItemDesc::Psig_modtype(mtd) => walk_module_type_declaration(mtd, t, comments, arena), + SignatureItemDesc::Psig_open(od) => walk_open_description(od, t, comments, arena), + SignatureItemDesc::Psig_include(id) => walk_include_description(id, t, comments, arena), + SignatureItemDesc::Psig_attribute(attr) => walk_attribute(attr, t, comments, arena), + SignatureItemDesc::Psig_extension(ext, _) => walk_extension(ext, t, comments, arena), } } -fn walk_value_description(vd: &ValueDescription, t: &mut CommentTable, comments: Vec) { - let (leading, trailing) = partition_leading_trailing(comments, &vd.pval_name.loc); - CommentTable::attach(&mut t.leading, vd.pval_name.loc.clone(), leading); +fn walk_value_description(vd: &ValueDescription, t: &mut CommentTable, comments: Vec, arena: &mut ParseArena) { + let (leading, trailing) = partition_leading_trailing(comments, vd.pval_name.loc, arena); + t.attach_leading(vd.pval_name.loc, leading, arena); - let (after_name, rest) = partition_adjacent_trailing(&vd.pval_name.loc, trailing); - CommentTable::attach(&mut t.trailing, vd.pval_name.loc.clone(), after_name); + let (after_name, rest) = partition_adjacent_trailing(vd.pval_name.loc, trailing, arena); + t.attach_trailing(vd.pval_name.loc, after_name, arena); - let (before, inside, after) = partition_by_loc(rest, &vd.pval_type.ptyp_loc); - CommentTable::attach(&mut t.leading, vd.pval_type.ptyp_loc.clone(), before); - walk_core_type(&vd.pval_type, t, inside); - CommentTable::attach(&mut t.trailing, vd.pval_type.ptyp_loc.clone(), after); + let (before, inside, after) = partition_by_loc(rest, vd.pval_type.ptyp_loc, arena); + t.attach_leading(vd.pval_type.ptyp_loc, before, arena); + walk_core_type(&vd.pval_type, t, inside, arena); + t.attach_trailing(vd.pval_type.ptyp_loc, after, arena); } -fn walk_type_extension(te: &TypeExtension, t: &mut CommentTable, comments: Vec) { - let (leading, trailing) = partition_leading_trailing(comments, &te.ptyext_path.loc); - CommentTable::attach(&mut t.leading, te.ptyext_path.loc.clone(), leading); +fn walk_type_extension(te: &TypeExtension, t: &mut CommentTable, comments: Vec, arena: &mut ParseArena) { + let (leading, trailing) = partition_leading_trailing(comments, te.ptyext_path.loc, arena); + t.attach_leading(te.ptyext_path.loc, leading, arena); - let (after_path, rest) = partition_adjacent_trailing(&te.ptyext_path.loc, trailing); - CommentTable::attach(&mut t.trailing, te.ptyext_path.loc.clone(), after_path); + let (after_path, rest) = partition_adjacent_trailing(te.ptyext_path.loc, trailing, arena); + t.attach_trailing(te.ptyext_path.loc, after_path, arena); // Type params let rest = if te.ptyext_params.is_empty() { @@ -688,11 +755,12 @@ fn walk_type_extension(te: &TypeExtension, t: &mut CommentTable, comments: Vec) { - let (before, inside, after) = partition_by_loc(comments, &id.pincl_mod.pmod_loc); - CommentTable::attach(&mut t.leading, id.pincl_mod.pmod_loc.clone(), before); - walk_module_expr(&id.pincl_mod, t, inside); - CommentTable::attach(&mut t.trailing, id.pincl_mod.pmod_loc.clone(), after); +fn walk_include_declaration(id: &IncludeDeclaration, t: &mut CommentTable, comments: Vec, arena: &mut ParseArena) { + let (before, inside, after) = partition_by_loc(comments, id.pincl_mod.pmod_loc, arena); + t.attach_leading(id.pincl_mod.pmod_loc, before, arena); + walk_module_expr(&id.pincl_mod, t, inside, arena); + t.attach_trailing(id.pincl_mod.pmod_loc, after, arena); } -fn walk_include_description(id: &IncludeDescription, t: &mut CommentTable, comments: Vec) { - let (before, inside, after) = partition_by_loc(comments, &id.pincl_mod.pmty_loc); - CommentTable::attach(&mut t.leading, id.pincl_mod.pmty_loc.clone(), before); - walk_mod_type(&id.pincl_mod, t, inside); - CommentTable::attach(&mut t.trailing, id.pincl_mod.pmty_loc.clone(), after); +fn walk_include_description(id: &IncludeDescription, t: &mut CommentTable, comments: Vec, arena: &mut ParseArena) { + let (before, inside, after) = partition_by_loc(comments, id.pincl_mod.pmty_loc, arena); + t.attach_leading(id.pincl_mod.pmty_loc, before, arena); + walk_mod_type(&id.pincl_mod, t, inside, arena); + t.attach_trailing(id.pincl_mod.pmty_loc, after, arena); } fn walk_module_type_declaration( mtd: &ModuleTypeDeclaration, t: &mut CommentTable, comments: Vec, + arena: &mut ParseArena, ) { - let (leading, trailing) = partition_leading_trailing(comments, &mtd.pmtd_name.loc); - CommentTable::attach(&mut t.leading, mtd.pmtd_name.loc.clone(), leading); + let (leading, trailing) = partition_leading_trailing(comments, mtd.pmtd_name.loc, arena); + t.attach_leading(mtd.pmtd_name.loc, leading, arena); match &mtd.pmtd_type { None => { - CommentTable::attach(&mut t.trailing, mtd.pmtd_name.loc.clone(), trailing); + t.attach_trailing(mtd.pmtd_name.loc, trailing, arena); } Some(mod_type) => { - let (after_name, rest) = partition_adjacent_trailing(&mtd.pmtd_name.loc, trailing); - CommentTable::attach(&mut t.trailing, mtd.pmtd_name.loc.clone(), after_name); + let (after_name, rest) = partition_adjacent_trailing(mtd.pmtd_name.loc, trailing, arena); + t.attach_trailing(mtd.pmtd_name.loc, after_name, arena); - let (before, inside, after) = partition_by_loc(rest, &mod_type.pmty_loc); - CommentTable::attach(&mut t.leading, mod_type.pmty_loc.clone(), before); - walk_mod_type(mod_type, t, inside); - CommentTable::attach(&mut t.trailing, mod_type.pmty_loc.clone(), after); + let (before, inside, after) = partition_by_loc(rest, mod_type.pmty_loc, arena); + t.attach_leading(mod_type.pmty_loc, before, arena); + walk_mod_type(mod_type, t, inside, arena); + t.attach_trailing(mod_type.pmty_loc, after, arena); } } } -fn walk_module_binding(mb: &ModuleBinding, t: &mut CommentTable, comments: Vec) { - let (leading, trailing) = partition_leading_trailing(comments, &mb.pmb_name.loc); - CommentTable::attach(&mut t.leading, mb.pmb_name.loc.clone(), leading); +fn walk_module_binding(mb: &ModuleBinding, t: &mut CommentTable, comments: Vec, arena: &mut ParseArena) { + let (leading, trailing) = partition_leading_trailing(comments, mb.pmb_name.loc, arena); + t.attach_leading(mb.pmb_name.loc, leading, arena); - let (after_name, rest) = partition_adjacent_trailing(&mb.pmb_name.loc, trailing); - CommentTable::attach(&mut t.trailing, mb.pmb_name.loc.clone(), after_name); + let (after_name, rest) = partition_adjacent_trailing(mb.pmb_name.loc, trailing, arena); + t.attach_trailing(mb.pmb_name.loc, after_name, arena); - let (leading, inside, trailing) = partition_by_loc(rest, &mb.pmb_expr.pmod_loc); + let (leading, inside, trailing) = partition_by_loc(rest, mb.pmb_expr.pmod_loc, arena); match &mb.pmb_expr.pmod_desc { ModuleExprDesc::Pmod_constraint { .. } => { let combined: Vec = leading.into_iter().chain(inside.into_iter()).collect(); - walk_module_expr(&mb.pmb_expr, t, combined); + walk_module_expr(&mb.pmb_expr, t, combined, arena); } _ => { - CommentTable::attach(&mut t.leading, mb.pmb_expr.pmod_loc.clone(), leading); - walk_module_expr(&mb.pmb_expr, t, inside); + t.attach_leading(mb.pmb_expr.pmod_loc, leading, arena); + walk_module_expr(&mb.pmb_expr, t, inside, arena); } } - CommentTable::attach(&mut t.trailing, mb.pmb_expr.pmod_loc.clone(), trailing); + t.attach_trailing(mb.pmb_expr.pmod_loc, trailing, arena); } -fn walk_module_declaration(md: &ModuleDeclaration, t: &mut CommentTable, comments: Vec) { - let (leading, trailing) = partition_leading_trailing(comments, &md.pmd_name.loc); - CommentTable::attach(&mut t.leading, md.pmd_name.loc.clone(), leading); +fn walk_module_declaration(md: &ModuleDeclaration, t: &mut CommentTable, comments: Vec, arena: &mut ParseArena) { + let (leading, trailing) = partition_leading_trailing(comments, md.pmd_name.loc, arena); + t.attach_leading(md.pmd_name.loc, leading, arena); - let (after_name, rest) = partition_adjacent_trailing(&md.pmd_name.loc, trailing); - CommentTable::attach(&mut t.trailing, md.pmd_name.loc.clone(), after_name); + let (after_name, rest) = partition_adjacent_trailing(md.pmd_name.loc, trailing, arena); + t.attach_trailing(md.pmd_name.loc, after_name, arena); - let (leading, inside, trailing) = partition_by_loc(rest, &md.pmd_type.pmty_loc); - CommentTable::attach(&mut t.leading, md.pmd_type.pmty_loc.clone(), leading); - walk_mod_type(&md.pmd_type, t, inside); - CommentTable::attach(&mut t.trailing, md.pmd_type.pmty_loc.clone(), trailing); + let (leading, inside, trailing) = partition_by_loc(rest, md.pmd_type.pmty_loc, arena); + t.attach_leading(md.pmd_type.pmty_loc, leading, arena); + walk_mod_type(&md.pmd_type, t, inside, arena); + t.attach_trailing(md.pmd_type.pmty_loc, trailing, arena); } -fn walk_open_description(od: &OpenDescription, t: &mut CommentTable, comments: Vec) { - let loc = &od.popen_lid.loc; - let (leading, trailing) = partition_leading_trailing(comments, loc); - CommentTable::attach(&mut t.leading, loc.clone(), leading); - CommentTable::attach(&mut t.trailing, loc.clone(), trailing); +fn walk_open_description(od: &OpenDescription, t: &mut CommentTable, comments: Vec, arena: &mut ParseArena) { + let loc = od.popen_lid.loc; + let (leading, trailing) = partition_leading_trailing(comments, loc, arena); + t.attach_leading(loc, leading, arena); + t.attach_trailing(loc, trailing, arena); } -fn walk_value_bindings(vbs: &[ValueBinding], t: &mut CommentTable, comments: Vec) { +fn walk_value_bindings(vbs: &[ValueBinding], t: &mut CommentTable, comments: Vec, arena: &mut ParseArena) { let nodes: Vec> = vbs.iter().map(|vb| Node::ValueBinding(vb)).collect(); - walk_list(&nodes, t, comments); + walk_list(&nodes, t, comments, arena); } -fn walk_type_declarations(tds: &[TypeDeclaration], t: &mut CommentTable, comments: Vec) { +fn walk_type_declarations(tds: &[TypeDeclaration], t: &mut CommentTable, comments: Vec, arena: &mut ParseArena) { let nodes: Vec> = tds.iter().map(|td| Node::TypeDeclaration(td)).collect(); - walk_list(&nodes, t, comments); + walk_list(&nodes, t, comments, arena); } -fn walk_value_binding(vb: &ValueBinding, t: &mut CommentTable, comments: Vec) { - let pattern_loc = &vb.pvb_pat.ppat_loc; - let expr_loc = &vb.pvb_expr.pexp_loc; +/// Rewrite value binding locations for sugar cases. +/// OCaml's comment_table.ml has special handling for value binding sugar: +/// - `let x: poly_type = expr` where expr is constraint/newtype +/// The AST locations for these sugar forms span the entire binding, which would +/// cause all comments to be "inside" the pattern. OCaml rewrites the locations +/// so the pattern ends at the type annotation, and uses the inner expression. +/// +/// Returns (pattern_loc, expression_ref, expression_loc) +fn rewrite_value_binding_locs<'a>(vb: &'a ValueBinding, arena: &mut ParseArena) -> (LocIdx, &'a Expression, LocIdx) { + // Default: use the value binding's own locations + let default = (vb.pvb_pat.ppat_loc, &vb.pvb_expr, vb.pvb_expr.pexp_loc); + + // Check for the sugar cases that OCaml handles specially + match (&vb.pvb_pat.ppat_desc, &vb.pvb_expr.pexp_desc) { + // Case 1: Ppat_constraint(pat, Ptyp_poly([], t)) with Pexp_constraint(expr, _) + // let x: t = (expr: typ) + ( + PatternDesc::Ppat_constraint(pat, typ), + ExpressionDesc::Pexp_constraint(expr, _), + ) if matches!(&typ.ptyp_desc, CoreTypeDesc::Ptyp_poly(vars, _) if vars.is_empty()) => { + // Pattern loc ends at the inner type's location + if let CoreTypeDesc::Ptyp_poly(_, inner_typ) = &typ.ptyp_desc { + let new_pat_loc = arena.from_location(&Location { + loc_start: arena.loc_start(pat.ppat_loc).clone(), + loc_end: arena.loc_end(inner_typ.ptyp_loc).clone(), + loc_ghost: false, + }); + (new_pat_loc, expr.as_ref(), expr.pexp_loc) + } else { + default + } + } - let (leading, inside, trailing) = partition_by_loc(comments, pattern_loc); + // Case 2: Ppat_constraint(pat, Ptyp_poly(vars, t)) with Pexp_fun + // let x: type a. t = (a, b) => ... + ( + PatternDesc::Ppat_constraint(pat, typ), + ExpressionDesc::Pexp_fun { .. }, + ) if matches!(&typ.ptyp_desc, CoreTypeDesc::Ptyp_poly(vars, _) if !vars.is_empty()) => { + // Pattern loc ends at the inner type's location + if let CoreTypeDesc::Ptyp_poly(_, inner_typ) = &typ.ptyp_desc { + let new_pat_loc = arena.from_location(&Location { + loc_start: arena.loc_start(vb.pvb_pat.ppat_loc).clone(), + loc_end: arena.loc_end(inner_typ.ptyp_loc).clone(), + loc_ghost: false, + }); + (new_pat_loc, &vb.pvb_expr, vb.pvb_expr.pexp_loc) + } else { + default + } + } + + // Case 3: Ppat_constraint(pat, Ptyp_poly(vars, t)) with Pexp_newtype(_, Pexp_constraint(expr, _)) + // let x: type t. (...) => ... = (type t) => (a, b): (...) => ... => ... + // This is the value binding sugar case + ( + PatternDesc::Ppat_constraint(_pat, typ), + ExpressionDesc::Pexp_newtype(_, inner_expr), + ) if matches!(&typ.ptyp_desc, CoreTypeDesc::Ptyp_poly(vars, _) if !vars.is_empty()) => { + // Check if inner expression is Pexp_constraint(expr, _) + if let ExpressionDesc::Pexp_constraint(expr, _) = &inner_expr.pexp_desc { + if let CoreTypeDesc::Ptyp_poly(_, inner_typ) = &typ.ptyp_desc { + let new_pat_loc = arena.from_location(&Location { + loc_start: arena.loc_start(vb.pvb_pat.ppat_loc).clone(), + loc_end: arena.loc_end(inner_typ.ptyp_loc).clone(), + loc_ghost: false, + }); + // Use the inner expr (from Pexp_constraint), not the outer Pexp_newtype! + (new_pat_loc, expr.as_ref(), expr.pexp_loc) + } else { + default + } + } else { + default + } + } + + _ => default, + } +} + +fn walk_value_binding(vb: &ValueBinding, t: &mut CommentTable, comments: Vec, arena: &mut ParseArena) { + // OCaml rewrites value binding locations for sugar cases to properly partition comments. + // This is necessary because the AST locations for sugar forms span the entire binding, + // which causes all comments to be "inside" the pattern and none for the expression. + let (pattern_loc, expr_ref, expr_loc) = rewrite_value_binding_locs(vb, arena); + + let (leading, inside, trailing) = partition_by_loc(comments, pattern_loc, arena); // Everything before start of pattern can only be leading on the pattern - CommentTable::attach(&mut t.leading, pattern_loc.clone(), leading); - walk_pattern(&vb.pvb_pat, t, inside); + t.attach_leading(pattern_loc, leading, arena); + walk_pattern(&vb.pvb_pat, t, inside, arena); - let (after_pat, surrounding_expr) = partition_adjacent_trailing(pattern_loc, trailing); - CommentTable::attach(&mut t.trailing, pattern_loc.clone(), after_pat); + let (after_pat, surrounding_expr) = partition_adjacent_trailing(pattern_loc, trailing, arena); + t.attach_trailing(pattern_loc, after_pat, arena); - let (before_expr, inside_expr, after_expr) = partition_by_loc(surrounding_expr, expr_loc); + let (before_expr, inside_expr, after_expr) = partition_by_loc(surrounding_expr, expr_loc, arena); - if is_block_expr(&vb.pvb_expr) { + if is_block_expr(expr_ref) { let combined: Vec = before_expr .into_iter() .chain(inside_expr.into_iter()) .chain(after_expr.into_iter()) .collect(); - walk_expression(&vb.pvb_expr, t, combined); + walk_expression(expr_ref, t, combined, arena); } else { - CommentTable::attach(&mut t.leading, expr_loc.clone(), before_expr); - walk_expression(&vb.pvb_expr, t, inside_expr); - CommentTable::attach(&mut t.trailing, expr_loc.clone(), after_expr); + t.attach_leading(expr_loc, before_expr, arena); + walk_expression(expr_ref, t, inside_expr, arena); + t.attach_trailing(expr_loc, after_expr, arena); } } -fn walk_type_declaration(td: &TypeDeclaration, t: &mut CommentTable, comments: Vec) { - let (before_name, rest) = partition_leading_trailing(comments, &td.ptype_name.loc); - CommentTable::attach(&mut t.leading, td.ptype_name.loc.clone(), before_name); +fn walk_type_declaration(td: &TypeDeclaration, t: &mut CommentTable, comments: Vec, arena: &mut ParseArena) { + let (before_name, rest) = partition_leading_trailing(comments, td.ptype_name.loc, arena); + t.attach_leading(td.ptype_name.loc, before_name, arena); - let (after_name, rest) = partition_adjacent_trailing(&td.ptype_name.loc, rest); - CommentTable::attach(&mut t.trailing, td.ptype_name.loc.clone(), after_name); + let (after_name, rest) = partition_adjacent_trailing(td.ptype_name.loc, rest, arena); + t.attach_trailing(td.ptype_name.loc, after_name, arena); // Type params let rest = if td.ptype_params.is_empty() { @@ -836,22 +988,23 @@ fn walk_type_declaration(td: &TypeDeclaration, t: &mut CommentTable, comments: V } else { visit_list_but_continue_with_remaining_comments( &td.ptype_params, - |param| ¶m.0.ptyp_loc, - |param, t, comments| walk_core_type(¶m.0, t, comments), + |param, _arena| param.0.ptyp_loc, + |param, t, comments, arena| walk_core_type(¶m.0, t, comments, arena), t, rest, false, + arena, ) }; // Manifest: = typexpr let rest = match &td.ptype_manifest { Some(typexpr) => { - let (before_typ, inside_typ, after_typ) = partition_by_loc(rest, &typexpr.ptyp_loc); - CommentTable::attach(&mut t.leading, typexpr.ptyp_loc.clone(), before_typ); - walk_core_type(typexpr, t, inside_typ); - let (after_typ_adj, rest) = partition_adjacent_trailing(&typexpr.ptyp_loc, after_typ); - CommentTable::attach(&mut t.trailing, typexpr.ptyp_loc.clone(), after_typ_adj); + let (before_typ, inside_typ, after_typ) = partition_by_loc(rest, typexpr.ptyp_loc, arena); + t.attach_leading(typexpr.ptyp_loc, before_typ, arena); + walk_core_type(typexpr, t, inside_typ, arena); + let (after_typ_adj, rest) = partition_adjacent_trailing(typexpr.ptyp_loc, after_typ, arena); + t.attach_trailing(typexpr.ptyp_loc, after_typ_adj, arena); rest } None => rest, @@ -861,45 +1014,47 @@ fn walk_type_declaration(td: &TypeDeclaration, t: &mut CommentTable, comments: V TypeKind::Ptype_abstract | TypeKind::Ptype_open => rest, TypeKind::Ptype_record(lds) => { if lds.is_empty() { - CommentTable::attach(&mut t.inside, td.ptype_loc.clone(), rest); + t.attach_inside(td.ptype_loc, rest, arena); Vec::new() } else { let nodes: Vec> = lds.iter().map(|ld| Node::LabelDeclaration(ld)).collect(); - walk_list(&nodes, t, rest); + walk_list(&nodes, t, rest, arena); Vec::new() } } - TypeKind::Ptype_variant(cds) => walk_constructor_declarations(cds, t, rest), + TypeKind::Ptype_variant(cds) => walk_constructor_declarations(cds, t, rest, arena), }; - CommentTable::attach(&mut t.trailing, td.ptype_loc.clone(), rest); + t.attach_trailing(td.ptype_loc, rest, arena); } -fn walk_label_declaration(ld: &LabelDeclaration, t: &mut CommentTable, comments: Vec) { - let (before_name, rest) = partition_leading_trailing(comments, &ld.pld_name.loc); - CommentTable::attach(&mut t.leading, ld.pld_name.loc.clone(), before_name); +fn walk_label_declaration(ld: &LabelDeclaration, t: &mut CommentTable, comments: Vec, arena: &mut ParseArena) { + let (before_name, rest) = partition_leading_trailing(comments, ld.pld_name.loc, arena); + t.attach_leading(ld.pld_name.loc, before_name, arena); - let (after_name, rest) = partition_adjacent_trailing(&ld.pld_name.loc, rest); - CommentTable::attach(&mut t.trailing, ld.pld_name.loc.clone(), after_name); + let (after_name, rest) = partition_adjacent_trailing(ld.pld_name.loc, rest, arena); + t.attach_trailing(ld.pld_name.loc, after_name, arena); - let (before_typ, inside_typ, after_typ) = partition_by_loc(rest, &ld.pld_type.ptyp_loc); - CommentTable::attach(&mut t.leading, ld.pld_type.ptyp_loc.clone(), before_typ); - walk_core_type(&ld.pld_type, t, inside_typ); - CommentTable::attach(&mut t.trailing, ld.pld_type.ptyp_loc.clone(), after_typ); + let (before_typ, inside_typ, after_typ) = partition_by_loc(rest, ld.pld_type.ptyp_loc, arena); + t.attach_leading(ld.pld_type.ptyp_loc, before_typ, arena); + walk_core_type(&ld.pld_type, t, inside_typ, arena); + t.attach_trailing(ld.pld_type.ptyp_loc, after_typ, arena); } fn walk_constructor_declarations( cds: &[ConstructorDeclaration], t: &mut CommentTable, comments: Vec, + arena: &mut ParseArena, ) -> Vec { visit_list_but_continue_with_remaining_comments( cds, - |cd| &cd.pcd_loc, - walk_constructor_declaration, + |cd, _arena| cd.pcd_loc, + |cd, t, comments, arena| walk_constructor_declaration(cd, t, comments, arena), t, comments, false, + arena, ) } @@ -907,54 +1062,58 @@ fn walk_constructor_declaration( cd: &ConstructorDeclaration, t: &mut CommentTable, comments: Vec, + arena: &mut ParseArena, ) { - let (before_name, rest) = partition_leading_trailing(comments, &cd.pcd_name.loc); - CommentTable::attach(&mut t.leading, cd.pcd_name.loc.clone(), before_name); + let (before_name, rest) = partition_leading_trailing(comments, cd.pcd_name.loc, arena); + t.attach_leading(cd.pcd_name.loc, before_name, arena); - let (after_name, rest) = partition_adjacent_trailing(&cd.pcd_name.loc, rest); - CommentTable::attach(&mut t.trailing, cd.pcd_name.loc.clone(), after_name); + let (after_name, rest) = partition_adjacent_trailing(cd.pcd_name.loc, rest, arena); + t.attach_trailing(cd.pcd_name.loc, after_name, arena); - let rest = walk_constructor_arguments(&cd.pcd_args, t, rest); + let rest = walk_constructor_arguments(&cd.pcd_args, t, rest, arena); let rest = match &cd.pcd_res { Some(typexpr) => { - let (before_typ, inside_typ, after_typ) = partition_by_loc(rest, &typexpr.ptyp_loc); - CommentTable::attach(&mut t.leading, typexpr.ptyp_loc.clone(), before_typ); - walk_core_type(typexpr, t, inside_typ); - let (after_typ_adj, rest) = partition_adjacent_trailing(&typexpr.ptyp_loc, after_typ); - CommentTable::attach(&mut t.trailing, typexpr.ptyp_loc.clone(), after_typ_adj); + let (before_typ, inside_typ, after_typ) = partition_by_loc(rest, typexpr.ptyp_loc, arena); + t.attach_leading(typexpr.ptyp_loc, before_typ, arena); + walk_core_type(typexpr, t, inside_typ, arena); + let (after_typ_adj, rest) = partition_adjacent_trailing(typexpr.ptyp_loc, after_typ, arena); + t.attach_trailing(typexpr.ptyp_loc, after_typ_adj, arena); rest } None => rest, }; - CommentTable::attach(&mut t.trailing, cd.pcd_loc.clone(), rest); + t.attach_trailing(cd.pcd_loc, rest, arena); } fn walk_constructor_arguments( args: &ConstructorArguments, t: &mut CommentTable, comments: Vec, + arena: &mut ParseArena, ) -> Vec { match args { ConstructorArguments::Pcstr_tuple(typexprs) => { visit_list_but_continue_with_remaining_comments( typexprs, - |te| &te.ptyp_loc, - |te, t, comments| walk_core_type(te, t, comments), + |te, _arena| te.ptyp_loc, + |te, t, comments, arena| walk_core_type(te, t, comments, arena), t, comments, false, + arena, ) } ConstructorArguments::Pcstr_record(lds) => { visit_list_but_continue_with_remaining_comments( lds, - |ld| &ld.pld_loc, - walk_label_declaration, + |ld, _arena| ld.pld_loc, + |ld, t, comments, arena| walk_label_declaration(ld, t, comments, arena), t, comments, false, + arena, ) } } @@ -964,127 +1123,131 @@ fn walk_extension_constructor( ec: &ExtensionConstructor, t: &mut CommentTable, comments: Vec, + arena: &mut ParseArena, ) { - let (leading, trailing) = partition_leading_trailing(comments, &ec.pext_name.loc); - CommentTable::attach(&mut t.leading, ec.pext_name.loc.clone(), leading); + let (leading, trailing) = partition_leading_trailing(comments, ec.pext_name.loc, arena); + t.attach_leading(ec.pext_name.loc, leading, arena); - let (after_name, rest) = partition_adjacent_trailing(&ec.pext_name.loc, trailing); - CommentTable::attach(&mut t.trailing, ec.pext_name.loc.clone(), after_name); + let (after_name, rest) = partition_adjacent_trailing(ec.pext_name.loc, trailing, arena); + t.attach_trailing(ec.pext_name.loc, after_name, arena); match &ec.pext_kind { ExtensionConstructorKind::Pext_decl(args, res) => { - let rest = walk_constructor_arguments(args, t, rest); + let rest = walk_constructor_arguments(args, t, rest, arena); if let Some(typexpr) = res { let (before_typ, inside_typ, after_typ) = - partition_by_loc(rest, &typexpr.ptyp_loc); - CommentTable::attach(&mut t.leading, typexpr.ptyp_loc.clone(), before_typ); - walk_core_type(typexpr, t, inside_typ); - CommentTable::attach(&mut t.trailing, typexpr.ptyp_loc.clone(), after_typ); + partition_by_loc(rest, typexpr.ptyp_loc, arena); + t.attach_leading(typexpr.ptyp_loc, before_typ, arena); + walk_core_type(typexpr, t, inside_typ, arena); + t.attach_trailing(typexpr.ptyp_loc, after_typ, arena); } } ExtensionConstructorKind::Pext_rebind(lid) => { - let (leading, trailing) = partition_leading_trailing(rest, &lid.loc); - CommentTable::attach(&mut t.leading, lid.loc.clone(), leading); - CommentTable::attach(&mut t.trailing, lid.loc.clone(), trailing); + let (leading, trailing) = partition_leading_trailing(rest, lid.loc, arena); + t.attach_leading(lid.loc, leading, arena); + t.attach_trailing(lid.loc, trailing, arena); } } } -fn walk_expression(expr: &Expression, t: &mut CommentTable, comments: Vec) { +fn walk_expression(expr: &Expression, t: &mut CommentTable, comments: Vec, arena: &mut ParseArena) { if comments.is_empty() { return; } match &expr.pexp_desc { ExpressionDesc::Pexp_constant { .. } => { - let (leading, trailing) = partition_leading_trailing(comments, &expr.pexp_loc); - CommentTable::attach(&mut t.leading, expr.pexp_loc.clone(), leading); - CommentTable::attach(&mut t.trailing, expr.pexp_loc.clone(), trailing); + let (leading, trailing) = partition_leading_trailing(comments, expr.pexp_loc, arena); + t.attach_leading(expr.pexp_loc, leading, arena); + t.attach_trailing(expr.pexp_loc, trailing, arena); } ExpressionDesc::Pexp_ident(longident) => { - let (leading, trailing) = partition_leading_trailing(comments, &longident.loc); - CommentTable::attach(&mut t.leading, longident.loc.clone(), leading); - CommentTable::attach(&mut t.trailing, longident.loc.clone(), trailing); + let (leading, trailing) = partition_leading_trailing(comments, longident.loc, arena); + t.attach_leading(longident.loc, leading, arena); + t.attach_trailing(longident.loc, trailing, arena); } ExpressionDesc::Pexp_let(_, bindings, body) => { // Check if body is unit - if matches!(&body.pexp_desc, ExpressionDesc::Pexp_construct(name, None) if name.txt == Longident::Lident("()".to_string())) - { - walk_value_bindings(bindings, t, comments); + let body_is_unit = matches!(&body.pexp_desc, ExpressionDesc::Pexp_construct(name, None) if arena.is_lident(name.txt, "()")); + if body_is_unit { + walk_value_bindings(bindings, t, comments, arena); } else { let comments = visit_list_but_continue_with_remaining_comments( bindings, - |vb| { - if vb.pvb_pat.ppat_loc.loc_ghost { - &vb.pvb_expr.pexp_loc + |vb, arena| { + if arena.loc_ghost(vb.pvb_pat.ppat_loc) { + vb.pvb_expr.pexp_loc } else { - &vb.pvb_loc + vb.pvb_loc } }, - walk_value_binding, + |vb, t, comments, arena| walk_value_binding(vb, t, comments, arena), t, comments, true, + arena, ); if is_block_expr(body) { - walk_expression(body, t, comments); + walk_expression(body, t, comments, arena); } else { - let (leading, inside, trailing) = partition_by_loc(comments, &body.pexp_loc); - CommentTable::attach(&mut t.leading, body.pexp_loc.clone(), leading); - walk_expression(body, t, inside); - CommentTable::attach(&mut t.trailing, body.pexp_loc.clone(), trailing); + let (leading, inside, trailing) = partition_by_loc(comments, body.pexp_loc, arena); + t.attach_leading(body.pexp_loc, leading, arena); + walk_expression(body, t, inside, arena); + t.attach_trailing(body.pexp_loc, trailing, arena); } } } ExpressionDesc::Pexp_sequence(lhs, rhs) => { - let (leading, inside, trailing) = partition_by_loc(comments, &lhs.pexp_loc); + let (leading, inside, trailing) = partition_by_loc(comments, lhs.pexp_loc, arena); let comments = if is_block_expr(lhs) { - let (after_expr, comments) = partition_by_on_same_line(&lhs.pexp_loc, trailing); + let (after_expr, comments) = partition_by_on_same_line(lhs.pexp_loc, trailing, arena); let combined: Vec = leading .into_iter() .chain(inside.into_iter()) .chain(after_expr.into_iter()) .collect(); - walk_expression(lhs, t, combined); + walk_expression(lhs, t, combined, arena); comments } else { - CommentTable::attach(&mut t.leading, lhs.pexp_loc.clone(), leading); - walk_expression(lhs, t, inside); - let (after_expr, comments) = partition_by_on_same_line(&lhs.pexp_loc, trailing); - CommentTable::attach(&mut t.trailing, lhs.pexp_loc.clone(), after_expr); + t.attach_leading(lhs.pexp_loc, leading, arena); + walk_expression(lhs, t, inside, arena); + let (after_expr, comments) = partition_by_on_same_line(lhs.pexp_loc, trailing, arena); + t.attach_trailing(lhs.pexp_loc, after_expr, arena); comments }; if is_block_expr(rhs) { - walk_expression(rhs, t, comments); + walk_expression(rhs, t, comments, arena); } else { - let (leading, inside, trailing) = partition_by_loc(comments, &rhs.pexp_loc); - CommentTable::attach(&mut t.leading, rhs.pexp_loc.clone(), leading); - walk_expression(rhs, t, inside); - CommentTable::attach(&mut t.trailing, rhs.pexp_loc.clone(), trailing); + let (leading, inside, trailing) = partition_by_loc(comments, rhs.pexp_loc, arena); + t.attach_leading(rhs.pexp_loc, leading, arena); + walk_expression(rhs, t, inside, arena); + t.attach_trailing(rhs.pexp_loc, trailing, arena); } } ExpressionDesc::Pexp_open(_, lid, body) => { - let (leading, comments) = partition_leading_trailing(comments, &expr.pexp_loc); - let mut combined_loc = expr.pexp_loc.clone(); - combined_loc.loc_end = lid.loc.loc_end.clone(); - CommentTable::attach(&mut t.leading, combined_loc, leading); + let (leading, comments) = partition_leading_trailing(comments, expr.pexp_loc, arena); + let combined_loc = arena.from_location(&Location::from_positions( + arena.loc_start(expr.pexp_loc).clone(), + arena.loc_end(lid.loc).clone(), + )); + t.attach_leading(combined_loc, leading, arena); - let (leading, trailing) = partition_leading_trailing(comments, &lid.loc); - CommentTable::attach(&mut t.leading, lid.loc.clone(), leading); + let (leading, trailing) = partition_leading_trailing(comments, lid.loc, arena); + t.attach_leading(lid.loc, leading, arena); - let (after_longident, rest) = partition_by_on_same_line(&lid.loc, trailing); - CommentTable::attach(&mut t.trailing, lid.loc.clone(), after_longident); + let (after_longident, rest) = partition_by_on_same_line(lid.loc, trailing, arena); + t.attach_trailing(lid.loc, after_longident, arena); if is_block_expr(body) { - walk_expression(body, t, rest); + walk_expression(body, t, rest, arena); } else { - let (leading, inside, trailing) = partition_by_loc(rest, &body.pexp_loc); - CommentTable::attach(&mut t.leading, body.pexp_loc.clone(), leading); - walk_expression(body, t, inside); - CommentTable::attach(&mut t.trailing, body.pexp_loc.clone(), trailing); + let (leading, inside, trailing) = partition_by_loc(rest, body.pexp_loc, arena); + t.attach_leading(body.pexp_loc, leading, arena); + walk_expression(body, t, inside, arena); + t.attach_trailing(body.pexp_loc, trailing, arena); } } ExpressionDesc::Pexp_extension(ext) => { @@ -1099,157 +1262,161 @@ fn walk_expression(expr: &Expression, t: &mut CommentTable, comments: Vec { - let (leading, comments) = partition_leading_trailing(comments, &expr.pexp_loc); - let mut combined_loc = expr.pexp_loc.clone(); - combined_loc.loc_end = ext.pext_loc.loc_end.clone(); - CommentTable::attach(&mut t.leading, combined_loc, leading); + let (leading, comments) = partition_leading_trailing(comments, expr.pexp_loc, arena); + let combined_loc = arena.from_location(&Location::from_positions( + arena.loc_start(expr.pexp_loc).clone(), + arena.loc_end(ext.pext_loc).clone(), + )); + t.attach_leading(combined_loc, leading, arena); - let (leading, inside, trailing) = partition_by_loc(comments, &ext.pext_loc); - CommentTable::attach(&mut t.leading, ext.pext_loc.clone(), leading); - walk_extension_constructor(ext, t, inside); + let (leading, inside, trailing) = partition_by_loc(comments, ext.pext_loc, arena); + t.attach_leading(ext.pext_loc, leading, arena); + walk_extension_constructor(ext, t, inside, arena); - let (after_ext_constr, rest) = partition_by_on_same_line(&ext.pext_loc, trailing); - CommentTable::attach(&mut t.trailing, ext.pext_loc.clone(), after_ext_constr); + let (after_ext_constr, rest) = partition_by_on_same_line(ext.pext_loc, trailing, arena); + t.attach_trailing(ext.pext_loc, after_ext_constr, arena); if is_block_expr(body) { - walk_expression(body, t, rest); + walk_expression(body, t, rest, arena); } else { - let (leading, inside, trailing) = partition_by_loc(rest, &body.pexp_loc); - CommentTable::attach(&mut t.leading, body.pexp_loc.clone(), leading); - walk_expression(body, t, inside); - CommentTable::attach(&mut t.trailing, body.pexp_loc.clone(), trailing); + let (leading, inside, trailing) = partition_by_loc(rest, body.pexp_loc, arena); + t.attach_leading(body.pexp_loc, leading, arena); + walk_expression(body, t, inside, arena); + t.attach_trailing(body.pexp_loc, trailing, arena); } } ExpressionDesc::Pexp_letmodule(name, module, body) => { - let (leading, comments) = partition_leading_trailing(comments, &expr.pexp_loc); - let mut combined_loc = expr.pexp_loc.clone(); - combined_loc.loc_end = module.pmod_loc.loc_end.clone(); - CommentTable::attach(&mut t.leading, combined_loc, leading); + let (leading, comments) = partition_leading_trailing(comments, expr.pexp_loc, arena); + let combined_loc = arena.from_location(&Location::from_positions( + arena.loc_start(expr.pexp_loc).clone(), + arena.loc_end(module.pmod_loc).clone(), + )); + t.attach_leading(combined_loc, leading, arena); - let (leading, trailing) = partition_leading_trailing(comments, &name.loc); - CommentTable::attach(&mut t.leading, name.loc.clone(), leading); + let (leading, trailing) = partition_leading_trailing(comments, name.loc, arena); + t.attach_leading(name.loc, leading, arena); - let (after_string, rest) = partition_adjacent_trailing(&name.loc, trailing); - CommentTable::attach(&mut t.trailing, name.loc.clone(), after_string); + let (after_string, rest) = partition_adjacent_trailing(name.loc, trailing, arena); + t.attach_trailing(name.loc, after_string, arena); let (before_mod_expr, inside_mod_expr, after_mod_expr) = - partition_by_loc(rest, &module.pmod_loc); - CommentTable::attach(&mut t.leading, module.pmod_loc.clone(), before_mod_expr); - walk_module_expr(module, t, inside_mod_expr); + partition_by_loc(rest, module.pmod_loc, arena); + t.attach_leading(module.pmod_loc, before_mod_expr, arena); + walk_module_expr(module, t, inside_mod_expr, arena); - let (after_mod_expr_adj, rest) = partition_by_on_same_line(&module.pmod_loc, after_mod_expr); - CommentTable::attach(&mut t.trailing, module.pmod_loc.clone(), after_mod_expr_adj); + let (after_mod_expr_adj, rest) = partition_by_on_same_line(module.pmod_loc, after_mod_expr, arena); + t.attach_trailing(module.pmod_loc, after_mod_expr_adj, arena); if is_block_expr(body) { - walk_expression(body, t, rest); + walk_expression(body, t, rest, arena); } else { - let (leading, inside, trailing) = partition_by_loc(rest, &body.pexp_loc); - CommentTable::attach(&mut t.leading, body.pexp_loc.clone(), leading); - walk_expression(body, t, inside); - CommentTable::attach(&mut t.trailing, body.pexp_loc.clone(), trailing); + let (leading, inside, trailing) = partition_by_loc(rest, body.pexp_loc, arena); + t.attach_leading(body.pexp_loc, leading, arena); + walk_expression(body, t, inside, arena); + t.attach_trailing(body.pexp_loc, trailing, arena); } } ExpressionDesc::Pexp_assert(inner) => { if is_block_expr(inner) { - walk_expression(inner, t, comments); + walk_expression(inner, t, comments, arena); } else { - let (leading, inside, trailing) = partition_by_loc(comments, &inner.pexp_loc); - CommentTable::attach(&mut t.leading, inner.pexp_loc.clone(), leading); - walk_expression(inner, t, inside); - CommentTable::attach(&mut t.trailing, inner.pexp_loc.clone(), trailing); + let (leading, inside, trailing) = partition_by_loc(comments, inner.pexp_loc, arena); + t.attach_leading(inner.pexp_loc, leading, arena); + walk_expression(inner, t, inside, arena); + t.attach_trailing(inner.pexp_loc, trailing, arena); } } ExpressionDesc::Pexp_coerce(inner, _, typ) => { - let (leading, inside, trailing) = partition_by_loc(comments, &inner.pexp_loc); - CommentTable::attach(&mut t.leading, inner.pexp_loc.clone(), leading); - walk_expression(inner, t, inside); + let (leading, inside, trailing) = partition_by_loc(comments, inner.pexp_loc, arena); + t.attach_leading(inner.pexp_loc, leading, arena); + walk_expression(inner, t, inside, arena); - let (after_expr, rest) = partition_adjacent_trailing(&inner.pexp_loc, trailing); - CommentTable::attach(&mut t.trailing, inner.pexp_loc.clone(), after_expr); + let (after_expr, rest) = partition_adjacent_trailing(inner.pexp_loc, trailing, arena); + t.attach_trailing(inner.pexp_loc, after_expr, arena); - let (leading, inside, trailing) = partition_by_loc(rest, &typ.ptyp_loc); - CommentTable::attach(&mut t.leading, typ.ptyp_loc.clone(), leading); - walk_core_type(typ, t, inside); - CommentTable::attach(&mut t.trailing, typ.ptyp_loc.clone(), trailing); + let (leading, inside, trailing) = partition_by_loc(rest, typ.ptyp_loc, arena); + t.attach_leading(typ.ptyp_loc, leading, arena); + walk_core_type(typ, t, inside, arena); + t.attach_trailing(typ.ptyp_loc, trailing, arena); } ExpressionDesc::Pexp_constraint(inner, typ) => { - let (leading, inside, trailing) = partition_by_loc(comments, &inner.pexp_loc); - CommentTable::attach(&mut t.leading, inner.pexp_loc.clone(), leading); - walk_expression(inner, t, inside); + let (leading, inside, trailing) = partition_by_loc(comments, inner.pexp_loc, arena); + t.attach_leading(inner.pexp_loc, leading, arena); + walk_expression(inner, t, inside, arena); - let (after_expr, rest) = partition_adjacent_trailing(&inner.pexp_loc, trailing); - CommentTable::attach(&mut t.trailing, inner.pexp_loc.clone(), after_expr); + let (after_expr, rest) = partition_adjacent_trailing(inner.pexp_loc, trailing, arena); + t.attach_trailing(inner.pexp_loc, after_expr, arena); - let (leading, inside, trailing) = partition_by_loc(rest, &typ.ptyp_loc); - CommentTable::attach(&mut t.leading, typ.ptyp_loc.clone(), leading); - walk_core_type(typ, t, inside); - CommentTable::attach(&mut t.trailing, typ.ptyp_loc.clone(), trailing); + let (leading, inside, trailing) = partition_by_loc(rest, typ.ptyp_loc, arena); + t.attach_leading(typ.ptyp_loc, leading, arena); + walk_core_type(typ, t, inside, arena); + t.attach_trailing(typ.ptyp_loc, trailing, arena); } ExpressionDesc::Pexp_tuple(exprs) if exprs.is_empty() => { - CommentTable::attach(&mut t.inside, expr.pexp_loc.clone(), comments); + t.attach_inside(expr.pexp_loc, comments, arena); } ExpressionDesc::Pexp_array(exprs) if exprs.is_empty() => { - CommentTable::attach(&mut t.inside, expr.pexp_loc.clone(), comments); + t.attach_inside(expr.pexp_loc, comments, arena); } ExpressionDesc::Pexp_construct(name, None) - if name.txt == Longident::Lident("[]".to_string()) => + if arena.is_lident(name.txt, "[]") => { - CommentTable::attach(&mut t.inside, expr.pexp_loc.clone(), comments); + t.attach_inside(expr.pexp_loc, comments, arena); } ExpressionDesc::Pexp_construct(name, Some(_)) - if name.txt == Longident::Lident("::".to_string()) => + if arena.is_lident(name.txt, "::") => { - let list_exprs = collect_list_exprs(expr); + let list_exprs = collect_list_exprs(arena, expr); let nodes: Vec> = list_exprs.iter().map(|e| Node::Expression(e)).collect(); - walk_list(&nodes, t, comments); + walk_list(&nodes, t, comments, arena); } ExpressionDesc::Pexp_construct(name, args) => { - let (leading, trailing) = partition_leading_trailing(comments, &name.loc); - CommentTable::attach(&mut t.leading, name.loc.clone(), leading); + let (leading, trailing) = partition_leading_trailing(comments, name.loc, arena); + t.attach_leading(name.loc, leading, arena); match args { Some(arg_expr) => { - let (after_longident, rest) = partition_adjacent_trailing(&name.loc, trailing); - CommentTable::attach(&mut t.trailing, name.loc.clone(), after_longident); - walk_expression(arg_expr, t, rest); + let (after_longident, rest) = partition_adjacent_trailing(name.loc, trailing, arena); + t.attach_trailing(name.loc, after_longident, arena); + walk_expression(arg_expr, t, rest, arena); } None => { - CommentTable::attach(&mut t.trailing, name.loc.clone(), trailing); + t.attach_trailing(name.loc, trailing, arena); } } } ExpressionDesc::Pexp_variant(_, None) => {} ExpressionDesc::Pexp_variant(_, Some(arg)) => { - walk_expression(arg, t, comments); + walk_expression(arg, t, comments, arena); } ExpressionDesc::Pexp_array(exprs) | ExpressionDesc::Pexp_tuple(exprs) => { let nodes: Vec> = exprs.iter().map(|e| Node::Expression(e)).collect(); - walk_list(&nodes, t, comments); + walk_list(&nodes, t, comments, arena); } ExpressionDesc::Pexp_record(fields, spread) => { if fields.is_empty() { - CommentTable::attach(&mut t.inside, expr.pexp_loc.clone(), comments); + t.attach_inside(expr.pexp_loc, comments, arena); } else { let comments = match spread { None => comments, Some(spread_expr) => { let (leading, inside, trailing) = - partition_by_loc(comments, &spread_expr.pexp_loc); - CommentTable::attach(&mut t.leading, spread_expr.pexp_loc.clone(), leading); - walk_expression(spread_expr, t, inside); + partition_by_loc(comments, spread_expr.pexp_loc, arena); + t.attach_leading(spread_expr.pexp_loc, leading, arena); + walk_expression(spread_expr, t, inside, arena); let (after_expr, rest) = - partition_adjacent_trailing(&spread_expr.pexp_loc, trailing); - CommentTable::attach(&mut t.trailing, spread_expr.pexp_loc.clone(), after_expr); + partition_adjacent_trailing(spread_expr.pexp_loc, trailing, arena); + t.attach_trailing(spread_expr.pexp_loc, after_expr, arena); rest } }; @@ -1258,232 +1425,416 @@ fn walk_expression(expr: &Expression, t: &mut CommentTable, comments: Vec { - let (leading, inside, trailing) = partition_by_loc(comments, &inner.pexp_loc); + let (leading, inside, trailing) = partition_by_loc(comments, inner.pexp_loc, arena); let trailing = if is_block_expr(inner) { - let (after_expr, rest) = partition_adjacent_trailing(&inner.pexp_loc, trailing); + let (after_expr, rest) = partition_adjacent_trailing(inner.pexp_loc, trailing, arena); let combined: Vec = leading .into_iter() .chain(inside.into_iter()) .chain(after_expr.into_iter()) .collect(); - walk_expression(inner, t, combined); + walk_expression(inner, t, combined, arena); rest } else { - CommentTable::attach(&mut t.leading, inner.pexp_loc.clone(), leading); - walk_expression(inner, t, inside); + t.attach_leading(inner.pexp_loc, leading, arena); + walk_expression(inner, t, inside, arena); trailing }; - let (after_expr, rest) = partition_adjacent_trailing(&inner.pexp_loc, trailing); - CommentTable::attach(&mut t.trailing, inner.pexp_loc.clone(), after_expr); + let (after_expr, rest) = partition_adjacent_trailing(inner.pexp_loc, trailing, arena); + t.attach_trailing(inner.pexp_loc, after_expr, arena); - let (leading, trailing) = partition_leading_trailing(rest, &lid.loc); - CommentTable::attach(&mut t.leading, lid.loc.clone(), leading); - CommentTable::attach(&mut t.trailing, lid.loc.clone(), trailing); + let (leading, trailing) = partition_leading_trailing(rest, lid.loc, arena); + t.attach_leading(lid.loc, leading, arena); + t.attach_trailing(lid.loc, trailing, arena); } ExpressionDesc::Pexp_setfield(obj, lid, value) => { - let (leading, inside, trailing) = partition_by_loc(comments, &obj.pexp_loc); + let (leading, inside, trailing) = partition_by_loc(comments, obj.pexp_loc, arena); let rest = if is_block_expr(obj) { - let (after_expr, rest) = partition_adjacent_trailing(&obj.pexp_loc, trailing); + let (after_expr, rest) = partition_adjacent_trailing(obj.pexp_loc, trailing, arena); let combined: Vec = leading .into_iter() .chain(inside.into_iter()) .chain(after_expr.into_iter()) .collect(); - walk_expression(obj, t, combined); + walk_expression(obj, t, combined, arena); rest } else { - let (after_expr, rest) = partition_adjacent_trailing(&obj.pexp_loc, trailing); - CommentTable::attach(&mut t.leading, obj.pexp_loc.clone(), leading); - walk_expression(obj, t, inside); - CommentTable::attach(&mut t.trailing, obj.pexp_loc.clone(), after_expr); + let (after_expr, rest) = partition_adjacent_trailing(obj.pexp_loc, trailing, arena); + t.attach_leading(obj.pexp_loc, leading, arena); + walk_expression(obj, t, inside, arena); + t.attach_trailing(obj.pexp_loc, after_expr, arena); rest }; - let (before_longident, after_longident) = partition_leading_trailing(rest, &lid.loc); - CommentTable::attach(&mut t.leading, lid.loc.clone(), before_longident); + let (before_longident, after_longident) = partition_leading_trailing(rest, lid.loc, arena); + t.attach_leading(lid.loc, before_longident, arena); - let (after_longident_adj, rest) = partition_adjacent_trailing(&lid.loc, after_longident); - CommentTable::attach(&mut t.trailing, lid.loc.clone(), after_longident_adj); + let (after_longident_adj, rest) = partition_adjacent_trailing(lid.loc, after_longident, arena); + t.attach_trailing(lid.loc, after_longident_adj, arena); if is_block_expr(value) { - walk_expression(value, t, rest); + walk_expression(value, t, rest, arena); } else { - let (leading, inside, trailing) = partition_by_loc(rest, &value.pexp_loc); - CommentTable::attach(&mut t.leading, value.pexp_loc.clone(), leading); - walk_expression(value, t, inside); - CommentTable::attach(&mut t.trailing, value.pexp_loc.clone(), trailing); + let (leading, inside, trailing) = partition_by_loc(rest, value.pexp_loc, arena); + t.attach_leading(value.pexp_loc, leading, arena); + walk_expression(value, t, inside, arena); + t.attach_trailing(value.pexp_loc, trailing, arena); } } ExpressionDesc::Pexp_ifthenelse(cond, then_branch, else_branch) => { - let (leading, rest) = partition_leading_trailing(comments, &expr.pexp_loc); - CommentTable::attach(&mut t.leading, expr.pexp_loc.clone(), leading); + let (leading, rest) = partition_leading_trailing(comments, expr.pexp_loc, arena); + t.attach_leading(expr.pexp_loc, leading, arena); - let (leading, inside, trailing) = partition_by_loc(rest, &cond.pexp_loc); + let (leading, inside, trailing) = partition_by_loc(rest, cond.pexp_loc, arena); let comments = if is_block_expr(cond) { - let (after_expr, comments) = partition_adjacent_trailing(&cond.pexp_loc, trailing); + let (after_expr, comments) = partition_adjacent_trailing(cond.pexp_loc, trailing, arena); let combined: Vec = leading .into_iter() .chain(inside.into_iter()) .chain(after_expr.into_iter()) .collect(); - walk_expression(cond, t, combined); + walk_expression(cond, t, combined, arena); comments } else { - CommentTable::attach(&mut t.leading, cond.pexp_loc.clone(), leading); - walk_expression(cond, t, inside); - let (after_expr, comments) = partition_adjacent_trailing(&cond.pexp_loc, trailing); - CommentTable::attach(&mut t.trailing, cond.pexp_loc.clone(), after_expr); + t.attach_leading(cond.pexp_loc, leading, arena); + walk_expression(cond, t, inside, arena); + let (after_expr, comments) = partition_adjacent_trailing(cond.pexp_loc, trailing, arena); + t.attach_trailing(cond.pexp_loc, after_expr, arena); comments }; - let (leading, inside, trailing) = partition_by_loc(comments, &then_branch.pexp_loc); + let (leading, inside, trailing) = partition_by_loc(comments, then_branch.pexp_loc, arena); let comments = if is_block_expr(then_branch) { let (after_expr, trailing) = - partition_adjacent_trailing(&then_branch.pexp_loc, trailing); + partition_adjacent_trailing(then_branch.pexp_loc, trailing, arena); let combined: Vec = leading .into_iter() .chain(inside.into_iter()) .chain(after_expr.into_iter()) .collect(); - walk_expression(then_branch, t, combined); + walk_expression(then_branch, t, combined, arena); trailing } else { - CommentTable::attach(&mut t.leading, then_branch.pexp_loc.clone(), leading); - walk_expression(then_branch, t, inside); + t.attach_leading(then_branch.pexp_loc, leading, arena); + walk_expression(then_branch, t, inside, arena); let (after_expr, comments) = - partition_adjacent_trailing(&then_branch.pexp_loc, trailing); - CommentTable::attach(&mut t.trailing, then_branch.pexp_loc.clone(), after_expr); + partition_adjacent_trailing(then_branch.pexp_loc, trailing, arena); + t.attach_trailing(then_branch.pexp_loc, after_expr, arena); comments }; if let Some(else_expr) = else_branch { if is_block_expr(else_expr) || is_if_then_else_expr(else_expr) { - walk_expression(else_expr, t, comments); + walk_expression(else_expr, t, comments, arena); } else { let (leading, inside, trailing) = - partition_by_loc(comments, &else_expr.pexp_loc); - CommentTable::attach(&mut t.leading, else_expr.pexp_loc.clone(), leading); - walk_expression(else_expr, t, inside); - CommentTable::attach(&mut t.trailing, else_expr.pexp_loc.clone(), trailing); + partition_by_loc(comments, else_expr.pexp_loc, arena); + t.attach_leading(else_expr.pexp_loc, leading, arena); + walk_expression(else_expr, t, inside, arena); + t.attach_trailing(else_expr.pexp_loc, trailing, arena); } } } ExpressionDesc::Pexp_while(cond, body) => { - let (leading, inside, trailing) = partition_by_loc(comments, &cond.pexp_loc); + let (leading, inside, trailing) = partition_by_loc(comments, cond.pexp_loc, arena); let rest = if is_block_expr(cond) { - let (after_expr, rest) = partition_adjacent_trailing(&cond.pexp_loc, trailing); + let (after_expr, rest) = partition_adjacent_trailing(cond.pexp_loc, trailing, arena); let combined: Vec = leading .into_iter() .chain(inside.into_iter()) .chain(after_expr.into_iter()) .collect(); - walk_expression(cond, t, combined); + walk_expression(cond, t, combined, arena); rest } else { - CommentTable::attach(&mut t.leading, cond.pexp_loc.clone(), leading); - walk_expression(cond, t, inside); - let (after_expr, rest) = partition_adjacent_trailing(&cond.pexp_loc, trailing); - CommentTable::attach(&mut t.trailing, cond.pexp_loc.clone(), after_expr); + t.attach_leading(cond.pexp_loc, leading, arena); + walk_expression(cond, t, inside, arena); + let (after_expr, rest) = partition_adjacent_trailing(cond.pexp_loc, trailing, arena); + t.attach_trailing(cond.pexp_loc, after_expr, arena); rest }; if is_block_expr(body) { - walk_expression(body, t, rest); + walk_expression(body, t, rest, arena); } else { - let (leading, inside, trailing) = partition_by_loc(rest, &body.pexp_loc); - CommentTable::attach(&mut t.leading, body.pexp_loc.clone(), leading); - walk_expression(body, t, inside); - CommentTable::attach(&mut t.trailing, body.pexp_loc.clone(), trailing); + let (leading, inside, trailing) = partition_by_loc(rest, body.pexp_loc, arena); + t.attach_leading(body.pexp_loc, leading, arena); + walk_expression(body, t, inside, arena); + t.attach_trailing(body.pexp_loc, trailing, arena); } } ExpressionDesc::Pexp_for(pat, from, to, _, body) => { - let (leading, inside, trailing) = partition_by_loc(comments, &pat.ppat_loc); - CommentTable::attach(&mut t.leading, pat.ppat_loc.clone(), leading); - walk_pattern(pat, t, inside); + let (leading, inside, trailing) = partition_by_loc(comments, pat.ppat_loc, arena); + t.attach_leading(pat.ppat_loc, leading, arena); + walk_pattern(pat, t, inside, arena); - let (after_pat, rest) = partition_adjacent_trailing(&pat.ppat_loc, trailing); - CommentTable::attach(&mut t.trailing, pat.ppat_loc.clone(), after_pat); + let (after_pat, rest) = partition_adjacent_trailing(pat.ppat_loc, trailing, arena); + t.attach_trailing(pat.ppat_loc, after_pat, arena); - let (leading, inside, trailing) = partition_by_loc(rest, &from.pexp_loc); - CommentTable::attach(&mut t.leading, from.pexp_loc.clone(), leading); - walk_expression(from, t, inside); + let (leading, inside, trailing) = partition_by_loc(rest, from.pexp_loc, arena); + t.attach_leading(from.pexp_loc, leading, arena); + walk_expression(from, t, inside, arena); - let (after_expr, rest) = partition_adjacent_trailing(&from.pexp_loc, trailing); - CommentTable::attach(&mut t.trailing, from.pexp_loc.clone(), after_expr); + let (after_expr, rest) = partition_adjacent_trailing(from.pexp_loc, trailing, arena); + t.attach_trailing(from.pexp_loc, after_expr, arena); - let (leading, inside, trailing) = partition_by_loc(rest, &to.pexp_loc); - CommentTable::attach(&mut t.leading, to.pexp_loc.clone(), leading); - walk_expression(to, t, inside); + let (leading, inside, trailing) = partition_by_loc(rest, to.pexp_loc, arena); + t.attach_leading(to.pexp_loc, leading, arena); + walk_expression(to, t, inside, arena); - let (after_expr, rest) = partition_adjacent_trailing(&to.pexp_loc, trailing); - CommentTable::attach(&mut t.trailing, to.pexp_loc.clone(), after_expr); + let (after_expr, rest) = partition_adjacent_trailing(to.pexp_loc, trailing, arena); + t.attach_trailing(to.pexp_loc, after_expr, arena); if is_block_expr(body) { - walk_expression(body, t, rest); + walk_expression(body, t, rest, arena); } else { - let (leading, inside, trailing) = partition_by_loc(rest, &body.pexp_loc); - CommentTable::attach(&mut t.leading, body.pexp_loc.clone(), leading); - walk_expression(body, t, inside); - CommentTable::attach(&mut t.trailing, body.pexp_loc.clone(), trailing); + let (leading, inside, trailing) = partition_by_loc(rest, body.pexp_loc, arena); + t.attach_leading(body.pexp_loc, leading, arena); + walk_expression(body, t, inside, arena); + t.attach_trailing(body.pexp_loc, trailing, arena); } } ExpressionDesc::Pexp_pack(mod_expr) => { - let (before, inside, after) = partition_by_loc(comments, &mod_expr.pmod_loc); - CommentTable::attach(&mut t.leading, mod_expr.pmod_loc.clone(), before); - walk_module_expr(mod_expr, t, inside); - CommentTable::attach(&mut t.trailing, mod_expr.pmod_loc.clone(), after); + let (before, inside, after) = partition_by_loc(comments, mod_expr.pmod_loc, arena); + t.attach_leading(mod_expr.pmod_loc, before, arena); + walk_module_expr(mod_expr, t, inside, arena); + t.attach_trailing(mod_expr.pmod_loc, after, arena); } ExpressionDesc::Pexp_match(match_expr, cases) | ExpressionDesc::Pexp_try(match_expr, cases) => { - let (before, inside, after) = partition_by_loc(comments, &match_expr.pexp_loc); + let (before, inside, after) = partition_by_loc(comments, match_expr.pexp_loc, arena); let after = if is_block_expr(match_expr) { let (after_expr, rest) = - partition_adjacent_trailing(&match_expr.pexp_loc, after); + partition_adjacent_trailing(match_expr.pexp_loc, after, arena); let combined: Vec = before .into_iter() .chain(inside.into_iter()) .chain(after_expr.into_iter()) .collect(); - walk_expression(match_expr, t, combined); + walk_expression(match_expr, t, combined, arena); rest } else { - CommentTable::attach(&mut t.leading, match_expr.pexp_loc.clone(), before); - walk_expression(match_expr, t, inside); + t.attach_leading(match_expr.pexp_loc, before, arena); + walk_expression(match_expr, t, inside, arena); after }; - let (after_expr, rest) = partition_adjacent_trailing(&match_expr.pexp_loc, after); - CommentTable::attach(&mut t.trailing, match_expr.pexp_loc.clone(), after_expr); + let (after_expr, rest) = partition_adjacent_trailing(match_expr.pexp_loc, after, arena); + t.attach_trailing(match_expr.pexp_loc, after_expr, arena); let nodes: Vec> = cases.iter().map(|c| Node::Case(c)).collect(); - walk_list(&nodes, t, rest); + walk_list(&nodes, t, rest, arena); } ExpressionDesc::Pexp_apply { funct, args, .. } => { // Check for unary expressions if args.len() == 1 { if let ExpressionDesc::Pexp_ident(ident) = &funct.pexp_desc { - if let Longident::Lident(op) = &ident.txt { + if let Longident::Lident(op) = arena.get_longident(ident.txt) { + let op_str = arena.get_string(*op); if matches!( - op.as_str(), + op_str, "~+" | "~+." | "~-" | "~-." | "~~~" | "not" | "!" ) { let (_, arg_expr) = &args[0]; let (before, inside, after) = - partition_by_loc(comments, &arg_expr.pexp_loc); - CommentTable::attach(&mut t.leading, arg_expr.pexp_loc.clone(), before); - walk_expression(arg_expr, t, inside); - CommentTable::attach(&mut t.trailing, arg_expr.pexp_loc.clone(), after); + partition_by_loc(comments, arg_expr.pexp_loc, arena); + t.attach_leading(arg_expr.pexp_loc, before, arena); + walk_expression(arg_expr, t, inside, arena); + t.attach_trailing(arg_expr.pexp_loc, after, arena); + return; + } + } + } + } + + // Special case for Array.get: walk arguments directly like OCaml + if args.len() == 2 { + if let ExpressionDesc::Pexp_ident(ident) = &funct.pexp_desc { + if let Longident::Ldot(base, method_idx) = arena.get_longident(ident.txt) { + if let Longident::Lident(module_idx) = base.as_ref() { + let module = arena.get_string(*module_idx); + let method = arena.get_string(*method_idx); + if module == "Array" && method == "get" { + // Match OCaml: walk_list [Expression parent_expr; Expression member_expr] t comments + let (_, parent_expr) = &args[0]; + let (_, member_expr) = &args[1]; + let nodes: Vec> = vec![ + Node::Expression(parent_expr), + Node::Expression(member_expr), + ]; + walk_list(&nodes, t, comments, arena); + return; + } + } + } + } + } + + // Special case for Array.set: walk arguments directly like OCaml + if args.len() == 3 { + if let ExpressionDesc::Pexp_ident(ident) = &funct.pexp_desc { + if let Longident::Ldot(base, method_idx) = arena.get_longident(ident.txt) { + if let Longident::Lident(module_idx) = base.as_ref() { + let module = arena.get_string(*module_idx); + let method = arena.get_string(*method_idx); + if module == "Array" && method == "set" { + // Match OCaml: walk_list [Expression parent_expr; Expression member_expr; Expression target_expr] t comments + let (_, parent_expr) = &args[0]; + let (_, member_expr) = &args[1]; + let (_, target_expr) = &args[2]; + let nodes: Vec> = vec![ + Node::Expression(parent_expr), + Node::Expression(member_expr), + Node::Expression(target_expr), + ]; + walk_list(&nodes, t, comments, arena); + return; + } + } + } + } + } + + // Special case for Primitive_dict.make (dict{} syntax) + // Match OCaml: just walk the key_values array expression + if args.len() == 1 { + if let ExpressionDesc::Pexp_ident(ident) = &funct.pexp_desc { + if let Longident::Ldot(parent, method_idx) = arena.get_longident(ident.txt) { + if arena.get_string(*method_idx) == "make" { + if let Longident::Lident(module_idx) = parent.as_ref() { + if arena.get_string(*module_idx) == "Primitive_dict" { + let (_, key_values) = &args[0]; + // Check if key_values is a tuple array (matching OCaml's is_tuple_array) + if parsetree_viewer::is_tuple_array(key_values) { + // Walk the key_values expression directly + walk_list(&[Node::Expression(key_values)], t, comments, arena); + return; + } + } + } + } + } + } + } + + // Special case for Belt.Array.concatMany (spread array syntax) + // Match OCaml: flatten all sub-array expressions and walk them together + if args.len() == 1 { + if let ExpressionDesc::Pexp_ident(ident) = &funct.pexp_desc { + if let Longident::Ldot(parent, method_idx) = arena.get_longident(ident.txt) { + if arena.get_string(*method_idx) == "concatMany" { + if let Longident::Ldot(grandparent, parent_name) = parent.as_ref() { + if arena.get_string(*parent_name) == "Array" { + if let Longident::Lident(base) = grandparent.as_ref() { + if arena.get_string(*base) == "Belt" { + // Found Belt.Array.concatMany + let (_, arg) = &args[0]; + if let ExpressionDesc::Pexp_array(sub_arrays) = &arg.pexp_desc { + // Collect all expressions from sub-arrays + let mut all_exprs: Vec<&Expression> = Vec::new(); + for sub_array in sub_arrays { + if let ExpressionDesc::Pexp_array(exprs) = &sub_array.pexp_desc { + all_exprs.extend(exprs.iter()); + } else { + // Spread expression + all_exprs.push(sub_array); + } + } + // Walk all expressions together + let nodes: Vec> = all_exprs + .into_iter() + .map(|e| Node::Expression(e)) + .collect(); + walk_list(&nodes, t, comments, arena); + return; + } + } + } + } + } + } + } + } + } + + // Special case for Belt.List.concatMany (spread list syntax) + // Match OCaml: flatten all sub-list expressions and walk them together + if args.len() == 1 { + if let ExpressionDesc::Pexp_ident(ident) = &funct.pexp_desc { + if let Longident::Ldot(parent, method_idx) = arena.get_longident(ident.txt) { + if arena.get_string(*method_idx) == "concatMany" { + if let Longident::Ldot(grandparent, parent_name) = parent.as_ref() { + if arena.get_string(*parent_name) == "List" { + if let Longident::Lident(base) = grandparent.as_ref() { + if arena.get_string(*base) == "Belt" { + // Found Belt.List.concatMany + let (_, arg) = &args[0]; + if let ExpressionDesc::Pexp_array(sub_lists) = &arg.pexp_desc { + // Collect all expressions from sub-lists + let mut all_exprs: Vec<&Expression> = Vec::new(); + for sub_list in sub_lists { + // Collect list elements + let (exprs, spread) = parsetree_viewer::collect_list_expressions(arena, sub_list); + all_exprs.extend(exprs); + if let Some(spread_expr) = spread { + all_exprs.push(spread_expr); + } + } + // Walk all expressions together + let nodes: Vec> = all_exprs + .into_iter() + .map(|e| Node::Expression(e)) + .collect(); + walk_list(&nodes, t, comments, arena); + return; + } + } + } + } + } + } + } + } + } + + // Check for binary expressions - match OCaml's special handling + if args.len() == 2 { + if let ExpressionDesc::Pexp_ident(ident) = &funct.pexp_desc { + if let Longident::Lident(op) = arena.get_longident(ident.txt) { + let op_str = arena.get_string(*op); + if matches!( + op_str, + ":=" | "||" | "&&" | "==" | "===" | "<" | ">" | "!=" | "!==" + | "<=" | ">=" | "+" | "+." | "-" | "-." | "++" + | "|||" | "^^^" | "&&&" | "*" | "*." | "/" | "/." | "**" + | "->" | "<>" + ) { + let (_, operand1) = &args[0]; + let (_, operand2) = &args[1]; + + // Handle operand1 + let (before, inside, after) = partition_by_loc(comments, operand1.pexp_loc, arena); + t.attach_leading(operand1.pexp_loc, before, arena); + walk_expression(operand1, t, inside, arena); + let (after_operand1, rest) = partition_adjacent_trailing(operand1.pexp_loc, after, arena); + t.attach_trailing(operand1.pexp_loc, after_operand1, arena); + + // Handle operand2 + let (before, inside, after) = partition_by_loc(rest, operand2.pexp_loc, arena); + t.attach_leading(operand2.pexp_loc, before, arena); + walk_expression(operand2, t, inside, arena); + t.attach_trailing(operand2.pexp_loc, after, arena); return; } } @@ -1491,72 +1842,347 @@ fn walk_expression(expr: &Expression, t: &mut CommentTable, comments: Vec { - // Walk through the function parameters and body - walk_expression(body, t, comments); + walk_apply_expr(funct, args, t, comments, arena); + } + ExpressionDesc::Pexp_fun { .. } | ExpressionDesc::Pexp_newtype(_, _) => { + // Walk through function parameters and body, matching OCaml's handling + let (_is_async, parameters, return_expr) = parsetree_viewer::fun_expr(expr); + + // Walk each parameter, collecting remaining comments + let mut prev_loc: Option = None; + let mut comments = comments; + + for param in ¶meters { + use parsetree_viewer::FunParam; + // Get location for this parameter + let param_loc = match param { + FunParam::NewTypes { names, .. } => { + // For NewTypes, use the first name's location. + // This matches OCaml's comment_table which creates a pattern + // with loc = string_loc.loc (the first newtype name's location). + if let Some(first) = names.first() { + first.loc + } else { + arena.none_loc() + } + } + FunParam::Parameter { label, default_expr, pat, .. } => { + let start_pos = match label { + ArgLabel::Labelled(lbl) | ArgLabel::Optional(lbl) + if arena.to_location(lbl.loc) != Location::none() => + { + arena.loc_start(lbl.loc).clone() + } + _ => arena.loc_start(pat.ppat_loc).clone(), + }; + let end_pos = match default_expr { + Some(expr) => arena.loc_end(expr.pexp_loc).clone(), + None => arena.loc_end(pat.ppat_loc).clone(), + }; + arena.from_location(&Location::from_positions(start_pos, end_pos)) + } + }; + + let (leading, inside, trailing) = partition_by_loc(comments.clone(), param_loc, arena); + + // Attach leading comments considering previous parameter + match prev_loc { + None => { + t.attach_leading(param_loc, leading, arena); + } + Some(prev) => { + let prev_resolved = arena.to_location(prev); + let curr_resolved = arena.to_location(param_loc); + if prev_resolved.loc_end.line == curr_resolved.loc_start.line { + let (after_prev, before_curr) = partition_adjacent_trailing(prev, leading, arena); + t.attach_trailing(prev, after_prev, arena); + t.attach_leading(param_loc, before_curr, arena); + } else { + let (on_same_line, after) = partition_by_on_same_line(prev, leading, arena); + t.attach_trailing(prev, on_same_line, arena); + let (before_curr, _, _) = partition_by_loc(after, param_loc, arena); + t.attach_leading(param_loc, before_curr, arena); + } + } + } + + // Walk the parameter + match param { + FunParam::NewTypes { names, .. } => { + // For newtypes, attach inside comments to the first name's location + if let Some(first) = names.first() { + t.attach_inside(first.loc, inside, arena); + } + } + FunParam::Parameter { default_expr, pat, .. } => { + let (leading, inside2, trailing2) = partition_by_loc(inside, pat.ppat_loc, arena); + t.attach_leading(pat.ppat_loc, leading, arena); + walk_pattern(pat, t, inside2, arena); + + match default_expr { + Some(expr) => { + let (after_pat, rest) = partition_adjacent_trailing(pat.ppat_loc, trailing2, arena); + t.attach_trailing(pat.ppat_loc, after_pat, arena); + if is_block_expr(expr) { + walk_expression(expr, t, rest, arena); + } else { + let (l, i, tr) = partition_by_loc(rest, expr.pexp_loc, arena); + t.attach_leading(expr.pexp_loc, l, arena); + walk_expression(expr, t, i, arena); + t.attach_trailing(expr.pexp_loc, tr, arena); + } + } + None => { + t.attach_trailing(pat.ppat_loc, trailing2, arena); + } + } + } + } + + prev_loc = Some(param_loc); + comments = trailing; + } + + // Handle trailing comments after last parameter + if let Some(prev) = prev_loc { + let (after_prev, rest) = partition_adjacent_trailing(prev, comments, arena); + t.attach_trailing(prev, after_prev, arena); + comments = rest; + } + + // Walk return expression + match &return_expr.pexp_desc { + ExpressionDesc::Pexp_constraint(inner_expr, typ) + if arena.loc_start(inner_expr.pexp_loc).cnum >= arena.loc_end(typ.ptyp_loc).cnum => + { + let (leading, inside, trailing) = partition_by_loc(comments, typ.ptyp_loc, arena); + t.attach_leading(typ.ptyp_loc, leading, arena); + walk_core_type(typ, t, inside, arena); + let (after_typ, rest) = partition_adjacent_trailing(typ.ptyp_loc, trailing, arena); + t.attach_trailing(typ.ptyp_loc, after_typ, arena); + if is_block_expr(inner_expr) { + walk_expression(inner_expr, t, rest, arena); + } else { + let (l, i, tr) = partition_by_loc(rest, inner_expr.pexp_loc, arena); + t.attach_leading(inner_expr.pexp_loc, l, arena); + walk_expression(inner_expr, t, i, arena); + t.attach_trailing(inner_expr.pexp_loc, tr, arena); + } + } + _ => { + if is_block_expr(return_expr) { + walk_expression(return_expr, t, comments, arena); + } else { + let (l, i, tr) = partition_by_loc(comments, return_expr.pexp_loc, arena); + t.attach_leading(return_expr.pexp_loc, l, arena); + walk_expression(return_expr, t, i, arena); + t.attach_trailing(return_expr.pexp_loc, tr, arena); + } + } + } } ExpressionDesc::Pexp_send(inner, _) | ExpressionDesc::Pexp_await(inner) => { - walk_expression(inner, t, comments); + walk_expression(inner, t, comments, arena); } ExpressionDesc::Pexp_jsx_element(jsx) => { - walk_jsx_element(jsx, t, comments); + walk_jsx_element(jsx, expr.pexp_loc, t, comments, arena); } } } -fn walk_jsx_element(jsx: &JsxElement, t: &mut CommentTable, comments: Vec) { +fn walk_jsx_element(jsx: &JsxElement, pexp_loc: LocIdx, t: &mut CommentTable, comments: Vec, arena: &mut ParseArena) { if comments.is_empty() { return; } match jsx { JsxElement::Fragment(fragment) => { + // For fragment, get the opening token location (<>) + let opening_loc = { + let full_loc = arena.to_location(pexp_loc); + arena.from_location(&Location::from_positions( + full_loc.loc_start.clone(), + fragment.opening.clone(), + )) + }; + + // Partition on same line as opening + let (on_same_line, rest) = partition_by_on_same_line(opening_loc, comments, arena); + t.attach_trailing(opening_loc, on_same_line, arena); + let nodes: Vec> = fragment.children.iter().map(|e| Node::Expression(e)).collect(); - walk_list(&nodes, t, comments); + walk_list(&nodes, t, rest, arena); } JsxElement::Unary(unary) => { - // Walk the props - for prop in &unary.props { - walk_jsx_prop(prop, t, vec![]); + // Compute the closing token location for /> + // OCaml: unary_element_closing_token creates a loc with start at expr_loc.end - 2 + let closing_token_loc = { + let expr_loc = arena.to_location(pexp_loc); + let end_pos = &expr_loc.loc_end; + let start_pos = crate::location::Position { + file_name: end_pos.file_name, + line: end_pos.line, + bol: if end_pos.bol >= 2 { end_pos.bol - 2 } else { 0 }, + cnum: if end_pos.cnum >= 2 { end_pos.cnum - 2 } else { 0 }, + }; + arena.from_location(&Location::from_positions(start_pos, end_pos.clone())) + }; + + let name_loc = unary.tag_name.loc; + + // Get the next token after the tag name (first prop or closing token) + let next_token = if unary.props.is_empty() { + closing_token_loc + } else { + get_jsx_prop_loc(&unary.props[0], arena) + }; + + // Partition comments: same line as tag name and before next token -> trailing of tag name + let (after_opening_tag_name, rest) = partition_adjacent_trailing_before_next_token_on_same_line( + name_loc, + next_token, + comments, + arena, + ); + + // Only attach comments to the element name if they are on the same line + t.attach_trailing(name_loc, after_opening_tag_name, arena); + + if unary.props.is_empty() { + // Attach comments to the closing /> token + let (before_closing_token, _rest) = partition_leading_trailing(rest, closing_token_loc, arena); + t.attach_leading(closing_token_loc, before_closing_token, arena); + } else { + // Walk through props + let (comments_for_props, _rest) = partition_leading_trailing(rest, closing_token_loc, arena); + let prop_nodes: Vec> = unary.props.iter().map(|p| Node::JsxProp(p)).collect(); + walk_list(&prop_nodes, t, comments_for_props, arena); } - // Remaining comments attach to the element - let loc = &unary.tag_name.loc; - CommentTable::attach(&mut t.trailing, loc.clone(), comments); } JsxElement::Container(container) => { - // Walk props and children - for prop in &container.props { - walk_jsx_prop(prop, t, vec![]); + // Create location for the opening > token + let opening_greater_than_loc = { + let opening_end = &container.opening_end; + arena.from_location(&Location::from_positions( + opening_end.clone(), + opening_end.clone(), + )) + }; + + let name_loc = container.tag_name_start.loc; + + // Get the next token after the tag name (first prop or opening >) + let next_token = if container.props.is_empty() { + opening_greater_than_loc + } else { + get_jsx_prop_loc(&container.props[0], arena) + }; + + // Partition comments: same line as tag name and before next token + let (after_opening_tag_name, rest) = partition_adjacent_trailing_before_next_token_on_same_line( + name_loc, + next_token, + comments, + arena, + ); + + // Attach comments to the element name if they are on the same line + t.attach_trailing(name_loc, after_opening_tag_name, arena); + + let rest = if container.props.is_empty() { + // Attach comments to the opening > token + let (before_greater_than, rest) = partition_leading_trailing(rest, opening_greater_than_loc, arena); + t.attach_leading(opening_greater_than_loc, before_greater_than, arena); + rest + } else { + // Walk props + let (comments_for_props, rest) = partition_leading_trailing(rest, opening_greater_than_loc, arena); + let prop_nodes: Vec> = container.props.iter().map(|p| Node::JsxProp(p)).collect(); + walk_list(&prop_nodes, t, comments_for_props, arena); + rest + }; + + // Comments after '>' on the same line should be attached to '>' + let (after_opening_greater_than, rest) = partition_by_on_same_line(opening_greater_than_loc, rest, arena); + t.attach_trailing(opening_greater_than_loc, after_opening_greater_than, arena); + + // Get closing tag location if present + let (comments_for_children, _rest) = match &container.closing_tag { + None => (rest, vec![]), + Some(closing_tag) => { + let closing_tag_loc = { + arena.from_location(&Location::from_positions( + closing_tag.start.clone(), + closing_tag.end.clone(), + )) + }; + partition_leading_trailing(rest, closing_tag_loc, arena) + } + }; + + if container.children.is_empty() { + // Attach all comments to the closing tag if there are no children + if let Some(closing_tag) = &container.closing_tag { + let closing_tag_loc = arena.from_location(&Location::from_positions( + closing_tag.start.clone(), + closing_tag.end.clone(), + )); + + let opening_end_line = arena.to_location(opening_greater_than_loc).loc_end.line; + let closing_start_line = closing_tag.start.line; + + // Check if there's space between opening and closing tags + if opening_end_line < closing_start_line + 1 { + // Comments between tags get attached to "inside" the expression + let (inside_comments, leading_for_closing) = partition_between_lines( + opening_end_line, + closing_start_line, + comments_for_children, + ); + t.attach_inside(pexp_loc, inside_comments, arena); + t.attach_leading(closing_tag_loc, leading_for_closing, arena); + } else { + // If closing tag is on the same line, attach to closing tag + t.attach_leading(closing_tag_loc, comments_for_children, arena); + } + } + } else { + // Walk through children + let children_nodes: Vec> = container.children.iter().map(|e| Node::Expression(e)).collect(); + walk_list(&children_nodes, t, comments_for_children, arena); } - let nodes: Vec> = container.children.iter().map(|e| Node::Expression(e)).collect(); - walk_list(&nodes, t, comments); } } } -fn walk_jsx_prop(prop: &JsxProp, t: &mut CommentTable, comments: Vec) { +fn walk_jsx_prop(prop: &JsxProp, t: &mut CommentTable, comments: Vec, arena: &mut ParseArena) { match prop { JsxProp::Punning { name, .. } => { - let (leading, trailing) = partition_leading_trailing(comments, &name.loc); - CommentTable::attach(&mut t.leading, name.loc.clone(), leading); - CommentTable::attach(&mut t.trailing, name.loc.clone(), trailing); + let (leading, trailing) = partition_leading_trailing(comments, name.loc, arena); + t.attach_leading(name.loc, leading, arena); + t.attach_trailing(name.loc, trailing, arena); } JsxProp::Value { name, value, .. } => { - let (leading, trailing) = partition_leading_trailing(comments, &name.loc); - CommentTable::attach(&mut t.leading, name.loc.clone(), leading); - - let (after_lbl, rest) = partition_adjacent_trailing(&name.loc, trailing); - CommentTable::attach(&mut t.trailing, name.loc.clone(), after_lbl); - - let (before, inside, after) = partition_by_loc(rest, &value.pexp_loc); - CommentTable::attach(&mut t.leading, value.pexp_loc.clone(), before); - walk_expression(value, t, inside); - CommentTable::attach(&mut t.trailing, value.pexp_loc.clone(), after); + // Match OCaml's walk_jsx_prop which calls walk_list [Expression value] + // This is important because walk_list uses get_loc(Expression) which may + // return the braces location if the expression has res.braces attribute + let name_end_line = arena.loc_end(name.loc).line; + let value_start_line = arena.loc_start(value.pexp_loc).line; + + if name_end_line == value_start_line { + // In the rare case that comments are found between name=value, + // where both are on the same line, + // we assign them to the value, and not to the name. + walk_list(&[Node::Expression(value)], t, comments, arena); + } else { + // otherwise we attach comments that come directly after the name to the name + let (on_same_line_as_name, rest) = partition_by_on_same_line(name.loc, comments, arena); + t.attach_trailing(name.loc, on_same_line_as_name, arena); + walk_list(&[Node::Expression(value)], t, rest, arena); + } } JsxProp::Spreading { expr, .. } => { - walk_expression(expr, t, comments); + walk_expression(expr, t, comments, arena); } } } @@ -1566,631 +2192,879 @@ fn walk_apply_expr( arguments: &[(ArgLabel, Expression)], t: &mut CommentTable, comments: Vec, + arena: &mut ParseArena, ) { - let (before, inside, after) = partition_by_loc(comments, &call_expr.pexp_loc); + let (before, inside, after) = partition_by_loc(comments, call_expr.pexp_loc, arena); let after = if is_block_expr(call_expr) { - let (after_expr, rest) = partition_adjacent_trailing(&call_expr.pexp_loc, after); + let (after_expr, rest) = partition_adjacent_trailing(call_expr.pexp_loc, after, arena); let combined: Vec = before .into_iter() .chain(inside.into_iter()) .chain(after_expr.into_iter()) .collect(); - walk_expression(call_expr, t, combined); + walk_expression(call_expr, t, combined, arena); rest } else { - CommentTable::attach(&mut t.leading, call_expr.pexp_loc.clone(), before); - walk_expression(call_expr, t, inside); + t.attach_leading(call_expr.pexp_loc, before, arena); + walk_expression(call_expr, t, inside, arena); after }; - let (after_expr, rest) = partition_adjacent_trailing(&call_expr.pexp_loc, after); - CommentTable::attach(&mut t.trailing, call_expr.pexp_loc.clone(), after_expr); + let (after_expr, rest) = partition_adjacent_trailing(call_expr.pexp_loc, after, arena); + t.attach_trailing(call_expr.pexp_loc, after_expr, arena); let nodes: Vec> = arguments .iter() .map(|(lbl, expr)| { let loc = match lbl { ArgLabel::Labelled(lbl_loc) | ArgLabel::Optional(lbl_loc) => { - let mut loc = lbl_loc.loc.clone(); - loc.loc_end = expr.pexp_loc.loc_end.clone(); - loc + let start = arena.loc_start(lbl_loc.loc); + let end = arena.loc_end(expr.pexp_loc); + arena.from_location(&Location::from_positions(start.clone(), end.clone())) } - ArgLabel::Nolabel => expr.pexp_loc.clone(), + ArgLabel::Nolabel => expr.pexp_loc, }; Node::ExprArgument { expr, loc } }) .collect(); - walk_list(&nodes, t, rest); + walk_list(&nodes, t, rest, arena); } fn walk_expr_argument( expr: &Expression, - _loc: &Location, + loc: &LocIdx, t: &mut CommentTable, comments: Vec, + arena: &mut ParseArena, ) { - walk_expression(expr, t, comments); + // Match OCaml's walk_expr_argument which handles labelled arguments properly + let (leading, trailing) = partition_leading_trailing(comments, *loc, arena); + t.attach_leading(*loc, leading, arena); + + let (after_label, rest) = partition_adjacent_trailing(*loc, trailing, arena); + t.attach_trailing(*loc, after_label, arena); + + let (before, inside, after) = partition_by_loc(rest, expr.pexp_loc, arena); + t.attach_leading(expr.pexp_loc, before, arena); + walk_expression(expr, t, inside, arena); + t.attach_trailing(expr.pexp_loc, after, arena); } fn walk_expr_record_row( - li: &Loc, + li: &Loc, expr: &Expression, t: &mut CommentTable, comments: Vec, + arena: &mut ParseArena, ) { - let (leading, trailing) = partition_leading_trailing(comments, &li.loc); - CommentTable::attach(&mut t.leading, li.loc.clone(), leading); + let (leading, trailing) = partition_leading_trailing(comments, li.loc, arena); + t.attach_leading(li.loc, leading, arena); - let (after_li, rest) = partition_adjacent_trailing(&li.loc, trailing); - CommentTable::attach(&mut t.trailing, li.loc.clone(), after_li); + let (after_li, rest) = partition_adjacent_trailing(li.loc, trailing, arena); + t.attach_trailing(li.loc, after_li, arena); - let (before, inside, after) = partition_by_loc(rest, &expr.pexp_loc); - CommentTable::attach(&mut t.leading, expr.pexp_loc.clone(), before); - walk_expression(expr, t, inside); - CommentTable::attach(&mut t.trailing, expr.pexp_loc.clone(), after); + let (before, inside, after) = partition_by_loc(rest, expr.pexp_loc, arena); + t.attach_leading(expr.pexp_loc, before, arena); + walk_expression(expr, t, inside, arena); + t.attach_trailing(expr.pexp_loc, after, arena); } -fn walk_case(case: &Case, t: &mut CommentTable, comments: Vec) { - let (before, inside, after) = partition_by_loc(comments, &case.pc_lhs.ppat_loc); - CommentTable::attach(&mut t.leading, case.pc_lhs.ppat_loc.clone(), before); - walk_pattern(&case.pc_lhs, t, inside); +fn walk_case(case: &Case, t: &mut CommentTable, comments: Vec, arena: &mut ParseArena) { + let (before, inside, after) = partition_by_loc(comments, case.pc_lhs.ppat_loc, arena); + // cases don't have a location on their own, leading comments should go + // after the bar on the pattern - match OCaml's List.concat [before; inside] + let pattern_comments: Vec = before.into_iter() + .chain(inside.into_iter()) + .collect(); + walk_pattern(&case.pc_lhs, t, pattern_comments, arena); - let (after_pat, rest) = partition_adjacent_trailing(&case.pc_lhs.ppat_loc, after); - CommentTable::attach(&mut t.trailing, case.pc_lhs.ppat_loc.clone(), after_pat); + let (after_pat, rest) = partition_adjacent_trailing(case.pc_lhs.ppat_loc, after, arena); + t.attach_trailing(case.pc_lhs.ppat_loc, after_pat, arena); - // Handle guard + // Handle guard - match OCaml's special handling for block expressions let rest = match &case.pc_guard { Some(guard) => { - let (before, inside, after) = partition_by_loc(rest, &guard.pexp_loc); - CommentTable::attach(&mut t.leading, guard.pexp_loc.clone(), before); - walk_expression(guard, t, inside); - let (after_guard, rest) = partition_adjacent_trailing(&guard.pexp_loc, after); - CommentTable::attach(&mut t.trailing, guard.pexp_loc.clone(), after_guard); + let (before, inside, after) = partition_by_loc(rest, guard.pexp_loc, arena); + let (after_guard, rest) = partition_adjacent_trailing(guard.pexp_loc, after, arena); + if is_block_expr(guard) { + // For block expressions, pass all comments into walk_expression + let all_comments: Vec = before.into_iter() + .chain(inside.into_iter()) + .chain(after_guard.into_iter()) + .collect(); + walk_expression(guard, t, all_comments, arena); + } else { + t.attach_leading(guard.pexp_loc, before, arena); + walk_expression(guard, t, inside, arena); + t.attach_trailing(guard.pexp_loc, after_guard, arena); + } rest } None => rest, }; if is_block_expr(&case.pc_rhs) { - walk_expression(&case.pc_rhs, t, rest); + walk_expression(&case.pc_rhs, t, rest, arena); } else { - let (before, inside, after) = partition_by_loc(rest, &case.pc_rhs.pexp_loc); - CommentTable::attach(&mut t.leading, case.pc_rhs.pexp_loc.clone(), before); - walk_expression(&case.pc_rhs, t, inside); - CommentTable::attach(&mut t.trailing, case.pc_rhs.pexp_loc.clone(), after); + let (before, inside, after) = partition_by_loc(rest, case.pc_rhs.pexp_loc, arena); + t.attach_leading(case.pc_rhs.pexp_loc, before, arena); + walk_expression(&case.pc_rhs, t, inside, arena); + t.attach_trailing(case.pc_rhs.pexp_loc, after, arena); } } -fn walk_pattern(pattern: &Pattern, t: &mut CommentTable, comments: Vec) { +fn walk_pattern(pattern: &Pattern, t: &mut CommentTable, comments: Vec, arena: &mut ParseArena) { if comments.is_empty() { return; } match &pattern.ppat_desc { PatternDesc::Ppat_any | PatternDesc::Ppat_constant { .. } | PatternDesc::Ppat_interval { .. } => { - let (leading, trailing) = partition_leading_trailing(comments, &pattern.ppat_loc); - CommentTable::attach(&mut t.leading, pattern.ppat_loc.clone(), leading); - CommentTable::attach(&mut t.trailing, pattern.ppat_loc.clone(), trailing); + let (leading, trailing) = partition_leading_trailing(comments, pattern.ppat_loc, arena); + t.attach_leading(pattern.ppat_loc, leading, arena); + t.attach_trailing(pattern.ppat_loc, trailing, arena); } PatternDesc::Ppat_var(name) => { - let (leading, trailing) = partition_leading_trailing(comments, &name.loc); - CommentTable::attach(&mut t.leading, name.loc.clone(), leading); - CommentTable::attach(&mut t.trailing, name.loc.clone(), trailing); + let (leading, trailing) = partition_leading_trailing(comments, name.loc, arena); + t.attach_leading(name.loc, leading, arena); + t.attach_trailing(name.loc, trailing, arena); } PatternDesc::Ppat_alias(pat, name) => { - let (before, inside, after) = partition_by_loc(comments, &pat.ppat_loc); - CommentTable::attach(&mut t.leading, pat.ppat_loc.clone(), before); - walk_pattern(pat, t, inside); + let (before, inside, after) = partition_by_loc(comments, pat.ppat_loc, arena); + t.attach_leading(pat.ppat_loc, before, arena); + walk_pattern(pat, t, inside, arena); - let (after_pat, rest) = partition_adjacent_trailing(&pat.ppat_loc, after); - CommentTable::attach(&mut t.trailing, pat.ppat_loc.clone(), after_pat); + let (after_pat, rest) = partition_adjacent_trailing(pat.ppat_loc, after, arena); + t.attach_trailing(pat.ppat_loc, after_pat, arena); - let (leading, trailing) = partition_leading_trailing(rest, &name.loc); - CommentTable::attach(&mut t.leading, name.loc.clone(), leading); - CommentTable::attach(&mut t.trailing, name.loc.clone(), trailing); + let (leading, trailing) = partition_leading_trailing(rest, name.loc, arena); + t.attach_leading(name.loc, leading, arena); + t.attach_trailing(name.loc, trailing, arena); } PatternDesc::Ppat_tuple(pats) if pats.is_empty() => { - CommentTable::attach(&mut t.inside, pattern.ppat_loc.clone(), comments); + t.attach_inside(pattern.ppat_loc, comments, arena); } PatternDesc::Ppat_array(pats) if pats.is_empty() => { - CommentTable::attach(&mut t.inside, pattern.ppat_loc.clone(), comments); + t.attach_inside(pattern.ppat_loc, comments, arena); } - PatternDesc::Ppat_construct(name, None) - if name.txt == Longident::Lident("[]".to_string()) => + PatternDesc::Ppat_construct(name, _) + if arena.is_lident(name.txt, "()") || arena.is_lident(name.txt, "[]") => { - CommentTable::attach(&mut t.inside, pattern.ppat_loc.clone(), comments); + // Unit and empty list get comments inside (like OCaml reference) + t.attach_inside(pattern.ppat_loc, comments, arena); } PatternDesc::Ppat_construct(name, Some(_)) - if name.txt == Longident::Lident("::".to_string()) => + if arena.is_lident(name.txt, "::") => { - let list_pats = collect_list_patterns(pattern); + let list_pats = collect_list_patterns(arena, pattern); let nodes: Vec> = list_pats.iter().map(|p| Node::Pattern(p)).collect(); - walk_list(&nodes, t, comments); + walk_list(&nodes, t, comments, arena); } PatternDesc::Ppat_construct(name, args) => { - let (leading, trailing) = partition_leading_trailing(comments, &name.loc); - CommentTable::attach(&mut t.leading, name.loc.clone(), leading); + let (leading, trailing) = partition_leading_trailing(comments, name.loc, arena); + t.attach_leading(name.loc, leading, arena); match args { Some(arg_pat) => { - let (after_longident, rest) = partition_adjacent_trailing(&name.loc, trailing); - CommentTable::attach(&mut t.trailing, name.loc.clone(), after_longident); - walk_pattern(arg_pat, t, rest); + let (after_longident, rest) = partition_adjacent_trailing(name.loc, trailing, arena); + t.attach_trailing(name.loc, after_longident, arena); + walk_pattern(arg_pat, t, rest, arena); } None => { - CommentTable::attach(&mut t.trailing, name.loc.clone(), trailing); + t.attach_trailing(name.loc, trailing, arena); } } } PatternDesc::Ppat_variant(_, None) => {} PatternDesc::Ppat_variant(_, Some(arg)) => { - walk_pattern(arg, t, comments); + walk_pattern(arg, t, comments, arena); } PatternDesc::Ppat_tuple(pats) | PatternDesc::Ppat_array(pats) => { let nodes: Vec> = pats.iter().map(|p| Node::Pattern(p)).collect(); - walk_list(&nodes, t, comments); + walk_list(&nodes, t, comments, arena); } PatternDesc::Ppat_record(fields, _) => { let nodes: Vec> = fields .iter() .map(|f| Node::PatternRecordRow(&f.lid, &f.pat)) .collect(); - walk_list(&nodes, t, comments); + walk_list(&nodes, t, comments, arena); } - PatternDesc::Ppat_or(lhs, rhs) => { - let (before, inside, after) = partition_by_loc(comments, &lhs.ppat_loc); - CommentTable::attach(&mut t.leading, lhs.ppat_loc.clone(), before); - walk_pattern(lhs, t, inside); - - let (after_lhs, rest) = partition_adjacent_trailing(&lhs.ppat_loc, after); - CommentTable::attach(&mut t.trailing, lhs.ppat_loc.clone(), after_lhs); - - let (before, inside, after) = partition_by_loc(rest, &rhs.ppat_loc); - CommentTable::attach(&mut t.leading, rhs.ppat_loc.clone(), before); - walk_pattern(rhs, t, inside); - CommentTable::attach(&mut t.trailing, rhs.ppat_loc.clone(), after); + PatternDesc::Ppat_or(_, _) => { + // Collect the entire or-chain and walk as a list (like OCaml reference) + let or_chain = parsetree_viewer::collect_or_pattern_chain(pattern); + let nodes: Vec> = or_chain.iter().map(|p| Node::Pattern(p)).collect(); + walk_list(&nodes, t, comments, arena); } PatternDesc::Ppat_constraint(pat, typ) => { - let (before, inside, after) = partition_by_loc(comments, &pat.ppat_loc); - CommentTable::attach(&mut t.leading, pat.ppat_loc.clone(), before); - walk_pattern(pat, t, inside); + let (before, inside, after) = partition_by_loc(comments, pat.ppat_loc, arena); + t.attach_leading(pat.ppat_loc, before, arena); + walk_pattern(pat, t, inside, arena); - let (after_pat, rest) = partition_adjacent_trailing(&pat.ppat_loc, after); - CommentTable::attach(&mut t.trailing, pat.ppat_loc.clone(), after_pat); + let (after_pat, rest) = partition_adjacent_trailing(pat.ppat_loc, after, arena); + t.attach_trailing(pat.ppat_loc, after_pat, arena); - let (before, inside, after) = partition_by_loc(rest, &typ.ptyp_loc); - CommentTable::attach(&mut t.leading, typ.ptyp_loc.clone(), before); - walk_core_type(typ, t, inside); - CommentTable::attach(&mut t.trailing, typ.ptyp_loc.clone(), after); + let (before, inside, after) = partition_by_loc(rest, typ.ptyp_loc, arena); + t.attach_leading(typ.ptyp_loc, before, arena); + walk_core_type(typ, t, inside, arena); + t.attach_trailing(typ.ptyp_loc, after, arena); } PatternDesc::Ppat_type(lid) => { - let (leading, trailing) = partition_leading_trailing(comments, &lid.loc); - CommentTable::attach(&mut t.leading, lid.loc.clone(), leading); - CommentTable::attach(&mut t.trailing, lid.loc.clone(), trailing); + let (leading, trailing) = partition_leading_trailing(comments, lid.loc, arena); + t.attach_leading(lid.loc, leading, arena); + t.attach_trailing(lid.loc, trailing, arena); } PatternDesc::Ppat_exception(inner) => { - walk_pattern(inner, t, comments); + walk_pattern(inner, t, comments, arena); } PatternDesc::Ppat_unpack(name) => { - let (leading, trailing) = partition_leading_trailing(comments, &name.loc); - CommentTable::attach(&mut t.leading, name.loc.clone(), leading); - CommentTable::attach(&mut t.trailing, name.loc.clone(), trailing); + let (leading, trailing) = partition_leading_trailing(comments, name.loc, arena); + t.attach_leading(name.loc, leading, arena); + t.attach_trailing(name.loc, trailing, arena); } PatternDesc::Ppat_extension(ext) => { - walk_extension(ext, t, comments); + walk_extension(ext, t, comments, arena); } PatternDesc::Ppat_open(lid, pat) => { - let (leading, trailing) = partition_leading_trailing(comments, &lid.loc); - CommentTable::attach(&mut t.leading, lid.loc.clone(), leading); + let (leading, trailing) = partition_leading_trailing(comments, lid.loc, arena); + t.attach_leading(lid.loc, leading, arena); - let (after_lid, rest) = partition_adjacent_trailing(&lid.loc, trailing); - CommentTable::attach(&mut t.trailing, lid.loc.clone(), after_lid); + let (after_lid, rest) = partition_adjacent_trailing(lid.loc, trailing, arena); + t.attach_trailing(lid.loc, after_lid, arena); - walk_pattern(pat, t, rest); + walk_pattern(pat, t, rest, arena); } } } fn walk_pattern_record_row( - li: &Loc, + li: &Loc, pat: &Pattern, t: &mut CommentTable, comments: Vec, + arena: &mut ParseArena, ) { - let (leading, trailing) = partition_leading_trailing(comments, &li.loc); - CommentTable::attach(&mut t.leading, li.loc.clone(), leading); + let (leading, trailing) = partition_leading_trailing(comments, li.loc, arena); + t.attach_leading(li.loc, leading, arena); - let (after_li, rest) = partition_adjacent_trailing(&li.loc, trailing); - CommentTable::attach(&mut t.trailing, li.loc.clone(), after_li); + let (after_li, rest) = partition_adjacent_trailing(li.loc, trailing, arena); + t.attach_trailing(li.loc, after_li, arena); - let (before, inside, after) = partition_by_loc(rest, &pat.ppat_loc); - CommentTable::attach(&mut t.leading, pat.ppat_loc.clone(), before); - walk_pattern(pat, t, inside); - CommentTable::attach(&mut t.trailing, pat.ppat_loc.clone(), after); + let (before, inside, after) = partition_by_loc(rest, pat.ppat_loc, arena); + t.attach_leading(pat.ppat_loc, before, arena); + walk_pattern(pat, t, inside, arena); + t.attach_trailing(pat.ppat_loc, after, arena); } -fn walk_core_type(ct: &CoreType, t: &mut CommentTable, comments: Vec) { +fn walk_core_type(ct: &CoreType, t: &mut CommentTable, comments: Vec, arena: &mut ParseArena) { if comments.is_empty() { return; } match &ct.ptyp_desc { CoreTypeDesc::Ptyp_any | CoreTypeDesc::Ptyp_var(_) => { - let (leading, trailing) = partition_leading_trailing(comments, &ct.ptyp_loc); - CommentTable::attach(&mut t.leading, ct.ptyp_loc.clone(), leading); - CommentTable::attach(&mut t.trailing, ct.ptyp_loc.clone(), trailing); + let (leading, trailing) = partition_leading_trailing(comments, ct.ptyp_loc, arena); + t.attach_leading(ct.ptyp_loc, leading, arena); + t.attach_trailing(ct.ptyp_loc, trailing, arena); } CoreTypeDesc::Ptyp_constr(name, args) => { - let (leading, trailing) = partition_leading_trailing(comments, &name.loc); - CommentTable::attach(&mut t.leading, name.loc.clone(), leading); + let (leading, trailing) = partition_leading_trailing(comments, name.loc, arena); + t.attach_leading(name.loc, leading, arena); if args.is_empty() { - CommentTable::attach(&mut t.trailing, name.loc.clone(), trailing); + t.attach_trailing(name.loc, trailing, arena); } else { - let (after_name, rest) = partition_adjacent_trailing(&name.loc, trailing); - CommentTable::attach(&mut t.trailing, name.loc.clone(), after_name); + let (after_name, rest) = partition_adjacent_trailing(name.loc, trailing, arena); + t.attach_trailing(name.loc, after_name, arena); visit_list_but_continue_with_remaining_comments( args, - |arg| &arg.ptyp_loc, - |arg, t, comments| walk_core_type(arg, t, comments), + |arg, _arena| arg.ptyp_loc, + |arg, t, comments, arena| walk_core_type(arg, t, comments, arena), t, rest, false, + arena, ); } } - CoreTypeDesc::Ptyp_arrow { arg, ret, .. } => { - let (before, inside, after) = partition_by_loc(comments, &arg.typ.ptyp_loc); - CommentTable::attach(&mut t.leading, arg.typ.ptyp_loc.clone(), before); - walk_core_type(&arg.typ, t, inside); + CoreTypeDesc::Ptyp_arrow { .. } => { + // OCaml flattens the arrow type into a list of parameters first, then walks them. + // This ensures comments between parameters are properly partitioned. + use crate::parser::parsetree_viewer; + let (_, parameters, return_type) = parsetree_viewer::arrow_type(ct, None); - let (after_arg, rest) = partition_adjacent_trailing(&arg.typ.ptyp_loc, after); - CommentTable::attach(&mut t.trailing, arg.typ.ptyp_loc.clone(), after_arg); + // Walk type parameters using visit_list_but_continue_with_remaining_comments + let comments = walk_type_parameters(¶meters, t, comments, arena); - let (before, inside, after) = partition_by_loc(rest, &ret.ptyp_loc); - CommentTable::attach(&mut t.leading, ret.ptyp_loc.clone(), before); - walk_core_type(ret, t, inside); - CommentTable::attach(&mut t.trailing, ret.ptyp_loc.clone(), after); + // Handle return type + let (before_ret, inside_ret, after_ret) = partition_by_loc(comments, return_type.ptyp_loc, arena); + t.attach_leading(return_type.ptyp_loc, before_ret, arena); + walk_core_type(return_type, t, inside_ret, arena); + t.attach_trailing(return_type.ptyp_loc, after_ret, arena); } CoreTypeDesc::Ptyp_tuple(types) => { let nodes: Vec> = types.iter().map(|ty| Node::CoreType(ty)).collect(); - walk_list(&nodes, t, comments); + walk_list(&nodes, t, comments, arena); } CoreTypeDesc::Ptyp_object(fields, _) => { let nodes: Vec> = fields.iter().map(|f| Node::ObjectField(f)).collect(); - walk_list(&nodes, t, comments); + walk_list(&nodes, t, comments, arena); } - CoreTypeDesc::Ptyp_poly(_, typ) => { - walk_core_type(typ, t, comments); + CoreTypeDesc::Ptyp_poly(vars, typ) => { + // OCaml walks type variables as a list, attaching leading/trailing comments to each + let comments = if vars.is_empty() { + comments + } else { + visit_list_but_continue_with_remaining_comments( + vars, + |var, _arena| var.loc, + |var, t, comments, arena| { + let (before, after) = partition_leading_trailing(comments, var.loc, arena); + t.attach_leading(var.loc, before, arena); + t.attach_trailing(var.loc, after, arena); + }, + t, + comments, + false, + arena, + ) + }; + // Then handle the inner type + let (before_typ, inside_typ, after_typ) = partition_by_loc(comments, typ.ptyp_loc, arena); + t.attach_leading(typ.ptyp_loc, before_typ, arena); + walk_core_type(typ, t, inside_typ, arena); + t.attach_trailing(typ.ptyp_loc, after_typ, arena); } CoreTypeDesc::Ptyp_variant(fields, _, _) => { let nodes: Vec> = fields.iter().map(|f| Node::RowField(f)).collect(); - walk_list(&nodes, t, comments); + walk_list(&nodes, t, comments, arena); } CoreTypeDesc::Ptyp_package((name, constraints)) => { - let (leading, trailing) = partition_leading_trailing(comments, &name.loc); - CommentTable::attach(&mut t.leading, name.loc.clone(), leading); + let (leading, trailing) = partition_leading_trailing(comments, name.loc, arena); + t.attach_leading(name.loc, leading, arena); if constraints.is_empty() { - CommentTable::attach(&mut t.trailing, name.loc.clone(), trailing); + t.attach_trailing(name.loc, trailing, arena); } else { - let (after_name, rest) = partition_adjacent_trailing(&name.loc, trailing); - CommentTable::attach(&mut t.trailing, name.loc.clone(), after_name); + let (after_name, rest) = partition_adjacent_trailing(name.loc, trailing, arena); + t.attach_trailing(name.loc, after_name, arena); let nodes: Vec> = constraints .iter() .map(|(li, ty)| Node::PackageConstraint(li, ty)) .collect(); - walk_list(&nodes, t, rest); + walk_list(&nodes, t, rest, arena); } } CoreTypeDesc::Ptyp_alias(typ, _name) => { // The alias name is just a String without location info - let (before, inside, after) = partition_by_loc(comments, &typ.ptyp_loc); - CommentTable::attach(&mut t.leading, typ.ptyp_loc.clone(), before); - walk_core_type(typ, t, inside); - CommentTable::attach(&mut t.trailing, typ.ptyp_loc.clone(), after); + let (before, inside, after) = partition_by_loc(comments, typ.ptyp_loc, arena); + t.attach_leading(typ.ptyp_loc, before, arena); + walk_core_type(typ, t, inside, arena); + t.attach_trailing(typ.ptyp_loc, after, arena); } CoreTypeDesc::Ptyp_extension(ext) => { - walk_extension(ext, t, comments); + walk_extension(ext, t, comments, arena); } } } -fn walk_object_field(field: &ObjectField, t: &mut CommentTable, comments: Vec) { +/// Walk type parameters of an arrow type, properly partitioning comments between parameters. +/// Returns remaining comments after all parameters. +fn walk_type_parameters( + parameters: &[crate::parser::parsetree_viewer::TypeParameter<'_>], + t: &mut CommentTable, + comments: Vec, + arena: &mut ParseArena, +) -> Vec { + use crate::parser::parsetree_viewer::TypeParameter; + use crate::parser::ast::ArgLabel; + + visit_list_but_continue_with_remaining_comments( + parameters, + |param, arena| { + // OCaml: get_loc uses {(Asttypes.get_lbl_loc lbl) with loc_end = typ.ptyp_loc.loc_end} + // For labeled parameters, the location starts at the label + // For unlabeled parameters, use just the type's location + match param.lbl.located() { + Some(name) => arena.mk_loc_spanning(name.loc, param.typ.ptyp_loc), + None => param.typ.ptyp_loc, + } + }, + |param: &TypeParameter<'_>, t, comments, arena| { + // walk_node: walk each type parameter + // OCaml uses typexpr.ptyp_loc for partitioning, not the combined location! + // This means comments between the label and type (like `~a: /* c1 */ typ`) + // become "before" comments and get attached as leading to the type. + let (before, inside, after) = partition_by_loc(comments, param.typ.ptyp_loc, arena); + t.attach_leading(param.typ.ptyp_loc, before, arena); + walk_core_type(param.typ, t, inside, arena); + t.attach_trailing(param.typ.ptyp_loc, after, arena); + }, + t, + comments, + false, // newline_delimited + arena, + ) +} + +fn walk_object_field(field: &ObjectField, t: &mut CommentTable, comments: Vec, arena: &mut ParseArena) { match field { ObjectField::Otag(lbl, _attrs, typ) => { - let (leading, trailing) = partition_leading_trailing(comments, &lbl.loc); - CommentTable::attach(&mut t.leading, lbl.loc.clone(), leading); + let (leading, trailing) = partition_leading_trailing(comments, lbl.loc, arena); + t.attach_leading(lbl.loc, leading, arena); - let (after_lbl, rest) = partition_adjacent_trailing(&lbl.loc, trailing); - CommentTable::attach(&mut t.trailing, lbl.loc.clone(), after_lbl); + let (after_lbl, rest) = partition_adjacent_trailing(lbl.loc, trailing, arena); + t.attach_trailing(lbl.loc, after_lbl, arena); - let (before, inside, after) = partition_by_loc(rest, &typ.ptyp_loc); - CommentTable::attach(&mut t.leading, typ.ptyp_loc.clone(), before); - walk_core_type(typ, t, inside); - CommentTable::attach(&mut t.trailing, typ.ptyp_loc.clone(), after); + let (before, inside, after) = partition_by_loc(rest, typ.ptyp_loc, arena); + t.attach_leading(typ.ptyp_loc, before, arena); + walk_core_type(typ, t, inside, arena); + t.attach_trailing(typ.ptyp_loc, after, arena); } ObjectField::Oinherit(typ) => { - walk_core_type(typ, t, comments); + walk_core_type(typ, t, comments, arena); } } } -fn walk_row_field(field: &RowField, t: &mut CommentTable, comments: Vec) { +fn walk_row_field(field: &RowField, t: &mut CommentTable, comments: Vec, arena: &mut ParseArena) { match field { RowField::Rtag(tag, _attrs, _flag, args) => { - let (leading, trailing) = partition_leading_trailing(comments, &tag.loc); - CommentTable::attach(&mut t.leading, tag.loc.clone(), leading); + let (leading, trailing) = partition_leading_trailing(comments, tag.loc, arena); + t.attach_leading(tag.loc, leading, arena); if args.is_empty() { - CommentTable::attach(&mut t.trailing, tag.loc.clone(), trailing); + t.attach_trailing(tag.loc, trailing, arena); } else { - let (after_tag, rest) = partition_adjacent_trailing(&tag.loc, trailing); - CommentTable::attach(&mut t.trailing, tag.loc.clone(), after_tag); + let (after_tag, rest) = partition_adjacent_trailing(tag.loc, trailing, arena); + t.attach_trailing(tag.loc, after_tag, arena); visit_list_but_continue_with_remaining_comments( args, - |arg| &arg.ptyp_loc, - |arg, t, comments| walk_core_type(arg, t, comments), + |arg, _arena| arg.ptyp_loc, + |arg, t, comments, arena| walk_core_type(arg, t, comments, arena), t, rest, false, + arena, ); } } RowField::Rinherit(typ) => { - walk_core_type(typ, t, comments); + walk_core_type(typ, t, comments, arena); } } } fn walk_package_constraint( - li: &Loc, + li: &Loc, typ: &CoreType, t: &mut CommentTable, comments: Vec, + arena: &mut ParseArena, ) { - let (leading, trailing) = partition_leading_trailing(comments, &li.loc); - CommentTable::attach(&mut t.leading, li.loc.clone(), leading); + let (leading, trailing) = partition_leading_trailing(comments, li.loc, arena); + t.attach_leading(li.loc, leading, arena); - let (after_li, rest) = partition_adjacent_trailing(&li.loc, trailing); - CommentTable::attach(&mut t.trailing, li.loc.clone(), after_li); + let (after_li, rest) = partition_adjacent_trailing(li.loc, trailing, arena); + t.attach_trailing(li.loc, after_li, arena); - let (before, inside, after) = partition_by_loc(rest, &typ.ptyp_loc); - CommentTable::attach(&mut t.leading, typ.ptyp_loc.clone(), before); - walk_core_type(typ, t, inside); - CommentTable::attach(&mut t.trailing, typ.ptyp_loc.clone(), after); + let (before, inside, after) = partition_by_loc(rest, typ.ptyp_loc, arena); + t.attach_leading(typ.ptyp_loc, before, arena); + walk_core_type(typ, t, inside, arena); + t.attach_trailing(typ.ptyp_loc, after, arena); } -fn walk_module_expr(me: &ModuleExpr, t: &mut CommentTable, comments: Vec) { +fn walk_module_expr(me: &ModuleExpr, t: &mut CommentTable, comments: Vec, arena: &mut ParseArena) { if comments.is_empty() { return; } match &me.pmod_desc { ModuleExprDesc::Pmod_ident(lid) => { - let (leading, trailing) = partition_leading_trailing(comments, &lid.loc); - CommentTable::attach(&mut t.leading, lid.loc.clone(), leading); - CommentTable::attach(&mut t.trailing, lid.loc.clone(), trailing); + let (leading, trailing) = partition_leading_trailing(comments, lid.loc, arena); + t.attach_leading(lid.loc, leading, arena); + t.attach_trailing(lid.loc, trailing, arena); + } + ModuleExprDesc::Pmod_structure(structure) if structure.is_empty() => { + // Empty structure - attach inside comments to the module expr location + t.attach_inside(me.pmod_loc, comments, arena); } ModuleExprDesc::Pmod_structure(structure) => { - walk_structure(structure, t, comments); - } - ModuleExprDesc::Pmod_functor(name, arg_type, body) => { - // Handle functor name - let (leading, trailing) = partition_leading_trailing(comments, &name.loc); - CommentTable::attach(&mut t.leading, name.loc.clone(), leading); - - let (after_name, rest) = partition_adjacent_trailing(&name.loc, trailing); - CommentTable::attach(&mut t.trailing, name.loc.clone(), after_name); - - // Handle optional argument type - let rest = match arg_type { - Some(mod_type) => { - let (before, inside, after) = partition_by_loc(rest, &mod_type.pmty_loc); - CommentTable::attach(&mut t.leading, mod_type.pmty_loc.clone(), before); - walk_mod_type(mod_type, t, inside); - let (after_mod_type, rest) = - partition_adjacent_trailing(&mod_type.pmty_loc, after); - CommentTable::attach(&mut t.trailing, mod_type.pmty_loc.clone(), after_mod_type); - rest + walk_structure(structure, t, comments, arena); + } + ModuleExprDesc::Pmod_functor(_, _, _) => { + // Collect all functor parameters and walk them as a list + let (parameters, return_mod_expr) = parsetree_viewer::mod_expr_functor(me); + + // Use the combined location from label to end of mod_type for each parameter + let comments = visit_list_but_continue_with_remaining_comments( + ¶meters, + |param, arena| { + // Location spans from label start to mod_type end (if present) + match param.mod_type { + None => param.lbl.loc, + Some(mod_type) => arena.mk_loc_spanning(param.lbl.loc, mod_type.pmty_loc), + } + }, + |param, t, comments, arena| { + walk_mod_expr_parameter(param, t, comments, arena); + }, + t, + comments, + false, + arena, + ); + + // Handle return expression, with special case for Pmod_constraint + // where the constraint comes before the expression (: Set => expr) + match &return_mod_expr.pmod_desc { + ModuleExprDesc::Pmod_constraint(mod_expr, mod_type) + if arena.loc_end(mod_type.pmty_loc).cnum <= arena.loc_start(mod_expr.pmod_loc).cnum => + { + let (before, inside, after) = partition_by_loc(comments, mod_type.pmty_loc, arena); + t.attach_leading(mod_type.pmty_loc, before, arena); + walk_mod_type(mod_type, t, inside, arena); + let (after_type, rest) = partition_adjacent_trailing(mod_type.pmty_loc, after, arena); + t.attach_trailing(mod_type.pmty_loc, after_type, arena); + + let (before, inside, after) = partition_by_loc(rest, mod_expr.pmod_loc, arena); + t.attach_leading(mod_expr.pmod_loc, before, arena); + walk_module_expr(mod_expr, t, inside, arena); + t.attach_trailing(mod_expr.pmod_loc, after, arena); } - None => rest, - }; - - let (before, inside, after) = partition_by_loc(rest, &body.pmod_loc); - CommentTable::attach(&mut t.leading, body.pmod_loc.clone(), before); - walk_module_expr(body, t, inside); - CommentTable::attach(&mut t.trailing, body.pmod_loc.clone(), after); + _ => { + let (before, inside, after) = partition_by_loc(comments, return_mod_expr.pmod_loc, arena); + t.attach_leading(return_mod_expr.pmod_loc, before, arena); + walk_module_expr(return_mod_expr, t, inside, arena); + t.attach_trailing(return_mod_expr.pmod_loc, after, arena); + } + } } - ModuleExprDesc::Pmod_apply(funct, arg) => { - let (before, inside, after) = partition_by_loc(comments, &funct.pmod_loc); - CommentTable::attach(&mut t.leading, funct.pmod_loc.clone(), before); - walk_module_expr(funct, t, inside); - - let (after_funct, rest) = partition_adjacent_trailing(&funct.pmod_loc, after); - CommentTable::attach(&mut t.trailing, funct.pmod_loc.clone(), after_funct); - - let (before, inside, after) = partition_by_loc(rest, &arg.pmod_loc); - CommentTable::attach(&mut t.leading, arg.pmod_loc.clone(), before); - walk_module_expr(arg, t, inside); - CommentTable::attach(&mut t.trailing, arg.pmod_loc.clone(), after); + ModuleExprDesc::Pmod_apply(_, _) => { + // Collect all module expressions in the apply chain (call_expr first, then args) + let (args, call_expr) = parsetree_viewer::mod_expr_apply(me); + // OCaml's mod_expr_apply returns [call_expr, arg1, arg2, ...] but ours returns (args, call_expr) + // Build the list with call_expr first + let mut mod_exprs: Vec<&ModuleExpr> = vec![call_expr]; + mod_exprs.extend(args); + // Walk all module expressions as a list + let nodes: Vec> = mod_exprs.iter().map(|me| Node::ModuleExpr(me)).collect(); + walk_list(&nodes, t, comments, arena); } ModuleExprDesc::Pmod_constraint(module_expr, mod_type) => { - let (before, inside, after) = partition_by_loc(comments, &module_expr.pmod_loc); - CommentTable::attach(&mut t.leading, module_expr.pmod_loc.clone(), before); - walk_module_expr(module_expr, t, inside); - - let (after_mod, rest) = partition_adjacent_trailing(&module_expr.pmod_loc, after); - CommentTable::attach(&mut t.trailing, module_expr.pmod_loc.clone(), after_mod); - - let (before, inside, after) = partition_by_loc(rest, &mod_type.pmty_loc); - CommentTable::attach(&mut t.leading, mod_type.pmty_loc.clone(), before); - walk_mod_type(mod_type, t, inside); - CommentTable::attach(&mut t.trailing, mod_type.pmty_loc.clone(), after); + // Check which comes first in the source: the type or the expression + // For `X: Int` (normal constraint), type comes after + // For `: Int = X` (module binding constraint), type comes before + if arena.loc_start(mod_type.pmty_loc).cnum >= arena.loc_end(module_expr.pmod_loc).cnum { + // Type comes after expr: `X: Int` + let (before, inside, after) = partition_by_loc(comments, module_expr.pmod_loc, arena); + t.attach_leading(module_expr.pmod_loc, before, arena); + walk_module_expr(module_expr, t, inside, arena); + let (after_mod, rest) = partition_adjacent_trailing(module_expr.pmod_loc, after, arena); + t.attach_trailing(module_expr.pmod_loc, after_mod, arena); + + let (before, inside, after) = partition_by_loc(rest, mod_type.pmty_loc, arena); + t.attach_leading(mod_type.pmty_loc, before, arena); + walk_mod_type(mod_type, t, inside, arena); + t.attach_trailing(mod_type.pmty_loc, after, arena); + } else { + // Type comes before expr: `: Int = X` + let (before, inside, after) = partition_by_loc(comments, mod_type.pmty_loc, arena); + t.attach_leading(mod_type.pmty_loc, before, arena); + walk_mod_type(mod_type, t, inside, arena); + let (after_type, rest) = partition_adjacent_trailing(mod_type.pmty_loc, after, arena); + t.attach_trailing(mod_type.pmty_loc, after_type, arena); + + let (before, inside, after) = partition_by_loc(rest, module_expr.pmod_loc, arena); + t.attach_leading(module_expr.pmod_loc, before, arena); + walk_module_expr(module_expr, t, inside, arena); + t.attach_trailing(module_expr.pmod_loc, after, arena); + } } ModuleExprDesc::Pmod_unpack(expr) => { - walk_expression(expr, t, comments); + walk_expression(expr, t, comments, arena); } ModuleExprDesc::Pmod_extension(ext) => { - walk_extension(ext, t, comments); + walk_extension(ext, t, comments, arena); } } } -fn walk_mod_type(mt: &ModuleType, t: &mut CommentTable, comments: Vec) { +/// Walk a functor parameter (attrs, label, optional mod_type) +fn walk_mod_expr_parameter( + param: &parsetree_viewer::FunctorParam<'_>, + t: &mut CommentTable, + comments: Vec, + arena: &mut ParseArena, +) { + let (leading, trailing) = partition_leading_trailing(comments, param.lbl.loc, arena); + t.attach_leading(param.lbl.loc, leading, arena); + + match param.mod_type { + None => { + t.attach_trailing(param.lbl.loc, trailing, arena); + } + Some(mod_type) => { + let (after_lbl, rest) = partition_adjacent_trailing(param.lbl.loc, trailing, arena); + t.attach_trailing(param.lbl.loc, after_lbl, arena); + + let (before, inside, after) = partition_by_loc(rest, mod_type.pmty_loc, arena); + t.attach_leading(mod_type.pmty_loc, before, arena); + walk_mod_type(mod_type, t, inside, arena); + t.attach_trailing(mod_type.pmty_loc, after, arena); + } + } +} + +fn walk_mod_type(mt: &ModuleType, t: &mut CommentTable, comments: Vec, arena: &mut ParseArena) { if comments.is_empty() { return; } match &mt.pmty_desc { ModuleTypeDesc::Pmty_ident(lid) => { - let (leading, trailing) = partition_leading_trailing(comments, &lid.loc); - CommentTable::attach(&mut t.leading, lid.loc.clone(), leading); - CommentTable::attach(&mut t.trailing, lid.loc.clone(), trailing); + let (leading, trailing) = partition_leading_trailing(comments, lid.loc, arena); + t.attach_leading(lid.loc, leading, arena); + t.attach_trailing(lid.loc, trailing, arena); + } + ModuleTypeDesc::Pmty_signature(sig) if sig.is_empty() => { + // Empty signature - attach inside comments to the module type location + t.attach_inside(mt.pmty_loc, comments, arena); } ModuleTypeDesc::Pmty_signature(sig) => { - walk_signature(sig, t, comments); - } - ModuleTypeDesc::Pmty_functor(name, arg_type, ret) => { - // Handle functor name - let (leading, trailing) = partition_leading_trailing(comments, &name.loc); - CommentTable::attach(&mut t.leading, name.loc.clone(), leading); - - let (after_name, rest) = partition_adjacent_trailing(&name.loc, trailing); - CommentTable::attach(&mut t.trailing, name.loc.clone(), after_name); - - // Handle optional argument type - let rest = match arg_type { - Some(mod_type) => { - let (before, inside, after) = partition_by_loc(rest, &mod_type.pmty_loc); - CommentTable::attach(&mut t.leading, mod_type.pmty_loc.clone(), before); - walk_mod_type(mod_type, t, inside); - let (after_mod_type, rest) = - partition_adjacent_trailing(&mod_type.pmty_loc, after); - CommentTable::attach(&mut t.trailing, mod_type.pmty_loc.clone(), after_mod_type); - rest - } - None => rest, - }; + walk_signature(sig, t, comments, arena); + } + ModuleTypeDesc::Pmty_functor(_, _, _) => { + // Collect all functor parameters like OCaml's functor_type + let (parameters, return_mod_type) = functor_type_params(mt); + + // Walk parameters using list-based comment distribution + // This matches OCaml's visit_list_but_continue_with_remaining_comments + let comments = visit_list_but_continue_with_remaining_comments( + ¶meters, + |param, arena| { + // get_loc: compute the location for each parameter + // For "_" label, use just the mod_type location + // Otherwise, use label.loc to mod_type.loc.end (or just label.loc if no mod_type) + let (_, lbl, mod_type_option) = param; + match mod_type_option { + None => lbl.loc, + Some(mod_type) => { + if lbl.txt == "_" { + mod_type.pmty_loc + } else { + // Create a combined location from label start to mod_type end + arena.mk_loc_spanning(lbl.loc, mod_type.pmty_loc) + } + } + } + }, + |param, t, comments, arena| { + walk_mod_type_parameter(param, t, comments, arena); + }, + t, + comments, + false, // newline_delimited + arena, + ); - let (before, inside, after) = partition_by_loc(rest, &ret.pmty_loc); - CommentTable::attach(&mut t.leading, ret.pmty_loc.clone(), before); - walk_mod_type(ret, t, inside); - CommentTable::attach(&mut t.trailing, ret.pmty_loc.clone(), after); + // Walk return type with remaining comments + let (before, inside, after) = partition_by_loc(comments, return_mod_type.pmty_loc, arena); + t.attach_leading(return_mod_type.pmty_loc, before, arena); + walk_mod_type(return_mod_type, t, inside, arena); + t.attach_trailing(return_mod_type.pmty_loc, after, arena); } ModuleTypeDesc::Pmty_with(typ, constraints) => { - let (before, inside, after) = partition_by_loc(comments, &typ.pmty_loc); - CommentTable::attach(&mut t.leading, typ.pmty_loc.clone(), before); - walk_mod_type(typ, t, inside); + let (before, inside, after) = partition_by_loc(comments, typ.pmty_loc, arena); + t.attach_leading(typ.pmty_loc, before, arena); + walk_mod_type(typ, t, inside, arena); - let (after_typ, rest) = partition_adjacent_trailing(&typ.pmty_loc, after); - CommentTable::attach(&mut t.trailing, typ.pmty_loc.clone(), after_typ); + let (after_typ, rest) = partition_adjacent_trailing(typ.pmty_loc, after, arena); + t.attach_trailing(typ.pmty_loc, after_typ, arena); // Walk with constraints if needed for constraint in constraints { match constraint { WithConstraint::Pwith_type(lid, td) | WithConstraint::Pwith_typesubst(lid, td) => { - let (leading, trailing) = partition_leading_trailing(rest.clone(), &lid.loc); - CommentTable::attach(&mut t.leading, lid.loc.clone(), leading); - walk_type_declaration(td, t, trailing); + let (leading, trailing) = partition_leading_trailing(rest.clone(), lid.loc, arena); + t.attach_leading(lid.loc, leading, arena); + walk_type_declaration(td, t, trailing, arena); } WithConstraint::Pwith_module(mod_lid, target_lid) | WithConstraint::Pwith_modsubst(mod_lid, target_lid) => { - let (leading, trailing) = partition_leading_trailing(rest.clone(), &mod_lid.loc); - CommentTable::attach(&mut t.leading, mod_lid.loc.clone(), leading); - let (after_mod, rest2) = partition_adjacent_trailing(&mod_lid.loc, trailing); - CommentTable::attach(&mut t.trailing, mod_lid.loc.clone(), after_mod); - let (leading, trailing) = partition_leading_trailing(rest2, &target_lid.loc); - CommentTable::attach(&mut t.leading, target_lid.loc.clone(), leading); - CommentTable::attach(&mut t.trailing, target_lid.loc.clone(), trailing); + let (leading, trailing) = partition_leading_trailing(rest.clone(), mod_lid.loc, arena); + t.attach_leading(mod_lid.loc, leading, arena); + let (after_mod, rest2) = partition_adjacent_trailing(mod_lid.loc, trailing, arena); + t.attach_trailing(mod_lid.loc, after_mod, arena); + let (leading, trailing) = partition_leading_trailing(rest2, target_lid.loc, arena); + t.attach_leading(target_lid.loc, leading, arena); + t.attach_trailing(target_lid.loc, trailing, arena); } } } } ModuleTypeDesc::Pmty_typeof(me) => { - walk_module_expr(me, t, comments); + // Partition comments by the module expression location + // Leading comments attach to mod_expr.pmod_loc, not to items inside + let (leading, inside, trailing) = partition_by_loc(comments, me.pmod_loc, arena); + t.attach_leading(me.pmod_loc, leading, arena); + walk_module_expr(me, t, inside, arena); + t.attach_trailing(me.pmod_loc, trailing, arena); } ModuleTypeDesc::Pmty_extension(ext) => { - walk_extension(ext, t, comments); + walk_extension(ext, t, comments, arena); } ModuleTypeDesc::Pmty_alias(lid) => { - let (leading, trailing) = partition_leading_trailing(comments, &lid.loc); - CommentTable::attach(&mut t.leading, lid.loc.clone(), leading); - CommentTable::attach(&mut t.trailing, lid.loc.clone(), trailing); + let (leading, trailing) = partition_leading_trailing(comments, lid.loc, arena); + t.attach_leading(lid.loc, leading, arena); + t.attach_trailing(lid.loc, trailing, arena); } } } -fn walk_attribute(_attr: &Attribute, _t: &mut CommentTable, _comments: Vec) { - // Attributes don't have much structure to walk +fn walk_attribute(attr: &Attribute, t: &mut CommentTable, comments: Vec, arena: &mut ParseArena) { + let (name, payload) = attr; + let (leading, trailing) = partition_leading_trailing(comments, name.loc, arena); + t.attach_leading(name.loc, leading, arena); + + let (after_name, rest) = partition_adjacent_trailing(name.loc, trailing, arena); + t.attach_trailing(name.loc, after_name, arena); + + // Walk the payload + match payload { + PStr(items) => { + walk_structure(items, t, rest, arena); + } + PSig(items) => { + walk_signature(items, t, rest, arena); + } + PTyp(typ) => { + walk_core_type(typ, t, rest, arena); + } + PPat(pat, guard) => { + walk_pattern(pat, t, rest.clone(), arena); + if let Some(guard_expr) = guard { + walk_expression(guard_expr, t, Vec::new(), arena); + } + } + } } -fn walk_extension(ext: &Extension, t: &mut CommentTable, comments: Vec) { +fn walk_extension(ext: &Extension, t: &mut CommentTable, comments: Vec, arena: &mut ParseArena) { let (name, payload) = ext; - let (leading, trailing) = partition_leading_trailing(comments, &name.loc); - CommentTable::attach(&mut t.leading, name.loc.clone(), leading); + let (leading, trailing) = partition_leading_trailing(comments, name.loc, arena); + t.attach_leading(name.loc, leading, arena); match payload { PStr(items) => { if !items.is_empty() { - let (after_name, rest) = partition_adjacent_trailing(&name.loc, trailing); - CommentTable::attach(&mut t.trailing, name.loc.clone(), after_name); - walk_structure(items, t, rest); + let (after_name, rest) = partition_adjacent_trailing(name.loc, trailing, arena); + t.attach_trailing(name.loc, after_name, arena); + walk_structure(items, t, rest, arena); } else { - CommentTable::attach(&mut t.trailing, name.loc.clone(), trailing); + t.attach_trailing(name.loc, trailing, arena); } } PSig(items) => { if !items.is_empty() { - let (after_name, rest) = partition_adjacent_trailing(&name.loc, trailing); - CommentTable::attach(&mut t.trailing, name.loc.clone(), after_name); - walk_signature(items, t, rest); + let (after_name, rest) = partition_adjacent_trailing(name.loc, trailing, arena); + t.attach_trailing(name.loc, after_name, arena); + walk_signature(items, t, rest, arena); } else { - CommentTable::attach(&mut t.trailing, name.loc.clone(), trailing); + t.attach_trailing(name.loc, trailing, arena); } } PTyp(typ) => { - let (after_name, rest) = partition_adjacent_trailing(&name.loc, trailing); - CommentTable::attach(&mut t.trailing, name.loc.clone(), after_name); - walk_core_type(typ, t, rest); + let (after_name, rest) = partition_adjacent_trailing(name.loc, trailing, arena); + t.attach_trailing(name.loc, after_name, arena); + walk_core_type(typ, t, rest, arena); } PPat(pat, guard) => { - let (after_name, rest) = partition_adjacent_trailing(&name.loc, trailing); - CommentTable::attach(&mut t.trailing, name.loc.clone(), after_name); - walk_pattern(pat, t, rest.clone()); + let (after_name, rest) = partition_adjacent_trailing(name.loc, trailing, arena); + t.attach_trailing(name.loc, after_name, arena); + walk_pattern(pat, t, rest.clone(), arena); if let Some(guard_expr) = guard { - walk_expression(guard_expr, t, Vec::new()); + walk_expression(guard_expr, t, Vec::new(), arena); } } } } +/// Collect all functor parameters from a module type. +/// This is equivalent to OCaml's functor_type function. +fn functor_type_params(modtype: &ModuleType) -> (Vec<(&[Attribute], &crate::parser::ast::StringLoc, Option<&ModuleType>)>, &ModuleType) { + fn process<'a>( + acc: Vec<(&'a [Attribute], &'a crate::parser::ast::StringLoc, Option<&'a ModuleType>)>, + modtype: &'a ModuleType, + ) -> (Vec<(&'a [Attribute], &'a crate::parser::ast::StringLoc, Option<&'a ModuleType>)>, &'a ModuleType) { + match &modtype.pmty_desc { + ModuleTypeDesc::Pmty_functor(lbl, arg_type, return_type) => { + let mut new_acc = acc; + new_acc.push((&modtype.pmty_attributes, lbl, arg_type.as_ref().map(|t| t.as_ref()))); + process(new_acc, return_type) + } + _ => (acc, modtype), + } + } + process(Vec::new(), modtype) +} + +/// Walk a single functor parameter's comments. +/// This matches OCaml's walk_mod_type_parameter. +fn walk_mod_type_parameter( + param: &(&[Attribute], &crate::parser::ast::StringLoc, Option<&ModuleType>), + t: &mut CommentTable, + comments: Vec, + arena: &mut ParseArena, +) { + let (_attrs, lbl, mod_type_option) = param; + + let (leading, trailing) = partition_leading_trailing(comments, lbl.loc, arena); + t.attach_leading(lbl.loc, leading, arena); + + match mod_type_option { + None => { + t.attach_trailing(lbl.loc, trailing, arena); + } + Some(mod_type) => { + let (after_lbl, rest) = partition_adjacent_trailing(lbl.loc, trailing, arena); + t.attach_trailing(lbl.loc, after_lbl, arena); + let (before, inside, after) = partition_by_loc(rest, mod_type.pmty_loc, arena); + t.attach_leading(mod_type.pmty_loc, before, arena); + walk_mod_type(mod_type, t, inside, arena); + t.attach_trailing(mod_type.pmty_loc, after, arena); + } + } +} + /// Visit a list of nodes but return any remaining comments. fn visit_list_but_continue_with_remaining_comments<'a, T>( nodes: &'a [T], - get_loc: impl Fn(&'a T) -> &'a Location, - walk_node: impl Fn(&'a T, &mut CommentTable, Vec), + get_loc: impl Fn(&'a T, &mut ParseArena) -> LocIdx, + walk_node: impl Fn(&'a T, &mut CommentTable, Vec, &mut ParseArena), t: &mut CommentTable, comments: Vec, newline_delimited: bool, + arena: &mut ParseArena, ) -> Vec { - visit_list_impl(nodes, get_loc, walk_node, t, comments, newline_delimited, None) + visit_list_impl(nodes, get_loc, walk_node, t, comments, newline_delimited, None, arena) } fn visit_list_impl<'a, T>( nodes: &'a [T], - get_loc: impl Fn(&'a T) -> &'a Location, - walk_node: impl Fn(&'a T, &mut CommentTable, Vec), + get_loc: impl Fn(&'a T, &mut ParseArena) -> LocIdx, + walk_node: impl Fn(&'a T, &mut CommentTable, Vec, &mut ParseArena), t: &mut CommentTable, comments: Vec, newline_delimited: bool, - prev_loc: Option, + prev_loc: Option, + arena: &mut ParseArena, ) -> Vec { if comments.is_empty() { return Vec::new(); @@ -2199,11 +3073,11 @@ fn visit_list_impl<'a, T>( return match prev_loc { Some(loc) => { let (after_prev, rest) = if newline_delimited { - partition_by_on_same_line(&loc, comments) + partition_by_on_same_line(loc, comments, arena) } else { - partition_adjacent_trailing(&loc, comments) + partition_adjacent_trailing(loc, comments, arena) }; - CommentTable::attach(&mut t.trailing, loc, after_prev); + t.attach_trailing(loc, after_prev, arena); rest } None => comments, @@ -2212,31 +3086,35 @@ fn visit_list_impl<'a, T>( let node = &nodes[0]; let rest_nodes = &nodes[1..]; - let curr_loc = get_loc(node); + let curr_loc = get_loc(node, arena); + + let (leading, inside, trailing) = partition_by_loc(comments, curr_loc, arena); - let (leading, inside, trailing) = partition_by_loc(comments, curr_loc); + let prev_loc_resolved = prev_loc.map(|l| arena.to_location(l)); + let curr_loc_resolved = arena.to_location(curr_loc); match &prev_loc { None => { // First node, all leading comments attach here - CommentTable::attach(&mut t.leading, curr_loc.clone(), leading); + t.attach_leading(curr_loc, leading, arena); } - Some(prev_loc) => { + Some(prev_loc_idx) => { + let prev_loc_resolved = prev_loc_resolved.as_ref().unwrap(); // Check if on same line - if prev_loc.loc_end.line == curr_loc.loc_start.line { - let (after_prev, before_curr) = partition_adjacent_trailing(prev_loc, leading); - CommentTable::attach(&mut t.trailing, prev_loc.clone(), after_prev); - CommentTable::attach(&mut t.leading, curr_loc.clone(), before_curr); + if prev_loc_resolved.loc_end.line == curr_loc_resolved.loc_start.line { + let (after_prev, before_curr) = partition_adjacent_trailing(*prev_loc_idx, leading, arena); + t.attach_trailing(*prev_loc_idx, after_prev, arena); + t.attach_leading(curr_loc, before_curr, arena); } else { - let (on_same_line_as_prev, after_prev) = partition_by_on_same_line(prev_loc, leading); - CommentTable::attach(&mut t.trailing, prev_loc.clone(), on_same_line_as_prev); - let (before_curr, _, _) = partition_by_loc(after_prev, curr_loc); - CommentTable::attach(&mut t.leading, curr_loc.clone(), before_curr); + let (on_same_line_as_prev, after_prev) = partition_by_on_same_line(*prev_loc_idx, leading, arena); + t.attach_trailing(*prev_loc_idx, on_same_line_as_prev, arena); + let (before_curr, _, _) = partition_by_loc(after_prev, curr_loc, arena); + t.attach_leading(curr_loc, before_curr, arena); } } } - walk_node(node, t, inside); + walk_node(node, t, inside, arena); visit_list_impl( rest_nodes, get_loc, @@ -2244,20 +3122,21 @@ fn visit_list_impl<'a, T>( t, trailing, newline_delimited, - Some(curr_loc.clone()), + Some(curr_loc), + arena, ) } /// Create a comment table from a structure and comments. -pub fn make_for_structure(structure: &Structure, comments: Vec) -> CommentTable { +pub fn make_for_structure(structure: &[StructureItem], comments: Vec, arena: &mut ParseArena) -> CommentTable { let mut table = CommentTable::new(); - walk_structure(structure, &mut table, comments); + walk_structure(structure, &mut table, comments, arena); table } /// Create a comment table from a signature and comments. -pub fn make_for_signature(signature: &Signature, comments: Vec) -> CommentTable { +pub fn make_for_signature(signature: &[SignatureItem], comments: Vec, arena: &mut ParseArena) -> CommentTable { let mut table = CommentTable::new(); - walk_signature(signature, &mut table, comments); + walk_signature(signature, &mut table, comments, arena); table } diff --git a/compiler-rust/src/parser/core.rs b/compiler-rust/src/parser/core.rs index 928f73c5eca..b3221b77581 100644 --- a/compiler-rust/src/parser/core.rs +++ b/compiler-rust/src/parser/core.rs @@ -3,7 +3,9 @@ //! This module contains the main parsing functions that convert a token //! stream into an AST. It mirrors `res_core.ml` from the OCaml implementation. -use crate::location::{Located, Location, Position}; +use crate::intern::StrIdx; +use crate::location::Position; +use crate::parse_arena::{Located, LocIdx, ParseArena}; use super::ast::*; use super::diagnostics::DiagnosticCategory; @@ -16,21 +18,17 @@ use super::token::Token; // Location Helpers // ============================================================================ -/// Create a location from start and end positions. -pub fn mk_loc(start: &Position, end: &Position) -> Location { - Location::from_positions(start.clone(), end.clone()) -} - /// Create a located value with the given location. -pub fn with_loc(txt: T, loc: Location) -> Located { - Located { txt, loc } +pub fn with_loc(txt: T, loc: LocIdx) -> Loc { + Loc { txt, loc } } /// Create a located value with no location (ghost). -pub fn mknoloc(txt: T) -> Located { - Located { +/// Uses the pre-allocated "none" location at index 0. +pub fn mknoloc(txt: T) -> Loc { + Loc { txt, - loc: Location::none(), + loc: LocIdx::none(), } } @@ -47,7 +45,7 @@ pub mod recover { let id = mknoloc("rescript.exprhole".to_string()); Expression { pexp_desc: ExpressionDesc::Pexp_extension((id, Payload::PStr(vec![]))), - pexp_loc: Location::none(), + pexp_loc: LocIdx::none(), pexp_attributes: vec![], } } @@ -57,7 +55,7 @@ pub mod recover { let id = mknoloc("rescript.typehole".to_string()); CoreType { ptyp_desc: CoreTypeDesc::Ptyp_extension((id, Payload::PStr(vec![]))), - ptyp_loc: Location::none(), + ptyp_loc: LocIdx::none(), ptyp_attributes: vec![], } } @@ -67,7 +65,7 @@ pub mod recover { let id = mknoloc("rescript.patternhole".to_string()); Pattern { ppat_desc: PatternDesc::Ppat_extension((id, Payload::PStr(vec![]))), - ppat_loc: Location::none(), + ppat_loc: LocIdx::none(), ppat_attributes: vec![], } } @@ -76,7 +74,7 @@ pub mod recover { pub fn default_module_expr() -> ModuleExpr { ModuleExpr { pmod_desc: ModuleExprDesc::Pmod_structure(vec![]), - pmod_loc: Location::none(), + pmod_loc: LocIdx::none(), pmod_attributes: vec![], } } @@ -85,11 +83,21 @@ pub mod recover { pub fn default_module_type() -> ModuleType { ModuleType { pmty_desc: ModuleTypeDesc::Pmty_signature(vec![]), - pmty_loc: Location::none(), + pmty_loc: LocIdx::none(), pmty_attributes: vec![], } } + /// Create a default signature item for error recovery. + /// Used when an attribute is found without an item to attach it to. + pub fn default_signature_item() -> SignatureItem { + let id = mknoloc("rescript.sigitemhole".to_string()); + SignatureItem { + psig_desc: SignatureItemDesc::Psig_extension((id, Payload::PStr(vec![])), vec![]), + psig_loc: LocIdx::none(), + } + } + /// Recover from missing `=>` by also accepting `->`. pub fn recover_equal_greater(p: &mut Parser<'_>) { p.expect(Token::EqualGreater); @@ -107,6 +115,49 @@ pub mod recover { } false } + + /// Skip tokens and maybe retry parsing. + /// + /// This matches OCaml's `skip_tokens_and_maybe_retry` which is used in error recovery. + /// It skips over unexpected tokens and returns true if parsing should be retried + /// (i.e., we found a token that can start the grammar we're looking for). + /// + /// Logic: + /// 1. If current token is a keyword AND on same line as previous, skip and don't retry + /// 2. If we should abort list parse: + /// - If current token can start our grammar, DON'T advance, return true (retry) + /// - Else return false (don't retry) + /// 3. Else: + /// - Skip tokens until we should abort list parse + /// - If we end up at a valid start token, return true (retry) + /// - Else return false (don't retry) + pub fn skip_tokens_and_maybe_retry(p: &mut Parser<'_>, is_start_of_grammar: F) -> bool + where + F: Fn(&Token) -> bool, + { + // Case 1: keyword on same line - skip it and don't retry + if p.token.is_keyword() && p.prev_end_pos.line == p.start_pos.line { + p.next(); + return false; + } + + // Case 2: should abort list parse + if should_abort_list_parse(p) { + // If current token can start our grammar, retry without advancing + if is_start_of_grammar(&p.token) { + return true; + } + return false; + } + + // Case 3: normal recovery - skip until we should abort or find start + p.next(); + while !should_abort_list_parse(p) { + p.next(); + } + + is_start_of_grammar(&p.token) + } } // ============================================================================ @@ -154,8 +205,7 @@ pub mod error_messages { "String interpolation is not supported in pattern matching."; /// Error message for type definition in function. - pub const TYPE_DEFINITION_IN_FUNCTION: &str = "Type definitions are not allowed inside functions.\n\ - Move this `type` declaration to the top level or into a module."; + pub const TYPE_DEFINITION_IN_FUNCTION: &str = "Type definitions are not allowed inside functions.\n Move this `type` declaration to the top level or into a module."; /// Error message for type param. pub const TYPE_PARAM: &str = @@ -193,6 +243,124 @@ pub mod error_messages { attr_name, attr_name ) } + + /// Generate error message for keyword used as record field name in expressions. + pub fn keyword_field_in_expr(keyword_txt: &str) -> String { + format!( + "Cannot use keyword `{}` as a record field name. Suggestion: rename it (e.g. `{}_`)", + keyword_txt, keyword_txt + ) + } + + /// Generate error message for keyword used as record field name in patterns. + pub fn keyword_field_in_pattern(keyword_txt: &str) -> String { + format!( + "Cannot use keyword `{}` here. Keywords are not allowed as record field names.", + keyword_txt + ) + } + + /// Generate error message for keyword used as record field name in type declarations. + pub fn keyword_field_in_type(keyword_txt: &str) -> String { + format!( + "Cannot use keyword `{}` as a record field name. Suggestion: rename it (e.g. `{}_`)\n \ + If you need the field to be \"{}\" at runtime, annotate the field: `@as(\"{}\") {}_ : ...`", + keyword_txt, keyword_txt, keyword_txt, keyword_txt, keyword_txt + ) + } +} + +// ============================================================================ +// Keyword Field Error Handling +// ============================================================================ + +/// Emit an error for keyword used as record field name. +/// OCaml: emit_keyword_field_error +pub fn emit_keyword_field_error(p: &mut Parser<'_>, mk_message: F) +where + F: Fn(&str) -> String, +{ + let keyword_txt = format!("{}", p.token); + let keyword_start = p.start_pos.clone(); + let keyword_end = p.end_pos.clone(); + p.err_at( + keyword_start, + keyword_end, + DiagnosticCategory::Message(mk_message(&keyword_txt)), + ); +} + +/// Recover a keyword used as field name if it's probably a full field name (not punning). +/// Checks if there's a colon after it, in which case we recover by appending "_" to the name. +/// OCaml: recover_keyword_field_name_if_probably_field +pub fn recover_keyword_field_name_if_probably_field( + p: &mut Parser<'_>, + mk_message: F, +) -> Option<(String, LocIdx)> +where + F: Fn(&str) -> String, +{ + if p.token.is_keyword() + && p.lookahead(|st| { + st.next(); + st.token == Token::Colon + }) + { + emit_keyword_field_error(p, mk_message); + let loc = p.mk_loc_current(); + let recovered_field_name = format!("{}_", p.token); + p.next(); + Some((recovered_field_name, loc)) + } else { + None + } +} + +// ============================================================================ +// Identifier Parsing +// ============================================================================ + +/// Parse an identifier (lident or uident) with custom error message. +/// OCaml: parse_ident ~msg ~start_pos p +/// +/// Logic: +/// 1. If token is Lident/Uident: return it +/// 2. If token is a keyword on the same line: emit "keyword reserved" error, return keyword +/// 3. Otherwise: emit the custom msg, advance and return empty string +pub fn parse_ident(p: &mut Parser<'_>, msg: &str, start_pos: Position) -> (String, LocIdx) { + match &p.token { + Token::Lident(ident) | Token::Uident(ident) => { + let ident = ident.clone(); + p.next(); + let loc = p.mk_loc_to_prev_end(&start_pos); + (ident, loc) + } + token if token.is_keyword() && p.prev_end_pos.line == p.start_pos.line => { + let token_txt = format!("{}", p.token); + let err_msg = format!( + "`{}` is a reserved keyword. Keywords need to be escaped: \\\"{}\"", + token_txt, token_txt + ); + p.err_at( + start_pos.clone(), + p.end_pos.clone(), + DiagnosticCategory::Message(err_msg), + ); + p.next(); + let loc = p.mk_loc_to_prev_end(&start_pos); + (token_txt, loc) + } + _ => { + p.err_at( + start_pos.clone(), + p.end_pos.clone(), + DiagnosticCategory::Message(msg.to_string()), + ); + p.next(); + let loc = p.mk_loc_to_prev_end(&start_pos); + (String::new(), loc) + } + } } // ============================================================================ @@ -352,19 +520,46 @@ pub fn doc_comment_to_attribute(loc: Location, content: String) -> Attribute { // ============================================================================ /// Build a Longident from a list of strings (in order). -pub fn build_longident(words: &[String]) -> Longident { +/// +/// Note: Strings are pushed (not interned) since they come from user input +/// and should NOT be shared during marshalling. +pub fn build_longident(arena: &mut ParseArena, words: &[String]) -> Longident { let mut iter = words.iter(); let first = iter.next().expect("build_longident: empty words"); - let mut result = Longident::Lident(first.clone()); + let first_idx = arena.push_string(first.clone()); + let mut result = Longident::Lident(first_idx); for word in iter { - result = Longident::Ldot(Box::new(result), word.clone()); + let word_idx = arena.push_string(word.clone()); + result = Longident::Ldot(Box::new(result), word_idx); } result } -/// Get the last component of a longident. -pub fn lident_of_path(longident: &Longident) -> String { - longident.last().to_string() +/// Build a longident from a list of path components and push to arena. +/// Returns the arena index for proper sharing during marshalling. +pub fn build_longident_idx(p: &mut Parser<'_>, words: &[String]) -> crate::parse_arena::LidentIdx { + let lid = build_longident(p.arena_mut(), words); + p.push_longident(lid) +} + +/// Create a simple Lident from a dynamic string (from user input). +/// Uses push (not intern) so strings are NOT shared during marshalling. +pub fn make_lident(arena: &mut ParseArena, name: impl Into) -> Longident { + let str_idx = arena.push_string(name.into()); + Longident::Lident(str_idx) +} + +/// Create a simple Lident from a static string (operator, keyword, etc.). +/// Uses intern so identical strings ARE shared during marshalling. +pub fn make_lident_static(arena: &mut ParseArena, name: &str) -> Longident { + let str_idx = arena.intern_string(name); + Longident::Lident(str_idx) +} + +/// Get the last component of a longident as a string. +/// Requires arena to look up the StrIdx. +pub fn lident_of_path(arena: &ParseArena, longident: &Longident) -> String { + arena.get_string(longident.last_idx()).to_string() } // ============================================================================ @@ -402,9 +597,15 @@ pub mod ast_helper { } } - /// Create an identifier expression. - pub fn make_ident(lid: Longident, loc: Location) -> Expression { - make_expr(ExpressionDesc::Pexp_ident(with_loc(lid, loc.clone())), loc) + /// Create an identifier expression with arena-allocated longident. + pub fn make_ident_idx(lid_idx: crate::parse_arena::LidentIdx, loc: Location) -> Expression { + make_expr(ExpressionDesc::Pexp_ident(with_loc(lid_idx, loc.clone())), loc) + } + + /// Create an identifier expression (allocates in arena). + pub fn make_ident(p: &mut Parser<'_>, lid: Longident, loc: Location) -> Expression { + let lid_idx = p.push_longident(lid); + make_expr(ExpressionDesc::Pexp_ident(with_loc(lid_idx, loc.clone())), loc) } /// Create a constant expression. @@ -412,11 +613,12 @@ pub mod ast_helper { make_expr(ExpressionDesc::Pexp_constant(constant), loc) } - /// Create a unit expression: () - pub fn make_unit(loc: Location) -> Expression { + /// Create a unit expression: () (requires parser for arena allocation) + pub fn make_unit(p: &mut Parser<'_>, loc: Location) -> Expression { + let lid_idx = p.push_lident_static("()"); make_expr( ExpressionDesc::Pexp_construct( - with_loc(Longident::Lident("()".to_string()), loc.clone()), + with_loc(lid_idx, loc.clone()), None, ), loc, @@ -482,43 +684,46 @@ pub mod ast_helper { /// - lid_loc: Just the constructor name (e.g., `Some` at columns 28-32) /// - ppat_loc: Full pattern extent (e.g., `Some(y)` at columns 28-35) pub fn make_construct_pat( - lid: Longident, + lid_idx: crate::parse_arena::LidentIdx, arg: Option, lid_loc: Location, ppat_loc: Location, ) -> Pattern { make_pat( - PatternDesc::Ppat_construct(with_loc(lid, lid_loc), arg.map(Box::new)), + PatternDesc::Ppat_construct(with_loc(lid_idx, lid_loc), arg.map(Box::new)), ppat_loc, ) } /// Create a list pattern `[a, b, ...rest]`. pub fn make_list_pattern( - p: &Parser<'_>, + p: &mut Parser<'_>, loc: Location, items: Vec, spread: Option, ) -> Pattern { + // Pre-allocate list constructor longidents + let nil_idx = p.push_lident_static("[]"); + let cons_idx = p.push_lident_static("::"); + // Build from the end: start with spread or [] let mut result = match spread { Some(pat) => pat, None => { - let nil_loc = Location { - loc_ghost: true, - ..loc.clone() - }; - let nil = with_loc(Longident::Lident("[]".to_string()), nil_loc.clone()); + // Use a ghost location with the same positions as loc + // This matches OCaml's behavior: Location { loc_ghost: true, ..loc } + let nil_loc = p.arena_mut().mk_ghost_loc(loc); + let nil = with_loc(nil_idx, nil_loc); make_pat(PatternDesc::Ppat_construct(nil, None), nil_loc) } }; // Build :: chain from the end for item in items.into_iter().rev() { - let tuple_loc = p.mk_loc(&item.ppat_loc.loc_start, &result.ppat_loc.loc_end); - let cons_loc = tuple_loc.clone(); + let tuple_loc = p.mk_loc(&p.loc_start(item.ppat_loc), &p.loc_end(result.ppat_loc)); + let cons_loc = tuple_loc; let tuple = make_pat(PatternDesc::Ppat_tuple(vec![item, result]), tuple_loc); - let cons = with_loc(Longident::Lident("::".to_string()), cons_loc.clone()); + let cons = with_loc(cons_idx, cons_loc); result = make_pat( PatternDesc::Ppat_construct(cons, Some(Box::new(tuple))), cons_loc, @@ -537,12 +742,12 @@ pub mod ast_helper { /// - ptyp_loc: full extent including type arguments /// This matches OCaml's behavior. pub fn make_type_constr( - lid: Longident, + lid_idx: crate::parse_arena::LidentIdx, args: Vec, lid_loc: Location, ptyp_loc: Location, ) -> CoreType { - make_typ(CoreTypeDesc::Ptyp_constr(with_loc(lid, lid_loc), args), ptyp_loc) + make_typ(CoreTypeDesc::Ptyp_constr(with_loc(lid_idx, lid_loc), args), ptyp_loc) } } @@ -561,7 +766,7 @@ fn negate_string(s: &str) -> String { /// Create a unary expression from an operator token and operand. pub fn make_unary_expr( - p: &Parser<'_>, + p: &mut Parser<'_>, start_pos: Position, token_end: Position, token: Token, @@ -611,25 +816,41 @@ pub fn make_unary_expr( format!("~{}", token_string) }; - let op_expr = ast_helper::make_ident(Longident::Lident(operator), token_loc); - let loc = p.mk_loc(&start_pos, &operand.pexp_loc.loc_end); + let op_lid = make_lident_static(p.arena_mut(), &operator); + let op_expr = ast_helper::make_ident(p, op_lid, token_loc); + let loc = p.mk_loc(&start_pos, &p.loc_end(operand.pexp_loc)); ast_helper::make_apply(op_expr, vec![(ArgLabel::Nolabel, operand)], loc) } /// Create an infix operator expression. +/// When `=` is used as a binary operator (which is likely a mistake - should be `==`), +/// emit a helpful error message. pub fn make_infix_operator( - p: &Parser<'_>, + p: &mut Parser<'_>, token: Token, start_pos: Position, end_pos: Position, ) -> Expression { - let stringified_token = token.to_string(); + // Special handling for = used as binary operator + // This is likely a mistake - user probably meant == + let stringified_token = if token == Token::Equal { + // TODO: could have a totally different meaning like x->fooSet(y) + p.err_at( + start_pos.clone(), + end_pos.clone(), + super::diagnostics::DiagnosticCategory::Message( + "Did you mean `==` here?".to_string(), + ), + ); + "=".to_string() + } else { + token.to_string() + }; let loc = p.mk_loc(&start_pos, &end_pos); - let operator = with_loc(Longident::Lident(stringified_token), loc.clone()); - - ast_helper::make_ident(operator.txt, loc) + let op_lid = make_lident_static(p.arena_mut(), &stringified_token); + ast_helper::make_ident(p, op_lid, loc) } // ============================================================================ @@ -837,11 +1058,15 @@ mod tests { #[test] fn test_mk_loc() { + use crate::parse_arena::ParseArena; + let mut arena = ParseArena::new(); let start = Position::new("test.res", 1, 0, 0); let end = Position::new("test.res", 1, 0, 10); - let loc = mk_loc(&start, &end); - assert_eq!(loc.loc_start, start); - assert_eq!(loc.loc_end, end); + let loc_idx = arena.mk_loc_from_positions(&start, &end); + // Verify the location can be retrieved from the arena + let full_loc = arena.to_location(loc_idx); + assert_eq!(full_loc.loc_start, start); + assert_eq!(full_loc.loc_end, end); } #[test] @@ -934,7 +1159,7 @@ mod tests { #[test] fn test_ast_helper_make_expr() { - let loc = Location::none(); + let loc = LocIdx::none(); let expr = ast_helper::make_expr( ExpressionDesc::Pexp_constant(Constant::Integer("42".to_string(), None)), loc.clone(), @@ -947,7 +1172,7 @@ mod tests { #[test] fn test_ast_helper_make_var_pat() { - let loc = Location::none(); + let loc = LocIdx::none(); let pat = ast_helper::make_var_pat("x".to_string(), loc); assert!(matches!(pat.ppat_desc, PatternDesc::Ppat_var(_))); } diff --git a/compiler-rust/src/parser/diagnostics.rs b/compiler-rust/src/parser/diagnostics.rs index d2b16b6ca33..c3383e161a7 100644 --- a/compiler-rust/src/parser/diagnostics.rs +++ b/compiler-rust/src/parser/diagnostics.rs @@ -6,6 +6,7 @@ use crate::location::{Location, Position}; use serde::{Deserialize, Serialize}; +use super::grammar::Grammar; use super::token::Token; /// A category of diagnostic message. @@ -16,12 +17,12 @@ pub enum DiagnosticCategory { /// The unexpected token. token: Token, /// The parsing context (stack of grammar rules being parsed). - context: Vec<(String, Position)>, + context: Vec<(Grammar, Position)>, }, /// An expected token was not found. Expected { /// The expected grammar context. - context: Option, + context: Option, /// Position of the previous token. pos: Position, /// The expected token. @@ -90,20 +91,34 @@ impl ParserDiagnostic { /// Explain the diagnostic as a human-readable message. pub fn explain(&self) -> String { + self.explain_with_source(None) + } + + /// Explain the diagnostic with optional source code for special error handling. + /// OCaml has special cases for detecting old syntax like `|>` and `[|...|]`. + pub fn explain_with_source(&self, src: Option<&str>) -> String { match &self.category { - DiagnosticCategory::Unexpected { token, context: _ } => { - if token.is_keyword() { - let name = format!("{}", token); - format!( - "`{}` is a reserved keyword. Keywords need to be escaped: \\\"{}\"", - name, name - ) - } else { - format!( - "I'm not sure what to parse here when looking at \"{}\".", - token - ) + DiagnosticCategory::Unexpected { token, context } => { + let base = explain_unexpected(token, context); + // OCaml: special handling for old data-last pipe |> and array syntax [|...|] + if let (Token::Bar, Some(source)) = (token, src) { + let idx_prev = self.start_pos.cnum.saturating_sub(1) as usize; + let idx_next = self.end_pos.cnum as usize; + let bytes = source.as_bytes(); + // Check for [| (old array literal syntax) + if idx_prev < bytes.len() && bytes[idx_prev] == b'[' { + return base + "\n\n Did you mean to write an array literal? \ + Arrays are written with `[ ... ]` (not `[| ... |]`).\n \ + Quick fix: replace `[|` with `[` and `|]` with `]`.\n \ + Example: `[|1, 2, 3|]` -> `[1, 2, 3]`"; + } + // Check for |> (old data-last pipe) + if idx_next < bytes.len() && bytes[idx_next] == b'>' { + return base + "\n\n The old data-last pipe `|>` has been removed \ + from the language.\n Refactor to use a data-first `->` pipe instead."; + } } + base } DiagnosticCategory::Expected { token, context, .. } => { let hint = match context { @@ -137,7 +152,8 @@ impl ParserDiagnostic { ) } Token::Underscore => "`_` isn't a valid name.".to_string(), - _ => "I'm expecting a lowercase name like `user` or `age`".to_string(), + // OCaml has a typo in this message - missing backtick after "user" + _ => "I'm expecting a lowercase name like `user or `age`".to_string(), }, DiagnosticCategory::UnclosedString => { "This string is missing a double quote at the end".to_string() @@ -173,15 +189,158 @@ fn uncapitalize_first(s: &str) -> String { } } +/// Default message for unexpected tokens. +fn default_unexpected(token: &Token) -> String { + format!( + "I'm not sure what to parse here when looking at \"{}\".", + token + ) +} + +/// Explain an unexpected token based on parsing context (breadcrumbs). +/// This matches OCaml's explain function in res_diagnostics.ml. +/// +/// Note: In OCaml, breadcrumbs are stored with the most recent at the head (prepended). +/// In Rust, we append to Vec, so the most recent breadcrumb is at the END. +/// We need to iterate from the end to match OCaml's pattern matching behavior. +fn explain_unexpected(token: &Token, context: &[(Grammar, Position)]) -> String { + use super::grammar; + + // Check if token is a reserved keyword first (OCaml does this at the end, but it's the same) + let reserved_keyword = |t: &Token| { + let name = format!("{}", t); + format!( + "`{}` is a reserved keyword. Keywords need to be escaped: \\\"{}\"", + name, name + ) + }; + + if context.is_empty() { + if token.is_keyword() { + return reserved_keyword(token); + } + return default_unexpected(token); + } + + // OCaml uses (head :: rest) pattern, where head is most recent. + // In Rust Vec, most recent is at the end, so we use last() and slice before it. + let (most_recent, _) = context.last().unwrap(); + let rest = &context[..context.len() - 1]; + + // Helper to get the "next" breadcrumb (second most recent) + let next_grammar = rest.last().map(|(g, _)| g); + + match most_recent { + // AtomicTypExpr context + Grammar::AtomicTypExpr => { + // Check next grammar context + if let Some(next) = next_grammar { + match (next, token) { + // In record field declarations + (Grammar::StringFieldDeclarations | Grammar::FieldDeclarations, + Token::String(_) | Token::At | Token::Rbrace | Token::Comma | Token::Eof) => { + return "I'm missing a type here".to_string(); + } + _ => {} + } + } + // Check if token is a structure item start or EOF + if grammar::is_structure_item_start(token) || *token == Token::Eof { + return "Missing a type here".to_string(); + } + default_unexpected(token) + } + + // ExprOperand context + Grammar::ExprOperand => { + if let Some(next) = next_grammar { + match (next, token) { + // Empty expression block + (Grammar::ExprBlock, Token::Rbrace) => { + return "It seems that this expression block is empty".to_string(); + } + // Pattern matching + (Grammar::ExprBlock, Token::Bar) => { + return "Looks like there might be an expression missing here".to_string(); + } + // Record field mutation + (Grammar::ExprSetField, _) => { + return "It seems that this record field mutation misses an expression".to_string(); + } + // Array mutation + (Grammar::ExprArrayMutation, _) => { + return "Seems that an expression is missing, with what do I mutate the array?".to_string(); + } + // After binary operator or unary + (Grammar::ExprBinaryAfterOp(_) | Grammar::ExprUnary, _) => { + return "Did you forget to write an expression here?".to_string(); + } + // Let binding + (Grammar::LetBinding, _) => { + return "This let-binding misses an expression".to_string(); + } + _ => {} + } + } + // Check rest of the context (has remaining breadcrumbs) + if !rest.is_empty() && matches!(token, Token::Rbracket | Token::Rbrace | Token::Eof) { + return "Missing expression".to_string(); + } + default_unexpected(token) + } + + // TypeParam context + Grammar::TypeParam => { + if let Token::Lident(ident) = token { + return format!("Did you mean '{}? A Type parameter starts with a quote.", ident); + } + default_unexpected(token) + } + + // Pattern context + Grammar::Pattern => { + if let Some(next) = next_grammar { + match (token, next) { + // Missing name in let binding + (Token::Equal, Grammar::LetBinding) => { + return "I was expecting a name for this let-binding. Example: `let message = \"hello\"`".to_string(); + } + // For loop + (Token::In, Grammar::ExprFor) => { + return "A for-loop has the following form: `for i in 0 to 10`. Did you forget to supply a name before `in`?".to_string(); + } + // Pattern match case + (Token::EqualGreater, Grammar::PatternMatchCase) => { + return "I was expecting a pattern to match on before the `=>`".to_string(); + } + _ => {} + } + } + if token.is_keyword() { + return reserved_keyword(token); + } + default_unexpected(token) + } + + // Default case + _ => { + if token.is_keyword() { + return reserved_keyword(token); + } + default_unexpected(token) + } + } +} + /// Convenience constructors for diagnostic categories. impl DiagnosticCategory { /// Create an unexpected token diagnostic. - pub fn unexpected(token: Token, context: Vec<(String, Position)>) -> Self { + pub fn unexpected(token: Token, context: Vec<(Grammar, Position)>) -> Self { DiagnosticCategory::Unexpected { token, context } } /// Create an expected token diagnostic. - pub fn expected(token: Token, pos: Position, context: Option) -> Self { + pub fn expected(token: Token, pos: Position, context: Option) -> Self { DiagnosticCategory::Expected { token, pos, diff --git a/compiler-rust/src/parser/doc.rs b/compiler-rust/src/parser/doc.rs index 65bd06ae323..b99b1c2b1e7 100644 --- a/compiler-rust/src/parser/doc.rs +++ b/compiler-rust/src/parser/doc.rs @@ -315,13 +315,27 @@ impl Doc { } } - /// Check if the document fits within the given width - fn fits(width: i32, stack: &[(i32, Mode, &Doc)]) -> bool { + /// Check if the document fits within the given width. + /// Takes the current item and the rest of the stack as a slice to avoid cloning. + fn fits(width: i32, first: (i32, Mode, &Doc), rest: &[(i32, Mode, &Doc)]) -> bool { let mut width = width; - let mut stack: Vec<(i32, Mode, &Doc)> = stack.to_vec(); + // Create a stack: first the rest items (same order - they'll be processed later), + // then the first item (which will be popped and processed first) + let mut stack: Vec<(i32, Mode, &Doc)> = Vec::with_capacity(rest.len() + 1); + // Push rest items in order (they'll be processed after first) + for item in rest.iter() { + stack.push(*item); + } + // Push the first item last so it gets processed first (popped first) + stack.push(first); + + // Limit iterations to prevent exponential blowup with deeply nested custom layouts + let mut iterations = 0; + const MAX_ITERATIONS: i32 = 10000; while let Some((indent, mode, doc)) = stack.pop() { - if width < 0 { + iterations += 1; + if iterations > MAX_ITERATIONS || width < 0 { return false; } @@ -460,8 +474,10 @@ impl Doc { } } Doc::Group { should_break, doc } => { + // Include remaining stack in fits check (like OCaml) + // Pass stack as slice reference to avoid cloning if should_break.get() - || !Self::fits(width - pos, &[(indent, Mode::Flat, doc)]) + || !Self::fits(width - pos, (indent, Mode::Flat, doc), &stack) { stack.push((indent, Mode::Break, doc)); } else { @@ -470,9 +486,11 @@ impl Doc { } Doc::CustomLayout(docs) => { // Find the first layout that fits, or use the last one + // Include remaining stack in fits check (like OCaml) + // Pass stack as slice reference to avoid cloning let mut chosen = docs.last(); for doc in docs.iter() { - if Self::fits(width - pos, &[(indent, Mode::Flat, doc)]) { + if Self::fits(width - pos, (indent, Mode::Flat, doc), &stack) { chosen = Some(doc); break; } @@ -489,9 +507,72 @@ impl Doc { stack.push((indent, mode, doc)); } while let Some((indent, mode, doc)) = stack.pop() { - // Simplified processing for remaining suffices - if let Doc::Text(txt) = doc { - buffer.push_str(txt); + match doc { + Doc::Nil | Doc::BreakParent | Doc::LineSuffix(_) => {} + Doc::Text(txt) => { + buffer.push_str(txt); + pos += txt.len() as i32; + } + Doc::Concat(docs) => { + for doc in docs.iter().rev() { + stack.push((indent, mode, doc)); + } + } + Doc::Indent(doc) => { + stack.push((indent + 2, mode, doc)); + } + Doc::LineBreak(style) => { + if mode == Mode::Break { + if *style == LineStyle::Literal { + buffer.push('\n'); + pos = 0; + } else { + let trimmed_len = buffer.trim_end_matches(' ').len(); + buffer.truncate(trimmed_len); + buffer.push('\n'); + if indent > 0 { + buffer.push_str(&" ".repeat(indent as usize)); + } + pos = indent; + } + } else { + // Flat mode + match style { + LineStyle::Classic => { + buffer.push(' '); + pos += 1; + } + LineStyle::Hard => { + let trimmed_len = buffer.trim_end_matches(' ').len(); + buffer.truncate(trimmed_len); + buffer.push('\n'); + pos = 0; + } + LineStyle::Literal => { + buffer.push('\n'); + pos = 0; + } + LineStyle::Soft => {} + } + } + } + Doc::Group { doc: contents, should_break } => { + let mode = if should_break.get() { Mode::Break } else { Mode::Flat }; + stack.push((indent, mode, contents)); + } + Doc::IfBreaks { yes, no, .. } => { + if mode == Mode::Break { + stack.push((indent, mode, yes)); + } else { + stack.push((indent, mode, no)); + } + } + Doc::CustomLayout(docs) => { + // Use the first option + if let Some(first) = docs.first() { + stack.push((indent, mode, first)); + } + } } } diff --git a/compiler-rust/src/parser/expr.rs b/compiler-rust/src/parser/expr.rs index 3de544d737f..d0920850ec3 100644 --- a/compiler-rust/src/parser/expr.rs +++ b/compiler-rust/src/parser/expr.rs @@ -3,10 +3,11 @@ //! This module contains the expression parsing logic, converting tokens //! into expression AST nodes. -use crate::location::{Located, Location, Position}; +use crate::location::Position; +use crate::parse_arena::{LidentIdx, Located, LocIdx, ParseArena}; use super::ast::*; -use super::core::{ExprContext, ast_helper, make_braces_attr, mknoloc, recover, with_loc}; +use super::core::{ExprContext, ast_helper, if_let_attr, make_braces_attr, mknoloc, recover, with_loc}; use super::diagnostics::DiagnosticCategory; use super::grammar; use super::grammar::Grammar; @@ -52,9 +53,15 @@ pub fn parse_constant(p: &mut Parser<'_>) -> Constant { } Token::Codepoint { c, original } => { let value = *c; - let _orig = original.clone(); + let orig = original.clone(); p.next(); - Constant::Char(value) + // When parsing for the printer (not type checker), preserve the original escape format + // by encoding it as a string with a special prefix, like OCaml does. + if p.mode == ParserMode::ParseForTypeChecker { + Constant::Char(value) + } else { + Constant::String(orig, Some("INTERNAL_RES_CHAR_CONTENTS".to_string())) + } } _ => { p.err(DiagnosticCategory::Message("Expected constant".to_string())); @@ -67,23 +74,50 @@ pub fn parse_constant(p: &mut Parser<'_>) -> Constant { // Placeholder Transformation // ============================================================================ +/// Check and emit "consecutive expressions" error if expressions on same line without semicolon. +/// +/// Matches OCaml's `parse_newline_or_semicolon_expr_block`: +/// - If token is Semicolon, consume it +/// - If token can start a block expression AND on same line as previous, emit error +/// - Otherwise, do nothing +pub fn parse_newline_or_semicolon_expr_block(p: &mut Parser<'_>) { + if p.token == Token::Semicolon { + p.next(); + return; + } + + if grammar::is_block_expr_start(&p.token) { + // Check if we're on the same line as the previous token + // OCaml: if p.prev_end_pos.pos_lnum < p.start_pos.pos_lnum then () else err + if p.prev_end_pos.line >= p.start_pos.line { + // Same line: emit error + // Use err_at which respects regions (like OCaml's Parser.err) + p.err_at( + p.prev_end_pos.clone(), + p.end_pos.clone(), + DiagnosticCategory::message( + "consecutive expressions on a line must be separated by ';' or a newline", + ), + ); + } + } +} + /// Check if an expression is the underscore placeholder `_` -fn is_underscore_placeholder(expr: &Expression) -> bool { - matches!( - &expr.pexp_desc, - ExpressionDesc::Pexp_ident(loc) if matches!(&loc.txt, Longident::Lident(s) if s == "_") - ) +fn is_underscore_placeholder(expr: &Expression, arena: &ParseArena) -> bool { + match &expr.pexp_desc { + ExpressionDesc::Pexp_ident(loc) => arena.is_lident(loc.txt, "_"), + _ => false, + } } /// Replace underscore placeholders with a reference to the given variable name -fn replace_underscores_in_expr(expr: Expression, var_name: &str) -> Expression { - if is_underscore_placeholder(&expr) { +fn replace_underscores_in_expr(expr: Expression, var_name: &str, arena: &mut ParseArena) -> Expression { + if is_underscore_placeholder(&expr, arena) { let loc = expr.pexp_loc.clone(); + let lid_idx = arena.push_lident(var_name); Expression { - pexp_desc: ExpressionDesc::Pexp_ident(with_loc( - Longident::Lident(var_name.to_string()), - loc.clone(), - )), + pexp_desc: ExpressionDesc::Pexp_ident(with_loc(lid_idx, loc.clone())), pexp_loc: loc, pexp_attributes: vec![], } @@ -99,6 +133,7 @@ fn transform_placeholder_application( args: Vec<(ArgLabel, Expression)>, partial: bool, loc: Location, + arena: &mut ParseArena, ) -> Expression { // Find the LAST underscore placeholder and get its location // OCaml uses a mutable ref that gets overwritten for each underscore found, @@ -106,7 +141,7 @@ fn transform_placeholder_application( let underscore_loc = args .iter() .filter_map(|(_, expr)| { - if is_underscore_placeholder(expr) { + if is_underscore_placeholder(expr, arena) { Some(expr.pexp_loc.clone()) } else { None @@ -135,7 +170,7 @@ fn transform_placeholder_application( let var_name = "__x"; let transformed_args: Vec<(ArgLabel, Expression)> = args .into_iter() - .map(|(label, expr)| (label, replace_underscores_in_expr(expr, var_name))) + .map(|(label, expr)| (label, replace_underscores_in_expr(expr, var_name, arena))) .collect(); // Create the inner Pexp_apply @@ -154,7 +189,7 @@ fn transform_placeholder_application( // OCaml: pattern has ppat_loc: Location.none, but StringLoc uses underscore's location let pattern = Pattern { ppat_desc: PatternDesc::Ppat_var(with_loc(var_name.to_string(), underscore_loc.clone())), - ppat_loc: Location::none(), + ppat_loc: LocIdx::none(), ppat_attributes: vec![], }; @@ -178,12 +213,14 @@ fn transform_placeholder_application( /// Parse a value path after a dot (for field access). /// This parses things like `Lexing.pos_fname` into a Longident. -fn parse_value_path_after_dot(p: &mut Parser<'_>) -> Located { +fn parse_value_path_after_dot(p: &mut Parser<'_>) -> Located { let start_pos = p.start_pos.clone(); match &p.token { Token::Uident(name) => { - let mut path = Longident::Lident(name.clone()); + let name = name.clone(); // Clone to release the borrow + let name_idx = p.arena_mut().push_string(name); + let mut path = Longident::Lident(name_idx); p.next(); // Continue parsing the path: Module.Module.field @@ -191,46 +228,60 @@ fn parse_value_path_after_dot(p: &mut Parser<'_>) -> Located { p.next(); match &p.token { Token::Uident(name) => { - path = Longident::Ldot(Box::new(path), name.clone()); + let name = name.clone(); // Clone to release the borrow + let name_idx = p.arena_mut().push_string(name); + path = Longident::Ldot(Box::new(path), name_idx); p.next(); } Token::Lident(name) => { - path = Longident::Ldot(Box::new(path), name.clone()); + let name = name.clone(); // Clone to release the borrow + let name_idx = p.arena_mut().push_string(name); + path = Longident::Ldot(Box::new(path), name_idx); p.next(); break; } Token::String(name) => { // Quoted field: Module."switch" - path = Longident::Ldot(Box::new(path), name.clone()); + let name = name.clone(); // Clone to release the borrow + let name_idx = p.arena_mut().push_string(name); + path = Longident::Ldot(Box::new(path), name_idx); p.next(); break; } - _ => break, + _ => { + // OCaml: parse_value_path_tail emits error and adds "_" for missing ident + p.err_unexpected(); + let underscore_idx = p.arena_mut().push_string("_".to_string()); + path = Longident::Ldot(Box::new(path), underscore_idx); + break; + } } } - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); - with_loc(path, loc) + let loc = p.mk_loc_to_prev_end(&start_pos); + let lid_idx = p.push_longident(path); + with_loc(lid_idx, loc) } Token::Lident(name) => { - let path = Longident::Lident(name.clone()); + let lid_idx = p.push_lident(name.clone()); p.next(); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); - with_loc(path, loc) + let loc = p.mk_loc_to_prev_end(&start_pos); + with_loc(lid_idx, loc) } Token::String(name) => { // Quoted field: ."switch" - let path = Longident::Lident(name.clone()); + let lid_idx = p.push_lident(name.clone()); p.next(); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); - with_loc(path, loc) + let loc = p.mk_loc_to_prev_end(&start_pos); + with_loc(lid_idx, loc) } _ => { p.err(DiagnosticCategory::Message( "Expected identifier after dot".to_string(), )); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); - with_loc(Longident::Lident("_".to_string()), loc) + let loc = p.mk_loc_to_prev_end(&start_pos); + let lid_idx = p.push_lident_static("_"); + with_loc(lid_idx, loc) } } } @@ -268,8 +319,9 @@ pub fn parse_value_or_constructor(p: &mut Parser<'_>) -> Expression { } } - let lid = super::core::build_longident(&path_parts); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let lid = super::core::build_longident(p.arena_mut(), &path_parts); + let lid_idx = p.push_longident(lid); + let loc = p.mk_loc_to_prev_end(&start_pos); // Check if it's a constructor (all uppercase components) if path_parts @@ -282,11 +334,11 @@ pub fn parse_value_or_constructor(p: &mut Parser<'_>) -> Expression { let has_arg = arg.is_some(); Expression { pexp_desc: ExpressionDesc::Pexp_construct( - with_loc(lid, loc.clone()), + with_loc(lid_idx, loc.clone()), arg.map(Box::new), ), pexp_loc: if has_arg { - p.mk_loc(&start_pos, &p.prev_end_pos) + p.mk_loc_to_prev_end(&start_pos) } else { loc }, @@ -294,14 +346,15 @@ pub fn parse_value_or_constructor(p: &mut Parser<'_>) -> Expression { } } else { // Regular identifier - ast_helper::make_ident(lid, loc) + ast_helper::make_ident_idx(lid_idx, loc) } } Token::Lident(name) => { let name = name.clone(); p.next(); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); - ast_helper::make_ident(Longident::Lident(name), loc) + let loc = p.mk_loc_to_prev_end(&start_pos); + let lid_idx = p.push_lident(&name); + ast_helper::make_ident_idx(lid_idx, loc) } _ => { p.err(DiagnosticCategory::Message( @@ -323,10 +376,10 @@ fn parse_constructor_arg(p: &mut Parser<'_>) -> Option { if p.token == Token::Rparen { // Empty constructor args: Rgb() p.next(); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); - let lid = Longident::Lident("()".to_string()); + let loc = p.mk_loc_to_prev_end(&start_pos); + let lid_idx = p.push_lident_static("()"); Some(Expression { - pexp_desc: ExpressionDesc::Pexp_construct(with_loc(lid, loc.clone()), None), + pexp_desc: ExpressionDesc::Pexp_construct(with_loc(lid_idx, loc.clone()), None), pexp_loc: loc, pexp_attributes: vec![], }) @@ -350,7 +403,7 @@ fn parse_constructor_arg(p: &mut Parser<'_>) -> Option { if exprs.len() == 1 { Some(exprs.into_iter().next().unwrap()) } else { - let loc = p.mk_loc(&tuple_start, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&tuple_start); Some(Expression { pexp_desc: ExpressionDesc::Pexp_tuple(exprs), pexp_loc: loc, @@ -364,7 +417,7 @@ fn parse_constructor_arg(p: &mut Parser<'_>) -> Option { // C((1,2)) = single tuple argument = Pexp_tuple([Pexp_tuple([1,2])]) // C(1,2) = multiple arguments = Pexp_tuple([1, 2]) if matches!(first_expr.pexp_desc, ExpressionDesc::Pexp_tuple(_)) { - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); Some(Expression { pexp_desc: ExpressionDesc::Pexp_tuple(vec![first_expr]), pexp_loc: loc, @@ -401,7 +454,7 @@ pub fn parse_expr_with_operand(p: &mut Parser<'_>, operand: Expression) -> Expre if p.token == Token::ColonGreaterThan { p.next(); let typ = super::typ::parse_typ_expr(p); - let loc = p.mk_loc(&expr.pexp_loc.loc_start, &typ.ptyp_loc.loc_end); + let loc = p.mk_loc_spanning(expr.pexp_loc, typ.ptyp_loc); Expression { pexp_desc: ExpressionDesc::Pexp_coerce(Box::new(expr), None, typ), pexp_loc: loc, @@ -414,14 +467,23 @@ pub fn parse_expr_with_operand(p: &mut Parser<'_>, operand: Expression) -> Expre /// Parse an expression with a specific context. pub fn parse_expr_with_context(p: &mut Parser<'_>, context: ExprContext) -> Expression { + // Check for excessive parse depth to prevent stack overflow + if p.exceeded_parse_depth() { + p.err(super::diagnostics::DiagnosticCategory::Message( + "Maximum parse depth exceeded".to_string(), + )); + return recover::default_expr(); + } + p.inc_parse_depth(); + let expr = parse_operand_expr(p, context); let expr = parse_binary_expr(p, expr, 1, context); let expr = parse_ternary_expr(p, expr); // Handle coercion: expr :> type - if p.token == Token::ColonGreaterThan { + let result = if p.token == Token::ColonGreaterThan { p.next(); let typ = super::typ::parse_typ_expr(p); - let loc = p.mk_loc(&expr.pexp_loc.loc_start, &typ.ptyp_loc.loc_end); + let loc = p.mk_loc_spanning(expr.pexp_loc, typ.ptyp_loc); Expression { pexp_desc: ExpressionDesc::Pexp_coerce(Box::new(expr), None, typ), pexp_loc: loc, @@ -429,7 +491,10 @@ pub fn parse_expr_with_context(p: &mut Parser<'_>, context: ExprContext) -> Expr } } else { expr - } + }; + + p.dec_parse_depth(); + result } /// Parse a ternary expression (condition ? true_branch : false_branch). @@ -444,10 +509,7 @@ pub fn parse_ternary_expr(p: &mut Parser<'_>, left_operand: Expression) -> Expre p.eat_breadcrumb(); - let loc = p.mk_loc( - &left_operand.pexp_loc.loc_start, - &false_branch.pexp_loc.loc_end, - ); + let loc = p.mk_loc_spanning(left_operand.pexp_loc, false_branch.pexp_loc); Expression { pexp_desc: ExpressionDesc::Pexp_ifthenelse( @@ -510,8 +572,9 @@ pub fn parse_operand_expr(p: &mut Parser<'_>, context: ExprContext) -> Expressio } else { // Just a regular "async" identifier - continue with primary expr parsing // to handle function calls like async(x) - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); - let ident = ast_helper::make_ident(Longident::Lident("async".to_string()), loc); + let loc = p.mk_loc_to_prev_end(&start_pos); + let lid_idx = p.push_lident_static("async"); + let ident = ast_helper::make_ident_idx(lid_idx, loc); (parse_primary_expr(p, ident, false), false) } } @@ -520,7 +583,7 @@ pub fn parse_operand_expr(p: &mut Parser<'_>, context: ExprContext) -> Expressio // Handle assert directly to preserve attribute location in expr location p.next(); let arg = parse_expr(p); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); ( Expression { pexp_desc: ExpressionDesc::Pexp_assert(Box::new(arg)), @@ -606,7 +669,7 @@ pub fn parse_await_expression(p: &mut Parser<'_>) -> Expression { let token_prec = Token::MinusGreater.precedence(); let operand = parse_unary_expr(p); let expr = parse_binary_expr(p, operand, token_prec, ExprContext::Ordinary); - let loc = p.mk_loc(&start_pos, &expr.pexp_loc.loc_end); + let loc = p.mk_loc(&start_pos, &p.loc_end(expr.pexp_loc)); Expression { pexp_desc: ExpressionDesc::Pexp_await(Box::new(expr)), @@ -674,7 +737,7 @@ fn parse_es6_arrow_expression_internal( let body = parse_expr_with_context(p, context); let body = match return_type { Some(typ) => { - let loc = p.mk_loc(&body.pexp_loc.loc_start, &typ.ptyp_loc.loc_end); + let loc = p.mk_loc_spanning(body.pexp_loc, typ.ptyp_loc); Expression { pexp_desc: ExpressionDesc::Pexp_constraint(Box::new(body), typ), pexp_loc: loc, @@ -707,9 +770,10 @@ fn parse_es6_arrow_expression_internal( (loc.clone(), loc) } }; + let unit_lid = p.push_lident_static("()"); let unit_pat = Pattern { ppat_desc: PatternDesc::Ppat_construct( - with_loc(Longident::Lident("()".to_string()), unit_pat_loc.clone()), + with_loc(unit_lid, unit_pat_loc.clone()), None, ), ppat_loc: unit_pat_loc, @@ -806,7 +870,7 @@ fn parse_es6_arrow_expression_internal( // Only update the location, don't touch pexp_attributes Expression { - pexp_loc: p.mk_loc(&start_pos, &arrow_expr.pexp_loc.loc_end), + pexp_loc: p.mk_loc(&start_pos, &p.loc_end(arrow_expr.pexp_loc)), ..arrow_expr } } @@ -839,8 +903,9 @@ fn parse_es6_arrow_expression_with_params( // OCaml: for braced arrow {x => body}, Pexp_fun location starts at => // The pattern location is from `{` to end of ident // So Pexp_fun starts at pattern.loc_end + 1 (skipping space after ident) - let mut fun_loc = p.mk_loc(¶m.pat.ppat_loc.loc_end, &end_pos); - fun_loc.loc_start.cnum += 1; // Skip past the space after pattern (to the `=` of `=>`) + let mut fun_start = p.loc_end(param.pat.ppat_loc); + fun_start.cnum += 1; // Skip past the space after pattern (to the `=` of `=>`) + let fun_loc = p.mk_loc(&fun_start, &end_pos); let mut pat = param.pat; if !param.attrs.is_empty() { @@ -887,9 +952,10 @@ fn parse_parameters(p: &mut Parser<'_>) -> Vec { let end_pos = p.end_pos.clone(); p.next(); let loc = p.mk_loc(&lparen_pos, &end_pos); + let unit_lid = p.push_lident_static("()"); let unit_pat = Pattern { ppat_desc: PatternDesc::Ppat_construct( - with_loc(Longident::Lident("()".to_string()), loc.clone()), + with_loc(unit_lid, loc.clone()), None, ), ppat_loc: loc.clone(), @@ -906,27 +972,79 @@ fn parse_parameters(p: &mut Parser<'_>) -> Vec { )); } else if had_dot { // We had a dot but there are more tokens - parse parameters + p.leave_breadcrumb(Grammar::ParameterList); while p.token != Token::Rparen && p.token != Token::Eof { if let Some(param) = parse_parameter(p) { params.push(param); + } else { + // No param parsed - check if we should continue or stop + if recover::should_abort_list_parse(p) { + break; + } + // Unexpected token - report error and skip + p.err_unexpected(); + p.next(); + continue; } - if !p.optional(&Token::Comma) { + + // Check for comma or handle missing comma like OCaml + if p.token == Token::Comma { + p.next(); + } else if p.token == Token::Rparen || p.token == Token::Eof { + break; + } else if grammar::is_parameter_start(&p.token) { + // Token looks like another param but no comma - missing comma case + p.expect(Token::Comma); + } else if !recover::should_abort_list_parse(p) { + // Unexpected token, not closing/EOF/abort - expect comma + p.expect(Token::Comma); + if p.token == Token::Semicolon { + p.next(); + } + } else { break; } } + p.eat_breadcrumb(); p.expect(Token::Rparen); let rparen_end_pos = p.prev_end_pos.clone(); // Set paren positions on the first type param (if any) set_first_type_param_paren_pos(&mut params, &lparen_pos, &rparen_end_pos); } else { + p.leave_breadcrumb(Grammar::ParameterList); while p.token != Token::Rparen && p.token != Token::Eof { if let Some(param) = parse_parameter(p) { params.push(param); + } else { + // No param parsed - check if we should continue or stop + if recover::should_abort_list_parse(p) { + break; + } + // Unexpected token - report error and skip + p.err_unexpected(); + p.next(); + continue; } - if !p.optional(&Token::Comma) { + + // Check for comma or handle missing comma like OCaml + if p.token == Token::Comma { + p.next(); + } else if p.token == Token::Rparen || p.token == Token::Eof { + break; + } else if grammar::is_parameter_start(&p.token) { + // Token looks like another param but no comma - missing comma case + p.expect(Token::Comma); + } else if !recover::should_abort_list_parse(p) { + // Unexpected token, not closing/EOF/abort - expect comma + p.expect(Token::Comma); + if p.token == Token::Semicolon { + p.next(); + } + } else { break; } } + p.eat_breadcrumb(); p.expect(Token::Rparen); let rparen_end_pos = p.prev_end_pos.clone(); // Set paren positions on the first type param (if any) @@ -993,15 +1111,19 @@ fn parse_parameter(p: &mut Parser<'_>) -> Option { let tilde_pos = p.start_pos.clone(); p.next(); let (lbl_name, lbl_loc) = parse_lident(p); + // Intern the string to get a StrIdx for sharing with identifiers + let lbl_str_idx = p.arena_mut().intern_string(&lbl_name); // OCaml: label location is just the name, not including ~ - let lbl_located = Located::new(lbl_name.clone(), lbl_loc); + let lbl_located = Located::new(lbl_str_idx, lbl_loc); // OCaml: pattern var location includes ~ (from tilde_pos to end of name) - let name_loc_with_tilde = p.mk_loc(&tilde_pos, &p.prev_end_pos); + let name_loc_with_tilde = p.mk_loc_to_prev_end(&tilde_pos); let lbl = match &p.token { Token::Comma | Token::Equal | Token::Rparen | Token::EqualGreater => { // Just ~name - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); - let pat = ast_helper::make_var_pat(lbl_name.clone(), loc); + // OCaml (line 1855): Ast_helper.Pat.var ~attrs ~loc + let loc = p.mk_loc_to_prev_end(&start_pos); + let mut pat = ast_helper::make_var_pat(lbl_name.clone(), loc); + pat.ppat_attributes = attrs.clone(); (ArgLabel::Labelled(lbl_located), pat, None) } Token::Colon => { @@ -1010,31 +1132,39 @@ fn parse_parameter(p: &mut Parser<'_>) -> Option { // But if there are attributes, it includes those too (from start_pos) p.next(); let typ = super::typ::parse_typ_expr(p); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); // Use start_pos if there are attributes, otherwise use tilde_pos // OCaml includes @as() attributes in the inner Ppat_var location let var_loc = if attrs.is_empty() { name_loc_with_tilde.clone() } else { - p.mk_loc(&start_pos, &name_loc_with_tilde.loc_end) + p.mk_loc(&start_pos, &p.loc_end(name_loc_with_tilde)) }; let var_pat = ast_helper::make_var_pat(lbl_name.clone(), var_loc); + // OCaml (lines 1863-1864): Ast_helper.Pat.constraint_ ~attrs ~loc pat typ + // The attrs go on the OUTER constraint pattern let pat = Pattern { ppat_desc: PatternDesc::Ppat_constraint(Box::new(var_pat), typ), ppat_loc: loc, - ppat_attributes: vec![], + ppat_attributes: attrs.clone(), }; (ArgLabel::Labelled(lbl_located), pat, None) } Token::As => { // ~name as pattern + // OCaml (line 1871): {pat with ppat_attributes = attrs @ pat.ppat_attributes} p.next(); - let pat = super::pattern::parse_constrained_pattern(p); + let mut pat = super::pattern::parse_constrained_pattern(p); + // Prepend attrs to pattern's existing attributes + let mut new_attrs = attrs.clone(); + new_attrs.extend(pat.ppat_attributes); + pat.ppat_attributes = new_attrs; (ArgLabel::Labelled(lbl_located), pat, None) } _ => { - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); - let pat = ast_helper::make_var_pat(lbl_name.clone(), loc); + let loc = p.mk_loc_to_prev_end(&start_pos); + let mut pat = ast_helper::make_var_pat(lbl_name.clone(), loc); + pat.ppat_attributes = attrs.clone(); (ArgLabel::Labelled(lbl_located), pat, None) } }; @@ -1058,7 +1188,7 @@ fn parse_parameter(p: &mut Parser<'_>) -> Option { let expr = if p.token == Token::Colon { p.next(); let typ = super::typ::parse_typ_expr(p); - let loc = p.mk_loc(&expr.pexp_loc.loc_start, &typ.ptyp_loc.loc_end); + let loc = p.mk_loc_spanning(expr.pexp_loc, typ.ptyp_loc); Expression { pexp_desc: ExpressionDesc::Pexp_constraint(Box::new(expr), typ), pexp_loc: loc, @@ -1073,9 +1203,11 @@ fn parse_parameter(p: &mut Parser<'_>) -> Option { (label, pat, default) }; + // OCaml puts labeled arg attrs directly on the pattern (not on the returned parameter) + // So FundefTermParam.attrs should be empty for labeled args with attrs on the pattern return Some(super::core::FundefParameter::Term( super::core::FundefTermParam { - attrs, + attrs: vec![], // attrs are already on pat.ppat_attributes label, expr: default, pat, @@ -1094,7 +1226,7 @@ fn parse_parameter(p: &mut Parser<'_>) -> Option { let pat = if p.token == Token::Colon { p.next(); let typ = super::typ::parse_typ_expr(p); - let loc = p.mk_loc(&pat.ppat_loc.loc_start, &typ.ptyp_loc.loc_end); + let loc = p.mk_loc_spanning(pat.ppat_loc, typ.ptyp_loc); Pattern { ppat_desc: PatternDesc::Ppat_constraint(Box::new(pat), typ), ppat_loc: loc, @@ -1103,6 +1235,49 @@ fn parse_parameter(p: &mut Parser<'_>) -> Option { } else { pat }; + + // Check for default value (= expr) - this means it's a labeled param missing the ~ + if p.token == Token::Equal { + // Get the name from the pattern for the error message + let lbl_name = match &pat.ppat_desc { + PatternDesc::Ppat_var(var) => var.txt.clone(), + _ => String::new(), + }; + + p.next(); // consume = (OCaml does this first, so prev_end_pos includes =) + + // OCaml: emit "missing tilde" error + let msg = if lbl_name.is_empty() { + "A labeled parameter starts with a `~`.".to_string() + } else { + format!("A labeled parameter starts with a `~`. Did you mean: `~{}`?", lbl_name) + }; + p.err_at(start_pos.clone(), p.prev_end_pos.clone(), DiagnosticCategory::Message(msg)); + + // Create label as Optional + let lbl_str_idx = p.arena_mut().intern_string(&lbl_name); + let lbl_loc = pat.ppat_loc; + let label = ArgLabel::Optional(Located::new(lbl_str_idx, lbl_loc)); + + // Check for =? (optional with no default) + let default = if p.token == Token::Question { + p.next(); + None + } else { + Some(parse_constrained_or_coerced_expr(p)) + }; + + return Some(super::core::FundefParameter::Term( + super::core::FundefTermParam { + attrs, + label, + expr: default, + pat, + start_pos, + }, + )); + } + return Some(super::core::FundefParameter::Term( super::core::FundefTermParam { attrs, @@ -1122,7 +1297,7 @@ fn parse_lident_list(p: &mut Parser<'_>) -> Vec> { let mut lidents = vec![]; while let Token::Lident(name) = &p.token { let name = name.clone(); - let loc = p.mk_loc(&p.start_pos, &p.end_pos); + let loc = p.mk_loc_current(); p.next(); lidents.push(with_loc(name, loc)); } @@ -1134,15 +1309,31 @@ fn parse_lident(p: &mut Parser<'_>) -> (String, Location) { match &p.token { Token::Lident(name) => { let name = name.clone(); - let loc = p.mk_loc(&p.start_pos, &p.end_pos); + let loc = p.mk_loc_current(); p.next(); (name, loc) } + Token::Eof => { + p.err_unexpected(); + ("_".to_string(), p.mk_loc_current()) + } _ => { - p.err(DiagnosticCategory::Message( - "Expected lowercase identifier".to_string(), - )); - ("_".to_string(), Location::none()) + // OCaml: parse_lident recovery - if keyword on same line, skip it. + // Otherwise skip tokens until we find an Lident or should abort. + p.err(DiagnosticCategory::Lident(p.token.clone())); + if p.token.is_keyword() && p.prev_end_pos.line == p.start_pos.line { + p.next(); + } else { + p.next(); // skip the bad token + // Skip tokens until we find an Lident or should abort list parse + while !super::core::recover::should_abort_list_parse(p) && p.token != Token::Eof { + p.next(); + } + if matches!(p.token, Token::Lident(_)) { + return parse_lident(p); + } + } + ("_".to_string(), p.mk_loc_current()) } } } @@ -1161,6 +1352,7 @@ fn parse_attributes(p: &mut Parser<'_>) -> Attributes { let loc = loc.clone(); let content = content.clone(); p.next(); + let loc = p.from_location(&loc); attrs.push(super::core::doc_comment_to_attribute(loc, content)); } _ => break, @@ -1246,7 +1438,7 @@ fn parse_attribute_id(p: &mut Parser<'_>, start_pos: Position) -> Located) -> Payload { let start_pos = p.start_pos.clone(); p.next(); // Create a structure item with the string expression + // IMPORTANT: Each location must be created separately to match OCaml's allocation pattern + let pexp_loc = p.mk_loc_to_prev_end(&start_pos); + let pstr_loc = p.mk_loc_to_prev_end(&start_pos); let str_expr = Expression { pexp_desc: ExpressionDesc::Pexp_constant(Constant::String(s, tag)), - pexp_loc: p.mk_loc(&start_pos, &p.prev_end_pos), + pexp_loc, pexp_attributes: vec![], }; return Payload::PStr(vec![StructureItem { pstr_desc: StructureItemDesc::Pstr_eval(str_expr, vec![]), - pstr_loc: p.mk_loc(&start_pos, &p.prev_end_pos), + pstr_loc, }]); } @@ -1305,13 +1500,6 @@ pub fn parse_binary_expr( break; } - // Disambiguate `<` between binary operator and JSX start. - // If `<` is immediately followed by JSX tokens (``), - // treat it as the start of a new JSX expression, not as a binary operator. - if p.token == Token::LessThan && is_jsx_start_after_less_than(p) { - break; - } - // Disambiguate `-`, `-.`, `<`, and `%` between binary and unary/new expression. // When on a new line AND not surrounded by whitespace on both sides, // these tokens start a new expression rather than being binary operators. @@ -1357,7 +1545,7 @@ pub fn parse_binary_expr( // Handle special case for assignment if token == Token::ColonEqual { let right = parse_expr_with_context(p, context); - let loc = p.mk_loc(&left.pexp_loc.loc_start, &right.pexp_loc.loc_end); + let loc = p.mk_loc_spanning(left.pexp_loc, right.pexp_loc); left = ast_helper::make_apply( super::core::make_infix_operator(p, Token::ColonEqual, op_start, op_end), vec![(ArgLabel::Nolabel, left), (ArgLabel::Nolabel, right)], @@ -1376,11 +1564,11 @@ pub fn parse_binary_expr( }; let right = parse_binary_expr(p, right, next_prec, context); - let loc = p.mk_loc(&left.pexp_loc.loc_start, &right.pexp_loc.loc_end); - let op_loc = p.mk_loc(&op_start, &op_end); + let loc = p.mk_loc_spanning(left.pexp_loc, right.pexp_loc); // Build application expression - let op_expr = ast_helper::make_ident(Longident::Lident(token.to_string()), op_loc); + // Use make_infix_operator to handle special cases like `=` (should be `==`) + let op_expr = super::core::make_infix_operator(p, token.clone(), op_start, op_end); left = ast_helper::make_apply( op_expr, vec![(ArgLabel::Nolabel, left), (ArgLabel::Nolabel, right)], @@ -1456,24 +1644,25 @@ pub fn parse_atomic_expr(p: &mut Parser<'_>) -> Expression { Token::True | Token::False => { let is_true = p.token == Token::True; p.next(); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); - let lid = Longident::Lident(if is_true { "true" } else { "false" }.to_string()); + let loc = p.mk_loc_to_prev_end(&start_pos); + let lid = super::core::make_lident_static(p.arena_mut(), if is_true { "true" } else { "false" }); + let lid_idx = p.push_longident(lid); Expression { - pexp_desc: ExpressionDesc::Pexp_construct(with_loc(lid, loc.clone()), None), + pexp_desc: ExpressionDesc::Pexp_construct(with_loc(lid_idx, loc.clone()), None), pexp_loc: loc, pexp_attributes: vec![], } } Token::Int { .. } | Token::String(_) | Token::Float { .. } | Token::Codepoint { .. } => { let c = parse_constant(p); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); ast_helper::make_constant(c, loc) } Token::Regex { pattern, flags } => { let pattern = pattern.clone(); let flags = flags.clone(); p.next(); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); // OCaml format: single string with slashes: "/" + pattern + "/" + flags let regex_str = format!("/{}/{}", pattern, flags); @@ -1494,20 +1683,95 @@ pub fn parse_atomic_expr(p: &mut Parser<'_>) -> Expression { with_loc("re".to_string(), loc), Payload::PStr(vec![str_item]), )), - pexp_loc: Location::none(), + pexp_loc: LocIdx::none(), pexp_attributes: vec![], } } + // OCaml: when parser sees `/` in expression position, it rescans as regex + Token::Forwardslash => { + p.next_regex_token(); + if let Token::Regex { ref pattern, ref flags } = p.token { + let pattern = pattern.clone(); + let flags = flags.clone(); + p.next(); + let loc = p.mk_loc_to_prev_end(&start_pos); + let regex_str = format!("/{}/{}", pattern, flags); + let tag = get_string_tag(p); + let str_expr = Expression { + pexp_desc: ExpressionDesc::Pexp_constant(Constant::String(regex_str, tag)), + pexp_loc: loc.clone(), + pexp_attributes: vec![], + }; + let str_item = StructureItem { + pstr_desc: StructureItemDesc::Pstr_eval(str_expr, vec![]), + pstr_loc: loc.clone(), + }; + Expression { + pexp_desc: ExpressionDesc::Pexp_extension(( + with_loc("re".to_string(), loc), + Payload::PStr(vec![str_item]), + )), + pexp_loc: LocIdx::none(), + pexp_attributes: vec![], + } + } else { + Expression { + pexp_desc: ExpressionDesc::Pexp_extension(( + with_loc("re".to_string(), LocIdx::none()), + Payload::PStr(vec![]), + )), + pexp_loc: LocIdx::none(), + pexp_attributes: vec![], + } + } + } + Token::ForwardslashDot => { + p.next_regex_token(); + if let Token::Regex { ref pattern, ref flags } = p.token { + let pattern = format!(".{}", pattern); + let flags = flags.clone(); + p.next(); + let loc = p.mk_loc_to_prev_end(&start_pos); + let regex_str = format!("/{}/{}", pattern, flags); + let tag = get_string_tag(p); + let str_expr = Expression { + pexp_desc: ExpressionDesc::Pexp_constant(Constant::String(regex_str, tag)), + pexp_loc: loc.clone(), + pexp_attributes: vec![], + }; + let str_item = StructureItem { + pstr_desc: StructureItemDesc::Pstr_eval(str_expr, vec![]), + pstr_loc: loc.clone(), + }; + Expression { + pexp_desc: ExpressionDesc::Pexp_extension(( + with_loc("re".to_string(), loc), + Payload::PStr(vec![str_item]), + )), + pexp_loc: LocIdx::none(), + pexp_attributes: vec![], + } + } else { + Expression { + pexp_desc: ExpressionDesc::Pexp_extension(( + with_loc("re".to_string(), LocIdx::none()), + Payload::PStr(vec![]), + )), + pexp_loc: LocIdx::none(), + pexp_attributes: vec![], + } + } + } Token::Uident(_) | Token::Lident(_) => parse_value_or_constructor(p), Token::Lparen => { p.next(); if p.token == Token::Rparen { // Unit: () p.next(); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); - let lid = Longident::Lident("()".to_string()); + let loc = p.mk_loc_to_prev_end(&start_pos); + let lid_idx = p.push_lident_static("()"); Expression { - pexp_desc: ExpressionDesc::Pexp_construct(with_loc(lid, loc.clone()), None), + pexp_desc: ExpressionDesc::Pexp_construct(with_loc(lid_idx, loc.clone()), None), pexp_loc: loc, pexp_attributes: vec![], } @@ -1543,7 +1807,7 @@ pub fn parse_atomic_expr(p: &mut Parser<'_>) -> Expression { p.next(); // Assert takes a full expression, not just an operand let arg = parse_expr(p); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); Expression { pexp_desc: ExpressionDesc::Pexp_assert(Box::new(arg)), pexp_loc: loc, @@ -1581,10 +1845,10 @@ pub fn parse_atomic_expr(p: &mut Parser<'_>) -> Expression { p.err(DiagnosticCategory::Message( "Expected extension name after %".to_string(), )); - with_loc("error".to_string(), Location::none()) + with_loc("error".to_string(), LocIdx::none()) } else { let id = parts.join("."); - with_loc(id, p.mk_loc(&id_start, &p.prev_end_pos)) + with_loc(id, p.mk_loc_to_prev_end(&id_start)) }; let payload = if p.token == Token::Lparen { @@ -1596,7 +1860,7 @@ pub fn parse_atomic_expr(p: &mut Parser<'_>) -> Expression { Payload::PStr(vec![]) }; - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); Expression { pexp_desc: ExpressionDesc::Pexp_extension((name, payload)), pexp_loc: loc, @@ -1608,7 +1872,7 @@ pub fn parse_atomic_expr(p: &mut Parser<'_>) -> Expression { // OCaml: after parse_template_expr, overrides location to [start_pos, p.prev_end_pos) // This ensures the outer expression location spans from opening to closing backtick let mut expr = parse_template_literal(p); - expr.pexp_loc = p.mk_loc(&start_pos, &p.prev_end_pos); + expr.pexp_loc = p.mk_loc_to_prev_end(&start_pos); expr } Token::Hash => { @@ -1620,8 +1884,17 @@ pub fn parse_atomic_expr(p: &mut Parser<'_>) -> Expression { p.next(); name } - Token::Int { i, .. } => { + Token::Int { i, suffix } => { + // Clone values before borrowing p mutably let tag = i.clone(); + let has_suffix = suffix.is_some(); + // OCaml: emit error if numeric poly variant has a suffix + if has_suffix { + p.err(DiagnosticCategory::Message(format!( + "A numeric polymorphic variant cannot be followed by a letter. Did you mean `#{}`?", + tag + ))); + } p.next(); tag } @@ -1646,10 +1919,11 @@ pub fn parse_atomic_expr(p: &mut Parser<'_>) -> Expression { if p.token == Token::Rparen { p.next(); // OCaml uses the full () location for both the expression and the longident - let unit_loc = p.mk_loc(&lparen_pos, &p.prev_end_pos); + let unit_loc = p.mk_loc_to_prev_end(&lparen_pos); + let lid_idx = p.push_lident_static("()"); Some(Box::new(Expression { pexp_desc: ExpressionDesc::Pexp_construct( - with_loc(Longident::Lident("()".to_string()), unit_loc.clone()), + with_loc(lid_idx, unit_loc.clone()), None, ), pexp_loc: unit_loc, @@ -1731,7 +2005,7 @@ pub fn parse_atomic_expr(p: &mut Parser<'_>) -> Expression { None }; - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); Expression { pexp_desc: ExpressionDesc::Pexp_variant(tag, arg), pexp_loc: loc, @@ -1744,9 +2018,11 @@ pub fn parse_atomic_expr(p: &mut Parser<'_>) -> Expression { parse_first_class_module_expr(p, start_pos) } Token::Underscore => { + // OCaml: Underscore is not a valid expression operand, emit an error + // This matches OCaml's parse_atomic_expr which uses Diagnostics.lident + p.err(DiagnosticCategory::Lident(Token::Underscore)); p.next(); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); - ast_helper::make_ident(Longident::Lident("_".to_string()), loc) + recover::default_expr() } Token::Eof => { p.err(DiagnosticCategory::Message( @@ -1755,12 +2031,25 @@ pub fn parse_atomic_expr(p: &mut Parser<'_>) -> Expression { recover::default_expr() } _ => { - p.err(DiagnosticCategory::Message(format!( - "Unexpected token: {:?}", - p.token - ))); - // Advance past the unexpected token to prevent infinite loops - p.next(); + // Use err_unexpected which creates a proper Unexpected diagnostic + // with breadcrumbs, matching OCaml's parse_region behavior + // OCaml uses prev_end_pos as start, but p.end_pos as end + let err_start = p.prev_end_pos.clone(); + let err_end = p.end_pos.clone(); + p.err_at( + err_start, + err_end, + DiagnosticCategory::unexpected(p.token.clone(), p.breadcrumbs().to_vec()), + ); + + // Try to skip tokens and retry parsing if we find a valid start token + // This matches OCaml's skip_tokens_and_maybe_retry behavior + if recover::skip_tokens_and_maybe_retry(p, grammar::is_atomic_expr_start) { + // Eat our breadcrumb first, then recurse + // OCaml returns from match, then eat_breadcrumb runs + p.eat_breadcrumb(); + return parse_atomic_expr(p); + } recover::default_expr() } }; @@ -1780,10 +2069,10 @@ pub fn parse_constrained_or_coerced_expr(p: &mut Parser<'_>) -> Expression { if p.token == Token::ColonGreaterThan { // OCaml: The inner Pexp_constraint has a location that ends at the constraint type, // not extending to the outer coercion target type - let constraint_loc = p.mk_loc(&expr.pexp_loc.loc_start, &typ.ptyp_loc.loc_end); + let constraint_loc = p.mk_loc_spanning(expr.pexp_loc, typ.ptyp_loc); p.next(); let target_typ = super::typ::parse_typ_expr(p); - let coerce_loc = p.mk_loc(&expr.pexp_loc.loc_start, &target_typ.ptyp_loc.loc_end); + let coerce_loc = p.mk_loc_spanning(expr.pexp_loc, target_typ.ptyp_loc); // OCaml represents (x : t :> int) as Pexp_coerce(Pexp_constraint(x, t), int) // The constraint is nested inside the expression, not as the optional middle type let constraint_expr = Expression { @@ -1797,7 +2086,7 @@ pub fn parse_constrained_or_coerced_expr(p: &mut Parser<'_>) -> Expression { pexp_attributes: vec![], } } else { - let loc = p.mk_loc(&expr.pexp_loc.loc_start, &typ.ptyp_loc.loc_end); + let loc = p.mk_loc_spanning(expr.pexp_loc, typ.ptyp_loc); Expression { pexp_desc: ExpressionDesc::Pexp_constraint(Box::new(expr), typ), pexp_loc: loc, @@ -1808,7 +2097,7 @@ pub fn parse_constrained_or_coerced_expr(p: &mut Parser<'_>) -> Expression { // Direct coercion: expr :> type p.next(); let typ = super::typ::parse_typ_expr(p); - let loc = p.mk_loc(&expr.pexp_loc.loc_start, &typ.ptyp_loc.loc_end); + let loc = p.mk_loc_spanning(expr.pexp_loc, typ.ptyp_loc); Expression { pexp_desc: ExpressionDesc::Pexp_coerce(Box::new(expr), None, typ), pexp_loc: loc, @@ -1819,9 +2108,203 @@ pub fn parse_constrained_or_coerced_expr(p: &mut Parser<'_>) -> Expression { } } +/// OCaml's over_parse_constrained_or_coerced_or_arrow_expression. +/// After parsing a block expression or let binding value, check if `:` follows +/// and handle the constraint/coercion/arrow overparse with appropriate error messages. +pub fn over_parse_constrained_or_coerced_or_arrow_expression( + p: &mut Parser<'_>, + expr: Expression, +) -> Expression { + match &p.token { + Token::ColonGreaterThan => { + // Coercion: expr :> type + p.next(); + let typ = super::typ::parse_typ_expr(p); + let loc = p.mk_loc_spanning(expr.pexp_loc, typ.ptyp_loc); + Expression { + pexp_desc: ExpressionDesc::Pexp_coerce(Box::new(expr), None, typ), + pexp_loc: loc, + pexp_attributes: vec![], + } + } + Token::Colon => { + p.next(); + let typ = super::typ::parse_typ_expr_no_arrow(p); + match &p.token { + Token::EqualGreater => { + // Ambiguous arrow: expr: type => body + p.next(); + let body = parse_expr(p); + + // Convert expression to pattern + let (pat, expr_is_unit) = match &expr.pexp_desc { + ExpressionDesc::Pexp_ident(longident) => { + // Longident.flatten |> String.concat "." + let lid = p.arena().get_longident(longident.txt); + let parts: Vec<&str> = lid.flatten_idx().iter() + .map(|idx| p.arena().get_string(*idx)) + .collect(); + let name = parts.join("."); + let name_loc = with_loc(name, longident.loc); + (Pattern { + ppat_desc: PatternDesc::Ppat_var(name_loc), + ppat_loc: expr.pexp_loc, + ppat_attributes: vec![], + }, false) + } + ExpressionDesc::Pexp_construct(lid, None) => { + let longident = p.arena().get_longident(lid.txt); + let is_unit = matches!(longident, Longident::Lident(s) if p.arena().get_string(*s) == "()"); + if is_unit { + (Pattern { + ppat_desc: PatternDesc::Ppat_construct(lid.clone(), None), + ppat_loc: expr.pexp_loc, + ppat_attributes: vec![], + }, true) + } else { + let name_loc = with_loc("pattern".to_string(), expr.pexp_loc); + (Pattern { + ppat_desc: PatternDesc::Ppat_var(name_loc), + ppat_loc: expr.pexp_loc, + ppat_attributes: vec![], + }, false) + } + } + _ => { + let name_loc = with_loc("pattern".to_string(), expr.pexp_loc); + (Pattern { + ppat_desc: PatternDesc::Ppat_var(name_loc), + ppat_loc: expr.pexp_loc, + ppat_attributes: vec![], + }, false) + } + }; + + let arrow_loc = p.mk_loc_spanning(expr.pexp_loc, body.pexp_loc); + + // Interpretation 1: (param) => (body : type) + let arrow1 = Expression { + pexp_desc: ExpressionDesc::Pexp_fun { + arity: Arity::Unknown, + arg_label: ArgLabel::Nolabel, + default: None, + lhs: pat.clone(), + rhs: Box::new(Expression { + pexp_desc: ExpressionDesc::Pexp_constraint(Box::new(body.clone()), typ.clone()), + pexp_loc: p.mk_loc_spanning(body.pexp_loc, typ.ptyp_loc), + pexp_attributes: vec![], + }), + is_async: false, + }, + pexp_loc: arrow_loc, + pexp_attributes: vec![], + }; + + if expr_is_unit { + arrow1 + } else { + // Interpretation 2: (param: type) => body + let arrow2 = Expression { + pexp_desc: ExpressionDesc::Pexp_fun { + arity: Arity::Unknown, + arg_label: ArgLabel::Nolabel, + default: None, + lhs: Pattern { + ppat_desc: PatternDesc::Ppat_constraint(Box::new(pat), typ.clone()), + ppat_loc: p.mk_loc_spanning(expr.pexp_loc, typ.ptyp_loc), + ppat_attributes: vec![], + }, + rhs: Box::new(body.clone()), + is_async: false, + }, + pexp_loc: arrow_loc, + pexp_attributes: vec![], + }; + + // Use ResPrinter to render both interpretations + use super::doc::Doc; + use super::printer2; + use super::comment_table::CommentTable; + let state = printer2::PrinterState::init(); + let mut cmt_tbl = CommentTable::new(); + let msg = Doc::breakable_group( + Doc::concat(vec![ + Doc::text("Did you mean to annotate the parameter type or the return type?"), + Doc::indent(Doc::concat(vec![ + Doc::line(), + Doc::text("1) "), + printer2::print_expression(&state, &arrow1, &mut cmt_tbl, p.arena()), + Doc::line(), + Doc::text("2) "), + printer2::print_expression(&state, &arrow2, &mut cmt_tbl, p.arena()), + ])), + ]), + true, + ).to_string(80); + + p.err_at( + p.loc_start(expr.pexp_loc), + p.loc_end(body.pexp_loc), + DiagnosticCategory::message(&msg), + ); + arrow1 + } + } + _ => { + // Simple constraint: expr : type + let loc = p.mk_loc_spanning(expr.pexp_loc, typ.ptyp_loc); + let constrained = Expression { + pexp_desc: ExpressionDesc::Pexp_constraint(Box::new(expr), typ.clone()), + pexp_loc: loc, + pexp_attributes: vec![], + }; + + // Use ResPrinter to render the constrained expression in parens + use super::doc::Doc; + use super::printer2; + use super::comment_table::CommentTable; + let state = printer2::PrinterState::init(); + let mut cmt_tbl = CommentTable::new(); + let printed = printer2::add_parens( + printer2::print_expression(&state, &constrained, &mut cmt_tbl, p.arena()), + ); + let msg = Doc::breakable_group( + Doc::concat(vec![ + Doc::text("Expressions with type constraints need to be wrapped in parens:"), + Doc::indent(Doc::concat(vec![ + Doc::line(), + printed, + ])), + ]), + true, + ).to_string(80); + + p.err_at( + p.loc_start(constrained.pexp_loc), + p.loc_end(typ.ptyp_loc), + DiagnosticCategory::message(&msg), + ); + constrained + } + } + } + _ => expr, + } +} + /// Parse an expression with optional type constraint for function arguments. /// Used in labeled argument contexts like `~compare=?intCompare: (int, int) => int`. fn parse_constrained_expr_in_arg(p: &mut Parser<'_>) -> Expression { + // OCaml: _ is valid in labeled argument position (~label=_) + // BUT NOT if it's the start of an arrow function: (~onClick=_ => ...) + // This must be checked before parse_constrained_or_coerced_expr + if p.token == Token::Underscore && !super::core::is_es6_arrow_expression(p, false) { + let start_pos = p.start_pos.clone(); + p.next(); + let loc = p.mk_loc_to_prev_end(&start_pos); + let lid = super::core::make_lident_static(p.arena_mut(), "_"); + return ast_helper::make_ident(p, lid, loc); + } parse_constrained_or_coerced_expr(p) } @@ -1834,7 +2317,7 @@ pub fn parse_primary_expr(p: &mut Parser<'_>, operand: Expression, no_call: bool // OCaml: let start_pos = operand.pexp_loc.loc_start in // Capture start position from operand BEFORE any transformations (like underscore apply) // This ensures that subsequent operations (field access, etc.) use the original location - let start_pos = operand.pexp_loc.loc_start.clone(); + let start_pos = p.loc_start(operand.pexp_loc); let mut expr = operand; loop { @@ -1844,29 +2327,33 @@ pub fn parse_primary_expr(p: &mut Parser<'_>, operand: Expression, no_call: bool match &p.token { Token::Lident(name) => { let name = name.clone(); - let name_loc = p.mk_loc(&p.start_pos, &p.end_pos); + let name_loc = p.mk_loc_current(); + let lid_idx = p.push_lident(&name); p.next(); // Check for field assignment: expr.field = value if p.token == Token::Equal { + // OCaml: leave_breadcrumb ExprSetField + p.leave_breadcrumb(Grammar::ExprSetField); p.next(); let value = parse_expr(p); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + p.eat_breadcrumb(); + let loc = p.mk_loc_to_prev_end(&start_pos); expr = Expression { pexp_desc: ExpressionDesc::Pexp_setfield( Box::new(expr), - with_loc(Longident::Lident(name), name_loc), + with_loc(lid_idx, name_loc), Box::new(value), ), pexp_loc: loc, pexp_attributes: vec![], }; } else { - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); expr = Expression { pexp_desc: ExpressionDesc::Pexp_field( Box::new(expr), - with_loc(Longident::Lident(name), name_loc), + with_loc(lid_idx, name_loc), ), pexp_loc: loc, pexp_attributes: vec![], @@ -1876,29 +2363,33 @@ pub fn parse_primary_expr(p: &mut Parser<'_>, operand: Expression, no_call: bool Token::String(name) => { // Quoted field access: expr."switch" let name = name.clone(); - let name_loc = p.mk_loc(&p.start_pos, &p.end_pos); + let name_loc = p.mk_loc_current(); + let lid_idx = p.push_lident(&name); p.next(); // Check for field assignment: expr."field" = value if p.token == Token::Equal { + // OCaml: leave_breadcrumb ExprSetField + p.leave_breadcrumb(Grammar::ExprSetField); p.next(); let value = parse_expr(p); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + p.eat_breadcrumb(); + let loc = p.mk_loc_to_prev_end(&start_pos); expr = Expression { pexp_desc: ExpressionDesc::Pexp_setfield( Box::new(expr), - with_loc(Longident::Lident(name), name_loc), + with_loc(lid_idx, name_loc), Box::new(value), ), pexp_loc: loc, pexp_attributes: vec![], }; } else { - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); expr = Expression { pexp_desc: ExpressionDesc::Pexp_field( Box::new(expr), - with_loc(Longident::Lident(name), name_loc), + with_loc(lid_idx, name_loc), ), pexp_loc: loc, pexp_attributes: vec![], @@ -1909,7 +2400,7 @@ pub fn parse_primary_expr(p: &mut Parser<'_>, operand: Expression, no_call: bool // Module-qualified field access: expr.Module.field // Parse the path (e.g., Lexing.pos_fname) and create Pexp_field let field_path = parse_value_path_after_dot(p); - let loc = p.mk_loc(&start_pos, &field_path.loc.loc_end); + let loc = p.mk_loc(&start_pos, &p.loc_end(field_path.loc)); expr = Expression { pexp_desc: ExpressionDesc::Pexp_field(Box::new(expr), field_path), pexp_loc: loc, @@ -1930,9 +2421,10 @@ pub fn parse_primary_expr(p: &mut Parser<'_>, operand: Expression, no_call: bool // For function calls, use expr's current location start, NOT the original operand's start // This is important for chained calls like f(a, _, b)(x, y) where the second call // should start from the Pexp_fun's location (the underscore position) - let loc = p.mk_loc(&expr.pexp_loc.loc_start, &p.prev_end_pos); + let loc_start_pos = p.loc_start(expr.pexp_loc); + let loc = p.mk_loc_to_prev_end(&loc_start_pos); // Apply placeholder transformation: f(a, _, b) => fun __x -> f(a, __x, b) - expr = transform_placeholder_application(Box::new(expr), args, partial, loc); + expr = transform_placeholder_application(Box::new(expr), args, partial, loc, p.arena_mut()); } Token::Lbracket => { // If [ is on a new line, it's an array literal (new expression), not indexing. @@ -1966,7 +2458,7 @@ pub fn parse_primary_expr(p: &mut Parser<'_>, operand: Expression, no_call: bool // String index: obj["prop"] = value -> Pexp_apply("#=", [Pexp_send(obj, "prop"), value]) // OCaml: loc = mk_loc start_pos rhs_expr.pexp_loc.loc_end // Use the inner expression's end, not prev_end_pos (which includes braces) - let loc = p.mk_loc(&start_pos, &value.pexp_loc.loc_end); + let loc = p.mk_loc(&start_pos, &p.loc_end(value.pexp_loc)); // First create the Pexp_send for property access // Use rbracket_end for location (OCaml includes the ] in the location) let send_expr = Expression { @@ -1982,10 +2474,8 @@ pub fn parse_primary_expr(p: &mut Parser<'_>, operand: Expression, no_call: bool }; // Create the "#=" operator let operator_loc = p.mk_loc(&equal_start, &equal_end); - let operator = ast_helper::make_ident( - Longident::Lident("#=".to_string()), - operator_loc, - ); + let op_lid = super::core::make_lident_static(p.arena_mut(), "#="); + let operator = ast_helper::make_ident(p, op_lid, operator_loc); // Apply "#=" to [send_expr, value] expr = ast_helper::make_apply( operator, @@ -1999,16 +2489,16 @@ pub fn parse_primary_expr(p: &mut Parser<'_>, operand: Expression, no_call: bool // Non-string index: arr[index] = value -> Array.set(arr, index, value) // OCaml: loc = mk_loc start_pos p.prev_end_pos // Uses prev_end_pos (includes braces) for Array.set - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); // Use the bracket location [index] for the synthesized Array.set identifier // (matching OCaml's array_loc = mk_loc lbracket rbracket) - let array_set = ast_helper::make_ident( - Longident::Ldot( - Box::new(Longident::Lident("Array".to_string())), - "set".to_string(), - ), - bracket_loc.clone(), + let array_idx = p.arena_mut().intern_string("Array"); + let set_idx = p.arena_mut().intern_string("set"); + let array_set_lid = Longident::Ldot( + Box::new(Longident::Lident(array_idx)), + set_idx, ); + let array_set = ast_helper::make_ident(p, array_set_lid, bracket_loc.clone()); let apply_expr = ast_helper::make_apply( array_set, vec![ @@ -2045,11 +2535,15 @@ pub fn parse_primary_expr(p: &mut Parser<'_>, operand: Expression, no_call: bool // Non-string index: arr[index] -> Array.get(arr, index) // Use the bracket location [index] for the synthesized Array.get identifier // (matching OCaml's array_loc = mk_loc lbracket rbracket) + let array_idx = p.arena_mut().intern_string("Array"); + let get_idx = p.arena_mut().intern_string("get"); + let array_get_lid = Longident::Ldot( + Box::new(Longident::Lident(array_idx)), + get_idx, + ); let array_get = ast_helper::make_ident( - Longident::Ldot( - Box::new(Longident::Lident("Array".to_string())), - "get".to_string(), - ), + p, + array_get_lid, bracket_loc, ); // OCaml doesn't add res.array.access attribute in the parser @@ -2070,14 +2564,22 @@ pub fn parse_primary_expr(p: &mut Parser<'_>, operand: Expression, no_call: bool if p.prev_end_pos.line < p.start_pos.line { break; } - // Tagged templates can be any expression: (foo ? bar : baz)`...` match &expr.pexp_desc { ExpressionDesc::Pexp_ident(lid) => { let prefix = (lid.txt.clone(), lid.loc.clone()); expr = parse_template_literal_with_prefix(p, Some(prefix)); } _ => { - expr = parse_tagged_template_literal_with_tag_expr(p, expr); + // OCaml: only bare names are valid as tagged template tags + p.err_at( + p.loc_start(expr.pexp_loc).clone(), + p.loc_end(expr.pexp_loc).clone(), + DiagnosticCategory::message( + "Tagged template literals are currently restricted to names like: \ + myTagFunction`foo ${bar}`.", + ), + ); + expr = parse_template_literal_with_prefix(p, None); } } } @@ -2098,29 +2600,11 @@ fn parse_call_args(p: &mut Parser<'_>) -> (Vec<(ArgLabel, Expression)>, bool) { // OCaml's start_pos for empty args is the position after '(' is consumed let start_pos = p.start_pos.clone(); - // Check for uncurried call syntax: f(. x, y) - // The dot indicates an uncurried function call (deprecated in newer ReScript) - let uncurried = p.token == Token::Dot; - if uncurried { - p.next(); - // Check for apply(.) - uncurried unit call - // This produces a single unit argument, not an empty list - // OCaml uses Location.mknoloc here, so no location - if p.token == Token::Rparen { - let unit_expr = Expression { - pexp_desc: ExpressionDesc::Pexp_construct( - Loc { - txt: Longident::Lident("()".to_string()), - loc: Location::none(), - }, - None, - ), - pexp_loc: Location::none(), - pexp_attributes: vec![], - }; - args.push((ArgLabel::Nolabel, unit_expr)); - } - } + // Leave breadcrumb for ArgumentList (matching OCaml's parse_comma_delimited_region) + p.leave_breadcrumb(Grammar::ArgumentList); + + // Uncurried call syntax: f(. x, y) or f(. x, y, . z) + // The dots are handled by parse_argument which consumes them while p.token != Token::Rparen && p.token != Token::Eof { // Check for partial application marker: f(a, ...) @@ -2130,14 +2614,48 @@ fn parse_call_args(p: &mut Parser<'_>) -> (Vec<(ArgLabel, Expression)>, bool) { break; } + // OCaml: parse_comma_delimited_region calls f() which returns None + // when the token can't start an argument. Check before parsing. + if !grammar::is_argument_start(&p.token) { + if recover::should_abort_list_parse(p) { + break; + } + p.err(DiagnosticCategory::unexpected(p.token.clone(), p.breadcrumbs().to_vec())); + p.next(); + continue; + } + let (label, expr) = parse_argument(p); args.push((label, expr)); - if !p.optional(&Token::Comma) { + if p.token == Token::Comma { + // Consume the comma and continue + p.next(); + } else if p.token == Token::Rparen || p.token == Token::Eof { + // At closing token, done + break; + } else if grammar::is_argument_start(&p.token) { + // Token looks like another argument but no comma - missing comma case + // This matches OCaml: "is_list_element grammar p.token" check + p.expect(Token::Comma); + // Continue parsing (don't break) + } else if !recover::should_abort_list_parse(p) { + // Token is not argument start, not closing, not EOF, + // and should_abort_list_parse is false - expect comma + // This matches OCaml's behavior for unexpected tokens like ']' in arg list + p.expect(Token::Comma); + // Skip semicolons if present (OCaml does this) + if p.token == Token::Semicolon { + p.next(); + } + // Continue parsing (don't break) + } else { + // should_abort_list_parse returned true - stop parsing break; } } + p.eat_breadcrumb(); p.expect(Token::Rparen); // Get prev_end_pos AFTER consuming ')' to match OCaml behavior let rparen_end = p.prev_end_pos.clone(); @@ -2146,10 +2664,11 @@ fn parse_call_args(p: &mut Parser<'_>) -> (Vec<(ArgLabel, Expression)>, bool) { // OCaml treats empty parens as a unit argument if args.is_empty() && !partial { let unit_loc = p.mk_loc(&start_pos, &rparen_end); + let lid_idx = p.push_lident_static("()"); let unit_expr = Expression { pexp_desc: ExpressionDesc::Pexp_construct( Loc { - txt: Longident::Lident("()".to_string()), + txt: lid_idx, loc: unit_loc.clone(), }, None, @@ -2164,11 +2683,38 @@ fn parse_call_args(p: &mut Parser<'_>) -> (Vec<(ArgLabel, Expression)>, bool) { } /// Parse a single argument (possibly labeled). +/// Handles uncurried dot prefix: f(. x, y, . z) - the dot is consumed but +/// doesn't change the argument structure (it's just part of uncurried syntax). fn parse_argument(p: &mut Parser<'_>) -> (ArgLabel, Expression) { + // Handle uncurried dot marker before argument + // In f(. a, b, . c), each dot is consumed before the argument + if p.token == Token::Dot { + p.next(); + // Check for apply(.) - uncurried unit call + if p.token == Token::Rparen { + let lid_idx = p.push_lident_static("()"); + let unit_expr = Expression { + pexp_desc: ExpressionDesc::Pexp_construct( + Loc { + txt: lid_idx, + loc: LocIdx::none(), + }, + None, + ), + pexp_loc: LocIdx::none(), + pexp_attributes: vec![], + }; + return (ArgLabel::Nolabel, unit_expr); + } + // Fall through to parse the actual argument + } + if p.token == Token::Tilde { p.next(); let (name, name_loc) = parse_lident(p); - let name_located = Located::new(name.clone(), name_loc.clone()); + // Intern the name to get a StrIdx - this will be shared with Longident::Lident for punning + let name_str_idx = p.arena_mut().intern_string(&name); + let name_located = Located::new(name_str_idx, name_loc.clone()); if p.token == Token::Equal { p.next(); @@ -2186,29 +2732,76 @@ fn parse_argument(p: &mut Parser<'_>) -> (ArgLabel, Expression) { } else if p.token == Token::Question { // ~label? (optional punning) p.next(); - // Use the label's location for the punned expression - let expr = ast_helper::make_ident(Longident::Lident(name.clone()), name_loc.clone()); + // Use the same interned StrIdx for the identifier - this enables sharing + let expr = ast_helper::make_ident(p, Longident::Lident(name_str_idx), name_loc.clone()); (ArgLabel::Optional(name_located), expr) } else if p.token == Token::Colon { - // ~label: type (labeled with type annotation - punning with constraint) + // ~label: ... could be type constraint or wrong separator + // OCaml checks is_typ_expr_start to decide + let colon_start = p.start_pos.clone(); p.next(); - let typ = super::typ::parse_typ_expr(p); - // Use the label's location for the punned expression - let ident_expr = ast_helper::make_ident(Longident::Lident(name.clone()), name_loc.clone()); - // Constraint location spans from label name to end of type - let constraint_loc = p.mk_loc(&name_loc.loc_start, &p.prev_end_pos); - let expr = Expression { - pexp_desc: ExpressionDesc::Pexp_constraint(Box::new(ident_expr), typ), - pexp_loc: constraint_loc, - pexp_attributes: vec![], - }; - (ArgLabel::Labelled(name_located), expr) + let colon_end = p.prev_end_pos.clone(); + if super::grammar::is_typ_expr_start(&p.token) { + // ~label: type (labeled with type annotation - punning with constraint) + let typ = super::typ::parse_typ_expr(p); + let ident_expr = ast_helper::make_ident(p, Longident::Lident(name_str_idx), name_loc.clone()); + let constraint_start = p.loc_start(name_loc); + let constraint_loc = p.mk_loc_to_prev_end(&constraint_start); + let expr = Expression { + pexp_desc: ExpressionDesc::Pexp_constraint(Box::new(ident_expr), typ), + pexp_loc: constraint_loc, + pexp_attributes: vec![], + }; + (ArgLabel::Labelled(name_located), expr) + } else if p.token == Token::Question { + // ~label:?value -> should be ~label=?value + p.err_at( + colon_start, + colon_end, + DiagnosticCategory::message( + "Optional labelled arguments use `=?`. Example: `~label=?value`", + ), + ); + p.next(); + let expr = parse_constrained_or_coerced_expr(p); + (ArgLabel::Optional(name_located), expr) + } else { + // ~label:value -> should be ~label=value + p.err_at( + colon_start, + colon_end, + DiagnosticCategory::message( + "Use `=` to pass a labelled argument. Example: `~label=value`", + ), + ); + let expr = if p.token == Token::Underscore && !super::core::is_es6_arrow_expression(p, false) { + let start = p.start_pos.clone(); + p.next(); + let loc = p.mk_loc_to_prev_end(&start); + let lid = super::core::make_lident_static(p.arena_mut(), "_"); + ast_helper::make_ident(p, lid, loc) + } else { + parse_constrained_or_coerced_expr(p) + }; + (ArgLabel::Labelled(name_located), expr) + } } else { // ~label (punning) - // Use the label's location for the punned expression - let expr = ast_helper::make_ident(Longident::Lident(name.clone()), name_loc.clone()); + // Use the same interned StrIdx for the identifier - this enables sharing + let expr = ast_helper::make_ident(p, Longident::Lident(name_str_idx), name_loc.clone()); (ArgLabel::Labelled(name_located), expr) } + } else if p.token == Token::Underscore && !super::core::is_es6_arrow_expression(p, false) { + // OCaml: _ as argument is valid (placeholder for partial application) + // BUT NOT if it's the start of an arrow function: f(_ => ...) + // This must be checked before parse_constrained_or_coerced_expr which + // would now treat _ as an error in parse_atomic_expr + let start_pos = p.start_pos.clone(); + p.next(); + let loc = p.mk_loc_to_prev_end(&start_pos); + let lid = super::core::make_lident_static(p.arena_mut(), "_"); + let expr = ast_helper::make_ident(p, lid, loc); + (ArgLabel::Nolabel, expr) } else { // Unlabeled argument - may have type constraint like f({}:t) (ArgLabel::Nolabel, parse_constrained_or_coerced_expr(p)) @@ -2231,12 +2824,15 @@ fn parse_tuple_expr(p: &mut Parser<'_>, start_pos: Position, first: Expression) } p.expect(Token::Rparen); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); + // OCaml: A tuple needs at least two elements if elements.len() < 2 { - p.err(DiagnosticCategory::Message( - super::core::error_messages::TUPLE_SINGLE_ELEMENT.to_string(), - )); + p.err_at( + start_pos.clone(), + p.prev_end_pos.clone(), + DiagnosticCategory::Message("A tuple needs at least two elements".to_string()), + ); } Expression { @@ -2271,8 +2867,13 @@ fn parse_array_expr(p: &mut Parser<'_>) -> Expression { } } + // OCaml: the old Reason syntax [|...|] leaves a trailing | before ]. + // Skip it so we can properly close the array. + if p.token == Token::Bar { + p.next(); + } p.expect(Token::Rbracket); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); // Check if there are any spreads let has_spread = items.iter().any(|(is_spread, _)| *is_spread); @@ -2326,17 +2927,19 @@ fn parse_array_expr(p: &mut Parser<'_>) -> Expression { pexp_attributes: vec![], }; - let concat_many = Expression { - pexp_desc: ExpressionDesc::Pexp_ident(with_loc( - Longident::Ldot( - Box::new(Longident::Ldot( - Box::new(Longident::Lident("Belt".to_string())), - "Array".to_string(), - )), - "concatMany".to_string(), - ), - loc.clone(), + let belt_idx = p.arena_mut().intern_string("Belt"); + let array_idx = p.arena_mut().intern_string("Array"); + let concat_many_idx = p.arena_mut().intern_string("concatMany"); + let lid = Longident::Ldot( + Box::new(Longident::Ldot( + Box::new(Longident::Lident(belt_idx)), + array_idx, )), + concat_many_idx, + ); + let lid_idx = p.push_longident(lid); + let concat_many = Expression { + pexp_desc: ExpressionDesc::Pexp_ident(with_loc(lid_idx, loc.clone())), pexp_loc: loc.clone(), pexp_attributes: vec![(mknoloc("res.spread".to_string()), Payload::PStr(vec![]))], }; @@ -2380,7 +2983,7 @@ fn parse_list_expr(p: &mut Parser<'_>, start_pos: Position) -> Expression { } p.expect(Token::Rbrace); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); // Split items into segments by spread boundaries // Each segment is (non_spread_items, optional_spread) @@ -2389,13 +2992,16 @@ fn parse_list_expr(p: &mut Parser<'_>, start_pos: Position) -> Expression { match segments.len() { 0 => { // Empty list: list{} → [] - make_empty_list(&loc) + // OCaml: {expr with pexp_loc = loc} - overwrite ghost pexp_loc with original location + let mut expr = make_empty_list(p, loc); + expr.pexp_loc = loc; + expr } 1 => { // Single segment: just build with :: constructors // OCaml: spread expression keeps its original location in single segment case let (exprs, spread, _, _) = segments.into_iter().next().unwrap(); - let mut result = make_list_expression_simple(&loc, exprs, spread); + let mut result = make_list_expression_simple(p, loc, exprs, spread); // The outermost expression should have the full list location result.pexp_loc = loc; result @@ -2417,15 +3023,20 @@ fn parse_list_expr(p: &mut Parser<'_>, start_pos: Position) -> Expression { }; // Build Belt.List.concatMany + let belt_idx = p.arena_mut().intern_string("Belt"); + let list_idx = p.arena_mut().intern_string("List"); + let concat_many_idx = p.arena_mut().intern_string("concatMany"); + let lid = Longident::Ldot( + Box::new(Longident::Ldot( + Box::new(Longident::Lident(belt_idx)), + list_idx, + )), + concat_many_idx, + ); + let lid_idx = p.push_longident(lid); let concat_many_ident = Expression { pexp_desc: ExpressionDesc::Pexp_ident(Loc { - txt: Longident::Ldot( - Box::new(Longident::Ldot( - Box::new(Longident::Lident("Belt".to_string())), - "List".to_string(), - )), - "concatMany".to_string(), - ), + txt: lid_idx, loc: loc.clone(), }), pexp_loc: loc.clone(), @@ -2493,17 +3104,23 @@ fn split_list_by_spread( segments } -/// Build an empty list expression `[]` -fn make_empty_list(loc: &Location) -> Expression { +/// Build an empty list expression `[]` with ghost locations. +/// Both pexp_loc and the inner Longident location are ghost. +/// This matches OCaml's handle_seq base case: construct ~loc nil None (where loc is ghost). +/// The caller should overwrite pexp_loc if needed (e.g., for outermost list expression). +fn make_empty_list(p: &mut Parser<'_>, loc: Location) -> Expression { + // OCaml: let loc = {loc with Location.loc_ghost = true} + let ghost_loc = p.arena_mut().mk_ghost_loc(loc); + let lid_idx = p.push_lident_static("[]"); Expression { pexp_desc: ExpressionDesc::Pexp_construct( Loc { - txt: Longident::Lident("[]".to_string()), - loc: loc.clone(), + txt: lid_idx, + loc: ghost_loc, }, None, ), - pexp_loc: loc.clone(), + pexp_loc: ghost_loc, pexp_attributes: vec![], } } @@ -2513,7 +3130,8 @@ fn make_empty_list(loc: &Location) -> Expression { /// `[e1, e2]` → `e1 :: (e2 :: [])` /// `[e1, e2, ...rest]` → `e1 :: (e2 :: rest)` fn make_list_expression_simple( - loc: &Location, + p: &mut Parser<'_>, + loc: Location, exprs: Vec, spread: Option, ) -> Expression { @@ -2521,54 +3139,61 @@ fn make_list_expression_simple( // For lists without spread, they end at the empty list's end let list_end = spread .as_ref() - .map(|s| s.pexp_loc.loc_end.clone()) - .unwrap_or_else(|| loc.loc_end.clone()); - let tail = spread.unwrap_or_else(|| make_empty_list(loc)); - - // Fold from right: 3 :: [] -> 2 :: (3 :: []) -> 1 :: (2 :: (3 :: [])) - exprs.into_iter().rev().fold(tail, |acc, item| { - let cons_loc = Location::from_positions(item.pexp_loc.loc_start.clone(), list_end.clone()); + .map(|s| p.loc_end(s.pexp_loc).clone()) + .unwrap_or_else(|| p.loc_end(loc).clone()); + let mut acc = spread.unwrap_or_else(|| make_empty_list(p, loc)); + + // Build from right: 3 :: [] -> 2 :: (3 :: []) -> 1 :: (2 :: (3 :: [])) + for item in exprs.into_iter().rev() { + let item_start = p.loc_start(item.pexp_loc).clone(); + let cons_loc = p.mk_loc_from_positions(&item_start, &list_end); let tuple = Expression { pexp_desc: ExpressionDesc::Pexp_tuple(vec![item, acc]), - pexp_loc: cons_loc.clone(), + pexp_loc: cons_loc, pexp_attributes: vec![], }; - Expression { + let lid_idx = p.push_lident_static("::"); + acc = Expression { pexp_desc: ExpressionDesc::Pexp_construct( Loc { - txt: Longident::Lident("::".to_string()), - loc: cons_loc.clone(), + txt: lid_idx, + loc: cons_loc, }, Some(Box::new(tuple)), ), pexp_loc: cons_loc, pexp_attributes: vec![], - } - }) -} + }; + } + acc +} /// Build a list expression for multi-segment lists with explicit segment locations /// OCaml uses the segment's start/end for the sub-expression location /// And updates the final expression's pexp_loc to segment extent fn make_list_expression_with_loc( - p: &Parser<'_>, + p: &mut Parser<'_>, exprs: Vec, spread: Option, seg_start: Position, seg_end: Position, ) -> Expression { - let seg_loc = p.mk_loc(&seg_start, &seg_end); + let seg_loc = p.mk_loc_from_positions(&seg_start, &seg_end); + + // Pre-allocate the list constructor longidents + let nil_idx = p.push_lident_static("[]"); + let cons_idx = p.push_lident_static("::"); // Build the list using cons cells - let list_end = seg_loc.loc_end.clone(); - let tail = spread.unwrap_or_else(|| { + let list_end = seg_end; + let mut acc = spread.unwrap_or_else(|| { // Empty list with ghost location (same as OCaml's make_list_expression) - let ghost_loc = Location::none(); + let ghost_loc = LocIdx::none(); Expression { pexp_desc: ExpressionDesc::Pexp_construct( Loc { - txt: Longident::Lident("[]".to_string()), - loc: ghost_loc.clone(), + txt: nil_idx, + loc: ghost_loc, }, None, ), @@ -2577,30 +3202,31 @@ fn make_list_expression_with_loc( } }); - let expr = exprs.into_iter().rev().fold(tail, |acc, item| { - let cons_loc = Location::from_positions(item.pexp_loc.loc_start.clone(), list_end.clone()); + for item in exprs.into_iter().rev() { + let item_start = p.loc_start(item.pexp_loc).clone(); + let cons_loc = p.mk_loc_from_positions(&item_start, &list_end); let tuple = Expression { pexp_desc: ExpressionDesc::Pexp_tuple(vec![item, acc]), - pexp_loc: cons_loc.clone(), + pexp_loc: cons_loc, pexp_attributes: vec![], }; - Expression { + acc = Expression { pexp_desc: ExpressionDesc::Pexp_construct( Loc { - txt: Longident::Lident("::".to_string()), - loc: cons_loc.clone(), + txt: cons_idx, + loc: cons_loc, }, Some(Box::new(tuple)), ), pexp_loc: cons_loc, pexp_attributes: vec![], - } - }); + }; + } // OCaml: `{expr with pexp_loc = loc}` updates outermost expression's location Expression { pexp_loc: seg_loc, - ..expr + ..acc } } @@ -2613,6 +3239,19 @@ fn parse_dict_expr(p: &mut Parser<'_>, start_pos: Position) -> Expression { let mut key_value_pairs: Vec = vec![]; while p.token != Token::Rbrace && p.token != Token::Eof { + // Check for spread syntax (not supported in dicts) + if p.token == Token::DotDotDot { + p.err(DiagnosticCategory::Message( + super::core::error_messages::DICT_EXPR_SPREAD.to_string(), + )); + p.next(); // consume the ... + // Skip the spread expression + let _ = parse_unary_expr(p); + if !p.optional(&Token::Comma) { + break; + } + continue; + } // Parse key (string) match &p.token { Token::String(s) => { @@ -2626,16 +3265,16 @@ fn parse_dict_expr(p: &mut Parser<'_>, start_pos: Position) -> Expression { p.expect(Token::Colon); let value = parse_expr(p); - let value_end = value.pexp_loc.loc_end.clone(); + let value_end = p.loc_end(value.pexp_loc); // Create tuple (key_string, value) // Key uses None delimiter to be printed as "key" (object property style) let key_expr = Expression { pexp_desc: ExpressionDesc::Pexp_constant(Constant::String(key, None)), - pexp_loc: key_loc.clone(), + pexp_loc: key_loc, pexp_attributes: vec![], }; - let tuple_loc = p.mk_loc(&key_loc.loc_start, &value_end); + let tuple_loc = p.mk_loc(&p.loc_start(key_loc), &value_end); let tuple = Expression { pexp_desc: ExpressionDesc::Pexp_tuple(vec![key_expr, value]), pexp_loc: tuple_loc, @@ -2656,7 +3295,7 @@ fn parse_dict_expr(p: &mut Parser<'_>, start_pos: Position) -> Expression { } p.expect(Token::Rbrace); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); // Create array of key-value pairs let array_expr = Expression { @@ -2666,12 +3305,16 @@ fn parse_dict_expr(p: &mut Parser<'_>, start_pos: Position) -> Expression { }; // Create Primitive_dict.make identifier + let prim_idx = p.arena_mut().intern_string("Primitive_dict"); + let make_idx = p.arena_mut().intern_string("make"); + let lid = Longident::Ldot( + Box::new(Longident::Lident(prim_idx)), + make_idx, + ); + let lid_idx = p.push_longident(lid); let make_ident = Expression { pexp_desc: ExpressionDesc::Pexp_ident(Loc { - txt: Longident::Ldot( - Box::new(Longident::Lident("Primitive_dict".to_string())), - "make".to_string(), - ), + txt: lid_idx, loc: loc.clone(), }), pexp_loc: loc.clone(), @@ -2699,7 +3342,7 @@ fn parse_braced_or_record_expr(p: &mut Parser<'_>) -> Expression { // Check for empty braces if p.token == Token::Rbrace { p.next(); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); return Expression { pexp_desc: ExpressionDesc::Pexp_record(vec![], None), pexp_loc: loc, @@ -2719,7 +3362,7 @@ fn parse_braced_or_record_expr(p: &mut Parser<'_>) -> Expression { if p.token == Token::Colon { p.next(); let typ = super::typ::parse_typ_expr(p); - let loc = p.mk_loc(&spread_start, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&spread_start); spread = Expression { pexp_desc: ExpressionDesc::Pexp_constraint(Box::new(spread), typ), pexp_loc: loc, @@ -2729,7 +3372,7 @@ fn parse_braced_or_record_expr(p: &mut Parser<'_>) -> Expression { p.optional(&Token::Comma); let fields = parse_record_fields(p); p.expect(Token::Rbrace); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); return Expression { pexp_desc: ExpressionDesc::Pexp_record(fields, Some(Box::new(spread))), pexp_loc: loc, @@ -2737,6 +3380,40 @@ fn parse_braced_or_record_expr(p: &mut Parser<'_>) -> Expression { }; } + // OCaml: Token.is_keyword token case in parse_braced_or_record_expr + // Check for keyword as first token (before block expression check) + if p.token.is_keyword() { + if let Some((recovered_name, loc)) = super::core::recover_keyword_field_name_if_probably_field( + p, + super::core::error_messages::keyword_field_in_expr, + ) { + // OCaml: Parser.expect Colon p + p.expect(Token::Colon); + // Check for optional marker + let opt = p.token == Token::Question; + if opt { + p.next(); + } + let field_expr = parse_expr(p); + let lid_idx = p.push_lident(&recovered_name); + let lid = with_loc(lid_idx, loc); + let first_field = ExpressionRecordField { lid, expr: field_expr, opt }; + p.optional(&Token::Comma); + let mut fields = parse_record_fields(p); + fields.insert(0, first_field); + p.expect(Token::Rbrace); + let loc = p.mk_loc_to_prev_end(&start_pos); + return Expression { + pexp_desc: ExpressionDesc::Pexp_record(fields, None), + pexp_loc: loc, + pexp_attributes: vec![], + }; + } else { + // Not followed by colon - parse as block expression + return parse_block_expr(p, start_pos); + } + } + // Check if this looks like a block expression (module-level constructs or let/expressions) if is_block_expression_start(&p.token) { return parse_block_expr(p, start_pos); @@ -2745,6 +3422,9 @@ fn parse_braced_or_record_expr(p: &mut Parser<'_>) -> Expression { // Check if this looks like a record (name followed by : or ,) // or a JS object (string key followed by :) // Also check for optional field syntax: { ? name, ... } + // Also check for error case: {ident1 ident2:...} where we have two identifiers + // and the second one is followed by colon (this is a record field error case). + // OCaml res_core.ml line 3229-3247 handles this case specially. let is_record = p.lookahead(|state| { // Optional field punning: { ? name, ... } if state.token == Token::Question { @@ -2775,7 +3455,21 @@ fn parse_braced_or_record_expr(p: &mut Parser<'_>) -> Expression { if started_with_uident || parts > 1 { matches!(state.token, Token::Colon | Token::Comma) } else { - matches!(state.token, Token::Colon | Token::Comma) + // Also check for error case: {ident1 ident2:...} + // This is when first identifier is followed by another identifier (on a different line) + // or followed by another identifier and then a colon (on same line) + // OCaml handles this specially to give good error messages for record fields + if matches!(state.token, Token::Lident(_)) { + // Skip the second identifier + state.next(); + // If colon follows, this is likely {ident1 ident2: value} - missing comma + // If another identifier follows or something else, might be a record error case + // We'll return true to let the record field parsing handle the error + return matches!(state.token, Token::Colon | Token::Lident(_)); + } + // Include Token::Equal to detect {foo = value} as a record with wrong separator + // OCaml res_core.ml line 3206 handles this case + matches!(state.token, Token::Colon | Token::Comma | Token::Equal) } }); @@ -2792,7 +3486,7 @@ fn parse_braced_or_record_expr(p: &mut Parser<'_>) -> Expression { if is_record { let fields = parse_record_fields(p); p.expect(Token::Rbrace); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); return Expression { pexp_desc: ExpressionDesc::Pexp_record(fields, None), pexp_loc: loc, @@ -2819,10 +3513,84 @@ fn parse_braced_or_record_expr(p: &mut Parser<'_>) -> Expression { return parse_braced_arrow_ident(p, start_pos); } + // Special handling for identifier followed by semicolon: {a;} or {a; b()} + // OCaml creates the ident expression WITHOUT ~loc when followed by semicolon, + // which defaults to Location.none (ghost location). + // This matches res_core.ml line 3248-3250. + let is_ident_semicolon = p.lookahead(|state| { + if let Token::Lident(_) | Token::Uident(_) = &state.token { + // Check for simple ident or dotted path (Foo.bar) + loop { + state.next(); + if state.token == Token::Dot { + state.next(); + if !matches!(state.token, Token::Lident(_) | Token::Uident(_)) { + return false; + } + } else { + break; + } + } + matches!(state.token, Token::Semicolon) + } else { + false + } + }); + + if is_ident_semicolon { + return parse_braced_ident_semicolon(p, start_pos); + } + // Fall back to block expression parse_block_expr(p, start_pos) } +/// Parse braced expression starting with identifier followed by semicolon: {a;} or {a; b()} +/// OCaml creates the ident expression WITHOUT ~loc when followed by semicolon, +/// which defaults to Location.none (ghost location). +fn parse_braced_ident_semicolon(p: &mut Parser<'_>, start_pos: Position) -> Expression { + // Parse the value/constructor expression + let mut ident_expr = parse_value_or_constructor(p); + + // Set the expression location to ghost (matching OCaml's behavior) + // OCaml: Ast_helper.Exp.ident path_ident <- no ~loc, defaults to Location.none + ident_expr.pexp_loc = LocIdx::none(); + + // Consume the semicolon + p.expect(Token::Semicolon); + + // Parse the rest of the block (if any) + let rest = parse_block_body(p); + + p.expect(Token::Rbrace); + let braces_loc = p.mk_loc_to_prev_end(&start_pos); + + // Build the final expression + let mut expr = if let Some(rest_expr) = rest { + // Create sequence: a; b() + // OCaml: loc = {e1.pexp_loc with loc_end = e2.pexp_loc.loc_end} + // Since e1 has ghost loc, the sequence loc should also be ghost + let seq_loc = p.mk_loc_spanning_preserve_ghost(ident_expr.pexp_loc, rest_expr.pexp_loc); + Expression { + pexp_desc: ExpressionDesc::Pexp_sequence( + Box::new(ident_expr), + Box::new(rest_expr), + ), + pexp_loc: seq_loc, + pexp_attributes: vec![], + } + } else { + // Just the identifier with trailing semicolon: {a;} + ident_expr + }; + + // Add res.braces attribute + let braces_attr = make_braces_attr(braces_loc); + expr.pexp_attributes.insert(0, braces_attr); + + expr +} + /// Check if a token starts a block expression (vs record). fn is_block_expression_start(token: &Token) -> bool { matches!( @@ -2885,12 +3653,12 @@ fn parse_braced_arrow_ident(p: &mut Parser<'_>, start_pos: Position) -> Expressi let arrow_expr = parse_ternary_expr(p, arrow_expr); // Handle semicolon and continuation (block expression semantics) - p.optional(&Token::Semicolon); + parse_newline_or_semicolon_expr_block(p); let expr = if p.token != Token::Rbrace && p.token != Token::Eof { // There's more content - parse as sequence if let Some(rest) = parse_block_body(p) { - let new_loc = p.mk_loc(&arrow_expr.pexp_loc.loc_start, &rest.pexp_loc.loc_end); + let new_loc = p.mk_loc_spanning(arrow_expr.pexp_loc, rest.pexp_loc); Expression { pexp_desc: ExpressionDesc::Pexp_sequence(Box::new(arrow_expr), Box::new(rest)), pexp_loc: new_loc, @@ -2904,7 +3672,7 @@ fn parse_braced_arrow_ident(p: &mut Parser<'_>, start_pos: Position) -> Expressi }; p.expect(Token::Rbrace); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); // Add res.braces attribute let braces_attr = make_braces_attr(loc); @@ -2919,31 +3687,37 @@ fn parse_braced_arrow_ident(p: &mut Parser<'_>, start_pos: Position) -> Expressi /// Note: This does NOT consume the closing Rbrace - the caller must do that. fn parse_expr_block(p: &mut Parser<'_>) -> Expression { let start_pos = p.start_pos.clone(); + // OCaml: leave_breadcrumb ExprBlock - critical for error recovery + // This allows should_abort_list_parse to detect } as a block terminator + p.leave_breadcrumb(Grammar::ExprBlock); // Parse the block body - this handles building the proper nesting for let/module/open/exception let body = parse_block_body(p); + p.eat_breadcrumb(); // Don't expect Rbrace here - caller will do that // Use current position for empty block, or body's end position - let end_pos = body - .as_ref() - .map(|e| e.pexp_loc.loc_end.clone()) - .unwrap_or_else(|| p.prev_end_pos.clone()); - let loc = p.mk_loc(&start_pos, &end_pos); - - body.unwrap_or_else(|| ast_helper::make_unit(loc)) + // OCaml: when the block is empty, use exprhole (not unit) so that + // error recovery produces [%rescript.exprhole] instead of () + body.unwrap_or_else(super::core::recover::default_expr) } /// Parse a block expression { stmt1; stmt2; expr } WITH res.braces attribute. /// This is used for standalone braced expressions where res.braces is needed /// to preserve the bracing information. fn parse_block_expr(p: &mut Parser<'_>, start_pos: Position) -> Expression { + // OCaml: leave_breadcrumb ExprBlock - critical for error recovery + p.leave_breadcrumb(Grammar::ExprBlock); // Parse the block body - this handles building the proper nesting for let/module/open/exception let body = parse_block_body(p); + p.eat_breadcrumb(); p.expect(Token::Rbrace); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); - let mut expr = body.unwrap_or_else(|| ast_helper::make_unit(loc.clone())); + let mut expr = match body { + Some(e) => e, + None => ast_helper::make_unit(p, loc.clone()), + }; // Note: The special {ident =>} case is handled separately by parse_braced_arrow_ident. // For other arrow functions inside braces ({_ => ...}, {() => ...}, {(x, y) => ...}), @@ -2966,7 +3740,11 @@ fn parse_block_body(p: &mut Parser<'_>) -> Option { p.next(); } - if p.token == Token::Rbrace || p.token == Token::Eof { + // Check if we can parse more expressions. + // OCaml uses `is_block_expr_start` here to determine if the block continues. + // This is important for error recovery - when `else` appears after an if's then-branch, + // we should NOT try to parse it as a block expression. + if p.token == Token::Rbrace || p.token == Token::Eof || !grammar::is_block_expr_start(&p.token) { return None; } @@ -2987,19 +3765,19 @@ fn parse_block_body(p: &mut Parser<'_>) -> Option { }; let lid = parse_module_longident(p); - // Consume optional semicolon/newline - p.optional(&Token::Semicolon); + // Check consecutive expressions + parse_newline_or_semicolon_expr_block(p); // Parse the rest of the block as the body let rest = parse_block_body(p); let body = rest.unwrap_or_else(|| { // OCaml: when block ends without trailing expression, implicit () is at the } position - let loc = p.mk_loc(&p.start_pos, &p.end_pos); - ast_helper::make_unit(loc) + let loc = p.mk_loc_current(); + ast_helper::make_unit(p, loc) }); // OCaml uses p.prev_end_pos for Pexp_open location - let loc = p.mk_loc(&expr_start, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&expr_start); Expression { pexp_desc: ExpressionDesc::Pexp_open(override_flag, lid, Box::new(body)), pexp_loc: loc, @@ -3020,12 +3798,12 @@ fn parse_block_body(p: &mut Parser<'_>) -> Option { let pack_expr = parse_first_class_module_expr(p, expr_start); let expr = parse_expr_with_operand(p, pack_expr); - // Consume optional semicolon - p.optional(&Token::Semicolon); + // Check consecutive expressions + parse_newline_or_semicolon_expr_block(p); // Check for continuation if let Some(rest) = parse_block_body(p) { - let new_loc = p.mk_loc(&expr.pexp_loc.loc_start, &rest.pexp_loc.loc_end); + let new_loc = p.mk_loc_spanning(expr.pexp_loc, rest.pexp_loc); Expression { pexp_desc: ExpressionDesc::Pexp_sequence(Box::new(expr), Box::new(rest)), pexp_loc: new_loc, @@ -3053,7 +3831,7 @@ fn parse_block_body(p: &mut Parser<'_>) -> Option { // For `module M: T = E`, the constraint type T appears before =, so // the location spans from mod_type start to module_expr end if let Some(mod_type) = mod_type { - let loc = p.mk_loc(&mod_type.pmty_loc.loc_start, &module_expr.pmod_loc.loc_end); + let loc = p.mk_loc_spanning(mod_type.pmty_loc, module_expr.pmod_loc); module_expr = ModuleExpr { pmod_desc: ModuleExprDesc::Pmod_constraint( Box::new(module_expr), @@ -3064,19 +3842,19 @@ fn parse_block_body(p: &mut Parser<'_>) -> Option { }; } - // Consume optional semicolon/newline - p.optional(&Token::Semicolon); + // Check consecutive expressions + parse_newline_or_semicolon_expr_block(p); // Parse the rest of the block as the body let rest = parse_block_body(p); let body = rest.unwrap_or_else(|| { // OCaml: when block ends without trailing expression, implicit () is at the } position - let loc = p.mk_loc(&p.start_pos, &p.end_pos); - ast_helper::make_unit(loc) + let loc = p.mk_loc_current(); + ast_helper::make_unit(p, loc) }); // OCaml uses p.prev_end_pos for Pexp_letmodule location - let loc = p.mk_loc(&expr_start, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&expr_start); Expression { pexp_desc: ExpressionDesc::Pexp_letmodule( module_name, @@ -3095,25 +3873,104 @@ fn parse_block_body(p: &mut Parser<'_>) -> Option { let ext = super::module::parse_extension_constructor(p, vec![], Some(expr_start.clone())); - // Consume optional semicolon/newline - p.optional(&Token::Semicolon); + // Check consecutive expressions + parse_newline_or_semicolon_expr_block(p); // Parse the rest of the block as the body let rest = parse_block_body(p); let body = rest.unwrap_or_else(|| { // OCaml: when block ends without trailing expression, implicit () is at the } position - let loc = p.mk_loc(&p.start_pos, &p.end_pos); - ast_helper::make_unit(loc) + let loc = p.mk_loc_current(); + ast_helper::make_unit(p, loc) }); // OCaml uses p.prev_end_pos for Pexp_letexception location - let loc = p.mk_loc(&expr_start, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&expr_start); Expression { pexp_desc: ExpressionDesc::Pexp_letexception(ext, Box::new(body)), pexp_loc: loc, pexp_attributes: vec![], } } + Token::Typ => { + // Type definitions are not allowed inside blocks/functions in ReScript + // OCaml: parse the type definition first to get the correct error location, + // then emit the error and continue parsing + let type_start = p.start_pos.clone(); + p.begin_region(); + p.next(); // consume 'type' + + // Skip the entire type definition to get its end position + // Type definition format: type [rec] name [] = body [and ...] + // Skip 'rec' if present + if p.token == Token::Rec { + p.next(); + } + // Skip type name (identifier) + if matches!(p.token, Token::Lident(_)) { + p.next(); + } + // Skip type parameters <'a, 'b> if present + if p.token == Token::LessThan { + let mut depth = 1; + p.next(); + while depth > 0 && p.token != Token::Eof { + match p.token { + Token::LessThan => depth += 1, + Token::GreaterThan => depth -= 1, + _ => {} + } + p.next(); + } + } + // Skip = and the type body + if p.token == Token::Equal { + p.next(); + // Skip until we hit a newline, semicolon, closing brace, or a new statement keyword + // The type body can contain identifiers, dots, angle brackets, etc. + let mut brace_depth = 0; + let mut paren_depth = 0; + let mut angle_depth = 0; + while p.token != Token::Eof { + // Track nesting + match &p.token { + Token::Lbrace => brace_depth += 1, + Token::Rbrace if brace_depth > 0 => brace_depth -= 1, + Token::Rbrace => break, // End of enclosing block + Token::Lparen => paren_depth += 1, + Token::Rparen if paren_depth > 0 => paren_depth -= 1, + Token::LessThan => angle_depth += 1, + Token::GreaterThan if angle_depth > 0 => angle_depth -= 1, + _ => {} + } + // Stop at statement boundaries (outside of nested structures) + if brace_depth == 0 && paren_depth == 0 && angle_depth == 0 { + match &p.token { + Token::Let { .. } | Token::Module | Token::Open | Token::External | Token::Exception => break, + _ => {} + } + // Stop at line break (implicit statement separator) + // prev_end_pos.line < start_pos.line means there was a newline + if p.prev_end_pos.line < p.start_pos.line { + break; + } + } + p.next(); + } + } + p.end_region(); + // Emit error at the type definition location + p.err_at( + type_start, + p.prev_end_pos.clone(), + super::diagnostics::DiagnosticCategory::Message( + super::core::error_messages::TYPE_DEFINITION_IN_FUNCTION.to_string(), + ), + ); + // Parse the next semicolon/newline if present, then continue + parse_newline_or_semicolon_expr_block(p); + return parse_block_body(p); + } _ => { let mut expr = parse_expr(p); @@ -3122,18 +3979,19 @@ fn parse_block_body(p: &mut Parser<'_>) -> Option { expr.pexp_attributes.extend(attrs.clone()); } - // Consume optional semicolon - p.optional(&Token::Semicolon); + // Check consecutive expressions + parse_newline_or_semicolon_expr_block(p); // Check for continuation if let Some(rest) = parse_block_body(p) { - let new_loc = p.mk_loc(&expr.pexp_loc.loc_start, &rest.pexp_loc.loc_end); + let new_loc = p.mk_loc_spanning(expr.pexp_loc, rest.pexp_loc); return Some(Expression { pexp_desc: ExpressionDesc::Pexp_sequence(Box::new(expr), Box::new(rest)), pexp_loc: new_loc, pexp_attributes: vec![], }); } else { + let expr = over_parse_constrained_or_coerced_or_arrow_expression(p, expr); return Some(expr); } } @@ -3160,7 +4018,7 @@ fn parse_let_in_block_with_continuation_and_attrs( // OCaml includes leading attributes in the binding location let binding_start_pos = leading_attrs .first() - .map(|attr| attr.0.loc.loc_start.clone()) + .map(|attr| p.loc_start(attr.0.loc)) .unwrap_or_else(|| p.start_pos.clone()); let start_pos = p.start_pos.clone(); @@ -3193,7 +4051,11 @@ fn parse_let_in_block_with_continuation_and_attrs( // Check if this is `type a.` syntax (locally abstract types) let is_locally_abstract = p.token == Token::Typ; - let typ = super::typ::parse_typ_expr(p); + let typ = if is_locally_abstract { + super::typ::parse_locally_abstract_type(p) + } else { + super::typ::parse_typ_expr(p) + }; // Extract type variables and inner type if this is a Ptyp_poly from `type a.` syntax let (final_typ, newtype_info) = match typ.ptyp_desc { @@ -3206,7 +4068,7 @@ fn parse_let_in_block_with_continuation_and_attrs( let inner_for_constraint = (**inner).clone(); // Substitute Ptyp_constr -> Ptyp_var for the Ptyp_poly body - let substituted_inner = super::typ::substitute_type_vars((**inner).clone(), &var_set); + let substituted_inner = super::typ::substitute_type_vars(p.arena(), (**inner).clone(), &var_set); // Rebuild the Ptyp_poly with the substituted body let substituted_typ = CoreType { @@ -3221,7 +4083,7 @@ fn parse_let_in_block_with_continuation_and_attrs( }; // Create a constraint pattern - let loc = p.mk_loc(&first_pat.ppat_loc.loc_start, &final_typ.ptyp_loc.loc_end); + let loc = p.mk_loc_spanning(first_pat.ppat_loc, final_typ.ptyp_loc); let pat = Pattern { ppat_desc: PatternDesc::Ppat_constraint(Box::new(first_pat), final_typ), ppat_loc: loc, @@ -3236,7 +4098,7 @@ fn parse_let_in_block_with_continuation_and_attrs( let mut first_value = parse_expr(p); // Compute binding location BEFORE wrapping (OCaml uses this for locally abstract type locations) - let first_loc = p.mk_loc(&binding_start_pos, &p.prev_end_pos); + let first_loc = p.mk_loc_to_prev_end(&binding_start_pos); // For locally abstract types, OCaml uses the binding location for the pattern constraint and Ptyp_poly let first_pat = if is_locally_abstract { @@ -3317,7 +4179,7 @@ fn parse_let_in_block_with_continuation_and_attrs( let pat = if p.token == Token::Colon { p.next(); let typ = super::typ::parse_typ_expr(p); - let loc = p.mk_loc(&pat.ppat_loc.loc_start, &typ.ptyp_loc.loc_end); + let loc = p.mk_loc_spanning(pat.ppat_loc, typ.ptyp_loc); Pattern { ppat_desc: PatternDesc::Ppat_constraint(Box::new(pat), typ), ppat_loc: loc, @@ -3329,7 +4191,7 @@ fn parse_let_in_block_with_continuation_and_attrs( p.expect(Token::Equal); let value = parse_expr(p); - let binding_loc = p.mk_loc(&binding_start, &p.prev_end_pos); + let binding_loc = p.mk_loc_to_prev_end(&binding_start); bindings.push(ValueBinding { pvb_pat: pat, pvb_expr: value, @@ -3338,16 +4200,16 @@ fn parse_let_in_block_with_continuation_and_attrs( }); } - // Consume optional semicolon/newline - p.optional(&Token::Semicolon); + // Check consecutive expressions + parse_newline_or_semicolon_expr_block(p); // Parse the rest of the block as the body let rest = parse_block_body(p); let is_implicit_body = rest.is_none(); let body = rest.unwrap_or_else(|| { // OCaml: when block ends without trailing expression, implicit () is at the } position - let loc = p.mk_loc(&p.start_pos, &p.end_pos); - ast_helper::make_unit(loc) + let loc = p.mk_loc_current(); + ast_helper::make_unit(p, loc) }); // OCaml: Pexp_let location always uses p.prev_end_pos after parsing body @@ -3368,7 +4230,7 @@ fn parse_module_name(p: &mut Parser<'_>) -> Located { match &p.token { Token::Uident(name) => { let name = name.clone(); - let loc = p.mk_loc(&p.start_pos, &p.end_pos); + let loc = p.mk_loc_current(); p.next(); with_loc(name, loc) } @@ -3382,7 +4244,7 @@ fn parse_module_name(p: &mut Parser<'_>) -> Located { } /// Parse a module long identifier. -fn parse_module_longident(p: &mut Parser<'_>) -> Located { +fn parse_module_longident(p: &mut Parser<'_>) -> Located { let start_pos = p.start_pos.clone(); let mut parts = vec![]; @@ -3413,18 +4275,54 @@ fn parse_module_longident(p: &mut Parser<'_>) -> Located { parts.push("Error".to_string()); } - let lid = super::core::build_longident(&parts); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); - with_loc(lid, loc) + let lid = super::core::build_longident(p.arena_mut(), &parts); + let lid_idx = p.push_longident(lid); + let loc = p.mk_loc_to_prev_end(&start_pos); + with_loc(lid_idx, loc) +} + +/// Handle comma after parsing a record field, matching OCaml's parse_comma_delimited_region. +/// Returns true if parsing should continue, false if it should stop. +fn handle_record_field_comma(p: &mut Parser<'_>) -> bool { + if p.token == Token::Comma { + p.next(); + true + } else if p.token == Token::Rbrace || p.token == Token::Eof { + false + } else if grammar::is_record_row_start(&p.token) { + // Token looks like another field but no comma - missing comma case + p.expect(Token::Comma); + true + } else if !recover::should_abort_list_parse(p) { + // Unexpected token, not closing/EOF/abort - expect comma + p.expect(Token::Comma); + if p.token == Token::Semicolon { + p.next(); + } + true + } else { + false + } } /// Parse record fields. fn parse_record_fields(p: &mut Parser<'_>) -> Vec { let mut fields = vec![]; + p.leave_breadcrumb(Grammar::RecordRows); + while p.token != Token::Rbrace && p.token != Token::Eof { let field_start = p.start_pos.clone(); + // Check for additional spread (second spread is an error) + // OCaml: parse_record_expr_row checks for DotDotDot and emits error + if p.token == Token::DotDotDot { + p.err(DiagnosticCategory::Message( + super::core::error_messages::RECORD_EXPR_SPREAD.to_string(), + )); + p.next(); + } + // Check for optional field punning: { ? name, ... } let opt_punning = p.token == Token::Question; if opt_punning { @@ -3435,6 +4333,7 @@ fn parse_record_fields(p: &mut Parser<'_>) -> Vec { let expr_start = if opt_punning { p.start_pos.clone() } else { field_start.clone() }; // Support qualified record labels: {Module.label: value} + // OCaml: Lident/Uident case in parse_record_expr_row let mut parts: Vec = vec![]; loop { match &p.token { @@ -3442,10 +4341,6 @@ fn parse_record_fields(p: &mut Parser<'_>) -> Vec { parts.push(name.clone()); p.next(); } - _ if p.token.is_keyword() => { - parts.push(p.token.to_string()); - p.next(); - } _ => break, } if p.token == Token::Dot { @@ -3455,11 +4350,48 @@ fn parse_record_fields(p: &mut Parser<'_>) -> Vec { } } + // If parts is empty, check for keyword field + // OCaml: Token.is_keyword p.token case in parse_record_expr_row if parts.is_empty() { - break; + if p.token.is_keyword() { + // Try to recover keyword as field name if followed by colon + if let Some((recovered_name, loc)) = super::core::recover_keyword_field_name_if_probably_field( + p, + super::core::error_messages::keyword_field_in_expr, + ) { + // OCaml: Parser.expect Colon p + p.expect(Token::Colon); + // Check for optional marker after colon: name: ? value + let opt = p.token == Token::Question; + if opt { + p.next(); + } + let expr = parse_expr(p); + let lid_idx = p.push_lident(&recovered_name); + let lid = with_loc(lid_idx, loc); + fields.push(ExpressionRecordField { lid, expr, opt }); + if !handle_record_field_comma(p) { + break; + } + continue; + } else { + // Just emit the error and break + super::core::emit_keyword_field_error(p, super::core::error_messages::keyword_field_in_expr); + break; + } + } + // Token is not a valid field start - check if we should continue or stop + if p.token == Token::Rbrace || p.token == Token::Eof || recover::should_abort_list_parse(p) { + break; + } + // Unexpected token - report error and skip + p.err_unexpected(); + p.next(); + continue; } - let lid_unloc = super::core::build_longident(&parts); + let lid_unloc = super::core::build_longident(p.arena_mut(), &parts); + let lid_idx = p.push_longident(lid_unloc); let pun_name = parts.last().cloned().unwrap_or("_".to_string()); let (lid, expr, opt) = if p.token == Token::Colon { @@ -3474,22 +4406,67 @@ fn parse_record_fields(p: &mut Parser<'_>) -> Vec { p.next(); } let expr = parse_expr(p); - (with_loc(lid_unloc, lid_loc), expr, opt) + (with_loc(lid_idx, lid_loc), expr, opt) + } else if p.token == Token::Equal { + // OCaml: Token.Equal case in parse_record_expr_row + // {field=value} instead of {field: value} + let lid_end = p.prev_end_pos.clone(); + p.err_at( + p.start_pos.clone(), + p.end_pos.clone(), + DiagnosticCategory::message( + "Records use `:` when assigning fields. Example: `{field: value}`", + ), + ); + p.next(); // consume = + let lid_loc = p.mk_loc(&field_start, &lid_end); + let opt = p.token == Token::Question; + if opt { + p.next(); + } + let expr = parse_expr(p); + (with_loc(lid_idx, lid_loc), expr, opt) + } else if matches!(p.token, Token::Lident(_)) { + // OCaml res_core.ml line 3229-3247: Error case where ident is followed by another ident + // Example: {updateF value:...} where updateF and value are separate identifiers + // If they are on different lines, emit "Did you forget a `,`?" + // If they are on the same line, emit "Did you forget a `:`?" + let prev_line = p.prev_end_pos.line; + let curr_line = p.start_pos.line; + + // Punning: this field is punned (value is same as name) + let loc = p.mk_loc_to_prev_end(&expr_start); + let pun_idx = p.arena_mut().push_string(pun_name); + let punned_expr = ast_helper::make_ident(p, Longident::Lident(pun_idx), loc.clone()); + let lid = with_loc(lid_idx, loc); + + // Emit appropriate error and expect comma or colon + if prev_line < curr_line { + // Different lines - expect comma + p.expect(Token::Comma); + } else { + // Same line - expect colon + p.expect(Token::Colon); + } + + (lid, punned_expr, opt_punning) } else { // Punning: field is same as variable // For optional punned fields, the expression location is just the identifier (using expr_start) - let loc = p.mk_loc(&expr_start, &p.prev_end_pos); - let expr = ast_helper::make_ident(Longident::Lident(pun_name), loc.clone()); - (with_loc(lid_unloc, loc), expr, opt_punning) + let loc = p.mk_loc_to_prev_end(&expr_start); + let pun_idx = p.arena_mut().push_string(pun_name); + let expr = ast_helper::make_ident(p, Longident::Lident(pun_idx), loc.clone()); + (with_loc(lid_idx, loc), expr, opt_punning) }; fields.push(ExpressionRecordField { lid, expr, opt }); - if !p.optional(&Token::Comma) { + if !handle_record_field_comma(p) { break; } } + p.eat_breadcrumb(); fields } @@ -3507,20 +4484,21 @@ fn parse_js_object_expr(p: &mut Parser<'_>, start_pos: Position) -> Expression { // The lid location should be just the key, not including the value let key_loc = p.mk_loc(&field_start, &key_end); + let lid_idx = p.push_lident(&key); if p.token == Token::Colon { p.next(); let expr = parse_expr(p); fields.push(ExpressionRecordField { - lid: with_loc(Longident::Lident(key), key_loc), + lid: with_loc(lid_idx, key_loc), expr, opt: false, }); } else { // Punning for string keys (less common but valid) - let expr = ast_helper::make_ident(Longident::Lident(key.clone()), key_loc.clone()); + let expr = ast_helper::make_ident_idx(lid_idx, key_loc.clone()); fields.push(ExpressionRecordField { - lid: with_loc(Longident::Lident(key), key_loc), + lid: with_loc(lid_idx, key_loc), expr, opt: false, }); @@ -3535,7 +4513,7 @@ fn parse_js_object_expr(p: &mut Parser<'_>, start_pos: Position) -> Expression { } p.expect(Token::Rbrace); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); // Create the inner record expression let record_expr = Expression { @@ -3564,33 +4542,73 @@ fn parse_js_object_expr(p: &mut Parser<'_>, start_pos: Position) -> Expression { // Control Flow Expressions // ============================================================================ -/// Parse an if expression. -fn parse_if_expr(p: &mut Parser<'_>) -> Expression { - let start_pos = p.start_pos.clone(); - p.expect(Token::If); - +/// Parse the condition of an if expression. +/// OCaml: parse_if_condition +fn parse_if_condition(p: &mut Parser<'_>) -> Expression { + p.leave_breadcrumb(Grammar::IfCondition); let condition = parse_expr_with_context(p, ExprContext::When); + p.eat_breadcrumb(); + condition +} + +/// Parse the then-branch of an if expression. +/// OCaml: parse_then_branch +fn parse_then_branch(p: &mut Parser<'_>) -> Expression { + p.leave_breadcrumb(Grammar::IfBranch); p.expect(Token::Lbrace); - // Use parse_expr_block (no res.braces) for if branches, matching OCaml behavior - let then_branch = parse_expr_block(p); + let then_expr = parse_expr_block(p); p.expect(Token::Rbrace); + p.eat_breadcrumb(); + then_expr +} + +/// Parse the else-branch of an if expression (body only, after `else` is consumed). +/// OCaml: parse_else_branch +fn parse_else_branch(p: &mut Parser<'_>) -> Expression { + p.expect(Token::Lbrace); + let block_expr = parse_expr_block(p); + p.expect(Token::Rbrace); + block_expr +} + +/// Parse the body of an if expression (after `if` is consumed). +/// OCaml: parse_if_expr +/// +/// This function handles the region management for error suppression: +/// - The calling function (parse_if_or_if_let_expression) has already called begin_region +/// - When we see `else`, we end_region (to allow else branch to report its own errors) +/// then begin_region for the else branch +/// - We end_region at the end in both cases +fn parse_if_expr_body(p: &mut Parser<'_>, start_pos: Position) -> Expression { + let condition = parse_if_condition(p); + let then_branch = parse_then_branch(p); let else_branch = if p.token == Token::Else { - p.next(); - if p.token == Token::If { - Some(Box::new(parse_if_expr(p))) + // End the region for the then-branch (allows else branch to report errors) + p.end_region(); + p.leave_breadcrumb(Grammar::ElseBranch); + p.next(); // consume `else` + // Begin a new region for the else-branch + p.begin_region(); + + let else_expr = if p.token == Token::If { + // `else if` - recursively parse another if expression + // Note: parse_if_or_if_let_expression will do its own begin_region + parse_if_or_if_let_expression(p) } else { - p.expect(Token::Lbrace); - // Use parse_expr_block (no res.braces) for else branches, matching OCaml behavior - let expr = parse_expr_block(p); - p.expect(Token::Rbrace); - Some(Box::new(expr)) - } + parse_else_branch(p) + }; + + p.eat_breadcrumb(); + p.end_region(); + Some(Box::new(else_expr)) } else { + // No else branch - end the region here + p.end_region(); None }; - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); Expression { pexp_desc: ExpressionDesc::Pexp_ifthenelse( @@ -3603,6 +4621,157 @@ fn parse_if_expr(p: &mut Parser<'_>) -> Expression { } } +/// Parse an if expression (or if-let expression). +/// OCaml: parse_if_or_if_let_expression +/// +/// This is the main entry point for parsing if expressions. +/// It sets up the region and breadcrumb, then delegates to parse_if_expr_body. +fn parse_if_or_if_let_expression(p: &mut Parser<'_>) -> Expression { + p.begin_region(); + p.leave_breadcrumb(Grammar::ExprIf); + let start_pos = p.start_pos.clone(); + p.expect(Token::If); + + let expr = match &p.token { + Token::Let { .. } => { + // if-let expression: parse as match with @res.iflet attribute + p.next(); // consume `let` + parse_if_let_expr(p, start_pos) + } + _ => parse_if_expr_body(p, start_pos), + }; + + p.eat_breadcrumb(); + expr +} + +/// Parse an if-let expression (after `if` and `let` are consumed). +/// OCaml: parse_if_let_expr +/// +/// Produces a Pexp_match with @res.iflet and @warning "-4" attributes, +/// and emits an experimental if-let error message. +fn parse_if_let_expr(p: &mut Parser<'_>, start_pos: Position) -> Expression { + let pattern = super::pattern::parse_pattern(p); + p.expect(Token::Equal); + let condition_expr = parse_if_condition(p); + let then_expr = parse_then_branch(p); + + let else_expr = match &p.token { + Token::Else => { + p.end_region(); + p.leave_breadcrumb(Grammar::ElseBranch); + p.next(); // consume `else` + p.begin_region(); + let else_expr = match &p.token { + Token::If => parse_if_or_if_let_expression(p), + _ => parse_else_branch(p), + }; + p.eat_breadcrumb(); + p.end_region(); + else_expr + } + _ => { + p.end_region(); + // No else: use () as the else expression + let loc = p.mk_loc_to_prev_end(&p.start_pos.clone()); + ast_helper::make_unit(p, loc) + } + }; + + let loc = p.mk_loc_to_prev_end(&start_pos); + + // Build the match expression: match condition { | pattern => then | _ => else } + let if_let_expr = Expression { + pexp_desc: ExpressionDesc::Pexp_match( + Box::new(condition_expr), + vec![ + Case { + pc_bar: None, + pc_lhs: pattern, + pc_guard: None, + pc_rhs: then_expr, + }, + Case { + pc_bar: None, + pc_lhs: Pattern { + ppat_desc: PatternDesc::Ppat_any, + ppat_loc: loc, + ppat_attributes: vec![], + }, + pc_guard: None, + pc_rhs: else_expr, + }, + ], + ), + pexp_loc: loc, + pexp_attributes: vec![ + if_let_attr(), + suppress_fragile_match_warning_attr(p), + ], + }; + + // Emit the experimental if-let error message using ResPrinter + { + use super::doc::Doc; + use super::printer2; + use super::comment_table::CommentTable; + + // Create a copy without attributes for printing + let switch_expr = Expression { + pexp_attributes: vec![], + ..if_let_expr.clone() + }; + + let state = printer2::PrinterState::init(); + let mut cmt_tbl = CommentTable::new(); + let msg = Doc::concat(vec![ + Doc::text("If-let is currently highly experimental."), + Doc::line(), + Doc::text("Use a regular `switch` with pattern matching instead:"), + Doc::concat(vec![ + Doc::hard_line(), + Doc::hard_line(), + printer2::print_expression(&state, &switch_expr, &mut cmt_tbl, p.arena()), + ]), + ]).to_string(80); + + p.err_at( + p.loc_start(if_let_expr.pexp_loc), + p.loc_end(if_let_expr.pexp_loc), + DiagnosticCategory::message(&msg), + ); + } + + if_let_expr +} + +/// Create the @warning "-4" attribute to suppress fragile match warnings. +fn suppress_fragile_match_warning_attr(p: &mut Parser<'_>) -> Attribute { + use super::ast::*; + let loc = p.mk_loc_to_prev_end(&p.start_pos.clone()); + ( + mknoloc("warning".to_string()), + Payload::PStr(vec![ + StructureItem { + pstr_desc: StructureItemDesc::Pstr_eval( + Expression { + pexp_desc: ExpressionDesc::Pexp_constant(Constant::String("-4".to_string(), None)), + pexp_loc: loc, + pexp_attributes: vec![], + }, + vec![], + ), + pstr_loc: loc, + }, + ]), + ) +} + +/// Legacy entry point for if expressions - wraps parse_if_or_if_let_expression. +fn parse_if_expr(p: &mut Parser<'_>) -> Expression { + parse_if_or_if_let_expression(p) +} + /// Parse a block body for switch case RHS (no braces). /// Similar to parse_block_body but respects ExprContext and stops at | or }. fn parse_switch_case_body(p: &mut Parser<'_>) -> Option { @@ -3634,12 +4803,12 @@ fn parse_switch_case_body(p: &mut Parser<'_>) -> Option { let rest = parse_switch_case_body(p); let body = rest.unwrap_or_else(|| { // OCaml uses mk_loc p.start_pos p.end_pos for synthesized unit - let loc = p.mk_loc(&p.start_pos, &p.end_pos); - ast_helper::make_unit(loc) + let loc = p.mk_loc_current(); + ast_helper::make_unit(p, loc) }); // OCaml uses p.prev_end_pos for Pexp_open location - let loc = p.mk_loc(&expr_start, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&expr_start); Expression { pexp_desc: ExpressionDesc::Pexp_open(OverrideFlag::Fresh, lid, Box::new(body)), pexp_loc: loc, @@ -3663,7 +4832,7 @@ fn parse_switch_case_body(p: &mut Parser<'_>) -> Option { // Check for continuation if let Some(rest) = parse_switch_case_body(p) { - let new_loc = p.mk_loc(&expr.pexp_loc.loc_start, &rest.pexp_loc.loc_end); + let new_loc = p.mk_loc_spanning(expr.pexp_loc, rest.pexp_loc); Expression { pexp_desc: ExpressionDesc::Pexp_sequence(Box::new(expr), Box::new(rest)), pexp_loc: new_loc, @@ -3685,12 +4854,12 @@ fn parse_switch_case_body(p: &mut Parser<'_>) -> Option { let rest = parse_switch_case_body(p); let body = rest.unwrap_or_else(|| { // OCaml uses mk_loc p.start_pos p.end_pos for synthesized unit - let loc = p.mk_loc(&p.start_pos, &p.end_pos); - ast_helper::make_unit(loc) + let loc = p.mk_loc_current(); + ast_helper::make_unit(p, loc) }); // OCaml uses p.prev_end_pos for Pexp_letmodule location - let loc = p.mk_loc(&expr_start, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&expr_start); Expression { pexp_desc: ExpressionDesc::Pexp_letmodule( module_name, @@ -3716,12 +4885,12 @@ fn parse_switch_case_body(p: &mut Parser<'_>) -> Option { let rest = parse_switch_case_body(p); let body = rest.unwrap_or_else(|| { // OCaml uses mk_loc p.start_pos p.end_pos for synthesized unit - let loc = p.mk_loc(&p.start_pos, &p.end_pos); - ast_helper::make_unit(loc) + let loc = p.mk_loc_current(); + ast_helper::make_unit(p, loc) }); // OCaml uses p.prev_end_pos for Pexp_letexception location - let loc = p.mk_loc(&expr_start, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&expr_start); Expression { pexp_desc: ExpressionDesc::Pexp_letexception(ext, Box::new(body)), pexp_loc: loc, @@ -3737,7 +4906,7 @@ fn parse_switch_case_body(p: &mut Parser<'_>) -> Option { // Check for continuation if let Some(rest) = parse_switch_case_body(p) { - let new_loc = p.mk_loc(&expr.pexp_loc.loc_start, &rest.pexp_loc.loc_end); + let new_loc = p.mk_loc_spanning(expr.pexp_loc, rest.pexp_loc); Expression { pexp_desc: ExpressionDesc::Pexp_sequence(Box::new(expr), Box::new(rest)), pexp_loc: new_loc, @@ -3782,7 +4951,7 @@ fn parse_let_in_switch_case(p: &mut Parser<'_>) -> Expression { p.next(); let typ = super::typ::parse_typ_expr(p); // Create a constraint pattern - let loc = p.mk_loc(&first_pat.ppat_loc.loc_start, &typ.ptyp_loc.loc_end); + let loc = p.mk_loc_spanning(first_pat.ppat_loc, typ.ptyp_loc); Pattern { ppat_desc: PatternDesc::Ppat_constraint(Box::new(first_pat), typ), ppat_loc: loc, @@ -3794,7 +4963,7 @@ fn parse_let_in_switch_case(p: &mut Parser<'_>) -> Expression { p.expect(Token::Equal); let first_value = parse_expr(p); - let first_loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let first_loc = p.mk_loc_to_prev_end(&start_pos); // Add let.unwrap attribute if this is let? let first_attrs = if unwrap { @@ -3825,7 +4994,7 @@ fn parse_let_in_switch_case(p: &mut Parser<'_>) -> Expression { let pat = if p.token == Token::Colon { p.next(); let typ = super::typ::parse_typ_expr(p); - let loc = p.mk_loc(&pat.ppat_loc.loc_start, &typ.ptyp_loc.loc_end); + let loc = p.mk_loc_spanning(pat.ppat_loc, typ.ptyp_loc); Pattern { ppat_desc: PatternDesc::Ppat_constraint(Box::new(pat), typ), ppat_loc: loc, @@ -3837,7 +5006,7 @@ fn parse_let_in_switch_case(p: &mut Parser<'_>) -> Expression { p.expect(Token::Equal); let value = parse_expr(p); - let binding_loc = p.mk_loc(&binding_start, &p.prev_end_pos); + let binding_loc = p.mk_loc_to_prev_end(&binding_start); bindings.push(ValueBinding { pvb_pat: pat, pvb_expr: value, @@ -3853,12 +5022,12 @@ fn parse_let_in_switch_case(p: &mut Parser<'_>) -> Expression { let rest = parse_switch_case_body(p); let body = rest.unwrap_or_else(|| { // OCaml uses mk_loc p.start_pos p.end_pos for synthesized unit - let loc = p.mk_loc(&p.start_pos, &p.end_pos); - ast_helper::make_unit(loc) + let loc = p.mk_loc_current(); + ast_helper::make_unit(p, loc) }); // OCaml: Pexp_let location always uses p.prev_end_pos after parsing body - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); Expression { pexp_desc: ExpressionDesc::Pexp_let(rec_flag, bindings, Box::new(body)), @@ -3905,7 +5074,8 @@ fn parse_first_class_module_expr_inner(p: &mut Parser<'_>, start_pos: Position) // Parse any attributes between : and the module identifier let attrs = parse_attributes(p); let mut pkg_type = super::typ::parse_package_type(p); - pkg_type.ptyp_loc.loc_start = colon_pos; + // Update location to start at colon position + pkg_type.ptyp_loc = p.mk_loc(&colon_pos, &p.loc_end(pkg_type.ptyp_loc)); // Attach any attributes parsed if !attrs.is_empty() { pkg_type.ptyp_attributes.extend(attrs); @@ -3916,7 +5086,7 @@ fn parse_first_class_module_expr_inner(p: &mut Parser<'_>, start_pos: Position) }; p.expect(Token::Rparen); - let full_loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let full_loc = p.mk_loc_to_prev_end(&start_pos); if let Some(pkg_type) = package_type { // OCaml: when constrained, pack_expr location spans only start to end of module expr (not including type) @@ -3945,12 +5115,31 @@ fn parse_first_class_module_expr_inner(p: &mut Parser<'_>, start_pos: Position) /// Parses one or more expressions separated by newlines/semicolons, /// stopping at `|` (next case) or `}` (end of switch). fn parse_switch_case_block(p: &mut Parser<'_>) -> Expression { - // Use the new recursive parser that properly nests let/module/open/exception - parse_switch_case_body(p).unwrap_or_else(|| { - // OCaml uses mk_loc p.start_pos p.end_pos for synthesized unit - let loc = p.mk_loc(&p.start_pos, &p.end_pos); - ast_helper::make_unit(loc) - }) + // OCaml uses parse_expr_block which pushes ExprBlock breadcrumb. + // This is critical for error messages: ExprBlock + Bar → "Looks like there might be + // an expression missing here" (for empty switch case bodies like | Empty => | Next => ...) + p.leave_breadcrumb(Grammar::ExprBlock); + // Use the recursive parser that properly nests let/module/open/exception + let result = parse_switch_case_body(p).unwrap_or_else(|| { + // OCaml: parse_expr_block -> parse_expr_block_item -> parse_expr -> + // parse_atomic_expr encounters | or } and emits an error through the + // breadcrumb-aware diagnostic system before returning exprhole. + // Match OCaml's error position: prev_end_pos..end_pos (like parse_atomic_expr default) + // Push ExprOperand so breadcrumb-aware diagnostics see [.., ExprBlock, ExprOperand] + // which triggers "Looks like there might be an expression missing here" for Bar. + if p.token != Token::Rbrace && p.token != Token::Eof { + p.leave_breadcrumb(Grammar::ExprOperand); + p.err_at( + p.prev_end_pos.clone(), + p.end_pos.clone(), + DiagnosticCategory::unexpected(p.token.clone(), p.breadcrumbs().to_vec()), + ); + p.eat_breadcrumb(); + } + recover::default_expr() + }); + p.eat_breadcrumb(); + result } /// Parse a switch expression. @@ -3963,10 +5152,21 @@ fn parse_switch_expr(p: &mut Parser<'_>) -> Expression { let mut cases = vec![]; while p.token != Token::Rbrace && p.token != Token::Eof { + // OCaml uses begin_region/end_region around each case + // This allows errors from different cases to all be reported + p.begin_region(); + // OCaml: Parser.leave_breadcrumb p Grammar.PatternMatchCase + p.leave_breadcrumb(Grammar::PatternMatchCase); + if p.token == Token::Bar { let bar_pos = Some(p.start_pos.clone()); p.next(); - let lhs = super::pattern::parse_constrained_pattern(p); + // OCaml: Parser.leave_breadcrumb p Grammar.Pattern + // OCaml uses parse_pattern (not parse_constrained_pattern) for switch case patterns. + // Constraints are only handled inside parenthesized/delimited patterns. + p.leave_breadcrumb(Grammar::Pattern); + let lhs = super::pattern::parse_pattern(p); + p.eat_breadcrumb(); let guard = if p.token == Token::When || (p.token == Token::If) { p.next(); Some(parse_expr_with_context(p, ExprContext::When)) @@ -3982,13 +5182,27 @@ fn parse_switch_expr(p: &mut Parser<'_>) -> Expression { pc_guard: guard, pc_rhs: rhs, }); + p.end_region(); + p.eat_breadcrumb(); } else { + p.end_region(); + p.eat_breadcrumb(); break; } } + // OCaml: emit error if switch has no cases + // OCaml uses end_pos (end of current token) as the error end, not start_pos + if cases.is_empty() { + p.err_at( + p.prev_end_pos.clone(), + p.end_pos.clone(), + DiagnosticCategory::Message("Pattern matching needs at least one case".to_string()), + ); + } + p.expect(Token::Rbrace); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); Expression { pexp_desc: ExpressionDesc::Pexp_match(Box::new(scrutinee), cases), @@ -4008,7 +5222,7 @@ fn parse_while_expr(p: &mut Parser<'_>) -> Expression { let body = parse_expr_block(p); p.expect(Token::Rbrace); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); Expression { pexp_desc: ExpressionDesc::Pexp_while(Box::new(condition), Box::new(body)), @@ -4036,8 +5250,8 @@ fn parse_for_expr(p: &mut Parser<'_>) -> Expression { if p.token == Token::Rparen { // for () - unit pattern, then check for alias p.next(); - let loc = p.mk_loc(&lparen_pos, &p.prev_end_pos); - let unit_pat = super::pattern::make_unit_construct_pattern(loc); + let loc = p.mk_loc_to_prev_end(&lparen_pos); + let unit_pat = super::pattern::make_unit_construct_pattern(p, loc); let pat = super::pattern::parse_alias_pattern(p, unit_pat, vec![]); (pat, false) } else { @@ -4099,7 +5313,7 @@ fn parse_for_expr(p: &mut Parser<'_>) -> Expression { p.eat_breadcrumb(); p.end_region(); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); Expression { pexp_desc: ExpressionDesc::Pexp_for( @@ -4120,20 +5334,25 @@ fn parse_try_expr(p: &mut Parser<'_>) -> Expression { p.expect(Token::Try); let body = parse_expr_with_context(p, ExprContext::When); - // "catch" is not a keyword, so we check for Lident("catch") - if !matches!(&p.token, Token::Lident(s) if s == "catch") { - p.err(DiagnosticCategory::Message("Expected 'catch'".to_string())); - } else { - p.next(); - } + // "catch" is not a keyword, but OCaml uses `Parser.expect Res_token.catch p` + // where `Res_token.catch = Lident "catch"`. This produces "Did you forget a `catch` here?" + p.expect(Token::Lident("catch".to_string())); p.expect(Token::Lbrace); let mut cases = vec![]; while p.token != Token::Rbrace && p.token != Token::Eof { + // OCaml uses begin_region/end_region around each case + p.begin_region(); + // OCaml: Parser.leave_breadcrumb p Grammar.PatternMatchCase + p.leave_breadcrumb(Grammar::PatternMatchCase); + if p.token == Token::Bar { let bar_pos = Some(p.start_pos.clone()); p.next(); + // OCaml: Parser.leave_breadcrumb p Grammar.Pattern + p.leave_breadcrumb(Grammar::Pattern); let lhs = super::pattern::parse_constrained_pattern(p); + p.eat_breadcrumb(); let guard = if p.token == Token::When { p.next(); Some(parse_expr_with_context(p, ExprContext::When)) @@ -4150,13 +5369,17 @@ fn parse_try_expr(p: &mut Parser<'_>) -> Expression { pc_guard: guard, pc_rhs: rhs, }); + p.end_region(); + p.eat_breadcrumb(); } else { + p.end_region(); + p.eat_breadcrumb(); break; } } p.expect(Token::Rbrace); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); Expression { pexp_desc: ExpressionDesc::Pexp_try(Box::new(body), cases), @@ -4169,30 +5392,103 @@ fn parse_try_expr(p: &mut Parser<'_>) -> Expression { // JSX Parsing // ============================================================================ +/// Maximum JSX nesting depth to prevent stack overflow. +/// This is a safety limit for malformed input with deeply nested JSX-like syntax. +const MAX_JSX_DEPTH: usize = 20; + +/// Convert a Longident to a string. +fn longident_to_string(lid: &super::longident::Longident, arena: &ParseArena) -> String { + match lid { + super::longident::Longident::Lident(idx) => arena.get_string(*idx).to_string(), + super::longident::Longident::Ldot(prefix, idx) => { + format!("{}.{}", longident_to_string(prefix, arena), arena.get_string(*idx)) + } + super::longident::Longident::Lapply(a, b) => { + format!("{}({})", longident_to_string(a, arena), longident_to_string(b, arena)) + } + } +} + +/// Convert a JSX tag name to a string for error messages. +fn jsx_tag_name_to_string_for_error(tag_name: &JsxTagName, p: &Parser<'_>) -> String { + match tag_name { + JsxTagName::Lower(name) => name.clone(), + JsxTagName::Upper(lid_idx) => { + let lid = p.arena().get_longident(*lid_idx); + longident_to_string(lid, p.arena()) + } + JsxTagName::QualifiedLower { path, name } => { + let lid = p.arena().get_longident(*path); + format!("{}.{}", longident_to_string(lid, p.arena()), name) + } + JsxTagName::Invalid(name) => name.clone(), + } +} + +/// Check if two JSX tag names match. +fn jsx_tag_names_match(opening: &JsxTagName, closing: &JsxTagName, p: &Parser<'_>) -> bool { + jsx_tag_name_to_string_for_error(opening, p) == jsx_tag_name_to_string_for_error(closing, p) +} + /// Parse a JSX element. fn parse_jsx(p: &mut Parser<'_>) -> Expression { + p.leave_breadcrumb(Grammar::Jsx); let start_pos = p.start_pos.clone(); + + // Check for excessive nesting depth to prevent stack overflow + if p.jsx_depth >= MAX_JSX_DEPTH { + p.err(super::diagnostics::DiagnosticCategory::Message( + "Maximum JSX nesting depth exceeded".to_string(), + )); + // Return a placeholder expression instead of continuing + p.next(); // consume < + return recover::default_expr(); + } + + p.jsx_depth += 1; p.expect(Token::LessThan); // Check for fragment <> if p.token == Token::GreaterThan { - return parse_jsx_fragment(p, start_pos); + let result = parse_jsx_fragment(p, start_pos); + p.eat_breadcrumb(); + p.jsx_depth -= 1; + return result; } // Parse tag name - the location starts at the identifier, not the '<' let tag_name_start = p.start_pos.clone(); let tag_name = parse_jsx_tag_name(p); - let tag_name_loc = p.mk_loc(&tag_name_start, &p.prev_end_pos); + let tag_name_loc = p.mk_loc_to_prev_end(&tag_name_start); // Parse props let props = parse_jsx_props(p); - // Self-closing or container? + // Self-closing, container, or error recovery? + // OCaml has three cases: Forwardslash, GreaterThan, or token (unexpected) if p.token == Token::Forwardslash { p.next(); p.expect(Token::GreaterThan); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); + + p.eat_breadcrumb(); + p.jsx_depth -= 1; + Expression { + pexp_desc: ExpressionDesc::Pexp_jsx_element(JsxElement::Unary(JsxUnaryElement { + tag_name: with_loc(tag_name, tag_name_loc), + props, + })), + pexp_loc: loc, + pexp_attributes: vec![], + } + } else if p.token != Token::GreaterThan { + // OCaml: | token -> Parser.err p (Diagnostics.unexpected token p.breadcrumbs); + // Ast_helper.Exp.jsx_unary_element ~loc name jsx_props + p.err(DiagnosticCategory::unexpected(p.token.clone(), p.breadcrumbs().to_vec())); + let loc = p.mk_loc_to_prev_end(&start_pos); + p.eat_breadcrumb(); + p.jsx_depth -= 1; Expression { pexp_desc: ExpressionDesc::Pexp_jsx_element(JsxElement::Unary(JsxUnaryElement { tag_name: with_loc(tag_name, tag_name_loc), @@ -4209,13 +5505,95 @@ fn parse_jsx(p: &mut Parser<'_>) -> Expression { let children = parse_jsx_children(p); // Parse closing tag - p.expect(Token::LessThan); - p.expect(Token::Forwardslash); - let _closing_tag_name = parse_jsx_tag_name(p); - p.expect(Token::GreaterThan); + // OCaml has three cases: + // 1. LessThan when peekSlash -> proper closing tag + // 2. token when is_structure_item_start -> None (missing closing tag) + // 3. _ -> "Did you forget a `" at the opening tag position + let opening_name = jsx_tag_name_to_string_for_error(&tag_name, p); + p.err_at( + start_pos.clone(), + opening_end.clone(), + DiagnosticCategory::Message( + format!("Missing ", opening_name), + ), + ); + false + } else { + // Case 3: unexpected token + p.err(DiagnosticCategory::Message( + "Did you forget a `") + if !jsx_tag_names_match(&tag_name, &closing_tag_name, p) { + let opening_name = jsx_tag_name_to_string_for_error(&tag_name, p); + // OCaml checks: if structure_item_start -> "Missing " + // else -> "Closing jsx name should be the same..." + if super::grammar::is_structure_item_start(&p.token) { + p.err_at( + start_pos.clone(), + p.prev_end_pos.clone(), + DiagnosticCategory::Message( + format!("Missing ", opening_name), + ), + ); + // OCaml: expect GreaterThan in this branch + p.expect(Token::GreaterThan); + } else { + p.err_at( + start_pos.clone(), + p.prev_end_pos.clone(), + DiagnosticCategory::Message( + format!("Missing ", opening_name), + ), + ); + } + } + p.expect(Token::GreaterThan); + closing_tag_end = p.prev_end_pos.clone(); + } else { + // No closing tag - create a synthetic one + closing_tag_name = JsxTagName::Invalid("error".to_string()); + closing_tag_name_loc = p.mk_loc_to_prev_end(&start_pos); + closing_tag_end = p.prev_end_pos.clone(); + } + + let closing_tag = if has_closing_tag { + Some(JsxClosingTag { + start: p.prev_end_pos.clone(), // approximate + name: with_loc(closing_tag_name, closing_tag_name_loc), + end: closing_tag_end, + }) + } else { + // OCaml: closing_tag_start is None when no proper closing tag was found + None + }; + let loc = p.mk_loc_to_prev_end(&start_pos); + + p.eat_breadcrumb(); + p.jsx_depth -= 1; Expression { pexp_desc: ExpressionDesc::Pexp_jsx_element(JsxElement::Container( JsxContainerElement { @@ -4223,7 +5601,7 @@ fn parse_jsx(p: &mut Parser<'_>) -> Expression { opening_end, props, children, - closing_tag: None, // Simplified + closing_tag, }, )), pexp_loc: loc, @@ -4244,7 +5622,7 @@ fn parse_jsx_fragment(p: &mut Parser<'_>, start_pos: Position) -> Expression { let closing = p.start_pos.clone(); p.expect(Token::GreaterThan); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); Expression { pexp_desc: ExpressionDesc::Pexp_jsx_element(JsxElement::Fragment(JsxFragment { @@ -4268,6 +5646,11 @@ fn read_hyphen_chain(p: &mut Parser<'_>, initial: String) -> String { matches!(&state.token, Token::Lident(_) | Token::Uident(_)) }); if !has_ident_after { + // OCaml: advances past '-' THEN emits error at the next token position + p.next(); // consume '-' + p.err(DiagnosticCategory::Message( + "JSX identifier cannot end with a hyphen".to_string(), + )); break; } p.next(); // consume - @@ -4309,14 +5692,24 @@ fn parse_jsx_tag_name(p: &mut Parser<'_>) -> JsxTagName { p.next(); let full_name = read_hyphen_chain(p, lname); // This is a qualified lowercase tag: Foo.custom-tag - let path = super::core::build_longident(&parts); - return JsxTagName::QualifiedLower { path, name: full_name }; + let path = super::core::build_longident(p.arena_mut(), &parts); + let path_idx = p.push_longident(path); + return JsxTagName::QualifiedLower { path: path_idx, name: full_name }; + } + _ => { + // OCaml: "expected identifier after '.' in JSX tag name" + // OCaml returns Error "Foo." which becomes JsxTagInvalid "Foo." + p.err(DiagnosticCategory::Message( + "expected identifier after '.' in JSX tag name".to_string(), + )); + let name_with_dot = parts.join(".") + "."; + return JsxTagName::Invalid(name_with_dot); } - _ => break, } } - let lid = super::core::build_longident(&parts); - JsxTagName::Upper(lid) + let lid = super::core::build_longident(p.arena_mut(), &parts); + let lid_idx = p.push_longident(lid); + JsxTagName::Upper(lid_idx) } _ => { p.err(DiagnosticCategory::Message( @@ -4328,7 +5721,9 @@ fn parse_jsx_tag_name(p: &mut Parser<'_>) -> JsxTagName { } /// Parse JSX props. +/// Matches OCaml: parse_region ~grammar:Grammar.JsxAttribute ~f:parse_jsx_prop p fn parse_jsx_props(p: &mut Parser<'_>) -> Vec { + p.leave_breadcrumb(Grammar::JsxAttribute); let mut props = vec![]; loop { @@ -4344,7 +5739,7 @@ fn parse_jsx_props(p: &mut Parser<'_>) -> Vec { p.expect(Token::DotDotDot); let expr = parse_expr(p); p.expect(Token::Rbrace); - let loc = p.mk_loc(&spread_start, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&spread_start); props.push(JsxProp::Spreading { loc, expr }); } else { break; @@ -4352,7 +5747,7 @@ fn parse_jsx_props(p: &mut Parser<'_>) -> Vec { } Token::Lident(name) => { let name = name.clone(); - let name_loc = p.mk_loc(&p.start_pos, &p.end_pos); + let name_loc = p.mk_loc_current(); p.next(); if p.token == Token::Equal { @@ -4386,7 +5781,7 @@ fn parse_jsx_props(p: &mut Parser<'_>) -> Vec { p.next(); if let Token::Lident(name) = &p.token { let name = name.clone(); - let name_loc = p.mk_loc(&p.start_pos, &p.end_pos); + let name_loc = p.mk_loc_current(); p.next(); props.push(JsxProp::Punning { optional: true, @@ -4397,7 +5792,7 @@ fn parse_jsx_props(p: &mut Parser<'_>) -> Vec { token if token.is_keyword() => { // JSX props may use keyword-like identifiers (rare but valid). let name = token.to_string(); - let name_loc = p.mk_loc(&p.start_pos, &p.end_pos); + let name_loc = p.mk_loc_current(); p.next(); if p.token == Token::Equal { @@ -4421,16 +5816,27 @@ fn parse_jsx_props(p: &mut Parser<'_>) -> Vec { }); } } - _ => break, + _ => { + // OCaml parse_region recovery: if token is EOF or should_abort_list_parse, stop. + // Otherwise, emit error, skip token, and continue. + if p.token == Token::Eof || recover::should_abort_list_parse(p) { + break; + } + p.err(DiagnosticCategory::unexpected(p.token.clone(), p.breadcrumbs().to_vec())); + p.next(); + } } } + p.eat_breadcrumb(); props } /// Parse JSX children. fn parse_jsx_children(p: &mut Parser<'_>) -> Vec { let mut children = vec![]; + let mut skip_count = 0; + const MAX_SKIP_COUNT: usize = 100; loop { // Check for closing tag @@ -4448,6 +5854,15 @@ fn parse_jsx_children(p: &mut Parser<'_>) -> Vec { let atomic = parse_atomic_expr(p); let expr = parse_primary_expr(p, atomic, true); children.push(expr); + } else if p.token == Token::DotDotDot { + // OCaml: "Spreading JSX children is no longer supported." + p.err(DiagnosticCategory::Message( + "Spreading JSX children is no longer supported.".to_string(), + )); + p.next(); // consume ... + // Parse the expression after ... to not lose it + let expr = parse_atomic_expr(p); + children.push(expr); } else if p.token == Token::Eof { break; } else if matches!(p.token, Token::Lident(_) | Token::Uident(_)) { @@ -4462,13 +5877,15 @@ fn parse_jsx_children(p: &mut Parser<'_>) -> Vec { match &p.token { Token::Lident(name) => { let name = name.clone(); - let name_loc = p.mk_loc(&p.start_pos, &p.end_pos); + let name_loc = p.mk_loc_current(); + let lid_idx = p.push_lident(&name); p.next(); - let loc = p.mk_loc(&expr.pexp_loc.loc_start, &p.prev_end_pos); + let loc_start_pos = p.loc_start(expr.pexp_loc); + let loc = p.mk_loc_to_prev_end(&loc_start_pos); expr = Expression { pexp_desc: ExpressionDesc::Pexp_field( Box::new(expr), - with_loc(Longident::Lident(name), name_loc), + with_loc(lid_idx, name_loc), ), pexp_loc: loc, pexp_attributes: vec![], @@ -4476,7 +5893,7 @@ fn parse_jsx_children(p: &mut Parser<'_>) -> Vec { } Token::Uident(_) => { let field_path = parse_value_path_after_dot(p); - let loc = p.mk_loc(&expr.pexp_loc.loc_start, &field_path.loc.loc_end); + let loc = p.mk_loc(&p.loc_start(expr.pexp_loc), &p.loc_end(field_path.loc)); expr = Expression { pexp_desc: ExpressionDesc::Pexp_field(Box::new(expr), field_path), pexp_loc: loc, @@ -4493,7 +5910,7 @@ fn parse_jsx_children(p: &mut Parser<'_>) -> Vec { let s = s.clone(); let tag = get_string_tag(p); p.next(); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); children.push(ast_helper::make_constant( Constant::String(s, tag), loc, @@ -4528,7 +5945,30 @@ fn parse_jsx_children(p: &mut Parser<'_>) -> Vec { let expr = parse_atomic_expr(p); children.push(expr); } else { - // Skip whitespace and other tokens + // Break on tokens that clearly indicate we're outside JSX context + // These are structural tokens that should never appear inside JSX children + if matches!( + p.token, + Token::Typ + | Token::Let { .. } + | Token::Module + | Token::External + | Token::Open + | Token::Include + | Token::Exception + | Token::Rbrace // End of enclosing block + | Token::Rparen // End of enclosing parens + | Token::Rbracket // End of enclosing array + | Token::Equal // Assignment, likely type definition + | Token::Semicolon // Statement separator + ) { + break; + } + // Skip whitespace and other tokens (with limit to prevent infinite loop) + skip_count += 1; + if skip_count > MAX_SKIP_COUNT { + break; + } p.next(); } } @@ -4542,8 +5982,8 @@ fn parse_jsx_braced_expr(p: &mut Parser<'_>, lbrace_start: Position) -> Expressi match parse_block_body(p) { Some(expr) => expr, None => { - let loc = p.mk_loc(&lbrace_start, &p.prev_end_pos); - ast_helper::make_unit(loc) + let loc = p.mk_loc_to_prev_end(&lbrace_start); + ast_helper::make_unit(p, loc) } } } @@ -4557,14 +5997,14 @@ fn parse_jsx_braced_expr(p: &mut Parser<'_>, lbrace_start: Position) -> Expressi /// If prefix is Some(ident), it's a tagged template literal like `sql`...``. fn parse_template_literal_with_prefix( p: &mut Parser<'_>, - prefix: Option<(Longident, Location)>, + prefix: Option<(LidentIdx, Location)>, ) -> Expression { let start_pos = p.start_pos.clone(); let template_literal_attr = (mknoloc("res.template".to_string()), Payload::PStr(vec![])); // Determine the string delimiter based on prefix (json -> "json", otherwise "js") let part_prefix = match &prefix { - Some((Longident::Lident(name), _)) if name == "json" => Some("json".to_string()), + Some((lid_idx, _)) if p.arena().is_lident(*lid_idx, "json") => Some("json".to_string()), _ => Some("js".to_string()), }; @@ -4586,8 +6026,9 @@ fn parse_template_literal_with_prefix( Token::TemplatePart { text, pos } => { // Part before an interpolation ${ let text = text.clone(); + let pos = pos.clone(); // OCaml uses the embedded last_pos from the token, not p.end_pos - let text_loc = p.mk_loc(&text_start_pos, pos); + let text_loc = p.mk_loc_from_positions(&text_start_pos, &pos); let mut str_expr = ast_helper::make_constant( Constant::String(text, part_prefix.clone()), text_loc, @@ -4606,8 +6047,9 @@ fn parse_template_literal_with_prefix( Token::TemplateTail { text, pos } => { // Final part or simple template string let text = text.clone(); + let pos = pos.clone(); // OCaml uses the embedded last_pos from the token, not p.end_pos - let text_loc = p.mk_loc(&text_start_pos, pos); + let text_loc = p.mk_loc_from_positions(&text_start_pos, &pos); let mut str_expr = ast_helper::make_constant( Constant::String(text, part_prefix.clone()), text_loc, @@ -4619,7 +6061,7 @@ fn parse_template_literal_with_prefix( } Token::Backtick => { // Empty template string - let text_loc = p.mk_loc(&text_start_pos, &p.end_pos); + let text_loc = p.mk_loc_to_end(&text_start_pos); let mut str_expr = ast_helper::make_constant( Constant::String("".to_string(), part_prefix.clone()), text_loc, @@ -4637,21 +6079,18 @@ fn parse_template_literal_with_prefix( } _ => { // This shouldn't happen in well-formed template literals - p.err(DiagnosticCategory::Message(format!( - "Unexpected token in template literal: {:?}", - p.token - ))); + p.err_unexpected(); p.next(); break; } } } - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); // Check if this is a tagged template (non-json prefix) let is_tagged = match &prefix { - Some((Longident::Lident(name), _)) if name == "json" => false, + Some((lid_idx, _)) if p.arena().is_lident(*lid_idx, "json") => false, Some(_) => true, None => false, }; @@ -4668,12 +6107,12 @@ fn parse_template_literal_with_prefix( let strings_array = Expression { pexp_desc: ExpressionDesc::Pexp_array(strings), - pexp_loc: Location::none(), + pexp_loc: LocIdx::none(), pexp_attributes: vec![], }; let values_array = Expression { pexp_desc: ExpressionDesc::Pexp_array(values), - pexp_loc: Location::none(), + pexp_loc: LocIdx::none(), pexp_attributes: vec![], }; @@ -4713,10 +6152,10 @@ fn parse_template_literal_with_prefix( let (mut str_expr, _) = parts.into_iter().next().unwrap(); if prefix.is_none() { // Non-prefixed: OCaml overrides location in parse_atomic_expr to include backticks - str_expr.pexp_loc = p.mk_loc(&start_pos, &p.prev_end_pos); + str_expr.pexp_loc = p.mk_loc_to_prev_end(&start_pos); } else { // Prefixed (like json`...`): keep string part's location but adjust start to backtick - str_expr.pexp_loc.loc_start = start_pos; + str_expr.pexp_loc = p.mk_loc(&start_pos, &p.loc_end(str_expr.pexp_loc)); } return str_expr; } @@ -4731,14 +6170,15 @@ fn parse_template_literal_with_prefix( } // Fold with ++ operator + let lid_idx = p.push_lident_static("++"); let hidden_operator = Expression { - pexp_desc: ExpressionDesc::Pexp_ident(mknoloc(Longident::Lident("++".to_string()))), - pexp_loc: Location::none(), + pexp_desc: ExpressionDesc::Pexp_ident(mknoloc(lid_idx)), + pexp_loc: LocIdx::none(), pexp_attributes: vec![], }; let concat = |e1: Expression, e2: Expression| -> Expression { - let concat_loc = p.mk_loc(&e1.pexp_loc.loc_start, &e2.pexp_loc.loc_end); + let concat_loc = p.mk_loc_spanning(e1.pexp_loc, e2.pexp_loc); Expression { pexp_desc: ExpressionDesc::Pexp_apply { funct: Box::new(hidden_operator.clone()), @@ -4762,7 +6202,7 @@ fn parse_template_literal_with_prefix( /// Parse a tagged template literal where the tag is an arbitrary expression (not just an identifier). fn parse_tagged_template_literal_with_tag_expr(p: &mut Parser<'_>, tag_expr: Expression) -> Expression { - let tag_start = tag_expr.pexp_loc.loc_start.clone(); + let tag_start = p.loc_start(tag_expr.pexp_loc); let template_start = p.start_pos.clone(); let template_literal_attr = (mknoloc("res.template".to_string()), Payload::PStr(vec![])); @@ -4781,8 +6221,9 @@ fn parse_tagged_template_literal_with_tag_expr(p: &mut Parser<'_>, tag_expr: Exp match &p.token { Token::TemplatePart { text, pos } => { let text = text.clone(); + let pos = pos.clone(); // OCaml uses the embedded last_pos from the token, not p.end_pos - let text_loc = p.mk_loc(&text_start_pos, pos); + let text_loc = p.mk_loc_from_positions(&text_start_pos, &pos); let mut str_expr = ast_helper::make_constant(Constant::String(text, Some("js".to_string())), text_loc); str_expr.pexp_attributes.push(template_literal_attr.clone()); @@ -4796,8 +6237,9 @@ fn parse_tagged_template_literal_with_tag_expr(p: &mut Parser<'_>, tag_expr: Exp } Token::TemplateTail { text, pos } => { let text = text.clone(); + let pos = pos.clone(); // OCaml uses the embedded last_pos from the token, not p.end_pos - let text_loc = p.mk_loc(&text_start_pos, pos); + let text_loc = p.mk_loc_from_positions(&text_start_pos, &pos); let mut str_expr = ast_helper::make_constant(Constant::String(text, Some("js".to_string())), text_loc); str_expr.pexp_attributes.push(template_literal_attr.clone()); @@ -4807,7 +6249,7 @@ fn parse_tagged_template_literal_with_tag_expr(p: &mut Parser<'_>, tag_expr: Exp } Token::Backtick => { // Empty template string - let text_loc = p.mk_loc(&text_start_pos, &p.end_pos); + let text_loc = p.mk_loc_to_end(&text_start_pos); let mut str_expr = ast_helper::make_constant( Constant::String("".to_string(), Some("js".to_string())), text_loc, @@ -4824,10 +6266,7 @@ fn parse_tagged_template_literal_with_tag_expr(p: &mut Parser<'_>, tag_expr: Exp break; } _ => { - p.err(DiagnosticCategory::Message(format!( - "Unexpected token in template literal: {:?}", - p.token - ))); + p.err_unexpected(); p.next(); break; } @@ -4839,12 +6278,12 @@ fn parse_tagged_template_literal_with_tag_expr(p: &mut Parser<'_>, tag_expr: Exp let strings_array = Expression { pexp_desc: ExpressionDesc::Pexp_array(strings), - pexp_loc: Location::none(), + pexp_loc: LocIdx::none(), pexp_attributes: vec![], }; let values_array = Expression { pexp_desc: ExpressionDesc::Pexp_array(values), - pexp_loc: Location::none(), + pexp_loc: LocIdx::none(), pexp_attributes: vec![], }; @@ -4853,10 +6292,10 @@ fn parse_tagged_template_literal_with_tag_expr(p: &mut Parser<'_>, tag_expr: Exp Payload::PStr(vec![]), ); - let loc = p.mk_loc(&tag_start, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&tag_start); // If we failed to advance (EOF / malformed), make sure the location at least starts at the tag. - let loc = if loc.loc_end.cnum == 0 { + let loc = if p.loc_end(loc).cnum == 0 { p.mk_loc(&tag_start, &template_start) } else { loc diff --git a/compiler-rust/src/parser/formatter.rs b/compiler-rust/src/parser/formatter.rs index d79b801220d..89f62754141 100644 --- a/compiler-rust/src/parser/formatter.rs +++ b/compiler-rust/src/parser/formatter.rs @@ -1,7 +1,8 @@ //! OCaml-compatible Format module implementation //! //! This module provides a pretty-printing formatter that matches OCaml's Format module -//! semantics. It uses a box-based system with deferred line-break decisions. +//! semantics exactly. It uses a queue-based scan algorithm that defers line-break decisions +//! until enough content has been seen, matching OCaml's streaming approach. //! //! # Box Types //! @@ -9,203 +10,524 @@ //! - **V (vertical)**: Always breaks at every break hint //! - **HV (horizontal-or-vertical)**: All on one line OR all broken (exclusive choice) //! - **HOV (horizontal-or-vertical packing)**: Pack as much as fits, break when necessary +//! - **Box**: Like HOV but with indentation-aware break logic //! -//! # Example +//! # Algorithm //! -//! ```ignore -//! let mut f = Formatter::new(output); -//! f.open_hovbox(2); // @[ -//! f.string("let "); -//! f.string("x"); -//! f.space(); // @; -//! f.string("="); -//! f.space(); // @; -//! f.string("42"); -//! f.close_box(); // @] -//! f.flush(); -//! ``` +//! Tokens are enqueued with initially unknown sizes. A scan stack tracks unresolved +//! breaks and box-opens. When the next break arrives, the previous break's size is +//! resolved. `advance_left` processes the queue front whenever sizes are known or +//! the pending content exceeds available space (assigning pp_infinity to force breaks). +use std::collections::VecDeque; use std::io::Write; /// Default margin (line width) - same as OCaml's default -pub const DEFAULT_MARGIN: usize = 80; +pub const DEFAULT_MARGIN: usize = 78; + +/// Large value for default token size (matching OCaml's pp_infinity) +const PP_INFINITY: i32 = 1000000010; /// Box types matching OCaml's Format module #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum BoxKind { - /// Horizontal - never break (open_hbox) + /// Horizontal - never break (Pp_hbox) H, - /// Vertical - always break at hints (open_vbox) + /// Vertical - always break at hints (Pp_vbox) V, - /// Horizontal-or-Vertical exclusive (open_hvbox) - /// Either all on one line OR all broken + /// Horizontal-or-Vertical exclusive (Pp_hvbox) HV, - /// Horizontal-or-Vertical packing (open_hovbox / open_box) - /// Pack as much as fits, break when necessary + /// Horizontal-or-Vertical packing (Pp_hovbox) HOV, + /// Structural box (Pp_box) + Box, + /// Box that fits on one line (Pp_fits) - computed at format time + Fits, } -/// Tokens in the output stream +/// Tokens in the pretty-printer queue (matching OCaml's pp_token) #[derive(Clone, Debug)] -enum Token { - /// Raw string to output - String(String), - /// Break hint: space if fits, newline+indent if not - /// nspaces: number of spaces if not breaking - /// offset: additional indent offset if breaking - Break { nspaces: usize, offset: i32 }, - /// Open a new box - OpenBox { kind: BoxKind, indent: i32 }, - /// Close current box - CloseBox, - /// Force a newline +enum PpToken { + /// Text to print (Pp_text) + Text(String), + /// Break hint (Pp_break) + /// nspaces: spaces if not breaking, offset: indent offset if breaking + Break { nspaces: i32, offset: i32 }, + /// Open a box (Pp_begin) + Begin { indent: i32, kind: BoxKind }, + /// Close a box (Pp_end) + End, + /// Force a newline (Pp_newline) Newline, } -/// A box containing buffered tokens -#[derive(Debug)] -struct Box { - kind: BoxKind, - indent: i32, - tokens: Vec, +/// Queue element with mutable size +#[derive(Clone, Debug)] +struct QueueElem { + /// Size: negative means unknown (= -(pp_right_total at creation time)) + /// When resolved: total content from here to the next break/box-close + size: i32, + token: PpToken, + /// Declared length of this token + length: i32, } -impl Box { - fn new(kind: BoxKind, indent: i32) -> Self { - Box { - kind, - indent, - tokens: Vec::new(), - } - } +/// Scan stack element +#[derive(Clone, Debug)] +struct ScanElem { + /// Value of pp_left_total when this element was enqueued + left_total: i32, + /// Index into the queue + queue_index: usize, +} + +/// Format stack element (describes an active box) +#[derive(Clone, Debug)] +struct FormatElem { + box_type: BoxKind, + width: i32, } /// Pretty-printing formatter matching OCaml's Format module pub struct Formatter { out: W, - /// Target line width - margin: usize, - /// Current column position (0-based) - col: usize, - /// The current top-level box (only one at a time, nested boxes are tokens) - current_box: Option, - /// Depth of nested boxes (0 means we're in the top-level box) - box_depth: usize, - /// Stack of indentation levels - indent_stack: Vec, - /// Stack tracking whether each box level is "broken" (had a line break) - /// When a box is broken, all subsequent breaks in HOV mode also break - broken_stack: Vec, + /// Target line width (pp_margin) + margin: i32, + /// Minimal space left before margin when opening a box (pp_min_space_left) + min_space_left: i32, + /// Maximum indentation (pp_max_indent = pp_margin - pp_min_space_left) + max_indent: i32, + /// Space remaining on current line (pp_space_left) + space_left: i32, + /// Current indentation (pp_current_indent) + current_indent: i32, + /// True when line was just broken (pp_is_new_line) + is_new_line: bool, + /// Total width of tokens already printed (pp_left_total) + left_total: i32, + /// Total width of tokens ever enqueued (pp_right_total) + right_total: i32, + /// Current box depth (pp_curr_depth) + curr_depth: i32, + /// The queue of pending tokens + queue: VecDeque, + /// The scan stack (tracks unresolved breaks and box-opens) + scan_stack: Vec, + /// The format stack (tracks active boxes during rendering) + format_stack: Vec, + /// Global monotonic index for queue elements + queue_offset: usize, } impl Formatter { /// Create a new formatter writing to the given output pub fn new(out: W) -> Self { - Formatter { + let margin = DEFAULT_MARGIN as i32; + let min_space_left = 10; + let mut f = Formatter { out, - margin: DEFAULT_MARGIN, - col: 0, - current_box: None, - box_depth: 0, - indent_stack: vec![0], - broken_stack: vec![false], - } + margin, + min_space_left, + max_indent: margin - min_space_left, + space_left: margin, + current_indent: 0, + is_new_line: true, + left_total: 1, + right_total: 1, + curr_depth: 0, + queue: VecDeque::new(), + scan_stack: Vec::new(), + format_stack: Vec::new(), + queue_offset: 0, + }; + // Initialize scan stack with sentinel (matching OCaml's initialize_scan_stack) + f.initialize_scan_stack(); + // Open the system box (matching OCaml's pp_open_sys_box) + f.pp_open_sys_box(); + f } /// Set the margin (line width) pub fn set_margin(&mut self, margin: usize) { - self.margin = margin; + self.margin = margin as i32; + self.max_indent = self.margin - self.min_space_left; + // Reset state like OCaml's pp_rinit + self.pp_rinit(); } /// Get current column position pub fn column(&self) -> usize { - self.col - } - - /// Get current indentation level - fn current_indent(&self) -> usize { - *self.indent_stack.last().unwrap_or(&0) + (self.margin - self.space_left).max(0) as usize } // ======================================================================== - // Low-level output methods (bypass boxing) + // Output functions // ======================================================================== - /// Write a string directly to output, updating column - /// Also marks the current box as broken if string contains newlines - fn write_raw(&mut self, s: &str) { + fn pp_output_string(&mut self, s: &str) { let _ = self.out.write_all(s.as_bytes()); - // Update column, accounting for newlines - if let Some(pos) = s.rfind('\n') { - self.col = s.len() - pos - 1; - // Mark current box as broken since we crossed a line boundary - if let Some(broken) = self.broken_stack.last_mut() { - *broken = true; - } - } else { - self.col += s.chars().count(); - } } - /// Write n spaces directly - fn write_spaces(&mut self, n: usize) { + fn pp_output_newline(&mut self) { + let _ = self.out.write_all(b"\n"); + } + + fn pp_output_spaces(&mut self, n: i32) { for _ in 0..n { let _ = self.out.write_all(b" "); } - self.col += n; } - /// Write newline and indent to current level + offset - /// Also marks the current box as broken - fn write_newline_indent(&mut self, offset: i32) { - let _ = self.out.write_all(b"\n"); - let indent = (self.current_indent() as i32 + offset).max(0) as usize; - for _ in 0..indent { + fn pp_output_indent(&mut self, n: i32) { + for _ in 0..n { let _ = self.out.write_all(b" "); } - self.col = indent; - // Mark current box as broken - if let Some(broken) = self.broken_stack.last_mut() { - *broken = true; + } + + // ======================================================================== + // Format helpers (matching OCaml's format.ml) + // ======================================================================== + + /// Format text: reduce space_left, output string + fn format_pp_text(&mut self, size: i32, s: &str) { + self.space_left -= size; + self.pp_output_string(s); + self.is_new_line = false; + } + + /// Format string if non-empty + fn format_string(&mut self, s: &str) { + if !s.is_empty() { + self.format_pp_text(s.len() as i32, s); } } - /// Check if current box is broken (has had a line break) - fn is_broken(&self) -> bool { - *self.broken_stack.last().unwrap_or(&false) + /// Break to new line with given offset from box width + fn break_new_line(&mut self, offset: i32, width: i32) { + self.pp_output_newline(); + self.is_new_line = true; + let indent = self.margin - width + offset; + let real_indent = indent.min(self.max_indent).max(0); + self.current_indent = real_indent; + self.space_left = self.margin - self.current_indent; + self.pp_output_indent(self.current_indent); + } + + /// Break line (no offset) + fn break_line(&mut self, width: i32) { + self.break_new_line(0, width); + } + + /// Stay on same line with given number of spaces + fn break_same_line(&mut self, width: i32) { + self.space_left -= width; + self.pp_output_spaces(width); + } + + /// Force break line if box is too far right (matching OCaml's pp_force_break_line) + fn pp_force_break_line(&mut self) { + match self.format_stack.last() { + None => { + self.pp_output_newline(); + } + Some(elem) => { + let width = elem.width; + if width > self.space_left { + match elem.box_type { + BoxKind::Fits | BoxKind::H => {} + _ => { + self.break_line(width); + } + } + } + } + } } // ======================================================================== - // Token handling + // Format token (matching OCaml's format_pp_token) // ======================================================================== - /// Add a token to the current box, or write directly if no box is open - fn emit(&mut self, token: Token) { - if let Some(box_) = self.current_box.as_mut() { - box_.tokens.push(token); + fn format_pp_token(&mut self, size: i32, token: &PpToken) { + match token { + PpToken::Text(s) => { + self.format_pp_text(size, s); + } + + PpToken::Begin { indent, kind } => { + let insertion_point = self.margin - self.space_left; + if insertion_point > self.max_indent { + self.pp_force_break_line(); + } + let width = self.space_left - indent; + let box_type = match kind { + BoxKind::V => BoxKind::V, + _ => { + if size > self.space_left { + *kind + } else { + BoxKind::Fits + } + } + }; + self.format_stack.push(FormatElem { box_type, width }); + } + + PpToken::End => { + self.format_stack.pop(); + } + + PpToken::Newline => { + match self.format_stack.last() { + None => { + self.pp_output_newline(); + } + Some(elem) => { + let width = elem.width; + self.break_line(width); + } + } + } + + PpToken::Break { nspaces, offset } => { + match self.format_stack.last() { + None => {} + Some(elem) => { + let box_type = elem.box_type; + let width = elem.width; + match box_type { + BoxKind::HOV => { + if size > self.space_left { + self.break_new_line(*offset, width); + } else { + self.break_same_line(*nspaces); + } + } + BoxKind::Box => { + // Have the line just been broken here? + if self.is_new_line { + self.break_same_line(*nspaces); + } else if size > self.space_left { + self.break_new_line(*offset, width); + } else if self.current_indent > self.margin - width + *offset { + self.break_new_line(*offset, width); + } else { + self.break_same_line(*nspaces); + } + } + BoxKind::HV => { + self.break_new_line(*offset, width); + } + BoxKind::Fits => { + self.break_same_line(*nspaces); + } + BoxKind::V => { + self.break_new_line(*offset, width); + } + BoxKind::H => { + self.break_same_line(*nspaces); + } + } + } + } + } + } + } + + // ======================================================================== + // Queue and scan stack management + // ======================================================================== + + /// Enqueue a token (matching OCaml's pp_enqueue) + fn pp_enqueue(&mut self, elem: QueueElem) { + self.right_total += elem.length; + self.queue.push_back(elem); + } + + /// Clear the queue (matching OCaml's pp_clear_queue) + fn pp_clear_queue(&mut self) { + self.left_total = 1; + self.right_total = 1; + self.queue.clear(); + self.queue_offset = 0; + } + + /// Initialize scan stack with sentinel + fn initialize_scan_stack(&mut self) { + self.scan_stack.clear(); + let queue_elem = QueueElem { + size: -1, // Size.unknown + token: PpToken::Text(String::new()), + length: 0, + }; + // Push sentinel with left_total = -1 + // The sentinel queue elem doesn't go in the main queue + // We use a special index that won't match any real queue position + self.scan_stack.push(ScanElem { + left_total: -1, + queue_index: usize::MAX, + }); + // Store the sentinel element - we don't actually need it in the queue + // since it's only used as a guard in set_size + let _ = queue_elem; + } + + /// Get queue element by absolute index + fn queue_get(&self, abs_index: usize) -> Option<&QueueElem> { + if abs_index == usize::MAX { + return None; // sentinel + } + if abs_index >= self.queue_offset { + self.queue.get(abs_index - self.queue_offset) + } else { + None + } + } + + /// Get mutable queue element by absolute index + fn queue_get_mut(&mut self, abs_index: usize) -> Option<&mut QueueElem> { + if abs_index == usize::MAX { + return None; // sentinel + } + if abs_index >= self.queue_offset { + self.queue.get_mut(abs_index - self.queue_offset) } else { - // No box open - render immediately - self.render_token(&token, false); + None } } + /// Current absolute index for the next element to be pushed + fn queue_abs_end(&self) -> usize { + self.queue_offset + self.queue.len() + } + + /// Set size of top scan stack element (matching OCaml's set_size) + /// ty=true: resolve breaks, ty=false: resolve box-opens + fn set_size(&mut self, ty: bool) { + if let Some(scan_elem) = self.scan_stack.last() { + let left_total = scan_elem.left_total; + let queue_index = scan_elem.queue_index; + + // Check if scan stack data is obsolete + if left_total < self.left_total { + self.initialize_scan_stack(); + return; + } + + if let Some(queue_elem) = self.queue_get(queue_index) { + let old_size = queue_elem.size; + let token_is_break = matches!(queue_elem.token, PpToken::Break { .. }); + let token_is_begin = matches!(queue_elem.token, PpToken::Begin { .. }); + + if token_is_break && ty { + // Resolve break size + let new_size = self.right_total + old_size; + if let Some(elem) = self.queue_get_mut(queue_index) { + elem.size = new_size; + } + self.scan_stack.pop(); + } else if token_is_begin && !ty { + // Resolve box-open size + let new_size = self.right_total + old_size; + if let Some(elem) = self.queue_get_mut(queue_index) { + elem.size = new_size; + } + self.scan_stack.pop(); + } + } + } + } + + /// Push a token on the scan stack (matching OCaml's scan_push) + /// If b is true, set_size is called first (for breaks) + fn scan_push(&mut self, b: bool, elem: QueueElem) { + let queue_index = self.queue_abs_end(); + self.pp_enqueue(elem); + if b { + self.set_size(true); + } + let scan_elem = ScanElem { + left_total: self.right_total, + queue_index, + }; + self.scan_stack.push(scan_elem); + } + + /// Process tokens from the queue front (matching OCaml's advance_left) + fn advance_left(&mut self) { + loop { + let (size, token, length) = match self.queue.front() { + None => return, + Some(elem) => { + let size = elem.size; + let pending_count = self.right_total - self.left_total; + if size >= 0 || pending_count >= self.space_left { + (size, elem.token.clone(), elem.length) + } else { + return; + } + } + }; + + self.queue.pop_front(); + self.queue_offset += 1; + + let actual_size = if size >= 0 { size } else { PP_INFINITY }; + self.format_pp_token(actual_size, &token); + self.left_total += length; + } + } + + /// Enqueue and advance (matching OCaml's enqueue_advance) + fn enqueue_advance(&mut self, elem: QueueElem) { + self.pp_enqueue(elem); + self.advance_left(); + } + + /// Enqueue a string (matching OCaml's enqueue_string_as) + fn enqueue_string_as(&mut self, size: i32, s: String) { + self.enqueue_advance(QueueElem { + size, + token: PpToken::Text(s), + length: size, + }); + } + + /// Initialize/reset the formatter (matching OCaml's pp_rinit) + fn pp_rinit(&mut self) { + self.pp_clear_queue(); + self.initialize_scan_stack(); + self.format_stack.clear(); + self.current_indent = 0; + self.curr_depth = 0; + self.space_left = self.margin; + self.pp_open_sys_box(); + } + + /// Open the system box (matching OCaml's pp_open_sys_box) + fn pp_open_sys_box(&mut self) { + self.pp_open_box_gen(0, BoxKind::HOV); + } + // ======================================================================== // Public API - Box management // ======================================================================== + /// Open a box (matching OCaml's pp_open_box_gen) + fn pp_open_box_gen(&mut self, indent: i32, kind: BoxKind) { + self.curr_depth += 1; + let size = -self.right_total; + let elem = QueueElem { + size, + token: PpToken::Begin { indent, kind }, + length: 0, + }; + self.scan_push(false, elem); + } + /// Open a box with the given kind and indent offset - /// - /// The indent is relative to the current column when content is rendered. pub fn open_box(&mut self, kind: BoxKind, indent: i32) { - if self.current_box.is_none() { - // Top-level box - start fresh - self.current_box = Some(Box::new(kind, indent)); - self.box_depth = 1; - } else { - // Nested box - add token to current box - self.emit(Token::OpenBox { kind, indent }); - self.box_depth += 1; - } + self.pp_open_box_gen(indent, kind); } /// Open a horizontal box (never breaks) @@ -228,53 +550,17 @@ impl Formatter { self.open_box(BoxKind::HOV, indent); } - /// Close the current box and render its contents + /// Close the current box (matching OCaml's pp_close_box) pub fn close_box(&mut self) { - if self.box_depth == 0 { - return; - } - - self.box_depth -= 1; - - if self.box_depth > 0 { - // Closing a nested box - just emit CloseBox token - self.emit(Token::CloseBox); - } else { - // Closing the top-level box - render everything - if let Some(box_) = self.current_box.take() { - // Calculate if box fits on one line - let size = self.calculate_size(&box_.tokens); - let fits = self.col + size <= self.margin; - - // Push new indent level and broken state for this box - let box_indent = (self.col as i32 + box_.indent).max(0) as usize; - self.indent_stack.push(box_indent); - self.broken_stack.push(false); - - // Render based on box kind and whether it fits - match box_.kind { - BoxKind::H => { - // Always horizontal - self.render_tokens(&box_.tokens, false); - } - BoxKind::V => { - // Always vertical - self.render_tokens(&box_.tokens, true); - } - BoxKind::HV => { - // Exclusive: all horizontal OR all vertical - self.render_tokens(&box_.tokens, !fits); - } - BoxKind::HOV => { - // Packing: break only when necessary - self.render_tokens_packing(&box_.tokens); - } - } - - // Pop indent level and broken state - self.indent_stack.pop(); - self.broken_stack.pop(); - } + if self.curr_depth > 1 { + self.enqueue_advance(QueueElem { + size: 0, + token: PpToken::End, + length: 0, + }); + self.set_size(true); + self.set_size(false); + self.curr_depth -= 1; } } @@ -284,7 +570,8 @@ impl Formatter { /// Print a string pub fn string(&mut self, s: &str) { - self.emit(Token::String(s.to_string())); + let len = s.chars().count() as i32; + self.enqueue_string_as(len, s.to_string()); } /// Print a string slice (alias for string) @@ -293,18 +580,20 @@ impl Formatter { } /// Print formatted content using format_args! - /// - /// Usage: `f.print(format_args!("{} = {}", name, value))` pub fn print(&mut self, args: std::fmt::Arguments<'_>) { self.string(&args.to_string()); } - /// Break hint: space if fits, newline+indent if not - /// - /// - `nspaces`: number of spaces if not breaking - /// - `offset`: additional indent offset if breaking + /// Break hint (matching OCaml's pp_print_break → pp_print_custom_break) pub fn break_(&mut self, nspaces: usize, offset: i32) { - self.emit(Token::Break { nspaces, offset }); + let nspaces = nspaces as i32; + let size = -self.right_total; + let elem = QueueElem { + size, + token: PpToken::Break { nspaces, offset }, + length: nspaces, + }; + self.scan_push(true, elem); } /// Space that may become a newline (equivalent to @; in OCaml) @@ -317,258 +606,26 @@ impl Formatter { self.break_(0, 0); } - /// Force a newline + /// Force a newline (matching OCaml's pp_force_newline) pub fn newline(&mut self) { - self.emit(Token::Newline); + self.enqueue_advance(QueueElem { + size: 0, + token: PpToken::Newline, + length: 0, + }); } - /// Flush all pending output + /// Flush all pending output (matching OCaml's pp_flush_queue) pub fn flush(&mut self) { - // Close any remaining boxes - while self.box_depth > 0 { + // Close all boxes except the system box + while self.curr_depth > 1 { self.close_box(); } - let _ = self.out.flush(); - } - - // ======================================================================== - // Size calculation - // ======================================================================== - - /// Calculate the horizontal size of tokens (if all on one line) - fn calculate_size(&self, tokens: &[Token]) -> usize { - let mut size = 0; - let mut depth = 0; - - for token in tokens { - match token { - Token::String(s) => { - size += s.chars().count(); - } - Token::Break { nspaces, .. } => { - if depth == 0 { - size += nspaces; - } - } - Token::OpenBox { .. } => { - depth += 1; - } - Token::CloseBox => { - if depth > 0 { - depth -= 1; - } - } - Token::Newline => { - // Newline forces break - return large value - return usize::MAX / 2; - } - } - } - size - } - - /// Calculate size of tokens up to next break (for packing) - fn size_until_break(&self, tokens: &[Token], start: usize) -> usize { - let mut size = 0; - let mut depth = 0; - - for token in tokens.iter().skip(start) { - match token { - Token::String(s) => { - size += s.chars().count(); - } - Token::Break { .. } if depth == 0 => { - // Found a break at current level - return size; - } - Token::Break { nspaces, .. } => { - size += nspaces; - } - Token::OpenBox { .. } => { - depth += 1; - } - Token::CloseBox => { - if depth > 0 { - depth -= 1; - } - } - Token::Newline => { - return usize::MAX / 2; - } - } - } - size - } - - // ======================================================================== - // Rendering - // ======================================================================== - - /// Render a single token - fn render_token(&mut self, token: &Token, breaking: bool) { - match token { - Token::String(s) => { - self.write_raw(s); - } - Token::Break { nspaces, offset } => { - if breaking { - self.write_newline_indent(*offset); - } else { - self.write_spaces(*nspaces); - } - } - Token::OpenBox { .. } => { - // OpenBox tokens are handled by render_tokens, not render_token - // This should not be reached in normal usage - } - Token::CloseBox => { - // CloseBox tokens are handled by render_tokens, not render_token - // This should not be reached in normal usage - } - Token::Newline => { - self.write_newline_indent(0); - } - } - } - - /// Render tokens with uniform break decision - fn render_tokens(&mut self, tokens: &[Token], breaking: bool) { - let mut i = 0; - while i < tokens.len() { - let token = &tokens[i]; - match token { - Token::OpenBox { kind, indent } => { - // Find matching close and render nested box - let (nested_tokens, end_idx) = self.extract_nested_box(tokens, i + 1); - - // Push indent and broken state for nested box - let box_indent = (self.col as i32 + indent).max(0) as usize; - self.indent_stack.push(box_indent); - self.broken_stack.push(false); - - // Calculate if nested box fits - let size = self.calculate_size(&nested_tokens); - let fits = self.col + size <= self.margin; - - // Render based on box kind - match kind { - BoxKind::H => self.render_tokens(&nested_tokens, false), - BoxKind::V => self.render_tokens(&nested_tokens, true), - BoxKind::HV => self.render_tokens(&nested_tokens, !fits), - BoxKind::HOV => self.render_tokens_packing(&nested_tokens), - } - - self.indent_stack.pop(); - self.broken_stack.pop(); - i = end_idx + 1; - } - Token::CloseBox => { - // Skip - handled by extract_nested_box - i += 1; - } - _ => { - self.render_token(token, breaking); - i += 1; - } - } - } - } - - /// Render tokens with packing (break only when necessary) - /// In HOV packing mode, once the box is "broken" (had a line break), - /// all subsequent breaks also break. This matches OCaml's Format behavior. - fn render_tokens_packing(&mut self, tokens: &[Token]) { - let mut i = 0; - while i < tokens.len() { - let token = &tokens[i]; - match token { - Token::OpenBox { kind, indent } => { - // Find matching close and render nested box - let (nested_tokens, end_idx) = self.extract_nested_box(tokens, i + 1); - - // Push indent and broken state for nested box - let box_indent = (self.col as i32 + indent).max(0) as usize; - self.indent_stack.push(box_indent); - self.broken_stack.push(false); - - // Calculate if nested box fits - let size = self.calculate_size(&nested_tokens); - let fits = self.col + size <= self.margin; - - // Render based on box kind - match kind { - BoxKind::H => self.render_tokens(&nested_tokens, false), - BoxKind::V => self.render_tokens(&nested_tokens, true), - BoxKind::HV => self.render_tokens(&nested_tokens, !fits), - BoxKind::HOV => self.render_tokens_packing(&nested_tokens), - } - - self.indent_stack.pop(); - self.broken_stack.pop(); - i = end_idx + 1; - } - Token::CloseBox => { - i += 1; - } - Token::Break { nspaces, offset } => { - // In HOV packing: space() evaluates independently, but cut() honors broken state - // cut() has nspaces=0, space() has nspaces=1 - // When content has embedded newlines (broken=true), cut() should break - if *nspaces == 0 && self.is_broken() { - // Cut after multiline content - break - self.write_newline_indent(*offset); - } else { - // Check if next segment (until break at same level) fits - // OCaml uses < (strict) not <= for the fits check - let size_ahead = self.size_until_break(tokens, i + 1); - if self.col + nspaces + size_ahead < self.margin { - // Fits - use spaces - self.write_spaces(*nspaces); - } else { - // Doesn't fit - break - self.write_newline_indent(*offset); - } - } - i += 1; - } - Token::String(s) => { - self.write_raw(s); - i += 1; - } - Token::Newline => { - self.write_newline_indent(0); - i += 1; - } - } - } - } - - /// Extract nested box tokens, returning (tokens, index of CloseBox) - fn extract_nested_box(&self, tokens: &[Token], start: usize) -> (Vec, usize) { - let mut result = Vec::new(); - let mut depth = 1; - let mut i = start; - - while i < tokens.len() && depth > 0 { - match &tokens[i] { - Token::OpenBox { .. } => { - depth += 1; - result.push(tokens[i].clone()); - } - Token::CloseBox => { - depth -= 1; - if depth > 0 { - result.push(tokens[i].clone()); - } - } - _ => { - result.push(tokens[i].clone()); - } - } - i += 1; - } - - (result, i - 1) + // Set right_total to infinity to force all remaining tokens to be processed + self.right_total = PP_INFINITY; + self.advance_left(); + // Re-initialize + self.pp_rinit(); } } @@ -672,7 +729,7 @@ mod tests { }); // HV box: if it doesn't fit, ALL breaks become newlines let newlines = result.matches('\n').count(); - assert!(newlines == 0 || newlines == 5, "HV box should be all-or-nothing"); + assert!(newlines == 0 || newlines == 5, "HV box should be all-or-nothing, got: {:?}", result); } #[test] diff --git a/compiler-rust/src/parser/grammar.rs b/compiler-rust/src/parser/grammar.rs index ec4f70785b9..4ece3dfc24b 100644 --- a/compiler-rust/src/parser/grammar.rs +++ b/compiler-rust/src/parser/grammar.rs @@ -3,13 +3,15 @@ //! This module defines grammar rules that specify what tokens can start //! and terminate various syntactic constructs. It mirrors `res_grammar.ml`. +use serde::{Deserialize, Serialize}; + use super::token::Token; /// Grammar rules representing different parsing contexts. /// /// These are used by the parser to determine what tokens are valid /// in a given context, enabling error recovery and better diagnostics. -#[derive(Debug, Clone, PartialEq)] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub enum Grammar { /// Open description: `open Belt` OpenDescription, @@ -261,6 +263,7 @@ pub fn is_atomic_expr_start(token: &Token) -> bool { | Token::Percent | Token::Forwardslash | Token::ForwardslashDot + | Token::Regex { .. } | Token::Dict ) } @@ -320,6 +323,7 @@ pub fn is_expr_start(token: &Token) -> bool { | Token::While | Token::Forwardslash | Token::ForwardslashDot + | Token::Regex { .. } | Token::Dict ) } @@ -362,9 +366,11 @@ pub fn is_block_expr_start(token: &Token) -> bool { | Token::Switch | Token::True | Token::Try + | Token::Typ | Token::Uident(_) | Token::Underscore | Token::While + | Token::Regex { .. } | Token::Dict ) } diff --git a/compiler-rust/src/parser/jsx_ppx.rs b/compiler-rust/src/parser/jsx_ppx.rs index 87cd9ea1850..32c0bc7dc0d 100644 --- a/compiler-rust/src/parser/jsx_ppx.rs +++ b/compiler-rust/src/parser/jsx_ppx.rs @@ -11,7 +11,8 @@ //! - Key props use `jsxKeyed`/`jsxsKeyed` instead //! - `@react.component` transforms functions to accept props record -use crate::location::{Located, Location, LocationId, Position, PositionId}; +use crate::location::{Location as FullLocation, Position}; +use crate::parse_arena::{LidentIdx, Located, LocIdx, ParseArena}; use super::ast::*; use super::longident::Longident; @@ -51,8 +52,9 @@ impl Default for JsxConfig { } /// Extract capitalized file name from a file path -fn filename_from_loc(loc: &Location) -> String { - let file_name = &loc.loc_start.file_name; +fn filename_from_loc(loc: &Location, arena: &ParseArena) -> String { + let file_name_idx = arena.loc_start(*loc).file_name; + let file_name = arena.get_string(file_name_idx); if file_name.is_empty() { return String::new(); } @@ -104,11 +106,11 @@ struct NamedType { // ============================================================================ /// Transform a structure, applying JSX PPX transformations -pub fn transform_structure(structure: Structure, initial_version: i32) -> Structure { +pub fn transform_structure(structure: Structure, initial_version: i32, arena: &mut ParseArena) -> Structure { // Extract file name from first item's location let file_name = structure .first() - .map(|item| filename_from_loc(&item.pstr_loc)) + .map(|item| filename_from_loc(&item.pstr_loc, arena)) .unwrap_or_default(); let mut config = JsxConfig { @@ -119,18 +121,18 @@ pub fn transform_structure(structure: Structure, initial_version: i32) -> Struct let mut result = vec![]; for item in structure { - let items = transform_structure_item_multi(item, &mut config); + let items = transform_structure_item_multi(item, &mut config, arena); result.extend(items); } result } /// Transform a signature, applying JSX PPX transformations -pub fn transform_signature(signature: Signature, initial_version: i32) -> Signature { +pub fn transform_signature(signature: Signature, initial_version: i32, arena: &mut ParseArena) -> Signature { // Extract file name from first item's location let file_name = signature .first() - .map(|item| filename_from_loc(&item.psig_loc)) + .map(|item| filename_from_loc(&item.psig_loc, arena)) .unwrap_or_default(); let mut config = JsxConfig { @@ -141,7 +143,7 @@ pub fn transform_signature(signature: Signature, initial_version: i32) -> Signat let mut result = vec![]; for item in signature { - let items = transform_signature_item_multi(item, &mut config); + let items = transform_signature_item_multi(item, &mut config, arena); result.extend(items); } result @@ -153,11 +155,11 @@ pub fn transform_signature(signature: Signature, initial_version: i32) -> Signat /// Transform a structure item, potentially returning multiple items /// (e.g., props type + transformed function) -fn transform_structure_item_multi(item: StructureItem, config: &mut JsxConfig) -> Vec { +fn transform_structure_item_multi(item: StructureItem, config: &mut JsxConfig, arena: &mut ParseArena) -> Vec { // Check for @@jsxConfig attribute if let StructureItemDesc::Pstr_attribute(attr) = &item.pstr_desc { if attr.0.txt == "jsxConfig" { - update_config_from_attribute(attr, config); + update_config_from_attribute(arena, attr, config); } return vec![item]; } @@ -169,19 +171,19 @@ fn transform_structure_item_multi(item: StructureItem, config: &mut JsxConfig) - // Handle Pstr_value with potential @react.component if let StructureItemDesc::Pstr_value(rec_flag, bindings) = item.pstr_desc { - return transform_value_bindings(rec_flag, bindings, &item.pstr_loc, config); + return transform_value_bindings(rec_flag, bindings, &item.pstr_loc, config, arena); } // Handle Pstr_primitive (external) with potential @react.component if let StructureItemDesc::Pstr_primitive(vd) = &item.pstr_desc { if has_react_component_attr(&vd.pval_attributes) { - return transform_react_component_external(vd.clone(), &item.pstr_loc, config); + return transform_react_component_external(vd.clone(), &item.pstr_loc, config, arena); } } // Handle module definitions (for nested module tracking) if let StructureItemDesc::Pstr_module(mb) = item.pstr_desc { - let transformed = transform_module_binding_with_tracking(mb, config); + let transformed = transform_module_binding_with_tracking(mb, config, arena); return vec![StructureItem { pstr_desc: StructureItemDesc::Pstr_module(transformed), pstr_loc: item.pstr_loc, @@ -190,18 +192,18 @@ fn transform_structure_item_multi(item: StructureItem, config: &mut JsxConfig) - // Default: just transform expressions within vec![StructureItem { - pstr_desc: transform_structure_item_desc(item.pstr_desc, config), + pstr_desc: transform_structure_item_desc(item.pstr_desc, config, arena), pstr_loc: item.pstr_loc, }] } -fn transform_module_binding_with_tracking(mb: ModuleBinding, config: &mut JsxConfig) -> ModuleBinding { +fn transform_module_binding_with_tracking(mb: ModuleBinding, config: &mut JsxConfig, arena: &mut ParseArena) -> ModuleBinding { // Track nested module name let module_name = mb.pmb_name.txt.clone(); config.nested_modules.push(module_name); config.has_component = false; - let transformed = transform_module_binding(mb, config); + let transformed = transform_module_binding(mb, config, arena); // Pop the module name config.nested_modules.pop(); @@ -215,6 +217,7 @@ fn transform_value_bindings( bindings: Vec, loc: &Location, config: &mut JsxConfig, + arena: &mut ParseArena, ) -> Vec { let mut props_types = vec![]; let mut transformed_bindings = vec![]; @@ -224,7 +227,7 @@ fn transform_value_bindings( if has_react_component_attr(&binding.pvb_attributes) { // Transform @react.component binding let (props_type, transformed, new_binding) = - transform_react_component_binding(binding, rec_flag, loc, config); + transform_react_component_binding(binding, rec_flag, loc, config, arena); if let Some(pt) = props_type { props_types.push(pt); @@ -236,7 +239,7 @@ fn transform_value_bindings( } else if has_react_component_with_props_attr(&binding.pvb_attributes) { // Transform @react.componentWithProps binding let (transformed, new_binding) = - transform_react_component_with_props_binding(binding, rec_flag, loc, config); + transform_react_component_with_props_binding(binding, rec_flag, loc, config, arena); transformed_bindings.push(transformed); if let Some(nb) = new_binding { @@ -244,7 +247,7 @@ fn transform_value_bindings( } } else { // Just transform expressions within - transformed_bindings.push(transform_value_binding(binding, config)); + transformed_bindings.push(transform_value_binding(binding, config, arena)); } } @@ -267,7 +270,7 @@ fn transform_value_bindings( /// Detect forwardRef wrapper and extract inner function /// Returns (wrapper_expr, has_forward_ref, inner_expression) /// wrapper_expr is the original wrapper (e.g., React.forwardRef) expression with its source location -fn spelunk_for_fun_expression(expr: &Expression) -> (Option<&Expression>, bool, &Expression) { +fn spelunk_for_fun_expression<'a>(arena: &ParseArena, expr: &'a Expression) -> (Option<&'a Expression>, bool, &'a Expression) { match &expr.pexp_desc { // let make = (~prop) => ... ExpressionDesc::Pexp_fun { .. } | ExpressionDesc::Pexp_newtype(_, _) => { @@ -275,22 +278,22 @@ fn spelunk_for_fun_expression(expr: &Expression) -> (Option<&Expression>, bool, } // let make = {let foo = bar in (~prop) => ...} ExpressionDesc::Pexp_let(_, _, inner) => { - let (_, has_forward_ref, inner_expr) = spelunk_for_fun_expression(inner); + let (_, has_forward_ref, inner_expr) = spelunk_for_fun_expression(arena, inner); (None, has_forward_ref, inner_expr) } // let make = React.forwardRef((~prop) => ...) ExpressionDesc::Pexp_apply { funct, args, .. } if args.len() == 1 && matches!(&args[0].0, ArgLabel::Nolabel) => { - let (_, _, inner_expr) = spelunk_for_fun_expression(&args[0].1); - let has_forward_ref = is_forward_ref(funct); + let (_, _, inner_expr) = spelunk_for_fun_expression(arena, &args[0].1); + let has_forward_ref = is_forward_ref(arena, funct); // Return the original funct expression (e.g., React.forwardRef) to preserve its source location (if has_forward_ref { Some(funct.as_ref()) } else { None }, has_forward_ref, inner_expr) } ExpressionDesc::Pexp_sequence(_, inner) => { - let (_, has_forward_ref, inner_expr) = spelunk_for_fun_expression(inner); + let (_, has_forward_ref, inner_expr) = spelunk_for_fun_expression(arena, inner); (None, has_forward_ref, inner_expr) } ExpressionDesc::Pexp_constraint(inner, _) => { - spelunk_for_fun_expression(inner) + spelunk_for_fun_expression(arena, inner) } _ => (None, false, expr) } @@ -302,6 +305,7 @@ fn transform_react_component_binding( rec_flag: RecFlag, pstr_loc: &Location, config: &mut JsxConfig, + arena: &mut ParseArena, ) -> (Option, ValueBinding, Option) { // Check for multiple components in the same module (OCaml: check_multiple_components) if config.has_component { @@ -325,7 +329,7 @@ fn transform_react_component_binding( // Detect forwardRef and get inner expression // wrapper_expr is the original React.forwardRef expression with its source location - let (wrapper_expr, has_forward_ref, inner_expr) = spelunk_for_fun_expression(&binding.pvb_expr); + let (wrapper_expr, has_forward_ref, inner_expr) = spelunk_for_fun_expression(arena, &binding.pvb_expr); // Detect if function is async let is_async = is_async_function(&binding.pvb_expr); @@ -338,11 +342,11 @@ fn transform_react_component_binding( .collect(); // Extract labeled arguments from the function (use inner expression to handle forwardRef) - let (args, newtypes, _) = recursively_extract_named_args(inner_expr); + let (args, newtypes, _) = recursively_extract_named_args(arena, inner_expr); // Build named type list for props let named_type_list: Vec = args.iter() - .filter_map(|arg| arg_to_type(arg)) + .filter_map(|arg| arg_to_type(arena, arg)) .collect(); // Create props type - either record or abstract with manifest (for sharedProps) @@ -353,7 +357,7 @@ fn transform_react_component_binding( }; // Build the internal expression pattern (use inner expression to handle forwardRef) - let (patterns_with_label, expression) = build_props_pattern_and_body(inner_expr, &args, config); + let (patterns_with_label, expression) = build_props_pattern_and_body(inner_expr, &args, config, arena); // Create record pattern: {a, b, _}: props<'a, 'b> let record_pattern = if patterns_with_label.is_empty() { @@ -402,13 +406,13 @@ fn transform_react_component_binding( } _ => { // Strip explicit Js.Nullable.t in case of forwardRef - return strip_js_nullable(&nt.interior_type); + return strip_js_nullable(arena, &nt.interior_type); } } } // For optional args, OCaml strips the option wrapper if nt.is_optional && nt.has_explicit_type { - strip_option(&nt.interior_type) + strip_option(arena, &nt.interior_type) } else { Some(nt.interior_type.clone()) } @@ -416,9 +420,11 @@ fn transform_react_component_binding( .collect() }; + let props_str_idx = arena.intern_string("props"); + let props_lid_idx = arena.push_longident(Longident::Lident(props_str_idx)); let props_constr = CoreType { ptyp_desc: CoreTypeDesc::Ptyp_constr( - Loc { txt: Longident::Lident("props".to_string()), loc: empty_loc() }, + Loc { txt: props_lid_idx, loc: empty_loc() }, props_type_params.clone(), ), ptyp_loc: empty_loc(), @@ -450,25 +456,74 @@ fn transform_react_component_binding( ppat_attributes: vec![], }; - // Only add type constraint if alias doesn't start with "_" (underscore means unused) - let ref_pattern = if !ref_alias.starts_with('_') { - // Type is Js.Nullable.t<'ref> - // OCaml calls ref_type Location.none, so inner Ptyp_var uses ghost location + // OCaml (line 749-751): only add Js.Nullable.t<'ref> constraint when the pattern is just + // Ppat_var {txt} (i.e., no existing constraint). If the original pattern already has a + // type constraint, preserve it. + let ref_pattern = if let Some(arg) = ref_arg { + // Check if the original pattern already has a type constraint + if matches!(arg.pattern.ppat_desc, PatternDesc::Ppat_constraint(_, _)) { + // Preserve the original pattern with its type annotation + arg.pattern.clone() + } else if !ref_alias.starts_with('_') { + // No existing constraint, and not unused - add Js.Nullable.t<'ref> + // OCaml calls ref_type Location.none, so inner Ptyp_var uses ghost location + let ref_type_var = CoreType { + ptyp_desc: CoreTypeDesc::Ptyp_var("ref".to_string()), + ptyp_loc: empty_loc(), + ptyp_attributes: vec![], + }; + let js_idx = arena.intern_string("Js"); + let nullable_idx = arena.intern_string("Nullable"); + let t_idx = arena.intern_string("t"); + let js_nullable_t_lid = arena.push_longident(Longident::Ldot( + Box::new(Longident::Ldot( + Box::new(Longident::Lident(js_idx)), + nullable_idx, + )), + t_idx, + )); + let js_nullable_t = CoreType { + ptyp_desc: CoreTypeDesc::Ptyp_constr( + Loc { + txt: js_nullable_t_lid, + loc: empty_loc(), + }, + vec![ref_type_var], + ), + ptyp_loc: empty_loc(), + ptyp_attributes: vec![], + }; + + // OCaml uses ghost location for the outer Ppat_constraint + Pattern { + ppat_desc: PatternDesc::Ppat_constraint(Box::new(base_ref_pattern), js_nullable_t), + ppat_loc: empty_loc(), + ppat_attributes: vec![], + } + } else { + base_ref_pattern + } + } else if !ref_alias.starts_with('_') { + // No ref_arg found but alias doesn't start with "_" - add Js.Nullable.t<'ref> let ref_type_var = CoreType { ptyp_desc: CoreTypeDesc::Ptyp_var("ref".to_string()), ptyp_loc: empty_loc(), ptyp_attributes: vec![], }; + let js_idx = arena.intern_string("Js"); + let nullable_idx = arena.intern_string("Nullable"); + let t_idx = arena.intern_string("t"); + let js_nullable_t_lid = arena.push_longident(Longident::Ldot( + Box::new(Longident::Ldot( + Box::new(Longident::Lident(js_idx)), + nullable_idx, + )), + t_idx, + )); let js_nullable_t = CoreType { ptyp_desc: CoreTypeDesc::Ptyp_constr( Loc { - txt: Longident::Ldot( - Box::new(Longident::Ldot( - Box::new(Longident::Lident("Js".to_string())), - "Nullable".to_string(), - )), - "t".to_string(), - ), + txt: js_nullable_t_lid, loc: empty_loc(), }, vec![ref_type_var], @@ -476,8 +531,6 @@ fn transform_react_component_binding( ptyp_loc: empty_loc(), ptyp_attributes: vec![], }; - - // OCaml uses ghost location for the outer Ppat_constraint Pattern { ppat_desc: PatternDesc::Ppat_constraint(Box::new(base_ref_pattern), js_nullable_t), ppat_loc: empty_loc(), @@ -580,18 +633,20 @@ fn transform_react_component_binding( ppat_attributes: vec![], }, // OCaml line 632: ~attrs:binding.pvb_expr.pexp_attributes - pvb_expr: make_props_wrapper_expr_with_ref(&fn_name, rec_flag, config, has_props_constraint, has_forward_ref, is_async, binding.pvb_expr.pexp_attributes.clone()), + pvb_expr: make_props_wrapper_expr_with_ref(arena, &fn_name, rec_flag, config, has_props_constraint, has_forward_ref, is_async, binding.pvb_expr.pexp_attributes.clone()), pvb_attributes: vec![], pvb_loc: empty_loc(), }; + let binding_str_idx = arena.push_string(binding_name.clone()); + let binding_lid_idx = arena.push_longident(Longident::Lident(binding_str_idx)); Expression { pexp_desc: ExpressionDesc::Pexp_let( RecFlag::Nonrecursive, vec![inner_binding], Box::new(Expression { pexp_desc: ExpressionDesc::Pexp_ident(Loc { - txt: Longident::Lident(binding_name.clone()), + txt: binding_lid_idx, loc: empty_loc(), }), pexp_loc: pstr_loc.clone(), @@ -603,18 +658,6 @@ fn transform_react_component_binding( } }; - // Create transformed binding - let transformed_binding = ValueBinding { - pvb_pat: Pattern { - ppat_desc: PatternDesc::Ppat_var(Loc { txt: fn_name.clone(), loc: empty_loc() }), - ppat_loc: empty_loc(), - ppat_attributes: vec![], - }, - pvb_expr: func_expr, - pvb_attributes: filtered_attrs, - pvb_loc: empty_loc(), - }; - // For forwardRef, wrap full_expression with React.forwardRef(...) // Use the original wrapper_expr to preserve source locations let final_full_expression = if has_forward_ref { @@ -633,14 +676,17 @@ fn transform_react_component_binding( } } else { // Fallback: create fresh expression (shouldn't happen) + let react_idx = arena.intern_string("React"); + let forwardref_idx = arena.intern_string("forwardRef"); + let react_forwardref_lid = arena.push_longident(Longident::Ldot( + Box::new(Longident::Lident(react_idx)), + forwardref_idx, + )); Expression { pexp_desc: ExpressionDesc::Pexp_apply { funct: Box::new(Expression { pexp_desc: ExpressionDesc::Pexp_ident(Loc { - txt: Longident::Ldot( - Box::new(Longident::Lident("React".to_string())), - "forwardRef".to_string(), - ), + txt: react_forwardref_lid, loc: empty_loc(), }), pexp_loc: empty_loc(), @@ -658,23 +704,120 @@ fn transform_react_component_binding( full_expression }; - // For nonrecursive, create a new binding with the wrapper - // OCaml uses real locations for the public make binding: - // - pvb_loc uses pstr_loc (the entire structure_item location including @react.component) - // - pattern uses the original fn_name location - let new_binding = if rec_flag == RecFlag::Nonrecursive && !full_module_name.is_empty() { - Some(ValueBinding { - pvb_pat: Pattern { - ppat_desc: PatternDesc::Ppat_var(Loc { txt: fn_name, loc: fn_name_loc.clone() }), - ppat_loc: fn_name_loc, - ppat_attributes: vec![], - }, - pvb_expr: final_full_expression, - pvb_attributes: vec![], - pvb_loc: pstr_loc.clone(), - }) - } else { - None + // Handle recursive vs nonrecursive differently + // OCaml's jsx_v4.ml lines 788-806 + let (transformed_binding, new_binding) = match rec_flag { + RecFlag::Recursive => { + // For recursive: create a nested let structure + // let rec make = { + // let "make$Internal" = func_expr in + // let make = full_expression in + // make + // } + let internal_fn_name = format!("{}$Internal", fn_name); + + // Inner let: let "make$Internal" = func_expr + let internal_binding = ValueBinding { + pvb_pat: Pattern { + ppat_desc: PatternDesc::Ppat_var(Loc { txt: internal_fn_name, loc: empty_loc() }), + ppat_loc: empty_loc(), + ppat_attributes: vec![], + }, + pvb_expr: func_expr, + pvb_attributes: vec![], + pvb_loc: empty_loc(), + }; + + // Middle let: let make = full_expression + let wrapper_binding = ValueBinding { + pvb_pat: Pattern { + ppat_desc: PatternDesc::Ppat_var(Loc { txt: fn_name.clone(), loc: empty_loc() }), + ppat_loc: empty_loc(), + ppat_attributes: vec![], + }, + pvb_expr: final_full_expression, + pvb_attributes: vec![], + pvb_loc: empty_loc(), + }; + + // Final identifier: make + let fn_str_idx = arena.push_string(fn_name.clone()); + let fn_lid_idx = arena.push_longident(Longident::Lident(fn_str_idx)); + let final_ident = Expression { + pexp_desc: ExpressionDesc::Pexp_ident(Loc { + txt: fn_lid_idx, + loc: empty_loc(), + }), + pexp_loc: empty_loc(), + pexp_attributes: vec![], + }; + + // Build nested let: let "make$Internal" = ... in (let make = ... in make) + let inner_let = Expression { + pexp_desc: ExpressionDesc::Pexp_let( + RecFlag::Nonrecursive, + vec![wrapper_binding], + Box::new(final_ident), + ), + pexp_loc: empty_loc(), + pexp_attributes: vec![], + }; + + let outer_let = Expression { + pexp_desc: ExpressionDesc::Pexp_let( + RecFlag::Nonrecursive, + vec![internal_binding], + Box::new(inner_let), + ), + pexp_loc: empty_loc(), + pexp_attributes: vec![], + }; + + // Create the transformed binding with nested let as expression + let binding = ValueBinding { + pvb_pat: Pattern { + ppat_desc: PatternDesc::Ppat_var(Loc { txt: fn_name, loc: original_binding_loc.clone() }), + ppat_loc: original_binding_loc, + ppat_attributes: vec![], + }, + pvb_expr: outer_let, + pvb_attributes: filtered_attrs, + pvb_loc: pstr_loc.clone(), + }; + + (binding, None) + } + RecFlag::Nonrecursive => { + // For nonrecursive: create two separate bindings + let transformed_binding = ValueBinding { + pvb_pat: Pattern { + ppat_desc: PatternDesc::Ppat_var(Loc { txt: fn_name.clone(), loc: empty_loc() }), + ppat_loc: empty_loc(), + ppat_attributes: vec![], + }, + pvb_expr: func_expr, + pvb_attributes: filtered_attrs, + pvb_loc: empty_loc(), + }; + + // Create new binding with wrapper if module name is non-empty + let new_binding = if !full_module_name.is_empty() { + Some(ValueBinding { + pvb_pat: Pattern { + ppat_desc: PatternDesc::Ppat_var(Loc { txt: fn_name, loc: fn_name_loc.clone() }), + ppat_loc: fn_name_loc, + ppat_attributes: vec![], + }, + pvb_expr: final_full_expression, + pvb_attributes: vec![], + pvb_loc: pstr_loc.clone(), + }) + } else { + None + }; + + (transformed_binding, new_binding) + } }; (Some(props_type), transformed_binding, new_binding) @@ -688,6 +831,7 @@ fn transform_react_component_with_props_binding( rec_flag: RecFlag, pstr_loc: &Location, config: &mut JsxConfig, + arena: &mut ParseArena, ) -> (ValueBinding, Option) { // Check for multiple components in the same module if config.has_component { @@ -704,7 +848,7 @@ fn transform_react_component_with_props_binding( let full_module_name = make_module_name(config, &fn_name); // Check if the expression uses React.forwardRef (not allowed with componentWithProps) - let (_, has_forward_ref, _) = spelunk_for_fun_expression(&binding.pvb_expr); + let (_, has_forward_ref, _) = spelunk_for_fun_expression(arena, &binding.pvb_expr); if has_forward_ref { eprintln!( "Components using React.forwardRef cannot use @react.componentWithProps. Use @react.component instead." @@ -722,7 +866,7 @@ fn transform_react_component_with_props_binding( .collect(); // Create props pattern based on the original function's pattern - let props_pattern = make_with_props_pattern(&binding.pvb_expr); + let props_pattern = make_with_props_pattern(arena, &binding.pvb_expr); // Create the applied expression: fnName(props) or fnName$Internal(props) let called_fn_name = match rec_flag { @@ -730,11 +874,15 @@ fn transform_react_component_with_props_binding( RecFlag::Nonrecursive => fn_name.clone(), }; + let called_fn_str_idx = arena.push_string(called_fn_name); + let called_fn_lid = arena.push_longident(Longident::Lident(called_fn_str_idx)); + let props_str_idx = arena.intern_string("props"); + let props_lid = arena.push_longident(Longident::Lident(props_str_idx)); let applied_expr = Expression { pexp_desc: ExpressionDesc::Pexp_apply { funct: Box::new(Expression { pexp_desc: ExpressionDesc::Pexp_ident(Loc { - txt: Longident::Lident(called_fn_name), + txt: called_fn_lid, loc: empty_loc(), }), pexp_loc: empty_loc(), @@ -744,7 +892,7 @@ fn transform_react_component_with_props_binding( ArgLabel::Nolabel, Expression { pexp_desc: ExpressionDesc::Pexp_ident(Loc { - txt: Longident::Lident("props".to_string()), + txt: props_lid, loc: empty_loc(), }), pexp_loc: empty_loc(), @@ -760,13 +908,13 @@ fn transform_react_component_with_props_binding( // Handle async wrapping if needed let applied_expr = if is_async { - wrap_with_jsx_promise(applied_expr) + wrap_with_jsx_promise(arena, applied_expr) } else { applied_expr }; // Wrap with React.element return type constraint - let constrained_expr = constrain_jsx_return(applied_expr, config); + let constrained_expr = constrain_jsx_return(arena, applied_expr, config); // Create wrapper expression: props => constrained_expr let wrapper_expr = Expression { @@ -798,7 +946,10 @@ fn transform_react_component_with_props_binding( }], Box::new(Expression { pexp_desc: ExpressionDesc::Pexp_ident(Loc { - txt: Longident::Lident(full_module_name), + txt: { + let str_idx = arena.push_string(full_module_name); + arena.push_longident(Longident::Lident(str_idx)) + }, loc: empty_loc(), }), pexp_loc: empty_loc(), @@ -832,7 +983,7 @@ fn transform_react_component_with_props_binding( ppat_loc: empty_loc(), ppat_attributes: vec![], }, - pvb_expr: transform_expression(binding.pvb_expr, config), + pvb_expr: transform_expression(binding.pvb_expr, config, arena), pvb_attributes: filtered_attrs, pvb_loc: binding.pvb_loc, }; @@ -840,8 +991,8 @@ fn transform_react_component_with_props_binding( } RecFlag::Nonrecursive => { // For non-recursive: wrap the function body with React.element constraint - let transformed_expr = transform_expression(binding.pvb_expr, config); - let constrained_expr = wrap_function_body_with_constraint(transformed_expr, config); + let transformed_expr = transform_expression(binding.pvb_expr, config, arena); + let constrained_expr = wrap_function_body_with_constraint(arena, transformed_expr, config); // OCaml line 905-909: clear pexp_attributes (they were moved to wrapper_expr) let constrained_expr = Expression { pexp_attributes: vec![], @@ -859,11 +1010,11 @@ fn transform_react_component_with_props_binding( } /// Wrap the innermost body of a function expression with constrain_jsx_return -fn wrap_function_body_with_constraint(expr: Expression, config: &JsxConfig) -> Expression { +fn wrap_function_body_with_constraint(arena: &mut ParseArena, expr: Expression, config: &JsxConfig) -> Expression { match expr.pexp_desc { ExpressionDesc::Pexp_fun { arg_label, default, lhs, rhs, arity, is_async } => { // Recursively wrap the body - let wrapped_rhs = wrap_function_body_with_constraint(*rhs, config); + let wrapped_rhs = wrap_function_body_with_constraint(arena, *rhs, config); Expression { pexp_desc: ExpressionDesc::Pexp_fun { arg_label, @@ -879,19 +1030,21 @@ fn wrap_function_body_with_constraint(expr: Expression, config: &JsxConfig) -> E } _ => { // This is the innermost body - wrap it with React.element constraint - constrain_jsx_return(expr, config) + constrain_jsx_return(arena, expr, config) } } } /// Create props pattern for componentWithProps based on the original function's pattern -fn make_with_props_pattern(expr: &Expression) -> Pattern { +fn make_with_props_pattern(arena: &mut ParseArena, expr: &Expression) -> Pattern { match &expr.pexp_desc { ExpressionDesc::Pexp_fun { lhs, .. } => { match &lhs.ppat_desc { PatternDesc::Ppat_constraint(_, typ) => { match &typ.ptyp_desc { - CoreTypeDesc::Ptyp_constr(loc, args) if loc.txt == Longident::Lident("props".to_string()) => { + CoreTypeDesc::Ptyp_constr(loc, args) if arena.is_lident(loc.txt, "props") => { + let props_str_idx = arena.intern_string("props"); + let props_lid = arena.push_longident(Longident::Lident(props_str_idx)); if !args.is_empty() { // props<_> Pattern { @@ -903,7 +1056,7 @@ fn make_with_props_pattern(expr: &Expression) -> Pattern { }), CoreType { ptyp_desc: CoreTypeDesc::Ptyp_constr( - Loc { txt: Longident::Lident("props".to_string()), loc: empty_loc() }, + Loc { txt: props_lid, loc: empty_loc() }, vec![CoreType { ptyp_desc: CoreTypeDesc::Ptyp_any, ptyp_loc: empty_loc(), @@ -928,7 +1081,7 @@ fn make_with_props_pattern(expr: &Expression) -> Pattern { }), CoreType { ptyp_desc: CoreTypeDesc::Ptyp_constr( - Loc { txt: Longident::Lident("props".to_string()), loc: empty_loc() }, + Loc { txt: props_lid, loc: empty_loc() }, vec![], ), ptyp_loc: empty_loc(), @@ -959,15 +1112,17 @@ fn simple_props_pattern() -> Pattern { } /// Wrap expression with Jsx.promise for async components -fn wrap_with_jsx_promise(expr: Expression) -> Expression { +fn wrap_with_jsx_promise(arena: &mut ParseArena, expr: Expression) -> Expression { + let jsx_idx = arena.intern_string("Jsx"); + let promise_idx = arena.intern_string("promise"); Expression { pexp_desc: ExpressionDesc::Pexp_apply { funct: Box::new(Expression { pexp_desc: ExpressionDesc::Pexp_ident(Loc { - txt: Longident::Ldot( - Box::new(Longident::Lident("Jsx".to_string())), - "promise".to_string(), - ), + txt: arena.push_longident(Longident::Ldot( + Box::new(Longident::Lident(jsx_idx)), + promise_idx, + )), loc: empty_loc(), }), pexp_loc: empty_loc(), @@ -993,7 +1148,7 @@ fn is_async_function(expr: &Expression) -> bool { ///// Create wrapper expression: props => fnName(props) /// OCaml's make_props_pattern only adds type constraint when there are props -fn make_props_wrapper_expr(fn_name: &str, _rec_flag: RecFlag, _config: &JsxConfig, has_props: bool) -> Expression { +fn make_props_wrapper_expr(arena: &mut ParseArena, fn_name: &str, _rec_flag: RecFlag, _config: &JsxConfig, has_props: bool) -> Expression { let props_pattern = Pattern { ppat_desc: PatternDesc::Ppat_var(Loc { txt: "props".to_string(), loc: empty_loc() }), ppat_loc: empty_loc(), @@ -1002,9 +1157,10 @@ fn make_props_wrapper_expr(fn_name: &str, _rec_flag: RecFlag, _config: &JsxConfi // Only constrain with props<_> if there are props (matches OCaml's make_props_pattern) let final_pattern = if has_props { + let props_str_idx = arena.intern_string("props"); let props_type = CoreType { ptyp_desc: CoreTypeDesc::Ptyp_constr( - Loc { txt: Longident::Lident("props".to_string()), loc: empty_loc() }, + Loc { txt: arena.push_longident(Longident::Lident(props_str_idx)), loc: empty_loc() }, vec![CoreType { ptyp_desc: CoreTypeDesc::Ptyp_any, ptyp_loc: empty_loc(), @@ -1023,11 +1179,13 @@ fn make_props_wrapper_expr(fn_name: &str, _rec_flag: RecFlag, _config: &JsxConfi props_pattern }; + let fn_str_idx = arena.push_string(fn_name.to_string()); + let props_str_idx = arena.intern_string("props"); let apply_expr = Expression { pexp_desc: ExpressionDesc::Pexp_apply { funct: Box::new(Expression { pexp_desc: ExpressionDesc::Pexp_ident(Loc { - txt: Longident::Lident(fn_name.to_string()), + txt: arena.push_longident(Longident::Lident(fn_str_idx)), loc: empty_loc(), }), pexp_loc: empty_loc(), @@ -1037,7 +1195,7 @@ fn make_props_wrapper_expr(fn_name: &str, _rec_flag: RecFlag, _config: &JsxConfi ArgLabel::Nolabel, Expression { pexp_desc: ExpressionDesc::Pexp_ident(Loc { - txt: Longident::Lident("props".to_string()), + txt: arena.push_longident(Longident::Lident(props_str_idx)), loc: empty_loc(), }), pexp_loc: empty_loc(), @@ -1068,7 +1226,8 @@ fn make_props_wrapper_expr(fn_name: &str, _rec_flag: RecFlag, _config: &JsxConfi /// Create wrapper expression with forwardRef support: (props, ref) => fnName(props, ref) /// expr_attrs: the original expression's attributes (e.g., @directive) to put on the outer Pexp_fun -fn make_props_wrapper_expr_with_ref(fn_name: &str, _rec_flag: RecFlag, _config: &JsxConfig, has_props: bool, has_forward_ref: bool, is_async: bool, expr_attrs: Attributes) -> Expression { +/// For recursive components, calls fn_name$Internal instead of fn_name +fn make_props_wrapper_expr_with_ref(arena: &mut ParseArena, fn_name: &str, rec_flag: RecFlag, _config: &JsxConfig, has_props: bool, has_forward_ref: bool, is_async: bool, expr_attrs: Attributes) -> Expression { let props_pattern = Pattern { ppat_desc: PatternDesc::Ppat_var(Loc { txt: "props".to_string(), loc: empty_loc() }), ppat_loc: empty_loc(), @@ -1077,9 +1236,10 @@ fn make_props_wrapper_expr_with_ref(fn_name: &str, _rec_flag: RecFlag, _config: // Only constrain with props<_> if there are props let final_pattern = if has_props { + let props_str_idx = arena.intern_string("props"); let props_type = CoreType { ptyp_desc: CoreTypeDesc::Ptyp_constr( - Loc { txt: Longident::Lident("props".to_string()), loc: empty_loc() }, + Loc { txt: arena.push_longident(Longident::Lident(props_str_idx)), loc: empty_loc() }, vec![CoreType { ptyp_desc: CoreTypeDesc::Ptyp_any, ptyp_loc: empty_loc(), @@ -1099,11 +1259,12 @@ fn make_props_wrapper_expr_with_ref(fn_name: &str, _rec_flag: RecFlag, _config: }; // Build arguments for the apply expression + let props_str_idx2 = arena.intern_string("props"); let mut apply_args = vec![( ArgLabel::Nolabel, Expression { pexp_desc: ExpressionDesc::Pexp_ident(Loc { - txt: Longident::Lident("props".to_string()), + txt: arena.push_longident(Longident::Lident(props_str_idx2)), loc: empty_loc(), }), pexp_loc: empty_loc(), @@ -1113,11 +1274,12 @@ fn make_props_wrapper_expr_with_ref(fn_name: &str, _rec_flag: RecFlag, _config: // For forwardRef, add ref argument if has_forward_ref { + let ref_str_idx = arena.intern_string("ref"); apply_args.push(( ArgLabel::Nolabel, Expression { pexp_desc: ExpressionDesc::Pexp_ident(Loc { - txt: Longident::Lident("ref".to_string()), + txt: arena.push_longident(Longident::Lident(ref_str_idx)), loc: empty_loc(), }), pexp_loc: empty_loc(), @@ -1126,11 +1288,17 @@ fn make_props_wrapper_expr_with_ref(fn_name: &str, _rec_flag: RecFlag, _config: )); } + // For recursive components, call fn_name$Internal; otherwise call fn_name + let called_fn_name = match rec_flag { + RecFlag::Recursive => format!("{}$Internal", fn_name), + RecFlag::Nonrecursive => fn_name.to_string(), + }; + let fn_str_idx2 = arena.push_string(called_fn_name); let apply_expr = Expression { pexp_desc: ExpressionDesc::Pexp_apply { funct: Box::new(Expression { pexp_desc: ExpressionDesc::Pexp_ident(Loc { - txt: Longident::Lident(fn_name.to_string()), + txt: arena.push_longident(Longident::Lident(fn_str_idx2)), loc: empty_loc(), }), pexp_loc: empty_loc(), @@ -1146,7 +1314,7 @@ fn make_props_wrapper_expr_with_ref(fn_name: &str, _rec_flag: RecFlag, _config: // Wrap with Jsx.promise for async components let apply_expr = if is_async { - wrap_with_jsx_promise(apply_expr) + wrap_with_jsx_promise(arena, apply_expr) } else { apply_expr }; @@ -1215,11 +1383,12 @@ fn build_props_pattern_and_body( expr: &Expression, args: &[ExtractedArg], config: &JsxConfig, + arena: &mut ParseArena, ) -> (Vec, Expression) { let mut patterns = vec![]; for arg in args { - let label = get_label(&arg.label); + let label = get_label(arena, &arg.label); if label.is_empty() { continue; } @@ -1239,9 +1408,10 @@ fn build_props_pattern_and_body( // Preserve original pattern attributes (OCaml does: pattern_with_safe_label with ppat_attributes = pattern.ppat_attributes) pat.ppat_attributes = arg.pattern.ppat_attributes.clone(); + let label_str_idx = arena.push_string(label.clone()); patterns.push(PatternRecordField { lid: Loc { - txt: Longident::Lident(label.clone()), + txt: arena.push_longident(Longident::Lident(label_str_idx)), loc: arg.loc.clone(), }, pat, @@ -1251,33 +1421,37 @@ fn build_props_pattern_and_body( // Get the body expression (innermost non-fun expression) let body = get_function_body(expr); - let transformed_body = transform_expression(body.clone(), config); + let transformed_body = transform_expression(body.clone(), config, arena); // Constrain return type to React.element - let constrained_body = constrain_jsx_return(transformed_body, config); + let constrained_body = constrain_jsx_return(arena, transformed_body, config); // Add default value handling - let final_body = add_default_value_matches(constrained_body, args); + let final_body = add_default_value_matches(arena, constrained_body, args); (patterns, final_body) } /// Add pattern matching for optional props with default values -fn add_default_value_matches(mut expr: Expression, args: &[ExtractedArg]) -> Expression { +fn add_default_value_matches(arena: &mut ParseArena, mut expr: Expression, args: &[ExtractedArg]) -> Expression { for arg in args.iter().rev() { if let Some(default) = &arg.default { // Use the label name for the match pattern, not the alias // For ~foo as bar, we use "foo" in the match - let label_name = get_label(&arg.label); + let label_name = get_label(arena, &arg.label); let alias = &arg.alias; let prefixed = format!("__{}", alias); // Create: let alias = switch __alias { | Some(labelName) => labelName | None => default } + let prefixed_str_idx = arena.push_string(prefixed); + let some_str_idx = arena.intern_string("Some"); + let none_str_idx = arena.intern_string("None"); + let label_name_str_idx = arena.push_string(label_name.clone()); let match_expr = Expression { pexp_desc: ExpressionDesc::Pexp_match( Box::new(Expression { pexp_desc: ExpressionDesc::Pexp_ident(Loc { - txt: Longident::Lident(prefixed), + txt: arena.push_longident(Longident::Lident(prefixed_str_idx)), loc: empty_loc(), }), pexp_loc: empty_loc(), @@ -1288,7 +1462,7 @@ fn add_default_value_matches(mut expr: Expression, args: &[ExtractedArg]) -> Exp pc_bar: None, pc_lhs: Pattern { ppat_desc: PatternDesc::Ppat_construct( - Loc { txt: Longident::Lident("Some".to_string()), loc: empty_loc() }, + Loc { txt: arena.push_longident(Longident::Lident(some_str_idx)), loc: empty_loc() }, Some(Box::new(Pattern { ppat_desc: PatternDesc::Ppat_var(Loc { txt: label_name.clone(), @@ -1304,7 +1478,7 @@ fn add_default_value_matches(mut expr: Expression, args: &[ExtractedArg]) -> Exp pc_guard: None, pc_rhs: Expression { pexp_desc: ExpressionDesc::Pexp_ident(Loc { - txt: Longident::Lident(label_name.clone()), + txt: arena.push_longident(Longident::Lident(label_name_str_idx)), loc: empty_loc(), }), pexp_loc: empty_loc(), @@ -1315,7 +1489,7 @@ fn add_default_value_matches(mut expr: Expression, args: &[ExtractedArg]) -> Exp pc_bar: None, pc_lhs: Pattern { ppat_desc: PatternDesc::Ppat_construct( - Loc { txt: Longident::Lident("None".to_string()), loc: empty_loc() }, + Loc { txt: arena.push_longident(Longident::Lident(none_str_idx)), loc: empty_loc() }, None, ), ppat_loc: empty_loc(), @@ -1382,11 +1556,11 @@ fn prefix_pattern_var(pat: &mut Pattern, prefix: &str) { // Signature Item Transformation // ============================================================================ -fn transform_signature_item_multi(item: SignatureItem, config: &mut JsxConfig) -> Vec { +fn transform_signature_item_multi(item: SignatureItem, config: &mut JsxConfig, arena: &mut ParseArena) -> Vec { // Check for @@jsxConfig attribute if let SignatureItemDesc::Psig_attribute(attr) = &item.psig_desc { if attr.0.txt == "jsxConfig" { - update_config_from_attribute(attr, config); + update_config_from_attribute(arena, attr, config); } return vec![item]; } @@ -1399,12 +1573,12 @@ fn transform_signature_item_multi(item: SignatureItem, config: &mut JsxConfig) - // Handle Psig_value with potential @react.component if let SignatureItemDesc::Psig_value(vd) = &item.psig_desc { if has_react_component_attr(&vd.pval_attributes) { - return transform_react_component_sig(vd.clone(), &item.psig_loc, config); + return transform_react_component_sig(vd.clone(), &item.psig_loc, config, arena); } } vec![SignatureItem { - psig_desc: transform_signature_item_desc(item.psig_desc, config), + psig_desc: transform_signature_item_desc(item.psig_desc, config, arena), psig_loc: item.psig_loc, }] } @@ -1413,6 +1587,7 @@ fn transform_react_component_sig( vd: ValueDescription, loc: &Location, config: &mut JsxConfig, + arena: &mut ParseArena, ) -> Vec { // Check for multiple components in the same module (OCaml: check_multiple_components) if config.has_component { @@ -1433,7 +1608,7 @@ fn transform_react_component_sig( let prop_types = collect_prop_types(&vd.pval_type); let named_type_list: Vec = prop_types.into_iter() .filter_map(|(label, attrs, loc, typ)| { - let label_str = get_label(&label); + let label_str = get_label(arena, &label); if label_str.is_empty() { None } else { @@ -1493,9 +1668,10 @@ fn transform_react_component_sig( // Create new value description with component type // OCaml: Typ.constr (Location.mkloc (Lident "props") psig_loc) params // Typ.constr without ~loc uses Location.none for ptyp_loc + let props_str_idx = arena.intern_string("props"); let props_type_ref = CoreType { ptyp_desc: CoreTypeDesc::Ptyp_constr( - Loc { txt: Longident::Lident("props".to_string()), loc: loc.clone() }, // longident uses psig_loc + Loc { txt: arena.push_longident(Longident::Lident(props_str_idx)), loc: loc.clone() }, // longident uses psig_loc props_type_params, ), ptyp_loc: empty_loc(), // OCaml: Typ.constr without ~loc defaults to Location.none @@ -1504,10 +1680,12 @@ fn transform_react_component_sig( // OCaml: {pval_type with ptyp_desc = new_external_type} // This preserves pval_type's original ptyp_loc + let react_str_idx = arena.intern_string("React"); + let component_str_idx = arena.intern_string("component"); let component_type = CoreType { ptyp_desc: CoreTypeDesc::Ptyp_constr( Loc { - txt: Longident::Ldot(Box::new(Longident::Lident("React".to_string())), "component".to_string()), + txt: arena.push_longident(Longident::Ldot(Box::new(Longident::Lident(react_str_idx)), component_str_idx)), loc: loc.clone(), // OCaml: {loc = psig_loc; txt = ...} }, vec![props_type_ref], @@ -1538,6 +1716,7 @@ fn transform_react_component_external( vd: ValueDescription, loc: &Location, config: &mut JsxConfig, + arena: &mut ParseArena, ) -> Vec { // Check for multiple components in the same module (OCaml: check_multiple_components) if config.has_component { @@ -1558,7 +1737,7 @@ fn transform_react_component_external( let prop_types = collect_prop_types(&vd.pval_type); let named_type_list: Vec = prop_types.into_iter() .filter_map(|(label, attrs, loc, typ)| { - let label_str = get_label(&label); + let label_str = get_label(arena, &label); if label_str.is_empty() { None } else { @@ -1617,9 +1796,10 @@ fn transform_react_component_external( }; // OCaml uses the external's full location for the props type and its longident + let props_str_idx = arena.intern_string("props"); let props_type_ref = CoreType { ptyp_desc: CoreTypeDesc::Ptyp_constr( - Loc { txt: Longident::Lident("props".to_string()), loc: loc.clone() }, + Loc { txt: arena.push_longident(Longident::Lident(props_str_idx)), loc: loc.clone() }, props_type_params, ), ptyp_loc: loc.clone(), @@ -1628,13 +1808,15 @@ fn transform_react_component_external( // OCaml uses the original return type's location for the outer core_type, // and the external's full location for the longident + let module_str_idx = arena.push_string(config.module_name.clone()); + let component_str_idx = arena.intern_string("component"); let component_type = CoreType { ptyp_desc: CoreTypeDesc::Ptyp_constr( Loc { - txt: Longident::Ldot( - Box::new(Longident::Lident(config.module_name.clone())), - "component".to_string(), - ), + txt: arena.push_longident(Longident::Ldot( + Box::new(Longident::Lident(module_str_idx)), + component_str_idx, + )), loc: loc.clone(), }, vec![props_type_ref], @@ -1800,10 +1982,12 @@ fn typ_vars_of_core_type(typ: &CoreType) -> Vec { } /// Check if an expression is React.forwardRef -fn is_forward_ref(expr: &Expression) -> bool { +fn is_forward_ref(arena: &ParseArena, expr: &Expression) -> bool { if let ExpressionDesc::Pexp_ident(loc) = &expr.pexp_desc { - if let Longident::Ldot(base, field) = &loc.txt { - if let Longident::Lident(m) = base.as_ref() { + if let Longident::Ldot(base, field_idx) = arena.get_longident(loc.txt) { + if let Longident::Lident(m_idx) = base.as_ref() { + let m = arena.get_string(*m_idx); + let field = arena.get_string(*field_idx); return m == "React" && field == "forwardRef"; } } @@ -1868,25 +2052,34 @@ fn make_module_name(config: &JsxConfig, fn_name: &str) -> String { } /// Strip `option` wrapper from a type, returning just `T` -fn strip_option(core_type: &CoreType) -> Option { +fn strip_option(arena: &ParseArena, core_type: &CoreType) -> Option { match &core_type.ptyp_desc { - CoreTypeDesc::Ptyp_constr(lid, args) if lid.txt.last() == "option" && args.len() == 1 => { - args.first().cloned() + CoreTypeDesc::Ptyp_constr(lid, args) if args.len() == 1 => { + let last_idx = arena.get_longident(lid.txt).last_idx(); + let last_str = arena.get_string(last_idx); + if last_str == "option" { + args.first().cloned() + } else { + Some(core_type.clone()) + } } _ => Some(core_type.clone()), } } /// Strip `Js.Nullable.t` wrapper from a type, returning just `T` -fn strip_js_nullable(core_type: &CoreType) -> Option { +fn strip_js_nullable(arena: &ParseArena, core_type: &CoreType) -> Option { match &core_type.ptyp_desc { CoreTypeDesc::Ptyp_constr(lid, args) if args.len() == 1 => { // Check for Js.Nullable.t - if let Longident::Ldot(outer, inner) = &lid.txt { + if let Longident::Ldot(outer, inner_idx) = arena.get_longident(lid.txt) { + let inner = arena.get_string(*inner_idx); if inner == "t" { - if let Longident::Ldot(js, nullable) = outer.as_ref() { + if let Longident::Ldot(js, nullable_idx) = outer.as_ref() { + let nullable = arena.get_string(*nullable_idx); if nullable == "Nullable" { - if let Longident::Lident(js_name) = js.as_ref() { + if let Longident::Lident(js_name_idx) = js.as_ref() { + let js_name = arena.get_string(*js_name_idx); if js_name == "Js" { return args.first().cloned(); } @@ -1902,14 +2095,16 @@ fn strip_js_nullable(core_type: &CoreType) -> Option { } /// Create React.element type constraint -fn jsx_element_type(config: &JsxConfig, loc: &Location) -> CoreType { +fn jsx_element_type(arena: &mut ParseArena, config: &JsxConfig, loc: &Location) -> CoreType { + let module_str_idx = arena.push_string(config.module_name.clone()); + let element_str_idx = arena.intern_string("element"); CoreType { ptyp_desc: CoreTypeDesc::Ptyp_constr( Loc { - txt: Longident::Ldot( - Box::new(Longident::Lident(config.module_name.clone())), - "element".to_string(), - ), + txt: arena.push_longident(Longident::Ldot( + Box::new(Longident::Lident(module_str_idx)), + element_str_idx, + )), loc: loc.clone(), }, vec![], @@ -1920,9 +2115,9 @@ fn jsx_element_type(config: &JsxConfig, loc: &Location) -> CoreType { } /// Wrap expression with React.element constraint (recursively through function bodies) -fn constrain_jsx_return(expr: Expression, config: &JsxConfig) -> Expression { +fn constrain_jsx_return(arena: &mut ParseArena, expr: Expression, config: &JsxConfig) -> Expression { let loc = &expr.pexp_loc; - let element_type = jsx_element_type(config, loc); + let element_type = jsx_element_type(arena, config, loc); match &expr.pexp_desc { ExpressionDesc::Pexp_fun { arg_label, default, lhs, rhs, arity, is_async } => { @@ -1931,7 +2126,7 @@ fn constrain_jsx_return(expr: Expression, config: &JsxConfig) -> Expression { arg_label: arg_label.clone(), default: default.clone(), lhs: lhs.clone(), - rhs: Box::new(constrain_jsx_return(*rhs.clone(), config)), + rhs: Box::new(constrain_jsx_return(arena, *rhs.clone(), config)), arity: *arity, is_async: *is_async, }, @@ -1943,7 +2138,7 @@ fn constrain_jsx_return(expr: Expression, config: &JsxConfig) -> Expression { Expression { pexp_desc: ExpressionDesc::Pexp_newtype( param.clone(), - Box::new(constrain_jsx_return(*inner.clone(), config)), + Box::new(constrain_jsx_return(arena, *inner.clone(), config)), ), pexp_loc: expr.pexp_loc.clone(), pexp_attributes: expr.pexp_attributes.clone(), @@ -1951,7 +2146,7 @@ fn constrain_jsx_return(expr: Expression, config: &JsxConfig) -> Expression { } ExpressionDesc::Pexp_constraint(inner, _) => { // Already constrained, wrap the inner with jsx element constraint - let constrained = constrain_jsx_return(*inner.clone(), config); + let constrained = constrain_jsx_return(arena, *inner.clone(), config); Expression { pexp_desc: ExpressionDesc::Pexp_constraint(Box::new(constrained), element_type), pexp_loc: expr.pexp_loc.clone(), @@ -1963,7 +2158,7 @@ fn constrain_jsx_return(expr: Expression, config: &JsxConfig) -> Expression { pexp_desc: ExpressionDesc::Pexp_let( *rec_flag, bindings.clone(), - Box::new(constrain_jsx_return(*body.clone(), config)), + Box::new(constrain_jsx_return(arena, *body.clone(), config)), ), pexp_loc: expr.pexp_loc.clone(), pexp_attributes: expr.pexp_attributes.clone(), @@ -1973,7 +2168,7 @@ fn constrain_jsx_return(expr: Expression, config: &JsxConfig) -> Expression { Expression { pexp_desc: ExpressionDesc::Pexp_sequence( first.clone(), - Box::new(constrain_jsx_return(*second.clone(), config)), + Box::new(constrain_jsx_return(arena, *second.clone(), config)), ), pexp_loc: expr.pexp_loc.clone(), pexp_attributes: expr.pexp_attributes.clone(), @@ -2010,18 +2205,21 @@ fn capitalize_first(s: &str) -> String { /// Build module access path: capitalize(module_) + "." + value -> parsed as Longident /// Matches OCaml's module_access_name -fn module_access_name(config: &JsxConfig, value: &str) -> Longident { +fn module_access_name(arena: &mut ParseArena, config: &JsxConfig, value: &str) -> LidentIdx { let capitalized = capitalize_first(&config.module_name); - Longident::Ldot(Box::new(Longident::Lident(capitalized)), value.to_string()) + let cap_str_idx = arena.push_string(capitalized); + let val_str_idx = arena.intern_string(value); + arena.push_longident(Longident::Ldot(Box::new(Longident::Lident(cap_str_idx)), val_str_idx)) } /// Try to find the key prop in a list of JSX props /// Returns the (label, expression) if found -fn try_find_key_prop(props: &[JsxProp]) -> Option<(ArgLabel, Expression)> { +fn try_find_key_prop(arena: &mut ParseArena, props: &[JsxProp]) -> Option<(ArgLabel, Expression)> { for prop in props { match prop { JsxProp::Punning { optional, name } if name.txt == "key" => { - let label_loc = Located::new(name.txt.clone(), name.loc.clone()); + let key_str_idx = arena.intern_string("key"); + let label_loc = Located::new(key_str_idx, name.loc.clone()); let arg_label = if *optional { ArgLabel::Optional(label_loc) } else { @@ -2030,7 +2228,7 @@ fn try_find_key_prop(props: &[JsxProp]) -> Option<(ArgLabel, Expression)> { // OCaml: Exp.ident without ~loc defaults to Location.none (ghost) let expr = Expression { pexp_desc: ExpressionDesc::Pexp_ident(Loc { - txt: Longident::Lident("key".to_string()), + txt: arena.push_longident(Longident::Lident(key_str_idx)), loc: name.loc.clone(), }), pexp_loc: empty_loc(), @@ -2039,7 +2237,8 @@ fn try_find_key_prop(props: &[JsxProp]) -> Option<(ArgLabel, Expression)> { return Some((arg_label, expr)); } JsxProp::Value { name, optional, value } if name.txt == "key" => { - let label_loc = Located::new(name.txt.clone(), name.loc.clone()); + let key_str_idx = arena.intern_string(&name.txt); + let label_loc = Located::new(key_str_idx, name.loc.clone()); let arg_label = if *optional { ArgLabel::Optional(label_loc) } else { @@ -2054,10 +2253,11 @@ fn try_find_key_prop(props: &[JsxProp]) -> Option<(ArgLabel, Expression)> { } /// Create a unit expression () at the given location -fn unit_expr(loc: &Location) -> Expression { +fn unit_expr(arena: &mut ParseArena, loc: &Location) -> Expression { + let unit_str_idx = arena.intern_string("()"); Expression { pexp_desc: ExpressionDesc::Pexp_construct( - Loc { txt: Longident::Lident("()".to_string()), loc: loc.clone() }, + Loc { txt: arena.push_longident(Longident::Lident(unit_str_idx)), loc: loc.clone() }, None, ), pexp_loc: loc.clone(), @@ -2073,9 +2273,9 @@ fn is_labelled(label: &ArgLabel) -> bool { matches!(label, ArgLabel::Labelled(_)) } -fn get_label(label: &ArgLabel) -> String { +fn get_label(arena: &ParseArena, label: &ArgLabel) -> String { match label { - ArgLabel::Labelled(s) | ArgLabel::Optional(s) => s.txt.clone(), + ArgLabel::Labelled(s) | ArgLabel::Optional(s) => arena.get_string(s.txt).to_string(), ArgLabel::Nolabel => String::new(), } } @@ -2086,19 +2286,19 @@ fn empty_loc() -> Location { } /// Recursively extract named arguments from a function expression -fn recursively_extract_named_args(expr: &Expression) -> (Vec, Vec, Option) { +fn recursively_extract_named_args(arena: &ParseArena, expr: &Expression) -> (Vec, Vec, Option) { let mut args = vec![]; let mut newtypes = vec![]; - extract_args_rec(expr, &mut args, &mut newtypes); + extract_args_rec(arena, expr, &mut args, &mut newtypes); (args, newtypes, None) } -fn extract_args_rec(expr: &Expression, args: &mut Vec, newtypes: &mut Vec) { +fn extract_args_rec(arena: &ParseArena, expr: &Expression, args: &mut Vec, newtypes: &mut Vec) { match &expr.pexp_desc { ExpressionDesc::Pexp_fun { arg_label, default, lhs, rhs, .. } => { // Check for key argument - this is an error (OCaml: raise_error) // Key cannot be accessed inside of a component - let label_name = get_label(arg_label); + let label_name = get_label(arena, arg_label); if label_name == "key" { eprintln!( "Key cannot be accessed inside of a component. Don't worry - you can always key a component from its parent! (at {:?})", @@ -2108,18 +2308,22 @@ fn extract_args_rec(expr: &Expression, args: &mut Vec, newtypes: & } // Skip unit argument or Ppat_any, but continue extracting from body - if matches!(&lhs.ppat_desc, PatternDesc::Ppat_construct(loc, _) if loc.txt == Longident::Lident("()".to_string())) - || matches!(&lhs.ppat_desc, PatternDesc::Ppat_any) + let is_unit_pattern = if let PatternDesc::Ppat_construct(loc, _) = &lhs.ppat_desc { + arena.is_lident(loc.txt, "()") + } else { + false + }; + if is_unit_pattern || matches!(&lhs.ppat_desc, PatternDesc::Ppat_any) { if matches!(arg_label, ArgLabel::Nolabel) { // Continue extracting from body even for skipped args (e.g., forwardRef (_, _ref) => ...) - extract_args_rec(rhs, args, newtypes); + extract_args_rec(arena, rhs, args, newtypes); return; } } if is_labelled(arg_label) || is_optional(arg_label) { - let alias = get_alias_from_pattern(lhs, arg_label); + let alias = get_alias_from_pattern(arena, lhs, arg_label); let type_ = get_type_from_pattern(lhs); args.push(ExtractedArg { @@ -2131,10 +2335,10 @@ fn extract_args_rec(expr: &Expression, args: &mut Vec, newtypes: & type_, }); - extract_args_rec(rhs, args, newtypes); + extract_args_rec(arena, rhs, args, newtypes); } else if matches!(arg_label, ArgLabel::Nolabel) { // For forwardRef, capture unlabeled 'ref' or '_ref' argument - let alias = get_alias_from_pattern(lhs, arg_label); + let alias = get_alias_from_pattern(arena, lhs, arg_label); if alias == "ref" || alias == "_ref" { let type_ = get_type_from_pattern(lhs); args.push(ExtractedArg { @@ -2147,27 +2351,27 @@ fn extract_args_rec(expr: &Expression, args: &mut Vec, newtypes: & }); } // Continue extracting from body even for ref - extract_args_rec(rhs, args, newtypes); + extract_args_rec(arena, rhs, args, newtypes); } } ExpressionDesc::Pexp_newtype(name, body) => { newtypes.push(name.clone()); - extract_args_rec(body, args, newtypes); + extract_args_rec(arena, body, args, newtypes); } ExpressionDesc::Pexp_constraint(inner, _) => { - extract_args_rec(inner, args, newtypes); + extract_args_rec(arena, inner, args, newtypes); } _ => {} } } -fn get_alias_from_pattern(pat: &Pattern, label: &ArgLabel) -> String { +fn get_alias_from_pattern(arena: &ParseArena, pat: &Pattern, label: &ArgLabel) -> String { match &pat.ppat_desc { PatternDesc::Ppat_var(loc) => loc.txt.clone(), PatternDesc::Ppat_alias(_, loc) => loc.txt.clone(), - PatternDesc::Ppat_constraint(inner, _) => get_alias_from_pattern(inner, label), + PatternDesc::Ppat_constraint(inner, _) => get_alias_from_pattern(arena, inner, label), PatternDesc::Ppat_any => "_".to_string(), - _ => get_label(label), + _ => get_label(arena, label), } } @@ -2185,8 +2389,8 @@ fn get_type_from_pattern(pat: &Pattern) -> Option { } } -fn arg_to_type(arg: &ExtractedArg) -> Option { - let label = get_label(&arg.label); +fn arg_to_type(arena: &ParseArena, arg: &ExtractedArg) -> Option { + let label = get_label(arena, &arg.label); // For unlabeled arguments (like 'ref' in forwardRef), use the alias as label // Note: "_ref" (underscore-prefixed) means unused ref, should NOT be added to props let label = if label.is_empty() { @@ -2475,7 +2679,7 @@ fn make_props_abstract_type_sig_with_live(name: &str, loc: &Location, manifest: // Config Update // ============================================================================ -fn update_config_from_attribute(attr: &Attribute, config: &mut JsxConfig) { +fn update_config_from_attribute(arena: &ParseArena, attr: &Attribute, config: &mut JsxConfig) { // Parse @@jsxConfig({version: 4, module_: "React"}) // Matches OCaml's update_config behavior if let Payload::PStr(items) = &attr.1 { @@ -2486,7 +2690,9 @@ fn update_config_from_attribute(attr: &Attribute, config: &mut JsxConfig) { let mut version_raw: Option = None; for field in fields { - match field.lid.txt.last() { + let last_idx = arena.get_longident(field.lid.txt).last_idx(); + let last_str = arena.get_string(last_idx); + match last_str { "version" => { if let ExpressionDesc::Pexp_constant(Constant::Integer(s, _)) = &field.expr.pexp_desc { if let Ok(v) = s.parse::() { @@ -2530,67 +2736,72 @@ fn update_config_from_attribute(attr: &Attribute, config: &mut JsxConfig) { // Structure/Signature Item Desc Transformation (for non-component items) // ============================================================================ -fn transform_structure_item_desc(desc: StructureItemDesc, config: &JsxConfig) -> StructureItemDesc { +fn transform_structure_item_desc(desc: StructureItemDesc, config: &JsxConfig, arena: &mut ParseArena) -> StructureItemDesc { match desc { StructureItemDesc::Pstr_value(rec_flag, bindings) => { StructureItemDesc::Pstr_value( rec_flag, - bindings.into_iter().map(|b| transform_value_binding(b, config)).collect(), + bindings.into_iter().map(|b| transform_value_binding(b, config, arena)).collect(), ) } StructureItemDesc::Pstr_eval(expr, attrs) => { - StructureItemDesc::Pstr_eval(transform_expression(expr, config), attrs) + StructureItemDesc::Pstr_eval(transform_expression(expr, config, arena), attrs) } StructureItemDesc::Pstr_module(mb) => { let mut config_clone = config.clone(); - StructureItemDesc::Pstr_module(transform_module_binding(mb, &mut config_clone)) + StructureItemDesc::Pstr_module(transform_module_binding(mb, &mut config_clone, arena)) } StructureItemDesc::Pstr_recmodule(mbs) => { - StructureItemDesc::Pstr_recmodule( - mbs.into_iter().map(|mb| { - let mut config_clone = config.clone(); - transform_module_binding(mb, &mut config_clone) - }).collect() - ) + let mut result = vec![]; + for mb in mbs { + let mut config_clone = config.clone(); + result.push(transform_module_binding(mb, &mut config_clone, arena)); + } + StructureItemDesc::Pstr_recmodule(result) } StructureItemDesc::Pstr_modtype(mt) => { let mut config_clone = config.clone(); - StructureItemDesc::Pstr_modtype(transform_module_type_declaration(mt, &mut config_clone)) + StructureItemDesc::Pstr_modtype(transform_module_type_declaration(mt, &mut config_clone, arena)) } other => other, } } -fn transform_module_type_declaration(mt: ModuleTypeDeclaration, config: &mut JsxConfig) -> ModuleTypeDeclaration { +fn transform_module_type_declaration(mt: ModuleTypeDeclaration, config: &mut JsxConfig, arena: &mut ParseArena) -> ModuleTypeDeclaration { ModuleTypeDeclaration { pmtd_name: mt.pmtd_name, - pmtd_type: mt.pmtd_type.map(|mty| transform_module_type(mty, config)), + pmtd_type: mt.pmtd_type.map(|mty| transform_module_type(mty, config, arena)), pmtd_attributes: mt.pmtd_attributes, pmtd_loc: mt.pmtd_loc, } } -fn transform_module_type(mty: ModuleType, config: &mut JsxConfig) -> ModuleType { +fn transform_module_type(mty: ModuleType, config: &mut JsxConfig, arena: &mut ParseArena) -> ModuleType { ModuleType { pmty_desc: match mty.pmty_desc { ModuleTypeDesc::Pmty_signature(sig_items) => { + // Save and reset has_component (OCaml: config.has_component <- false) + let old_has_component = config.has_component; + config.has_component = false; // Transform signature items let mut result = vec![]; for item in sig_items { - let items = transform_signature_item_multi(item, config); + let items = transform_signature_item_multi(item, config, arena); result.extend(items); } + // Restore has_component + config.has_component = old_has_component; ModuleTypeDesc::Pmty_signature(result) } ModuleTypeDesc::Pmty_functor(name, param, body) => { ModuleTypeDesc::Pmty_functor( name, - param.map(|p| Box::new(transform_module_type(*p, config))), - Box::new(transform_module_type(*body, config)), + param.map(|p| Box::new(transform_module_type(*p, config, arena))), + Box::new(transform_module_type(*body, config, arena)), ) } ModuleTypeDesc::Pmty_with(mty, constraints) => { - ModuleTypeDesc::Pmty_with(Box::new(transform_module_type(*mty, config)), constraints) + ModuleTypeDesc::Pmty_with(Box::new(transform_module_type(*mty, config, arena)), constraints) } other => other, }, @@ -2599,13 +2810,13 @@ fn transform_module_type(mty: ModuleType, config: &mut JsxConfig) -> ModuleType } } -fn transform_signature_item_desc(desc: SignatureItemDesc, config: &mut JsxConfig) -> SignatureItemDesc { +fn transform_signature_item_desc(desc: SignatureItemDesc, config: &mut JsxConfig, arena: &mut ParseArena) -> SignatureItemDesc { match desc { SignatureItemDesc::Psig_module(md) => { // Transform module declaration - recurse into the module type SignatureItemDesc::Psig_module(ModuleDeclaration { pmd_name: md.pmd_name, - pmd_type: transform_module_type(md.pmd_type, config), + pmd_type: transform_module_type(md.pmd_type, config, arena), pmd_attributes: md.pmd_attributes, pmd_loc: md.pmd_loc, }) @@ -2616,7 +2827,7 @@ fn transform_signature_item_desc(desc: SignatureItemDesc, config: &mut JsxConfig mds.into_iter() .map(|md| ModuleDeclaration { pmd_name: md.pmd_name, - pmd_type: transform_module_type(md.pmd_type, config), + pmd_type: transform_module_type(md.pmd_type, config, arena), pmd_attributes: md.pmd_attributes, pmd_loc: md.pmd_loc, }) @@ -2625,49 +2836,56 @@ fn transform_signature_item_desc(desc: SignatureItemDesc, config: &mut JsxConfig } SignatureItemDesc::Psig_modtype(mtd) => { // Transform module type declaration - SignatureItemDesc::Psig_modtype(transform_module_type_declaration(mtd, config)) + SignatureItemDesc::Psig_modtype(transform_module_type_declaration(mtd, config, arena)) } other => other, } } -fn transform_module_binding(mb: ModuleBinding, config: &mut JsxConfig) -> ModuleBinding { +fn transform_module_binding(mb: ModuleBinding, config: &mut JsxConfig, arena: &mut ParseArena) -> ModuleBinding { ModuleBinding { pmb_name: mb.pmb_name, - pmb_expr: transform_module_expr(mb.pmb_expr, config), + pmb_expr: transform_module_expr(mb.pmb_expr, config, arena), pmb_attributes: mb.pmb_attributes, pmb_loc: mb.pmb_loc, } } /// Transform a structure with an existing config (preserves file_name and nested_modules) -fn transform_structure_with_config(structure: Structure, config: &mut JsxConfig) -> Structure { +fn transform_structure_with_config(structure: Structure, config: &mut JsxConfig, arena: &mut ParseArena) -> Structure { + // Save and reset has_component (OCaml: config.has_component <- false) + let old_has_component = config.has_component; + config.has_component = false; + let mut result = vec![]; for item in structure { - let items = transform_structure_item_multi(item, config); + let items = transform_structure_item_multi(item, config, arena); result.extend(items); } + + // Restore has_component + config.has_component = old_has_component; result } -fn transform_module_expr(mexpr: ModuleExpr, config: &mut JsxConfig) -> ModuleExpr { +fn transform_module_expr(mexpr: ModuleExpr, config: &mut JsxConfig, arena: &mut ParseArena) -> ModuleExpr { ModuleExpr { pmod_desc: match mexpr.pmod_desc { ModuleExprDesc::Pmod_structure(items) => { // Transform structure with current config (preserving file_name and nested_modules) - ModuleExprDesc::Pmod_structure(transform_structure_with_config(items, config)) + ModuleExprDesc::Pmod_structure(transform_structure_with_config(items, config, arena)) } ModuleExprDesc::Pmod_functor(name, mtype, body) => { - ModuleExprDesc::Pmod_functor(name, mtype, Box::new(transform_module_expr(*body, config))) + ModuleExprDesc::Pmod_functor(name, mtype, Box::new(transform_module_expr(*body, config, arena))) } ModuleExprDesc::Pmod_apply(m1, m2) => { ModuleExprDesc::Pmod_apply( - Box::new(transform_module_expr(*m1, config)), - Box::new(transform_module_expr(*m2, config)), + Box::new(transform_module_expr(*m1, config, arena)), + Box::new(transform_module_expr(*m2, config, arena)), ) } ModuleExprDesc::Pmod_constraint(m, mt) => { - ModuleExprDesc::Pmod_constraint(Box::new(transform_module_expr(*m, config)), mt) + ModuleExprDesc::Pmod_constraint(Box::new(transform_module_expr(*m, config, arena)), mt) } other => other, }, @@ -2676,10 +2894,10 @@ fn transform_module_expr(mexpr: ModuleExpr, config: &mut JsxConfig) -> ModuleExp } } -fn transform_value_binding(binding: ValueBinding, config: &JsxConfig) -> ValueBinding { +fn transform_value_binding(binding: ValueBinding, config: &JsxConfig, arena: &mut ParseArena) -> ValueBinding { ValueBinding { pvb_pat: binding.pvb_pat, - pvb_expr: transform_expression(binding.pvb_expr, config), + pvb_expr: transform_expression(binding.pvb_expr, config, arena), pvb_attributes: binding.pvb_attributes, pvb_loc: binding.pvb_loc, } @@ -2689,150 +2907,150 @@ fn transform_value_binding(binding: ValueBinding, config: &JsxConfig) -> ValueBi // Expression Transformation // ============================================================================ -fn transform_expression(expr: Expression, config: &JsxConfig) -> Expression { +fn transform_expression(expr: Expression, config: &JsxConfig, arena: &mut ParseArena) -> Expression { let new_desc = match expr.pexp_desc { ExpressionDesc::Pexp_jsx_element(jsx) => { - transform_jsx_element(jsx, config, &expr.pexp_loc, &expr.pexp_attributes) + transform_jsx_element(jsx, config, &expr.pexp_loc, &expr.pexp_attributes, arena) } ExpressionDesc::Pexp_let(rec_flag, bindings, body) => { ExpressionDesc::Pexp_let( rec_flag, - bindings.into_iter().map(|b| transform_value_binding(b, config)).collect(), - Box::new(transform_expression(*body, config)), + bindings.into_iter().map(|b| transform_value_binding(b, config, arena)).collect(), + Box::new(transform_expression(*body, config, arena)), ) } ExpressionDesc::Pexp_fun { arg_label, default, lhs, rhs, is_async, arity } => { ExpressionDesc::Pexp_fun { arg_label, - default: default.map(|d| Box::new(transform_expression(*d, config))), + default: default.map(|d| Box::new(transform_expression(*d, config, arena))), lhs, - rhs: Box::new(transform_expression(*rhs, config)), + rhs: Box::new(transform_expression(*rhs, config, arena)), is_async, arity, } } ExpressionDesc::Pexp_apply { funct, args, partial, transformed_jsx } => { ExpressionDesc::Pexp_apply { - funct: Box::new(transform_expression(*funct, config)), - args: args.into_iter().map(|(lbl, e)| (lbl, transform_expression(e, config))).collect(), + funct: Box::new(transform_expression(*funct, config, arena)), + args: args.into_iter().map(|(lbl, e)| (lbl, transform_expression(e, config, arena))).collect(), partial, transformed_jsx, } } ExpressionDesc::Pexp_match(scrutinee, cases) => { ExpressionDesc::Pexp_match( - Box::new(transform_expression(*scrutinee, config)), - cases.into_iter().map(|c| transform_case(c, config)).collect(), + Box::new(transform_expression(*scrutinee, config, arena)), + cases.into_iter().map(|c| transform_case(c, config, arena)).collect(), ) } ExpressionDesc::Pexp_try(body, cases) => { ExpressionDesc::Pexp_try( - Box::new(transform_expression(*body, config)), - cases.into_iter().map(|c| transform_case(c, config)).collect(), + Box::new(transform_expression(*body, config, arena)), + cases.into_iter().map(|c| transform_case(c, config, arena)).collect(), ) } ExpressionDesc::Pexp_tuple(exprs) => { ExpressionDesc::Pexp_tuple( - exprs.into_iter().map(|e| transform_expression(e, config)).collect() + exprs.into_iter().map(|e| transform_expression(e, config, arena)).collect() ) } ExpressionDesc::Pexp_construct(lid, arg) => { ExpressionDesc::Pexp_construct( lid, - arg.map(|e| Box::new(transform_expression(*e, config))), + arg.map(|e| Box::new(transform_expression(*e, config, arena))), ) } ExpressionDesc::Pexp_variant(label, arg) => { ExpressionDesc::Pexp_variant( label, - arg.map(|e| Box::new(transform_expression(*e, config))), + arg.map(|e| Box::new(transform_expression(*e, config, arena))), ) } ExpressionDesc::Pexp_record(fields, base) => { ExpressionDesc::Pexp_record( fields.into_iter().map(|f| ExpressionRecordField { lid: f.lid, - expr: transform_expression(f.expr, config), + expr: transform_expression(f.expr, config, arena), opt: f.opt, }).collect(), - base.map(|e| Box::new(transform_expression(*e, config))), + base.map(|e| Box::new(transform_expression(*e, config, arena))), ) } ExpressionDesc::Pexp_field(obj, field) => { - ExpressionDesc::Pexp_field(Box::new(transform_expression(*obj, config)), field) + ExpressionDesc::Pexp_field(Box::new(transform_expression(*obj, config, arena)), field) } ExpressionDesc::Pexp_setfield(obj, field, value) => { ExpressionDesc::Pexp_setfield( - Box::new(transform_expression(*obj, config)), + Box::new(transform_expression(*obj, config, arena)), field, - Box::new(transform_expression(*value, config)), + Box::new(transform_expression(*value, config, arena)), ) } ExpressionDesc::Pexp_array(elems) => { ExpressionDesc::Pexp_array( - elems.into_iter().map(|e| transform_expression(e, config)).collect() + elems.into_iter().map(|e| transform_expression(e, config, arena)).collect() ) } ExpressionDesc::Pexp_ifthenelse(cond, then_branch, else_branch) => { ExpressionDesc::Pexp_ifthenelse( - Box::new(transform_expression(*cond, config)), - Box::new(transform_expression(*then_branch, config)), - else_branch.map(|e| Box::new(transform_expression(*e, config))), + Box::new(transform_expression(*cond, config, arena)), + Box::new(transform_expression(*then_branch, config, arena)), + else_branch.map(|e| Box::new(transform_expression(*e, config, arena))), ) } ExpressionDesc::Pexp_sequence(e1, e2) => { ExpressionDesc::Pexp_sequence( - Box::new(transform_expression(*e1, config)), - Box::new(transform_expression(*e2, config)), + Box::new(transform_expression(*e1, config, arena)), + Box::new(transform_expression(*e2, config, arena)), ) } ExpressionDesc::Pexp_while(cond, body) => { ExpressionDesc::Pexp_while( - Box::new(transform_expression(*cond, config)), - Box::new(transform_expression(*body, config)), + Box::new(transform_expression(*cond, config, arena)), + Box::new(transform_expression(*body, config, arena)), ) } ExpressionDesc::Pexp_for(pat, start, end_expr, dir, body) => { ExpressionDesc::Pexp_for( pat, - Box::new(transform_expression(*start, config)), - Box::new(transform_expression(*end_expr, config)), + Box::new(transform_expression(*start, config, arena)), + Box::new(transform_expression(*end_expr, config, arena)), dir, - Box::new(transform_expression(*body, config)), + Box::new(transform_expression(*body, config, arena)), ) } ExpressionDesc::Pexp_constraint(e, t) => { - ExpressionDesc::Pexp_constraint(Box::new(transform_expression(*e, config)), t) + ExpressionDesc::Pexp_constraint(Box::new(transform_expression(*e, config, arena)), t) } ExpressionDesc::Pexp_coerce(e, t1, t2) => { - ExpressionDesc::Pexp_coerce(Box::new(transform_expression(*e, config)), t1, t2) + ExpressionDesc::Pexp_coerce(Box::new(transform_expression(*e, config, arena)), t1, t2) } ExpressionDesc::Pexp_letmodule(name, mexpr, body) => { let mut config_clone = config.clone(); ExpressionDesc::Pexp_letmodule( name, - transform_module_expr(mexpr, &mut config_clone), - Box::new(transform_expression(*body, config)), + transform_module_expr(mexpr, &mut config_clone, arena), + Box::new(transform_expression(*body, config, arena)), ) } ExpressionDesc::Pexp_letexception(ext, body) => { - ExpressionDesc::Pexp_letexception(ext, Box::new(transform_expression(*body, config))) + ExpressionDesc::Pexp_letexception(ext, Box::new(transform_expression(*body, config, arena))) } ExpressionDesc::Pexp_assert(e) => { - ExpressionDesc::Pexp_assert(Box::new(transform_expression(*e, config))) + ExpressionDesc::Pexp_assert(Box::new(transform_expression(*e, config, arena))) } ExpressionDesc::Pexp_newtype(name, body) => { - ExpressionDesc::Pexp_newtype(name, Box::new(transform_expression(*body, config))) + ExpressionDesc::Pexp_newtype(name, Box::new(transform_expression(*body, config, arena))) } ExpressionDesc::Pexp_pack(mexpr) => { let mut config_clone = config.clone(); - ExpressionDesc::Pexp_pack(transform_module_expr(mexpr, &mut config_clone)) + ExpressionDesc::Pexp_pack(transform_module_expr(mexpr, &mut config_clone, arena)) } ExpressionDesc::Pexp_open(flag, lid, body) => { - ExpressionDesc::Pexp_open(flag, lid, Box::new(transform_expression(*body, config))) + ExpressionDesc::Pexp_open(flag, lid, Box::new(transform_expression(*body, config, arena))) } ExpressionDesc::Pexp_await(e) => { - ExpressionDesc::Pexp_await(Box::new(transform_expression(*e, config))) + ExpressionDesc::Pexp_await(Box::new(transform_expression(*e, config, arena))) } other => other, }; @@ -2844,12 +3062,12 @@ fn transform_expression(expr: Expression, config: &JsxConfig) -> Expression { } } -fn transform_case(case: Case, config: &JsxConfig) -> Case { +fn transform_case(case: Case, config: &JsxConfig, arena: &mut ParseArena) -> Case { Case { pc_bar: case.pc_bar, pc_lhs: case.pc_lhs, - pc_guard: case.pc_guard.map(|e| transform_expression(e, config)), - pc_rhs: transform_expression(case.pc_rhs, config), + pc_guard: case.pc_guard.map(|e| transform_expression(e, config, arena)), + pc_rhs: transform_expression(case.pc_rhs, config, arena), } } @@ -2862,16 +3080,17 @@ fn transform_jsx_element( config: &JsxConfig, loc: &Location, attrs: &Attributes, + arena: &mut ParseArena, ) -> ExpressionDesc { match jsx { JsxElement::Fragment(fragment) => { - transform_jsx_fragment(fragment, config, loc, attrs) + transform_jsx_fragment(fragment, config, loc, attrs, arena) } JsxElement::Unary(unary) => { - transform_jsx_unary(unary, config, loc, attrs) + transform_jsx_unary(unary, config, loc, attrs, arena) } JsxElement::Container(container) => { - transform_jsx_container(container, config, loc, attrs) + transform_jsx_container(container, config, loc, attrs, arena) } } } @@ -2880,22 +3099,23 @@ fn transform_jsx_element( fn mk_react_jsx( config: &JsxConfig, loc: &Location, - attrs: &Attributes, + _attrs: &Attributes, component_description: ComponentDescription, element_tag: Expression, props: Vec, children: Vec, + arena: &mut ParseArena, ) -> ExpressionDesc { let more_than_one_children = children.len() > 1; // Append children prop - let props_with_children = append_children_prop(config, component_description, props, children.clone()); + let props_with_children = append_children_prop(config, component_description, props, children.clone(), arena); // Create the props record (filtering out key) - let props_record = mk_record_from_props(loc, &props_with_children, config); + let props_record = mk_record_from_props(loc, &props_with_children, config, arena); // Determine jsx function and key handling - let key_prop = try_find_key_prop(&props_with_children); + let key_prop = try_find_key_prop(arena, &props_with_children); let (jsx_expr, key_and_unit) = { let jsx_part = match &key_prop { @@ -2909,18 +3129,22 @@ fn mk_react_jsx( let jsx_path = match component_description { ComponentDescription::FragmentComponent | ComponentDescription::UppercasedComponent => { - module_access_name(config, jsx_part) + module_access_name(arena, config, jsx_part) } ComponentDescription::LowercasedComponent => { let element_binding = if config.module_name.to_lowercase() == "react" { - Longident::Lident("ReactDOM".to_string()) + let react_dom_idx = arena.intern_string("ReactDOM"); + Longident::Lident(react_dom_idx) } else { + let cap_idx = arena.push_string(capitalize_first(&config.module_name)); + let elements_idx = arena.intern_string("Elements"); Longident::Ldot( - Box::new(Longident::Lident(capitalize_first(&config.module_name))), - "Elements".to_string(), + Box::new(Longident::Lident(cap_idx)), + elements_idx, ) }; - Longident::Ldot(Box::new(element_binding), jsx_part.to_string()) + let jsx_part_idx = arena.intern_string(jsx_part); + arena.push_longident(Longident::Ldot(Box::new(element_binding), jsx_part_idx)) } }; @@ -2937,7 +3161,7 @@ fn mk_react_jsx( Some((label, expr)) => { vec![ (label, expr), - (ArgLabel::Nolabel, unit_expr(&empty_loc())), + (ArgLabel::Nolabel, unit_expr(arena, &empty_loc())), ] } None => vec![], @@ -2968,6 +3192,7 @@ fn append_children_prop( component_description: ComponentDescription, mut props: Vec, children: Vec, + arena: &mut ParseArena, ) -> Vec { if children.is_empty() { return props; @@ -2975,7 +3200,7 @@ fn append_children_prop( if children.len() == 1 { let child = children.into_iter().next().unwrap(); - let transformed_child = transform_expression(child.clone(), config); + let transformed_child = transform_expression(child.clone(), config, arena); // For lowercase components, wrap in ReactDOM.someElement let expr = match component_description { @@ -2984,14 +3209,18 @@ fn append_children_prop( } ComponentDescription::LowercasedComponent => { let element_binding = if config.module_name.to_lowercase() == "react" { - Longident::Lident("ReactDOM".to_string()) + let react_dom_idx = arena.intern_string("ReactDOM"); + Longident::Lident(react_dom_idx) } else { + let cap_idx = arena.push_string(capitalize_first(&config.module_name)); + let elements_idx = arena.intern_string("Elements"); Longident::Ldot( - Box::new(Longident::Lident(capitalize_first(&config.module_name))), - "Elements".to_string(), + Box::new(Longident::Lident(cap_idx)), + elements_idx, ) }; - let some_element_path = Longident::Ldot(Box::new(element_binding), "someElement".to_string()); + let some_element_idx = arena.intern_string("someElement"); + let some_element_path = arena.push_longident(Longident::Ldot(Box::new(element_binding), some_element_idx)); // OCaml: Exp.apply without ~loc uses Location.none (default_loc = ref Location.none) Expression { @@ -3026,12 +3255,10 @@ fn append_children_prop( // Multiple children: wrap in Module.array([...]) // OCaml uses real location spanning all children for outer expressions but ghost for inner synthesized ones let loc = if let (Some(first), Some(last)) = (children.first(), children.last()) { - Location { - loc_start: first.pexp_loc.loc_start.clone(), - loc_end: last.pexp_loc.loc_end.clone(), - loc_ghost: false, - id: crate::location::LocationId::default_id(), - } + // Create composite location spanning from first child start to last child end + let start_idx = arena.loc_start_idx(first.pexp_loc); + let end_idx = arena.loc_end_idx(last.pexp_loc); + arena.mk_loc(start_idx, end_idx) } else { empty_loc() }; @@ -3039,7 +3266,7 @@ fn append_children_prop( // React.array function - uses ghost location for ident, real loc for outer expr let array_fn = Expression { pexp_desc: ExpressionDesc::Pexp_ident(Loc { - txt: module_access_name(config, "array"), + txt: module_access_name(arena, config, "array"), loc: loc.clone(), // OCaml uses the children loc for the longident }), pexp_loc: empty_loc(), // Ghost location for the ident expression itself @@ -3049,7 +3276,7 @@ fn append_children_prop( // Array literal containing children - ghost location let children_array = Expression { pexp_desc: ExpressionDesc::Pexp_array( - children.into_iter().map(|c| transform_expression(c, config)).collect() + children.into_iter().map(|c| transform_expression(c, config, arena)).collect() ), pexp_loc: empty_loc(), // Ghost location for the array pexp_attributes: vec![], @@ -3077,19 +3304,16 @@ fn append_children_prop( } /// Get location from a JSX prop -fn loc_from_prop(prop: &JsxProp) -> Location { +fn loc_from_prop(prop: &JsxProp, arena: &mut ParseArena) -> Location { match prop { - JsxProp::Punning { name, .. } => name.loc.clone(), + JsxProp::Punning { name, .. } => name.loc, JsxProp::Value { name, value, .. } => { // Location spans from name start to value end - Location { - loc_start: name.loc.loc_start.clone(), - loc_end: value.pexp_loc.loc_end.clone(), - loc_ghost: false, - id: LocationId::default_id(), - } + let start_idx = arena.loc_start_idx(name.loc); + let end_idx = arena.loc_end_idx(value.pexp_loc); + arena.mk_loc(start_idx, end_idx) } - JsxProp::Spreading { loc, .. } => loc.clone(), + JsxProp::Spreading { loc, .. } => *loc, } } @@ -3098,19 +3322,18 @@ fn mk_record_from_props( jsx_expr_loc: &Location, props: &[JsxProp], config: &JsxConfig, + arena: &mut ParseArena, ) -> Expression { // Calculate location from ALL props (including key) - OCaml does this before filtering let loc = if props.is_empty() { - jsx_expr_loc.clone() + *jsx_expr_loc } else { - let first = loc_from_prop(&props[0]); - let last = loc_from_prop(props.last().unwrap()); - Location { - loc_start: first.loc_start, - loc_end: last.loc_end, - loc_ghost: false, - id: LocationId::default_id(), - } + let first = loc_from_prop(&props[0], arena); + let last = loc_from_prop(props.last().unwrap(), arena); + // Create composite location from first to last + let start_idx = arena.loc_start_idx(first); + let end_idx = arena.loc_end_idx(last); + arena.mk_loc(start_idx, end_idx) }; // Filter out key prop AFTER calculating location @@ -3125,7 +3348,7 @@ fn mk_record_from_props( let (regular_props, spread_base) = { let mut props_iter = props.into_iter().peekable(); let spread_base = if let Some(JsxProp::Spreading { expr, .. }) = props_iter.peek() { - let spread = transform_expression(expr.clone(), config); + let spread = transform_expression(expr.clone(), config, arena); props_iter.next(); // consume the spread Some(Box::new(spread)) } else { @@ -3141,14 +3364,16 @@ fn mk_record_from_props( .filter_map(|prop| { match prop { JsxProp::Punning { optional, name } => { + let name_str_idx = arena.push_string(name.txt.clone()); + let name_str_idx2 = arena.push_string(name.txt.clone()); Some(ExpressionRecordField { lid: Loc { - txt: Longident::Lident(name.txt.clone()), + txt: arena.push_longident(Longident::Lident(name_str_idx)), loc: name.loc.clone(), }, expr: Expression { pexp_desc: ExpressionDesc::Pexp_ident(Loc { - txt: Longident::Lident(name.txt.clone()), + txt: arena.push_longident(Longident::Lident(name_str_idx2)), loc: name.loc.clone(), }), pexp_loc: name.loc.clone(), @@ -3158,12 +3383,13 @@ fn mk_record_from_props( }) } JsxProp::Value { name, optional, value } => { + let name_str_idx = arena.push_string(name.txt.clone()); Some(ExpressionRecordField { lid: Loc { - txt: Longident::Lident(name.txt.clone()), + txt: arena.push_longident(Longident::Lident(name_str_idx)), loc: name.loc.clone(), }, - expr: transform_expression(value.clone(), config), + expr: transform_expression(value.clone(), config, arena), opt: *optional, }) } @@ -3201,13 +3427,14 @@ fn transform_jsx_fragment( config: &JsxConfig, loc: &Location, attrs: &Attributes, + arena: &mut ParseArena, ) -> ExpressionDesc { let children = fragment.children; // Fragment expression: React.jsxFragment (or Module.jsxFragment) let fragment_expr = Expression { pexp_desc: ExpressionDesc::Pexp_ident(Loc { - txt: module_access_name(config, "jsxFragment"), + txt: module_access_name(arena, config, "jsxFragment"), loc: loc.clone(), }), pexp_loc: loc.clone(), @@ -3223,6 +3450,7 @@ fn transform_jsx_fragment( fragment_expr, vec![], // No props for fragments children, + arena, ) } @@ -3231,6 +3459,7 @@ fn transform_jsx_unary( config: &JsxConfig, loc: &Location, attrs: &Attributes, + arena: &mut ParseArena, ) -> ExpressionDesc { let tag_loc = &unary.tag_name.loc; match &unary.tag_name.txt { @@ -3249,13 +3478,15 @@ fn transform_jsx_unary( component_name_expr, unary.props, vec![], + arena, ) } JsxTagName::Upper(path) => { // Uppercase element like -> MyModule.make + let make_str_idx = arena.intern_string("make"); let make_id = Expression { pexp_desc: ExpressionDesc::Pexp_ident(Loc { - txt: Longident::Ldot(Box::new(path.clone()), "make".to_string()), + txt: arena.push_longident(Longident::Ldot(Box::new(arena.get_longident(*path).clone()), make_str_idx)), loc: tag_loc.clone(), }), pexp_loc: tag_loc.clone(), @@ -3269,13 +3500,15 @@ fn transform_jsx_unary( make_id, unary.props, vec![], + arena, ) } JsxTagName::QualifiedLower { path, name } => { // Qualified lowercase like -> MyModule.lowercase + let name_str_idx = arena.push_string(name.clone()); let make_id = Expression { pexp_desc: ExpressionDesc::Pexp_ident(Loc { - txt: Longident::Ldot(Box::new(path.clone()), name.clone()), + txt: arena.push_longident(Longident::Ldot(Box::new(arena.get_longident(*path).clone()), name_str_idx)), loc: tag_loc.clone(), }), pexp_loc: tag_loc.clone(), @@ -3289,6 +3522,7 @@ fn transform_jsx_unary( make_id, unary.props, vec![], + arena, ) } JsxTagName::Invalid(name) => { @@ -3303,6 +3537,7 @@ fn transform_jsx_container( config: &JsxConfig, loc: &Location, attrs: &Attributes, + arena: &mut ParseArena, ) -> ExpressionDesc { let tag_loc = &container.tag_name_start.loc; match &container.tag_name_start.txt { @@ -3321,13 +3556,15 @@ fn transform_jsx_container( component_name_expr, container.props, container.children, + arena, ) } JsxTagName::Upper(path) => { // Uppercase element like ... -> MyModule.make + let make_str_idx = arena.intern_string("make"); let make_id = Expression { pexp_desc: ExpressionDesc::Pexp_ident(Loc { - txt: Longident::Ldot(Box::new(path.clone()), "make".to_string()), + txt: arena.push_longident(Longident::Ldot(Box::new(arena.get_longident(*path).clone()), make_str_idx)), loc: tag_loc.clone(), }), pexp_loc: tag_loc.clone(), @@ -3341,13 +3578,15 @@ fn transform_jsx_container( make_id, container.props, container.children, + arena, ) } JsxTagName::QualifiedLower { path, name } => { // Qualified lowercase like ... + let name_str_idx = arena.push_string(name.clone()); let make_id = Expression { pexp_desc: ExpressionDesc::Pexp_ident(Loc { - txt: Longident::Ldot(Box::new(path.clone()), name.clone()), + txt: arena.push_longident(Longident::Ldot(Box::new(arena.get_longident(*path).clone()), name_str_idx)), loc: tag_loc.clone(), }), pexp_loc: tag_loc.clone(), @@ -3361,6 +3600,7 @@ fn transform_jsx_container( make_id, container.props, container.children, + arena, ) } JsxTagName::Invalid(name) => { diff --git a/compiler-rust/src/parser/longident.rs b/compiler-rust/src/parser/longident.rs index d08ebeba632..db425102dfb 100644 --- a/compiler-rust/src/parser/longident.rs +++ b/compiler-rust/src/parser/longident.rs @@ -2,30 +2,38 @@ //! //! This module defines `Longident`, which represents dotted identifiers //! like `Foo.Bar.baz`. It mirrors `Longident.t` from OCaml. +//! +//! Strings are stored as `StrIdx` indices into a string arena, enabling: +//! - Efficient storage (4 bytes per string reference) +//! - Identity-based sharing during marshalling (same StrIdx = same object) +use crate::intern::StrIdx; use crate::location::Location; use serde::{Deserialize, Serialize}; /// A long identifier, representing a dotted path like `Foo.Bar.baz`. +/// +/// Strings are stored as `StrIdx` indices into the arena's string interner. +/// This enables efficient sharing during marshalling: same StrIdx = same object. #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum Longident { /// A simple identifier: `foo` - Lident(String), + Lident(StrIdx), /// A dotted path: `Foo.bar` is `Ldot(Lident("Foo"), "bar")` - Ldot(Box, String), + Ldot(Box, StrIdx), /// An application (for functors): `F(X)` is `Lapply(Lident("F"), Lident("X"))` Lapply(Box, Box), } impl Longident { - /// Create a simple identifier. - pub fn lident(name: impl Into) -> Self { - Longident::Lident(name.into()) + /// Create a simple identifier from a StrIdx. + pub fn lident(name: StrIdx) -> Self { + Longident::Lident(name) } - /// Create a dotted identifier. - pub fn ldot(prefix: Longident, name: impl Into) -> Self { - Longident::Ldot(Box::new(prefix), name.into()) + /// Create a dotted identifier from a StrIdx. + pub fn ldot(prefix: Longident, name: StrIdx) -> Self { + Longident::Ldot(Box::new(prefix), name) } /// Create a functor application. @@ -33,35 +41,25 @@ impl Longident { Longident::Lapply(Box::new(functor), Box::new(arg)) } - /// Parse a string like "Foo.Bar.baz" into a Longident. - pub fn parse(s: &str) -> Self { - let parts: Vec<&str> = s.split('.').collect(); - let mut result = Longident::Lident(parts[0].to_string()); - for part in &parts[1..] { - result = Longident::Ldot(Box::new(result), (*part).to_string()); - } - result - } - - /// Get the last component of the identifier. - pub fn last(&self) -> &str { + /// Get the last component's StrIdx. + pub fn last_idx(&self) -> StrIdx { match self { - Longident::Lident(s) => s, - Longident::Ldot(_, s) => s, - Longident::Lapply(_, arg) => arg.last(), + Longident::Lident(s) => *s, + Longident::Ldot(_, s) => *s, + Longident::Lapply(_, arg) => arg.last_idx(), } } - /// Flatten to a list of strings. - pub fn flatten(&self) -> Vec<&str> { + /// Flatten to a list of StrIdx. + pub fn flatten_idx(&self) -> Vec { match self { - Longident::Lident(s) => vec![s.as_str()], + Longident::Lident(s) => vec![*s], Longident::Ldot(prefix, s) => { - let mut v = prefix.flatten(); - v.push(s.as_str()); + let mut v = prefix.flatten_idx(); + v.push(*s); v } - Longident::Lapply(f, _) => f.flatten(), + Longident::Lapply(f, _) => f.flatten_idx(), } } @@ -72,10 +70,11 @@ impl Longident { } impl std::fmt::Display for Longident { + /// Display shows StrIdx values. For actual string content, use arena lookup. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - Longident::Lident(s) => write!(f, "{}", s), - Longident::Ldot(prefix, s) => write!(f, "{}.{}", prefix, s), + Longident::Lident(s) => write!(f, "Lident(#{})", s.raw()), + Longident::Ldot(prefix, s) => write!(f, "{}.#{}", prefix, s.raw()), Longident::Lapply(func, arg) => write!(f, "{}({})", func, arg), } } @@ -92,41 +91,52 @@ pub fn mkloc(lid: Longident, loc: Location) -> LongidentLoc { #[cfg(test)] mod tests { use super::*; + use crate::intern::Interner; #[test] fn test_lident() { - let lid = Longident::lident("foo"); - assert_eq!(lid.last(), "foo"); + let mut interner = Interner::new(); + let foo_idx = interner.intern("foo"); + let lid = Longident::lident(foo_idx); + assert_eq!(lid.last_idx(), foo_idx); assert!(lid.is_simple()); - assert_eq!(lid.to_string(), "foo"); + assert_eq!(interner.get(lid.last_idx()), "foo"); } #[test] fn test_ldot() { - let lid = Longident::ldot(Longident::lident("Foo"), "bar"); - assert_eq!(lid.last(), "bar"); + let mut interner = Interner::new(); + let foo_idx = interner.intern("Foo"); + let bar_idx = interner.intern("bar"); + let lid = Longident::ldot(Longident::lident(foo_idx), bar_idx); + assert_eq!(lid.last_idx(), bar_idx); assert!(!lid.is_simple()); - assert_eq!(lid.to_string(), "Foo.bar"); - } - - #[test] - fn test_parse() { - let lid = Longident::parse("Foo.Bar.baz"); - assert_eq!(lid.last(), "baz"); - assert_eq!(lid.to_string(), "Foo.Bar.baz"); - assert_eq!(lid.flatten(), vec!["Foo", "Bar", "baz"]); } #[test] fn test_lapply() { - let lid = Longident::lapply(Longident::lident("F"), Longident::lident("X")); - assert_eq!(lid.to_string(), "F(X)"); + let mut interner = Interner::new(); + let f_idx = interner.intern("F"); + let x_idx = interner.intern("X"); + let lid = Longident::lapply(Longident::lident(f_idx), Longident::lident(x_idx)); + assert!(!lid.is_simple()); } #[test] - fn test_display() { - let lid = Longident::parse("Array.map"); - assert_eq!(format!("{}", lid), "Array.map"); + fn test_flatten() { + let mut interner = Interner::new(); + let foo_idx = interner.intern("Foo"); + let bar_idx = interner.intern("Bar"); + let baz_idx = interner.intern("baz"); + let lid = Longident::ldot( + Longident::ldot(Longident::lident(foo_idx), bar_idx), + baz_idx, + ); + let indices = lid.flatten_idx(); + assert_eq!(indices.len(), 3); + assert_eq!(interner.get(indices[0]), "Foo"); + assert_eq!(interner.get(indices[1]), "Bar"); + assert_eq!(interner.get(indices[2]), "baz"); } #[test] diff --git a/compiler-rust/src/parser/ml_printer.rs b/compiler-rust/src/parser/ml_printer.rs index 6b5aa7bace5..8a253774bab 100644 --- a/compiler-rust/src/parser/ml_printer.rs +++ b/compiler-rust/src/parser/ml_printer.rs @@ -6,10 +6,39 @@ use std::io::Write; -use crate::location::Located; +use crate::parse_arena::{LidentIdx, Located, ParseArena}; use super::ast::*; use super::formatter::{BoxKind, Formatter}; use super::longident::Longident; +use super::parsetree_viewer; + +// ============================================================================ +// Print context (matching OCaml's pprintast ctxt) +// ============================================================================ + +/// Context for expression printing, matching OCaml's pprintast `ctxt` type. +/// Determines when extra parentheses are needed for disambiguation. +#[derive(Debug, Clone, Copy, Default)] +struct PrintCtx { + pipe: bool, + semi: bool, + ifthenelse: bool, +} + +impl PrintCtx { + fn reset() -> Self { + Self { pipe: false, semi: false, ifthenelse: false } + } + fn under_pipe(self) -> Self { + Self { pipe: true, ..self } + } + fn under_semi(self) -> Self { + Self { semi: true, ..self } + } + fn under_ifthenelse(self) -> Self { + Self { ifthenelse: true, ..self } + } +} // ============================================================================ // Helper functions @@ -35,13 +64,21 @@ fn pattern_is_simple_var(pat: &Pattern, name: &str) -> bool { } /// Check if pattern needs parens when used as a function parameter -fn pattern_needs_parens_as_param(pat: &Pattern) -> bool { +fn pattern_needs_parens_as_param(pat: &Pattern, arena: &ParseArena) -> bool { match &pat.ppat_desc { PatternDesc::Ppat_construct(lid, arg) => { - match &lid.txt { + match arena.get_longident(lid.txt) { // () and [] don't need parens, but :: with args does - Longident::Lident(name) if name == "()" || name == "[]" => false, - Longident::Lident(name) if name == "::" => arg.is_some(), + Longident::Lident(name_idx) => { + let name = arena.get_string(*name_idx); + if name == "()" || name == "[]" { + false + } else if name == "::" { + arg.is_some() + } else { + true + } + } _ => true, } } @@ -52,6 +89,48 @@ fn pattern_needs_parens_as_param(pat: &Pattern) -> bool { } } +/// Check if a pattern is "simple" according to OCaml's pprintast. +/// Simple patterns can appear as arguments to variants/constructors without parens. +/// Based on pprintast.ml's simple_pattern function. +fn pattern_is_simple(pat: &Pattern, arena: &ParseArena) -> bool { + // In OCaml, simple_pattern delegates to pattern when attributes are present. + // pattern adds ((...)attrs) wrapping, so no extra parens needed. + if !pat.ppat_attributes.is_empty() { + return true; + } + match &pat.ppat_desc { + // These are all handled directly by simple_pattern: + PatternDesc::Ppat_any => true, + PatternDesc::Ppat_var(_) => true, + PatternDesc::Ppat_array(_) => true, + PatternDesc::Ppat_unpack(_) => true, + PatternDesc::Ppat_type(_) => true, + PatternDesc::Ppat_record(_, _) => true, + PatternDesc::Ppat_tuple(_) => true, + PatternDesc::Ppat_constant(_) => true, + PatternDesc::Ppat_interval(_, _) => true, + PatternDesc::Ppat_variant(_, None) => true, // Only variant without arg + PatternDesc::Ppat_constraint(_, _) => true, + PatternDesc::Ppat_exception(_) => true, + PatternDesc::Ppat_extension(_) => true, + PatternDesc::Ppat_open(_, _) => true, + PatternDesc::Ppat_construct(lid, _) => { + // () and [] are simple, others are not + match arena.get_longident(lid.txt) { + Longident::Lident(name_idx) => { + let name = arena.get_string(*name_idx); + name == "()" || name == "[]" + } + _ => false, + } + } + // These are NOT simple - need parens: + PatternDesc::Ppat_alias(_, _) => false, + PatternDesc::Ppat_or(_, _) => false, + PatternDesc::Ppat_variant(_, Some(_)) => false, + } +} + /// Check if a payload is empty (empty PStr) fn payload_is_empty(payload: &Payload) -> bool { matches!(payload, Payload::PStr(items) if items.is_empty()) @@ -66,9 +145,10 @@ fn constant_is_negative(c: &Constant) -> bool { } /// Check if a pattern is a cons pattern (::) -fn is_cons_pattern(p: &Pattern) -> bool { +fn is_cons_pattern(p: &Pattern, arena: &ParseArena) -> bool { if let PatternDesc::Ppat_construct(lid, _) = &p.ppat_desc { - if let Longident::Lident(name) = &lid.txt { + if let Longident::Lident(name_idx) = arena.get_longident(lid.txt) { + let name = arena.get_string(*name_idx); return name == "::"; } } @@ -110,10 +190,10 @@ fn ident_needs_parens(name: &str) -> bool { } /// Get operator name if expression is an identifier that is an operator -fn get_operator_name(expr: &Expression) -> Option<&str> { +fn get_operator_name<'a>(expr: &Expression, arena: &'a ParseArena) -> Option<&'a str> { match &expr.pexp_desc { - ExpressionDesc::Pexp_ident(lid) => match &lid.txt { - Longident::Lident(name) => Some(name.as_str()), + ExpressionDesc::Pexp_ident(lid) => match arena.get_longident(lid.txt) { + Longident::Lident(name_idx) => Some(arena.get_string(*name_idx)), _ => None, }, _ => None, @@ -137,10 +217,10 @@ fn needs_parens_in_binary_context(expr: &Expression) -> bool { } /// Check if expression is an infix operator application -fn is_infix_application(expr: &Expression) -> bool { +fn is_infix_application(expr: &Expression, arena: &ParseArena) -> bool { if let ExpressionDesc::Pexp_apply { funct, args, .. } = &expr.pexp_desc { if args.len() == 2 { - if let Some(op_name) = get_operator_name(funct) { + if let Some(op_name) = get_operator_name(funct, arena) { return is_infix_operator(op_name); } } @@ -149,10 +229,10 @@ fn is_infix_application(expr: &Expression) -> bool { } /// Check if expression is a prefix operator application -fn is_prefix_application(expr: &Expression) -> bool { +fn is_prefix_application(expr: &Expression, arena: &ParseArena) -> bool { if let ExpressionDesc::Pexp_apply { funct, args, .. } = &expr.pexp_desc { if args.len() == 1 { - if let Some(op_name) = get_operator_name(funct) { + if let Some(op_name) = get_operator_name(funct, arena) { return is_prefix_operator(op_name); } } @@ -170,16 +250,16 @@ fn application_has_labeled_args(expr: &Expression) -> bool { } /// Check if expression needs parens when used as a labeled argument value -fn needs_parens_as_labeled_arg(expr: &Expression) -> bool { - if is_prefix_application(expr) { +fn needs_parens_as_labeled_arg(expr: &Expression, arena: &ParseArena) -> bool { + if is_prefix_application(expr, arena) { return false; } - needs_parens_in_binary_context(expr) || is_infix_application(expr) + needs_parens_in_binary_context(expr) || is_infix_application(expr, arena) } /// Check if expression needs parens when used as an unlabeled function argument -fn needs_parens_as_function_arg(expr: &Expression) -> bool { - if is_prefix_application(expr) { +fn needs_parens_as_function_arg(expr: &Expression, arena: &ParseArena) -> bool { + if is_prefix_application(expr, arena) { return false; } needs_parens_in_binary_context(expr) || application_has_labeled_args(expr) @@ -190,7 +270,35 @@ fn expression_has_own_parens(expr: &Expression) -> bool { matches!(&expr.pexp_desc, ExpressionDesc::Pexp_assert(_)) } +/// Check if a Pexp_construct is a "simple construct" (like OCaml's is_simple_construct) +/// This includes: [], (), complete lists [a; b; c], and simple constructors without args +fn is_simple_construct(expr: &Expression, arena: &ParseArena) -> bool { + if !expr.pexp_attributes.is_empty() { + return false; + } + match &expr.pexp_desc { + ExpressionDesc::Pexp_construct(lid, None) => { + // () and [] and simple constructors are simple + true + } + ExpressionDesc::Pexp_construct(lid, Some(_)) => { + // Check if it's a complete list (ends with []) + if let Longident::Lident(name_idx) = arena.get_longident(lid.txt) { + let name = arena.get_string(*name_idx); + if name == "::" { + let (_, is_complete) = collect_list_elements(expr, arena); + return is_complete; + } + } + false + } + _ => false, + } +} + /// Check if expression is "simple" - doesn't need parens +/// Note: This version doesn't have arena access, so it can't check complete lists. +/// Use is_simple_expression_with_arena for full checking. fn is_simple_expression(expr: &Expression) -> bool { if !expr.pexp_attributes.is_empty() { return false; @@ -207,14 +315,47 @@ fn is_simple_expression(expr: &Expression) -> bool { | ExpressionDesc::Pexp_variant(_, None) | ExpressionDesc::Pexp_construct(_, None) | ExpressionDesc::Pexp_pack(_) - | ExpressionDesc::Pexp_field(_, _) // Field access is simple + // NOTE: Pexp_field and Pexp_send are NOT simple in OCaml's pprintast. + // They are in expression2, which means they need parens when nested. + // See expression2 vs simple_expr in pprintast.ml // OCaml's simple_expr handles these directly (no paren wrapping) | ExpressionDesc::Pexp_for(_, _, _, _, _) | ExpressionDesc::Pexp_while(_, _) + | ExpressionDesc::Pexp_jsx_element(_) // JSX elements are simple + ) +} + +/// Check if expression is "simple" - doesn't need parens (with arena for complete list checking) +fn is_simple_expression_with_arena(expr: &Expression, arena: &ParseArena) -> bool { + if !expr.pexp_attributes.is_empty() { + return false; + } + // Check for simple constructs first (handles complete lists) + if is_simple_construct(expr, arena) { + return true; + } + matches!( + &expr.pexp_desc, + ExpressionDesc::Pexp_ident(_) + | ExpressionDesc::Pexp_constant(_) + | ExpressionDesc::Pexp_tuple(_) + | ExpressionDesc::Pexp_array(_) + | ExpressionDesc::Pexp_record(_, _) + | ExpressionDesc::Pexp_constraint(_, _) + | ExpressionDesc::Pexp_coerce(_, _, _) + | ExpressionDesc::Pexp_variant(_, None) + | ExpressionDesc::Pexp_pack(_) + // NOTE: Pexp_field and Pexp_send are NOT simple in OCaml's pprintast. + // They are in expression2, which means they need parens when nested. + // OCaml's simple_expr handles these directly (no paren wrapping) + | ExpressionDesc::Pexp_for(_, _, _, _, _) + | ExpressionDesc::Pexp_while(_, _) + | ExpressionDesc::Pexp_jsx_element(_) // JSX elements are simple in OCaml ) } /// Check if expression needs parens in "semi" context (array/list elements) +/// OCaml: when ctxt.semi is true and expr is Pexp_fun/match/try/sequence, wrap in parens fn needs_parens_in_semi_context(expr: &Expression) -> bool { matches!( &expr.pexp_desc, @@ -225,9 +366,51 @@ fn needs_parens_in_semi_context(expr: &Expression) -> bool { ) } +/// Check if expression needs parens in "pipe" context (match case RHS) +/// OCaml: when ctxt.pipe is true and expr is Pexp_fun/match/try/sequence, wrap in parens +/// This is the same set of expressions as semi context +fn needs_parens_in_pipe_context(expr: &Expression) -> bool { + matches!( + &expr.pexp_desc, + ExpressionDesc::Pexp_fun { .. } + | ExpressionDesc::Pexp_match(_, _) + | ExpressionDesc::Pexp_try(_, _) + | ExpressionDesc::Pexp_sequence(_, _) + ) +} + +/// Check if expression needs parens in "ifthenelse" context +/// OCaml: when ctxt.ifthenelse is true and expr is Pexp_ifthenelse/Pexp_sequence, wrap in parens +fn needs_parens_in_ifthenelse_context(expr: &Expression) -> bool { + matches!( + &expr.pexp_desc, + ExpressionDesc::Pexp_ifthenelse(_, _, _) + | ExpressionDesc::Pexp_sequence(_, _) + ) +} + +/// Check if expression is "expression2" level - includes Pexp_field and Pexp_send +/// These don't need parens when used as binary operands or function arguments. +/// OCaml's pprintast.ml: expression2 handles Pexp_field and Pexp_send directly, +/// then falls through to simple_expr for other cases. +fn is_expression2(expr: &Expression, arena: &ParseArena) -> bool { + if !expr.pexp_attributes.is_empty() { + // Attributed expressions need to go through full expression printing + return false; + } + // Expression2 includes field and send expressions + if matches!(&expr.pexp_desc, ExpressionDesc::Pexp_field(_, _) | ExpressionDesc::Pexp_send(_, _)) { + return true; + } + // Plus everything that's simple + is_simple_expression_with_arena(expr, arena) +} + /// Check if an attribute is internal and should not be printed fn is_internal_attribute(name: &str) -> bool { - matches!(name, "res.await" | "res.array.access") + // Note: "res.await" IS printed (it's the AST marker for await modules) + // "res.array.access" is internal and should not be printed + matches!(name, "res.array.access") } /// Filter attributes to only include ones that should be printed @@ -244,7 +427,7 @@ fn has_attribute(attrs: &[(Located, Payload)], name: &str) -> bool { } /// Collect list elements from a cons pattern -fn collect_list_elements(expr: &Expression) -> (Vec<&Expression>, bool) { +fn collect_list_elements<'a>(expr: &'a Expression, arena: &ParseArena) -> (Vec<&'a Expression>, bool) { let mut elements = Vec::new(); let mut current = expr; @@ -256,7 +439,8 @@ fn collect_list_elements(expr: &Expression) -> (Vec<&Expression>, bool) { match ¤t.pexp_desc { ExpressionDesc::Pexp_construct(lid, None) => { - if let Longident::Lident(name) = &lid.txt { + if let Longident::Lident(name_idx) = arena.get_longident(lid.txt) { + let name = arena.get_string(*name_idx); if name == "[]" { return (elements, true); } @@ -265,7 +449,8 @@ fn collect_list_elements(expr: &Expression) -> (Vec<&Expression>, bool) { return (elements, false); } ExpressionDesc::Pexp_construct(lid, Some(arg)) => { - if let Longident::Lident(name) = &lid.txt { + if let Longident::Lident(name_idx) = arena.get_longident(lid.txt) { + let name = arena.get_string(*name_idx); if name == "::" { if let ExpressionDesc::Pexp_tuple(items) = &arg.pexp_desc { if items.len() == 2 && arg.pexp_attributes.is_empty() { @@ -288,15 +473,26 @@ fn collect_list_elements(expr: &Expression) -> (Vec<&Expression>, bool) { } fn escape_string(s: &str) -> String { + // The source was read as Latin-1 (each byte became a char with code point 0-255). + // We need to escape characters with code points > 127 using decimal escape sequences + // like \226\156\133, matching OCaml's default string escaping behavior. + // We iterate over CHARACTERS (not bytes) since each char IS the original byte value. let mut result = String::new(); - for c in s.chars() { - match c { - '\n' => result.push_str("\\n"), - '\r' => result.push_str("\\r"), - '\t' => result.push_str("\\t"), - '\\' => result.push_str("\\\\"), - '"' => result.push_str("\\\""), - c => result.push(c), + for ch in s.chars() { + let code = ch as u32; + match code { + 0x0A => result.push_str("\\n"), // newline + 0x0D => result.push_str("\\r"), // carriage return + 0x09 => result.push_str("\\t"), // tab + 0x5C => result.push_str("\\\\"), // backslash + 0x22 => result.push_str("\\\""), // double quote + 0x20..=0x7E => result.push(ch), // Printable ASCII + _ => { + // Non-ASCII or non-printable: use decimal escape + // Code point IS the original byte value (0-255) due to Latin-1 reading + result.push('\\'); + result.push_str(&code.to_string()); + } } } result @@ -307,29 +503,25 @@ fn escape_string(s: &str) -> String { // ============================================================================ /// Print structure in ML format (like Pprintast in OCaml) -pub fn print_structure_ml(structure: &Structure, out: &mut impl Write) { +pub fn print_structure_ml(structure: &Structure, arena: &ParseArena, out: &mut impl Write) { let mut f = Formatter::new(out); for (i, item) in structure.iter().enumerate() { if i > 0 { f.newline(); } - print_structure_item(&mut f, item); + print_structure_item(&mut f, arena, item); } f.flush(); } /// Print signature in ML format -pub fn print_signature_ml(signature: &[SignatureItem], out: &mut impl Write) { +pub fn print_signature_ml(signature: &[SignatureItem], arena: &ParseArena, out: &mut impl Write) { let mut f = Formatter::new(out); for (i, item) in signature.iter().enumerate() { if i > 0 { - f.space(); + f.newline(); // Top-level items on separate lines } - print_signature_item(&mut f, item); - } - // Only add trailing newline if there are items - if !signature.is_empty() { - f.newline(); + print_signature_item(&mut f, arena, item); } f.flush(); } @@ -338,12 +530,15 @@ pub fn print_signature_ml(signature: &[SignatureItem], out: &mut impl Write) { // Structure items // ============================================================================ -fn print_structure_item(f: &mut Formatter, item: &StructureItem) { +fn print_structure_item(f: &mut Formatter, arena: &ParseArena, item: &StructureItem) { match &item.pstr_desc { StructureItemDesc::Pstr_eval(expr, attrs) => { + // OCaml: pp f "@[;;%a@]%a" + f.open_box(BoxKind::HOV, 2); f.string(";;"); - print_expression_no_outer_parens(f, expr); - print_item_attributes(f, attrs); + print_expression_no_outer_parens(f, arena, expr); + f.close_box(); + print_item_attributes(f, arena, attrs); } StructureItemDesc::Pstr_value(rec_flag, bindings) => { let rec_str = match rec_flag { @@ -354,90 +549,232 @@ fn print_structure_item(f: &mut Formatter, item: &StructureItem) { if i > 0 { f.newline(); } - f.open_box(BoxKind::HOV, 2); + // OCaml: @[<2>%s %a%a@]%a + f.open_box(BoxKind::Box, 2); if i > 0 { f.string("and "); } else { f.string(rec_str); } - print_value_binding(f, &binding.pvb_pat, &binding.pvb_expr); - // Value binding attributes - print_item_attributes(f, &binding.pvb_attributes); + print_value_binding(f, arena, &binding.pvb_pat, &binding.pvb_expr); f.close_box(); + // Item attributes are OUTSIDE the box in OCaml + print_item_attributes(f, arena, &binding.pvb_attributes); } } StructureItemDesc::Pstr_primitive(vd) => { + // OCaml: pp f "@[external@ %a@ :@ %a@]%a" f.open_box(BoxKind::HOV, 2); - f.string("external "); + f.string("external"); + f.space(); f.string(&vd.pval_name.txt); - f.string(" : "); - print_core_type(f, &vd.pval_type); - for prim in &vd.pval_prim { - f.string(" = \""); - f.string(prim); - f.string("\""); + f.space(); + f.string(":"); + f.space(); + // OCaml value_description: pp f "@[%a%a@]" + // where %a%a = core_type followed by optional "@ =@ primitives" + f.open_box(BoxKind::HOV, 2); + print_core_type(f, arena, &vd.pval_type); + if !vd.pval_prim.is_empty() { + f.space(); + f.string("="); + f.space(); + for (i, prim) in vd.pval_prim.iter().enumerate() { + if i > 0 { + f.space(); + } + f.string("\""); + f.string(prim); + f.string("\""); + } } - print_item_attributes(f, &vd.pval_attributes); f.close_box(); + f.close_box(); + print_item_attributes(f, arena, &vd.pval_attributes); } StructureItemDesc::Pstr_type(rec_flag, decls) => { + // OCaml: @[<2>type %a%a%s%s%a@]%a for first, @[<2>and %a@]%a for others + // Each declaration is wrapped in a box with indent 2 let rec_str = match rec_flag { RecFlag::Recursive => "", RecFlag::Nonrecursive => " nonrec", }; for (i, decl) in decls.iter().enumerate() { + if i > 0 { + f.newline(); + } + // OCaml: @[<2> - Open structural box with indent 2 for type declaration + f.open_box(BoxKind::Box, 2); if i == 0 { f.string("type"); f.string(rec_str); f.string(" "); } else { - f.newline(); f.string("and "); } - print_type_declaration(f, decl); + print_type_declaration(f, arena, decl); + f.close_box(); + // OCaml: item attributes (%a) are printed OUTSIDE the @[<2>...@] box + print_item_attributes(f, arena, &decl.ptype_attributes); } } StructureItemDesc::Pstr_typext(ext) => { + // OCaml: pp f "@[<2>type %a%a += %a@ %a@]%a" + // Format: "type t += \n | Foo \n | Bar" + f.open_box(BoxKind::HV, 2); f.string("type "); - print_longident(f, &ext.ptyext_path.txt); - f.string(" += "); - for (i, ctor) in ext.ptyext_constructors.iter().enumerate() { - if i > 0 { - f.string(" | "); + // Print type params if present + if !ext.ptyext_params.is_empty() { + if ext.ptyext_params.len() == 1 { + // Single param: no parens, like OCaml's "type _ Tid.t +=" + print_core_type(f, arena, &ext.ptyext_params[0].0); + f.string(" "); + } else { + f.string("("); + for (i, (ty, _variance)) in ext.ptyext_params.iter().enumerate() { + if i > 0 { + f.string(","); + } + print_core_type(f, arena, ty); + } + f.string(") "); } - print_extension_constructor(f, ctor); } + print_longident_idx(f, arena, ext.ptyext_path.txt); + f.string(" += "); + if matches!(ext.ptyext_private, PrivateFlag::Private) { + f.string("private "); + } + // Extra space before line break to match OCaml's "+= \n" + f.string(" "); + // Each constructor starts with @\n|@; (newline, pipe, break) + for ctor in ext.ptyext_constructors.iter() { + f.newline(); + f.string("| "); + print_extension_constructor(f, arena, ctor); + } + f.close_box(); + print_item_attributes(f, arena, &ext.ptyext_attributes); } StructureItemDesc::Pstr_exception(ext) => { - f.string("exception "); - print_extension_constructor(f, ext); + // OCaml: pp f "@[exception@ %a@]" + // OCaml: pp f "@[exception@ %a@]" + f.open_box(BoxKind::HOV, 2); + f.string("exception"); + f.space(); // @ after "exception" + print_extension_constructor(f, arena, ext); + f.close_box(); } StructureItemDesc::Pstr_module(mb) => { + // OCaml: @[module %s%a@]%a + f.open_box(BoxKind::HOV, 2); f.string("module "); f.string(&mb.pmb_name.txt); - f.string(" = "); - print_module_expr(f, &mb.pmb_expr); + // OCaml: module_helper unwraps Pmod_functor with no attributes + // and prints functor parameters inline: `module F(A:X) = body` + let mut me = &mb.pmb_expr; + while let ModuleExprDesc::Pmod_functor(name, mt, body) = &me.pmod_desc { + if me.pmod_attributes.is_empty() { + if let Some(mt) = mt { + f.string("("); + f.string(&name.txt); + f.string(":"); + print_module_type(f, arena, mt); + f.string(")"); + } else { + f.string("()"); + } + me = body; + } else { + break; + } + } + // OCaml: special case for Pmod_constraint with ident or signature type + // prints "module X : mt = me'" instead of "module X = (me' : mt)" + if let ModuleExprDesc::Pmod_constraint(inner_me, mt) = &me.pmod_desc { + let is_sugar_type = matches!( + mt.pmty_desc, + ModuleTypeDesc::Pmty_ident(..) | ModuleTypeDesc::Pmty_signature(..) + ); + if is_sugar_type && me.pmod_attributes.is_empty() { + f.string(" :"); + f.space(); + print_module_type(f, arena, mt); + f.space(); + f.string("="); + f.space(); + print_module_expr(f, arena, inner_me); + f.space(); // OCaml: trailing @; produces space + } else { + f.string(" ="); + f.space(); + print_module_expr(f, arena, me); + } + } else { + f.string(" ="); + f.space(); + print_module_expr(f, arena, me); + } + f.close_box(); + print_item_attributes(f, arena, &mb.pmb_attributes); } StructureItemDesc::Pstr_recmodule(mbs) => { + // OCaml: @[@[module rec name:mt = me@]%a @ aux_list@] + // Outer HV box ensures and-bindings break onto separate lines + f.open_box(BoxKind::HV, 0); for (i, mb) in mbs.iter().enumerate() { if i == 0 { + f.open_box(BoxKind::HOV, 2); f.string("module rec "); } else { - f.string(" and "); + // Outer @ break: newline in HV box + f.space(); + // OCaml: @[@ and@ ...@] — HOV2 box starting with @ before "and" + f.open_box(BoxKind::HOV, 2); + f.space(); // @ before "and" — gives 1 space in packing mode + f.string("and "); } f.string(&mb.pmb_name.txt); - f.string(" = "); - print_module_expr(f, &mb.pmb_expr); + // Check for constraint sugar: `A:Mt = Me` instead of `A = (Me : Mt)` + if let ModuleExprDesc::Pmod_constraint(me, mt) = &mb.pmb_expr.pmod_desc { + f.string(":"); + print_module_type(f, arena, mt); + f.space(); // @ before = + f.string("="); + f.space(); // @ after = + print_module_expr(f, arena, me); + } else { + f.space(); // @ before = + f.string("="); + f.space(); // @ after = + print_module_expr(f, arena, &mb.pmb_expr); + } + f.close_box(); + // Print module binding attributes + print_item_attributes(f, arena, &mb.pmb_attributes); } + f.close_box(); } StructureItemDesc::Pstr_modtype(mtd) => { - f.string("module type "); + // OCaml: pp f "@[module@ type@ %s%a@]%a" + // where inner is: pp_print_space f (); pp f "@ =@ %a" (module_type ctxt) mt + // This produces two spaces before = when not breaking: "Sig =" + f.open_box(BoxKind::HOV, 2); + f.string("module"); + f.space(); + f.string("type"); + f.space(); f.string(&mtd.pmtd_name.txt); if let Some(mt) = &mtd.pmtd_type { - // OCaml has trailing space from name + space before = - f.string(" = "); - print_module_type(f, mt); + // pp_print_space + "@ =" gives two spaces before = + f.string(" "); // literal space from pp_print_space + f.space(); // break hint before = + f.string("="); + f.space(); + print_module_type(f, arena, mt); } + f.close_box(); + print_item_attributes(f, arena, &mtd.pmtd_attributes); } StructureItemDesc::Pstr_open(od) => { f.string("open"); @@ -445,13 +782,17 @@ fn print_structure_item(f: &mut Formatter, item: &StructureItem) { f.string("!"); } f.string(" "); - print_longident(f, &od.popen_lid.txt); - print_item_attributes(f, &od.popen_attributes); + print_longident_idx(f, arena, od.popen_lid.txt); + print_item_attributes(f, arena, &od.popen_attributes); } StructureItemDesc::Pstr_include(incl) => { - f.string("include "); - print_module_expr(f, &incl.pincl_mod); - print_item_attributes(f, &incl.pincl_attributes); + // OCaml: @[include@ %a@]%a + f.open_box(BoxKind::HOV, 2); + f.string("include"); + f.space(); + print_module_expr(f, arena, &incl.pincl_mod); + f.close_box(); + print_item_attributes(f, arena, &incl.pincl_attributes); } StructureItemDesc::Pstr_attribute((name, payload)) => { // Standalone/floating attributes use [@@@...] (3 @) @@ -459,7 +800,7 @@ fn print_structure_item(f: &mut Formatter, item: &StructureItem) { f.string(&name.txt); if !payload_is_empty(payload) { f.string(" "); - print_payload(f, payload); + print_payload(f, arena, payload); } else { f.string(" "); } @@ -470,9 +811,9 @@ fn print_structure_item(f: &mut Formatter, item: &StructureItem) { f.string("[%%"); f.string(&name.txt); f.space(); - print_payload(f, payload); + print_payload(f, arena, payload); f.string("]"); - print_item_attributes(f, attrs); + print_item_attributes(f, arena, attrs); f.close_box(); } } @@ -482,26 +823,105 @@ fn print_structure_item(f: &mut Formatter, item: &StructureItem) { // Value bindings // ============================================================================ -fn print_value_binding(f: &mut Formatter, pat: &Pattern, expr: &Expression) { +fn print_value_binding(f: &mut Formatter, arena: &ParseArena, pat: &Pattern, expr: &Expression) { if !expr.pexp_attributes.is_empty() { - print_pattern(f, pat); - f.string(" ="); + // OCaml: pp f "%a@;=@;%a" (pattern ctxt) p (expression ctxt) x + print_pattern(f, arena, pat); f.space(); - print_expression(f, expr); + f.string("="); + f.space(); + print_expression(f, arena, expr); return; } - // Special case: Ppat_constraint with Ptyp_poly type is printed without outer parens - // e.g. "let t : 'a . t = x" instead of "let (t : 'a . t) = x" + // Check for desugared locally abstract types (GADT sugar): + // let f : 'a 'b . type_expr = fun (type a) -> fun (type b) -> (body : type_expr') + // This gets printed as: let f : type a b. type_expr' = body + // OCaml pprintast.ml is_desugared_gadt function (lines 1054-1081) if let PatternDesc::Ppat_constraint(inner_pat, typ) = &pat.ppat_desc { - if matches!(typ.ptyp_desc, CoreTypeDesc::Ptyp_poly(..)) { - print_pattern(f, inner_pat); - f.string(" : "); - print_core_type(f, typ); - f.string(" ="); - f.space(); - print_expression_no_outer_parens(f, expr); - return; + if pat.ppat_attributes.is_empty() { + if let CoreTypeDesc::Ptyp_poly(tyvars, _) = &typ.ptyp_desc { + if !tyvars.is_empty() && typ.ptyp_attributes.is_empty() { + // Try to match the desugared GADT pattern + // Collect Pexp_newtype chain from expression + let mut e_tyvars = Vec::new(); + let mut curr_expr = expr; + while let ExpressionDesc::Pexp_newtype(tyvar, inner) = &curr_expr.pexp_desc { + if !curr_expr.pexp_attributes.is_empty() { + break; + } + e_tyvars.push(&tyvar.txt); + curr_expr = inner; + } + // Check if we end with Pexp_constraint(body, ct) and tyvars match + if let ExpressionDesc::Pexp_constraint(body, ct) = &curr_expr.pexp_desc { + if curr_expr.pexp_attributes.is_empty() && e_tyvars.len() == tyvars.len() { + // Check that tyvar names match (pattern has 'a, expr has a -> same base name) + let tyvars_match = tyvars.iter().zip(e_tyvars.iter()).all(|(pt, et)| { + pt.txt == **et + }); + if tyvars_match { + // Print sugared form: name : type t u v. ct = body + // OCaml: %a@;: type@;%a.@;%a@;=@;%a + print_simple_pattern(f, arena, inner_pat); + f.space(); + f.string(": type"); + f.space(); + for (i, tv) in e_tyvars.iter().enumerate() { + if i > 0 { + f.space(); + } + f.string(tv); + } + f.string("."); + f.space(); + print_core_type(f, arena, ct); + f.space(); + f.string("="); + f.space(); + print_expression(f, arena, body); + return; + } + } + } + } + } + } + } + + // Special case: Ppat_constraint - different handling based on type + // OCaml pprintast.ml lines 1096-1103 + if let PatternDesc::Ppat_constraint(inner_pat, typ) = &pat.ppat_desc { + if pat.ppat_attributes.is_empty() { + if matches!(typ.ptyp_desc, CoreTypeDesc::Ptyp_poly(..)) && typ.ptyp_attributes.is_empty() { + // Ptyp_poly: print without outer parens + // OCaml: pp f "%a@;:@;%a@;=@;%a" + print_simple_pattern(f, arena, inner_pat); + f.space(); + f.string(":"); + f.space(); + print_core_type(f, arena, typ); + f.space(); + f.string("="); + f.space(); + print_expression_no_outer_parens(f, arena, expr); + return; + } else { + // Non-poly: print with outer parens using simple_pattern for inner + // OCaml: pp f "(%a@;:@;%a)@;=@;%a" + f.string("("); + print_simple_pattern(f, arena, inner_pat); + f.space(); + f.string(":"); + f.space(); + print_core_type(f, arena, typ); + f.string(")"); + f.space(); + f.string("="); + f.space(); + print_expression_no_outer_parens(f, arena, expr); + return; + } } } @@ -514,96 +934,285 @@ fn print_value_binding(f: &mut Formatter, pat: &Pattern, expr: &Exp arity, is_async, } => { - print_pattern(f, pat); - f.string(" "); + // OCaml: pp f "%a@ %a" (simple_pattern ctxt) p pp_print_pexp_function x + // where pp_print_pexp_function does: pp f "%s%s%a@ %a" async_str arity_str param recurse + print_pattern(f, arena, pat); + f.space(); // @ between pattern and pp_print_pexp_function if *is_async { f.string("async "); } - // Print arity annotation + // Print arity annotation (only when explicitly set, matching OCaml's pprintast) if let Arity::Full(n) = arity { f.string(&format!("[arity:{}]", n)); - } else { - let computed_arity = count_function_arity(expr); - if computed_arity > 0 { - f.string(&format!("[arity:{}]", computed_arity)); - } } - print_inline_param(f, arg_label, default, lhs); - let body = print_remaining_inline_params(f, rhs); + print_inline_param(f, arena, arg_label, default, lhs); + f.space(); // @ between param and next + let body = print_remaining_inline_params(f, arena, rhs); + // OCaml: pp f "=@;%a" (expression ctxt) x + f.string("="); + f.space(); + print_expression_no_outer_parens(f, arena, body); + } + ExpressionDesc::Pexp_newtype(name, inner) => { + // Handle locally abstract types at the start: let f (type t) ... + // OCaml: pp f "%a@ %a" where second %a is pp_print_pexp_function + // pp_print_pexp_function for Pexp_newtype: pp f "(type@ %s)@ %a" + print_pattern(f, arena, pat); + f.space(); // @ between pattern and (type ...) + f.string("(type"); + f.space(); // @ inside (type@ %s) + f.string(&name.txt); + f.string(")"); + f.space(); // @ between ) and next + // Continue collecting newtypes and print arity when we hit a fun + let body = print_remaining_inline_params_with_arity(f, arena, inner, true); + // OCaml: pp f "=@;%a" (expression ctxt) x f.string("="); f.space(); - print_expression_no_outer_parens(f, body); + print_expression_no_outer_parens(f, arena, body); } _ => { - print_pattern(f, pat); - f.string(" ="); + // OCaml: pp f "%a@;=@;%a" (pattern ctxt) p (expression ctxt) x + print_pattern(f, arena, pat); + f.space(); + f.string("="); f.space(); - print_expression_no_outer_parens(f, expr); + print_expression_no_outer_parens(f, arena, expr); } } } +/// Print a function parameter. +/// For Nolabel: no trailing space (caller adds break) +/// For Labelled/Optional: includes trailing break (@;) to match OCaml's label_exp fn print_inline_param( f: &mut Formatter, + arena: &ParseArena, label: &ArgLabel, default: &Option>, pat: &Pattern, ) { match label { ArgLabel::Nolabel => { - if pattern_needs_parens_as_param(pat) { + // OCaml: pp f "%a@ " (simple_pattern ctxt) p + // The "@ " break is emitted by the caller, not by label_exp for Nolabel + // Wait - actually for Nolabel, pp_print_pexp_function uses (simple_pattern ctxt) directly, + // not label_exp. So there's no trailing break from the param itself. + if pattern_needs_parens_as_param(pat, arena) { f.string("("); - print_pattern(f, pat); - f.string(") "); + print_pattern(f, arena, pat); + f.string(")"); } else { - print_pattern(f, pat); - f.string(" "); + print_pattern(f, arena, pat); } } ArgLabel::Labelled(name) => { - if pattern_is_simple_var(pat, &name.txt) { + // OCaml label_exp: pp f "~%s@;" l OR pp f "~%s:%a@;" l (simple_pattern ctxt) p + // The trailing @; is Break(1,0) + let name_str = arena.get_string(name.txt); + if pattern_is_simple_var(pat, name_str) { f.string("~"); - f.string(&name.txt); - f.string(" "); + f.string(name_str); + f.space(); // @; from label_exp } else { f.string("~"); - f.string(&name.txt); + f.string(name_str); f.string(":"); - print_pattern(f, pat); - f.string(" "); + print_pattern(f, arena, pat); + f.space(); // @; from label_exp } } ArgLabel::Optional(name) => { + // OCaml label_exp: pp f "?(%s=@;%a)@;" OR pp f "?%s:(%a=@;%a)@;" etc. + // All cases have trailing @; = Break(1,0) + let name_str = arena.get_string(name.txt); if let Some(def) = default { - if pattern_is_simple_var(pat, &name.txt) { + if pattern_is_simple_var(pat, name_str) { f.string("?("); - f.string(&name.txt); - f.string("= "); - print_expression(f, def); - f.string(") "); + f.string(name_str); + f.string("="); + f.space(); // =@; inside + print_expression(f, arena, def); + f.string(")"); + f.space(); // trailing @; } else { f.string("?"); - f.string(&name.txt); + f.string(name_str); f.string(":("); - print_pattern(f, pat); - f.string("= "); - print_expression(f, def); - f.string(") "); + print_pattern(f, arena, pat); + f.string("="); + f.space(); // =@; inside + print_expression(f, arena, def); + f.string(")"); + f.space(); // trailing @; } - } else if pattern_is_simple_var(pat, &name.txt) { + } else if pattern_is_simple_var(pat, name_str) { f.string("?"); - f.string(&name.txt); - f.string(" "); + f.string(name_str); + f.space(); // @; trailing } else { f.string("?"); - f.string(&name.txt); + f.string(name_str); f.string(":"); - print_pattern(f, pat); - f.string(" "); + print_pattern(f, arena, pat); + f.space(); // @; trailing + } + } + } +} + +/// Print label_exp matching OCaml's label_exp function (without trailing break). +/// Used in print_fun_body where the caller adds " -> " after. +fn print_label_exp( + f: &mut Formatter, + arena: &ParseArena, + label: &ArgLabel, + default: &Option>, + pat: &Pattern, +) { + match label { + ArgLabel::Nolabel => { + // OCaml: simple_pattern ctxt p followed by "@ " + print_simple_pattern(f, arena, pat); + } + ArgLabel::Labelled(name) => { + let name_str = arena.get_string(name.txt); + if pattern_is_simple_var(pat, name_str) { + // Punned: ~foo + f.string("~"); + f.string(name_str); + } else { + // Explicit: ~foo:pattern + f.string("~"); + f.string(name_str); + f.string(":"); + print_simple_pattern(f, arena, pat); + } + } + ArgLabel::Optional(name) => { + let name_str = arena.get_string(name.txt); + if pattern_is_simple_var(pat, name_str) { + match default { + Some(def) => { + // ?(%s=@;%a) + f.string("?("); + f.string(name_str); + f.string("="); + f.space(); + print_expression(f, arena, def); + f.string(")"); + } + None => { + // ?%s + f.string("?"); + f.string(name_str); + } + } + } else { + match default { + Some(def) => { + // ?%s:(%a=@;%a) + f.string("?"); + f.string(name_str); + f.string(":("); + print_pattern(f, arena, pat); + f.string("="); + f.space(); + print_expression(f, arena, def); + f.string(")"); + } + None => { + // ?%s:%a + f.string("?"); + f.string(name_str); + f.string(":"); + print_simple_pattern(f, arena, pat); + } + } + } + } + } +} + +/// Print label_exp with trailing break/space, matching OCaml's label_exp. +/// Used in Pexp_fun expression printing where format breaks are used. +fn print_label_exp_with_break( + f: &mut Formatter, + arena: &ParseArena, + label: &ArgLabel, + default: &Option>, + pat: &Pattern, +) { + match label { + ArgLabel::Nolabel => { + // OCaml: %a@ (simple_pattern + break hint with space) + print_simple_pattern(f, arena, pat); + f.space(); + } + ArgLabel::Labelled(name) => { + let name_str = arena.get_string(name.txt); + if pattern_is_simple_var(pat, name_str) { + // Punned: ~foo@; + f.string("~"); + f.string(name_str); + f.space(); + } else { + // Explicit: ~foo:pattern@; + f.string("~"); + f.string(name_str); + f.string(":"); + print_simple_pattern(f, arena, pat); + f.space(); + } + } + ArgLabel::Optional(name) => { + let name_str = arena.get_string(name.txt); + if pattern_is_simple_var(pat, name_str) { + match default { + Some(def) => { + // ?(%s=@;%a)@; + f.string("?("); + f.string(name_str); + f.string("="); + f.space(); + print_expression(f, arena, def); + f.string(")"); + f.space(); + } + None => { + // ?%s@ (note: OCaml uses @ not @; for punned optional) + f.string("?"); + f.string(name_str); + f.space(); + } + } + } else { + match default { + Some(def) => { + // ?%s:(%a=@;%a)@; + f.string("?"); + f.string(name_str); + f.string(":("); + print_pattern(f, arena, pat); + f.string("="); + f.space(); + print_expression(f, arena, def); + f.string(")"); + f.space(); + } + None => { + // ?%s:%a@; + f.string("?"); + f.string(name_str); + f.string(":"); + print_simple_pattern(f, arena, pat); + f.space(); + } + } } } } @@ -611,7 +1220,18 @@ fn print_inline_param( fn print_remaining_inline_params<'a, W: Write>( f: &mut Formatter, + arena: &ParseArena, expr: &'a Expression, +) -> &'a Expression { + print_remaining_inline_params_with_arity(f, arena, expr, false) +} + +/// Helper to print remaining inline params, optionally printing arity on first Pexp_fun +fn print_remaining_inline_params_with_arity<'a, W: Write>( + f: &mut Formatter, + arena: &ParseArena, + expr: &'a Expression, + need_arity: bool, ) -> &'a Expression { if !expr.pexp_attributes.is_empty() { return expr; @@ -623,10 +1243,26 @@ fn print_remaining_inline_params<'a, W: Write>( default, lhs, rhs, + arity, .. } => { - print_inline_param(f, arg_label, default, lhs); - print_remaining_inline_params(f, rhs) + // Print arity for each Pexp_fun that has an arity annotation + // (matching OCaml's pprintast: only print when explicitly set) + if let Arity::Full(n) = arity { + f.string(&format!("[arity:{}]", n)); + } + print_inline_param(f, arena, arg_label, default, lhs); + f.space(); // @ between param and next recursive call + print_remaining_inline_params_with_arity(f, arena, rhs, false) + } + ExpressionDesc::Pexp_newtype(name, inner) => { + // OCaml: pp f "(type@ %s)@ %a" str.txt pp_print_pexp_function e + f.string("(type"); + f.space(); // @ inside (type@ %s) + f.string(&name.txt); + f.string(")"); + f.space(); // @ between ) and next + print_remaining_inline_params_with_arity(f, arena, inner, need_arity) } _ => expr, } @@ -636,76 +1272,120 @@ fn print_remaining_inline_params<'a, W: Write>( // Expressions // ============================================================================ -fn print_expression(f: &mut Formatter, expr: &Expression) { +fn print_expression(f: &mut Formatter, arena: &ParseArena, expr: &Expression) { let attrs = printable_attributes(&expr.pexp_attributes); let has_attrs = !attrs.is_empty(); if has_attrs { // OCaml Format: pp f "((%a)@,%a)" (expression ctxt) {x with pexp_attributes = []} (attributes ctxt) x.pexp_attributes - // No explicit box - the cut allows breaking before attributes + // One cut before ALL attributes (not per-attribute), then attributes are concatenated f.string("(("); - print_expression_inner(f, expr, false); + print_expression_inner(f, arena, expr, false, PrintCtx::reset()); f.string(")"); - for (name, payload) in attrs { - f.cut(); - f.string("[@"); - f.string(&name.txt); - if !payload_is_empty(payload) { - f.string(" "); - print_payload(f, payload); - } - f.string(" ]"); - } + f.cut(); // Single cut before all attributes + print_attributes(f, arena, &expr.pexp_attributes); f.string(")"); } else { - print_expression_inner(f, expr, false); + print_expression_inner(f, arena, expr, false, PrintCtx::reset()); } } -fn print_expression_no_outer_parens(f: &mut Formatter, expr: &Expression) { +fn print_expression_no_outer_parens(f: &mut Formatter, arena: &ParseArena, expr: &Expression) { let attrs = printable_attributes(&expr.pexp_attributes); let has_attrs = !attrs.is_empty(); if has_attrs { - // OCaml Format: pp f "((%a)@,%a)" - double parens with inner around expr + // OCaml Format: pp f "((%a)@,%a)" - one cut before all attributes f.string("(("); - print_expression_inner(f, expr, false); + print_expression_inner(f, arena, expr, false, PrintCtx::reset()); f.string(")"); - for (name, payload) in attrs { - f.cut(); // Allow break before attribute - f.string("[@"); - f.string(&name.txt); - if !payload_is_empty(payload) { - f.string(" "); - print_payload(f, payload); - } - f.string(" ]"); - } + f.cut(); // Single cut before all attributes + print_attributes(f, arena, &expr.pexp_attributes); f.string(")"); } else { - print_expression_inner(f, expr, false); + print_expression_inner(f, arena, expr, false, PrintCtx::reset()); } } -fn print_expression_simple(f: &mut Formatter, expr: &Expression) { +fn print_expression_simple(f: &mut Formatter, arena: &ParseArena, expr: &Expression) { + print_expression_simple_ctx(f, arena, expr, PrintCtx::reset()); +} + +/// Context-aware version of print_expression_simple. +/// In OCaml, `simple_expr ctxt` passes the context through, so when it falls through +/// to `expression ctxt`, context-dependent parenthesization (pipe, semi, ifthenelse) is applied. +fn print_expression_simple_ctx(f: &mut Formatter, arena: &ParseArena, expr: &Expression, ctx: PrintCtx) { // OCaml's simple_expr wraps non-simple expressions in parens // BUT: attributed expressions already produce ((expr)[@attr]) structure // so we don't add extra parens for them let has_attrs = !printable_attributes(&expr.pexp_attributes).is_empty(); - if is_simple_expression(expr) { - print_expression(f, expr); - } else if has_attrs { - // Attributed expressions already produce their own parens structure - print_expression(f, expr); + if has_attrs { + // OCaml: simple_expr for attributed exprs -> expression ctxt -> handles attrs + print_expression_with_ctx(f, arena, expr, ctx); + } else if is_simple_expression_with_arena(expr, arena) { + // Simple expressions print directly (no context needed - they don't produce parens) + print_expression_with_ctx(f, arena, expr, ctx); } else { + // Non-simple: wrap in parens and call expression with context + // OCaml's paren + expression boxes create a break opportunity f.string("("); - print_expression(f, expr); + print_expression_with_ctx(f, arena, expr, ctx); f.string(")"); } } -fn print_expression_semi_context(f: &mut Formatter, expr: &Expression) { +/// Print expression as simple_expr with under_semi context. +/// Used for array elements: OCaml uses `simple_expr (under_semi ctxt)`. +fn print_expression_simple_under_semi(f: &mut Formatter, arena: &ParseArena, expr: &Expression) { + print_expression_simple_under_semi_ctx(f, arena, expr, PrintCtx::reset()); +} + +/// Context-aware version of print_expression_simple_under_semi. +/// OCaml: `simple_expr (under_semi ctxt)` - applies under_semi to the inherited context. +fn print_expression_simple_under_semi_ctx(f: &mut Formatter, arena: &ParseArena, expr: &Expression, ctx: PrintCtx) { + let semi_ctx = ctx.under_semi(); + let has_attrs = !printable_attributes(&expr.pexp_attributes).is_empty(); + + if has_attrs { + // OCaml: expression (under_semi ctxt) for attributed non-simple expressions + print_expression_with_ctx(f, arena, expr, semi_ctx); + } else if is_simple_expression_with_arena(expr, arena) { + print_expression_with_ctx(f, arena, expr, semi_ctx); + } else { + f.string("("); + print_expression_with_ctx(f, arena, expr, semi_ctx); + f.string(")"); + } +} + +/// Print expression at "expression2" level - used for binary operands and function arguments. +/// OCaml's under_app: if x.pexp_attributes <> [] then expression ctxt f x else expression2 ctxt f x +/// Expression2 includes Pexp_field and Pexp_send without parens, other exprs use simple_expr. +fn print_expression2(f: &mut Formatter, arena: &ParseArena, expr: &Expression) { + print_expression2_ctx(f, arena, expr, PrintCtx::reset()); +} + +/// Context-aware version of print_expression2. +/// In OCaml, `expression2 ctxt` passes the context through. +fn print_expression2_ctx(f: &mut Formatter, arena: &ParseArena, expr: &Expression, ctx: PrintCtx) { + let has_attrs = !printable_attributes(&expr.pexp_attributes).is_empty(); + + if has_attrs { + // Attributed expressions go through full expression printing with context + print_expression_with_ctx(f, arena, expr, ctx); + } else if is_expression2(expr, arena) { + // Expression2-level expressions don't need parens + print_expression_with_ctx(f, arena, expr, ctx); + } else { + // Everything else needs parens (falls through from simple_expr) + f.string("("); + print_expression_with_ctx(f, arena, expr, ctx); + f.string(")"); + } +} + +fn print_expression_semi_context(f: &mut Formatter, arena: &ParseArena, expr: &Expression) { let attrs = printable_attributes(&expr.pexp_attributes); let has_attrs = !attrs.is_empty(); let needs_semi_parens = needs_parens_in_semi_context(expr); @@ -713,108 +1393,206 @@ fn print_expression_semi_context(f: &mut Formatter, expr: &Expressi if has_attrs { f.string("(("); - print_expression_inner(f, expr, false); + print_expression_inner(f, arena, expr, false, PrintCtx::reset()); f.string(")"); - for (name, payload) in attrs { - f.cut(); // Allow break before attribute - f.string("[@"); - f.string(&name.txt); - if !payload_is_empty(payload) { - f.string(" "); - print_payload(f, payload); - } - f.string(" ]"); - } + f.cut(); // Single cut before all attributes + print_attributes(f, arena, &expr.pexp_attributes); f.string(")"); } else if needs_semi_parens { f.string("(("); - print_expression_inner(f, expr, false); + print_expression_inner(f, arena, expr, false, PrintCtx::reset()); f.string("))"); } else if !is_simple { f.string("("); - print_expression_inner(f, expr, false); + print_expression_inner(f, arena, expr, false, PrintCtx::reset()); + f.string(")"); + } else { + print_expression_inner(f, arena, expr, false, PrintCtx::reset()); + } +} + +/// Print expression under OCaml's `under_semi` context. +/// Only wraps specific types in parens (fun/match/try/sequence, let/letmodule/open/letexception). +/// Everything else goes through normal expression printing. +/// +/// OCaml's `expression` function checks attributes FIRST, before context checks. +/// When an attributed expression is in semi context, the attribute handling wraps +/// the expression, and then the inner (unattributed) expression gets the semi parens. +/// This produces `(((seq)))[@attr]` instead of `(((seq))[@attr])`. +fn print_expression_under_semi(f: &mut Formatter, arena: &ParseArena, expr: &Expression) { + let attrs = printable_attributes(&expr.pexp_attributes); + let has_attrs = !attrs.is_empty(); + + if has_attrs { + // OCaml: attributes are checked first, then the inner expression gets the context check. + // pp f "((%a)@,%a)" (expression ctxt) {x with pexp_attributes=[]} (attributes ctxt) x.pexp_attributes + // The inner call to `expression ctxt` will then hit the semi context check. + f.string("(("); + // Print the inner expression with semi context (attrs stripped) + print_expression_under_semi_inner(f, arena, expr); + f.string(")"); + f.cut(); + print_attributes(f, arena, &expr.pexp_attributes); + f.string(")"); + } else { + let needs_semi_parens = needs_parens_in_semi_context(expr); + let needs_let_parens = matches!( + &expr.pexp_desc, + ExpressionDesc::Pexp_let(_, _, _) + | ExpressionDesc::Pexp_letmodule(_, _, _) + | ExpressionDesc::Pexp_open(_, _, _) + | ExpressionDesc::Pexp_letexception(_, _) + ); + if needs_semi_parens || needs_let_parens { + // OCaml: paren true (expression reset_ctxt) f x + f.string("("); + print_expression(f, arena, expr); + f.string(")"); + } else { + print_expression(f, arena, expr); + } + } +} + +/// Helper: print the inner expression (ignoring its attributes) under semi context. +/// This replicates OCaml's behavior where `expression ctxt` is called with attrs stripped, +/// and the semi context check then applies to the unattributed expression. +fn print_expression_under_semi_inner(f: &mut Formatter, arena: &ParseArena, expr: &Expression) { + let needs_semi_parens = needs_parens_in_semi_context(expr); + let needs_let_parens = matches!( + &expr.pexp_desc, + ExpressionDesc::Pexp_let(_, _, _) + | ExpressionDesc::Pexp_letmodule(_, _, _) + | ExpressionDesc::Pexp_open(_, _, _) + | ExpressionDesc::Pexp_letexception(_, _) + ); + if needs_semi_parens || needs_let_parens { + // paren true (expression reset_ctxt) f x + f.string("("); + print_expression_inner(f, arena, expr, false, PrintCtx::reset()); f.string(")"); } else { - print_expression_inner(f, expr, false); + print_expression_inner(f, arena, expr, false, PrintCtx::reset()); } } -fn print_expression_list_context(f: &mut Formatter, expr: &Expression) { +fn print_expression_list_context(f: &mut Formatter, arena: &ParseArena, expr: &Expression) { let attrs = printable_attributes(&expr.pexp_attributes); let has_attrs = !attrs.is_empty(); let needs_semi_parens = needs_parens_in_semi_context(expr); if has_attrs { f.string("("); - print_expression_inner(f, expr, false); - for (name, payload) in attrs { - f.cut(); // Allow break before attribute - f.string("[@"); - f.string(&name.txt); - if !payload_is_empty(payload) { - f.string(" "); - print_payload(f, payload); - } - f.string(" ]"); - } + print_expression_inner(f, arena, expr, false, PrintCtx::reset()); + f.cut(); // Single cut before all attributes + print_attributes(f, arena, &expr.pexp_attributes); f.string(")"); } else if needs_semi_parens { f.string("("); - print_expression_inner(f, expr, false); + print_expression_inner(f, arena, expr, false, PrintCtx::reset()); + f.string(")"); + } else { + print_expression(f, arena, expr); + } +} + +/// Print expression in "pipe" context (match case RHS) +/// OCaml wraps Pexp_fun/match/try/sequence in parens when under_pipe +/// Like under_semi, OCaml checks attributes first, then context. +fn print_expression_pipe_context(f: &mut Formatter, arena: &ParseArena, expr: &Expression) { + let attrs = printable_attributes(&expr.pexp_attributes); + let has_attrs = !attrs.is_empty(); + let needs_pipe_parens = needs_parens_in_pipe_context(expr); + + if has_attrs && needs_pipe_parens { + // Attribute handling first, then pipe context for inner expression + f.string("(("); + // Inner: apply pipe parens + f.string("("); + print_expression_inner(f, arena, expr, false, PrintCtx::reset()); + f.string(")"); + f.string(")"); + f.cut(); + print_attributes(f, arena, &expr.pexp_attributes); + f.string(")"); + } else if needs_pipe_parens { + f.string("("); + print_expression(f, arena, expr); + f.string(")"); + } else { + print_expression(f, arena, expr); + } +} + +/// Print expression under OCaml's `under_ifthenelse` context. +/// When ifthenelse=true, Pexp_ifthenelse and Pexp_sequence get wrapped in parens. +/// This is used for the condition and then-body of if-then-else expressions. +/// +/// Like under_semi, OCaml checks attributes first, then context. +fn print_expression_under_ifthenelse(f: &mut Formatter, arena: &ParseArena, expr: &Expression) { + let attrs = printable_attributes(&expr.pexp_attributes); + let has_attrs = !attrs.is_empty(); + + if has_attrs { + // Attribute handling first, then ifthenelse context for inner expression + f.string("(("); + print_expression_under_ifthenelse_inner(f, arena, expr); + f.string(")"); + f.cut(); + print_attributes(f, arena, &expr.pexp_attributes); + f.string(")"); + } else if needs_parens_in_ifthenelse_context(expr) { + f.string("("); + print_expression(f, arena, expr); f.string(")"); } else { - print_expression(f, expr); + print_expression(f, arena, expr); } } -fn print_expression_parens_if_complex(f: &mut Formatter, expr: &Expression) { +/// Helper: print inner expression (ignoring attrs) under ifthenelse context +fn print_expression_under_ifthenelse_inner(f: &mut Formatter, arena: &ParseArena, expr: &Expression) { + if needs_parens_in_ifthenelse_context(expr) { + f.string("("); + print_expression_inner(f, arena, expr, false, PrintCtx::reset()); + f.string(")"); + } else { + print_expression_inner(f, arena, expr, false, PrintCtx::reset()); + } +} + +fn print_expression_parens_if_complex(f: &mut Formatter, arena: &ParseArena, expr: &Expression) { let attrs = printable_attributes(&expr.pexp_attributes); let has_attrs = !attrs.is_empty(); - let needs_parens = needs_parens_as_function_arg(expr); + let needs_parens = needs_parens_as_function_arg(expr, arena); let has_own_parens = expression_has_own_parens(expr); if has_attrs { - // OCaml Format: pp f "((%a)@,%a)" - cut before attributes allows line break there + // OCaml Format: pp f "((%a)@,%a)" - one cut before all attributes if has_own_parens { f.string("("); - print_expression_inner(f, expr, false); - for (name, payload) in attrs { - f.cut(); // Allow break before attribute - f.string("[@"); - f.string(&name.txt); - if !payload_is_empty(payload) { - f.string(" "); - print_payload(f, payload); - } - f.string(" ]"); - } + print_expression_inner(f, arena, expr, false, PrintCtx::reset()); + f.cut(); // Single cut before all attributes + print_attributes(f, arena, &expr.pexp_attributes); f.string(")"); } else { f.string("(("); - print_expression_inner(f, expr, false); + print_expression_inner(f, arena, expr, false, PrintCtx::reset()); f.string(")"); - for (name, payload) in attrs { - f.cut(); // Allow break before attribute - f.string("[@"); - f.string(&name.txt); - if !payload_is_empty(payload) { - f.string(" "); - print_payload(f, payload); - } - f.string(" ]"); - } + f.cut(); // Single cut before all attributes + print_attributes(f, arena, &expr.pexp_attributes); f.string(")"); } } else if needs_parens && !has_own_parens { f.string("("); - print_expression_inner(f, expr, false); + print_expression_inner(f, arena, expr, false, PrintCtx::reset()); f.string(")"); } else { - print_expression_inner(f, expr, false); + print_expression_inner(f, arena, expr, false, PrintCtx::reset()); } } -fn print_fun_body(f: &mut Formatter, expr: &Expression) { +fn print_fun_body(f: &mut Formatter, arena: &ParseArena, expr: &Expression) { match &expr.pexp_desc { ExpressionDesc::Pexp_fun { arg_label, @@ -824,30 +1602,75 @@ fn print_fun_body(f: &mut Formatter, expr: &Expression) { .. } if expr.pexp_attributes.is_empty() => { f.string("fun "); - print_arg_label_expr(f, arg_label); - if let Some(def) = default { - f.string("?("); - print_pattern(f, lhs); - f.string(" = "); - print_expression(f, def); - f.string(")"); - } else { - print_pattern(f, lhs); - } + // OCaml label_exp: handles punning for labeled args + print_label_exp(f, arena, arg_label, default, lhs); f.string(" -> "); - print_fun_body(f, rhs); + print_fun_body(f, arena, rhs); } _ => { - print_expression_no_outer_parens(f, expr); + print_expression_no_outer_parens(f, arena, expr); } } -} +} + +fn print_expression_with_ctx(f: &mut Formatter, arena: &ParseArena, expr: &Expression, ctx: PrintCtx) { + let attrs = printable_attributes(&expr.pexp_attributes); + let has_attrs = !attrs.is_empty(); + + if has_attrs { + f.string("(("); + print_expression_inner(f, arena, expr, false, ctx); + f.string(")"); + f.cut(); + print_attributes(f, arena, &expr.pexp_attributes); + f.string(")"); + } else { + print_expression_inner(f, arena, expr, false, ctx); + } +} + +fn print_expression_inner(f: &mut Formatter, arena: &ParseArena, expr: &Expression, use_parens: bool, ctx: PrintCtx) { + // Context-dependent parenthesization (matching OCaml's pprintast lines 606-615) + if (ctx.pipe || ctx.semi) && matches!(&expr.pexp_desc, + ExpressionDesc::Pexp_fun { .. } + | ExpressionDesc::Pexp_match(_, _) + | ExpressionDesc::Pexp_try(_, _) + | ExpressionDesc::Pexp_sequence(_, _)) { + if use_parens { f.string("("); } + f.string("("); + print_expression_inner(f, arena, expr, false, PrintCtx::reset()); + f.string(")"); + if use_parens { f.string(")"); } + return; + } + if ctx.ifthenelse && matches!(&expr.pexp_desc, + ExpressionDesc::Pexp_ifthenelse(_, _, _) + | ExpressionDesc::Pexp_sequence(_, _)) { + if use_parens { f.string("("); } + f.string("("); + print_expression_inner(f, arena, expr, false, PrintCtx::reset()); + f.string(")"); + if use_parens { f.string(")"); } + return; + } + if ctx.semi && matches!(&expr.pexp_desc, + ExpressionDesc::Pexp_let(_, _, _) + | ExpressionDesc::Pexp_letmodule(_, _, _) + | ExpressionDesc::Pexp_open(_, _, _) + | ExpressionDesc::Pexp_letexception(_, _)) { + if use_parens { f.string("("); } + f.string("("); + print_expression_inner(f, arena, expr, false, PrintCtx::reset()); + f.string(")"); + if use_parens { f.string(")"); } + return; + } -fn print_expression_inner(f: &mut Formatter, expr: &Expression, use_parens: bool) { match &expr.pexp_desc { ExpressionDesc::Pexp_ident(lid) => { // OCaml wraps operators in parens when used as values - if let Longident::Lident(name) = &lid.txt { + if let Longident::Lident(name_idx) = arena.get_longident(lid.txt) { + let name = arena.get_string(*name_idx); if ident_needs_parens(name) { f.string("("); f.string(name); @@ -855,7 +1678,7 @@ fn print_expression_inner(f: &mut Formatter, expr: &Expression, use return; } } - print_longident(f, &lid.txt); + print_longident_idx(f, arena, lid.txt); } ExpressionDesc::Pexp_constant(c) => { let is_negative = match c { @@ -871,28 +1694,36 @@ fn print_expression_inner(f: &mut Formatter, expr: &Expression, use } } ExpressionDesc::Pexp_let(rec_flag, bindings, body) => { - let rec_str = match rec_flag { - RecFlag::Recursive => " rec", - RecFlag::Nonrecursive => "", - }; + // OCaml: @[<2>%a in@;<1 -2>%a@] + // where %a is (bindings reset_ctxt) (rf, l) and (expression ctxt) e if use_parens { f.string("("); } - f.open_box(BoxKind::HOV, 2); - f.string("let"); - f.string(rec_str); + f.open_box(BoxKind::Box, 2); + // OCaml: @[<2>%a in@;<1 -2>%a@] + // where %a is (bindings reset_ctxt) (rf, l) + // bindings wraps each binding in @[<2>kwd binding@] + let rec_str = match rec_flag { + RecFlag::Recursive => "let rec ", + RecFlag::Nonrecursive => "let ", + }; for (i, binding) in bindings.iter().enumerate() { + // OCaml bindings: pp f "@[<2>%s %a%a@]%a" + f.open_box(BoxKind::Box, 2); if i > 0 { - f.string(" and"); + f.newline(); + f.string("and "); + } else { + f.string(rec_str); } - f.string(" "); - print_pattern(f, &binding.pvb_pat); - f.string(" = "); - print_expression(f, &binding.pvb_expr); + print_value_binding(f, arena, &binding.pvb_pat, &binding.pvb_expr); + f.close_box(); + // Item attributes are outside the binding box in OCaml + print_item_attributes(f, arena, &binding.pvb_attributes); } f.string(" in"); - f.space(); - print_expression(f, body); + f.break_(1, -2); // @;<1 -2> - space or newline with -2 indent offset + print_expression_with_ctx(f, arena, body, ctx); f.close_box(); if use_parens { f.string(")"); @@ -906,67 +1737,91 @@ fn print_expression_inner(f: &mut Formatter, expr: &Expression, use arity, is_async, } => { + // OCaml: arity is only printed when explicitly set, not computed let arity_value = match arity { Arity::Full(n) => Some(*n), - Arity::Unknown => { - let computed = count_function_arity(expr); - if computed > 0 { Some(computed) } else { None } - } + Arity::Unknown => None, }; if use_parens { f.string("("); } + // OCaml: @[<2>%sfun@;%s%a->@;%a@] + f.open_box(BoxKind::Box, 2); if *is_async { f.string("async "); } - f.string("fun "); + f.string("fun"); + f.space(); if let Some(n) = arity_value { f.string(&format!("[arity:{}]", n)); } - print_arg_label_expr(f, arg_label); - if let Some(def) = default { - f.string("?("); - print_pattern(f, lhs); - f.string(" = "); - print_expression(f, def); - f.string(")"); - } else { - print_pattern(f, lhs); - } - f.string(" -> "); - print_fun_body(f, rhs); + // OCaml's label_exp prints param + trailing break/space + print_label_exp_with_break(f, arena, arg_label, default, lhs); + f.string("->"); + f.space(); + print_expression(f, arena, rhs); + f.close_box(); if use_parens { f.string(")"); } } ExpressionDesc::Pexp_apply { funct, args, partial, .. } => { - // Array access with @res.array.access - if has_attribute(&expr.pexp_attributes, "res.array.access") && args.len() == 2 { + // Array access: Array.get(arr, idx) -> arr.(idx) + // Also handles @res.array.access attribute for backwards compatibility + // OCaml uses simple_expr for the array expression and expression for the index + if (parsetree_viewer::is_array_access(arena, expr) || has_attribute(&expr.pexp_attributes, "res.array.access")) && args.len() == 2 { let (_, arr) = &args[0]; let (_, idx) = &args[1]; - f.string("("); - print_expression(f, arr); + if use_parens { + f.string("("); + } + // OCaml: (simple_expr ctxt) a for the array expression + print_expression_simple_ctx(f, arena, arr, ctx); + f.string(".("); + print_expression(f, arena, idx); + f.string(")"); + if use_parens { + f.string(")"); + } + return; + } + // Array set: Array.set(arr, idx, val) -> arr.(idx) <- val + // OCaml uses simple_expr for both array and value expressions + if parsetree_viewer::is_array_set(arena, expr) && args.len() == 3 { + let (_, arr) = &args[0]; + let (_, idx) = &args[1]; + let (_, val) = &args[2]; + if use_parens { + f.string("("); + } + // OCaml: (simple_expr ctxt) a for the array expression + print_expression_simple_ctx(f, arena, arr, ctx); f.string(".("); - print_expression(f, idx); - f.string("))"); + print_expression(f, arena, idx); + f.string(") <- "); + // OCaml: (simple_expr ctxt) v for the value expression + print_expression_simple_ctx(f, arena, val, ctx); + if use_parens { + f.string(")"); + } return; } // Infix/prefix operators - if let Some(op_name) = get_operator_name(funct) { + if let Some(op_name) = get_operator_name(funct, arena) { if is_infix_operator(op_name) && args.len() == 2 { let (_, lhs) = &args[0]; let (_, rhs) = &args[1]; if use_parens { f.string("("); } - f.open_box(BoxKind::HOV, 2); - // OCaml uses simple_expr which wraps non-simple exprs in parens - print_expression_simple(f, lhs); + f.open_box(BoxKind::Box, 2); + // OCaml: arg1 uses (label_x_expression_param reset_ctxt), arg2 uses (label_x_expression_param ctxt) + print_expression2_ctx(f, arena, lhs, PrintCtx::reset()); f.space(); f.string(op_name); f.space(); - print_expression_simple(f, rhs); + print_expression2_ctx(f, arena, rhs, ctx); if *partial { f.string(" ..."); } @@ -989,11 +1844,11 @@ fn print_expression_inner(f: &mut Formatter, expr: &Expression, use } _ => op_name, }; - // OCaml: @[<2>%s@;%a@] - no outer parens - f.open_box(BoxKind::HOV, 2); + // OCaml: @[<2>%s@;%a@] - no outer parens, uses (simple_expr ctxt) + f.open_box(BoxKind::Box, 2); f.string(shortened_op); f.space(); - print_expression_simple(f, arg); + print_expression_simple_ctx(f, arena, arg, ctx); if *partial { f.string(" ..."); } @@ -1003,15 +1858,17 @@ fn print_expression_inner(f: &mut Formatter, expr: &Expression, use } // Default: prefix application - // OCaml: pp f "@[%a@ %a@]" with break hint between func and args + // OCaml: pp f "%a@ %a" (expression2 ctxt) e (list (label_x_expression_param reset_ctxt)) l if use_parens { f.string("("); } f.open_box(BoxKind::HOV, 2); - print_expression(f, funct); + // OCaml uses (expression2 ctxt) for the function expression + print_expression2_ctx(f, arena, funct, ctx); for (label, arg) in args { f.space(); // Break hint between func and args - print_arg_with_label(f, label, arg); + // OCaml uses (label_x_expression_param reset_ctxt) for all args in normal apply + print_arg_with_label_ctx(f, arena, label, arg, PrintCtx::reset()); } if *partial { f.string(" ..."); @@ -1027,9 +1884,9 @@ fn print_expression_inner(f: &mut Formatter, expr: &Expression, use } f.open_box(BoxKind::HV, 0); f.open_box(BoxKind::HV, 0); - f.open_box(BoxKind::HOV, 2); + f.open_box(BoxKind::Box, 2); f.string("match "); - print_expression(f, scrutinee); + print_expression(f, arena, scrutinee); f.close_box(); f.space(); f.string("with"); @@ -1038,17 +1895,21 @@ fn print_expression_inner(f: &mut Formatter, expr: &Expression, use f.space(); f.string("| "); // OCaml: @[<2>%a%a@;->@;%a@] - f.open_box(BoxKind::HOV, 2); - print_pattern(f, &case.pc_lhs); + f.open_box(BoxKind::Box, 2); + print_pattern(f, arena, &case.pc_lhs); if let Some(guard) = &case.pc_guard { - f.space(); - f.string("when "); - print_expression(f, guard); + // OCaml: (option (expression ctxt) ~first:"@;when@;") + f.space(); // @; before "when" + f.string("when"); + f.space(); // @; after "when" + print_expression(f, arena, guard); } f.space(); f.string("->"); f.space(); - print_expression(f, &case.pc_rhs); + // OCaml uses (expression (under_pipe ctxt)) for case RHS, + // which wraps Pexp_fun/match/try/sequence in parens + print_expression_with_ctx(f, arena, &case.pc_rhs, ctx.under_pipe()); f.close_box(); } f.close_box(); @@ -1060,25 +1921,30 @@ fn print_expression_inner(f: &mut Formatter, expr: &Expression, use if use_parens { f.string("("); } - f.open_box(BoxKind::HOV, 0); + // OCaml: @[<0>@[try@ %a@]@ @[<0>with%a@]@] + f.open_box(BoxKind::Box, 0); f.open_box(BoxKind::HV, 2); - f.string("try "); - print_expression(f, body); + f.string("try"); + f.space(); // @ break between try and body + print_expression(f, arena, body); f.close_box(); - f.space(); - f.open_box(BoxKind::HOV, 0); + f.space(); // @ break between try-box and with-box + f.open_box(BoxKind::Box, 0); f.string("with"); for case in cases { f.space(); f.string("| "); - f.open_box(BoxKind::HOV, 2); - print_pattern(f, &case.pc_lhs); + f.open_box(BoxKind::Box, 2); + print_pattern(f, arena, &case.pc_lhs); if let Some(guard) = &case.pc_guard { - f.string(" when "); - print_expression(f, guard); + f.space(); // @; before "when" + f.string("when"); + f.space(); // @; after "when" + print_expression(f, arena, guard); } f.string(" -> "); - print_expression(f, &case.pc_rhs); + // OCaml uses (expression (under_pipe ctxt)) for case RHS + print_expression_with_ctx(f, arena, &case.pc_rhs, ctx.under_pipe()); f.close_box(); } f.close_box(); @@ -1088,36 +1954,50 @@ fn print_expression_inner(f: &mut Formatter, expr: &Expression, use } } ExpressionDesc::Pexp_tuple(exprs) => { + // OCaml: @[(%a)@] with (list (simple_expr ctxt) ~sep:",@;") + f.open_box(BoxKind::HOV, 2); f.string("("); for (i, e) in exprs.iter().enumerate() { if i > 0 { - f.string(", "); + f.string(","); + f.space(); } - print_expression(f, e); + print_expression_simple_ctx(f, arena, e, ctx); } f.string(")"); + f.close_box(); } ExpressionDesc::Pexp_construct(lid, arg) => { // Special handling for list syntax - if let Longident::Lident(name) = &lid.txt { + if let Longident::Lident(name_idx) = arena.get_longident(lid.txt) { + let name = arena.get_string(*name_idx); if name == "::" { - let (elements, is_complete) = collect_list_elements(expr); + let (elements, is_complete) = collect_list_elements(expr, arena); if is_complete && !elements.is_empty() { + // OCaml: @[[%a]@] with expression (under_semi ctxt) and sep ";@;" + f.open_box(BoxKind::HV, 0); f.string("["); for (i, elem) in elements.iter().enumerate() { if i > 0 { - f.string("; "); + f.string(";"); + f.space(); } - print_expression_list_context(f, elem); + // OCaml uses expression (under_semi), NOT simple_expr + print_expression_under_semi(f, arena, elem); } f.string("]"); + f.close_box(); return; } + // Non-complete list: a :: b :: expr + // OCaml: list (simple_expr ctxt) ~sep:"@;::@;" for (i, elem) in elements.iter().enumerate() { if i > 0 { - f.string(" :: "); + f.space(); + f.string("::"); + f.space(); } - print_expression(f, elem); + print_expression_simple_ctx(f, arena, elem, ctx); } return; } else if name == "[]" { @@ -1128,57 +2008,118 @@ fn print_expression_inner(f: &mut Formatter, expr: &Expression, use return; } } - print_longident(f, &lid.txt); if let Some(a) = arg { - f.string(" "); - print_expression(f, a); + // OCaml: @[<2>%a@;%a@] with (simple_expr ctxt) for arg + f.open_box(BoxKind::Box, 2); + print_longident_idx(f, arena, lid.txt); + f.space(); + print_expression_simple_ctx(f, arena, a, ctx); + f.close_box(); + } else { + print_longident_idx(f, arena, lid.txt); } } ExpressionDesc::Pexp_variant(label, arg) => { - f.string("`"); - f.string(label); if let Some(a) = arg { - f.string(" "); - print_expression(f, a); + // OCaml: @[<2>`%s@;%a@] with (simple_expr ctxt) for arg + f.open_box(BoxKind::Box, 2); + f.string("`"); + f.string(label); + f.space(); + print_expression_simple_ctx(f, arena, a, ctx); + f.close_box(); + } else { + f.string("`"); + f.string(label); } } ExpressionDesc::Pexp_record(fields, base) => { - f.string("{ "); + // OCaml: pp f "@[@[{@;%a%a@]@;}@]" + f.open_box(BoxKind::HV, 0); + f.open_box(BoxKind::HV, 2); + f.string("{"); + f.space(); // @; after { if let Some(b) = base { - print_expression(f, b); - f.string(" with "); + print_expression_simple_ctx(f, arena, b, ctx); + f.string(" with"); + f.space(); // @; after "with" } for (i, field) in fields.iter().enumerate() { if i > 0 { - f.string("; "); + f.string(";"); + f.space(); // ;@; separator + } + // Check for punning: { a } is shorthand for { a = a } + // OCaml only uses punning when field is Lident (not qualified) + let lid = arena.get_longident(field.lid.txt); + let is_punned = if let Longident::Lident(name_idx) = lid { + let fname = arena.get_string(*name_idx); + // Check if expression is Pexp_ident(Lident(fname)) + if let ExpressionDesc::Pexp_ident(expr_lid) = &field.expr.pexp_desc { + match arena.get_longident(expr_lid.txt) { + Longident::Lident(var_idx) => arena.get_string(*var_idx) == fname, + _ => false, + } + } else { + false + } + } else { + false + }; + + if is_punned { + // OCaml: pp f "@[%a%s@]" + f.open_box(BoxKind::HOV, 2); + print_longident_idx(f, arena, field.lid.txt); + if field.opt { + f.string("?"); // Optional punned field: name? + } + f.close_box(); + } else { + // OCaml: pp f "@[%a@;=@;%s%a@]" + f.open_box(BoxKind::HOV, 2); + print_longident_idx(f, arena, field.lid.txt); + f.space(); // @; before = + f.string("="); + f.space(); // @; after = + if field.opt { + f.string("?"); // Optional field: name = ?value + } + // OCaml uses (simple_expr ctxt) for record field values + print_expression_simple_ctx(f, arena, &field.expr, ctx); + f.close_box(); } - print_longident(f, &field.lid.txt); - f.string(" = "); - print_expression(f, &field.expr); } - f.string(" }"); + f.close_box(); + f.space(); // @; before } + f.string("}"); + f.close_box(); } ExpressionDesc::Pexp_field(obj, field) => { - print_expression_simple(f, obj); + // OCaml: (simple_expr ctxt) for the object + print_expression_simple_ctx(f, arena, obj, ctx); f.string("."); - print_longident(f, &field.txt); + print_longident_idx(f, arena, field.txt); } ExpressionDesc::Pexp_setfield(obj, field, value) => { - print_expression(f, obj); + // OCaml: pp f "@[<2>%a.%a@ <-@ %a@]" (simple_expr ctxt) e1 longident_loc li (simple_expr ctxt) e2 + // Note: uses simple_expr ctxt for both object and value + print_expression_simple_ctx(f, arena, obj, ctx); f.string("."); - print_longident(f, &field.txt); + print_longident_idx(f, arena, field.txt); f.string(" <- "); - print_expression(f, value); + print_expression_simple_ctx(f, arena, value, ctx); } ExpressionDesc::Pexp_array(elems) => { - f.open_box(BoxKind::HOV, 0); - f.open_box(BoxKind::HOV, 2); + // OCaml: @[<0>@[<2>[|%a|]@]@] with (list (simple_expr (under_semi ctxt)) ~sep:";") + f.open_box(BoxKind::Box, 0); + f.open_box(BoxKind::Box, 2); f.string("[|"); for (i, e) in elems.iter().enumerate() { if i > 0 { f.string(";"); } - print_expression_semi_context(f, e); + print_expression_simple_under_semi_ctx(f, arena, e, ctx); } f.string("|]"); f.close_box(); @@ -1188,21 +2129,27 @@ fn print_expression_inner(f: &mut Formatter, expr: &Expression, use if use_parens { f.string("("); } + // OCaml: @[@[<2>if@ %a@]@;@[<2>then@ %a@]%a@] + // Both condition and then body use expression (under_ifthenelse ctxt) f.open_box(BoxKind::HV, 0); - f.open_box(BoxKind::HOV, 2); - f.string("if "); - print_expression(f, cond); + f.open_box(BoxKind::Box, 2); + f.string("if"); + f.space(); // @ break between if and condition + print_expression_with_ctx(f, arena, cond, ctx.under_ifthenelse()); f.close_box(); - f.space(); - f.open_box(BoxKind::HOV, 2); - f.string("then "); - print_expression(f, then_expr); + f.space(); // @; break between if-box and then-box + f.open_box(BoxKind::Box, 2); + f.string("then"); + f.space(); // @ break between then and body + print_expression_with_ctx(f, arena, then_expr, ctx.under_ifthenelse()); f.close_box(); if let Some(e) = else_expr { - f.space(); - f.open_box(BoxKind::HOV, 2); - f.string("else "); - print_expression(f, e); + f.space(); // @; break before else + f.open_box(BoxKind::Box, 2); + f.string("else"); + f.space(); // @; break between else and body + // OCaml: expression (under_semi ctxt) for else body + print_expression_with_ctx(f, arena, e, ctx.under_semi()); f.close_box(); } f.close_box(); @@ -1214,23 +2161,36 @@ fn print_expression_inner(f: &mut Formatter, expr: &Expression, use if use_parens { f.string("("); } - // First element - wrap if it's a let (but not sequence, which prints flat) - if matches!(&e1.pexp_desc, ExpressionDesc::Pexp_let(_, _, _)) { - f.string("("); - print_expression(f, e1); - f.string(")"); - } else { - print_expression(f, e1); + // OCaml: flatten sequence chain and print with @[%a@] and ";@;" separator + // Uses expression (under_semi ctxt) for each element + let mut elements: Vec<&Expression> = Vec::new(); + // Collect flattened sequence elements (only unfold non-attributed sequences) + elements.push(e1); + let mut rest = e2.as_ref(); + loop { + match &rest.pexp_desc { + ExpressionDesc::Pexp_sequence(next_e1, next_e2) if rest.pexp_attributes.is_empty() => { + elements.push(next_e1); + rest = next_e2.as_ref(); + } + _ => { + elements.push(rest); + break; + } + } } - f.string("; "); - // Second element - wrap if it's a let (sequence nests without extra parens) - if matches!(&e2.pexp_desc, ExpressionDesc::Pexp_let(_, _, _)) { - f.string("("); - print_expression(f, e2); - f.string(")"); - } else { - print_expression(f, e2); + // Print in HV box: horizontal if fits, vertical otherwise + f.open_box(BoxKind::HV, 0); + for (i, elem) in elements.iter().enumerate() { + // OCaml: each element uses expression (under_semi ctxt) + // under_semi only wraps specific types in parens, NOT all non-simple exprs + print_expression_with_ctx(f, arena, elem, ctx.under_semi()); + if i < elements.len() - 1 { + f.string(";"); + f.space(); // ";@;" separator + } } + f.close_box(); if use_parens { f.string(")"); } @@ -1240,14 +2200,14 @@ fn print_expression_inner(f: &mut Formatter, expr: &Expression, use if use_parens { f.string("("); } - f.open_box(BoxKind::HOV, 2); + f.open_box(BoxKind::Box, 2); f.string("while"); f.space(); - print_expression(f, cond); + print_expression(f, arena, cond); f.space(); f.string("do"); f.space(); - print_expression(f, body); + print_expression(f, arena, body); f.space(); f.string("done"); f.close_box(); @@ -1256,77 +2216,104 @@ fn print_expression_inner(f: &mut Formatter, expr: &Expression, use } } ExpressionDesc::Pexp_for(pat, start, end, dir, body) => { + // OCaml: @[@[@[<2>for %a =@;%a@;%a%a@;do@]@;%a@]@;done@] if use_parens { f.string("("); } + f.open_box(BoxKind::HV, 0); + f.open_box(BoxKind::HV, 2); + f.open_box(BoxKind::Box, 2); f.string("for "); - print_pattern(f, pat); - f.string(" = "); - print_expression(f, start); + print_pattern(f, arena, pat); + f.string(" ="); + f.space(); + print_expression(f, arena, start); + f.space(); let dir_str = match dir { - DirectionFlag::Upto => " to ", - DirectionFlag::Downto => " downto ", + DirectionFlag::Upto => "to", + DirectionFlag::Downto => "downto", }; f.string(dir_str); - print_expression(f, end); - f.string(" do "); - print_expression(f, body); - f.string(" done"); + f.space(); + print_expression(f, arena, end); + f.space(); + f.string("do"); + f.close_box(); + f.space(); + print_expression(f, arena, body); + f.close_box(); + f.space(); + f.string("done"); + f.close_box(); if use_parens { f.string(")"); } } ExpressionDesc::Pexp_constraint(e, t) => { f.string("("); - print_expression(f, e); + print_expression(f, arena, e); f.string(" : "); - print_core_type(f, t); + print_core_type(f, arena, t); f.string(")"); } ExpressionDesc::Pexp_coerce(e, t1, t2) => { f.string("("); - print_expression(f, e); + print_expression(f, arena, e); if let Some(t) = t1 { f.string(" : "); - print_core_type(f, t); + print_core_type(f, arena, t); } f.string(" :> "); - print_core_type(f, t2); + print_core_type(f, arena, t2); f.string(")"); } ExpressionDesc::Pexp_send(e, meth) => { - print_expression(f, e); + // OCaml: pp f "@[%a#%s@]" (simple_expr ctxt) e s.txt + f.open_box(super::formatter::BoxKind::HOV, 2); + print_expression_simple_ctx(f, arena, e, ctx); f.string("#"); f.string(&meth.txt); + f.close_box(); } ExpressionDesc::Pexp_letmodule(name, mexpr, body) => { + // OCaml: pp f "@[let@ module@ %s@ =@ %a@ in@ %a@]" if use_parens { f.string("("); } f.open_box(BoxKind::HOV, 2); - f.string("let module "); + f.string("let"); + f.space(); + f.string("module"); + f.space(); f.string(&name.txt); - f.string(" = "); - print_module_expr(f, mexpr); - f.string(" in"); f.space(); - print_expression(f, body); + f.string("="); + f.space(); + print_module_expr(f, arena, mexpr); + f.space(); + f.string("in"); + f.space(); + print_expression_with_ctx(f, arena, body, ctx); f.close_box(); if use_parens { f.string(")"); } } ExpressionDesc::Pexp_letexception(ext, body) => { + // OCaml: pp f "@[let@ exception@ %a@ in@ %a@]" if use_parens { f.string("("); } f.open_box(BoxKind::HOV, 2); - f.string("let exception "); - print_extension_constructor(f, ext); - // OCaml has @;%a for attributes which produces trailing space even when no attrs - f.string(" in"); // Double space to match OCaml's trailing break from constructor_declaration + f.string("let"); + f.space(); + f.string("exception"); f.space(); - print_expression(f, body); + print_extension_constructor(f, arena, ext); + f.space(); + f.string("in"); + f.space(); + print_expression_with_ctx(f, arena, body, ctx); f.close_box(); if use_parens { f.string(")"); @@ -1334,51 +2321,71 @@ fn print_expression_inner(f: &mut Formatter, expr: &Expression, use } ExpressionDesc::Pexp_assert(e) => { // OCaml: @[assert@ %a@] - no parens - // Parens come from simple_expr when needed + // Parens come from (simple_expr ctxt) when needed f.open_box(BoxKind::HOV, 2); f.string("assert "); - print_expression_simple(f, e); + print_expression_simple_ctx(f, arena, e, ctx); f.close_box(); } ExpressionDesc::Pexp_newtype(name, body) => { - f.string("(fun (type "); + // OCaml: pp f "fun@;(type@;%s)@;->@;%a" + f.string("fun"); + f.space(); // @; after "fun" + f.string("(type"); + f.space(); // @; after "(type" f.string(&name.txt); - f.string(") -> "); - print_expression(f, body); f.string(")"); + f.space(); // @; after ")" + f.string("->"); + f.space(); // @; after "->" + print_expression(f, arena, body); } ExpressionDesc::Pexp_pack(mexpr) => { - f.string("(module "); - print_module_expr(f, mexpr); + // OCaml: pp f "(module@;%a)" (module_expr ctxt) me + f.string("(module"); + f.space(); // @; after "(module" + print_module_expr(f, arena, mexpr); f.string(")"); } - ExpressionDesc::Pexp_open(_override_flag, lid, body) => { + ExpressionDesc::Pexp_open(override_flag, lid, body) => { + // OCaml: pp f "@[<2>let open%s %a in@;%a@]" if use_parens { f.string("("); } - f.open_box(BoxKind::HOV, 2); - f.string("let open "); - print_longident(f, &lid.txt); + f.open_box(BoxKind::Box, 2); + f.string("let open"); + if matches!(override_flag, OverrideFlag::Override) { + f.string("!"); + } + f.string(" "); + print_longident_idx(f, arena, lid.txt); f.string(" in"); - f.space(); - print_expression(f, body); + f.space(); // @; + print_expression_with_ctx(f, arena, body, ctx); f.close_box(); if use_parens { f.string(")"); } } ExpressionDesc::Pexp_extension((name, payload)) => { - f.open_box(BoxKind::H, 2); + // OCaml: @[<2>[%%%s@ %a]@] — structural box with indent 2 + f.open_box(BoxKind::Box, 2); f.string("[%"); f.string(&name.txt); f.space(); - print_payload(f, payload); + print_payload(f, arena, payload); f.string("]"); f.close_box(); } ExpressionDesc::Pexp_await(e) => { - f.string("await "); - let needs_parens = !matches!( + // OCaml: @[await@ %a@] + f.open_box(BoxKind::HOV, 2); + f.string("await"); + f.space(); // @ break between await and expression + // Check if expression is "simple" enough to not need parens + // Note: attributed expressions will get their own parens from print_expression + let has_attrs = !printable_attributes(&e.pexp_attributes).is_empty(); + let is_simple = matches!( &e.pexp_desc, ExpressionDesc::Pexp_ident(_) | ExpressionDesc::Pexp_constant(_) @@ -1387,16 +2394,143 @@ fn print_expression_inner(f: &mut Formatter, expr: &Expression, use | ExpressionDesc::Pexp_array(_) | ExpressionDesc::Pexp_record(_, _) ); + // If has attributes, print_expression already produces ((expr)[@attr ]) + // so we don't need to add extra parens + let needs_parens = !is_simple && !has_attrs; if needs_parens { f.string("("); } - print_expression(f, e); + print_expression(f, arena, e); if needs_parens { f.string(")"); } + f.close_box(); + } + ExpressionDesc::Pexp_jsx_element(jsx) => { + print_jsx_element(f, arena, jsx); + } + } +} + +// ============================================================================ +// JSX Printing +// ============================================================================ + +fn jsx_tag_name_to_string(tag_name: &JsxTagName, arena: &ParseArena) -> String { + match tag_name { + JsxTagName::Lower(name) => name.clone(), + JsxTagName::QualifiedLower { path, name } => { + let path_str = print_longident_to_string(arena.get_longident(*path), arena); + format!("{}.{}", path_str, name) + } + JsxTagName::Upper(lident) => { + print_longident_to_string(arena.get_longident(*lident), arena) + } + JsxTagName::Invalid(name) => name.clone(), + } +} + +fn print_longident_to_string(lid: &Longident, arena: &ParseArena) -> String { + match lid { + Longident::Lident(name_idx) => arena.get_string(*name_idx).to_string(), + Longident::Ldot(prefix, name_idx) => { + let prefix_str = print_longident_to_string(prefix.as_ref(), arena); + let name = arena.get_string(*name_idx); + format!("{}.{}", prefix_str, name) + } + Longident::Lapply(left, right) => { + let left_str = print_longident_to_string(left.as_ref(), arena); + let right_str = print_longident_to_string(right.as_ref(), arena); + format!("{}({})", left_str, right_str) + } + } +} + +fn print_jsx_element(f: &mut Formatter, arena: &ParseArena, jsx: &JsxElement) { + match jsx { + JsxElement::Fragment(frag) => { + f.string("<>"); + for (i, child) in frag.children.iter().enumerate() { + if i > 0 { + f.space(); // OCaml uses "@ " (space with optional break) between children + } + print_expression_simple(f, arena, child); + } + f.string(""); + } + JsxElement::Unary(elem) => { + let name = jsx_tag_name_to_string(&elem.tag_name.txt, arena); + if elem.props.is_empty() { + f.string(&format!("<{} />", name)); + } else { + f.string(&format!("<{} ", name)); + print_jsx_props(f, arena, &elem.props); + f.string(" />"); + } + } + JsxElement::Container(elem) => { + let name = jsx_tag_name_to_string(&elem.tag_name_start.txt, arena); + let closing_name = match &elem.closing_tag { + None => String::new(), + Some(closing) => { + let close_name = jsx_tag_name_to_string(&closing.name.txt, arena); + format!("", close_name) + } + }; + if elem.props.is_empty() { + f.string(&format!("<{}>", name)); + for (i, child) in elem.children.iter().enumerate() { + if i > 0 { + f.space(); // OCaml uses "@ " between children + } + print_expression_simple(f, arena, child); + } + f.string(&closing_name); + } else { + f.string(&format!("<{} ", name)); + print_jsx_props(f, arena, &elem.props); + f.string(">"); + for (i, child) in elem.children.iter().enumerate() { + if i > 0 { + f.space(); // OCaml uses "@ " between children + } + print_expression_simple(f, arena, child); + } + f.string(&closing_name); + } + } + } +} + +fn print_jsx_props(f: &mut Formatter, arena: &ParseArena, props: &[JsxProp]) { + for (i, prop) in props.iter().enumerate() { + if i > 0 { + f.string(" "); + } + print_jsx_prop(f, arena, prop); + } +} + +fn print_jsx_prop(f: &mut Formatter, arena: &ParseArena, prop: &JsxProp) { + match prop { + JsxProp::Punning { optional, name } => { + if *optional { + f.string("?"); + } + f.string(&name.txt); + } + JsxProp::Value { name, optional, value } => { + f.string(&name.txt); + f.string("="); + if *optional { + f.string("?"); + } + print_expression_simple(f, arena, value); } - ExpressionDesc::Pexp_jsx_element(_jsx) => { - f.string(""); + JsxProp::Spreading { expr, .. } => { + f.string("{..."); + print_expression_simple(f, arena, expr); + f.string("}"); } } } @@ -1405,29 +2539,35 @@ fn print_expression_inner(f: &mut Formatter, expr: &Expression, use // Patterns // ============================================================================ -fn print_pattern(f: &mut Formatter, pat: &Pattern) { +fn print_pattern(f: &mut Formatter, arena: &ParseArena, pat: &Pattern) { let has_attrs = !pat.ppat_attributes.is_empty(); if has_attrs { f.string("(("); } - print_pattern_inner(f, pat); + print_pattern_inner(f, arena, pat); if has_attrs { f.string(")"); - for (name, payload) in &pat.ppat_attributes { - f.cut(); // Allow break before attribute - f.string("[@"); - f.string(&name.txt); - if !payload_is_empty(payload) { - f.string(" "); - print_payload(f, payload); - } - f.string(" ]"); - } + // OCaml: pp f "((%a)%a)" — NO cut/break between ) and attributes for patterns + // (Unlike expressions which use @, = Cut between ) and attributes) + print_attributes(f, arena, &pat.ppat_attributes); f.string(")"); } } -fn print_pattern_inner(f: &mut Formatter, pat: &Pattern) { +/// Print a pattern in "simple" context - non-simple patterns get wrapped in parens. +/// This matches OCaml's simple_pattern which wraps non-simple patterns via: +/// `| _ -> paren true (pattern ctxt) f x` +fn print_simple_pattern(f: &mut Formatter, arena: &ParseArena, pat: &Pattern) { + if pattern_is_simple(pat, arena) { + print_pattern(f, arena, pat); + } else { + f.string("("); + print_pattern(f, arena, pat); + f.string(")"); + } +} + +fn print_pattern_inner(f: &mut Formatter, arena: &ParseArena, pat: &Pattern) { match &pat.ppat_desc { PatternDesc::Ppat_any => { f.string("_"); @@ -1436,10 +2576,14 @@ fn print_pattern_inner(f: &mut Formatter, pat: &Pattern) { f.string(&name.txt); } PatternDesc::Ppat_alias(p, name) => { - // OCaml: @[<2>%a@;as@;%a@] - no outer parens - print_pattern(f, p); - f.string(" as "); + // OCaml: @[<2>%a@;as@;%a@] + f.open_box(BoxKind::Box, 2); + print_pattern(f, arena, p); + f.space(); // @; before as + f.string("as"); + f.space(); // @; after as f.string(&name.txt); + f.close_box(); } PatternDesc::Ppat_constant(c) => { // Negative numbers need parentheses in patterns @@ -1472,36 +2616,41 @@ fn print_pattern_inner(f: &mut Formatter, pat: &Pattern) { } } PatternDesc::Ppat_tuple(pats) => { + // OCaml: @[<1>(%a)@] with sep ",@;" + f.open_box(BoxKind::Box, 1); f.string("("); for (i, p) in pats.iter().enumerate() { if i > 0 { - f.string(", "); + f.string(","); + f.space(); // ,@; separator } // Alias patterns inside tuples need parentheses let needs_parens = matches!(p.ppat_desc, PatternDesc::Ppat_alias(..)); if needs_parens { f.string("("); } - print_pattern(f, p); + print_pattern(f, arena, p); if needs_parens { f.string(")"); } } f.string(")"); + f.close_box(); } PatternDesc::Ppat_construct(lid, arg) => { // Special case for cons pattern - no outer parens by default - if let Longident::Lident(name) = &lid.txt { + if let Longident::Lident(name_idx) = arena.get_longident(lid.txt) { + let name = arena.get_string(*name_idx); if name == "::" { if let Some(a) = arg { if let PatternDesc::Ppat_tuple(elements) = &a.ppat_desc { if elements.len() == 2 { // Left element needs parens if it's an alias or constraint - let left_needs_parens = pattern_needs_parens_as_param(&elements[0]); + let left_needs_parens = pattern_needs_parens_as_param(&elements[0], arena); if left_needs_parens { f.string("("); } - print_pattern(f, &elements[0]); + print_pattern(f, arena, &elements[0]); if left_needs_parens { f.string(")"); } @@ -1515,7 +2664,7 @@ fn print_pattern_inner(f: &mut Formatter, pat: &Pattern) { if right_needs_parens { f.string("("); } - print_pattern(f, &elements[1]); + print_pattern(f, arena, &elements[1]); if right_needs_parens { f.string(")"); } @@ -1525,100 +2674,144 @@ fn print_pattern_inner(f: &mut Formatter, pat: &Pattern) { } } } - print_longident(f, &lid.txt); if let Some(a) = arg { - f.string(" "); - // Alias patterns in constructor arguments need parentheses - let needs_parens = matches!(a.ppat_desc, PatternDesc::Ppat_alias(..)); - if needs_parens { - f.string("("); - } - print_pattern(f, a); - if needs_parens { - f.string(")"); - } + // OCaml: @[<2>%a@;%a@] with simple_pattern for arg + f.open_box(BoxKind::Box, 2); + print_longident_idx(f, arena, lid.txt); + f.space(); + print_simple_pattern(f, arena, a); + f.close_box(); + } else { + print_longident_idx(f, arena, lid.txt); } } PatternDesc::Ppat_variant(label, arg) => { - f.string("`"); - f.string(label); if let Some(a) = arg { - f.string(" "); - print_pattern(f, a); + // OCaml: @[<2>`%s@;%a@] with simple_pattern + f.open_box(BoxKind::Box, 2); + f.string("`"); + f.string(label); + f.space(); + print_simple_pattern(f, arena, a); + f.close_box(); + } else { + f.string("`"); + f.string(label); } } PatternDesc::Ppat_record(fields, closed) => { - f.string("{ "); + // OCaml closed: @[<2>{@;%a@;}@] with sep ";@;" + // OCaml open: @[<2>{@;%a;_}@] with sep ";@;" + f.open_box(BoxKind::Box, 2); + f.string("{"); + f.space(); // @; after { for (i, field) in fields.iter().enumerate() { if i > 0 { - f.string("; "); + f.string(";"); + f.space(); // ;@; separator } - let field_name = match &field.lid.txt { - Longident::Lident(name) => Some(name.as_str()), - Longident::Ldot(_, name) => Some(name.as_str()), - _ => None, - }; - let is_punned = if let Some(fname) = field_name { - matches!(&field.pat.ppat_desc, PatternDesc::Ppat_var(var) if var.txt == fname) - } else { - false + // OCaml only punns for simple Lident fields, not qualified Ldot fields + let is_punned = match arena.get_longident(field.lid.txt) { + Longident::Lident(name_idx) => { + let fname = arena.get_string(*name_idx); + field.pat.ppat_attributes.is_empty() && + matches!(&field.pat.ppat_desc, PatternDesc::Ppat_var(var) if var.txt == fname) + } + _ => false, }; if is_punned { - print_longident(f, &field.lid.txt); + // OCaml: @[<2>%a%s@] + f.open_box(BoxKind::Box, 2); + print_longident_idx(f, arena, field.lid.txt); + if field.opt { + f.string("?"); + } + f.close_box(); } else { - print_longident(f, &field.lid.txt); - f.string(" = "); - print_pattern(f, &field.pat); + // OCaml: @[<2>%a%s@;=@;%a@] + f.open_box(BoxKind::Box, 2); + print_longident_idx(f, arena, field.lid.txt); + if field.opt { + f.string("?"); + } + f.space(); // @; before = + f.string("="); + f.space(); // @; after = + // Print with parens for alias patterns (pattern1 context) + let needs_parens = matches!(&field.pat.ppat_desc, + PatternDesc::Ppat_alias(..) | PatternDesc::Ppat_or(..) + ); + if needs_parens { + f.string("("); + } + print_pattern(f, arena, &field.pat); + if needs_parens { + f.string(")"); + } + f.close_box(); } } if matches!(closed, ClosedFlag::Open) { f.string(";_}"); } else { - f.string(" }"); + f.space(); // @; before } + f.string("}"); } + f.close_box(); } PatternDesc::Ppat_array(pats) => { + // OCaml: pp f "@[<2>[|%a|]@]" with sep ";" + f.open_box(BoxKind::Box, 2); f.string("[|"); for (i, p) in pats.iter().enumerate() { if i > 0 { f.string(";"); } - print_pattern(f, p); + print_pattern(f, arena, p); } f.string("|]"); + f.close_box(); } PatternDesc::Ppat_or(p1, p2) => { - print_pattern(f, p1); + print_pattern(f, arena, p1); f.string("|"); - print_pattern(f, p2); + print_pattern(f, arena, p2); } PatternDesc::Ppat_constraint(p, t) => { + // OCaml: pp f "@[<2>(%a@;:@;%a)@]" (pattern1 ctxt) p (core_type ctxt) ct + f.open_box(BoxKind::Box, 2); f.string("("); - // Alias, or, and cons patterns inside constraints need extra parens + // Only alias and or patterns need extra parens (cons is handled by pattern1 without parens) let needs_inner_parens = matches!( p.ppat_desc, PatternDesc::Ppat_alias(..) | PatternDesc::Ppat_or(..) - ) || is_cons_pattern(p); + ); if needs_inner_parens { f.string("("); } - print_pattern(f, p); + print_pattern(f, arena, p); if needs_inner_parens { f.string(")"); } - f.string(" : "); - print_core_type(f, t); + f.space(); // @; before : + f.string(":"); + f.space(); // @; after : + print_core_type(f, arena, t); f.string(")"); + f.close_box(); } PatternDesc::Ppat_type(lid) => { f.string("#"); - print_longident(f, &lid.txt); + print_longident_idx(f, arena, lid.txt); } PatternDesc::Ppat_unpack(name) => { - f.string("(module "); + // OCaml: pp f "(module@ %s)@ " s.txt + f.string("(module"); + f.space(); // @ after "(module" f.string(&name.txt); f.string(")"); + f.space(); // @ trailing break } PatternDesc::Ppat_exception(p) => { f.string("exception "); @@ -1630,7 +2823,7 @@ fn print_pattern_inner(f: &mut Formatter, pat: &Pattern) { if needs_parens { f.string("("); } - print_pattern(f, p); + print_pattern(f, arena, p); if needs_parens { f.string(")"); } @@ -1640,38 +2833,70 @@ fn print_pattern_inner(f: &mut Formatter, pat: &Pattern) { f.string("[%"); f.string(&name.txt); f.space(); - print_payload(f, payload); + print_payload(f, arena, payload); f.string("]"); f.close_box(); } PatternDesc::Ppat_open(lid, p) => { - print_longident(f, &lid.txt); + print_longident_idx(f, arena, lid.txt); f.string(".("); - print_pattern(f, p); + print_pattern(f, arena, p); f.string(")"); } } } -// ============================================================================ -// Types -// ============================================================================ - -fn print_core_type(f: &mut Formatter, typ: &CoreType) { +// ============================================================================ +// Types +// ============================================================================ + +/// Print core_type at level 1 (wraps arrow and alias types in parens). +/// Matches OCaml's core_type1 which falls through to paren true (core_type ctxt) for those. +fn print_core_type1(f: &mut Formatter, arena: &ParseArena, typ: &CoreType) { + let needs_parens = matches!( + typ.ptyp_desc, + CoreTypeDesc::Ptyp_arrow { .. } | CoreTypeDesc::Ptyp_alias(..) + ); + if needs_parens { + f.string("("); + print_core_type(f, arena, typ); + f.string(")"); + } else { + print_core_type(f, arena, typ); + } +} + +fn print_core_type(f: &mut Formatter, arena: &ParseArena, typ: &CoreType) { // Types with attributes are wrapped: ((type)[@attr ]) let has_attrs = printable_attributes(&typ.ptyp_attributes).len() > 0; if has_attrs { f.string("(("); } - print_core_type_inner(f, typ); + // OCaml's core_type wraps fallthrough types (those handled by core_type1) in @[<2>...@] + // Types that already handle their own Box(2): Ptyp_arrow, Ptyp_alias, Ptyp_poly (non-empty vars) + // Ptyp_poly with empty vars just recurses into core_type, so no extra box needed + let needs_box = match &typ.ptyp_desc { + CoreTypeDesc::Ptyp_arrow { .. } => false, + CoreTypeDesc::Ptyp_alias(..) => false, + CoreTypeDesc::Ptyp_poly(vars, _) if !vars.is_empty() => false, + CoreTypeDesc::Ptyp_poly(_, _) => false, // empty vars recurses into core_type + _ => true, + }; + if needs_box { + f.open_box(BoxKind::Box, 2); + } + print_core_type_inner(f, arena, typ); + if needs_box { + f.close_box(); + } if has_attrs { f.string(")"); - print_attributes(f, &typ.ptyp_attributes); + print_attributes(f, arena, &typ.ptyp_attributes); f.string(")"); } } -fn print_core_type_inner(f: &mut Formatter, typ: &CoreType) { +fn print_core_type_inner(f: &mut Formatter, arena: &ParseArena, typ: &CoreType) { match &typ.ptyp_desc { CoreTypeDesc::Ptyp_any => { f.string("_"); @@ -1681,35 +2906,49 @@ fn print_core_type_inner(f: &mut Formatter, typ: &CoreType) { f.string(name); } CoreTypeDesc::Ptyp_arrow { arg, ret, arity } => { - print_arg_label(f, &arg.lbl); - // Arrow types as labeled args need parentheses - let arg_needs_parens = !matches!(arg.lbl, ArgLabel::Nolabel) - && matches!(arg.typ.ptyp_desc, CoreTypeDesc::Ptyp_arrow { .. }); + // OCaml: pp f "@[<2>%a@;->@;%a%s@]" + // Structural box with indent 2, break hints around -> + f.open_box(BoxKind::Box, 2); + print_arg_label(f, arena, &arg.lbl); + // Arrow and alias types as args need parentheses (OCaml's core_type1 + // wraps them via the `| _ -> paren true (core_type ctxt) f x` fallthrough) + let arg_needs_parens = matches!( + arg.typ.ptyp_desc, + CoreTypeDesc::Ptyp_arrow { .. } | CoreTypeDesc::Ptyp_alias(..) + ); if arg_needs_parens { f.string("("); } - print_core_type(f, &arg.typ); + print_core_type(f, arena, &arg.typ); if arg_needs_parens { f.string(")"); } - f.string(" -> "); - print_core_type(f, ret); + // Print attributes on the argument (after the type) + print_attributes(f, arena, &arg.attrs); + f.space(); // Break hint before -> + f.string("->"); + f.space(); // Break hint after -> + print_core_type(f, arena, ret); if let Arity::Full(n) = arity { f.string(&format!(" (a:{})", n)); } + f.close_box(); } CoreTypeDesc::Ptyp_tuple(types) => { + // OCaml: pp f "(%a)" (list (core_type1 ctxt) ~sep:"@;*@;") l f.string("("); for (i, t) in types.iter().enumerate() { if i > 0 { - f.string(" * "); + f.space(); // @; before * + f.string("*"); + f.space(); // @; after * } // Alias types inside tuple need parens for precedence let needs_parens = matches!(t.ptyp_desc, CoreTypeDesc::Ptyp_alias(..)); if needs_parens { f.string("("); } - print_core_type(f, t); + print_core_type(f, arena, t); if needs_parens { f.string(")"); } @@ -1717,58 +2956,58 @@ fn print_core_type_inner(f: &mut Formatter, typ: &CoreType) { f.string(")"); } CoreTypeDesc::Ptyp_constr(lid, args) => { - // OCaml format: list ~first:"(" ~last:")@;" (core_type ctxt) ~sep:",@;" f l - // On single line: (type , type ) constructor + // OCaml: | [x] -> pp f "%a@;" (core_type1 ctxt) x + // | _ -> list ~first:"(" ~last:")@;" (core_type ctxt) ~sep:",@;" f l if !args.is_empty() { if args.len() == 1 { - print_core_type(f, &args[0]); - // Single arg has @; after = space - f.string(" "); + // Single arg uses core_type1 (no extra Box wrapping) + print_core_type_inner(f, arena, &args[0]); + f.space(); // @; } else { f.string("("); for (i, t) in args.iter().enumerate() { if i > 0 { - // Separator is ,@; = comma + break = ", " - f.string(", "); + f.string(","); + f.space(); // ,@; } - print_core_type(f, t); + print_core_type(f, arena, t); } - // last is ")@;" = ) + break = ") " - f.string(") "); + f.string(")"); + f.space(); // )@; } } - print_longident(f, &lid.txt); + print_longident_idx(f, arena, lid.txt); } CoreTypeDesc::Ptyp_object(fields, closed) => { - // OCaml format: @[<@ %a%a@ > @] - // Field format: @[%s: %a@ %a@ @] - f.string("< "); + // OCaml: pp f "@[<@ %a%a@ > @]" + f.open_box(BoxKind::HOV, 2); + f.string("<"); + f.space(); // @ after < for (i, field) in fields.iter().enumerate() { if i > 0 { f.string(";"); } match field { ObjectField::Otag(name, attrs, typ) => { - // OCaml format: @[%s: %a@ %a@ @] - // = name: type (break) attrs (break) close_box - // On single line: name: typeattrs + // OCaml: pp f "@[%s: %a@ %a@ @]" + f.open_box(BoxKind::HOV, 2); f.string(&name.txt); f.string(": "); - print_core_type(f, typ); - // After type: @ (break = space) - f.string(" "); - // Attributes: %a then @ (break) + print_core_type(f, arena, typ); + f.space(); // @ after type let printable = printable_attributes(attrs); if !printable.is_empty() { - print_attributes(f, attrs); + print_attributes(f, arena, attrs); } - // Final break from @ before @] - f.string(" "); + f.space(); // @ before close + f.close_box(); } ObjectField::Oinherit(typ) => { - // OCaml format: @[%a@ @] - print_core_type(f, typ); - f.string(" "); + // OCaml: pp f "@[%a@ @]" + f.open_box(BoxKind::HOV, 2); + print_core_type(f, arena, typ); + f.space(); // @ after type + f.close_box(); } } } @@ -1778,27 +3017,36 @@ fn print_core_type_inner(f: &mut Formatter, typ: &CoreType) { if fields.is_empty() { f.string(".."); } else { - // Note: leading space before ;.. (combines with field's trailing space) f.string(" ;.."); } } - f.string(" > "); + f.space(); // @ before > + f.string(">"); + f.space(); // @ after > + f.close_box(); } CoreTypeDesc::Ptyp_alias(t, name) => { + // OCaml: pp f "@[<2>%a@;as@;'%s@]" (core_type1 ctxt) ct s + f.open_box(BoxKind::Box, 2); // Arrow types inside alias need parens for precedence let needs_parens = matches!(t.ptyp_desc, CoreTypeDesc::Ptyp_arrow { .. }); if needs_parens { f.string("("); } - print_core_type(f, t); + print_core_type(f, arena, t); if needs_parens { f.string(")"); } - f.string(" as '"); + f.space(); + f.string("as"); + f.space(); + f.string("'"); f.string(name); + f.close_box(); } CoreTypeDesc::Ptyp_variant(rows, closed, labels) => { - // OCaml: @[<2>[%a%a]@] with complex formatting + // OCaml: pp f "@[<2>[%a%a]@]" ... + f.open_box(BoxKind::Box, 2); f.string("["); // Empty variant cases @@ -1808,39 +3056,55 @@ fn print_core_type_inner(f: &mut Formatter, typ: &CoreType) { ClosedFlag::Closed => {} } } else { - // Non-empty: prefix + list + // Non-empty: prefix + break, then list + // OCaml: pp f "%s@;%a" prefix (list type_variant_helper ~sep:"@;<1 -2>| ") rows match (closed, &labels) { - (ClosedFlag::Closed, None) => f.string(" "), // Just break - (ClosedFlag::Closed, Some(_)) => f.string("< "), // < + break - (ClosedFlag::Open, _) => f.string("> "), // > + break + (ClosedFlag::Closed, None) => { + // Just break hint (no prefix character) + f.space(); + } + (ClosedFlag::Closed, Some(_)) => { + f.string("<"); + f.space(); + } + (ClosedFlag::Open, _) => { + f.string(">"); + f.space(); + } } for (i, row) in rows.iter().enumerate() { if i > 0 { - // Separator: @;<1 -2>| = break + " | " on same line - f.string(" | "); + // Separator: @;<1 -2>| = break with offset -2, then "| " + // The -2 offset causes the "|" to align with the "[" + f.break_(1, -2); + f.string("| "); } match row { RowField::Rtag(label, attrs, empty, types) => { // OCaml: @[<2>%a%a@;%a@] + f.open_box(BoxKind::Box, 2); f.string("`"); f.string(&label.txt); if !*empty || !types.is_empty() { - // of@; = " of " - f.string(" of "); + // of@; = " of " with break hint + f.space(); + f.string("of"); + f.space(); for (j, t) in types.iter().enumerate() { if j > 0 { f.string("&"); } - print_core_type(f, t); + print_core_type(f, arena, t); } } // Trailing break (@;) then attrs - f.string(" "); - print_attributes(f, attrs); + f.space(); + print_attributes(f, arena, attrs); + f.close_box(); } RowField::Rinherit(typ) => { - print_core_type(f, typ); + print_core_type(f, arena, typ); } } } @@ -1862,35 +3126,63 @@ fn print_core_type_inner(f: &mut Formatter, typ: &CoreType) { } } f.string("]"); + f.close_box(); } CoreTypeDesc::Ptyp_poly(vars, t) => { - if !vars.is_empty() { - for var in vars { + if vars.is_empty() { + // OCaml: Ptyp_poly ([], ct) -> core_type ctxt f ct + print_core_type(f, arena, t); + } else { + // OCaml: @[<2>%a@;.@;%a@] with tyvars separated by @; + f.open_box(BoxKind::Box, 2); + for (i, var) in vars.iter().enumerate() { + if i > 0 { + f.space(); // @; between tyvars + } f.string("'"); f.string(&var.txt); - f.string(" "); } - f.string(". "); + f.space(); // @; before . + f.string("."); + f.space(); // @; after . + print_core_type(f, arena, t); + f.close_box(); } - print_core_type(f, t); } CoreTypeDesc::Ptyp_package((lid, constraints)) => { - f.string("(module "); - print_longident(f, &lid.txt); - for (path, typ) in constraints { - f.string(" with type "); - print_longident(f, &path.txt); - f.string(" = "); - print_core_type(f, typ); + // OCaml: @[(module@ %a@ with@ %a)@] + f.open_box(BoxKind::HOV, 2); + f.string("(module"); + f.space(); // @ after "(module" + print_longident_idx(f, arena, lid.txt); + for (i, (path, typ)) in constraints.iter().enumerate() { + if i == 0 { + f.space(); // @ before "with" + f.string("with"); + f.space(); // @ after "with" + } else { + f.space(); // @ before "and" + f.string("and"); + f.space(); // @ after "and" + } + // OCaml: "type %a@ =@ %a" + f.string("type"); + f.space(); + print_longident_idx(f, arena, path.txt); + f.space(); // @ before "=" + f.string("="); + f.space(); // @ after "=" + print_core_type(f, arena, typ); } f.string(")"); + f.close_box(); } CoreTypeDesc::Ptyp_extension((name, payload)) => { f.open_box(BoxKind::H, 2); f.string("[%"); f.string(&name.txt); f.space(); - print_payload(f, payload); + print_payload(f, arena, payload); f.string("]"); f.close_box(); } @@ -1902,76 +3194,86 @@ fn print_core_type_inner(f: &mut Formatter, typ: &CoreType) { // Labels and arguments // ============================================================================ -fn print_arg_label(f: &mut Formatter, label: &ArgLabel) { +fn print_arg_label(f: &mut Formatter, arena: &ParseArena, label: &ArgLabel) { // In OCaml types, labeled arguments are printed as "label:type" without ~ match label { ArgLabel::Nolabel => {} ArgLabel::Labelled(s) => { - f.string(&s.txt); + f.string(arena.get_string(s.txt)); f.string(":"); } ArgLabel::Optional(s) => { f.string("?"); - f.string(&s.txt); + f.string(arena.get_string(s.txt)); f.string(":"); } } } /// Print arg label for expression context (uses ~) -fn print_arg_label_expr(f: &mut Formatter, label: &ArgLabel) { +fn print_arg_label_expr(f: &mut Formatter, arena: &ParseArena, label: &ArgLabel) { match label { ArgLabel::Nolabel => {} ArgLabel::Labelled(s) => { f.string("~"); - f.string(&s.txt); + f.string(arena.get_string(s.txt)); f.string(":"); } ArgLabel::Optional(s) => { f.string("?"); - f.string(&s.txt); + f.string(arena.get_string(s.txt)); f.string(":"); } } } -fn print_arg_with_label(f: &mut Formatter, label: &ArgLabel, arg: &Expression) { +fn print_arg_with_label(f: &mut Formatter, arena: &ParseArena, label: &ArgLabel, arg: &Expression) { + print_arg_with_label_ctx(f, arena, label, arg, PrintCtx::reset()); +} + +/// Context-aware version of print_arg_with_label. +/// OCaml's `label_x_expression_param ctxt` passes context through to simple_expr and expression2. +fn print_arg_with_label_ctx(f: &mut Formatter, arena: &ParseArena, label: &ArgLabel, arg: &Expression, ctx: PrintCtx) { match label { ArgLabel::Labelled(name) => { + let name_str = arena.get_string(name.txt); if let ExpressionDesc::Pexp_ident(lid) = &arg.pexp_desc { - if let Longident::Lident(arg_name) = &lid.txt { - if arg_name == &name.txt && arg.pexp_attributes.is_empty() { + if let Longident::Lident(arg_name_idx) = arena.get_longident(lid.txt) { + let arg_name = arena.get_string(*arg_name_idx); + if arg_name == name_str && arg.pexp_attributes.is_empty() { f.string("~"); - f.string(&name.txt); + f.string(name_str); return; } } } f.string("~"); - f.string(&name.txt); + f.string(name_str); f.string(":"); - // OCaml uses simple_expr which wraps non-simple exprs in parens - print_expression_simple(f, arg); + // OCaml uses simple_expr ctxt for labeled args + print_expression_simple_ctx(f, arena, arg, ctx); } ArgLabel::Optional(name) => { + let name_str = arena.get_string(name.txt); if let ExpressionDesc::Pexp_ident(lid) = &arg.pexp_desc { - if let Longident::Lident(arg_name) = &lid.txt { - if arg_name == &name.txt && arg.pexp_attributes.is_empty() { + if let Longident::Lident(arg_name_idx) = arena.get_longident(lid.txt) { + let arg_name = arena.get_string(*arg_name_idx); + if arg_name == name_str && arg.pexp_attributes.is_empty() { f.string("?"); - f.string(&name.txt); + f.string(name_str); return; } } } f.string("?"); - f.string(&name.txt); + f.string(name_str); f.string(":"); - // OCaml uses simple_expr which wraps non-simple exprs in parens - print_expression_simple(f, arg); + // OCaml uses simple_expr ctxt for optional args + print_expression_simple_ctx(f, arena, arg, ctx); } ArgLabel::Nolabel => { - // OCaml uses simple_expr which wraps non-simple exprs in parens - print_expression_simple(f, arg); + // OCaml uses expression2 ctxt for unlabeled args (label_x_expression_param -> Nolabel -> expression2) + print_expression2_ctx(f, arena, arg, ctx); } } } @@ -2040,42 +3342,52 @@ fn print_constant(f: &mut Formatter, c: &Constant) { // Longident // ============================================================================ -fn print_longident(f: &mut Formatter, lid: &Longident) { +fn print_longident(f: &mut Formatter, arena: &ParseArena, lid: &Longident) { match lid { - Longident::Lident(name) => { + Longident::Lident(name_idx) => { + let name = arena.get_string(*name_idx); f.string(name); } - Longident::Ldot(prefix, name) => { - print_longident(f, prefix); + Longident::Ldot(prefix, name_idx) => { + print_longident(f, arena, prefix); f.string("."); + let name = arena.get_string(*name_idx); f.string(name); } Longident::Lapply(m1, m2) => { - print_longident(f, m1); + print_longident(f, arena, m1); f.string("("); - print_longident(f, m2); + print_longident(f, arena, m2); f.string(")"); } } } +/// Print longident from index using arena +fn print_longident_idx(f: &mut Formatter, arena: &ParseArena, lid_idx: LidentIdx) { + print_longident(f, arena, arena.get_longident(lid_idx)); +} + // ============================================================================ // Payload // ============================================================================ -fn print_payload(f: &mut Formatter, payload: &Payload) { +fn print_payload(f: &mut Formatter, arena: &ParseArena, payload: &Payload) { match payload { Payload::PStr(items) => { // Special case: single Pstr_eval prints just the expression + // OCaml: pp f "@[<2>%a@]%a" (expression ctxt) e (item_attributes ctxt) attrs if items.len() == 1 { if let StructureItemDesc::Pstr_eval(expr, attrs) = &items[0].pstr_desc { - print_expression(f, expr); - print_item_attributes(f, attrs); + f.open_box(BoxKind::Box, 2); + print_expression(f, arena, expr); + f.close_box(); + print_item_attributes(f, arena, attrs); return; } } for (i, item) in items.iter().enumerate() { - print_structure_item(f, item); + print_structure_item(f, arena, item); if i < items.len() - 1 { f.string("\n "); } @@ -2085,7 +3397,7 @@ fn print_payload(f: &mut Formatter, payload: &Payload) { // Print signature items with : prefix and newlines between items f.string(":"); for (i, item) in sig_items.iter().enumerate() { - print_signature_item(f, item); + print_signature_item(f, arena, item); if i < sig_items.len() - 1 { f.string("\n "); } @@ -2093,14 +3405,14 @@ fn print_payload(f: &mut Formatter, payload: &Payload) { } Payload::PTyp(typ) => { f.string(":"); - print_core_type(f, typ); + print_core_type(f, arena, typ); } Payload::PPat(pat, guard) => { f.string("?"); - print_pattern(f, pat); + print_pattern(f, arena, pat); if let Some(g) = guard { f.string(" when "); - print_expression(f, g); + print_expression(f, arena, g); } } } @@ -2110,18 +3422,67 @@ fn print_payload(f: &mut Formatter, payload: &Payload) { // Type declarations // ============================================================================ -fn print_type_declaration(f: &mut Formatter, decl: &TypeDeclaration) { +/// Print record declaration: {field1: type; field2: type} +/// Matches OCaml's record_declaration: pp f "{@\n%a}" (list type_record_field ~sep:";@\n") lbls +/// Each field: @[<2>mutable? name?: type @; attrs@] +fn print_record_declaration(f: &mut Formatter, arena: &ParseArena, fields: &[LabelDeclaration]) { + // OCaml: pp f "{@\n%a}" (list type_record_field ~sep:";@\n") lbls + f.string("{"); + f.newline(); + if fields.is_empty() { + f.string("}"); + return; + } + for (i, field) in fields.iter().enumerate() { + // OCaml: @[<2>%a%s%a:@;%a@;%a@] + // mutable_flag, name, optional_flag, core_type, attributes + f.open_box(BoxKind::Box, 2); + if matches!(field.pld_mutable, MutableFlag::Mutable) { + f.string("mutable "); + } + f.string(&field.pld_name.txt); + if field.pld_optional { + f.string("?"); + } + f.string(":"); + f.space(); + print_core_type(f, arena, &field.pld_type); + f.space(); + print_attributes(f, arena, &field.pld_attributes); + f.close_box(); + if i < fields.len() - 1 { + f.string(";"); + f.newline(); + } else { + f.string("}"); + } + } +} + +fn print_type_declaration(f: &mut Formatter, arena: &ParseArena, decl: &TypeDeclaration) { if !decl.ptype_params.is_empty() { if decl.ptype_params.len() == 1 { - print_core_type(f, &decl.ptype_params[0].0); + // Print variance prefix + match decl.ptype_params[0].1 { + Variance::Covariant => f.string("+"), + Variance::Contravariant => f.string("-"), + Variance::Invariant => {} + } + print_core_type(f, arena, &decl.ptype_params[0].0); f.string(" "); } else { f.string("("); - for (i, (t, _)) in decl.ptype_params.iter().enumerate() { + for (i, (t, variance)) in decl.ptype_params.iter().enumerate() { if i > 0 { f.string(", "); } - print_core_type(f, t); + // Print variance prefix + match variance { + Variance::Covariant => f.string("+"), + Variance::Contravariant => f.string("-"), + Variance::Invariant => {} + } + print_core_type(f, arena, t); } f.string(") "); } @@ -2129,11 +3490,15 @@ fn print_type_declaration(f: &mut Formatter, decl: &TypeDeclaration f.string(&decl.ptype_name.txt); if let Some(manifest) = &decl.ptype_manifest { - f.string(" = "); + // OCaml: type_def_list prints " =" then type_declaration prints "@;private @;type" + // The break hint allows long types to wrap to the next line + f.string(" ="); if matches!(decl.ptype_private, PrivateFlag::Private) { - f.string("private "); + f.space(); // Break hint before private + f.string("private"); } - print_core_type(f, manifest); + f.space(); // Break hint before type body (OCaml's @;) + print_core_type(f, arena, manifest); } match &decl.ptype_kind { @@ -2143,313 +3508,510 @@ fn print_type_declaration(f: &mut Formatter, decl: &TypeDeclaration if matches!(decl.ptype_private, PrivateFlag::Private) { f.string(" private"); } - for (i, ctor) in ctors.iter().enumerate() { - // Each constructor starts on a new line with | prefix - if i > 0 { - f.string("\n | "); - } else { - f.string("\n | "); - } + // OCaml uses: pp f "%t%t@\n%a" intro priv (list ~sep:"@\n" constructor_declaration) xs + // Where constructor_declaration is: pp f "|@;"; ... + // This means each constructor gets @\n (force newline with indent) + |@; (break hint) + for ctor in ctors.iter() { + // OCaml: pp f "|@;"; constructor_declaration ... + // Each constructor gets @\n (force newline) + |@; (| then break hint) + f.newline(); + f.string("|"); + f.space(); // @; after | f.string(&ctor.pcd_name.txt); - match &ctor.pcd_args { - ConstructorArguments::Pcstr_tuple(args) if !args.is_empty() => { - f.string(" of "); - for (j, arg) in args.iter().enumerate() { - if j > 0 { - f.string(" * "); + // OCaml constructor_declaration: "%s%a@;%a" name args attrs + match &ctor.pcd_res { + None => { + // Non-GADT: pp f "@;of@;%a" (list (core_type1 ctxt) ~sep:"@;*@;") l + match &ctor.pcd_args { + ConstructorArguments::Pcstr_tuple(args) if !args.is_empty() => { + f.space(); // @; before "of" + f.string("of"); + f.space(); // @; after "of" + for (j, arg) in args.iter().enumerate() { + if j > 0 { + f.space(); // @; before * + f.string("*"); + f.space(); // @; after * + } + print_core_type1(f, arena, arg); + } } - print_core_type(f, arg); + ConstructorArguments::Pcstr_record(fields) => { + f.space(); // @; before "of" + f.string("of"); + f.space(); // @; after "of" + print_record_declaration(f, arena, fields); + } + _ => {} } } - ConstructorArguments::Pcstr_record(fields) => { - f.string(" of {\n "); - for (j, field) in fields.iter().enumerate() { - if j > 0 { - f.string(";\n "); + Some(res) => { + // GADT: "%s:@;%a@;%a" name args attrs + f.string(":"); + f.space(); // @; after : + match &ctor.pcd_args { + ConstructorArguments::Pcstr_tuple(args) if !args.is_empty() => { + // "%a@;->@;%a" (list core_type1 ~sep:"@;*@;") l core_type1 r + for (j, arg) in args.iter().enumerate() { + if j > 0 { + f.space(); // @; before * + f.string("*"); + f.space(); // @; after * + } + print_core_type1(f, arena, arg); + } + f.space(); // @; before -> + f.string("->"); + f.space(); // @; after -> + print_core_type1(f, arena, res); } - if matches!(field.pld_mutable, MutableFlag::Mutable) { - f.string("mutable "); + ConstructorArguments::Pcstr_record(fields) => { + print_record_declaration(f, arena, fields); + f.space(); // @; before -> + f.string("->"); + f.space(); // @; after -> + print_core_type1(f, arena, res); + } + _ => { + print_core_type1(f, arena, res); } - f.string(&field.pld_name.txt); - f.string(": "); - print_core_type(f, &field.pld_type); } - f.string("}"); } - _ => {} - } - if let Some(res) = &ctor.pcd_res { - f.string(": "); - print_core_type(f, res); } - // Trailing space after each constructor - f.string(" "); + // OCaml: @;%a for attrs (break hint before attrs) + f.space(); + print_attributes(f, arena, &ctor.pcd_attributes); } } TypeKind::Ptype_record(fields) => { + // OCaml: pp f "%t%t@;%a" intro priv (record_declaration ctxt) l + // record_declaration: pp f "{@\n%a}" outputs { then forced newline then fields then } f.string(" ="); if matches!(decl.ptype_private, PrivateFlag::Private) { f.string(" private"); } - if decl.ptype_params.len() > 1 { - f.string("\n {\n"); - } else { - f.string(" {\n"); - } - for (i, field) in fields.iter().enumerate() { - f.string(" "); - if matches!(field.pld_mutable, MutableFlag::Mutable) { - f.string("mutable "); - } - f.string(&field.pld_name.txt); - f.string(": "); - print_core_type(f, &field.pld_type); - if i < fields.len() - 1 { - f.string(" ;\n"); - } else { - f.string(" }"); - } - } + f.space(); // @; break hint + print_record_declaration(f, arena, fields); } TypeKind::Ptype_open => { - f.string(" = .."); + f.string(" ="); + if matches!(decl.ptype_private, PrivateFlag::Private) { + f.string(" private"); + } + f.string(" .."); } } - // Type attributes - print_item_attributes(f, &decl.ptype_attributes); + // Type constraints + for (ct1, ct2, _) in &decl.ptype_cstrs { + f.string(" constraint "); + print_core_type(f, arena, ct1); + f.string(" = "); + print_core_type(f, arena, ct2); + } + + // NOTE: Type attributes (ptype_attributes) are NOT printed here. + // In OCaml, item attributes are printed OUTSIDE the @[<2>...@] box + // by the caller (Pstr_type/Psig_type). } -fn print_extension_constructor(f: &mut Formatter, ext: &ExtensionConstructor) { +fn print_extension_constructor(f: &mut Formatter, arena: &ParseArena, ext: &ExtensionConstructor) { f.string(&ext.pext_name.txt); match &ext.pext_kind { ExtensionConstructorKind::Pext_decl(args, res) => { - match args { - ConstructorArguments::Pcstr_tuple(args) if !args.is_empty() => { - f.string(" of "); - for (i, arg) in args.iter().enumerate() { - if i > 0 { - f.string(" * "); + // OCaml: extension_constructor delegates to constructor_declaration + // Same format strings as constructor_declaration + match res { + None => { + // Non-GADT: "%s%a@;%a" name args attrs + match args { + ConstructorArguments::Pcstr_tuple(args) if !args.is_empty() => { + f.space(); // @; before "of" + f.string("of"); + f.space(); // @; after "of" + for (i, arg) in args.iter().enumerate() { + if i > 0 { + f.space(); // @; before * + f.string("*"); + f.space(); // @; after * + } + print_core_type1(f, arena, arg); + } } - print_core_type(f, arg); + ConstructorArguments::Pcstr_record(fields) => { + f.space(); // @; before "of" + f.string("of"); + f.space(); // @; after "of" + print_record_declaration(f, arena, fields); + } + _ => {} } - f.string(" "); + f.space(); // @; before attrs } - ConstructorArguments::Pcstr_record(fields) => { - f.string(" of {\n "); - for (i, field) in fields.iter().enumerate() { - if i > 0 { - f.string("; "); + Some(r) => { + // GADT: "%s:@;%a@;%a" name args attrs + f.string(":"); + f.space(); // @; after : + match args { + ConstructorArguments::Pcstr_tuple(args) if !args.is_empty() => { + for (i, arg) in args.iter().enumerate() { + if i > 0 { + f.space(); // @; before * + f.string("*"); + f.space(); // @; after * + } + print_core_type1(f, arena, arg); + } + f.space(); // @; before -> + f.string("->"); + f.space(); // @; after -> + print_core_type1(f, arena, r); } - if matches!(field.pld_mutable, MutableFlag::Mutable) { - f.string("mutable "); + ConstructorArguments::Pcstr_record(fields) => { + print_record_declaration(f, arena, fields); + f.space(); // @; before -> + f.string("->"); + f.space(); // @; after -> + print_core_type1(f, arena, r); + } + _ => { + print_core_type1(f, arena, r); } - f.string(&field.pld_name.txt); - f.string(": "); - print_core_type(f, &field.pld_type); } - f.string(" } "); - } - _ => { - // No args - add trailing space - f.string(" "); + f.space(); // @; before attrs } } - if let Some(r) = res { - f.string(": "); - print_core_type(f, r); - f.string(" "); - } } ExtensionConstructorKind::Pext_rebind(lid) => { // Print attributes before rebind - print_attributes(f, &ext.pext_attributes); + print_attributes(f, arena, &ext.pext_attributes); f.string(" = "); - print_longident(f, &lid.txt); + print_longident_idx(f, arena, lid.txt); return; // Don't print attributes twice } } // Print attributes - print_attributes(f, &ext.pext_attributes); + print_attributes(f, arena, &ext.pext_attributes); } // ============================================================================ // Modules // ============================================================================ -fn print_module_expr(f: &mut Formatter, mexpr: &ModuleExpr) { +fn print_module_expr(f: &mut Formatter, arena: &ParseArena, mexpr: &ModuleExpr) { // Print attributes on module expressions: ((mexpr)[@attr ]) let has_attrs = printable_attributes(&mexpr.pmod_attributes).len() > 0; if has_attrs { f.string("(("); } - print_module_expr_inner(f, mexpr); + print_module_expr_inner(f, arena, mexpr); if has_attrs { f.string(")"); - print_attributes(f, &mexpr.pmod_attributes); + print_attributes(f, arena, &mexpr.pmod_attributes); f.string(")"); } } -fn print_module_expr_inner(f: &mut Formatter, mexpr: &ModuleExpr) { +fn print_module_expr_inner(f: &mut Formatter, arena: &ParseArena, mexpr: &ModuleExpr) { match &mexpr.pmod_desc { ModuleExprDesc::Pmod_ident(lid) => { - print_longident(f, &lid.txt); + print_longident_idx(f, arena, lid.txt); } ModuleExprDesc::Pmod_structure(items) => { - f.string("struct "); - for item in items { - print_structure_item(f, item); - f.string(" "); + // OCaml: pp f "@[struct@;@[<0>%a@]@;<1 -2>end@]" with items separated by @\n + f.open_box(BoxKind::HV, 2); + f.string("struct"); + f.space(); // @; + f.open_box(BoxKind::Box, 0); + for (i, item) in items.iter().enumerate() { + if i > 0 { + f.newline(); // @\n forced newline between structure items + } + print_structure_item(f, arena, item); } + f.close_box(); + f.break_(1, -2); f.string("end"); + f.close_box(); } ModuleExprDesc::Pmod_functor(name, mtype, body) => { - f.string("functor ("); - f.string(&name.txt); if let Some(mt) = mtype { - f.string(" : "); - print_module_type(f, mt); + // OCaml: pp f "functor@ (%s@ :@ %a)@;->@;%a" + f.string("functor"); + f.space(); // @ after "functor" + f.string("("); + f.string(&name.txt); + f.space(); // @ after name + f.string(":"); + f.space(); // @ after ":" + print_module_type(f, arena, mt); + f.string(")"); + f.space(); // @; after ")" + f.string("->"); + f.space(); // @; after "->" + } else { + // OCaml: pp f "functor ()@;->@;%a" + f.string("functor ()"); + f.space(); // @; after "()" + f.string("->"); + f.space(); // @; after "->" } - f.string(") -> "); - print_module_expr(f, body); + print_module_expr(f, arena, body); } ModuleExprDesc::Pmod_apply(m1, m2) => { - print_module_expr(f, m1); + // OCaml: pp f "(%a)(%a)" - both functor and argument get parens f.string("("); - print_module_expr(f, m2); + print_module_expr(f, arena, m1); + f.string(")("); + print_module_expr(f, arena, m2); f.string(")"); } ModuleExprDesc::Pmod_constraint(m, mt) => { + // OCaml: pp f "@[(%a@ :@ %a)@]" + f.open_box(BoxKind::HOV, 2); f.string("("); - print_module_expr(f, m); - f.string(" : "); - print_module_type(f, mt); + print_module_expr(f, arena, m); + f.space(); // @ before ":" + f.string(":"); + f.space(); // @ after ":" + print_module_type(f, arena, mt); f.string(")"); + f.close_box(); } ModuleExprDesc::Pmod_unpack(e) => { - f.string("(val "); - print_expression(f, e); + // OCaml: (val@ %a) — break hint between val and expression + f.string("(val"); + f.space(); + print_expression(f, arena, e); f.string(")"); } ModuleExprDesc::Pmod_extension((name, payload)) => { - f.open_box(BoxKind::H, 2); + // OCaml: @[<2>[%%%s@ %a]@] + f.open_box(BoxKind::Box, 2); f.string("[%"); f.string(&name.txt); f.space(); - print_payload(f, payload); + print_payload(f, arena, payload); f.string("]"); f.close_box(); } } } -fn print_module_type(f: &mut Formatter, mtype: &ModuleType) { +fn print_module_type(f: &mut Formatter, arena: &ParseArena, mtype: &ModuleType) { // Print attributes on module types: ((mtype)[@attr ]) let has_attrs = printable_attributes(&mtype.pmty_attributes).len() > 0; if has_attrs { f.string("(("); } - print_module_type_inner(f, mtype); + print_module_type_inner(f, arena, mtype); if has_attrs { f.string(")"); - print_attributes(f, &mtype.pmty_attributes); + print_attributes(f, arena, &mtype.pmty_attributes); f.string(")"); } } -fn print_module_type_inner(f: &mut Formatter, mtype: &ModuleType) { +fn print_module_type_inner(f: &mut Formatter, arena: &ParseArena, mtype: &ModuleType) { match &mtype.pmty_desc { ModuleTypeDesc::Pmty_ident(lid) => { - print_longident(f, &lid.txt); + print_longident_idx(f, arena, lid.txt); } ModuleTypeDesc::Pmty_signature(items) => { - // OCaml uses HV box - breaks all items or none based on fit + // OCaml: pp f "@[@[sig@ %a@]@ end@]" + // Items separated by default "@ " = Break(1,0) (list without ~sep) + f.open_box(BoxKind::HV, 0); + f.open_box(BoxKind::HV, 2); f.string("sig"); - if items.is_empty() { - f.string(" end"); - } else { - f.string(" "); - for (i, item) in items.iter().enumerate() { - if i > 0 { - f.string(" "); - } - print_signature_item(f, item); + f.space(); // @ break hint after sig + for (i, item) in items.iter().enumerate() { + if i > 0 { + f.space(); // @ break hint between items } - f.string(" end"); + print_signature_item(f, arena, item); } + f.close_box(); + f.space(); // @ break hint before end + f.string("end"); + f.close_box(); } ModuleTypeDesc::Pmty_functor(name, arg_type, ret_type) => { - // Anonymous functors (name = "_") are printed as just "ArgType -> RetType" - // Named functors are printed as "functor (Name : ArgType) -> RetType" - if name.txt == "_" { + if arg_type.is_none() { + // OCaml: pp f "@[functor () ->@ %a@]" + f.open_box(BoxKind::HOV, 2); + f.string("functor ()"); + f.space(); + f.string("->"); + f.space(); + print_module_type(f, arena, ret_type); + f.close_box(); + } else if name.txt == "_" { + // OCaml: pp f "@[%a@ ->@ %a@]" + f.open_box(BoxKind::HOV, 2); if let Some(mt) = arg_type { - print_module_type(f, mt); + print_module_type(f, arena, mt); } - f.string(" -> "); - print_module_type(f, ret_type); + f.space(); + f.string("->"); + f.space(); + print_module_type(f, arena, ret_type); + f.close_box(); } else { - f.string("functor ("); + // OCaml: pp f "@[functor@ (%s@ :@ %a)@ ->@ %a@]" + f.open_box(BoxKind::HOV, 2); + f.string("functor"); + f.space(); + f.string("("); f.string(&name.txt); if let Some(mt) = arg_type { - f.string(" : "); - print_module_type(f, mt); + f.space(); + f.string(":"); + f.space(); + print_module_type(f, arena, mt); } - f.string(") -> "); - print_module_type(f, ret_type); + f.string(")"); + f.space(); + f.string("->"); + f.space(); + print_module_type(f, arena, ret_type); + f.close_box(); } } ModuleTypeDesc::Pmty_with(mt, constraints) => { - print_module_type(f, mt); - for constraint in constraints { - match constraint { - WithConstraint::Pwith_type(lid, decl) => { - f.string(" with type "); - print_longident(f, &lid.txt); - f.string(" = "); - if let Some(manifest) = &decl.ptype_manifest { - print_core_type(f, manifest); - } - } - WithConstraint::Pwith_module(lid1, lid2) => { - f.string(" with module "); - print_longident(f, &lid1.txt); - f.string(" = "); - print_longident(f, &lid2.txt); + // OCaml: pp f "@[(%a@ with@ %a)@]" when there are constraints + // or pp f "@[%a@]" when empty + if constraints.is_empty() { + f.open_box(BoxKind::HOV, 2); + print_module_type(f, arena, mt); + f.close_box(); + } else { + f.open_box(BoxKind::HOV, 2); + f.string("("); + print_module_type(f, arena, mt); + f.space(); + f.string("with"); + for (i, constraint) in constraints.iter().enumerate() { + if i > 0 { + f.space(); + f.string("and"); } - WithConstraint::Pwith_typesubst(lid, decl) => { - f.string(" with type "); - print_longident(f, &lid.txt); - f.string(" := "); - if let Some(manifest) = &decl.ptype_manifest { - print_core_type(f, manifest); + f.space(); + match constraint { + WithConstraint::Pwith_type(lid, decl) => { + // OCaml: pp f "type@ %a %a =@ %a" params lid type_decl + f.string("type"); + f.space(); // @ after type + // Print type params + if !decl.ptype_params.is_empty() { + if decl.ptype_params.len() == 1 { + print_core_type(f, arena, &decl.ptype_params[0].0); + f.string(" "); + } else { + f.string("("); + for (i, (t, _)) in decl.ptype_params.iter().enumerate() { + if i > 0 { + f.string(","); + } + print_core_type(f, arena, t); + } + f.string(") "); + } + } else { + f.string(" "); // space before lid when params empty + } + print_longident_idx(f, arena, lid.txt); + f.string(" ="); + f.space(); // @ after = + // type_declaration prints @; then private then manifest then constraints + f.space(); // @; in type_declaration + if decl.ptype_private == PrivateFlag::Private { + f.string("private "); + } + if let Some(manifest) = &decl.ptype_manifest { + print_core_type(f, arena, manifest); + } + // Print type constraints + for (ct1, ct2, _) in &decl.ptype_cstrs { + f.string(" constraint "); + print_core_type(f, arena, ct1); + f.string(" = "); + print_core_type(f, arena, ct2); + } + } + WithConstraint::Pwith_module(lid1, lid2) => { + f.string("module "); + print_longident_idx(f, arena, lid1.txt); + f.string(" = "); + print_longident_idx(f, arena, lid2.txt); + } + WithConstraint::Pwith_typesubst(lid, decl) => { + // Same pattern as Pwith_type but with := + f.string("type"); + f.space(); + // Print type params + if !decl.ptype_params.is_empty() { + if decl.ptype_params.len() == 1 { + print_core_type(f, arena, &decl.ptype_params[0].0); + f.string(" "); + } else { + f.string("("); + for (i, (t, _)) in decl.ptype_params.iter().enumerate() { + if i > 0 { + f.string(","); + } + print_core_type(f, arena, t); + } + f.string(") "); + } + } else { + f.string(" "); + } + print_longident_idx(f, arena, lid.txt); + f.string(" :="); + f.space(); + f.space(); + if decl.ptype_private == PrivateFlag::Private { + f.string("private "); + } + if let Some(manifest) = &decl.ptype_manifest { + print_core_type(f, arena, manifest); + } + // Print type constraints + for (ct1, ct2, _) in &decl.ptype_cstrs { + f.string(" constraint "); + print_core_type(f, arena, ct1); + f.string(" = "); + print_core_type(f, arena, ct2); + } + } + WithConstraint::Pwith_modsubst(lid1, lid2) => { + f.string("module "); + print_longident_idx(f, arena, lid1.txt); + f.string(" := "); + print_longident_idx(f, arena, lid2.txt); } - } - WithConstraint::Pwith_modsubst(lid1, lid2) => { - f.string(" with module "); - print_longident(f, &lid1.txt); - f.string(" := "); - print_longident(f, &lid2.txt); } } + f.string(")"); + f.close_box(); } } ModuleTypeDesc::Pmty_typeof(mexpr) => { f.string("module type of "); - print_module_expr(f, mexpr); + print_module_expr(f, arena, mexpr); } ModuleTypeDesc::Pmty_extension((name, payload)) => { f.open_box(BoxKind::H, 2); f.string("[%"); f.string(&name.txt); f.space(); - print_payload(f, payload); + print_payload(f, arena, payload); f.string("]"); f.close_box(); } ModuleTypeDesc::Pmty_alias(lid) => { f.string("(module "); - print_longident(f, &lid.txt); + print_longident_idx(f, arena, lid.txt); f.string(")"); } } @@ -2459,81 +4021,175 @@ fn print_module_type_inner(f: &mut Formatter, mtype: &ModuleType) { // Signature items // ============================================================================ -fn print_signature_item(f: &mut Formatter, item: &SignatureItem) { +fn print_signature_item(f: &mut Formatter, arena: &ParseArena, item: &SignatureItem) { match &item.psig_desc { SignatureItemDesc::Psig_value(vd) => { + // OCaml: pp f "@[<2>%s@ %a@ :@ %a@]%a" + f.open_box(BoxKind::Box, 2); if vd.pval_prim.is_empty() { - f.string("val "); + f.string("val"); } else { - f.string("external "); + f.string("external"); } + f.space(); f.string(&vd.pval_name.txt); - f.string(" : "); - print_core_type(f, &vd.pval_type); - for prim in &vd.pval_prim { - f.string(" = \""); - f.string(prim); - f.string("\""); + f.space(); + f.string(":"); + f.space(); + // OCaml value_description: pp f "@[%a%a@]" + f.open_box(BoxKind::HOV, 2); + print_core_type(f, arena, &vd.pval_type); + if !vd.pval_prim.is_empty() { + f.space(); + f.string("="); + f.space(); + for (i, prim) in vd.pval_prim.iter().enumerate() { + if i > 0 { + f.space(); + } + f.string("\""); + f.string(prim); + f.string("\""); + } } - print_item_attributes(f, &vd.pval_attributes); + f.close_box(); + f.close_box(); + print_item_attributes(f, arena, &vd.pval_attributes); } SignatureItemDesc::Psig_type(rec_flag, decls) => { + // OCaml: @[<2>type %a%a%s%s%a@]%a for first, @[<2>and %a@]%a for others + // Each declaration is wrapped in a box with indent 2 let rec_str = match rec_flag { RecFlag::Recursive => "", RecFlag::Nonrecursive => " nonrec", }; for (i, decl) in decls.iter().enumerate() { + if i > 0 { + f.newline(); + } + // OCaml: @[<2> - Open structural box with indent 2 for type declaration + f.open_box(BoxKind::Box, 2); if i == 0 { f.string("type"); f.string(rec_str); f.string(" "); } else { - f.string(" and "); + f.string("and "); } - print_type_declaration(f, decl); + print_type_declaration(f, arena, decl); + f.close_box(); + // OCaml: item attributes printed OUTSIDE the box + print_item_attributes(f, arena, &decl.ptype_attributes); } } SignatureItemDesc::Psig_typext(ext) => { + // Same format as Pstr_typext + f.open_box(BoxKind::HV, 2); f.string("type "); - print_longident(f, &ext.ptyext_path.txt); - f.string(" += "); - for (i, ctor) in ext.ptyext_constructors.iter().enumerate() { - if i > 0 { - f.string(" | "); + // Print type params if present + if !ext.ptyext_params.is_empty() { + if ext.ptyext_params.len() == 1 { + // Single param: no parens, like OCaml's "type _ Tid.t +=" + print_core_type(f, arena, &ext.ptyext_params[0].0); + f.string(" "); + } else { + f.string("("); + for (i, (ty, _variance)) in ext.ptyext_params.iter().enumerate() { + if i > 0 { + f.string(","); + } + print_core_type(f, arena, ty); + } + f.string(") "); } - print_extension_constructor(f, ctor); } + print_longident_idx(f, arena, ext.ptyext_path.txt); + f.string(" += "); + if matches!(ext.ptyext_private, PrivateFlag::Private) { + f.string("private "); + } + // Extra space before line break to match OCaml's "+= \n" + f.string(" "); + for ctor in ext.ptyext_constructors.iter() { + f.newline(); + f.string("| "); + print_extension_constructor(f, arena, ctor); + } + f.close_box(); + print_item_attributes(f, arena, &ext.ptyext_attributes); } SignatureItemDesc::Psig_exception(ext) => { - f.string("exception "); - print_extension_constructor(f, ext); + // OCaml: pp f "@[exception@ %a@]" + f.open_box(BoxKind::HOV, 2); + f.string("exception"); + f.space(); // @ after "exception" + print_extension_constructor(f, arena, ext); + f.close_box(); } SignatureItemDesc::Psig_module(md) => { + // OCaml has special case: if pmd_type is Pmty_alias with no attrs, use = syntax f.string("module "); f.string(&md.pmd_name.txt); + if let ModuleTypeDesc::Pmty_alias(lid) = &md.pmd_type.pmty_desc { + if md.pmd_type.pmty_attributes.is_empty() { + // module Name = Alias + f.string(" = "); + print_longident_idx(f, arena, lid.txt); + print_item_attributes(f, arena, &md.pmd_attributes); + return; + } + } + // module Name : ModuleType f.string(" : "); - print_module_type(f, &md.pmd_type); + print_module_type(f, arena, &md.pmd_type); + print_item_attributes(f, arena, &md.pmd_attributes); } SignatureItemDesc::Psig_recmodule(mds) => { + // OCaml: First decl is @[module@ rec@ %s:@ %a@]%a + // Others are @ @[and@ %s:@ %a@]%a for (i, md) in mds.iter().enumerate() { + if i > 0 { + // Break before "and" for subsequent declarations + f.break_(1, 0); + } + f.open_box(BoxKind::HOV, 2); if i == 0 { - f.string("module rec "); + f.string("module"); + f.space(); + f.string("rec"); + f.space(); } else { - f.string(" and "); + f.string("and"); + f.space(); } f.string(&md.pmd_name.txt); - f.string(" : "); - print_module_type(f, &md.pmd_type); + f.string(":"); + f.space(); + print_module_type(f, arena, &md.pmd_type); + f.close_box(); + print_item_attributes(f, arena, &md.pmd_attributes); } } SignatureItemDesc::Psig_modtype(mtd) => { - f.string("module type "); + // OCaml: pp f "@[module@ type@ %s%a@]%a" + // where inner is: pp_print_space f (); pp f "@ =@ %a" (module_type ctxt) mt + // This produces two spaces before = when not breaking: "Sig =" + f.open_box(BoxKind::HOV, 2); + f.string("module"); + f.space(); + f.string("type"); + f.space(); f.string(&mtd.pmtd_name.txt); if let Some(mt) = &mtd.pmtd_type { - // OCaml has trailing space from name + space before = - f.string(" = "); - print_module_type(f, mt); + // pp_print_space + "@ =" gives two spaces before = + f.string(" "); // literal space from pp_print_space + f.space(); // break hint before = + f.string("="); + f.space(); + print_module_type(f, arena, mt); } + f.close_box(); + print_item_attributes(f, arena, &mtd.pmtd_attributes); } SignatureItemDesc::Psig_open(od) => { f.string("open"); @@ -2541,13 +4197,17 @@ fn print_signature_item(f: &mut Formatter, item: &SignatureItem) { f.string("!"); } f.string(" "); - print_longident(f, &od.popen_lid.txt); - print_item_attributes(f, &od.popen_attributes); + print_longident_idx(f, arena, od.popen_lid.txt); + print_item_attributes(f, arena, &od.popen_attributes); } SignatureItemDesc::Psig_include(incl) => { - f.string("include "); - print_module_type(f, &incl.pincl_mod); - print_item_attributes(f, &incl.pincl_attributes); + // OCaml: @[include@ %a@]%a + f.open_box(BoxKind::HOV, 2); + f.string("include"); + f.space(); + print_module_type(f, arena, &incl.pincl_mod); + f.close_box(); + print_item_attributes(f, arena, &incl.pincl_attributes); } SignatureItemDesc::Psig_attribute((name, payload)) => { // Standalone/floating attributes use [@@@...] (3 @) @@ -2555,7 +4215,7 @@ fn print_signature_item(f: &mut Formatter, item: &SignatureItem) { f.string(&name.txt); if !payload_is_empty(payload) { f.string(" "); - print_payload(f, payload); + print_payload(f, arena, payload); } else { f.string(" "); } @@ -2566,41 +4226,44 @@ fn print_signature_item(f: &mut Formatter, item: &SignatureItem) { f.string("[%%"); f.string(&name.txt); f.space(); - print_payload(f, payload); + print_payload(f, arena, payload); f.string("]"); - print_item_attributes(f, attrs); + print_item_attributes(f, arena, attrs); f.close_box(); } } } -fn print_item_attributes(f: &mut Formatter, attrs: &[(Located, Payload)]) { +fn print_item_attributes(f: &mut Formatter, arena: &ParseArena, attrs: &[(Located, Payload)]) { + // OCaml: and item_attribute ctxt f (s, e) = pp f "@[<2>[@@@@%s@ %a]@]" s.txt (payload ctxt) e + // Each attribute is wrapped in a box with indent 2, with a break hint after the name let attrs = printable_attributes(attrs); for (name, payload) in attrs { + f.open_box(BoxKind::Box, 2); f.string("[@@"); f.string(&name.txt); + f.space(); // Break hint after name (matches OCaml's `@ `) if !payload_is_empty(payload) { - f.string(" "); - print_payload(f, payload); - f.string("]"); - } else { - f.string(" ]"); + print_payload(f, arena, payload); } + f.string("]"); + f.close_box(); } } /// Print attributes with single @ (for expressions, types, patterns) -fn print_attributes(f: &mut Formatter, attrs: &[(Located, Payload)]) { +/// OCaml: and attribute ctxt f (s, e) = pp f "@[<2>[@@%s@ %a]@]" s.txt (payload ctxt) e +fn print_attributes(f: &mut Formatter, arena: &ParseArena, attrs: &[(Located, Payload)]) { let attrs = printable_attributes(attrs); for (name, payload) in attrs { + f.open_box(BoxKind::Box, 2); f.string("[@"); f.string(&name.txt); + f.space(); // Break hint after name (matches OCaml's `@ `) if !payload_is_empty(payload) { - f.string(" "); - print_payload(f, payload); - f.string("]"); - } else { - f.string(" ]"); + print_payload(f, arena, payload); } + f.string("]"); + f.close_box(); } } diff --git a/compiler-rust/src/parser/mod.rs b/compiler-rust/src/parser/mod.rs index 72efa80da2d..811994ec374 100644 --- a/compiler-rust/src/parser/mod.rs +++ b/compiler-rust/src/parser/mod.rs @@ -51,7 +51,6 @@ pub mod module; pub mod parens; pub mod parsetree_viewer; pub mod pattern; -pub mod printer; pub mod printer2; pub mod scanner; pub mod state; @@ -72,10 +71,6 @@ pub use comment::{Comment, CommentStyle}; pub use diagnostics::{DiagnosticCategory, ParserDiagnostic}; pub use grammar::Grammar; pub use longident::{Longident, LongidentLoc}; -pub use printer::{ - Printer, print_core_type, print_expression, print_pattern, print_signature, print_structure, - print_structure_with_comments, print_structure_with_comments_and_width, print_structure_with_width, -}; pub use scanner::{ScanResult, Scanner, ScannerMode, ScannerSnapshot}; pub use state::{Parser, ParserMode, RegionStatus}; pub use token::Token; diff --git a/compiler-rust/src/parser/module.rs b/compiler-rust/src/parser/module.rs index e41f23bf130..10f6d73a1dc 100644 --- a/compiler-rust/src/parser/module.rs +++ b/compiler-rust/src/parser/module.rs @@ -5,18 +5,85 @@ use std::cell::RefCell; -use crate::location::{Located, Location, Position}; +use crate::location::Position; +use crate::parse_arena::{LidentIdx, Located, LocIdx, PosIdx}; +// Import Location as alias to LocIdx from ast use super::ast::*; -use super::core::{is_es6_arrow_functor, mknoloc, recover, with_loc}; +use super::ast::Location; +use super::core::{error_messages, is_es6_arrow_functor, mknoloc, recover, with_loc}; use super::diagnostics::DiagnosticCategory; use super::expr; +use super::grammar; +use super::grammar::Grammar; use super::longident::Longident; use super::pattern; use super::state::Parser; use super::token::Token; use super::typ; +// ============================================================================ +// Consecutive Statement/Expression Checking +// ============================================================================ + +/// Check and emit "consecutive statements" error if statements on same line without semicolon. +/// +/// Matches OCaml's `parse_newline_or_semicolon_structure`: +/// - If token is Semicolon, consume it +/// - If token can start a structure item AND on same line as previous, emit error +/// - Otherwise, do nothing +fn parse_newline_or_semicolon_structure(p: &mut Parser<'_>) { + if p.token == Token::Semicolon { + p.next(); + return; + } + + if grammar::is_structure_item_start(&p.token) { + // Check if we're on the same line as the previous token + // OCaml: if p.prev_end_pos.pos_lnum < p.start_pos.pos_lnum then () else err + if p.prev_end_pos.line >= p.start_pos.line { + // Same line: emit error + // Use err_at which respects regions (like OCaml's Parser.err) + p.err_at( + p.prev_end_pos.clone(), + p.end_pos.clone(), + DiagnosticCategory::message( + "consecutive statements on a line must be separated by ';' or a newline", + ), + ); + } + } +} + +/// Check and emit "consecutive statements" error for signature items. +/// +/// Matches OCaml's `parse_newline_or_semicolon_signature`: +/// - If token is Semicolon, consume it +/// - If token can start a signature item AND on same line as previous, emit error +/// - Otherwise, do nothing +fn parse_newline_or_semicolon_signature(p: &mut Parser<'_>) { + if p.token == Token::Semicolon { + p.next(); + return; + } + + if grammar::is_signature_item_start(&p.token) { + // Check if we're on the same line as the previous token + // OCaml: if p.prev_end_pos.pos_lnum < p.start_pos.pos_lnum then () else err + if p.prev_end_pos.line >= p.start_pos.line { + // Same line: emit error + // Use err_at which respects regions (like OCaml's Parser.err) + p.err_at( + p.prev_end_pos.clone(), + p.end_pos.clone(), + DiagnosticCategory::message( + "consecutive statements on a line must be separated by ';' or a newline", + ), + ); + } + } +} + // ============================================================================ // Inline Record Desugaring Context // ============================================================================ @@ -44,6 +111,36 @@ impl InlineTypesContext { } } +/// Parse label declarations using the parser's inline types context fields. +/// This is called from typ.rs when extracting inline records inside type constructor args. +pub fn parse_label_declarations_for_inline( + p: &mut Parser<'_>, + lbrace_pos: Option, +) -> Vec { + // Create a temporary RefCell from parser fields + // to reuse the existing parse_label_declarations logic + let inline_ctx = RefCell::new(InlineTypesContext { + found_inline_types: p.inline_types_found.take().unwrap_or_default(), + params: p.inline_types_params.clone(), + outer_name_loc: Location::none(), + }); + let current_path = p.current_type_name_path.clone(); + + let labels = parse_label_declarations( + p, + Some(&inline_ctx), + current_path.as_ref(), + lbrace_pos, + false, + ); + + // Copy back any found inline types to the parser fields + let ctx = inline_ctx.into_inner(); + p.inline_types_found = Some(ctx.found_inline_types); + + labels +} + // ============================================================================ // Helper Functions // ============================================================================ @@ -51,7 +148,7 @@ impl InlineTypesContext { /// Convert a module type to a package type (for Ptyp_package). /// For a simple module type identifier like `T`, creates `(T, [])`. /// For `T with type t = int`, creates `(T, [(t, int)])`. -fn module_type_to_package(mt: &ModuleType) -> PackageType { +fn module_type_to_package(p: &mut Parser<'_>, mt: &ModuleType) -> PackageType { match &mt.pmty_desc { ModuleTypeDesc::Pmty_ident(lid) => (lid.clone(), vec![]), ModuleTypeDesc::Pmty_with(base, constraints) => { @@ -59,11 +156,12 @@ fn module_type_to_package(mt: &ModuleType) -> PackageType { let lid = if let ModuleTypeDesc::Pmty_ident(lid) = &base.pmty_desc { lid.clone() } else { - with_loc(Longident::Lident("_".to_string()), mt.pmty_loc.clone()) + let lid_idx = p.push_lident_static("_"); + with_loc(lid_idx, mt.pmty_loc.clone()) }; // Convert WithConstraint to package type constraints - let pkg_constraints: Vec<(Loc, CoreType)> = constraints + let pkg_constraints: Vec<(Loc, CoreType)> = constraints .iter() .filter_map(|c| match c { WithConstraint::Pwith_type(type_lid, type_decl) => { @@ -85,7 +183,10 @@ fn module_type_to_package(mt: &ModuleType) -> PackageType { (lid, pkg_constraints) } - _ => (with_loc(Longident::Lident("_".to_string()), mt.pmty_loc.clone()), vec![]), + _ => { + let lid_idx = p.push_lident_static("_"); + (with_loc(lid_idx, mt.pmty_loc.clone()), vec![]) + } } } @@ -94,7 +195,13 @@ fn module_type_to_package(mt: &ModuleType) -> PackageType { // ============================================================================ /// Parse a structure (list of structure items). +/// Matches OCaml's parse_implementation which uses parse_region. +/// Note: OCaml does NOT create regions per structure item - the region is shared +/// so that after one error, subsequent errors in the same region are silenced. pub fn parse_structure(p: &mut Parser<'_>) -> Structure { + // OCaml uses parse_region with Grammar::Implementation + p.leave_breadcrumb(Grammar::Implementation); + let mut items = vec![]; while p.token != Token::Eof { @@ -112,20 +219,29 @@ pub fn parse_structure(p: &mut Parser<'_>) -> Structure { } } + p.eat_breadcrumb(); items } /// Parse a single structure item. pub fn parse_structure_item(p: &mut Parser<'_>) -> Option { - let start_pos = p.start_pos.clone(); + // Save start position as PosIdx to enable sharing with inner locations + let start_pos_idx = p.push_start_pos(); + let start_pos = p.start_pos; // Parse attributes let attrs = parse_attributes(p); + // Track the PosIdx used for this structure item's location + // For Pstr_value, this will be the same as the first binding's start + let mut item_start_idx = start_pos_idx; + // Track shared LocIdx for when we want to share the entire location (e.g., with value_binding) + let mut item_loc_idx: Option = None; + let desc = match &p.token { Token::Open => { // OCaml's popen_loc starts at 'open', not at outer attributes - let open_start = p.start_pos.clone(); + let open_start = p.start_pos; p.next(); // Check for open! override flag let override_flag = if p.token == Token::Bang { @@ -135,7 +251,8 @@ pub fn parse_structure_item(p: &mut Parser<'_>) -> Option { OverrideFlag::Fresh }; let lid = parse_module_long_ident(p); - let loc = p.mk_loc(&open_start, &p.prev_end_pos); + parse_newline_or_semicolon_structure(p); + let loc = p.mk_loc_to_prev_end(&open_start); Some(StructureItemDesc::Pstr_open(OpenDescription { popen_lid: lid, popen_override: override_flag, @@ -148,75 +265,257 @@ pub fn parse_structure_item(p: &mut Parser<'_>) -> Option { p.next(); // Position after let/let? for let.unwrap attribute location // OCaml uses p.Parser.start_pos which is the START of the NEXT token (after whitespace) - let let_end_pos = p.start_pos.clone(); + let let_end_pos = p.start_pos; let rec_flag = if p.token == Token::Rec { p.next(); RecFlag::Recursive } else { RecFlag::Nonrecursive }; - let bindings = parse_let_bindings(p, start_pos.clone(), let_end_pos, rec_flag, attrs.clone(), unwrap); + // Check for let? rec combination - not allowed + // OCaml: if rec_flag = Asttypes.Recursive && unwrap then emit error + if rec_flag == RecFlag::Recursive && unwrap { + // Error location: from start of `let?` to start of next token after `rec` + p.err_at( + start_pos.clone(), + p.start_pos.clone(), + DiagnosticCategory::Message( + "let? is not allowed to be recursive. Use a regular `let` or remove `rec`." + .to_string(), + ), + ); + } + // Pass start_pos_idx to enable position sharing with structure_item + let (bindings, _binding_loc_idx) = parse_let_bindings(p, start_pos_idx, let_end_pos, rec_flag, attrs.clone(), unwrap); + parse_newline_or_semicolon_structure(p); + // Don't share LocIdx - OCaml creates separate Location objects for pstr_loc and pvb_loc. + // The internal positions (PosIdx) are shared, but the Location records themselves are separate. Some(StructureItemDesc::Pstr_value(rec_flag, bindings)) } Token::Typ => { + // OCaml uses begin_region/end_region around type parsing + // This allows errors within one type definition to be de-duplicated, + // but errors from different type definitions can both be reported. + p.begin_region(); + let type_start = p.start_pos.clone(); // Capture 'type' keyword position - p.next(); - // `type t += ...` (type extension) vs `type t = ...` (type declaration) - let is_type_extension = p.token != Token::Rec - && p.lookahead(|state| { - // Parse the (possibly dotted) type path. + p.expect(Token::Typ); + + // OCaml's parse_type_definition_or_extension: + // 1. Parse rec/nonrec + // 2. Call parse_value_path (which accepts Uident and consumes extra token) + // 3. Parse type params + // 4. Check for PlusEqual -> type extension or type declaration + // + // When the name starts with Uident, parse_value_path's next_unsafe + // consumes an extra token (potentially = or +=), fundamentally changing + // the parsing behavior. We replicate this for Uident names. + + // Check if name starts with Uident and the path does NOT end with + // a lowercase ident. This detects error cases like `type T1 = D1` or + // `type M.T2 += D2` where OCaml's parse_value_path quirk changes behavior. + // Valid type extensions like `type Foo.Bar.t += ...` end with lident + // and should use the normal path. + let use_value_path_quirk = { + let check_uident_path = |state: &mut crate::parser::state::Parser<'_>| { + if !matches!(state.token, Token::Uident(_)) { + return false; + } + // Walk the dotted path loop { match &state.token { - Token::Lident(_) | Token::Uident(_) => { + Token::Uident(_) => { state.next(); if state.token == Token::Dot { state.next(); continue; } + // Path ended with Uident (no dot after) - this is the error case + return true; + } + Token::Lident(_) => { + // Path ends with lowercase - valid, use normal path + return false; + } + _ => { + // Something else - use value_path quirk + return true; } - _ => {} + } + } + }; + + if p.token == Token::Rec || matches!(&p.token, Token::Lident(s) if s == "nonrec") { + p.lookahead(|state| { + state.next(); // consume rec/nonrec + check_uident_path(state) + }) + } else { + p.lookahead(check_uident_path) + } + }; + + if use_value_path_quirk { + // OCaml's parse_value_path + next_unsafe behavior for Uident names + let rec_flag = if p.token == Token::Rec { + p.next(); + RecFlag::Recursive + } else if matches!(&p.token, Token::Lident(s) if s == "nonrec") { + p.next(); + RecFlag::Nonrecursive + } else { + RecFlag::Nonrecursive + }; + + let (path_parts, vp_name_start, _vp_name_end) = parse_value_path_for_type(p); + + // Parse type params (if any survive after parse_value_path consumed tokens) + let params = if p.token == Token::LessThan { + parse_type_params_angle(p) + } else { + vec![] + }; + + let result = if p.token == Token::PlusEqual { + // Type extension - build path and parse extension body + let lid_idx = super::core::build_longident_idx(p, &path_parts); + let path = with_loc(lid_idx, p.mk_loc_to_prev_end(&vp_name_start)); + + p.expect(Token::PlusEqual); + let private = if p.token == Token::Private { + p.next(); + PrivateFlag::Private + } else { + PrivateFlag::Public + }; + let mut bar_start = if p.token == Token::Bar { + let pos = p.start_pos.clone(); + p.next(); + Some(pos) + } else { + None + }; + let mut constructors = vec![]; + while p.token != Token::Eof { + constructors.push(parse_extension_constructor(p, vec![], bar_start.clone())); + if p.token == Token::Bar { + bar_start = Some(p.start_pos.clone()); + p.next(); + continue; } break; } - // Optional type params: <...> - if state.token == Token::LessThan { - let mut depth = 1; - state.next(); - while depth > 0 && state.token != Token::Eof { - match state.token { - Token::LessThan => depth += 1, - Token::GreaterThan => depth -= 1, + let ext = TypeExtension { + ptyext_path: path, + ptyext_params: params, + ptyext_constructors: constructors, + ptyext_private: private, + ptyext_attributes: attrs.clone(), + }; + parse_newline_or_semicolon_structure(p); + Some(StructureItemDesc::Pstr_typext(ext)) + } else { + // Type declaration - check for module path errors + if path_parts.len() > 1 { + // Module path already has error from parse_value_path_for_type + // OCaml emits the module path error here + let last = path_parts.last().cloned().unwrap_or_default(); + p.err_at( + vp_name_start.clone(), + p.prev_end_pos.clone(), + DiagnosticCategory::Message(format!( + "A type declaration's name cannot contain a module access. Did you mean `{}`?", + last + )), + ); + } + // OCaml: parse_value_path already consumed = or +=, + // so parse_type_equation_and_representation sees whatever comes after. + // It won't match Equal or Bar, so it returns (None, Public, Ptype_abstract). + let last = path_parts.last().cloned().unwrap_or_else(|| "_".to_string()); + let name_loc = p.mk_loc_to_prev_end(&vp_name_start); + let name = with_loc(last, name_loc); + let type_loc = p.mk_loc_to_prev_end(&type_start); + let decl = TypeDeclaration { + ptype_name: name, + ptype_params: params, + ptype_cstrs: vec![], + ptype_kind: TypeKind::Ptype_abstract, + ptype_private: PrivateFlag::Public, + ptype_manifest: None, + ptype_attributes: attrs.clone(), + ptype_loc: type_loc, + }; + parse_newline_or_semicolon_structure(p); + Some(StructureItemDesc::Pstr_type(rec_flag, vec![decl])) + }; + + p.end_region(); + result + } else { + // Normal case: name starts with Lident (or something else) + // Use the original lookahead-based approach + let is_type_extension = p.token != Token::Rec + && p.lookahead(|state| { + loop { + match &state.token { + Token::Lident(_) | Token::Uident(_) => { + state.next(); + if state.token == Token::Dot { + state.next(); + continue; + } + } _ => {} } + break; + } + if state.token == Token::LessThan { + let mut depth = 1; state.next(); + while depth > 0 && state.token != Token::Eof { + match state.token { + Token::LessThan => depth += 1, + Token::GreaterThan => depth -= 1, + _ => {} + } + state.next(); + } } - } - - state.token == Token::PlusEqual - }); + state.token == Token::PlusEqual + }); - if is_type_extension { - let ext = parse_type_extension(p, attrs.clone()); - Some(StructureItemDesc::Pstr_typext(ext)) - } else { - let mut rec_flag = if p.token == Token::Rec { - p.next(); - RecFlag::Recursive + let result = if is_type_extension { + let ext = parse_type_extension(p, attrs.clone()); + parse_newline_or_semicolon_structure(p); + Some(StructureItemDesc::Pstr_typext(ext)) } else { - RecFlag::Nonrecursive + let mut rec_flag = if p.token == Token::Rec { + p.next(); + RecFlag::Recursive + } else if matches!(&p.token, Token::Lident(s) if s == "nonrec") { + p.next(); + RecFlag::Nonrecursive + } else { + RecFlag::Nonrecursive + }; + let (decls, has_inline_types) = parse_type_declarations(p, attrs.clone(), type_start); + if has_inline_types { + rec_flag = RecFlag::Recursive; + } + parse_newline_or_semicolon_structure(p); + Some(StructureItemDesc::Pstr_type(rec_flag, decls)) }; - let (decls, has_inline_types) = parse_type_declarations(p, attrs.clone(), type_start); - // Inline record types require the type to be recursive - if has_inline_types { - rec_flag = RecFlag::Recursive; - } - Some(StructureItemDesc::Pstr_type(rec_flag, decls)) + + p.end_region(); + result } } Token::External => { p.next(); let vd = parse_value_description(p, attrs.clone(), start_pos.clone()); + parse_newline_or_semicolon_structure(p); Some(StructureItemDesc::Pstr_primitive(vd)) } Token::Exception => { @@ -224,32 +523,43 @@ pub fn parse_structure_item(p: &mut Parser<'_>) -> Option { let exception_start = p.start_pos.clone(); p.next(); let ext = parse_extension_constructor(p, attrs.clone(), Some(exception_start)); + parse_newline_or_semicolon_structure(p); Some(StructureItemDesc::Pstr_exception(ext)) } Token::Module => { + // OCaml uses begin_region/end_region around module parsing + p.begin_region(); + // Capture module_start BEFORE consuming 'module' for accurate locations let module_start = p.start_pos.clone(); p.next(); // Check for first-class module expression: module(...) - if p.token == Token::Lparen { + let result = if p.token == Token::Lparen { // Parse the first-class module, then continue with primary/binary parsing let pack_expr = super::expr::parse_first_class_module_expr_from_paren(p, start_pos.clone()); // Continue parsing the expression (handles ->, [], etc.) let expr = super::expr::parse_expr_with_operand(p, pack_expr); + parse_newline_or_semicolon_structure(p); Some(StructureItemDesc::Pstr_eval(expr, attrs.clone())) } else { - parse_module_definition(p, module_start, attrs.clone()) - } + let def = parse_module_definition(p, module_start, attrs.clone()); + parse_newline_or_semicolon_structure(p); + def + }; + + p.end_region(); + result } Token::Include => { // OCaml: parse_include_statement captures start_pos before consuming Include let include_start = p.start_pos.clone(); p.next(); let mod_expr = parse_module_expr(p); + parse_newline_or_semicolon_structure(p); Some(StructureItemDesc::Pstr_include(IncludeDeclaration { pincl_mod: mod_expr, - pincl_loc: p.mk_loc(&include_start, &p.prev_end_pos), + pincl_loc: p.mk_loc_to_prev_end(&include_start), pincl_attributes: attrs.clone(), })) } @@ -260,19 +570,22 @@ pub fn parse_structure_item(p: &mut Parser<'_>) -> Option { if p.token == Token::AtAt { p.next(); let attr = parse_attribute_body(p, attr_start); + parse_newline_or_semicolon_structure(p); Some(StructureItemDesc::Pstr_attribute(attr)) } else { // @ might be a doc comment or similar p.next(); let attr = parse_attribute_body(p, attr_start); + parse_newline_or_semicolon_structure(p); Some(StructureItemDesc::Pstr_attribute(attr)) } } Token::ModuleComment { loc, content } => { // Module-level doc comment (triple star /*** ... */) becomes a standalone res.doc attribute - let loc = loc.clone(); + let loc_cloned = loc.clone(); let content = content.clone(); p.next(); + let loc = p.from_location(&loc_cloned); let attr = super::core::doc_comment_to_attribute(loc, content); Some(StructureItemDesc::Pstr_attribute(attr)) } @@ -312,7 +625,7 @@ pub fn parse_structure_item(p: &mut Parser<'_>) -> Option { } } let id_name = parts.join("."); - let id = with_loc(id_name, p.mk_loc(&id_start, &p.prev_end_pos)); + let id = with_loc(id_name, p.mk_loc_to_prev_end(&id_start)); // Parse optional payload let payload = if p.token == Token::Lparen { p.next(); @@ -322,6 +635,7 @@ pub fn parse_structure_item(p: &mut Parser<'_>) -> Option { } else { Payload::PStr(vec![]) }; + parse_newline_or_semicolon_structure(p); Some(StructureItemDesc::Pstr_extension( (id, payload), attrs.clone(), @@ -331,12 +645,25 @@ pub fn parse_structure_item(p: &mut Parser<'_>) -> Option { // Could be an expression if is_expr_start(&p.token) { let expr = expr::parse_expr(p); + parse_newline_or_semicolon_structure(p); + Some(StructureItemDesc::Pstr_eval(expr, attrs.clone())) + } else if let Some(attr) = attrs.first() { + // OCaml: when attrs are present but no valid item follows, + // report the "Did you forget to attach" error and produce exprhole + let attr_name = &attr.0.txt; + let attr_loc = p.to_location(attr.0.loc); + p.err_at( + attr_loc.loc_start.clone(), + attr_loc.loc_end.clone(), + DiagnosticCategory::message(&error_messages::attribute_without_node(attr_name)), + ); + let expr = expr::parse_expr(p); + parse_newline_or_semicolon_structure(p); Some(StructureItemDesc::Pstr_eval(expr, attrs.clone())) } else if p.token != Token::Eof { - p.err(DiagnosticCategory::Message(format!( - "Unexpected token: {:?}", - p.token - ))); + // Use err_unexpected which creates a proper Unexpected diagnostic + // with breadcrumbs, matching OCaml's parse_region behavior + p.err_unexpected(); p.next(); None } else { @@ -346,13 +673,20 @@ pub fn parse_structure_item(p: &mut Parser<'_>) -> Option { }; // Consume trailing semicolon if present (OCaml includes this in the structure item location) + // If a semicolon is consumed, we can't share the LocIdx with value_binding because + // the structure_item location now extends past the binding's end if p.token == Token::Semicolon { p.next(); + // Clear any shared LocIdx - the semicolon extends the structure_item location + item_loc_idx = None; } desc.map(|d| StructureItem { pstr_desc: d, - pstr_loc: p.mk_loc(&start_pos, &p.prev_end_pos), + pstr_loc: match item_loc_idx { + Some(loc_idx) => loc_idx, + None => p.mk_loc_idx_to_prev_end(item_start_idx), + }, }) } @@ -361,24 +695,42 @@ pub fn parse_structure_item(p: &mut Parser<'_>) -> Option { // ============================================================================ /// Parse a signature (list of signature items). +/// +/// This matches OCaml's `parse_region p ~grammar:Grammar.Specification ~f:parse_signature_item_region`. +/// When a signature item cannot be parsed (returns None), we emit an "unexpected" error and +/// advance the token to avoid infinite loops. pub fn parse_signature(p: &mut Parser<'_>) -> Signature { + use super::core::recover::should_abort_list_parse; + use super::grammar::Grammar; + + // OCaml: Parser.leave_breadcrumb p Grammar.Specification + p.leave_breadcrumb(Grammar::Specification); + let mut items = vec![]; - while p.token != Token::Eof && p.token != Token::Rbrace { + loop { // Skip semicolons while p.token == Token::Semicolon { p.next(); } - if p.token == Token::Eof || p.token == Token::Rbrace { - break; - } - - if let Some(item) = parse_signature_item(p) { - items.push(item); + match parse_signature_item(p) { + Some(item) => items.push(item), + None => { + // OCaml's parse_region: when f returns None, check if we should abort + if p.token == Token::Eof || should_abort_list_parse(p) { + break; + } + // Emit unexpected token error and advance to avoid infinite loop + p.err_unexpected(); + p.next(); + } } } + // OCaml: Parser.eat_breadcrumb p + p.eat_breadcrumb(); + items } @@ -402,7 +754,8 @@ pub fn parse_signature_item(p: &mut Parser<'_>) -> Option { OverrideFlag::Fresh }; let lid = parse_module_long_ident(p); - let loc = p.mk_loc(&open_start, &p.prev_end_pos); + parse_newline_or_semicolon_signature(p); + let loc = p.mk_loc_to_prev_end(&open_start); Some(SignatureItemDesc::Psig_open(OpenDescription { popen_lid: lid, popen_override: override_flag, @@ -410,15 +763,32 @@ pub fn parse_signature_item(p: &mut Parser<'_>) -> Option { popen_attributes: attrs.clone(), })) } - Token::Let { .. } => { - // For signature let declarations, OCaml's value_description location - // starts at 'let', not at the attributes (different from external in structure) + Token::Let { unwrap } => { + let unwrap = *unwrap; + // For signature let declarations, OCaml uses regions + p.begin_region(); + // OCaml's value_description location starts at 'let', not at the attributes let let_pos = p.start_pos.clone(); + // If unwrap (let?), emit error - not allowed in signatures + if unwrap { + p.err_at( + start_pos.clone(), + p.end_pos.clone(), + DiagnosticCategory::Message( + "let? is not allowed in signatures. Use a regular `let` instead." + .to_string(), + ), + ); + } p.next(); let vd = parse_value_description(p, attrs.clone(), let_pos); + parse_newline_or_semicolon_signature(p); + p.end_region(); Some(SignatureItemDesc::Psig_value(vd)) } Token::Typ => { + // OCaml uses regions around type parsing in signatures + p.begin_region(); let type_start = p.start_pos.clone(); // Capture 'type' keyword position p.next(); let is_type_extension = p.token != Token::Rec @@ -453,13 +823,18 @@ pub fn parse_signature_item(p: &mut Parser<'_>) -> Option { state.token == Token::PlusEqual }); - if is_type_extension { + let result = if is_type_extension { let ext = parse_type_extension(p, attrs.clone()); + parse_newline_or_semicolon_signature(p); Some(SignatureItemDesc::Psig_typext(ext)) } else { let mut rec_flag = if p.token == Token::Rec { p.next(); RecFlag::Recursive + } else if matches!(&p.token, Token::Lident(s) if s == "nonrec") { + // Handle `type nonrec t = ...` - nonrec is a keyword in this context + p.next(); + RecFlag::Nonrecursive } else { RecFlag::Nonrecursive }; @@ -468,12 +843,16 @@ pub fn parse_signature_item(p: &mut Parser<'_>) -> Option { if has_inline_types { rec_flag = RecFlag::Recursive; } + parse_newline_or_semicolon_signature(p); Some(SignatureItemDesc::Psig_type(rec_flag, decls)) - } + }; + p.end_region(); + result } Token::External => { p.next(); let vd = parse_value_description(p, attrs.clone(), start_pos.clone()); + parse_newline_or_semicolon_signature(p); Some(SignatureItemDesc::Psig_value(vd)) } Token::Exception => { @@ -481,33 +860,42 @@ pub fn parse_signature_item(p: &mut Parser<'_>) -> Option { let exception_start = p.start_pos.clone(); p.next(); let ext = parse_extension_constructor(p, attrs.clone(), Some(exception_start)); + parse_newline_or_semicolon_signature(p); Some(SignatureItemDesc::Psig_exception(ext)) } Token::Module => { + // OCaml uses regions around module parsing in signatures + p.begin_region(); let module_start = p.start_pos.clone(); p.next(); - if p.token == Token::Typ { + let result = if p.token == Token::Typ { p.next(); let mtd = parse_module_type_declaration(p, attrs.clone(), false); + // No parse_newline_or_semicolon_signature for module type - matches OCaml Some(SignatureItemDesc::Psig_modtype(mtd)) } else if p.token == Token::Rec { p.next(); // For recursive modules, OCaml's pmd_loc includes attributes BEFORE 'module rec' // OCaml passes start_pos (captured BEFORE attributes) to parse_rec_module_spec let mds = parse_rec_module_declarations(p, attrs.clone(), start_pos.clone()); + parse_newline_or_semicolon_signature(p); Some(SignatureItemDesc::Psig_recmodule(mds)) } else { // For non-recursive modules, location starts at name (not 'module') let md = parse_module_declaration(p, attrs.clone(), None); + parse_newline_or_semicolon_signature(p); Some(SignatureItemDesc::Psig_module(md)) - } + }; + p.end_region(); + result } Token::Include => { p.next(); let mod_type = parse_module_type(p); + parse_newline_or_semicolon_signature(p); Some(SignatureItemDesc::Psig_include(IncludeDescription { pincl_mod: mod_type, - pincl_loc: p.mk_loc(&start_pos, &p.prev_end_pos), + pincl_loc: p.mk_loc_to_prev_end(&start_pos), pincl_attributes: attrs.clone(), })) } @@ -517,32 +905,43 @@ pub fn parse_signature_item(p: &mut Parser<'_>) -> Option { if p.token == Token::AtAt { p.next(); let attr = parse_attribute_body(p, attr_start); + parse_newline_or_semicolon_signature(p); Some(SignatureItemDesc::Psig_attribute(attr)) } else { p.next(); let attr = parse_attribute_body(p, attr_start); + parse_newline_or_semicolon_signature(p); Some(SignatureItemDesc::Psig_attribute(attr)) } } Token::ModuleComment { loc, content } => { // Module-level doc comment (triple star /*** ... */) becomes a standalone res.doc attribute - let loc = loc.clone(); + // Note: OCaml does NOT call parse_newline_or_semicolon_signature for ModuleComment + let loc_cloned = loc.clone(); let content = content.clone(); p.next(); + let loc = p.from_location(&loc_cloned); let attr = super::core::doc_comment_to_attribute(loc, content); Some(SignatureItemDesc::Psig_attribute(attr)) } Token::Percent | Token::PercentPercent => { let ext = parse_extension(p); + parse_newline_or_semicolon_signature(p); Some(SignatureItemDesc::Psig_extension(ext, attrs.clone())) } _ => { - if p.token != Token::Eof && p.token != Token::Rbrace { - p.err(DiagnosticCategory::Message(format!( - "Unexpected token in signature: {:?}", - p.token - ))); - p.next(); + // OCaml: when attrs are present but no valid item follows, report the error + // and return a sigitemhole placeholder + if let Some(attr) = attrs.first() { + let attr_name = &attr.0.txt; + let attr_loc = p.to_location(attr.0.loc); + p.err_at( + attr_loc.loc_start.clone(), + attr_loc.loc_end.clone(), + DiagnosticCategory::message(&error_messages::attribute_without_node(attr_name)), + ); + // Return sigitemhole as recovery + return Some(super::core::recover::default_signature_item()); } None } @@ -616,14 +1015,14 @@ pub fn parse_module_expr(p: &mut Parser<'_>) -> ModuleExpr { // OCaml line 6512: {mod_expr with pmod_loc = mk_loc start_pos p.prev_end_pos} // Override the outermost location after module application processing if let Some(primary_start) = primary_start_pos { - expr.pmod_loc = p.mk_loc(&primary_start, &p.prev_end_pos); + expr.pmod_loc = p.mk_loc_to_prev_end(&primary_start); } // Handle module constraint: M : S let expr = if p.token == Token::Colon { p.next(); let mod_type = parse_module_type(p); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); ModuleExpr { pmod_desc: ModuleExprDesc::Pmod_constraint(Box::new(expr), Box::new(mod_type)), pmod_loc: loc, @@ -697,7 +1096,7 @@ pub fn parse_module_expr_without_constraint(p: &mut Parser<'_>) -> ModuleExpr { // OCaml line 6512: {mod_expr with pmod_loc = mk_loc start_pos p.prev_end_pos} // Override the outermost location after module application processing if let Some(primary_start) = primary_start_pos { - expr.pmod_loc = p.mk_loc(&primary_start, &p.prev_end_pos); + expr.pmod_loc = p.mk_loc_to_prev_end(&primary_start); } // NOTE: We intentionally DON'T handle `: type` constraint here @@ -725,7 +1124,7 @@ fn parse_primary_module_expr(p: &mut Parser<'_>) -> ModuleExpr { let lid = parse_module_long_ident(p); ModuleExpr { pmod_desc: ModuleExprDesc::Pmod_ident(lid), - pmod_loc: p.mk_loc(&start_pos, &p.prev_end_pos), + pmod_loc: p.mk_loc_to_prev_end(&start_pos), pmod_attributes: vec![], } } @@ -734,7 +1133,7 @@ fn parse_primary_module_expr(p: &mut Parser<'_>) -> ModuleExpr { p.next(); let items = parse_structure_in_braces(p); p.expect(Token::Rbrace); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); ModuleExpr { pmod_desc: ModuleExprDesc::Pmod_structure(items), pmod_loc: loc, @@ -751,7 +1150,7 @@ fn parse_primary_module_expr(p: &mut Parser<'_>) -> ModuleExpr { if p.token == Token::Rparen { // Unit module expression: () p.next(); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); ModuleExpr { pmod_desc: ModuleExprDesc::Pmod_structure(vec![]), pmod_loc: loc, @@ -760,20 +1159,16 @@ fn parse_primary_module_expr(p: &mut Parser<'_>) -> ModuleExpr { } else { let inner = parse_module_expr(p); p.expect(Token::Rparen); - // OCaml: parse_primary_mod_expr updates the location to include the parens - // {mod_expr with pmod_loc = mk_loc start_pos p.prev_end_pos} - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); - ModuleExpr { - pmod_loc: loc, - ..inner - } + // OCaml: parse_atomic_module_expr does NOT update the location to include parens. + // It just returns mod_expr as-is, keeping the inner expression's original location. + inner } } } Token::Percent => { // Module extension let ext = parse_extension(p); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); ModuleExpr { pmod_desc: ModuleExprDesc::Pmod_extension(ext), pmod_loc: loc, @@ -806,17 +1201,17 @@ fn parse_primary_module_expr(p: &mut Parser<'_>) -> ModuleExpr { let mod_type = parse_module_type(p); // Create Ptyp_package from module type // OCaml uses colon_start for the package type location start - let pkg_loc = p.mk_loc(&colon_pos, &mod_type.pmty_loc.loc_end); + let pkg_loc = p.mk_loc(&colon_pos, &p.loc_end(mod_type.pmty_loc)); let pkg_type = CoreType { ptyp_desc: CoreTypeDesc::Ptyp_package( - module_type_to_package(&mod_type), + module_type_to_package(p, &mod_type), ), ptyp_loc: pkg_loc, ptyp_attributes: vec![], }; // OCaml: expect Rparen first, then create constraint with loc including Rparen p.expect(Token::Rparen); - let constraint_loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let constraint_loc = p.mk_loc_to_prev_end(&start_pos); Expression { pexp_desc: ExpressionDesc::Pexp_constraint( Box::new(expr), @@ -829,7 +1224,7 @@ fn parse_primary_module_expr(p: &mut Parser<'_>) -> ModuleExpr { p.expect(Token::Rparen); expr }; - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); ModuleExpr { pmod_desc: ModuleExprDesc::Pmod_unpack(Box::new(final_expr)), pmod_loc: loc, @@ -862,7 +1257,7 @@ fn parse_module_apply(p: &mut Parser<'_>, func: ModuleExpr) -> ModuleExpr { p.next(); // OCaml: let loc = mk_loc start_pos p.prev_end_pos in // For empty args, loc spans from lparen to after rparen - let loc = p.mk_loc(&lparen_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&lparen_pos); vec![ModuleExpr { pmod_desc: ModuleExprDesc::Pmod_structure(vec![]), pmod_loc: loc, @@ -893,7 +1288,7 @@ fn parse_module_apply(p: &mut Parser<'_>, func: ModuleExpr) -> ModuleExpr { // mod_expr args // Each nested apply gets loc from current result start to current arg end for arg in args { - let loc = p.mk_loc(&result.pmod_loc.loc_start, &arg.pmod_loc.loc_end); + let loc = p.mk_loc(&p.loc_start(result.pmod_loc), &p.loc_end(arg.pmod_loc)); result = ModuleExpr { pmod_desc: ModuleExprDesc::Pmod_apply(Box::new(result), Box::new(arg)), pmod_loc: loc, @@ -946,20 +1341,24 @@ fn parse_functor_arg(p: &mut Parser<'_>) -> Option { Token::Dot => { // Module path as type: Foo.Bar (punning for _ : Foo.Bar) // Continue parsing the module path - let mut lid = Longident::Lident(ident); + let ident_str_idx = p.arena_mut().push_string(ident); + let mut lid = Longident::Lident(ident_str_idx); while p.token == Token::Dot { p.next(); match &p.token { Token::Uident(name) => { - lid = Longident::Ldot(Box::new(lid), name.clone()); + let name_clone = name.clone(); + let name_str_idx = p.arena_mut().push_string(name_clone); + lid = Longident::Ldot(Box::new(lid), name_str_idx); p.next(); } _ => break, } } - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let lid_idx = p.push_longident(lid); + let loc = p.mk_loc_to_prev_end(&start_pos); let mod_type = ModuleType { - pmty_desc: ModuleTypeDesc::Pmty_ident(with_loc(lid, loc.clone())), + pmty_desc: ModuleTypeDesc::Pmty_ident(with_loc(lid_idx, loc.clone())), pmty_loc: loc, pmty_attributes: vec![], }; @@ -973,7 +1372,8 @@ fn parse_functor_arg(p: &mut Parser<'_>) -> Option { _ => { // Just Uident (punning for _ : Uident) let loc = p.mk_loc(&start_pos, &ident_end_pos); - let mod_ident = with_loc(Longident::Lident(ident), loc.clone()); + let lid_idx = p.push_lident(&ident); + let mod_ident = with_loc(lid_idx, loc.clone()); let mod_type = ModuleType { pmty_desc: ModuleTypeDesc::Pmty_ident(mod_ident), pmty_loc: loc, @@ -991,7 +1391,7 @@ fn parse_functor_arg(p: &mut Parser<'_>) -> Option { Token::Underscore => { // Anonymous parameter: _ : modtype p.next(); - let name_loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let name_loc = p.mk_loc_to_prev_end(&start_pos); p.expect(Token::Colon); let mod_type = parse_module_type(p); Some(FunctorArg { @@ -1005,7 +1405,7 @@ fn parse_functor_arg(p: &mut Parser<'_>) -> Option { // Unit parameter: () p.next(); p.expect(Token::Rparen); - let name_loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let name_loc = p.mk_loc_to_prev_end(&start_pos); Some(FunctorArg { attrs, name: with_loc("*".to_string(), name_loc), @@ -1061,7 +1461,7 @@ fn parse_functor_args(p: &mut Parser<'_>) -> Vec { if args.is_empty() { vec![FunctorArg { attrs: vec![], - name: with_loc("*".to_string(), p.mk_loc(&paren_start_pos, &p.prev_end_pos)), + name: with_loc("*".to_string(), p.mk_loc_to_prev_end(&paren_start_pos)), mod_type: None, start_pos: paren_start_pos, }] @@ -1096,8 +1496,8 @@ fn parse_functor_module_expr(p: &mut Parser<'_>) -> ModuleExpr { let rhs_module_expr = match return_type { Some(mod_type) => { let loc = p.mk_loc( - &rhs_module_expr.pmod_loc.loc_start, - &mod_type.pmty_loc.loc_end, + &p.loc_start(rhs_module_expr.pmod_loc), + &p.loc_end(mod_type.pmty_loc), ); ModuleExpr { pmod_desc: ModuleExprDesc::Pmod_constraint( @@ -1130,6 +1530,10 @@ fn parse_functor_module_expr(p: &mut Parser<'_>) -> ModuleExpr { /// Parse structure items within braces. fn parse_structure_in_braces(p: &mut Parser<'_>) -> Vec { + // OCaml uses parse_delimited_region ~grammar:Grammar.Structure ~closing:Rbrace + // The Structure breadcrumb is needed so that error recovery (skip_tokens_and_maybe_retry) + // knows that Rbrace is a list terminator and shouldn't be consumed + p.leave_breadcrumb(Grammar::Structure); let mut items = vec![]; while p.token != Token::Rbrace && p.token != Token::Eof { @@ -1147,6 +1551,7 @@ fn parse_structure_in_braces(p: &mut Parser<'_>) -> Vec { } } + p.eat_breadcrumb(); items } @@ -1172,11 +1577,13 @@ fn parse_module_type_no_with(p: &mut Parser<'_>) -> ModuleType { } fn parse_module_type_impl(p: &mut Parser<'_>, es6_arrow: bool, parse_with: bool) -> ModuleType { - let start_pos = p.start_pos.clone(); - // Parse attributes (e.g. `@attr module type of M`) let attrs = parse_attributes(p); + // Capture start position AFTER attributes - OCaml's module type locations + // don't include leading attributes + let start_pos = p.start_pos.clone(); + // Parse functor types first (if allowed), then fall back to primary module types. let typ = if es6_arrow { parse_functor_module_type(p) @@ -1184,27 +1591,27 @@ fn parse_module_type_impl(p: &mut Parser<'_>, es6_arrow: bool, parse_with: bool) parse_primary_module_type(p) }; + // OCaml attaches attributes to the inner module type BEFORE parsing `with` constraints. + // This means `@attr Foo with type t = int` becomes `Pmty_with(Foo[@attr], constraints)`, + // not `Pmty_with(Foo, constraints)[@attr]`. + let mut typ = typ; + if !attrs.is_empty() { + typ.pmty_attributes.extend(attrs); + } + // Handle with constraint: S with type t = ... // Only if parse_with is true - functor bodies don't parse `with` so it applies to the outer functor if parse_with && matches!(&p.token, Token::Lident(s) if s == "with") { p.next(); let constraints = parse_with_constraints(p); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); - let mut result = ModuleType { + let loc = p.mk_loc_to_prev_end(&start_pos); + ModuleType { pmty_desc: ModuleTypeDesc::Pmty_with(Box::new(typ), constraints), pmty_loc: loc, pmty_attributes: vec![], - }; - if !attrs.is_empty() { - result.pmty_attributes.extend(attrs); } - result } else { - let mut result = typ; - if !attrs.is_empty() { - result.pmty_attributes.extend(attrs); - } - result + typ } } @@ -1221,7 +1628,7 @@ fn parse_functor_module_type(p: &mut Parser<'_>) -> ModuleType { p.next(); // Use parse_module_type_no_with so `with` constraints apply to the outer functor let body = parse_module_type_no_with(p); - let loc = p.mk_loc(&start_pos, &body.pmty_loc.loc_end); + let loc = p.mk_loc_to_end_of(&start_pos, body.pmty_loc); return ModuleType { pmty_desc: ModuleTypeDesc::Pmty_functor( mknoloc("_".to_string()), @@ -1277,7 +1684,7 @@ fn parse_paren_functor_module_type(p: &mut Parser<'_>) -> ModuleType { let start_pos = functor_start.clone(); p.next(); // OCaml creates a location spanning the `()` for the `*` param name - let name_loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let name_loc = p.mk_loc_to_prev_end(&start_pos); params.push(FunctorParam { name: with_loc("*".to_string(), name_loc), param: None, @@ -1294,7 +1701,7 @@ fn parse_paren_functor_module_type(p: &mut Parser<'_>) -> ModuleType { Token::Underscore => { p.next(); // OCaml's arg_name location spans from start_pos (before attrs) to end of `_` - let name_loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let name_loc = p.mk_loc_to_prev_end(&start_pos); let name = with_loc("_".to_string(), name_loc); let param = if p.token == Token::Colon { p.next(); @@ -1320,7 +1727,7 @@ fn parse_paren_functor_module_type(p: &mut Parser<'_>) -> ModuleType { let name = match &p.token { Token::Lident(n) | Token::Uident(n) => { let n = n.clone(); - let loc = p.mk_loc(&p.start_pos, &p.end_pos); + let loc = p.mk_loc_current(); p.next(); with_loc(n, loc) } @@ -1355,7 +1762,7 @@ fn parse_paren_functor_module_type(p: &mut Parser<'_>) -> ModuleType { p.next(); p.expect(Token::Rparen); // OCaml creates a location spanning the `()` for the `*` param name - let name_loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let name_loc = p.mk_loc_to_prev_end(&start_pos); params.push(FunctorParam { name: with_loc("*".to_string(), name_loc), param: None, @@ -1390,7 +1797,7 @@ fn parse_paren_functor_module_type(p: &mut Parser<'_>) -> ModuleType { p.expect(Token::EqualGreater); // Use parse_module_type_no_with so `with` constraints apply to the outer functor let body = parse_module_type_no_with(p); - let end_pos = body.pmty_loc.loc_end.clone(); + let end_pos = p.loc_end(body.pmty_loc); // OCaml includes the opening `(` in the outermost Pmty_functor location // For inner functors (in multi-param), use the param's start position @@ -1429,7 +1836,7 @@ fn parse_primary_module_type(p: &mut Parser<'_>) -> ModuleType { let lid = parse_module_long_ident(p); ModuleType { pmty_desc: ModuleTypeDesc::Pmty_ident(lid), - pmty_loc: p.mk_loc(&start_pos, &p.prev_end_pos), + pmty_loc: p.mk_loc_to_prev_end(&start_pos), pmty_attributes: vec![], } } @@ -1438,7 +1845,7 @@ fn parse_primary_module_type(p: &mut Parser<'_>) -> ModuleType { p.next(); let items = parse_signature_in_braces(p); p.expect(Token::Rbrace); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); ModuleType { pmty_desc: ModuleTypeDesc::Pmty_signature(items), pmty_loc: loc, @@ -1451,7 +1858,7 @@ fn parse_primary_module_type(p: &mut Parser<'_>) -> ModuleType { p.expect(Token::Rparen); // OCaml updates the location to include the parentheses ModuleType { - pmty_loc: p.mk_loc(&start_pos, &p.prev_end_pos), + pmty_loc: p.mk_loc_to_prev_end(&start_pos), ..inner } } @@ -1463,7 +1870,7 @@ fn parse_primary_module_type(p: &mut Parser<'_>) -> ModuleType { if p.token == Token::Of { p.next(); let mod_expr = parse_module_expr(p); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); return ModuleType { pmty_desc: ModuleTypeDesc::Pmty_typeof(Box::new(mod_expr)), pmty_loc: loc, @@ -1479,7 +1886,7 @@ fn parse_primary_module_type(p: &mut Parser<'_>) -> ModuleType { Token::Percent => { // Module type extension let ext = parse_extension(p); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); ModuleType { pmty_desc: ModuleTypeDesc::Pmty_extension(ext), pmty_loc: loc, @@ -1496,24 +1903,44 @@ fn parse_primary_module_type(p: &mut Parser<'_>) -> ModuleType { } /// Parse signature items within braces. +/// +/// Like parse_signature, this matches OCaml's parse_region behavior. +/// When a signature item cannot be parsed, we emit an error and advance. +/// +/// Note: Uses Grammar::Signature (not Specification) because Signature terminates on Rbrace. fn parse_signature_in_braces(p: &mut Parser<'_>) -> Vec { + use super::core::recover::should_abort_list_parse; + use super::grammar::Grammar; + + // OCaml: Parser.leave_breadcrumb p Grammar.Signature (not Specification!) + // Grammar.Signature terminates on Rbrace, while Specification doesn't. + p.leave_breadcrumb(Grammar::Signature); + let mut items = vec![]; - while p.token != Token::Rbrace && p.token != Token::Eof { + loop { // Skip semicolons while p.token == Token::Semicolon { p.next(); } - if p.token == Token::Rbrace || p.token == Token::Eof { - break; - } - - if let Some(item) = parse_signature_item(p) { - items.push(item); + match parse_signature_item(p) { + Some(item) => items.push(item), + None => { + // OCaml's parse_region: when f returns None, check if we should abort + if p.token == Token::Eof || should_abort_list_parse(p) { + break; + } + // Emit unexpected token error and advance to avoid infinite loop + p.err_unexpected(); + p.next(); + } } } + // OCaml: Parser.eat_breadcrumb p + p.eat_breadcrumb(); + items } @@ -1542,7 +1969,7 @@ fn parse_with_constraint(p: &mut Parser<'_>) -> Option { Token::Typ => { p.next(); let lid = parse_type_long_ident(p); - let type_name = lid.txt.last().to_string(); + let type_name = p.arena().lident_last(lid.txt).to_string(); let type_loc = lid.loc.clone(); // Parse type parameters if present (angle bracket syntax: <'a, 'b>) @@ -1569,27 +1996,30 @@ fn parse_with_constraint(p: &mut Parser<'_>) -> Option { let typ = typ::parse_typ_expr(p); // Parse type constraints: constraint 'a = int constraint 'b = string + // Note: type variables can be uppercase ('X) or lowercase ('a) let mut cstrs = vec![]; while p.token == Token::Constraint { let cstr_start = p.start_pos.clone(); p.next(); p.expect(Token::SingleQuote); - let var = if let Token::Lident(name) = &p.token { - let name = name.clone(); - // OCaml: ident_loc spans from 'constraint' keyword to end of identifier - let loc = p.mk_loc(&cstr_start, &p.end_pos); - p.next(); - CoreType { - ptyp_desc: CoreTypeDesc::Ptyp_var(name), - ptyp_loc: loc, - ptyp_attributes: vec![], + // Accept both Lident ('a) and Uident ('X) as type variable names + let var = match &p.token { + Token::Lident(name) | Token::Uident(name) => { + let name = name.clone(); + // OCaml: ident_loc spans from 'constraint' keyword to end of identifier + let loc = p.mk_loc_to_end(&cstr_start); + p.next(); + CoreType { + ptyp_desc: CoreTypeDesc::Ptyp_var(name), + ptyp_loc: loc, + ptyp_attributes: vec![], + } } - } else { - break; + _ => break, }; p.expect(Token::Equal); let cstr_typ = typ::parse_typ_expr(p); - cstrs.push((var, cstr_typ, p.mk_loc(&cstr_start, &p.prev_end_pos))); + cstrs.push((var, cstr_typ, p.mk_loc_to_prev_end(&cstr_start))); } let decl = TypeDeclaration { @@ -1666,6 +2096,8 @@ fn is_expr_start(token: &Token) -> bool { | Token::Hash | Token::Backtick | Token::Percent + | Token::Forwardslash + | Token::ForwardslashDot | Token::Underscore ) } @@ -1673,7 +2105,7 @@ fn is_expr_start(token: &Token) -> bool { /// Parse a module long identifier. /// Handles both module paths (Foo.Bar.Baz) and module type paths (Foo.Bar.t). /// Module type names are typically lowercase (e.g., RGLEvents.t). -fn parse_module_long_ident(p: &mut Parser<'_>) -> Loc { +fn parse_module_long_ident(p: &mut Parser<'_>) -> Loc { let start_pos = p.start_pos.clone(); let mut path_parts = vec![]; @@ -1706,13 +2138,86 @@ fn parse_module_long_ident(p: &mut Parser<'_>) -> Loc { path_parts.push("Error".to_string()); } - let lid = super::core::build_longident(&path_parts); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); - with_loc(lid, loc) + let lid_idx = super::core::build_longident_idx(p, &path_parts); + let loc = p.mk_loc_to_prev_end(&start_pos); + with_loc(lid_idx, loc) +} + +/// Replicate OCaml's parse_value_path behavior for Uident type names. +/// +/// OCaml's parse_value_path has a quirk when the name starts with Uident: +/// - Its internal `aux` function always calls `Parser.next` (consuming current token) +/// - After aux returns, `Parser.next_unsafe` always consumes one additional token +/// +/// This means for `type T1 = D1`: aux consumes `T1`, next_unsafe consumes `=`, +/// so the type equation parser never sees `=` → abstract type, and `D1` becomes +/// a standalone expression. +/// +/// Returns (path_parts, name_start_pos, name_end_pos). +fn parse_value_path_for_type(p: &mut Parser<'_>) -> (Vec, Position, Position) { + let name_start = p.start_pos.clone(); + + // Recursive aux function that mirrors OCaml's aux in parse_value_path + fn aux(p: &mut Parser<'_>, path_parts: &mut Vec) { + // Save current token info BEFORE advancing (like OCaml) + let saved_token = p.token.clone(); + let saved_start = p.start_pos.clone(); + let saved_end = p.end_pos.clone(); + + // Push the current name + if let Token::Uident(name) | Token::Lident(name) = &saved_token { + path_parts.push(name.clone()); + } + + // Always advance (OCaml: Parser.next p) + p.next(); + + if p.token == Token::Dot { + // Consume the dot + p.expect(Token::Dot); + + match &p.token { + Token::Lident(name) => { + // Terminal: lowercase ident ends the path + path_parts.push(name.clone()); + // Don't consume - let it be consumed by next_unsafe below + } + Token::Uident(_) => { + // Recurse for more path segments + aux(p, path_parts); + return; + } + _ => { + // Error: unexpected token after dot + p.err_unexpected(); + path_parts.push("_".to_string()); + } + } + } else { + // Not a dot - emit lident error (OCaml: Diagnostics.lident token) + // The error points at the saved token's position + p.err_at( + saved_start, + saved_end, + DiagnosticCategory::Lident(saved_token), + ); + // Return path as-is (OCaml returns `path`) + return; + } + } + + let mut path_parts = Vec::new(); + aux(p, &mut path_parts); + + // OCaml: Parser.next_unsafe p - consume one more token + let name_end = p.prev_end_pos.clone(); + p.next_unsafe(); + + (path_parts, name_start, name_end) } /// Parse a type long identifier. -fn parse_type_long_ident(p: &mut Parser<'_>) -> Loc { +fn parse_type_long_ident(p: &mut Parser<'_>) -> Loc { let start_pos = p.start_pos.clone(); let mut path_parts = vec![]; @@ -1743,31 +2248,44 @@ fn parse_type_long_ident(p: &mut Parser<'_>) -> Loc { path_parts.push("error".to_string()); } - let lid = super::core::build_longident(&path_parts); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); - with_loc(lid, loc) + let lid_idx = super::core::build_longident_idx(p, &path_parts); + let loc = p.mk_loc_to_prev_end(&start_pos); + with_loc(lid_idx, loc) } /// Parse let bindings. -/// `start_pos` should be the position BEFORE the `let` keyword for the first binding. +/// `start_pos_idx` should be the PosIdx BEFORE the `let` keyword for the first binding. /// `let_end_pos` should be the position AFTER the `let`/`let?` keyword (for let.unwrap attribute location). +/// Using PosIdx for start_pos enables position sharing with the structure_item location. +/// Returns (bindings, Option) where LocIdx is Some only when there's exactly one binding +/// (to enable sharing with structure_item). For multiple bindings, returns None and the caller +/// should create a fresh location spanning all bindings. fn parse_let_bindings( p: &mut Parser<'_>, - start_pos: Position, + start_pos_idx: PosIdx, let_end_pos: Position, _rec_flag: RecFlag, outer_attrs: Attributes, unwrap: bool, -) -> Vec { +) -> (Vec, Option) { let mut bindings = vec![]; - let mut binding_start = start_pos.clone(); + // For the first binding, use the passed-in PosIdx to enable sharing + let mut binding_start_idx = start_pos_idx; + // Track the first binding's LocIdx for sharing with structure_item + let mut first_binding_loc: Option = None; // Track the location for let.unwrap attribute // For first binding: from start_pos to let_end_pos // For and bindings: captured at end of previous iteration when we see 'and' + let start_pos = *p.arena().get_position(start_pos_idx); let mut unwrap_attr_start = start_pos; let mut unwrap_attr_end = let_end_pos; loop { + // OCaml's parse_let_binding_body uses begin_region and leave_breadcrumb(LetBinding) + // for each binding. This allows proper error messages and error de-duplication. + p.begin_region(); + p.leave_breadcrumb(Grammar::LetBinding); + let mut attrs = parse_attributes(p); // Handle `and` after attributes: `@attr and foo = ...` @@ -1793,7 +2311,10 @@ fn parse_let_bindings( )); } + // OCaml sets Pattern breadcrumb before parsing the pattern + p.leave_breadcrumb(Grammar::Pattern); let pat = pattern::parse_pattern(p); + p.eat_breadcrumb(); // Handle optional type annotation: let x: int = ... // Also track locally abstract types for Pexp_newtype wrapping @@ -1806,7 +2327,11 @@ fn parse_let_bindings( // OCaml uses parse_poly_type_expr here (not parse_typ_expr) // This has special handling for `'a => T` to exclude the `'` from arrow location - let typ = typ::parse_poly_type_expr(p); + let typ = if is_locally_abstract { + typ::parse_locally_abstract_type(p) + } else { + typ::parse_poly_type_expr(p) + }; // Extract type variables and inner type if this is a Ptyp_poly from `type a.` syntax // The inner type is used directly for Pexp_constraint (with Ptyp_constr for type vars) @@ -1821,7 +2346,7 @@ fn parse_let_bindings( let inner_for_constraint = (*inner).clone(); // Substitute Ptyp_constr -> Ptyp_var for the Ptyp_poly body - let substituted_inner = typ::substitute_type_vars((*inner).clone(), &var_set); + let substituted_inner = typ::substitute_type_vars(p.arena(), (*inner).clone(), &var_set); // Rebuild the Ptyp_poly with the substituted body let substituted_typ = CoreType { @@ -1836,7 +2361,7 @@ fn parse_let_bindings( }; // Create a constraint pattern - let loc = p.mk_loc(&pat.ppat_loc.loc_start, &final_typ.ptyp_loc.loc_end); + let loc = p.mk_loc_spanning(pat.ppat_loc, final_typ.ptyp_loc); let pat = Pattern { ppat_desc: PatternDesc::Ppat_constraint(Box::new(pat), final_typ), ppat_loc: loc, @@ -1849,9 +2374,16 @@ fn parse_let_bindings( p.expect(Token::Equal); let mut expr = expr::parse_expr(p); + // OCaml: over_parse_constrained_or_coerced_or_arrow_expression on the let binding value + expr = expr::over_parse_constrained_or_coerced_or_arrow_expression(p, expr); // Compute binding location BEFORE wrapping (OCaml uses this for locally abstract type locations) - let binding_loc = p.mk_loc(&binding_start, &p.prev_end_pos); + // Use PosIdx-based location to enable sharing with structure_item + let binding_loc = p.mk_loc_idx_to_prev_end(binding_start_idx); + // Track the first binding's LocIdx for sharing with structure_item + if first_binding_loc.is_none() { + first_binding_loc = Some(binding_loc); + } // For locally abstract types, OCaml uses the binding location for the pattern constraint and Ptyp_poly let pat = if is_locally_abstract { @@ -1910,15 +2442,20 @@ fn parse_let_bindings( pvb_loc: loc, }); + // End the region and breadcrumb for this binding + p.eat_breadcrumb(); + p.end_region(); + // Check for `and` to continue with more bindings. // Also handle attributes/doc comments before `and`: `@attr and ...` or `/** doc */ and ...` if p.token == Token::And { // Capture `and` keyword location for let.unwrap attribute in next binding // OCaml uses p.Parser.start_pos and p.Parser.end_pos (before consuming 'and') - unwrap_attr_start = p.start_pos.clone(); - unwrap_attr_end = p.end_pos.clone(); + unwrap_attr_start = p.start_pos; + unwrap_attr_end = p.end_pos; // Capture start position BEFORE consuming `and` for next binding - binding_start = p.start_pos.clone(); + // For `and` bindings, we push a fresh position (no sharing needed with structure_item) + binding_start_idx = p.push_start_pos(); p.next(); } else if matches!(p.token, Token::At | Token::AtAt | Token::DocComment { .. }) { // Look ahead to see if attributes/doc comments are followed by And @@ -1941,14 +2478,21 @@ fn parse_let_bindings( break; } // Capture start position BEFORE the attributes for next binding - binding_start = p.start_pos.clone(); + binding_start_idx = p.push_start_pos(); // Continue - attributes will be parsed in the next iteration, and `and` will be consumed there } else { break; } } - bindings + // Return bindings and optionally the LocIdx for sharing with structure_item. + // Only share when there's exactly one binding - for multiple bindings, the structure_item + // should span all bindings which is different from the first binding's location. + if bindings.len() == 1 { + (bindings, first_binding_loc) + } else { + (bindings, None) + } } /// Parse type declarations. Returns the declarations and a flag indicating if inline types were found. @@ -2060,22 +2604,47 @@ fn parse_type_extension(p: &mut Parser<'_>, attrs: Attributes) -> TypeExtension let start_pos = p.start_pos.clone(); // Parse the extended type path (e.g. t or M.t). + // OCaml's parse_value_path expects the last segment to be lowercase. + // If an Uident is seen without a following dot, emit Lident diagnostic. let mut parts: Vec = vec![]; + let mut last_was_uident = false; + let mut last_uident_name = String::new(); + let mut last_uident_start = p.start_pos.clone(); + let mut last_uident_end = p.end_pos.clone(); loop { match &p.token { - Token::Lident(name) | Token::Uident(name) => { + Token::Lident(name) => { + parts.push(name.clone()); + last_was_uident = false; + p.next(); + } + Token::Uident(name) => { + last_uident_name = name.clone(); + last_uident_start = p.start_pos.clone(); + last_uident_end = p.end_pos.clone(); parts.push(name.clone()); + last_was_uident = true; p.next(); } _ => break, } if p.token == Token::Dot { + last_was_uident = false; // After a dot, the Uident is fine (it's a module) p.next(); continue; } break; } + // If the last segment was an Uident (not followed by a dot), emit error + if last_was_uident && !parts.is_empty() { + p.err_at( + last_uident_start, + last_uident_end, + DiagnosticCategory::Lident(Token::Uident(last_uident_name)), + ); + } + if parts.is_empty() { p.err(DiagnosticCategory::Message( "Expected type name for type extension".to_string(), @@ -2083,7 +2652,8 @@ fn parse_type_extension(p: &mut Parser<'_>, attrs: Attributes) -> TypeExtension parts.push("Error".to_string()); } - let path = with_loc(super::core::build_longident(&parts), p.mk_loc(&start_pos, &p.prev_end_pos)); + let lid_idx = super::core::build_longident_idx(p, &parts); + let path = with_loc(lid_idx, p.mk_loc_to_prev_end(&start_pos)); // Optional type params: <'a, +'b, -'c> let params = if p.token == Token::LessThan { @@ -2145,18 +2715,102 @@ fn parse_type_declaration_with_context( let attrs = [outer_attrs, inner_attrs].concat(); // Parse type name first (ReScript uses t<'a> not 'a t syntax) + // OCaml's approach: parse a value_path first, then check if it's a simple Lident. + // If it's a dotted path (Foo.bar), emit "A type declaration's name cannot contain a module access". + // If it's just an Uident (T1), emit "Did you mean `t1` instead of `T1`?" let name = match &p.token { Token::Lident(n) => { let n = n.clone(); - let loc = p.mk_loc(&p.start_pos, &p.end_pos); + let loc = p.mk_loc_current(); p.next(); - with_loc(n, loc) + // Check for module path after the name (e.g., `foo.bar`) + // Type declarations cannot have module paths - but we should parse them to give better errors + if p.token == Token::Dot { + // This is a dotted path like `foo.bar` - type names can't have module access + let mut parts = vec![n.clone()]; + while p.token == Token::Dot { + p.next(); + match &p.token { + Token::Lident(s) | Token::Uident(s) => { + parts.push(s.clone()); + p.next(); + } + _ => break, + } + } + let last = parts.last().cloned().unwrap_or_default(); + p.err(DiagnosticCategory::Message(format!( + "A type declaration's name cannot contain a module access. Did you mean `{}`?", + last + ))); + // Use the last part as the name for error recovery + with_loc(last, loc) + } else { + with_loc(n, loc) + } + } + Token::Uident(n) => { + // Parse the full path to give a better error message + let n = n.clone(); + let name_start = p.start_pos.clone(); + p.next(); + let name_end = p.prev_end_pos.clone(); + + // Check for module path + let is_dotted = p.token == Token::Dot; + let mut last_name = n.clone(); + if is_dotted { + while p.token == Token::Dot { + p.next(); + match &p.token { + Token::Lident(s) | Token::Uident(s) => { + last_name = s.clone(); + p.next(); + } + _ => break, + } + } + } + + let loc = p.mk_loc(&name_start, &name_end); + if is_dotted { + // Dotted path like Foo.bar - type names can't have module access + p.err_at( + name_start.clone(), + p.prev_end_pos.clone(), + DiagnosticCategory::Message(format!( + "A type declaration's name cannot contain a module access. Did you mean `{}`?", + last_name + )), + ); + } else { + // Just an uppercase name - suggest lowercase + p.err_at( + name_start.clone(), + p.prev_end_pos.clone(), + DiagnosticCategory::Lident(Token::Uident(n.clone())), + ); + } + // Use lowercase version for error recovery + let lower = last_name.chars().next().map(|c| c.to_lowercase().collect::() + &last_name[1..]).unwrap_or(last_name); + with_loc(lower, loc) + } + Token::Eof => { + // EOF uses Unexpected diagnostic like OCaml's parse_lident + p.err_unexpected(); + // OCaml: returns ("_", loc) for error recovery, creating a placeholder type + let loc = p.mk_loc_to_prev_end(&start_pos); + with_loc("_".to_string(), loc) } _ => { - p.err(DiagnosticCategory::Message( - "Expected type name".to_string(), - )); - return None; + // OCaml: parse_lident emits Lident diagnostic and returns ("_", loc) + p.err(DiagnosticCategory::Lident(p.token.clone())); + // Try to recover - if there's something on the same line, skip it + if p.token.is_keyword() && p.prev_end_pos.line == p.start_pos.line { + p.next(); + } + let loc = p.mk_loc_to_prev_end(&start_pos); + with_loc("_".to_string(), loc) } }; @@ -2171,8 +2825,10 @@ fn parse_type_declaration_with_context( let paren_end = p.prev_end_pos.clone(); // Emit helpful error about angle bracket syntax + // Use err_at (not err_multiple) so the region is silenced after this error, + // matching OCaml's behavior where only one error per region is reported. let suggested = format_type_with_angle_brackets(&name.txt, ¶ms); - p.err_multiple( + p.err_at( paren_start, paren_end, DiagnosticCategory::Message(format!( @@ -2196,7 +2852,12 @@ fn parse_type_declaration_with_context( let current_type_name_path = vec![name.txt.clone()]; // Parse optional manifest and/or kind (and ReScript's `type t = T = ...` equation form). - let (manifest, kind, private) = if p.token == Token::Equal { + // OCaml: if token is Bar, call expect Equal to generate "Did you forget a `=` here?" error + let (manifest, kind, private) = if p.token == Token::Equal || p.token == Token::Bar { + if p.token == Token::Bar { + // Generate error about missing `=` before variant constructors + p.expect(Token::Equal); + } // Heuristic: `{...}` after `=` can be a record type *or* a bs-object/object type. // Disambiguate by looking at the first significant token inside the braces. let looks_like_object_type_after_lbrace = |p: &mut Parser<'_>| -> bool { @@ -2278,40 +2939,16 @@ fn parse_type_declaration_with_context( }; // Better variant-vs-manifest disambiguation: a leading Uident without a following `.` - // is almost always a constructor in a variant type, even if there's only a single - // constructor (no `|`). + // is a constructor in a variant type. + // OCaml parser logic: if Uident is followed by `.`, it's a type path (Module.Type), + // otherwise it's a constructor declaration. let is_variant_type_starting_with_uident = |p: &mut Parser<'_>| -> bool { p.lookahead(|state| { state.next(); // consume Uident // `Foo.bar` is a type path, not a constructor. - if state.token == Token::Dot { - return false; - } - - // Any of these mean we're in constructor territory. - // Includes tokens that end the type declaration (like keywords starting new decls). - matches!( - state.token, - Token::Bar - | Token::Lparen - | Token::Lbrace - | Token::Colon // GADT syntax: `type t = Foo: t` - | Token::Equal // `type t = C = ...` - | Token::And - | Token::Constraint - | Token::Semicolon - | Token::Rbrace - | Token::Eof - // Keywords that start new top-level declarations - | Token::Let { .. } - | Token::Typ - | Token::Module - | Token::Open - | Token::Include - | Token::External - | Token::Exception - ) + // Anything else means it's a constructor. + state.token != Token::Dot }) }; @@ -2344,7 +2981,7 @@ fn parse_type_declaration_with_context( }); let typ = typ::parse_typ_expr(p); // Apply ghost location fix for spread-first closed objects - let typ = fix_spread_first_object_manifest(typ, is_spread_first).0; + let typ = fix_spread_first_object_manifest(p, typ, is_spread_first).0; manifest = Some(typ); } else { kind = parse_type_kind(p, Some(inline_ctx), Some(¤t_type_name_path)); @@ -2511,16 +3148,16 @@ fn parse_type_declaration_with_context( p.expect(Token::Equal); let typ = typ::parse_typ_expr(p); // OCaml: constraint tuple location also starts at "constraint" keyword - cstrs.push((var, typ, p.mk_loc(&cstr_start, &p.prev_end_pos))); + cstrs.push((var, typ, p.mk_loc_to_prev_end(&cstr_start))); } // In type declarations with qualified type constructors (Ldot), // OCaml uses the same location for both the CoreType and the longident // (just the constructor name, not including type arguments). // For unqualified (Lident), the CoreType uses full extent. - let manifest = manifest.map(fix_type_manifest_location); + let manifest = manifest.map(|t| fix_type_manifest_location(p.arena(), t)); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); Some(TypeDeclaration { ptype_name: name, ptype_params: params, @@ -2539,7 +3176,7 @@ fn parse_type_declaration_with_context( /// Also propagates ghost loc_start to alias wrappers. /// /// Returns the fixed type and whether the fix was applied. -fn fix_spread_first_object_manifest(typ: CoreType, is_spread_first: bool) -> (CoreType, bool) { +fn fix_spread_first_object_manifest(p: &mut Parser<'_>, typ: CoreType, is_spread_first: bool) -> (CoreType, bool) { if !is_spread_first { return (typ, false); } @@ -2560,15 +3197,11 @@ fn fix_spread_first_object_manifest(typ: CoreType, is_spread_first: bool) -> (Co } CoreTypeDesc::Ptyp_alias(inner, alias) => { // Recurse into inner type - let (fixed_inner, applied) = fix_spread_first_object_manifest(*inner, true); + let (fixed_inner, applied) = fix_spread_first_object_manifest(p, *inner, true); if applied { // OCaml uses inner type's loc_start for alias, so if inner is ghost, alias start is ghost too - let new_loc = Location { - loc_start: fixed_inner.ptyp_loc.loc_start.clone(), - loc_end: typ.ptyp_loc.loc_end, - loc_ghost: typ.ptyp_loc.loc_ghost, - id: typ.ptyp_loc.id, - }; + // Create a spanning location from fixed_inner start to typ end + let new_loc = p.mk_loc_spanning(fixed_inner.ptyp_loc, typ.ptyp_loc); (CoreType { ptyp_desc: CoreTypeDesc::Ptyp_alias(Box::new(fixed_inner), alias), ptyp_loc: new_loc, @@ -2583,7 +3216,7 @@ fn fix_spread_first_object_manifest(typ: CoreType, is_spread_first: bool) -> (Co } CoreTypeDesc::Ptyp_arrow { arg, ret, arity } => { // Recurse into arg ONLY if this is the direct manifest level - let (fixed_arg_typ, _) = fix_spread_first_object_manifest(arg.typ, true); + let (fixed_arg_typ, _) = fix_spread_first_object_manifest(p, arg.typ, true); let fixed_arg = TypeArg { typ: fixed_arg_typ, ..*arg @@ -2606,12 +3239,12 @@ fn fix_spread_first_object_manifest(typ: CoreType, is_spread_first: bool) -> (Co /// the CoreType and the longident. For unqualified (Lident), it uses full extent. /// EXCEPTION: When the type has attributes, OCaml keeps the full extent including /// type arguments (this allows the location to cover the entire attributed type). -fn fix_type_manifest_location(typ: CoreType) -> CoreType { +fn fix_type_manifest_location(arena: &crate::parse_arena::ParseArena, typ: CoreType) -> CoreType { match &typ.ptyp_desc { CoreTypeDesc::Ptyp_constr(lid, _) => { // Only adjust for qualified identifiers (Ldot) WITHOUT attributes // When there are attributes, OCaml keeps the full extent including type args - if matches!(lid.txt, Longident::Ldot(..)) && typ.ptyp_attributes.is_empty() { + if arena.is_ldot(lid.txt) && typ.ptyp_attributes.is_empty() { CoreType { ptyp_loc: lid.loc.clone(), ..typ @@ -2624,7 +3257,7 @@ fn fix_type_manifest_location(typ: CoreType) -> CoreType { // Also adjust Ldot types in arrow parameter positions // But NOT in return types - OCaml keeps type args in return type ptyp_loc let fixed_arg = TypeArg { - typ: fix_type_manifest_location(arg.typ.clone()), + typ: fix_type_manifest_location(arena, arg.typ.clone()), ..*arg.clone() }; // Return type is NOT fixed - OCaml includes type args for return types @@ -2637,6 +3270,14 @@ fn fix_type_manifest_location(typ: CoreType) -> CoreType { ..typ } } + CoreTypeDesc::Ptyp_alias(inner, alias_name) => { + // Recurse into the aliased type (e.g., `Color.t<...> as 'rgb`) + let fixed_inner = fix_type_manifest_location(arena, inner.as_ref().clone()); + CoreType { + ptyp_desc: CoreTypeDesc::Ptyp_alias(Box::new(fixed_inner), alias_name.clone()), + ..typ + } + } _ => typ, } } @@ -2654,7 +3295,7 @@ fn parse_type_params(p: &mut Parser<'_>) -> Vec<(CoreType, Variance)> { match &p.token { Token::Lident(name) | Token::Uident(name) => { let name = name.clone(); - let loc = p.mk_loc(&p.start_pos, &p.end_pos); + let loc = p.mk_loc_current(); p.next(); let typ = CoreType { ptyp_desc: CoreTypeDesc::Ptyp_var(name), @@ -2676,7 +3317,7 @@ fn parse_type_params(p: &mut Parser<'_>) -> Vec<(CoreType, Variance)> { match &p.token { Token::Lident(name) | Token::Uident(name) => { let name = name.clone(); - let loc = p.mk_loc(&p.start_pos, &p.end_pos); + let loc = p.mk_loc_current(); p.next(); let typ = CoreType { ptyp_desc: CoreTypeDesc::Ptyp_var(name), @@ -2726,7 +3367,7 @@ fn parse_type_params_angle(p: &mut Parser<'_>) -> Vec<(CoreType, Variance)> { match &p.token { Token::Lident(name) | Token::Uident(name) => { let name = name.clone(); - let loc = p.mk_loc(&p.start_pos, &p.end_pos); + let loc = p.mk_loc_current(); p.next(); let typ = CoreType { ptyp_desc: CoreTypeDesc::Ptyp_var(name), @@ -2772,7 +3413,7 @@ fn parse_type_params_angle(p: &mut Parser<'_>) -> Vec<(CoreType, Variance)> { // Add placeholder for recovery - use empty string for type var let typ = CoreType { ptyp_desc: CoreTypeDesc::Ptyp_var(String::new()), - ptyp_loc: p.mk_loc(¶m_start, &p.prev_end_pos), + ptyp_loc: p.mk_loc_to_prev_end(¶m_start), ptyp_attributes: vec![], }; params.push((typ, variance)); @@ -2797,7 +3438,7 @@ fn parse_type_params_angle(p: &mut Parser<'_>) -> Vec<(CoreType, Variance)> { // Add placeholder for recovery - use empty string for type var let typ = CoreType { ptyp_desc: CoreTypeDesc::Ptyp_var(String::new()), - ptyp_loc: p.mk_loc(¶m_start, &p.prev_end_pos), + ptyp_loc: p.mk_loc_to_prev_end(¶m_start), ptyp_attributes: vec![], }; params.push((typ, variance)); @@ -2805,7 +3446,7 @@ fn parse_type_params_angle(p: &mut Parser<'_>) -> Vec<(CoreType, Variance)> { } } else if p.token == Token::Underscore { // Anonymous/wildcard type parameter: _ - let loc = p.mk_loc(&p.start_pos, &p.end_pos); + let loc = p.mk_loc_current(); p.next(); let typ = CoreType { ptyp_desc: CoreTypeDesc::Ptyp_any, @@ -2824,7 +3465,7 @@ fn parse_type_params_angle(p: &mut Parser<'_>) -> Vec<(CoreType, Variance)> { name )), ); - let loc = p.mk_loc(&p.start_pos, &p.end_pos); + let loc = p.mk_loc_current(); p.next(); // Add for recovery let typ = CoreType { @@ -2861,7 +3502,7 @@ fn parse_type_params_old_style(p: &mut Parser<'_>, _type_name: &str) -> Vec<(Cor match &p.token { Token::Lident(name) | Token::Uident(name) => { let name = name.clone(); - let loc = p.mk_loc(&p.start_pos, &p.end_pos); + let loc = p.mk_loc_current(); p.next(); let typ = CoreType { ptyp_desc: CoreTypeDesc::Ptyp_var(name), @@ -2873,7 +3514,7 @@ fn parse_type_params_old_style(p: &mut Parser<'_>, _type_name: &str) -> Vec<(Cor t if t.is_keyword() => { // Reserved keyword as type param (e.g., 'for) let name = format!("{}", t); - let loc = p.mk_loc(&p.start_pos, &p.end_pos); + let loc = p.mk_loc_current(); p.next(); let typ = CoreType { ptyp_desc: CoreTypeDesc::Ptyp_var(name), @@ -2934,7 +3575,7 @@ fn parse_type_kind( // Record type - capture { position for first field's location (OCaml extends first spread field's loc to {) let lbrace_pos = p.start_pos.clone(); p.next(); - let labels = parse_label_declarations(p, inline_ctx, current_type_name_path, Some(lbrace_pos)); + let labels = parse_label_declarations(p, inline_ctx, current_type_name_path, Some(lbrace_pos), false); p.expect(Token::Rbrace); TypeKind::Ptype_record(labels) } @@ -3002,10 +3643,10 @@ fn parse_constructor_impl(p: &mut Parser<'_>, start_pos: Position) -> Option, start_pos: Position) -> Option { let n = n.clone(); - let loc = p.mk_loc(&p.start_pos, &p.end_pos); + let loc = p.mk_loc_current(); p.next(); with_loc(n, loc) } @@ -3062,20 +3703,39 @@ fn parse_constructor_impl(p: &mut Parser<'_>, start_pos: Position) -> Option return false, // String field = object type + Token::Rbrace if depth == 0 => return true, // End without string = record + Token::Eof => return true, + Token::Lparen | Token::Lbrace | Token::Lbracket => depth += 1, + Token::Rparen | Token::Rbracket => { + if depth > 0 { depth -= 1; } + } + Token::Rbrace => { + if depth > 0 { depth -= 1; } else { return true; } + } + _ => {} + } + state.next(); + } + } + true // Not object type → inline record }); if is_inline_record { let lbrace_pos = p.start_pos.clone(); p.next(); // consume { - let labels = parse_label_declarations(p, None, None, Some(lbrace_pos)); + let labels = parse_label_declarations(p, None, None, Some(lbrace_pos), true); p.expect(Token::Rbrace); // Allow trailing comma after inline record: Foo({...},) p.optional(&Token::Comma); @@ -3112,10 +3772,32 @@ fn parse_constructor_impl(p: &mut Parser<'_>, start_pos: Position) -> Option return true, + Token::Rbrace if depth == 0 => return false, + Token::Eof => return false, + Token::Lparen | Token::Lbrace | Token::Lbracket => depth += 1, + Token::Rparen | Token::Rbracket => { + if depth > 0 { depth -= 1; } + } + Token::Rbrace => { + if depth > 0 { depth -= 1; } else { return false; } + } + _ => {} + } + state.next(); + } + } + false }); if is_object { // Consume `{` and capture start_pos AFTER (like OCaml) @@ -3140,7 +3822,7 @@ fn parse_constructor_impl(p: &mut Parser<'_>, start_pos: Position) -> Option, start_pos: Position) -> Option, start_pos: Position) -> Option, inline_ctx: Option<&RefCell>, current_type_name_path: Option<&Vec>, lbrace_pos: Option, + for_constructor_record: bool, ) -> Vec { + p.leave_breadcrumb(grammar::Grammar::FieldDeclarations); let mut labels = vec![]; let mut is_first = true; @@ -3184,7 +3870,7 @@ fn parse_label_declarations( let start_pos = p.start_pos.clone(); p.next(); // Name location is just the "..." part - let name_loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let name_loc = p.mk_loc_to_prev_end(&start_pos); let spread_type = typ::parse_typ_expr(p); // OCaml extends the first spread field's location back to the { position let loc_start = if is_first { @@ -3198,7 +3884,7 @@ fn parse_label_declarations( let loc_end = if is_first { p.end_pos.clone() } else { - spread_type.ptyp_loc.loc_end.clone() + p.loc_end(spread_type.ptyp_loc) }; let loc = p.mk_loc(loc_start, &loc_end); labels.push(LabelDeclaration { @@ -3216,26 +3902,53 @@ fn parse_label_declarations( continue; } - if let Some(l) = parse_label_declaration(p, inline_ctx, current_type_name_path) { + if let Some(l) = parse_label_declaration(p, inline_ctx, current_type_name_path, for_constructor_record) { labels.push(l); } is_first = false; if !p.optional(&Token::Comma) { - break; + if grammar::is_list_element(&grammar::Grammar::FieldDeclarations, &p.token) { + // Missing comma but next token looks like another field declaration. + // Emit "Did you forget a `,` here?" and continue parsing. + p.expect(Token::Comma); + } else if p.token != Token::Eof && p.token != Token::Rbrace + && !super::core::recover::should_abort_list_parse(p) + { + p.expect(Token::Comma); + if p.token == Token::Semicolon { p.next(); } + } else { + break; + } } } + p.eat_breadcrumb(); labels } /// Parse a single label declaration. +/// +/// `for_constructor_record`: When true, capture location start AFTER attributes +/// (for Pcstr_record in constructors). When false, capture BEFORE (for Ptype_record). +/// This matches OCaml's behavior where constructor inline records parse outer attrs +/// before calling the field parser. fn parse_label_declaration( p: &mut Parser<'_>, inline_ctx: Option<&RefCell>, current_type_name_path: Option<&Vec>, + for_constructor_record: bool, ) -> Option { - let start_pos = p.start_pos.clone(); + // For regular records, capture start_pos BEFORE attrs (include attrs in location). + // For constructor records, capture AFTER attrs (exclude attrs from location). + // This matches OCaml's behavior where constructor records parse outer attrs + // at a higher level before calling the field parser. + let start_pos_before_attrs = p.start_pos.clone(); let attrs = parse_attributes(p); + let start_pos = if for_constructor_record { + p.start_pos.clone() + } else { + start_pos_before_attrs + }; let mutable = if p.token == Token::Mutable { p.next(); @@ -3247,14 +3960,40 @@ fn parse_label_declaration( let name = match &p.token { Token::Lident(n) => { let n = n.clone(); - let loc = p.mk_loc(&p.start_pos, &p.end_pos); + let loc = p.mk_loc_current(); p.next(); with_loc(n, loc) } + _ if p.token.is_keyword() => { + // OCaml: Token.is_keyword p.token + // Check if the keyword is followed by a colon - if so, recover by renaming + if let Some((recovered_name, loc)) = super::core::recover_keyword_field_name_if_probably_field( + p, + error_messages::keyword_field_in_type, + ) { + with_loc(recovered_name, loc) + } else { + // Just emit the error without recovery + super::core::emit_keyword_field_error(p, error_messages::keyword_field_in_type); + return None; + } + } _ => { - p.err(DiagnosticCategory::Message( - "Expected field name".to_string(), - )); + // Match OCaml's error handling: give specific messages for dangling attrs/mutable + // OCaml uses p.end_pos as the end position (not p.start_pos) + if !attrs.is_empty() { + p.err_at(start_pos.clone(), p.end_pos.clone(), DiagnosticCategory::Message( + "Attributes and doc comments can only be used at the beginning of a field declaration".to_string(), + )); + } else if mutable == MutableFlag::Mutable { + p.err_at(start_pos.clone(), p.end_pos.clone(), DiagnosticCategory::Message( + "The `mutable` qualifier can only be used at the beginning of a field declaration".to_string(), + )); + } else { + p.err(DiagnosticCategory::Message( + "Expected field name".to_string(), + )); + } return None; } }; @@ -3269,21 +4008,35 @@ fn parse_label_declaration( // Check for optional field marker let is_optional = p.optional(&Token::Question); - // Check for field punning: {form} is shorthand for {form: form} - // If no colon, the type name is the same as the field name - let is_punning = p.token != Token::Colon; - - if !is_punning { - p.expect(Token::Colon); - } + // Check for colon, equal (error recovery), or field punning + // OCaml: if Equal instead of Colon, emit specific error and continue + let is_punning = match &p.token { + Token::Colon => { + p.next(); + false + } + Token::Equal => { + // Common mistake: using = instead of : in record type declarations + p.err(DiagnosticCategory::Message( + "Record fields in type declarations use `:`. Example: `{field: string}`".to_string(), + )); + p.next(); + false + } + _ => { + // Field punning: {form} is shorthand for {form: form} + true + } + }; // Check if the field type is an inline record let typ = if is_punning { // Field punning: {form} becomes {form: form} // The type is a simple type constructor with the field name + let lid_idx = p.push_lident(&name.txt); CoreType { ptyp_desc: CoreTypeDesc::Ptyp_constr( - with_loc(Longident::Lident(name.txt.clone()), name.loc.clone()), + with_loc(lid_idx, name.loc.clone()), vec![], ), ptyp_loc: name.loc.clone(), @@ -3335,9 +4088,9 @@ fn parse_label_declaration( p.next(); // consume { let inline_ctx = inline_ctx.unwrap(); let extended_path = extended_path.as_ref().unwrap(); - let labels = parse_label_declarations(p, Some(inline_ctx), Some(extended_path), Some(type_start_pos.clone())); + let labels = parse_label_declarations(p, Some(inline_ctx), Some(extended_path), Some(type_start_pos.clone()), false); p.expect(Token::Rbrace); - let type_loc = p.mk_loc(&type_start_pos, &p.prev_end_pos); + let type_loc = p.mk_loc_to_prev_end(&type_start_pos); // Create the inline type name (e.g., "options.permissions.all") let inline_type_name = extended_path.join("."); @@ -3352,9 +4105,10 @@ fn parse_label_declaration( // Return a Ptyp_constr pointing to the inline type let params = inline_ctx.borrow().params.clone(); let type_args: Vec = params.into_iter().map(|(t, _)| t).collect(); + let lid_idx = p.push_lident(&inline_type_name); CoreType { ptyp_desc: CoreTypeDesc::Ptyp_constr( - with_loc(Longident::Lident(inline_type_name), type_loc.clone()), + with_loc(lid_idx, type_loc.clone()), type_args, ), ptyp_loc: type_loc, @@ -3362,14 +4116,16 @@ fn parse_label_declaration( } } else { // Not a record - parse as regular type (object type) - typ::parse_poly_type_expr(p) + // But still thread inline context through parser fields for nested extraction + parse_poly_type_with_inline_context(p, inline_ctx, extended_path.as_ref()) } } else { - typ::parse_poly_type_expr(p) + // Thread inline context through parser fields if available + parse_poly_type_with_inline_context(p, inline_ctx, extended_path.as_ref()) }; // OCaml uses typ.ptyp_loc.loc_end for label declaration's end, not p.prev_end_pos - let loc = p.mk_loc(&start_pos, &typ.ptyp_loc.loc_end); + let loc = p.mk_loc_to_end_of(&start_pos, typ.ptyp_loc); Some(LabelDeclaration { pld_name: name, pld_mutable: mutable, @@ -3380,6 +4136,42 @@ fn parse_label_declaration( }) } +/// Parse a poly type expression, threading inline context through parser fields +/// so that nested `{...}` in type constructor args can be extracted as inline records. +fn parse_poly_type_with_inline_context( + p: &mut Parser<'_>, + inline_ctx: Option<&RefCell>, + extended_path: Option<&Vec>, +) -> CoreType { + if let (Some(ctx), Some(path)) = (inline_ctx, extended_path) { + // Save old parser fields + let old_path = p.current_type_name_path.take(); + let old_found = p.inline_types_found.take(); + let old_params = std::mem::take(&mut p.inline_types_params); + + // Set parser fields for inline record extraction + p.current_type_name_path = Some(path.clone()); + p.inline_types_found = Some(ctx.borrow().found_inline_types.clone()); + p.inline_types_params = ctx.borrow().params.clone(); + + let typ = typ::parse_poly_type_expr(p); + + // Copy found inline types back to the RefCell context + if let Some(found) = p.inline_types_found.take() { + ctx.borrow_mut().found_inline_types = found; + } + + // Restore old parser fields + p.current_type_name_path = old_path; + p.inline_types_found = old_found; + p.inline_types_params = old_params; + + typ + } else { + typ::parse_poly_type_expr(p) + } +} + /// Parse a value description (for external). /// `loc_start` should be the position before any outer attributes (to match OCaml's location). fn parse_value_description( @@ -3394,14 +4186,14 @@ fn parse_value_description( let name = match &p.token { Token::Lident(n) => { let n = n.clone(); - let loc = p.mk_loc(&p.start_pos, &p.end_pos); + let loc = p.mk_loc_current(); p.next(); with_loc(n, loc) } Token::String(s) => { // Escaped identifier like "export" - store with quotes for printer to recognize let n = format!("\"{}\"", s); - let loc = p.mk_loc(&p.start_pos, &p.end_pos); + let loc = p.mk_loc_current(); p.next(); with_loc(n, loc) } @@ -3422,18 +4214,31 @@ fn parse_value_description( // Parse optional primitive let prim = if p.token == Token::Equal { + let equal_start = p.start_pos.clone(); + let equal_end = p.end_pos.clone(); p.next(); - let mut prims = vec![]; - while let Token::String(s) = &p.token { - prims.push(s.clone()); - p.next(); + match &p.token { + Token::String(s) => { + let s = s.clone(); + p.next(); + // OCaml only parses a single string here + vec![s] + } + _ => { + // OCaml: emit error when = is not followed by a string + let msg = format!( + "An external requires the name of the JS value you're referring to, like \"{}\".", + name.txt + ); + p.err_at(equal_start, equal_end, DiagnosticCategory::Message(msg)); + vec![] + } } - prims } else { vec![] }; - let loc = p.mk_loc(&loc_start, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&loc_start); ValueDescription { pval_name: name, pval_type: typ, @@ -3456,7 +4261,7 @@ pub fn parse_extension_constructor( pcd_name: mknoloc("Error".to_string()), pcd_args: ConstructorArguments::Pcstr_tuple(vec![]), pcd_res: None, - pcd_loc: p.mk_loc(&start_pos, &p.prev_end_pos), + pcd_loc: p.mk_loc_to_prev_end(&start_pos), pcd_attributes: vec![], }); @@ -3476,7 +4281,7 @@ pub fn parse_extension_constructor( ExtensionConstructor { pext_name: constructor.pcd_name, pext_kind: kind, - pext_loc: p.mk_loc(&start_pos, &p.prev_end_pos), + pext_loc: p.mk_loc_to_prev_end(&start_pos), pext_attributes: all_attrs, } } @@ -3514,7 +4319,7 @@ fn parse_module_definition(p: &mut Parser<'_>, module_start: Position, attrs: At let name = match &p.token { Token::Uident(n) => { let n = n.clone(); - let loc = p.mk_loc(&p.start_pos, &p.end_pos); + let loc = p.mk_loc_current(); p.next(); with_loc(n, loc) } @@ -3539,7 +4344,7 @@ fn parse_module_definition(p: &mut Parser<'_>, module_start: Position, attrs: At if let Some(mod_type) = mod_type { // Location spans from module type start to module expr end - let loc = p.mk_loc(&mod_type.pmty_loc.loc_start, &mod_expr.pmod_loc.loc_end); + let loc = p.mk_loc_spanning(mod_type.pmty_loc, mod_expr.pmod_loc); mod_expr = ModuleExpr { pmod_desc: ModuleExprDesc::Pmod_constraint( Box::new(mod_expr), @@ -3554,7 +4359,7 @@ fn parse_module_definition(p: &mut Parser<'_>, module_start: Position, attrs: At pmb_name: name, pmb_expr: mod_expr, pmb_attributes: attrs, - pmb_loc: p.mk_loc(&binding_start, &p.prev_end_pos), + pmb_loc: p.mk_loc_to_prev_end(&binding_start), }) }; @@ -3631,7 +4436,7 @@ fn parse_module_declaration(p: &mut Parser<'_>, outer_attrs: Attributes, start_p let name = match &p.token { Token::Uident(n) => { let n = n.clone(); - let loc = p.mk_loc(&p.start_pos, &p.end_pos); + let loc = p.mk_loc_current(); p.next(); with_loc(n, loc) } @@ -3666,7 +4471,7 @@ fn parse_module_declaration(p: &mut Parser<'_>, outer_attrs: Attributes, start_p parse_module_type(p) }; - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); ModuleDeclaration { pmd_name: name, pmd_type: mod_type, @@ -3741,7 +4546,7 @@ fn parse_module_type_declaration(p: &mut Parser<'_>, outer_attrs: Attributes, in let name = match &p.token { Token::Uident(n) | Token::Lident(n) => { let n = n.clone(); - let loc = p.mk_loc(&p.start_pos, &p.end_pos); + let loc = p.mk_loc_current(); p.next(); with_loc(n, loc) } @@ -3763,7 +4568,7 @@ fn parse_module_type_declaration(p: &mut Parser<'_>, outer_attrs: Attributes, in // In structure context (parse_module_type_impl), OCaml passes ~loc:(mk_loc name_start p.prev_end_pos) // In signature context (parse_module_type_declaration), OCaml doesn't pass ~loc, uses Location.none let loc = if in_structure { - p.mk_loc(&name_start, &p.prev_end_pos) + p.mk_loc_to_prev_end(&name_start) } else { Location::none() }; @@ -3788,9 +4593,10 @@ fn parse_attributes(p: &mut Parser<'_>) -> Attributes { attrs.push(parse_attribute_body(p, attr_start)); } Token::DocComment { loc, content } => { - let loc = loc.clone(); + let loc_cloned = loc.clone(); let content = content.clone(); p.next(); + let loc = p.from_location(&loc_cloned); attrs.push(super::core::doc_comment_to_attribute(loc, content)); } _ => break, @@ -3827,7 +4633,7 @@ fn parse_attribute_body(p: &mut Parser<'_>, start_pos: Position) -> Attribute { } let name = parts.join("."); - let name_loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let name_loc = p.mk_loc_to_prev_end(&start_pos); // Parse optional payload let is_adjacent = p.start_pos.cnum == p.prev_end_pos.cnum; @@ -3934,7 +4740,7 @@ pub fn parse_payload(p: &mut Parser<'_>) -> Payload { // OCaml: parse_newline_or_semicolon_structure consumes the semicolon // BEFORE computing the location, so structure item location includes the semicolon p.optional(&Token::Semicolon); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); items.push(StructureItem { pstr_desc: StructureItemDesc::Pstr_eval(expr, vec![]), @@ -3994,7 +4800,7 @@ fn parse_extension(p: &mut Parser<'_>) -> Extension { mknoloc("error".to_string()) } else { let id = parts.join("."); - with_loc(id, p.mk_loc(&id_start, &p.prev_end_pos)) + with_loc(id, p.mk_loc_to_prev_end(&id_start)) }; // Parse optional payload only if it's immediately adjacent. diff --git a/compiler-rust/src/parser/parens.rs b/compiler-rust/src/parser/parens.rs index c3051fa7ca4..4678f420c08 100644 --- a/compiler-rust/src/parser/parens.rs +++ b/compiler-rust/src/parser/parens.rs @@ -3,7 +3,7 @@ //! This module provides functions to determine when parentheses or braces //! are needed in printed output. It's a port of OCaml's `res_parens.ml`. -use crate::location::Location; +use crate::parse_arena::LocIdx; use crate::parser::ast::*; use crate::parser::longident::Longident; use crate::parser::parsetree_viewer; @@ -14,13 +14,13 @@ pub enum ParenKind { /// Parentheses are needed Parenthesized, /// Braces are needed at the given location - Braced(Location), + Braced(LocIdx), /// No wrapping needed Nothing, } /// Check if an expression needs parentheses/braces. -pub fn expr(expr: &Expression) -> ParenKind { +pub fn expr(arena: &crate::parse_arena::ParseArena, expr: &Expression) -> ParenKind { let opt_braces = parsetree_viewer::process_braces_attr(expr); match opt_braces { Some(attr) => ParenKind::Braced(attr.0.loc.clone()), @@ -39,14 +39,14 @@ pub fn expr(expr: &Expression) -> ParenKind { } /// Check if expression record row RHS needs parentheses. -pub fn expr_record_row_rhs(optional: bool, e: &Expression) -> ParenKind { - let kind = expr(e); +pub fn expr_record_row_rhs(arena: &crate::parse_arena::ParseArena, optional: bool, e: &Expression) -> ParenKind { + let kind = expr(arena, e); match kind { ParenKind::Nothing if optional => match &e.pexp_desc { ExpressionDesc::Pexp_ifthenelse(_, _, _) | ExpressionDesc::Pexp_fun { .. } => { ParenKind::Parenthesized } - _ if parsetree_viewer::is_binary_expression(e) => ParenKind::Parenthesized, + _ if parsetree_viewer::is_binary_expression(arena, e) => ParenKind::Parenthesized, _ => kind, }, _ => kind, @@ -54,7 +54,7 @@ pub fn expr_record_row_rhs(optional: bool, e: &Expression) -> ParenKind { } /// Check if a call expression needs parentheses/braces. -pub fn call_expr(expr: &Expression) -> ParenKind { +pub fn call_expr(arena: &crate::parse_arena::ParseArena, expr: &Expression) -> ParenKind { let opt_braces = parsetree_viewer::process_braces_attr(expr); match opt_braces { Some(attr) => ParenKind::Braced(attr.0.loc.clone()), @@ -65,8 +65,8 @@ pub fn call_expr(expr: &Expression) -> ParenKind { return ParenKind::Parenthesized; } - if parsetree_viewer::is_unary_expression(expr) - || parsetree_viewer::is_binary_expression(expr) + if parsetree_viewer::is_unary_expression(arena, expr) + || parsetree_viewer::is_binary_expression(arena, expr) { return ParenKind::Parenthesized; } @@ -103,7 +103,7 @@ pub fn call_expr(expr: &Expression) -> ParenKind { } /// Check if a structure expression needs parentheses/braces. -pub fn structure_expr(expr: &Expression) -> ParenKind { +pub fn structure_expr(arena: &crate::parse_arena::ParseArena, expr: &Expression) -> ParenKind { let opt_braces = parsetree_viewer::process_braces_attr(expr); match opt_braces { Some(attr) => ParenKind::Braced(attr.0.loc.clone()), @@ -126,7 +126,7 @@ pub fn structure_expr(expr: &Expression) -> ParenKind { } /// Check if a unary expression operand needs parentheses/braces. -pub fn unary_expr_operand(expr: &Expression) -> ParenKind { +pub fn unary_expr_operand(arena: &crate::parse_arena::ParseArena, expr: &Expression) -> ParenKind { let opt_braces = parsetree_viewer::process_braces_attr(expr); match opt_braces { Some(attr) => ParenKind::Braced(attr.0.loc.clone()), @@ -136,8 +136,8 @@ pub fn unary_expr_operand(expr: &Expression) -> ParenKind { return ParenKind::Parenthesized; } - if parsetree_viewer::is_unary_expression(expr) - || parsetree_viewer::is_binary_expression(expr) + if parsetree_viewer::is_unary_expression(arena, expr) + || parsetree_viewer::is_binary_expression(arena, expr) { return ParenKind::Parenthesized; } @@ -174,7 +174,7 @@ pub fn unary_expr_operand(expr: &Expression) -> ParenKind { } /// Check if a binary expression operand needs parentheses/braces. -pub fn binary_expr_operand(is_lhs: bool, expr: &Expression) -> ParenKind { +pub fn binary_expr_operand(arena: &crate::parse_arena::ParseArena, is_lhs: bool, expr: &Expression) -> ParenKind { let opt_braces = parsetree_viewer::process_braces_attr(expr); match opt_braces { Some(attr) => ParenKind::Braced(attr.0.loc.clone()), @@ -196,7 +196,7 @@ pub fn binary_expr_operand(is_lhs: bool, expr: &Expression) -> ParenKind { | ExpressionDesc::Pexp_fun { .. } | ExpressionDesc::Pexp_newtype(_, _) => ParenKind::Parenthesized, _ if parsetree_viewer::expr_is_uncurried_fun(expr) => ParenKind::Parenthesized, - _ if parsetree_viewer::is_binary_expression(expr) => ParenKind::Parenthesized, + _ if parsetree_viewer::is_binary_expression(arena, expr) => ParenKind::Parenthesized, _ if parsetree_viewer::is_ternary_expr(expr) => ParenKind::Parenthesized, ExpressionDesc::Pexp_assert(_) if is_lhs => ParenKind::Parenthesized, _ if parsetree_viewer::expr_is_await(expr) => ParenKind::Parenthesized, @@ -225,7 +225,7 @@ pub fn sub_binary_expr_operand(parent_operator: &str, child_operator: &str) -> b } /// Check if RHS binary expression operand needs parentheses. -pub fn rhs_binary_expr_operand(parent_operator: &str, rhs: &Expression) -> bool { +pub fn rhs_binary_expr_operand(arena: &crate::parse_arena::ParseArena, parent_operator: &str, rhs: &Expression) -> bool { match &rhs.pexp_desc { ExpressionDesc::Pexp_apply { funct, @@ -237,8 +237,9 @@ pub fn rhs_binary_expr_operand(parent_operator: &str, rhs: &Expression) -> bool } match &funct.pexp_desc { ExpressionDesc::Pexp_ident(ident) if funct.pexp_attributes.is_empty() => { - if let Longident::Lident(operator) = &ident.txt { - if parsetree_viewer::not_ghost_operator(operator, &ident.loc) { + if let Longident::Lident(op_idx) = arena.get_longident(ident.txt) { + let operator = arena.get_string(*op_idx); + if parsetree_viewer::not_ghost_operator(operator, ident.loc.is_none()) { let prec_parent = parsetree_viewer::operator_precedence(parent_operator); let prec_child = parsetree_viewer::operator_precedence(operator); @@ -255,7 +256,7 @@ pub fn rhs_binary_expr_operand(parent_operator: &str, rhs: &Expression) -> bool } /// Check if flatten operand RHS needs parentheses. -pub fn flatten_operand_rhs(parent_operator: &str, rhs: &Expression) -> bool { +pub fn flatten_operand_rhs(arena: &crate::parse_arena::ParseArena, parent_operator: &str, rhs: &Expression) -> bool { match &rhs.pexp_desc { ExpressionDesc::Pexp_apply { funct, args, .. } => { if args.len() != 2 { @@ -263,8 +264,9 @@ pub fn flatten_operand_rhs(parent_operator: &str, rhs: &Expression) -> bool { } match &funct.pexp_desc { ExpressionDesc::Pexp_ident(ident) => { - if let Longident::Lident(operator) = &ident.txt { - if parsetree_viewer::not_ghost_operator(operator, &ident.loc) { + if let Longident::Lident(op_idx) = arena.get_longident(ident.txt) { + let operator = arena.get_string(*op_idx); + if parsetree_viewer::not_ghost_operator(operator, ident.loc.is_none()) { let prec_parent = parsetree_viewer::operator_precedence(parent_operator); let prec_child = parsetree_viewer::operator_precedence(operator); @@ -298,63 +300,120 @@ pub fn flatten_operand_rhs(parent_operator: &str, rhs: &Expression) -> bool { } } +/// Check if flatten operand RHS needs parentheses, ignoring the attribute check. +/// This is used when we've already partitioned printable attrs and will handle them separately. +pub fn flatten_operand_rhs_without_attrs(arena: &crate::parse_arena::ParseArena, parent_operator: &str, rhs: &Expression) -> bool { + match &rhs.pexp_desc { + ExpressionDesc::Pexp_apply { funct, args, .. } => { + if args.len() != 2 { + return false; + } + match &funct.pexp_desc { + ExpressionDesc::Pexp_ident(ident) => { + if let Longident::Lident(op_idx) = arena.get_longident(ident.txt) { + let operator = arena.get_string(*op_idx); + if parsetree_viewer::not_ghost_operator(operator, ident.loc.is_none()) { + let prec_parent = + parsetree_viewer::operator_precedence(parent_operator); + let prec_child = parsetree_viewer::operator_precedence(operator); + // NOTE: Unlike flatten_operand_rhs, we don't check rhs.pexp_attributes here + return prec_parent >= prec_child; + } + } + false + } + _ => false, + } + } + ExpressionDesc::Pexp_constraint(inner, typ) + if matches!(&inner.pexp_desc, ExpressionDesc::Pexp_pack(_)) + && matches!(&typ.ptyp_desc, CoreTypeDesc::Ptyp_package(_)) => + { + false + } + ExpressionDesc::Pexp_fun { lhs, .. } => { + if let PatternDesc::Ppat_var(name) = &lhs.ppat_desc { + if name.txt == "__x" { + return false; + } + } + true + } + ExpressionDesc::Pexp_newtype(_, _) + | ExpressionDesc::Pexp_setfield(_, _, _) + | ExpressionDesc::Pexp_constraint(_, _) => true, + _ if parsetree_viewer::is_ternary_expr(rhs) => true, + _ => false, + } +} + /// Check if binary operator inside await needs parentheses. pub fn binary_operator_inside_await_needs_parens(operator: &str) -> bool { parsetree_viewer::operator_precedence(operator) < parsetree_viewer::operator_precedence("->") } /// Check if assert or await expression RHS needs parentheses/braces. -pub fn assert_or_await_expr_rhs(in_await: bool, expr: &Expression) -> ParenKind { +pub fn assert_or_await_expr_rhs(arena: &crate::parse_arena::ParseArena, in_await: bool, expr: &Expression) -> ParenKind { let opt_braces = parsetree_viewer::process_braces_attr(expr); match opt_braces { Some(attr) => ParenKind::Braced(attr.0.loc.clone()), - None => { - let filtered = parsetree_viewer::filter_parsing_attrs(&expr.pexp_attributes); - if !filtered.is_empty() { - return ParenKind::Parenthesized; - } + None => assert_or_await_expr_rhs_inner(arena, in_await, expr), + } +} - match &expr.pexp_desc { - ExpressionDesc::Pexp_apply { funct, .. } - if parsetree_viewer::is_binary_expression(expr) => - { - if let ExpressionDesc::Pexp_ident(ident) = &funct.pexp_desc { - if let Longident::Lident(operator) = &ident.txt { - if in_await && !binary_operator_inside_await_needs_parens(operator) { - return ParenKind::Nothing; - } - } +/// Check if await expression RHS needs parens, but IGNORE the res.braces attribute. +/// OCaml's await printing filters out @res.braces before checking, so `await {x}` prints as `await x`. +pub fn assert_or_await_expr_rhs_ignore_braces(arena: &crate::parse_arena::ParseArena, in_await: bool, expr: &Expression) -> ParenKind { + // Ignore the braces attribute - just check the expression structure + assert_or_await_expr_rhs_inner(arena, in_await, expr) +} + +fn assert_or_await_expr_rhs_inner(arena: &crate::parse_arena::ParseArena, in_await: bool, expr: &Expression) -> ParenKind { + let filtered = parsetree_viewer::filter_parsing_attrs(&expr.pexp_attributes); + if !filtered.is_empty() { + return ParenKind::Parenthesized; + } + + match &expr.pexp_desc { + ExpressionDesc::Pexp_apply { funct, .. } + if parsetree_viewer::is_binary_expression(arena, expr) => + { + if let ExpressionDesc::Pexp_ident(ident) = &funct.pexp_desc { + if let Longident::Lident(op_idx) = arena.get_longident(ident.txt) { + let operator = arena.get_string(*op_idx); + if in_await && !binary_operator_inside_await_needs_parens(operator) { + return ParenKind::Nothing; } - ParenKind::Parenthesized - } - // module(M: S) doesn't need parens - ExpressionDesc::Pexp_constraint(inner, typ) - if matches!(&inner.pexp_desc, ExpressionDesc::Pexp_pack(_)) - && matches!(&typ.ptyp_desc, CoreTypeDesc::Ptyp_package(_)) => - { - ParenKind::Nothing - } - ExpressionDesc::Pexp_fun { .. } - if parsetree_viewer::is_underscore_apply_sugar(expr) => - { - ParenKind::Nothing - } - ExpressionDesc::Pexp_assert(_) - | ExpressionDesc::Pexp_fun { .. } - | ExpressionDesc::Pexp_newtype(_, _) - | ExpressionDesc::Pexp_constraint(_, _) - | ExpressionDesc::Pexp_setfield(_, _, _) - | ExpressionDesc::Pexp_match(_, _) - | ExpressionDesc::Pexp_try(_, _) - | ExpressionDesc::Pexp_while(_, _) - | ExpressionDesc::Pexp_for(_, _, _, _, _) - | ExpressionDesc::Pexp_ifthenelse(_, _, _) => ParenKind::Parenthesized, - _ if !in_await && parsetree_viewer::expr_is_await(expr) => { - ParenKind::Parenthesized } - _ => ParenKind::Nothing, } + ParenKind::Parenthesized + } + // module(M: S) doesn't need parens + ExpressionDesc::Pexp_constraint(inner, typ) + if matches!(&inner.pexp_desc, ExpressionDesc::Pexp_pack(_)) + && matches!(&typ.ptyp_desc, CoreTypeDesc::Ptyp_package(_)) => + { + ParenKind::Nothing + } + ExpressionDesc::Pexp_fun { .. } + if parsetree_viewer::is_underscore_apply_sugar(expr) => + { + ParenKind::Nothing } + ExpressionDesc::Pexp_assert(_) + | ExpressionDesc::Pexp_fun { .. } + | ExpressionDesc::Pexp_newtype(_, _) + | ExpressionDesc::Pexp_constraint(_, _) + | ExpressionDesc::Pexp_setfield(_, _, _) + | ExpressionDesc::Pexp_match(_, _) + | ExpressionDesc::Pexp_try(_, _) + | ExpressionDesc::Pexp_while(_, _) + | ExpressionDesc::Pexp_for(_, _, _, _, _) + | ExpressionDesc::Pexp_ifthenelse(_, _, _) => ParenKind::Parenthesized, + _ if !in_await && parsetree_viewer::expr_is_await(expr) => { + ParenKind::Parenthesized + } + _ => ParenKind::Nothing, } } @@ -370,7 +429,7 @@ pub fn is_negative_constant(constant: &Constant) -> bool { } /// Check if field expression needs parentheses/braces. -pub fn field_expr(expr: &Expression) -> ParenKind { +pub fn field_expr(arena: &crate::parse_arena::ParseArena, expr: &Expression) -> ParenKind { let opt_braces = parsetree_viewer::process_braces_attr(expr); match opt_braces { Some(attr) => ParenKind::Braced(attr.0.loc.clone()), @@ -380,8 +439,8 @@ pub fn field_expr(expr: &Expression) -> ParenKind { return ParenKind::Parenthesized; } - if parsetree_viewer::is_binary_expression(expr) - || parsetree_viewer::is_unary_expression(expr) + if parsetree_viewer::is_binary_expression(arena, expr) + || parsetree_viewer::is_unary_expression(arena, expr) { return ParenKind::Parenthesized; } @@ -582,12 +641,12 @@ pub fn jsx_child_expr(expr: &Expression) -> ParenKind { } /// Check if binary expression needs parentheses/braces. -pub fn binary_expr(expr: &Expression) -> ParenKind { +pub fn binary_expr(arena: &crate::parse_arena::ParseArena, expr: &Expression) -> ParenKind { let opt_braces = parsetree_viewer::process_braces_attr(expr); match opt_braces { Some(attr) => ParenKind::Braced(attr.0.loc.clone()), None => { - if !expr.pexp_attributes.is_empty() && parsetree_viewer::is_binary_expression(expr) { + if !expr.pexp_attributes.is_empty() && parsetree_viewer::is_binary_expression(arena, expr) { ParenKind::Parenthesized } else { ParenKind::Nothing @@ -637,29 +696,24 @@ pub fn include_mod_expr(mod_expr: &ModuleExpr) -> bool { } /// Check if module expression needs parentheses. +/// OCaml logic: +/// - Pmod_constraint(Pmod_structure, Pmty_signature([Psig_module])) -> false +/// - Pmod_constraint(_, Pmty_signature([Psig_module])) -> true +/// - Otherwise -> false pub fn mod_expr_parens(mod_expr: &ModuleExpr) -> bool { match &mod_expr.pmod_desc { ModuleExprDesc::Pmod_constraint(inner, typ) => { - // Check if inner is Pmod_structure and typ is Pmty_signature with single Psig_module - match (&inner.pmod_desc, &typ.pmty_desc) { - (ModuleExprDesc::Pmod_structure(_), ModuleTypeDesc::Pmty_signature(items)) => { - if items.len() == 1 { - if let SignatureItemDesc::Psig_module(_) = &items[0].psig_desc { - return false; - } + // Check if typ is Pmty_signature with single Psig_module + if let ModuleTypeDesc::Pmty_signature(items) = &typ.pmty_desc { + if items.len() == 1 { + if let SignatureItemDesc::Psig_module(_) = &items[0].psig_desc { + // Sig is [Psig_module] - return false if inner is Pmod_structure, true otherwise + return !matches!(&inner.pmod_desc, ModuleExprDesc::Pmod_structure(_)); } - true } - (_, ModuleTypeDesc::Pmty_signature(items)) => { - if items.len() == 1 { - if let SignatureItemDesc::Psig_module(_) = &items[0].psig_desc { - return true; - } - } - false - } - _ => false, } + // Not the special [Psig_module] case -> false + false } _ => false, } diff --git a/compiler-rust/src/parser/parsetree_viewer.rs b/compiler-rust/src/parser/parsetree_viewer.rs index bcb5fc6168d..5e2e4013d6f 100644 --- a/compiler-rust/src/parser/parsetree_viewer.rs +++ b/compiler-rust/src/parser/parsetree_viewer.rs @@ -3,7 +3,7 @@ //! This module provides helper functions for analyzing and inspecting the AST. //! It's a port of OCaml's `res_parsetree_viewer.ml`. -use crate::location::Location; +use crate::parse_arena::{LocIdx, ParseArena}; use crate::parser::ast::*; use crate::parser::longident::Longident; @@ -48,6 +48,11 @@ pub fn has_ternary_attribute(attrs: &Attributes) -> bool { attrs.iter().any(|attr| attr.0.txt == "res.ternary") } +/// Check if an expression has the tagged template attribute. +pub fn has_tagged_template_attr(attrs: &Attributes) -> bool { + attrs.iter().any(|attr| attr.0.txt == "res.taggedTemplate") +} + /// Check if an expression is a ternary expression. /// This checks for the res.ternary attribute which is added by the parser /// for expressions like `cond ? a : b` (as opposed to `if cond { a } else { b }`). @@ -118,9 +123,10 @@ pub enum IfConditionKind<'a> { /// Collect all the branches of an if-expression chain. /// Returns a list of (location, condition_kind, then_expr) tuples and the final else expression. -pub fn collect_if_expressions( - expr: &Expression, -) -> (Vec<(&Location, IfConditionKind<'_>, &Expression)>, Option<&Expression>) { +pub fn collect_if_expressions<'a>( + arena: &crate::parse_arena::ParseArena, + expr: &'a Expression, +) -> (Vec<(&'a LocIdx, IfConditionKind<'a>, &'a Expression)>, Option<&'a Expression>) { let mut acc = Vec::new(); let mut current = expr; @@ -144,7 +150,7 @@ pub fn collect_if_expressions( && cases[0].pc_guard.is_none() && matches!( &cases[1].pc_rhs.pexp_desc, - ExpressionDesc::Pexp_construct(lid, _) if matches!(&lid.txt, Longident::Lident(s) if s == "()") + ExpressionDesc::Pexp_construct(lid, _) if arena.is_lident(lid.txt, "()") ) => { let pattern = &cases[0].pc_lhs; @@ -178,7 +184,7 @@ pub fn is_single_expression(expr: &Expression) -> bool { } /// Check if expression is a binary expression. -pub fn is_binary_expression(expr: &Expression) -> bool { +pub fn is_binary_expression(arena: &crate::parse_arena::ParseArena, expr: &Expression) -> bool { match &expr.pexp_desc { ExpressionDesc::Pexp_apply { funct, args, .. } => { if args.len() != 2 { @@ -186,8 +192,9 @@ pub fn is_binary_expression(expr: &Expression) -> bool { } match &funct.pexp_desc { ExpressionDesc::Pexp_ident(ident) => { - if let Longident::Lident(op) = &ident.txt { - not_ghost_operator(op, &ident.loc) + if let Longident::Lident(op_idx) = arena.get_longident(ident.txt) { + let op = arena.get_string(*op_idx); + not_ghost_operator(op, ident.loc.is_none()) } else { false } @@ -200,7 +207,7 @@ pub fn is_binary_expression(expr: &Expression) -> bool { } /// Get the operator from a binary expression, if it is one. -pub fn get_binary_operator(expr: &Expression) -> Option { +pub fn get_binary_operator(arena: &crate::parse_arena::ParseArena, expr: &Expression) -> Option { match &expr.pexp_desc { ExpressionDesc::Pexp_apply { funct, args, .. } => { if args.len() != 2 { @@ -208,9 +215,10 @@ pub fn get_binary_operator(expr: &Expression) -> Option { } match &funct.pexp_desc { ExpressionDesc::Pexp_ident(ident) => { - if let Longident::Lident(op) = &ident.txt { - if not_ghost_operator(op, &ident.loc) { - return Some(op.clone()); + if let Longident::Lident(op_idx) = arena.get_longident(ident.txt) { + let op = arena.get_string(*op_idx); + if not_ghost_operator(op, ident.loc.is_none()) { + return Some(op.to_string()); } } None @@ -222,6 +230,49 @@ pub fn get_binary_operator(expr: &Expression) -> Option { } } +/// Check if an expression is a single pipe expression. +/// Returns true for `x->f(g)` but not for `x->f->g` (multiple pipes). +/// Used for value binding layout optimization. +pub fn is_single_pipe_expr(arena: &crate::parse_arena::ParseArena, expr: &Expression) -> bool { + // Helper to check if expr is a pipe expression + fn is_pipe(arena: &crate::parse_arena::ParseArena, expr: &Expression) -> bool { + match &expr.pexp_desc { + ExpressionDesc::Pexp_apply { funct, args, .. } => { + if args.len() != 2 { + return false; + } + if let ExpressionDesc::Pexp_ident(ident) = &funct.pexp_desc { + if let Longident::Lident(op_idx) = arena.get_longident(ident.txt) { + return arena.get_string(*op_idx) == "->"; + } + } + false + } + _ => false, + } + } + + // Check if this is a pipe where the LHS is NOT also a pipe + match &expr.pexp_desc { + ExpressionDesc::Pexp_apply { funct, args, .. } => { + if args.len() != 2 { + return false; + } + if let ExpressionDesc::Pexp_ident(ident) = &funct.pexp_desc { + if let Longident::Lident(op_idx) = arena.get_longident(ident.txt) { + if arena.get_string(*op_idx) == "->" { + // It's a pipe - check that LHS is not also a pipe + let operand1 = &args[0].1; + return !is_pipe(arena, operand1); + } + } + } + false + } + _ => false, + } +} + /// Check if expression is an await expression. pub fn expr_is_await(expr: &Expression) -> bool { matches!(&expr.pexp_desc, ExpressionDesc::Pexp_await(_)) @@ -264,18 +315,58 @@ pub fn expr_is_uncurried_fun(expr: &Expression) -> bool { ) } +/// Check if the last argument is a callback that needs special printing. +/// This returns true if the last argument is a function/newtype and +/// all other arguments are NOT functions/newtypes. +/// Note: underscore apply sugar is NOT considered a callback here because +/// OCaml rewrites it before this check, and after rewriting it becomes Pexp_apply. +pub fn requires_special_callback_printing_last_arg(args: &[(ArgLabel, Expression)]) -> bool { + let mut iter = args.iter().peekable(); + while let Some((_, expr)) = iter.next() { + // Skip underscore apply sugar - it gets rewritten to Pexp_apply + if is_underscore_apply_sugar(expr) { + continue; + } + if is_fun_newtype(expr) { + // If this is the last element, return true + // Otherwise (function in non-last position), return false + return iter.peek().is_none(); + } + } + false +} + +/// Check if the first argument is a callback that needs special printing. +/// This returns true if: +/// - The first argument is a function/newtype (but NOT underscore apply sugar) +/// - AND there is at least one more argument after it +/// - AND all remaining arguments are NOT functions/newtypes +pub fn requires_special_callback_printing_first_arg(args: &[(ArgLabel, Expression)]) -> bool { + // Helper: is it a real callback (not underscore apply sugar) + fn is_real_callback(expr: &Expression) -> bool { + is_fun_newtype(expr) && !is_underscore_apply_sugar(expr) + } + match args { + // Single argument callback - use normal printing + [(_, expr)] if is_real_callback(expr) => false, + // First is callback, need to check rest + [(_, expr), rest @ ..] if is_real_callback(expr) => { + // All remaining args must NOT be callbacks + rest.iter().all(|(_, e)| !is_real_callback(e)) + } + _ => false, + } +} + /// Check if an expression is "huggable" (can be printed without line breaks). -pub fn is_huggable_expression(expr: &Expression) -> bool { +pub fn is_huggable_expression(arena: &crate::parse_arena::ParseArena, expr: &Expression) -> bool { match &expr.pexp_desc { ExpressionDesc::Pexp_array(_) | ExpressionDesc::Pexp_tuple(_) | ExpressionDesc::Pexp_record(_, _) => true, ExpressionDesc::Pexp_constant(Constant::String(_, Some(_))) => true, ExpressionDesc::Pexp_construct(lid, _) - if matches!( - lid.txt, - Longident::Lident(ref s) if s == "::" || s == "[]" - ) => + if arena.is_lident(lid.txt, "::") || arena.is_lident(lid.txt, "[]") => { true } @@ -311,12 +402,25 @@ fn is_multiline_text(txt: &str) -> bool { false } +/// Check if an expression is "huggable" as a RHS (simpler than is_huggable_expression). +pub fn is_huggable_rhs(expr: &Expression) -> bool { + match &expr.pexp_desc { + ExpressionDesc::Pexp_array(_) + | ExpressionDesc::Pexp_tuple(_) + | ExpressionDesc::Pexp_record(_, _) => true, + ExpressionDesc::Pexp_extension(ext) if ext.0.txt == "obj" => true, + _ if is_braced_expr(expr) => true, + _ => false, + } +} + /// Check if a longident represents a binary operator. -pub fn is_binary_operator(lid: &Longident) -> bool { +pub fn is_binary_operator(arena: &crate::parse_arena::ParseArena, lid: &Longident) -> bool { match lid { - Longident::Lident(op) => { + Longident::Lident(op_idx) => { + let op = arena.get_string(*op_idx); matches!( - op.as_str(), + op, "+" | "+." | "-" | "-." @@ -356,14 +460,14 @@ pub fn is_binary_operator(lid: &Longident) -> bool { } /// Check if an expression is a unary expression. -pub fn is_unary_expression(expr: &Expression) -> bool { +pub fn is_unary_expression(arena: &crate::parse_arena::ParseArena, expr: &Expression) -> bool { match &expr.pexp_desc { ExpressionDesc::Pexp_apply { funct, args, .. } => { if args.len() != 1 { return false; } if let ExpressionDesc::Pexp_ident(ident) = &funct.pexp_desc { - is_unary_operator(&ident.txt) + is_unary_operator_idx(arena, ident.txt) } else { false } @@ -372,32 +476,98 @@ pub fn is_unary_expression(expr: &Expression) -> bool { } } +/// Check if a longident index represents a unary operator. +pub fn is_unary_operator_idx(arena: &crate::parse_arena::ParseArena, lid_idx: crate::parse_arena::LidentIdx) -> bool { + if let Longident::Lident(op_idx) = arena.get_longident(lid_idx) { + let op = arena.get_string(*op_idx); + matches!(op, "~+" | "~+." | "~-" | "~-." | "~~~" | "!" | "not") + } else { + false + } +} + /// Check if a longident represents a unary operator. -pub fn is_unary_operator(lid: &Longident) -> bool { +pub fn is_unary_operator(arena: &crate::parse_arena::ParseArena, lid: &Longident) -> bool { match lid { - Longident::Lident(op) => { - matches!(op.as_str(), "~+" | "~+." | "~-" | "~-." | "~~~" | "!" | "not") + Longident::Lident(op_idx) => { + let op = arena.get_string(*op_idx); + matches!(op, "~+" | "~+." | "~-" | "~-." | "~~~" | "!" | "not") } _ => false, } } +/// Check if the RHS of a binary expression should be inlined (not put on a new line). +/// This matches OCaml's should_inline_rhs_binary_expr from res_parsetree_viewer.ml: +/// - Pexp_constant: inline +/// - Pexp_let, Pexp_letmodule, Pexp_letexception: inline +/// - Pexp_sequence, Pexp_open, Pexp_ifthenelse: inline +/// - Pexp_for, Pexp_while, Pexp_try: inline +/// - Pexp_array, Pexp_record: inline +/// Note: Pexp_match (switch) is NOT in this list, so it will NOT inline +pub fn should_inline_rhs_binary_expr(expr: &Expression) -> bool { + matches!( + &expr.pexp_desc, + ExpressionDesc::Pexp_constant(_) + | ExpressionDesc::Pexp_let(_, _, _) + | ExpressionDesc::Pexp_letmodule(_, _, _) + | ExpressionDesc::Pexp_letexception(_, _) + | ExpressionDesc::Pexp_sequence(_, _) + | ExpressionDesc::Pexp_open(_, _, _) + | ExpressionDesc::Pexp_ifthenelse(_, _, _) + | ExpressionDesc::Pexp_for(_, _, _, _, _) + | ExpressionDesc::Pexp_while(_, _) + | ExpressionDesc::Pexp_try(_, _) + | ExpressionDesc::Pexp_array(_) + | ExpressionDesc::Pexp_record(_, _) + ) +} + // ============================================================================ -// List Collection +// Dict and List Utilities // ============================================================================ +/// Check if an expression is an array of tuples (for dict detection). +/// Used to detect dict{} syntax which desugars to Primitive_dict.make([("key", value), ...]) +pub fn is_tuple_array(expr: &Expression) -> bool { + if let ExpressionDesc::Pexp_array(items) = &expr.pexp_desc { + items.iter().all(|e| matches!(&e.pexp_desc, ExpressionDesc::Pexp_tuple(_))) + } else { + false + } +} + +/// Check if a pattern has the res.dictPattern attribute. +/// Used to detect dict{} pattern syntax which desugars to @res.dictPattern {...} +pub fn has_dict_pattern_attribute(attrs: &[Attribute]) -> bool { + attrs.iter().any(|attr| attr.0.txt == "res.dictPattern") +} + +/// Check if a pattern is "huggable" (can be printed without line breaks). +/// Used for dict pattern rows to determine if the pattern should be on the same line as the key. +pub fn is_huggable_pattern(pat: &Pattern) -> bool { + matches!( + &pat.ppat_desc, + PatternDesc::Ppat_array(_) + | PatternDesc::Ppat_tuple(_) + | PatternDesc::Ppat_record(_, _) + | PatternDesc::Ppat_variant(_, _) + | PatternDesc::Ppat_construct(_, _) + ) +} + /// Collect expressions from a list constructor (::). /// Returns (list of expressions, optional spread expression). -pub fn collect_list_expressions(expr: &Expression) -> (Vec<&Expression>, Option<&Expression>) { +pub fn collect_list_expressions<'a>(arena: &crate::parse_arena::ParseArena, expr: &'a Expression) -> (Vec<&'a Expression>, Option<&'a Expression>) { let mut acc = Vec::new(); let mut current = expr; loop { match ¤t.pexp_desc { - ExpressionDesc::Pexp_construct(lid, None) if lid.txt == Longident::Lident("[]".to_string()) => { + ExpressionDesc::Pexp_construct(lid, None) if arena.is_lident(lid.txt, "[]") => { return (acc, None); } - ExpressionDesc::Pexp_construct(lid, Some(arg)) if lid.txt == Longident::Lident("::".to_string()) => { + ExpressionDesc::Pexp_construct(lid, Some(arg)) if arena.is_lident(lid.txt, "::") => { // The argument should be a tuple of (head, tail) if let ExpressionDesc::Pexp_tuple(exprs) = &arg.pexp_desc { if exprs.len() == 2 { @@ -418,16 +588,16 @@ pub fn collect_list_expressions(expr: &Expression) -> (Vec<&Expression>, Option< } /// Collect patterns from a list constructor (::). -pub fn collect_list_patterns(pat: &Pattern) -> (Vec<&Pattern>, Option<&Pattern>) { +pub fn collect_list_patterns<'a>(arena: &crate::parse_arena::ParseArena, pat: &'a Pattern) -> (Vec<&'a Pattern>, Option<&'a Pattern>) { let mut acc = Vec::new(); let mut current = pat; loop { match ¤t.ppat_desc { - PatternDesc::Ppat_construct(lid, None) if lid.txt == Longident::Lident("[]".to_string()) => { + PatternDesc::Ppat_construct(lid, None) if arena.is_lident(lid.txt, "[]") => { return (acc, None); } - PatternDesc::Ppat_construct(lid, Some(arg)) if lid.txt == Longident::Lident("::".to_string()) => { + PatternDesc::Ppat_construct(lid, Some(arg)) if arena.is_lident(lid.txt, "::") => { // The argument should be a tuple of (head, tail) if let PatternDesc::Ppat_tuple(pats) = &arg.ppat_desc { if pats.len() == 2 { @@ -470,36 +640,62 @@ pub fn collect_array_expressions(expr: &Expression) -> (Vec<&Expression>, Option pub enum FunParam<'a> { /// Regular parameter with pattern Parameter { - attrs: &'a Attributes, + attrs: &'a [Attribute], label: &'a ArgLabel, default_expr: Option<&'a Expression>, pat: &'a Pattern, }, - /// Newtype parameter: (type t) - NewType { - attrs: &'a Attributes, - name: &'a StringLoc, + /// Newtype parameter(s): (type t) or (type t u v) + /// Multiple consecutive newtypes are combined into a single NewTypes variant. + NewTypes { + attrs: &'a [Attribute], + names: Vec<&'a StringLoc>, }, } /// Extract function parameters from a potentially nested function expression. /// Returns (is_async, parameters, body). +/// +/// This matches OCaml's fun_expr which uses the `arity` field to determine +/// when to stop collecting parameters. For curried functions like +/// `(a, b, c) => (d, e, f) => 4`, the first function has an arity marker +/// that signals the end of its parameter list. +/// +/// The rule from OCaml: collect params when `arity = None || n_fun = 0` +/// - Always collect from the first function (n_fun = 0) +/// - For nested functions, only collect if arity is Unknown (no marker) +/// +/// IMPORTANT: OCaml's fun_expr only collects Pexp_newtype at the BEGINNING, +/// not during the collect_params loop. After encountering any Pexp_fun, +/// the loop stops at non-Pexp_fun nodes (including Pexp_newtype). pub fn fun_expr(expr: &Expression) -> (bool, Vec>, &Expression) { - // Check for async attribute OR is_async field in Pexp_fun - let mut is_async = expr.pexp_attributes.iter().any(|attr| attr.0.txt == "res.async"); + use crate::parser::ast::Arity; - // Also check is_async field on the first Pexp_fun - if let ExpressionDesc::Pexp_fun { - is_async: expr_is_async, - .. - } = &expr.pexp_desc - { - is_async = is_async || *expr_is_async; - } + // Check for async attribute on the outermost expression + let mut is_async = expr.pexp_attributes.iter().any(|attr| attr.0.txt == "res.async"); let mut params = Vec::new(); let mut current = expr; + // First, collect leading Pexp_newtype (like OCaml's top-level match) + // This combines consecutive newtypes like "type t, type u" into "type t u" + if let ExpressionDesc::Pexp_newtype(name, body) = ¤t.pexp_desc { + let mut names = vec![name]; + current = body; + + // Collect any additional consecutive newtypes + while let ExpressionDesc::Pexp_newtype(next_name, next_body) = ¤t.pexp_desc { + names.push(next_name); + current = next_body; + } + + params.push(FunParam::NewTypes { attrs: &[], names }); + } + + // Now collect_params: only handle Pexp_fun, stop at anything else + let mut n_fun = 0; + let mut found_first_pexp_fun = false; + loop { match ¤t.pexp_desc { ExpressionDesc::Pexp_fun { @@ -507,23 +703,44 @@ pub fn fun_expr(expr: &Expression) -> (bool, Vec>, &Expression) { default, lhs, rhs, - .. + arity, + is_async: expr_is_async, } => { - params.push(FunParam::Parameter { - attrs: ¤t.pexp_attributes, - label: arg_label, - default_expr: default.as_ref().map(|e| e.as_ref()), - pat: lhs, - }); - current = rhs; - } - ExpressionDesc::Pexp_newtype(name, body) => { - params.push(FunParam::NewType { - attrs: ¤t.pexp_attributes, - name, - }); - current = body; + // Check is_async on the FIRST Pexp_fun we encounter + // (it may be nested inside Pexp_newtype) + if !found_first_pexp_fun { + is_async = is_async || *expr_is_async; + found_first_pexp_fun = true; + } + + // OCaml's condition: arity = None || n_fun = 0 + // In Rust: Arity::Unknown corresponds to None, Arity::Full(_) to Some(_) + // Only collect if this is the first function OR there's no arity marker + if n_fun == 0 || matches!(arity, Arity::Unknown) { + // OCaml's fun_expr passes {expr_ with pexp_attributes = []} to collect_params, + // which means the FIRST parameter always gets empty attrs. For nested functions, + // the inner expression keeps its attributes. We emulate this by using empty + // slice for n_fun == 0. + let attrs: &[Attribute] = if n_fun == 0 { + &[] // First parameter: OCaml strips top-level attrs + } else { + ¤t.pexp_attributes // Nested: preserve attrs + }; + params.push(FunParam::Parameter { + attrs, + label: arg_label, + default_expr: default.as_ref().map(|e| e.as_ref()), + pat: lhs, + }); + n_fun += 1; + current = rhs; + } else { + // Stop collecting - arity marker indicates end of this function's params + break; + } } + // IMPORTANT: Don't collect Pexp_newtype here - OCaml's collect_params doesn't + // This ensures `(type a, ()) => (type b c, x) => 3` keeps the two functions separate _ => break, } } @@ -553,8 +770,58 @@ pub fn pattern_has_spread_attr(attrs: &Attributes) -> bool { has_spread_attr(attrs) } +/// Check if expression is Belt.Array.concatMany with @res.spread attribute. +/// This is the desugared form of `[...xs, a, b]`. +pub fn is_spread_belt_array_concat(arena: &ParseArena, expr: &Expression) -> bool { + match &expr.pexp_desc { + ExpressionDesc::Pexp_ident(loc_idx) => { + // Belt.Array.concatMany: Ldot(Ldot(Lident("Belt"), "Array"), "concatMany") + if let Longident::Ldot(parent, name_idx) = arena.get_longident(loc_idx.txt) { + if arena.get_string(*name_idx) == "concatMany" { + if let Longident::Ldot(grandparent, parent_name_idx) = parent.as_ref() { + if arena.get_string(*parent_name_idx) == "Array" { + if let Longident::Lident(base_idx) = grandparent.as_ref() { + if arena.get_string(*base_idx) == "Belt" { + return has_spread_attr(&expr.pexp_attributes); + } + } + } + } + } + } + false + } + _ => false, + } +} + +/// Check if expression is Belt.List.concatMany with @res.spread attribute. +/// This is the desugared form of `list{...xs, a, b}`. +pub fn is_spread_belt_list_concat(arena: &ParseArena, expr: &Expression) -> bool { + match &expr.pexp_desc { + ExpressionDesc::Pexp_ident(loc_idx) => { + // Belt.List.concatMany: Ldot(Ldot(Lident("Belt"), "List"), "concatMany") + if let Longident::Ldot(parent, name_idx) = arena.get_longident(loc_idx.txt) { + if arena.get_string(*name_idx) == "concatMany" { + if let Longident::Ldot(grandparent, parent_name_idx) = parent.as_ref() { + if arena.get_string(*parent_name_idx) == "List" { + if let Longident::Lident(base_idx) = grandparent.as_ref() { + if arena.get_string(*base_idx) == "Belt" { + return has_spread_attr(&expr.pexp_attributes); + } + } + } + } + } + } + false + } + _ => false, + } +} + /// Filter out parsing-only attributes (res.braces, res.ternary, res.await, etc.) -pub fn filter_parsing_attrs(attrs: &Attributes) -> Vec<&Attribute> { +pub fn filter_parsing_attrs(attrs: &[Attribute]) -> Vec<&Attribute> { attrs .iter() .filter(|attr| { @@ -582,12 +849,12 @@ pub fn is_printable_attribute(attr: &Attribute) -> bool { "res.iflet" | "res.braces" | "ns.braces" - | "JSX" | "res.await" | "res.template" | "res.taggedTemplate" | "res.ternary" | "res.inlineRecordDefinition" + | "res.dictPattern" ) } @@ -601,6 +868,21 @@ pub fn filter_printable_attributes(attrs: &Attributes) -> Vec<&Attribute> { attrs.iter().filter(|a| is_printable_attribute(a)).collect() } +/// Partition attributes into printable and internal (non-printable). +/// Returns (printable_attrs, internal_attrs). +pub fn partition_printable_attributes(attrs: &Attributes) -> (Vec<&Attribute>, Vec<&Attribute>) { + let mut printable = Vec::new(); + let mut internal = Vec::new(); + for attr in attrs.iter() { + if is_printable_attribute(attr) { + printable.push(attr); + } else { + internal.push(attr); + } + } + (printable, internal) +} + /// Check if expression has any attributes (excluding internal parsing ones). pub fn has_attributes(attrs: &Attributes) -> bool { attrs.iter().any(|attr| { @@ -617,6 +899,13 @@ pub fn has_attributes(attrs: &Attributes) -> bool { }) } +/// Check if an attribute is the inline record definition marker. +pub fn has_inline_record_definition_attribute(attrs: &Attributes) -> bool { + attrs + .iter() + .any(|attr| attr.0.txt == "res.inlineRecordDefinition") +} + // ============================================================================ // JSX Analysis // ============================================================================ @@ -661,6 +950,80 @@ pub fn is_equality_operator(op: &str) -> bool { matches!(op, "==" | "===" | "!=" | "!==") } +/// Check if the operator is right-associative. +/// Currently only exponentiation (**) is right-associative. +pub fn is_rhs_binary_operator(op: &str) -> bool { + op == "**" +} + +/// Check if parent and child operators can be flattened (same precedence, not both equality). +pub fn flattenable_operators(parent_op: &str, child_op: &str) -> bool { + let prec_parent = operator_precedence(parent_op); + let prec_child = operator_precedence(child_op); + if prec_parent == prec_child { + !(is_equality_operator(parent_op) && is_equality_operator(child_op)) + } else { + false + } +} + +/// Check if a binary expression should have its RHS indented. +/// Returns true if: +/// - The operator is an equality operator (==, ===, !=, !==), OR +/// - The LHS is NOT a same-precedence sub-expression, OR +/// - The operator is `:=` +pub fn should_indent_binary_expr(arena: &crate::parse_arena::ParseArena, expr: &Expression) -> bool { + use crate::parser::longident::Longident; + + match &expr.pexp_desc { + ExpressionDesc::Pexp_apply { funct, args, .. } if args.len() == 2 => { + if let ExpressionDesc::Pexp_ident(ident) = &funct.pexp_desc { + if let Longident::Lident(op_idx) = arena.get_longident(ident.txt) { + let op = arena.get_string(*op_idx); + if is_binary_operator_str(op) { + // Check the three conditions + if is_equality_operator(op) { + return true; + } + if op == ":=" { + return true; + } + // Check if LHS is NOT a same-precedence sub-expression + let (_, lhs) = &args[0]; + if !same_precedence_sub_expression(arena, op, lhs) { + return true; + } + } + } + } + false + } + _ => false, + } +} + +/// Check if sub_expression is a binary expression with same precedence as parent operator. +fn same_precedence_sub_expression(arena: &crate::parse_arena::ParseArena, parent_op: &str, sub_expr: &Expression) -> bool { + use crate::parser::longident::Longident; + + match &sub_expr.pexp_desc { + ExpressionDesc::Pexp_apply { funct, args, .. } if args.len() == 2 => { + if let ExpressionDesc::Pexp_ident(ident) = &funct.pexp_desc { + if let Longident::Lident(op_idx) = arena.get_longident(ident.txt) { + let sub_op = arena.get_string(*op_idx); + if is_binary_operator_str(sub_op) { + return flattenable_operators(parent_op, sub_op); + } + } + } + // Not a binary expression, so not same precedence + true + } + // Not a binary expression + _ => true, + } +} + /// Check if string is a binary operator. pub fn is_binary_operator_str(op: &str) -> bool { matches!( @@ -704,17 +1067,17 @@ pub fn is_unary_operator_str(op: &str) -> bool { /// Check if operator is not a ghost operator. /// Ghost operators are internal and shouldn't be printed as binary ops. -pub fn not_ghost_operator(op: &str, loc: &Location) -> bool { - is_binary_operator_str(op) && !(loc.loc_ghost && op == "++") +pub fn not_ghost_operator(op: &str, is_ghost: bool) -> bool { + is_binary_operator_str(op) && !(is_ghost && op == "++") } // ============================================================================ // Expression Rewriting // ============================================================================ -/// Rewrite underscore apply: `(__x) => f(a, __x, c)` becomes `f(a, _, c)`. -/// Returns the rewritten expression if applicable, otherwise None. -pub fn rewrite_underscore_apply(expr: &Expression) -> Option { +/// Check if an expression is the underscore apply sugar pattern: `(__x) => f(a, __x, c)`. +/// Returns a reference to the inner apply expression if it matches. +pub fn get_underscore_apply_inner<'a>(expr: &'a Expression) -> Option<&'a Expression> { match &expr.pexp_desc { ExpressionDesc::Pexp_fun { arg_label: ArgLabel::Nolabel, @@ -727,10 +1090,8 @@ pub fn rewrite_underscore_apply(expr: &Expression) -> Option { if let PatternDesc::Ppat_var(name) = &lhs.ppat_desc { if name.txt == "__x" { // Check if rhs is an apply - if let ExpressionDesc::Pexp_apply { .. } = &rhs.pexp_desc { - // TODO: Actually rewrite the apply to use `_` - // For now, just return None to use the original printing - return None; + if matches!(&rhs.pexp_desc, ExpressionDesc::Pexp_apply { .. }) { + return Some(rhs); } } } @@ -740,6 +1101,15 @@ pub fn rewrite_underscore_apply(expr: &Expression) -> Option { } } +/// Check if an expression is a `__x` identifier that should be printed as `_`. +/// Used when printing inside underscore apply sugar. +pub fn is_underscore_ident(expr: &Expression, arena: &ParseArena) -> bool { + match &expr.pexp_desc { + ExpressionDesc::Pexp_ident(lid) => arena.is_lident(lid.txt, "__x"), + _ => false, + } +} + // ============================================================================ // Type Analysis // ============================================================================ @@ -768,15 +1138,19 @@ pub fn arrow_type<'a>( typ: &'a CoreType, max_arity: Option, ) -> (&'a Attributes, Vec>, &'a CoreType) { - let max_arity = max_arity.unwrap_or(usize::MAX); + // Use isize to match OCaml's behavior where we stop when arity goes negative + let max_arity: isize = max_arity.map(|n| n as isize).unwrap_or(isize::MAX); fn process<'a>( attrs_before: &'a Attributes, acc: Vec>, typ: &'a CoreType, - remaining_arity: usize, + remaining_arity: isize, ) -> (&'a Attributes, Vec>, &'a CoreType) { - if remaining_arity == 0 { + // OCaml: | _ when max_arity < 0 -> (attrs_before, List.rev acc, typ) + // Stop when we've exhausted our arity budget (gone negative means we + // tried to consume one more than allowed) + if remaining_arity < 0 { return (attrs_before, acc, typ); } @@ -805,6 +1179,7 @@ pub fn arrow_type<'a>( // Labeled argument - continue processing // Calculate adjusted arity for @as workaround + // OCaml: When arg is Ptyp_any with @as attr, don't decrement arity let adjusted_arity = if matches!( &arg.typ.ptyp_desc, CoreTypeDesc::Ptyp_any @@ -905,15 +1280,17 @@ pub fn has_await_attribute(attrs: &Attributes) -> bool { // ============================================================================ /// Check if an expression is `Array.get(arr, idx)`. -pub fn is_array_access(expr: &Expression) -> bool { +pub fn is_array_access(arena: &crate::parse_arena::ParseArena, expr: &Expression) -> bool { match &expr.pexp_desc { ExpressionDesc::Pexp_apply { funct, args, .. } => { if args.len() != 2 { return false; } if let ExpressionDesc::Pexp_ident(lid) = &funct.pexp_desc { - if let Longident::Ldot(base, method) = &lid.txt { - if let Longident::Lident(module) = base.as_ref() { + if let Longident::Ldot(base, method_idx) = arena.get_longident(lid.txt) { + if let Longident::Lident(module_idx) = base.as_ref() { + let module = arena.get_string(*module_idx); + let method = arena.get_string(*method_idx); return module == "Array" && method == "get"; } } @@ -925,15 +1302,17 @@ pub fn is_array_access(expr: &Expression) -> bool { } /// Check if an expression is `Array.set(arr, idx, value)`. -pub fn is_array_set(expr: &Expression) -> bool { +pub fn is_array_set(arena: &crate::parse_arena::ParseArena, expr: &Expression) -> bool { match &expr.pexp_desc { ExpressionDesc::Pexp_apply { funct, args, .. } => { if args.len() != 3 { return false; } if let ExpressionDesc::Pexp_ident(lid) = &funct.pexp_desc { - if let Longident::Ldot(base, method) = &lid.txt { - if let Longident::Lident(module) = base.as_ref() { + if let Longident::Ldot(base, method_idx) = arena.get_longident(lid.txt) { + if let Longident::Lident(module_idx) = base.as_ref() { + let module = arena.get_string(*module_idx); + let method = arena.get_string(*method_idx); return module == "Array" && method == "set"; } } @@ -945,15 +1324,17 @@ pub fn is_array_set(expr: &Expression) -> bool { } /// Check if an expression is `String.get(str, idx)`. -pub fn is_string_access(expr: &Expression) -> bool { +pub fn is_string_access(arena: &crate::parse_arena::ParseArena, expr: &Expression) -> bool { match &expr.pexp_desc { ExpressionDesc::Pexp_apply { funct, args, .. } => { if args.len() != 2 { return false; } if let ExpressionDesc::Pexp_ident(lid) = &funct.pexp_desc { - if let Longident::Ldot(base, method) = &lid.txt { - if let Longident::Lident(module) = base.as_ref() { + if let Longident::Ldot(base, method_idx) = arena.get_longident(lid.txt) { + if let Longident::Lident(module_idx) = base.as_ref() { + let module = arena.get_string(*module_idx); + let method = arena.get_string(*method_idx); return module == "String" && method == "get"; } } @@ -966,10 +1347,10 @@ pub fn is_string_access(expr: &Expression) -> bool { /// Check if an expression is a rewritten underscore apply sugar pattern. /// i.e., the pattern `_` that comes from `arr[_]` being rewritten to `(__x) => Array.get(__x, _)`. -pub fn is_rewritten_underscore_apply_sugar(expr: &Expression) -> bool { +pub fn is_rewritten_underscore_apply_sugar(arena: &crate::parse_arena::ParseArena, expr: &Expression) -> bool { match &expr.pexp_desc { ExpressionDesc::Pexp_ident(lid) => { - matches!(&lid.txt, Longident::Lident(name) if name == "_") + arena.is_lident(lid.txt, "_") } _ => false, } diff --git a/compiler-rust/src/parser/pattern.rs b/compiler-rust/src/parser/pattern.rs index 49f49a397c7..6b7115c74d6 100644 --- a/compiler-rust/src/parser/pattern.rs +++ b/compiler-rust/src/parser/pattern.rs @@ -6,10 +6,23 @@ use super::ast::*; use super::core::{ast_helper, mknoloc, recover, template_literal_attr, with_loc}; use super::diagnostics::DiagnosticCategory; +use super::grammar::{self, Grammar}; use super::longident::Longident; use super::state::Parser; use super::token::Token; -use crate::location::{Located, Position}; +use crate::location::Position; +use crate::parse_arena::{Located, LocIdx}; + +/// Check if a constant is valid for an interval pattern. +/// This includes integers, floats, characters (Constant::Char), and +/// characters encoded as strings with INTERNAL_RES_CHAR_CONTENTS tag. +fn is_interval_constant(c: &Constant) -> bool { + match c { + Constant::Integer(..) | Constant::Char(..) | Constant::Float(..) => true, + Constant::String(_, Some(tag)) if tag == "INTERNAL_RES_CHAR_CONTENTS" => true, + _ => false, + } +} // ============================================================================ // Attribute Parsing for Patterns @@ -26,9 +39,10 @@ fn parse_attributes(p: &mut Parser<'_>) -> Attributes { } } Token::DocComment { loc, content } => { - let loc = loc.clone(); + let loc_cloned = loc.clone(); let content = content.clone(); p.next(); + let loc = p.from_location(&loc_cloned); attrs.push(super::core::doc_comment_to_attribute(loc, content)); } _ => break, @@ -90,7 +104,7 @@ fn parse_attribute_id(p: &mut Parser<'_>, start_pos: Position) -> Located) -> Payload { let expr = super::expr::parse_expr(p); items.push(StructureItem { pstr_desc: StructureItemDesc::Pstr_eval(expr, vec![]), - pstr_loc: crate::location::Location::none(), + pstr_loc: LocIdx::none(), }); if !p.optional(&Token::Comma) && !p.optional(&Token::Semicolon) { @@ -118,7 +132,7 @@ fn parse_payload(p: &mut Parser<'_>) -> Payload { /// Parse a type longident (for #...type pattern). /// Type paths can be like: typevar, Module.typevar, etc. -fn parse_type_longident(p: &mut Parser<'_>) -> Longident { +fn parse_type_longident(p: &mut Parser<'_>) -> crate::parse_arena::LidentIdx { let mut parts = vec![]; loop { @@ -141,11 +155,13 @@ fn parse_type_longident(p: &mut Parser<'_>) -> Longident { } } - if parts.is_empty() { - Longident::Lident("_".to_string()) + let lid = if parts.is_empty() { + let underscore_idx = p.arena_mut().intern_string("_"); + Longident::Lident(underscore_idx) } else { - super::core::build_longident(&parts) - } + super::core::build_longident(p.arena_mut(), &parts) + }; + p.push_longident(lid) } // ============================================================================ @@ -165,64 +181,61 @@ fn parse_single_pattern(p: &mut Parser<'_>) -> Pattern { // Handle interval patterns: 1 .. 2, 'a' .. 'z', -1 .. -1., etc. if p.token == Token::DotDot { if let PatternDesc::Ppat_constant(from) = &pat.ppat_desc { - match from { - Constant::Integer(..) | Constant::Char(..) | Constant::Float(..) => { - let from = from.clone(); - p.next(); - let to = match &p.token { - Token::Int { .. } | Token::Codepoint { .. } | Token::Float { .. } => { - super::expr::parse_constant(p) - } - Token::Minus => { - // Handle negative numbers: -1, -1.0 - p.next(); - match &p.token { - Token::Int { i, suffix } => { - let value = format!("-{}", i); - let suffix = suffix.clone(); - p.next(); - Constant::Integer(value, suffix) - } - Token::Float { f, suffix } => { - let value = format!("-{}", f); - let suffix = suffix.clone(); - p.next(); - Constant::Float(value, suffix) - } - _ => { - p.err(DiagnosticCategory::Message( - "Expected number after '-' in interval pattern".to_string(), - )); - Constant::Integer("0".to_string(), None) - } + if is_interval_constant(from) { + let from = from.clone(); + p.next(); + let to = match &p.token { + Token::Int { .. } | Token::Codepoint { .. } | Token::Float { .. } => { + super::expr::parse_constant(p) + } + Token::Minus => { + // Handle negative numbers: -1, -1.0 + p.next(); + match &p.token { + Token::Int { i, suffix } => { + let value = format!("-{}", i); + let suffix = suffix.clone(); + p.next(); + Constant::Integer(value, suffix) + } + Token::Float { f, suffix } => { + let value = format!("-{}", f); + let suffix = suffix.clone(); + p.next(); + Constant::Float(value, suffix) + } + _ => { + p.err(DiagnosticCategory::Message( + "Expected number after '-' in interval pattern".to_string(), + )); + Constant::Integer("0".to_string(), None) } } - _ => { - p.err(DiagnosticCategory::Message( - "Expected constant after '..' in pattern".to_string(), - )); - Constant::Integer("0".to_string(), None) - } - }; - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); - pat = Pattern { - ppat_desc: PatternDesc::Ppat_interval(from, to), - ppat_loc: loc, - ppat_attributes: vec![], - }; - } - _ => {} + } + _ => { + p.err(DiagnosticCategory::Message( + "Expected constant after '..' in pattern".to_string(), + )); + Constant::Integer("0".to_string(), None) + } + }; + let loc = p.mk_loc_to_prev_end(&start_pos); + pat = Pattern { + ppat_desc: PatternDesc::Ppat_interval(from, to), + ppat_loc: loc, + ppat_attributes: vec![], + }; } } } // Apply leading attributes to the pattern if !attrs.is_empty() { - let loc = p.mk_loc(&start_pos, &pat.ppat_loc.loc_end); + let loc = p.mk_loc(&start_pos, &p.loc_end(pat.ppat_loc)); // OCaml also extends the inner StringLoc in Ppat_var to include attributes let new_desc = match pat.ppat_desc { PatternDesc::Ppat_var(var_loc) => { - let extended_loc = p.mk_loc(&start_pos, &var_loc.loc.loc_end); + let extended_loc = p.mk_loc(&start_pos, &p.loc_end(var_loc.loc)); PatternDesc::Ppat_var(with_loc(var_loc.txt, extended_loc)) } other => other, @@ -253,7 +266,7 @@ fn parse_single_pattern_with_alias(p: &mut Parser<'_>) -> Pattern { let (name, name_loc) = match &p.token { Token::Lident(name) => { let name = name.clone(); - let name_loc = p.mk_loc(&p.start_pos, &p.end_pos); + let name_loc = p.mk_loc_current(); p.next(); (name, name_loc) } @@ -261,7 +274,7 @@ fn parse_single_pattern_with_alias(p: &mut Parser<'_>) -> Pattern { p.err(DiagnosticCategory::Message( "Expected identifier after 'as'".to_string(), )); - let err_loc = p.mk_loc(&p.start_pos, &p.end_pos); + let err_loc = p.mk_loc_current(); ("_".to_string(), err_loc) } }; @@ -269,9 +282,9 @@ fn parse_single_pattern_with_alias(p: &mut Parser<'_>) -> Pattern { let name_with_attrs_loc = if alias_attrs.is_empty() { name_loc } else { - p.mk_loc(&alias_start, &p.prev_end_pos) + p.mk_loc_to_prev_end(&alias_start) }; - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); pat = Pattern { ppat_desc: PatternDesc::Ppat_alias(Box::new(pat), with_loc(name, name_with_attrs_loc)), ppat_loc: loc, @@ -321,7 +334,7 @@ fn parse_or_pattern( patterns .into_iter() .reduce(|acc, pat| { - let loc = p.mk_loc(&acc.ppat_loc.loc_start, &pat.ppat_loc.loc_end); + let loc = p.mk_loc(&p.loc_start(acc.ppat_loc), &p.loc_end(pat.ppat_loc)); Pattern { ppat_desc: PatternDesc::Ppat_or(Box::new(acc), Box::new(pat)), ppat_loc: loc, @@ -337,10 +350,10 @@ pub fn parse_constrained_pattern(p: &mut Parser<'_>) -> Pattern { if p.token == Token::Colon { p.next(); - // Use no-arrow parsing so the `=>` token isn't consumed as part of a type - // when we're in contexts like switch cases: `| pat: t => expr`. - let typ = super::typ::parse_typ_expr_no_arrow(p); - let loc = p.mk_loc(&pat.ppat_loc.loc_start, &typ.ptyp_loc.loc_end); + // OCaml uses parse_typ_expr (with es6_arrow=true) here, not no-arrow. + // Switch cases use parse_pattern (not constrained), so => is safe here. + let typ = super::typ::parse_typ_expr(p); + let loc = p.mk_loc(&p.loc_start(pat.ppat_loc), &p.loc_end(typ.ptyp_loc)); Pattern { ppat_desc: PatternDesc::Ppat_constraint(Box::new(pat), typ), ppat_loc: loc, @@ -352,8 +365,12 @@ pub fn parse_constrained_pattern(p: &mut Parser<'_>) -> Pattern { } /// Create a unit construct pattern `()`. -pub fn make_unit_construct_pattern(loc: crate::location::Location) -> Pattern { - ast_helper::make_construct_pat(Longident::Lident("()".to_string()), None, loc.clone(), loc) +/// OCaml's Ast_helper.Pat.construct uses Location.none for the pattern location +/// when called without ~loc, so we use a ghost location here. +pub fn make_unit_construct_pattern(p: &mut super::state::Parser<'_>, lid_loc: Location) -> Pattern { + let lid_idx = p.push_lident_static("()"); + // Use ghost location for the pattern, but real location for the longident + ast_helper::make_construct_pat(lid_idx, None, lid_loc, LocIdx::none()) } /// Parse an optional alias `as name` after a pattern. @@ -365,13 +382,12 @@ pub fn parse_alias_pattern( mut pat: Pattern, _attrs: Vec, ) -> Pattern { - let start_pos = pat.ppat_loc.loc_start.clone(); while p.token == Token::As { p.next(); let name = match &p.token { Token::Lident(name) => { let name = name.clone(); - let loc = p.mk_loc(&p.start_pos, &p.end_pos); + let loc = p.mk_loc_current(); p.next(); with_loc(name, loc) } @@ -379,10 +395,12 @@ pub fn parse_alias_pattern( p.err(DiagnosticCategory::Message( "Expected identifier after 'as'".to_string(), )); - with_loc("_".to_string(), p.mk_loc(&p.start_pos, &p.end_pos)) + with_loc("_".to_string(), p.mk_loc_current()) } }; - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + // OCaml: {pattern.ppat_loc with loc_end = p.prev_end_pos} + // This preserves loc_start and loc_ghost from the pattern's location + let loc = p.mk_loc_extend_to_prev_end(pat.ppat_loc); pat = Pattern { ppat_desc: PatternDesc::Ppat_alias(Box::new(pat), name), ppat_loc: loc, @@ -421,7 +439,17 @@ pub fn parse_tuple_pattern( } p.expect(Token::Rparen); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + + // OCaml: A tuple needs at least two elements + if patterns.len() == 1 { + p.err_at( + start_pos.clone(), + p.prev_end_pos.clone(), + DiagnosticCategory::Message("A tuple needs at least two elements".to_string()), + ); + } + + let loc = p.mk_loc_to_prev_end(&start_pos); Pattern { ppat_desc: PatternDesc::Ppat_tuple(patterns), @@ -441,7 +469,7 @@ fn parse_atomic_pattern(p: &mut Parser<'_>) -> Pattern { match &p.token { Token::Underscore => { p.next(); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); Pattern { ppat_desc: PatternDesc::Ppat_any, ppat_loc: loc, @@ -451,7 +479,7 @@ fn parse_atomic_pattern(p: &mut Parser<'_>) -> Pattern { Token::Lident(name) => { let name = name.clone(); p.next(); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); // Check for alias (as) if p.token == Token::As { @@ -460,8 +488,8 @@ fn parse_atomic_pattern(p: &mut Parser<'_>) -> Pattern { let alias_start = p.start_pos.clone(); let alias = parse_lident(p); // OCaml: alias name location is just the name, not the whole pattern - let alias_name_loc = p.mk_loc(&alias_start, &p.prev_end_pos); - let overall_loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let alias_name_loc = p.mk_loc_to_prev_end(&alias_start); + let overall_loc = p.mk_loc_to_prev_end(&start_pos); let inner = ast_helper::make_var_pat(name, loc); Pattern { ppat_desc: PatternDesc::Ppat_alias( @@ -481,7 +509,7 @@ fn parse_atomic_pattern(p: &mut Parser<'_>) -> Pattern { | Token::Float { .. } | Token::Codepoint { .. } => { let c = super::expr::parse_constant(p); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); Pattern { ppat_desc: PatternDesc::Ppat_constant(c), ppat_loc: loc, @@ -491,17 +519,21 @@ fn parse_atomic_pattern(p: &mut Parser<'_>) -> Pattern { Token::True | Token::False => { let is_true = p.token == Token::True; p.next(); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); - let lid = Longident::Lident(if is_true { "true" } else { "false" }.to_string()); - ast_helper::make_construct_pat(lid, None, loc.clone(), loc) + let loc = p.mk_loc_to_prev_end(&start_pos); + let bool_str = if is_true { "true" } else { "false" }; + let bool_str_idx = p.arena_mut().intern_string(bool_str); + let lid = Longident::Lident(bool_str_idx); + let lid_idx = p.push_longident(lid); + ast_helper::make_construct_pat(lid_idx, None, loc.clone(), loc) } Token::Lparen => { p.next(); if p.token == Token::Rparen { // Unit pattern: () p.next(); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); - ast_helper::make_construct_pat(Longident::Lident("()".to_string()), None, loc.clone(), loc) + let loc = p.mk_loc_to_prev_end(&start_pos); + let lid_idx = p.push_lident_static("()"); + ast_helper::make_construct_pat(lid_idx, None, loc.clone(), loc) } else { // Parenthesized pattern or tuple let mut pat = parse_constrained_pattern(p); @@ -512,7 +544,7 @@ fn parse_atomic_pattern(p: &mut Parser<'_>) -> Pattern { } else { p.expect(Token::Rparen); // Extend the pattern's location to include the parentheses - pat.ppat_loc = p.mk_loc(&start_pos, &p.prev_end_pos); + pat.ppat_loc = p.mk_loc_to_prev_end(&start_pos); pat } } @@ -530,7 +562,7 @@ fn parse_atomic_pattern(p: &mut Parser<'_>) -> Pattern { Token::Exception => { p.next(); let pat = parse_atomic_pattern(p); - let loc = p.mk_loc(&start_pos, &pat.ppat_loc.loc_end); + let loc = p.mk_loc(&start_pos, &p.loc_end(pat.ppat_loc)); Pattern { ppat_desc: PatternDesc::Ppat_exception(Box::new(pat)), ppat_loc: loc, @@ -545,7 +577,7 @@ fn parse_atomic_pattern(p: &mut Parser<'_>) -> Pattern { let name_loc = match &p.token { Token::Uident(name) | Token::Lident(name) => { let name = name.clone(); - let loc = p.mk_loc(&p.start_pos, &p.end_pos); + let loc = p.mk_loc_current(); p.next(); with_loc(name, loc) } @@ -553,7 +585,7 @@ fn parse_atomic_pattern(p: &mut Parser<'_>) -> Pattern { p.err(DiagnosticCategory::Message( "Expected module name".to_string(), )); - with_loc("Error".to_string(), p.mk_loc(&p.start_pos, &p.end_pos)) + with_loc("Error".to_string(), p.mk_loc_current()) } }; @@ -562,14 +594,15 @@ fn parse_atomic_pattern(p: &mut Parser<'_>) -> Pattern { let colon_pos = p.start_pos.clone(); p.next(); let mut typ = super::typ::parse_package_type(p); - typ.ptyp_loc.loc_start = colon_pos; + // Recreate location starting from colon position + typ.ptyp_loc = p.mk_loc(&colon_pos, &p.loc_end(typ.ptyp_loc)); Some(typ) } else { None }; p.expect(Token::Rparen); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); // OCaml: When there's a constraint, Ppat_unpack's ppat_loc is just the name location. // Without constraint, it spans the full module(...) syntax. @@ -593,6 +626,25 @@ fn parse_atomic_pattern(p: &mut Parser<'_>) -> Pattern { } } Token::Hash => parse_poly_variant_pattern(p), + Token::DotDotDot => { + // Variant spread pattern: ...a or ...Foo.zz + // Creates Ppat_type with res.patVariantSpread attribute + p.next(); + let type_start = p.start_pos.clone(); + let lid = parse_type_longident(p); + let lid_loc = p.mk_loc_to_prev_end(&type_start); + let loc = p.mk_loc_to_prev_end(&start_pos); + // Add res.patVariantSpread attribute with ghost location + let spread_attr: Attribute = ( + Located { txt: "res.patVariantSpread".to_string(), loc: LocIdx::none() }, + Payload::PStr(vec![]), + ); + Pattern { + ppat_desc: PatternDesc::Ppat_type(with_loc(lid, lid_loc)), + ppat_loc: loc, + ppat_attributes: vec![spread_attr], + } + } Token::Percent => parse_extension_pattern(p, start_pos), Token::Backtick | Token::TemplateTail { .. } | Token::TemplatePart { .. } => { parse_template_literal_pattern(p, start_pos) @@ -601,15 +653,15 @@ fn parse_atomic_pattern(p: &mut Parser<'_>) -> Pattern { // List cons constructor: :: (printed by the current list pattern printer) p.next(); if p.token != Token::Colon { - p.err(DiagnosticCategory::Message( - "Unexpected token in pattern: Colon".to_string(), - )); + // Use err_unexpected for proper error message + p.err_unexpected(); recover::default_pattern() } else { p.next(); - let lid_loc = p.mk_loc(&start_pos, &p.prev_end_pos); - let lid = mknoloc(Longident::Lident("::".to_string())); + let lid_loc = p.mk_loc_to_prev_end(&start_pos); + let lid_idx = p.push_lident_static("::"); + let lid = mknoloc(lid_idx); let arg = if p.token == Token::Lparen { // Capture position of ( for tuple location (OCaml includes parens) @@ -617,9 +669,10 @@ fn parse_atomic_pattern(p: &mut Parser<'_>) -> Pattern { p.next(); if p.token == Token::Rparen { p.next(); - let unit_loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let unit_loc = p.mk_loc_to_prev_end(&start_pos); + let unit_lid_idx = p.push_lident_static("()"); Some(ast_helper::make_construct_pat( - Longident::Lident("()".to_string()), + unit_lid_idx, None, unit_loc.clone(), unit_loc, @@ -643,7 +696,7 @@ fn parse_atomic_pattern(p: &mut Parser<'_>) -> Pattern { if patterns.len() == 1 { let single = patterns.into_iter().next().unwrap(); if matches!(single.ppat_desc, PatternDesc::Ppat_tuple(_)) { - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); Some(Pattern { ppat_desc: PatternDesc::Ppat_tuple(vec![single]), ppat_loc: loc, @@ -654,7 +707,7 @@ fn parse_atomic_pattern(p: &mut Parser<'_>) -> Pattern { } } else { // OCaml uses p.end_pos (end of next token after `)`) for tuple location - let tuple_loc = p.mk_loc(&tuple_start, &p.end_pos); + let tuple_loc = p.mk_loc_to_end(&tuple_start); Some(Pattern { ppat_desc: PatternDesc::Ppat_tuple(patterns), ppat_loc: tuple_loc, @@ -668,7 +721,7 @@ fn parse_atomic_pattern(p: &mut Parser<'_>) -> Pattern { // C((a,b)) = single tuple argument = Ppat_tuple([Ppat_tuple([a,b])]) // C(a,b) = multiple arguments = Ppat_tuple([a, b]) if matches!(first.ppat_desc, PatternDesc::Ppat_tuple(_)) { - let loc = p.mk_loc(&start_pos, &p.end_pos); + let loc = p.mk_loc_to_end(&start_pos); Some(Pattern { ppat_desc: PatternDesc::Ppat_tuple(vec![first]), ppat_loc: loc, @@ -704,7 +757,7 @@ fn parse_atomic_pattern(p: &mut Parser<'_>) -> Pattern { }; let suffix = suffix.clone(); p.next(); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); Pattern { ppat_desc: PatternDesc::Ppat_constant(Constant::Integer(value, suffix)), ppat_loc: loc, @@ -719,7 +772,7 @@ fn parse_atomic_pattern(p: &mut Parser<'_>) -> Pattern { }; let suffix = suffix.clone(); p.next(); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); Pattern { ppat_desc: PatternDesc::Ppat_constant(Constant::Float(value, suffix)), ppat_loc: loc, @@ -734,15 +787,23 @@ fn parse_atomic_pattern(p: &mut Parser<'_>) -> Pattern { } } } - _ => { - p.err(DiagnosticCategory::Message(format!( - "Unexpected token in pattern: {:?}", - p.token - ))); - // Advance to prevent infinite loops - p.next(); + Token::Eof => { + // EOF: just report error and return default (no skip_tokens_and_maybe_retry) + // OCaml: | Eof -> Parser.err ~start_pos:p.prev_end_pos p ...; Recover.default_pattern () + p.err_unexpected_at(p.prev_end_pos.clone()); recover::default_pattern() } + _ => { + // Other unexpected tokens: report error and try to skip/retry + // OCaml: | token -> Parser.err p ...; match skip_tokens_and_maybe_retry ... + p.err_unexpected(); + if recover::skip_tokens_and_maybe_retry(p, grammar::is_atomic_pattern_start) { + // Found a valid pattern start after skipping, retry parsing + parse_atomic_pattern(p) + } else { + recover::default_pattern() + } + } } } @@ -755,9 +816,20 @@ fn parse_lident(p: &mut Parser<'_>) -> String { name } _ => { - p.err(DiagnosticCategory::Message( - "Expected lowercase identifier".to_string(), - )); + // OCaml: parse_lident recovery - emit error, skip tokens, try to find an Lident + p.err(DiagnosticCategory::Lident(p.token.clone())); + if p.token.is_keyword() && p.prev_end_pos.line == p.start_pos.line { + p.next(); + } else { + p.next(); // skip the bad token + // Skip tokens until we find an Lident or should abort list parse + while !super::core::recover::should_abort_list_parse(p) && p.token != Token::Eof { + p.next(); + } + if matches!(p.token, Token::Lident(_)) { + return parse_lident(p); + } + } "_".to_string() } } @@ -789,8 +861,9 @@ fn parse_constructor_pattern(p: &mut Parser<'_>) -> Pattern { p.next(); } - let lid = super::core::build_longident(&path_parts); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let lid = super::core::build_longident(p.arena_mut(), &path_parts); + let lid_idx = p.push_longident(lid); + let loc = p.mk_loc_to_prev_end(&start_pos); // Check for constructor argument let arg = if p.token == Token::Lparen { @@ -801,9 +874,10 @@ fn parse_constructor_pattern(p: &mut Parser<'_>) -> Pattern { p.next(); // Empty parentheses - unit pattern // OCaml: unit pattern location starts at ( not at constructor name - let unit_loc = p.mk_loc(&lparen_pos, &p.prev_end_pos); + let unit_loc = p.mk_loc_to_prev_end(&lparen_pos); + let unit_lid_idx = p.push_lident_static("()"); Some(ast_helper::make_construct_pat( - Longident::Lident("()".to_string()), + unit_lid_idx, None, unit_loc.clone(), unit_loc, @@ -831,7 +905,7 @@ fn parse_constructor_pattern(p: &mut Parser<'_>) -> Pattern { // If the single argument is itself a tuple, wrap it if matches!(single.ppat_desc, PatternDesc::Ppat_tuple(_)) { // OCaml: wrapper tuple location extends to end of next token - let wrap_loc = p.mk_loc(&lparen_pos, &p.end_pos); + let wrap_loc = p.mk_loc_to_end(&lparen_pos); Some(Pattern { ppat_desc: PatternDesc::Ppat_tuple(vec![single]), ppat_loc: wrap_loc, @@ -842,7 +916,7 @@ fn parse_constructor_pattern(p: &mut Parser<'_>) -> Pattern { } } else { // OCaml uses p.end_pos (end of next token after `)`) for tuple location - let tuple_loc = p.mk_loc(&tuple_start, &p.end_pos); + let tuple_loc = p.mk_loc_to_end(&tuple_start); Some(Pattern { ppat_desc: PatternDesc::Ppat_tuple(patterns), ppat_loc: tuple_loc, @@ -856,7 +930,7 @@ fn parse_constructor_pattern(p: &mut Parser<'_>) -> Pattern { if matches!(first.ppat_desc, PatternDesc::Ppat_tuple(_)) { // OCaml: wrapper tuple location starts at outer ( and extends to end of next token // This means in `Some((a,b)) =>`, the wrapper tuple includes the ` =>` - let wrap_loc = p.mk_loc(&lparen_pos, &p.end_pos); + let wrap_loc = p.mk_loc_to_end(&lparen_pos); Some(Pattern { ppat_desc: PatternDesc::Ppat_tuple(vec![first]), ppat_loc: wrap_loc, @@ -872,12 +946,12 @@ fn parse_constructor_pattern(p: &mut Parser<'_>) -> Pattern { }; let full_loc = if arg.is_some() { - p.mk_loc(&start_pos, &p.prev_end_pos) + p.mk_loc_to_prev_end(&start_pos) } else { loc.clone() }; - ast_helper::make_construct_pat(lid, arg, loc, full_loc) + ast_helper::make_construct_pat(lid_idx, arg, loc, full_loc) } // ============================================================================ @@ -885,21 +959,58 @@ fn parse_constructor_pattern(p: &mut Parser<'_>) -> Pattern { // ============================================================================ /// Parse an array pattern [p1, p2, ...]. +/// Parse a pattern that does NOT allow spread (`...`). +/// If spread is encountered, emit the provided error message and skip over it, +/// then continue parsing the pattern normally. +/// This matches OCaml's `parse_non_spread_pattern`. +fn parse_non_spread_pattern(p: &mut Parser<'_>, error_msg: &str) -> Option { + // Check for spread and emit error if found + if p.token == Token::DotDotDot { + p.err(DiagnosticCategory::Message(error_msg.to_string())); + p.next(); // Skip past the ... + } + + // Now parse the pattern if we can + if super::grammar::is_pattern_start(&p.token) { + let pat = parse_pattern(p); + // Check for type constraint: pat : typ + if p.token == Token::Colon { + p.next(); + let typ = super::typ::parse_typ_expr(p); + let loc = p.mk_loc_spanning(pat.ppat_loc, typ.ptyp_loc); + Some(Pattern { + ppat_desc: PatternDesc::Ppat_constraint(Box::new(pat), typ), + ppat_loc: loc, + ppat_attributes: vec![], + }) + } else { + Some(pat) + } + } else { + None + } +} + fn parse_array_pattern(p: &mut Parser<'_>) -> Pattern { let start_pos = p.start_pos.clone(); p.expect(Token::Lbracket); let mut patterns = vec![]; while p.token != Token::Rbracket && p.token != Token::Eof { - // Use parse_constrained_pattern to support [1 : int, 2 : int] syntax - patterns.push(parse_constrained_pattern(p)); - if !p.optional(&Token::Comma) { + // Use parse_non_spread_pattern to disallow spread in array patterns + // and emit appropriate error message + if let Some(pat) = parse_non_spread_pattern(p, super::core::error_messages::ARRAY_PATTERN_SPREAD) { + patterns.push(pat); + if !p.optional(&Token::Comma) { + break; + } + } else { break; } } p.expect(Token::Rbracket); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); Pattern { ppat_desc: PatternDesc::Ppat_array(patterns), @@ -911,31 +1022,113 @@ fn parse_array_pattern(p: &mut Parser<'_>) -> Pattern { /// Parse a list pattern list{p1, p2, ...spread}. fn parse_list_pattern(p: &mut Parser<'_>, start_pos: crate::location::Position) -> Pattern { // Token::List already includes the opening '{' + // OCaml: uses parse_comma_delimited_reversed_list with parse_pattern_region + // which collects (has_spread, pattern) tuples, then validates spreads after. - let mut patterns = vec![]; - let mut spread = None; + // Collect items using OCaml's parse_pattern_region approach + let mut items: Vec<(bool, Pattern)> = vec![]; - while p.token != Token::Rbrace && p.token != Token::Eof { - if p.token == Token::DotDotDot { - // OCaml does NOT include ... in the spread pattern location + p.leave_breadcrumb(Grammar::PatternOcamlList); + loop { + // parse_pattern_region: check what token we have + let item = if p.token == Token::DotDotDot { p.next(); - let spread_pat = parse_constrained_pattern(p); - spread = Some(spread_pat); - // Allow trailing comma after spread: list{a, ...rest,} - p.optional(&Token::Comma); - break; - } - // Use parse_constrained_pattern to support (pat: type) inside list patterns - patterns.push(parse_constrained_pattern(p)); - if !p.optional(&Token::Comma) { - break; + Some((true, parse_constrained_pattern(p))) + } else if super::grammar::is_pattern_start(&p.token) { + Some((false, parse_constrained_pattern(p))) + } else { + None + }; + + match item { + Some(node) => { + if p.token == Token::Comma { + p.next(); + items.push(node); + } else if p.token == Token::Rbrace || p.token == Token::Eof { + items.push(node); + break; + } else if super::grammar::is_pattern_start(&p.token) || p.token == Token::DotDotDot { + // Missing comma - report and continue + p.expect(Token::Comma); + items.push(node); + } else { + items.push(node); + if !(p.token == Token::Eof || p.token == Token::Rbrace + || super::core::recover::should_abort_list_parse(p)) + { + p.expect(Token::Comma); + p.next(); + } + break; + } + } + None => { + if p.token == Token::Eof || p.token == Token::Rbrace + || super::core::recover::should_abort_list_parse(p) + { + break; + } else { + p.err(DiagnosticCategory::unexpected( + p.token.clone(), + p.breadcrumbs().to_vec(), + )); + p.next(); + } + } } } + p.eat_breadcrumb(); p.expect(Token::Rbrace); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); - - ast_helper::make_list_pattern(p, loc, patterns, spread) + let loc = p.mk_loc_to_prev_end(&start_pos); + + // OCaml: items collected in reverse order, first reversed item with spread = tail. + // We collected in forward order. Reverse to match OCaml's processing. + items.reverse(); + + match items.as_slice() { + [(true, _), ..] => { + let (_, spread_pat) = items.remove(0); + // Remaining items: report any that also have spread + let patterns: Vec = items + .into_iter() + .map(|(has_spread, pat)| { + if has_spread { + p.err_at( + p.loc_start(pat.ppat_loc), + p.end_pos.clone(), + DiagnosticCategory::Message( + super::core::error_messages::LIST_PATTERN_SPREAD.to_string(), + ), + ); + } + pat + }) + .rev() + .collect(); + ast_helper::make_list_pattern(p, loc, patterns, Some(spread_pat)) + } + _ => { + let patterns: Vec = items + .into_iter() + .map(|(has_spread, pat)| { + if has_spread { + p.err_at( + p.loc_start(pat.ppat_loc), + p.end_pos.clone(), + DiagnosticCategory::Message( + super::core::error_messages::LIST_PATTERN_SPREAD.to_string(), + ), + ); + } + pat + }) + .rev() + .collect(); + ast_helper::make_list_pattern(p, loc, patterns, None) + } + } } /// Parse a record pattern {field: pat, ...}. @@ -943,18 +1136,29 @@ fn parse_record_pattern(p: &mut Parser<'_>) -> Pattern { let start_pos = p.start_pos.clone(); p.expect(Token::Lbrace); - let mut fields = vec![]; + // OCaml: collects (has_spread, PatField|PatUnderscore) tuples via + // parse_comma_delimited_reversed_list, then validates spreads after parsing. + let mut raw_fields: Vec<(bool, Option)> = vec![]; let mut closed = ClosedFlag::Closed; while p.token != Token::Rbrace && p.token != Token::Eof { if p.token == Token::Underscore { p.next(); - closed = ClosedFlag::Open; + raw_fields.push((false, None)); // PatUnderscore // Allow trailing comma after underscore: {a, _,} p.optional(&Token::Comma); - break; + continue; } + // Check for spread pattern - OCaml: DotDotDot case in parse_record_pattern_row + // Parse as a regular field with has_spread=true, validate after + let has_spread = if p.token == Token::DotDotDot { + p.next(); + true + } else { + false + }; + let field_start = p.start_pos.clone(); // Check for optional field punning: { ? name, ... } @@ -968,6 +1172,7 @@ fn parse_record_pattern(p: &mut Parser<'_>) -> Pattern { // Support qualified record labels in patterns: {Module.label: pat} // (also needed for ambiguity disambiguation, mirroring OCaml syntax). + // OCaml: Lident/Uident case in parse_record_pattern_row let mut parts: Vec = vec![]; loop { match &p.token { @@ -975,10 +1180,6 @@ fn parse_record_pattern(p: &mut Parser<'_>) -> Pattern { parts.push(name.clone()); p.next(); } - _ if p.token.is_keyword() => { - parts.push(p.token.to_string()); - p.next(); - } _ => break, } if p.token == Token::Dot { @@ -988,14 +1189,44 @@ fn parse_record_pattern(p: &mut Parser<'_>) -> Pattern { } } + // If parts is empty, check for keyword field + // OCaml: Token.is_keyword p.token case in parse_record_pattern_row if parts.is_empty() { + if p.token.is_keyword() { + // Try to recover keyword as field name if followed by colon + if let Some((recovered_name, loc)) = super::core::recover_keyword_field_name_if_probably_field( + p, + super::core::error_messages::keyword_field_in_pattern, + ) { + // OCaml: Parser.expect Colon p + p.expect(Token::Colon); + // Check for optional marker after colon: name: ? pat + let opt = p.token == Token::Question; + if opt { + p.next(); + } + let pat = parse_pattern(p); + let lid_idx = p.push_lident(&recovered_name); + let lid = with_loc(lid_idx, loc); + raw_fields.push((false, Some(PatternRecordField { lid, pat, opt }))); + if !p.optional(&Token::Comma) { + break; + } + continue; + } else { + // Just emit the error and break + super::core::emit_keyword_field_error(p, super::core::error_messages::keyword_field_in_pattern); + break; + } + } break; } // Capture the end of the longident before parsing colon and pattern let lid_end_pos = p.prev_end_pos.clone(); - let lid_unloc = super::core::build_longident(&parts); + let lid_unloc = super::core::build_longident(p.arena_mut(), &parts); + let lid_idx = p.push_longident(lid_unloc); let pun_name = parts.last().cloned().unwrap_or("_".to_string()); let (lid, pat, opt) = if p.token == Token::Colon { @@ -1009,22 +1240,40 @@ fn parse_record_pattern(p: &mut Parser<'_>) -> Pattern { let pat = parse_pattern(p); // Longident location only covers the field name, not the pattern let lid_loc = p.mk_loc(&field_start, &lid_end_pos); - (with_loc(lid_unloc, lid_loc), pat, opt) + (with_loc(lid_idx, lid_loc), pat, opt) + } else if p.token == Token::Equal { + // OCaml: Token.Equal case in parse_record_pattern_row + // {field=value} instead of {field: value} + p.err_at( + p.start_pos.clone(), + p.end_pos.clone(), + DiagnosticCategory::message( + "Record patterns use `:` when matching fields. Example: `{field: value}`", + ), + ); + p.next(); // consume = + let opt = p.token == Token::Question; + if opt { + p.next(); + } + let pat = parse_pattern(p); + let lid_loc = p.mk_loc(&field_start, &lid_end_pos); + (with_loc(lid_idx, lid_loc), pat, opt) } else if p.token == Token::Question { // field? (optional punning after field name - less common) p.next(); - let loc = p.mk_loc(&field_start, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&field_start); let pat = ast_helper::make_var_pat(pun_name, loc.clone()); - (with_loc(lid_unloc, loc), pat, true) + (with_loc(lid_idx, loc), pat, true) } else { // Punning: field is same as variable (use last identifier in the path) // For optional punned fields, the pattern location is just the identifier (using pat_start) - let loc = p.mk_loc(&pat_start, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&pat_start); let pat = ast_helper::make_var_pat(pun_name, loc.clone()); - (with_loc(lid_unloc, loc), pat, opt_punning) + (with_loc(lid_idx, loc), pat, opt_punning) }; - fields.push(PatternRecordField { lid, pat, opt }); + raw_fields.push((has_spread, Some(PatternRecordField { lid, pat, opt }))); if !p.optional(&Token::Comma) { break; @@ -1032,7 +1281,45 @@ fn parse_record_pattern(p: &mut Parser<'_>) -> Pattern { } p.expect(Token::Rbrace); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); + + // OCaml: process raw_fields in reverse order. + // Last PatUnderscore becomes Open flag, spread fields emit errors. + // Reverse to match OCaml's reversed list processing. + raw_fields.reverse(); + + // Check if first (last parsed) item is Underscore + if let Some((false, None)) = raw_fields.first() { + closed = ClosedFlag::Open; + raw_fields.remove(0); + } + + // Process fields in reversed order (matching OCaml's fold_left on reversed list). + // Prepend each field to build the correct forward order. + // This ensures the LAST spread field's error is emitted first (region silencing). + let mut fields = vec![]; + for (has_spread, field_opt) in raw_fields.into_iter() { + match field_opt { + Some(field) => { + if has_spread { + // OCaml: Parser.err ~start_pos:pattern.ppat_loc.loc_start p + // end_pos defaults to p.end_pos (current token end) + p.err_at( + p.loc_start(field.pat.ppat_loc), + p.end_pos.clone(), + DiagnosticCategory::Message( + super::core::error_messages::RECORD_PATTERN_SPREAD.to_string(), + ), + ); + } + // OCaml: field :: fields (prepend to maintain correct order) + fields.insert(0, field); + } + None => { + // PatUnderscore in middle - just skip (OCaml: (fields, flag)) + } + } + } Pattern { ppat_desc: PatternDesc::Ppat_record(fields, closed), @@ -1051,7 +1338,8 @@ fn parse_dict_pattern(p: &mut Parser<'_>, start_pos: crate::location::Position) Token::String(key) => { let key = key.clone(); // OCaml: let loc = mk_loc p.start_pos p.end_pos - captures key location BEFORE consuming - let key_loc = p.mk_loc(&p.start_pos, &p.end_pos); + let key_loc = p.mk_loc_current(); + let lid_idx = p.push_lident(&key); p.next(); p.expect(Token::Colon); @@ -1062,7 +1350,7 @@ fn parse_dict_pattern(p: &mut Parser<'_>, start_pos: crate::location::Position) let pat = parse_pattern(p); // OCaml: Location.mkloc (Longident.Lident s) loc - uses key location, not whole field fields.push(PatternRecordField { - lid: with_loc(Longident::Lident(key), key_loc), + lid: with_loc(lid_idx, key_loc), pat, opt, }); @@ -1081,7 +1369,7 @@ fn parse_dict_pattern(p: &mut Parser<'_>, start_pos: crate::location::Position) } p.expect(Token::Rbrace); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); // OCaml: adds (Location.mknoloc "res.dictPattern", PStr []) attribute // Dict patterns are parsed as open record patterns with the dictPattern attribute @@ -1125,7 +1413,7 @@ fn parse_extension_pattern(p: &mut Parser<'_>, start_pos: crate::location::Posit )); mknoloc("error".to_string()) } else { - with_loc(parts.join("."), p.mk_loc(&id_start, &p.prev_end_pos)) + with_loc(parts.join("."), p.mk_loc_to_prev_end(&id_start)) }; let payload = if p.token == Token::Lparen { @@ -1137,7 +1425,7 @@ fn parse_extension_pattern(p: &mut Parser<'_>, start_pos: crate::location::Posit Payload::PStr(vec![]) }; - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); Pattern { ppat_desc: PatternDesc::Ppat_extension((id, payload)), @@ -1154,46 +1442,40 @@ fn parse_template_literal_pattern(p: &mut Parser<'_>, start_pos: crate::location p.next_template_literal_token(); } - loop { - match &p.token { - Token::TemplatePart { text: chunk, .. } => { - text.push_str(chunk); - p.next(); - // Consume interpolation expression. - let _ = super::expr::parse_expr(p); - p.next_template_literal_token(); - } - Token::TemplateTail { text: chunk, .. } => { - text.push_str(chunk); - p.next(); - break; - } - Token::Backtick => { - // Empty template string - p.next(); - break; - } - Token::Eof => { - p.err(DiagnosticCategory::Message( - "Unterminated template literal".to_string(), - )); - break; - } - _ => { - p.err(DiagnosticCategory::Message(format!( - "Unexpected token in template literal pattern: {:?}", - p.token - ))); + // Check if this is a simple template (no interpolation) + let delimiter = if let Token::TemplateTail { text: chunk, .. } = &p.token { + text.push_str(chunk); + p.next(); + Some("js".to_string()) + } else { + // Has interpolation - skip all tokens and report error at original start_pos + // OCaml: Parser.err ~start_pos ~end_pos:p.prev_end_pos p (message ...) + fn skip_tokens(p: &mut Parser<'_>) { + if p.token != Token::Eof { p.next(); - break; + if p.token == Token::Backtick { + p.next(); + } else { + skip_tokens(p); + } } } - } + skip_tokens(p); + p.err_at( + start_pos.clone(), + p.prev_end_pos.clone(), + DiagnosticCategory::Message( + super::core::error_messages::STRING_INTERPOLATION_IN_PATTERN.to_string(), + ), + ); + // OCaml returns Pconst_string ("", None) in error case + None + }; - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); Pattern { - ppat_desc: PatternDesc::Ppat_constant(Constant::String(text, Some("js".to_string()))), + ppat_desc: PatternDesc::Ppat_constant(Constant::String(text, delimiter)), ppat_loc: loc, ppat_attributes: vec![template_literal_attr()], } @@ -1215,8 +1497,8 @@ fn parse_poly_variant_pattern(p: &mut Parser<'_>) -> Pattern { // Track start position of the type path for location let type_start = p.start_pos.clone(); let lid = parse_type_longident(p); - let lid_loc = p.mk_loc(&type_start, &p.prev_end_pos); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let lid_loc = p.mk_loc_to_prev_end(&type_start); + let loc = p.mk_loc_to_prev_end(&start_pos); return Pattern { ppat_desc: PatternDesc::Ppat_type(with_loc(lid, lid_loc)), ppat_loc: loc, @@ -1230,8 +1512,17 @@ fn parse_poly_variant_pattern(p: &mut Parser<'_>) -> Pattern { p.next(); name } - Token::Int { i, .. } => { + Token::Int { i, suffix } => { + // Clone values before borrowing p mutably let tag = i.clone(); + let has_suffix = suffix.is_some(); + // OCaml: emit error if numeric poly variant has a suffix + if has_suffix { + p.err(DiagnosticCategory::Message(format!( + "A numeric polymorphic variant cannot be followed by a letter. Did you mean `#{}`?", + tag + ))); + } p.next(); tag } @@ -1256,10 +1547,11 @@ fn parse_poly_variant_pattern(p: &mut Parser<'_>) -> Pattern { // Empty: #tag() // OCaml creates the unit pattern location BEFORE consuming `)`, // so the location only covers the `(` character. - let unit_loc = p.mk_loc(&tuple_start, &p.prev_end_pos); + let unit_loc = p.mk_loc_to_prev_end(&tuple_start); p.next(); + let unit_lid_idx = p.push_lident_static("()"); Some(Box::new(ast_helper::make_construct_pat( - Longident::Lident("()".to_string()), + unit_lid_idx, None, unit_loc.clone(), unit_loc, @@ -1277,12 +1569,17 @@ fn parse_poly_variant_pattern(p: &mut Parser<'_>) -> Pattern { patterns.push(parse_constrained_pattern(p)); } p.expect(Token::Rparen); - let tuple_loc = p.mk_loc(&tuple_start, &p.prev_end_pos); - Some(Box::new(Pattern { - ppat_desc: PatternDesc::Ppat_tuple(patterns), - ppat_loc: tuple_loc, - ppat_attributes: vec![], - })) + // Trailing comma with single element: #tag(a,) -> just the pattern, not a tuple + if patterns.len() == 1 { + Some(Box::new(patterns.into_iter().next().unwrap())) + } else { + let tuple_loc = p.mk_loc_to_prev_end(&tuple_start); + Some(Box::new(Pattern { + ppat_desc: PatternDesc::Ppat_tuple(patterns), + ppat_loc: tuple_loc, + ppat_attributes: vec![], + })) + } } else { p.expect(Token::Rparen); Some(Box::new(first)) @@ -1292,7 +1589,7 @@ fn parse_poly_variant_pattern(p: &mut Parser<'_>) -> Pattern { None }; - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); Pattern { ppat_desc: PatternDesc::Ppat_variant(tag, arg), diff --git a/compiler-rust/src/parser/printer.rs b/compiler-rust/src/parser/printer.rs deleted file mode 100644 index 055ed3bd915..00000000000 --- a/compiler-rust/src/parser/printer.rs +++ /dev/null @@ -1,4664 +0,0 @@ -//! ReScript AST printer. -//! -//! This module converts the AST back to ReScript source code. -//! It's used for formatting and roundtrip testing. - -use super::ast::*; -use super::comment::{Comment, CommentStyle}; -use super::doc::Doc; -use super::longident::Longident; -use super::token::Token; -use crate::location::Location; - -/// Printer state for formatting output. -pub struct Printer { - /// Output buffer. - output: String, - /// Current indentation level. - indent: usize, - /// Indentation string (spaces). - indent_str: &'static str, - /// Maximum line width for formatting decisions. - max_width: usize, - /// Current line length (approximate, in bytes). - line_len: usize, - /// Optional comment stream for preserving comments. - comments: Option, -} - -#[derive(Debug, Clone)] -struct CommentCursor { - comments: Vec, - index: usize, -} - -impl CommentCursor { - fn new(comments: Vec) -> Self { - Self { comments, index: 0 } - } - - fn peek(&self) -> Option<&Comment> { - self.comments.get(self.index) - } - - fn advance(&mut self) { - if self.index < self.comments.len() { - self.index += 1; - } - } -} - -impl Default for Printer { - fn default() -> Self { - Self::new() - } -} - -impl Printer { - /// Create a new printer. - pub fn new() -> Self { - Printer { - output: String::new(), - indent: 0, - indent_str: " ", - max_width: 100, - line_len: 0, - comments: None, - } - } - - /// Create a new printer with a custom line width. - pub fn with_width(max_width: usize) -> Self { - Printer { - max_width, - ..Self::new() - } - } - - /// Create a new printer with comments. - pub fn with_comments(comments: Vec) -> Self { - Printer { - comments: Some(CommentCursor::new(comments)), - ..Self::new() - } - } - - /// Create a new printer with comments and a custom line width. - pub fn with_comments_and_width(comments: Vec, max_width: usize) -> Self { - Printer { - max_width, - comments: Some(CommentCursor::new(comments)), - ..Self::new() - } - } - - /// Get the printed output. - pub fn output(&self) -> &str { - &self.output - } - - /// Consume the printer and return the output. - pub fn into_output(self) -> String { - self.output - } - - /// Write a string to the output. - fn write(&mut self, s: &str) { - self.output.push_str(s); - if let Some(idx) = s.rfind('\n') { - let after = &s[idx + 1..]; - self.line_len = after.len(); - } else { - self.line_len += s.len(); - } - } - - /// Classify an identifier to determine how it should be printed. - /// This matches OCaml's classify_ident_content function. - /// - /// - `allow_uident`: If true, uppercase letters are allowed at the start (for module/type names). - /// - `allow_hyphen`: If true, hyphens are allowed in the identifier (for JSX tag names). - /// - /// Returns true if the identifier needs escaping. - fn needs_escaping(s: &str, allow_uident: bool, allow_hyphen: bool) -> bool { - // Keywords always need escaping (except true/false which are boolean literals) - if Token::is_keyword_txt(s) && s != "true" && s != "false" { - return true; - } - - if s.is_empty() { - return true; - } - - let bytes = s.as_bytes(); - - // Check first character - match bytes[0] { - // Backslash means it's already an escaped/uppercase exotic identifier - b'\\' => return false, - // Uppercase allowed only if allow_uident is true - b'A'..=b'Z' => { - if !allow_uident { - return true; - } - } - // Lowercase and underscore always allowed - b'a'..=b'z' | b'_' => {} - // Anything else needs escaping - _ => return true, - } - - // Check subsequent characters - for &b in &bytes[1..] { - match b { - b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'\'' | b'_' => {} - b'-' if allow_hyphen => {} - _ => return true, - } - } - - false - } - - /// Write an identifier, escaping it if it's a keyword or exotic. - /// Keywords like "switch" need to be written as \"switch" in ReScript. - /// Exotic identifiers like "=" also need escaping: \"=" - /// - /// By default, identifiers starting with uppercase letters need escaping. - /// Use `write_ident_allow_uident` for contexts where uppercase is allowed (module names, etc.). - fn write_ident(&mut self, s: &str) { - self.write_ident_with_options(s, false, false); - } - - /// Write an identifier allowing uppercase first characters (for module names, type constructors, etc.) - fn write_ident_allow_uident(&mut self, s: &str) { - self.write_ident_with_options(s, true, false); - } - - /// Write an identifier with configurable escaping rules. - fn write_ident_with_options(&mut self, s: &str, allow_uident: bool, allow_hyphen: bool) { - if Self::needs_escaping(s, allow_uident, allow_hyphen) { - self.write("\\\""); - self.write(s); - self.write("\""); - } else { - self.write(s); - } - } - - /// Write a type variable name with proper escaping. - /// Type variables allow uppercase letters (e.g., 'T, 'Element). - fn write_type_var(&mut self, s: &str) { - // Type variables allow uppercase, so use allow_uident=true - if Self::needs_escaping(s, true, false) { - self.write("\\\""); - self.write(s); - self.write("\""); - } else { - self.write(s); - } - } - - /// Write a newline and indentation. - fn newline(&mut self) { - self.output.push('\n'); - self.line_len = 0; - for _ in 0..self.indent { - self.output.push_str(self.indent_str); - self.line_len += self.indent_str.len(); - } - } - - /// Increase indentation. - fn indent(&mut self) { - self.indent += 1; - } - - /// Decrease indentation. - fn dedent(&mut self) { - if self.indent > 0 { - self.indent -= 1; - } - } - - /// Write a space. - fn space(&mut self) { - self.write(" "); - } - - /// Render a Doc and write it to the output buffer. - /// The Doc's line breaks will be resolved based on max_width. - fn write_doc(&mut self, doc: Doc) { - let rendered = doc.to_string(self.max_width as i32); - // Add current indentation to each line - for (i, line) in rendered.lines().enumerate() { - if i > 0 { - self.output.push('\n'); - for _ in 0..self.indent { - self.output.push_str(self.indent_str); - } - } - self.output.push_str(line); - } - // Update line_len based on last line - if let Some(last_newline) = self.output.rfind('\n') { - self.line_len = self.output.len() - last_newline - 1; - } else { - self.line_len = self.output.len(); - } - } - - /// Convert an expression to a string using a fresh printer. - fn expr_to_string(&self, expr: &Expression) -> String { - let mut p = Printer::with_width(self.max_width); - p.print_expression(expr); - p.into_output() - } - - /// Print a list expression using Doc for proper line breaking. - fn print_list_with_doc(&mut self, elems: &[&Expression], spread: Option<&Expression>) { - if elems.is_empty() && spread.is_none() { - self.write("list{}"); - return; - } - - // Collect element locations for consuming comments later - let mut elem_locations: Vec = Vec::new(); - let mut all_docs: Vec<(Doc, String)> = Vec::new(); - - for elem in elems { - let elem_str = self.expr_to_string(elem); - let trailing_comment = self.get_trailing_comments_text(&elem.pexp_loc); - elem_locations.push(elem.pexp_loc.clone()); - all_docs.push((Doc::text(elem_str), trailing_comment)); - } - - if let Some(spread_expr) = spread { - let spread_str = format!("...{}", self.expr_to_string(spread_expr)); - let trailing_comment = self.get_trailing_comments_text(&spread_expr.pexp_loc); - elem_locations.push(spread_expr.pexp_loc.clone()); - all_docs.push((Doc::text(spread_str), trailing_comment)); - } - - // Build doc with separators, using line_suffix for trailing comments - let docs_with_sep: Vec<(Doc, Doc)> = all_docs - .into_iter() - .map(|(elem_doc, comment)| { - let elem_with_comment = if comment.is_empty() { - elem_doc - } else { - Doc::concat(vec![ - elem_doc, - Doc::line_suffix(Doc::text(comment)), - ]) - }; - (elem_with_comment, Doc::concat(vec![Doc::text(","), Doc::line()])) - }) - .collect(); - - let doc = Doc::group(Doc::concat(vec![ - Doc::text("list{"), - Doc::indent(Doc::concat(vec![ - Doc::soft_line(), - Doc::join_with_sep(docs_with_sep), - Doc::trailing_comma(), - ])), - Doc::soft_line(), - Doc::text("}"), - ])); - - self.write_doc(doc); - - // Consume the comments that were included - for loc in &elem_locations { - self.consume_trailing_comments_for_loc(loc); - } - } - - /// Print an array expression using Doc for proper line breaking. - fn print_array_with_doc(&mut self, elems: &[Expression]) { - if elems.is_empty() { - self.write("[]"); - return; - } - - // Collect element locations for consuming comments later - let mut elem_locations: Vec = Vec::new(); - let mut all_docs: Vec<(Doc, String)> = Vec::new(); - - for elem in elems { - let elem_str = self.expr_to_string(elem); - let trailing_comment = self.get_trailing_comments_text(&elem.pexp_loc); - elem_locations.push(elem.pexp_loc.clone()); - all_docs.push((Doc::text(elem_str), trailing_comment)); - } - - // Build doc with separators, using line_suffix for trailing comments - let docs_with_sep: Vec<(Doc, Doc)> = all_docs - .into_iter() - .map(|(elem_doc, comment)| { - let elem_with_comment = if comment.is_empty() { - elem_doc - } else { - Doc::concat(vec![ - elem_doc, - Doc::line_suffix(Doc::text(comment)), - ]) - }; - (elem_with_comment, Doc::concat(vec![Doc::text(","), Doc::line()])) - }) - .collect(); - - let doc = Doc::group(Doc::concat(vec![ - Doc::text("["), - Doc::indent(Doc::concat(vec![ - Doc::soft_line(), - Doc::join_with_sep(docs_with_sep), - Doc::trailing_comma(), - ])), - Doc::soft_line(), - Doc::text("]"), - ])); - - self.write_doc(doc); - - // Consume the comments that were included - for loc in &elem_locations { - self.consume_trailing_comments_for_loc(loc); - } - } - - /// Print a record expression field to string (for Doc formatting). - fn record_field_to_string(&self, field: &ExpressionRecordField) -> String { - // Check for punning: if field name equals expression variable name - if let ExpressionDesc::Pexp_ident(path) = &field.expr.pexp_desc { - if let Longident::Lident(name) = &path.txt { - if let Longident::Lident(field_name) = &field.lid.txt { - if name == field_name && !field.opt { - // Punned field - just the name (with escaping) - return self.ident_to_string(name); - } - } - } - } - - let mut result = String::new(); - - // Field name (with escaping for keywords/exotic idents) - result.push_str(&self.lident_to_string(&field.lid.txt)); - result.push_str(": "); - - // Optional marker - if field.opt { - result.push_str("? "); - } - - // Expression - result.push_str(&self.expr_to_string(&field.expr)); - - result - } - - /// Convert a longident to string. - fn longident_to_string(&self, lid: &Longident) -> String { - match lid { - Longident::Lident(name) => name.clone(), - Longident::Ldot(prefix, name) => { - format!("{}.{}", self.longident_to_string(prefix), name) - } - Longident::Lapply(a, b) => { - format!("{}({})", self.longident_to_string(a), self.longident_to_string(b)) - } - } - } - - /// Convert a longident to string, escaping the final segment if needed. - fn lident_to_string(&self, lid: &Longident) -> String { - match lid { - Longident::Lident(name) => self.ident_to_string(name), - Longident::Ldot(prefix, name) => { - format!("{}.{}", self.longident_to_string(prefix), self.ident_to_string(name)) - } - Longident::Lapply(_, _) => { - "printLident: Longident.Lapply is not supported".to_string() - } - } - } - - /// Convert an identifier to string, escaping if needed. - fn ident_to_string(&self, name: &str) -> String { - if Self::needs_escaping(name, false, false) { - format!("\\\"{}\"", name) - } else { - name.to_string() - } - } - - /// Print a record expression using Doc for proper line breaking. - fn print_record_with_doc( - &mut self, - fields: &[ExpressionRecordField], - spread: Option<&Expression>, - loc: &Location, - ) { - if fields.is_empty() && spread.is_none() { - self.write("{}"); - return; - } - - // Check if record spans multiple lines (to force break) - let force_break = if let Some(first_field) = fields.first() { - loc.loc_start.line < first_field.lid.loc.loc_start.line - } else if let Some(spread_expr) = spread { - loc.loc_start.line < spread_expr.pexp_loc.loc_start.line - } else { - false - }; - - // Also check if the record was originally multiline by checking if any field is on different line - let multiline = force_break || fields.windows(2).any(|w| { - w[0].expr.pexp_loc.loc_end.line < w[1].lid.loc.loc_start.line - }); - - let mut all_docs: Vec<(Doc, String)> = Vec::new(); - - // Add spread if present - if let Some(spread_expr) = spread { - all_docs.push(( - Doc::concat(vec![ - Doc::text("..."), - Doc::text(self.expr_to_string(spread_expr)), - ]), - String::new(), // No trailing comment for spread - )); - } - - // Disallow punning for single-element records (unless there's a spread) - let punning_allowed = spread.is_some() || fields.len() > 1; - - // Collect field locations for later consuming comments - let mut field_locations: Vec = Vec::new(); - - for field in fields { - // Create combined location for this field (from name to expression end) - let field_loc = Location { - loc_start: field.lid.loc.loc_start.clone(), - loc_end: field.expr.pexp_loc.loc_end.clone(), - loc_ghost: false, - id: field.lid.loc.id, - }; - - let field_str = if punning_allowed { - self.record_field_to_string(field) - } else { - // Single field without spread - no punning - let mut result = self.lident_to_string(&field.lid.txt); - result.push_str(": "); - if field.opt { - result.push_str("?"); - } - result.push_str(&self.expr_to_string(&field.expr)); - result - }; - - // Get trailing comments for this field - let trailing_comment = self.get_trailing_comments_text(&field_loc); - - field_locations.push(field_loc); - all_docs.push((Doc::text(field_str), trailing_comment)); - } - - // Build doc with separators - // Use line_suffix for trailing comments so they appear AFTER the comma - let docs_with_sep: Vec<(Doc, Doc)> = all_docs - .into_iter() - .map(|(field_doc, comment)| { - // Field doc with optional line suffix for trailing comment - let field_with_comment = if comment.is_empty() { - field_doc - } else { - // Use line_suffix so comment prints AFTER the comma - Doc::concat(vec![ - field_doc, - Doc::line_suffix(Doc::text(comment)), - ]) - }; - - // Standard separator: comma + line break - let sep = Doc::concat(vec![Doc::text(","), Doc::line()]); - - (field_with_comment, sep) - }) - .collect(); - - let inner = Doc::concat(vec![ - Doc::soft_line(), - Doc::join_with_sep(docs_with_sep), - Doc::trailing_comma(), - ]); - - let doc = Doc::breakable_group( - Doc::concat(vec![ - Doc::text("{"), - Doc::indent(inner), - Doc::soft_line(), - Doc::text("}"), - ]), - multiline || force_break, - ); - - self.write_doc(doc); - - // Consume the comments that were included in the doc - for field_loc in &field_locations { - self.consume_trailing_comments_for_loc(field_loc); - } - } - - /// Check if we're at the start of a line. - fn at_line_start(&self) -> bool { - self.output.is_empty() || self.output.ends_with('\n') - } - - /// Ensure indentation is written if we're at the start of a line. - fn write_indent_if_line_start(&mut self) { - if self.at_line_start() { - for _ in 0..self.indent { - self.output.push_str(self.indent_str); - self.line_len += self.indent_str.len(); - } - } - } - - fn comments_enabled(&self) -> bool { - self.comments.is_some() - } - - fn comment_before_loc(comment: &Comment, loc: &Location) -> bool { - comment.loc.loc_start.cnum <= loc.loc_start.cnum - } - - fn is_trailing_comment_for_loc(comment: &Comment, loc: &Location) -> bool { - let start = &comment.loc.loc_start; - let end = &loc.loc_end; - start.line == end.line && start.cnum >= end.cnum && comment.prev_tok_end_pos.cnum >= end.cnum - } - - /// Get trailing comments for a location without consuming them. - /// Returns them as formatted text. - fn get_trailing_comments_text(&self, loc: &Location) -> String { - let Some(cursor) = &self.comments else { - return String::new(); - }; - - let mut result = String::new(); - let mut temp_cursor = cursor.clone(); - - // Skip comments that come before the location's end line - while let Some(comment) = temp_cursor.peek() { - if comment.loc.loc_start.line < loc.loc_end.line { - temp_cursor.advance(); - } else { - break; - } - } - - while let Some(comment) = temp_cursor.peek() { - if Self::is_trailing_comment_for_loc(comment, loc) { - result.push(' '); - match comment.style { - CommentStyle::SingleLine => { - result.push_str("//"); - result.push_str(comment.txt()); - } - CommentStyle::MultiLine => { - result.push_str("/*"); - result.push_str(comment.txt()); - result.push_str("*/"); - } - CommentStyle::DocComment => { - result.push_str("/**"); - result.push_str(comment.txt()); - result.push_str("*/"); - } - CommentStyle::ModuleComment => { - result.push_str("/***"); - result.push_str(comment.txt()); - result.push_str("*/"); - } - } - temp_cursor.advance(); - } else { - break; - } - } - - result - } - - /// Consume trailing comments for a location from the cursor. - fn consume_trailing_comments_for_loc(&mut self, loc: &Location) { - let Some(mut cursor) = self.comments.take() else { - return; - }; - while let Some(comment) = cursor.peek() { - if Self::is_trailing_comment_for_loc(comment, loc) { - cursor.advance(); - } else { - break; - } - } - self.comments = Some(cursor); - } - - fn print_comment_text(&mut self, comment: &Comment) { - match comment.style { - CommentStyle::SingleLine => { - self.write("//"); - self.write(comment.txt()); - } - CommentStyle::MultiLine => { - self.write("/*"); - self.write(comment.txt()); - self.write("*/"); - } - CommentStyle::DocComment => { - self.write("/**"); - self.write(comment.txt()); - self.write("*/"); - } - CommentStyle::ModuleComment => { - self.write("/***"); - self.write(comment.txt()); - self.write("*/"); - } - } - } - - fn print_comment_leading(&mut self, comment: &Comment) { - let inline = comment.loc.loc_start.line == comment.prev_tok_end_pos.line; - if inline { - if !self.at_line_start() && !self.output.ends_with(' ') { - self.space(); - } - self.print_comment_text(comment); - if comment.is_single_line() { - self.newline(); - } else if !self.output.ends_with(' ') { - self.space(); - } - } else { - if !self.at_line_start() { - self.newline(); - } - self.write_indent_if_line_start(); - self.print_comment_text(comment); - self.newline(); - } - } - - fn print_comment_trailing(&mut self, comment: &Comment) { - if !self.at_line_start() && !self.output.ends_with(' ') { - self.space(); - } - self.print_comment_text(comment); - if comment.is_single_line() { - self.newline(); - } else if !self.output.ends_with(' ') { - self.space(); - } - } - - fn print_comments_before_loc(&mut self, loc: &Location) { - let Some(mut cursor) = self.comments.take() else { - return; - }; - while let Some(comment) = cursor.peek() { - if Self::comment_before_loc(comment, loc) { - self.print_comment_leading(comment); - cursor.advance(); - } else { - break; - } - } - self.comments = Some(cursor); - } - - fn print_comments_before_loc_end(&mut self, loc: &Location) { - let Some(mut cursor) = self.comments.take() else { - return; - }; - while let Some(comment) = cursor.peek() { - if comment.loc.loc_start.cnum <= loc.loc_end.cnum { - self.print_comment_leading(comment); - cursor.advance(); - } else { - break; - } - } - self.comments = Some(cursor); - } - - fn has_comment_before_loc_end(&self, loc: &Location) -> bool { - self.comments - .as_ref() - .and_then(|cursor| cursor.peek()) - .map_or(false, |comment| comment.loc.loc_start.cnum <= loc.loc_end.cnum) - } - - fn print_trailing_comments_for_loc(&mut self, loc: &Location) { - let Some(mut cursor) = self.comments.take() else { - return; - }; - while let Some(comment) = cursor.peek() { - if Self::is_trailing_comment_for_loc(comment, loc) { - self.print_comment_trailing(comment); - cursor.advance(); - } else { - break; - } - } - self.comments = Some(cursor); - } - - fn flush_remaining_comments(&mut self) { - let Some(mut cursor) = self.comments.take() else { - return; - }; - while let Some(comment) = cursor.peek() { - self.print_comment_leading(comment); - cursor.advance(); - } - self.comments = Some(cursor); - } - - /// Check if an expression is a block-like form (let, letmodule, letexception, open, sequence) - /// that shouldn't get extra braces when inside another block. - fn is_block_body_expr(expr: &Expression) -> bool { - matches!( - &expr.pexp_desc, - ExpressionDesc::Pexp_let(..) - | ExpressionDesc::Pexp_letmodule(..) - | ExpressionDesc::Pexp_letexception(..) - | ExpressionDesc::Pexp_open(..) - | ExpressionDesc::Pexp_sequence(..) - ) - } - - /// Collect list expressions from a cons chain (`::`) into a vector of expressions - /// and an optional spread expression. - /// - /// For `list{a, b, c}` represented as `a :: b :: c :: []`, returns `([a, b, c], None)`. - /// For `list{a, b, ...rest}` represented as `a :: b :: rest`, returns `([a, b], Some(rest))`. - fn collect_list_expressions(expr: &Expression) -> (Vec<&Expression>, Option<&Expression>) { - let mut acc = Vec::new(); - let mut current = expr; - - loop { - match ¤t.pexp_desc { - // Empty list `[]` - end of list, no spread - ExpressionDesc::Pexp_construct(lid, _) - if matches!(&lid.txt, Longident::Lident(s) if s == "[]") => - { - return (acc, None); - } - // Cons cell `::` with tuple argument (head, tail) - ExpressionDesc::Pexp_construct(lid, Some(arg)) - if matches!(&lid.txt, Longident::Lident(s) if s == "::") => - { - if let ExpressionDesc::Pexp_tuple(elems) = &arg.pexp_desc { - if elems.len() == 2 { - acc.push(&elems[0]); - current = &elems[1]; - continue; - } - } - // Malformed cons - treat as spread - return (acc, Some(current)); - } - // Not a list constructor - this is a spread - _ => { - return (acc, Some(current)); - } - } - } - } - - /// Collect list patterns from a cons chain (`::`) into a vector of patterns - /// and a tail pattern. - /// - /// For `list{a, b, c}` represented as `a :: b :: c :: []`, returns `([a, b, c], [])`. - /// For `list{a, b, ...rest}` represented as `a :: b :: rest`, returns `([a, b], rest)`. - fn collect_list_patterns(pat: &Pattern) -> (Vec<&Pattern>, &Pattern) { - let mut acc = Vec::new(); - let mut current = pat; - - loop { - match ¤t.ppat_desc { - // Cons cell `::` with tuple argument (head, tail) - PatternDesc::Ppat_construct(lid, Some(arg)) - if matches!(&lid.txt, Longident::Lident(s) if s == "::") => - { - if let PatternDesc::Ppat_tuple(elems) = &arg.ppat_desc { - if elems.len() == 2 { - acc.push(&elems[0]); - current = &elems[1]; - continue; - } - } - // Malformed cons - return as-is - return (acc, current); - } - // Not a cons constructor - return the tail - _ => { - return (acc, current); - } - } - } - } - - /// Print a block body expression without adding outer braces. - /// Used for printing the continuation of let/module/open/exception. - fn print_block_body(&mut self, expr: &Expression) { - self.print_block_body_inner(expr, true); - } - - fn print_block_body_inner(&mut self, expr: &Expression, print_attrs: bool) { - if print_attrs { - // Print any non-internal attributes on the expression - for attr in &expr.pexp_attributes { - if !Self::is_internal_attribute(attr) { - self.write("@"); - self.print_attribute(attr); - self.space(); - } - } - } - - match &expr.pexp_desc { - ExpressionDesc::Pexp_let(rec_flag, bindings, body) => { - self.print_let_bindings(*rec_flag, bindings); - self.newline(); - self.print_block_body(body); - } - ExpressionDesc::Pexp_letmodule(name, modexpr, body) => { - self.write("module "); - self.write(&name.txt); - self.write(" = "); - self.print_module_expr(modexpr); - self.newline(); - self.print_block_body(body); - } - ExpressionDesc::Pexp_letexception(ext, body) => { - self.write("exception "); - self.print_extension_constructor(ext); - self.newline(); - self.print_block_body(body); - } - ExpressionDesc::Pexp_open(override_flag, lid, body) => { - self.write("open"); - if *override_flag == OverrideFlag::Override { - self.write("!"); - } - self.write(" "); - self.print_longident(&lid.txt); - self.newline(); - self.print_block_body(body); - } - ExpressionDesc::Pexp_sequence(left, right) => { - self.print_expression(left); - self.newline(); - self.print_block_body(right); - } - _ => { - // Not a block form, print normally - self.print_expression(expr); - } - } - } - - // ======================================================================== - // Structure Printing - // ======================================================================== - - /// Print a structure. - pub fn print_structure(&mut self, structure: &Structure) { - let mut prev_loc_end_line = 0; - for (i, item) in structure.iter().enumerate() { - if i > 0 { - // Add blank line only if there was a blank line in the source - let item_start_line = item.pstr_loc.loc_start.line; - if item_start_line - prev_loc_end_line > 1 { - self.newline(); - self.newline(); - } else { - self.newline(); - } - } - if self.comments_enabled() { - self.print_comments_before_loc(&item.pstr_loc); - } - self.print_structure_item(item); - if self.comments_enabled() { - self.print_trailing_comments_for_loc(&item.pstr_loc); - } - prev_loc_end_line = item.pstr_loc.loc_end.line; - } - if self.comments_enabled() { - self.flush_remaining_comments(); - } - } - - /// Print a structure item. - pub fn print_structure_item(&mut self, item: &StructureItem) { - // Print attributes on the same line as the item (not on separate lines) - self.print_attributes_with_sep(&item.pstr_desc.get_attributes(), false); - match &item.pstr_desc { - StructureItemDesc::Pstr_eval(expr, _attrs) => { - if matches!(&expr.pexp_desc, ExpressionDesc::Pexp_sequence(..)) { - self.write("{"); - self.indent(); - self.newline(); - self.print_block_body_inner(expr, false); - self.dedent(); - self.newline(); - self.write("}"); - } else { - self.print_expression(expr); - } - } - StructureItemDesc::Pstr_value(rec_flag, bindings) => { - self.print_let_bindings(*rec_flag, bindings); - } - StructureItemDesc::Pstr_primitive(vd) => { - self.print_value_description(vd); - } - StructureItemDesc::Pstr_type(rec_flag, decls) => { - self.print_type_declarations(*rec_flag, decls); - } - StructureItemDesc::Pstr_typext(ext) => { - self.print_type_extension(ext); - } - StructureItemDesc::Pstr_exception(ext) => { - self.write("exception "); - self.print_extension_constructor(ext); - } - StructureItemDesc::Pstr_module(mb) => { - self.print_module_binding(mb); - } - StructureItemDesc::Pstr_recmodule(mbs) => { - for (i, mb) in mbs.iter().enumerate() { - if i == 0 { - self.write("module rec "); - } else { - self.newline(); - self.write("and "); - } - self.write(&mb.pmb_name.txt); - self.write(" = "); - self.print_module_expr(&mb.pmb_expr); - } - } - StructureItemDesc::Pstr_modtype(mtd) => { - self.print_module_type_declaration(mtd); - } - StructureItemDesc::Pstr_open(od) => { - self.print_attributes(&od.popen_attributes); - self.write("open"); - if od.popen_override == OverrideFlag::Override { - self.write("!"); - } - self.write(" "); - self.print_longident(&od.popen_lid.txt); - } - StructureItemDesc::Pstr_include(incl) => { - self.write("include "); - self.print_module_expr(&incl.pincl_mod); - } - StructureItemDesc::Pstr_attribute(attr) => { - self.write("@@"); - self.print_attribute(attr); - } - StructureItemDesc::Pstr_extension(ext, _attrs) => { - // Module-level extensions use %% - self.write("%%"); - self.write_ident(&ext.0.txt); - self.print_extension_payload(&ext.1); - } - } - } - - // ======================================================================== - // Let Bindings - // ======================================================================== - - /// Print let bindings. - fn print_let_bindings(&mut self, rec_flag: RecFlag, bindings: &[ValueBinding]) { - for (i, binding) in bindings.iter().enumerate() { - // Print attributes before the let keyword (each on separate line) - self.print_attributes(&binding.pvb_attributes); - if i == 0 { - self.write("let "); - if rec_flag == RecFlag::Recursive { - self.write("rec "); - } - } else { - self.newline(); - self.write("and "); - } - self.print_value_binding(binding); - } - } - - /// Print a single value binding. - fn print_value_binding(&mut self, binding: &ValueBinding) { - self.print_pattern(&binding.pvb_pat); - self.write(" = "); - // Check if expression needs to be wrapped in braces - // (sequences and other multi-statement expressions) - if Self::needs_braces_in_binding(&binding.pvb_expr) { - self.write("{"); - self.indent(); - self.newline(); - self.print_block_body(&binding.pvb_expr); - self.dedent(); - self.newline(); - self.write("}"); - } else { - self.print_expression(&binding.pvb_expr); - } - } - - /// Check if an expression needs to be wrapped in braces when used as a binding RHS. - fn needs_braces_in_binding(expr: &Expression) -> bool { - matches!( - &expr.pexp_desc, - ExpressionDesc::Pexp_sequence(..) - | ExpressionDesc::Pexp_open(..) - | ExpressionDesc::Pexp_let(..) - | ExpressionDesc::Pexp_letmodule(..) - | ExpressionDesc::Pexp_letexception(..) - ) - } - - // ======================================================================== - // Binary/Unary Expression Detection - // ======================================================================== - - /// List of binary operators in ReScript. - const BINARY_OPERATORS: &'static [&'static str] = &[ - ":=", "||", "&&", "=", "==", "===", "<", ">", "!=", "!==", "<=", ">=", "+", "+.", "-", "-.", - "++", "*", "*.", "/", "/.", "**", "->", "<>", "%", "|||", "^^^", "&&&", "<<", ">>", ">>>", - ]; - - /// List of unary operators in ReScript. - const UNARY_OPERATORS: &'static [&'static str] = &["!", "?", "~+", "~+.", "~-", "~-.", "not"]; - - /// Check if an operator is a binary operator. - fn is_binary_operator(op: &str) -> bool { - Self::BINARY_OPERATORS.contains(&op) - } - - /// Check if an operator is a unary operator. - fn is_unary_operator(op: &str) -> bool { - Self::UNARY_OPERATORS.contains(&op) - } - - /// Check if a labeled argument is punned (e.g., `~foo` instead of `~foo=foo`). - /// This is detected by checking if the argument is a ghost identifier with the same name as the label. - fn is_punned_arg(&self, label: &ArgLabel, arg: &Expression) -> bool { - let label_name = match label { - ArgLabel::Labelled(name) | ArgLabel::Optional(name) => &name.txt, - ArgLabel::Nolabel => return false, - }; - - // OCaml's punning detection: label matches the ident name, no attributes, simple ident - if !arg.pexp_attributes.is_empty() { - return false; - } - - if let ExpressionDesc::Pexp_ident(lid) = &arg.pexp_desc { - if let Longident::Lident(ident_name) = &lid.txt { - return ident_name == label_name; - } - } - - false - } - - /// Try to extract binary expression components from a Pexp_apply. - /// Returns (operator, left, right) if this is a binary expression. - fn as_binary_expr<'b>( - &self, - funct: &'b Expression, - args: &'b [(ArgLabel, Expression)], - ) -> Option<(&'b str, &'b Expression, &'b Expression)> { - // Must have exactly 2 unlabeled arguments - if args.len() != 2 { - return None; - } - let (label1, left) = &args[0]; - let (label2, right) = &args[1]; - if !matches!(label1, ArgLabel::Nolabel) || !matches!(label2, ArgLabel::Nolabel) { - return None; - } - - // Function must be an identifier that is a binary operator - if let ExpressionDesc::Pexp_ident(lid) = &funct.pexp_desc { - if let Longident::Lident(op) = &lid.txt { - if Self::is_binary_operator(op) { - return Some((op.as_str(), left, right)); - } - } - } - None - } - - /// Try to extract unary expression components from a Pexp_apply. - /// Returns (operator, operand) if this is a unary expression. - fn as_unary_expr<'b>( - &self, - funct: &'b Expression, - args: &'b [(ArgLabel, Expression)], - ) -> Option<(&'b str, &'b Expression)> { - // Must have exactly 1 unlabeled argument - if args.len() != 1 { - return None; - } - let (label, operand) = &args[0]; - if !matches!(label, ArgLabel::Nolabel) { - return None; - } - - // Function must be an identifier that is a unary operator - if let ExpressionDesc::Pexp_ident(lid) = &funct.pexp_desc { - if let Longident::Lident(op) = &lid.txt { - if Self::is_unary_operator(op) { - // Map internal names to display names - let display_op = match op.as_str() { - "~-" => "-", - "~-." => "-.", - "~+" => "+", - "~+." => "+.", - "not" => "!", - other => other, - }; - return Some((display_op, operand)); - } - } - } - None - } - - // ======================================================================== - // Template Literal Printing - // ======================================================================== - - /// Print an untagged template literal. - /// Walks the ++ chain and reconstructs the template. - fn print_template_literal(&mut self, expr: &Expression) { - let mut tag = "js"; - let mut inner = Printer::new(); - - fn walk_expr(printer: &mut Printer, expr: &Expression, tag: &mut &str) { - match &expr.pexp_desc { - ExpressionDesc::Pexp_apply { funct, args, .. } => { - // Check if this is a ++ operation - if let ExpressionDesc::Pexp_ident(lid) = &funct.pexp_desc { - if let Longident::Lident(op) = &lid.txt { - if op == "++" && args.len() == 2 { - walk_expr(printer, &args[0].1, tag); - walk_expr(printer, &args[1].1, tag); - return; - } - } - } - // Not a ++, print as interpolation - printer.write("${"); - printer.print_expression(expr); - printer.write("}"); - } - ExpressionDesc::Pexp_constant(Constant::String(txt, Some(prefix))) => { - *tag = if prefix == "json" { "json" } else { "js" }; - // Print the template string contents - printer.print_template_string_contents(txt); - } - ExpressionDesc::Pexp_constant(Constant::String(txt, None)) => { - // Might be a regular string, print as template content - printer.print_template_string_contents(txt); - } - _ => { - // Expression interpolation - printer.write("${"); - printer.print_expression(expr); - printer.write("}"); - } - } - } - - walk_expr(&mut inner, expr, &mut tag); - let content = inner.into_output(); - - // Wrap with backticks - if tag == "js" { - self.write("`"); - } else { - self.write(tag); - self.write("`"); - } - self.write(&content); - self.write("`"); - } - - /// Print template string contents (handling escapes). - fn print_template_string_contents(&mut self, s: &str) { - // The string is already stored with escapes, output directly - self.write(s); - } - - /// Print a tagged template literal: tag`strings${values}` - fn print_tagged_template_literal(&mut self, tag: &Expression, args: &[(ArgLabel, Expression)]) { - // Args should be [strings_array, values_array] - if args.len() != 2 { - // Fallback to regular apply - self.print_expression(tag); - self.write("("); - for (i, (label, arg)) in args.iter().enumerate() { - if i > 0 { - self.write(", "); - } - self.print_arg_label(label); - self.print_expression(arg); - } - self.write(")"); - return; - } - - let strings = match &args[0].1.pexp_desc { - ExpressionDesc::Pexp_array(arr) => arr, - _ => { - self.print_expression(tag); - return; - } - }; - let values = match &args[1].1.pexp_desc { - ExpressionDesc::Pexp_array(arr) => arr, - _ => { - self.print_expression(tag); - return; - } - }; - - // Print the tag - self.print_expression(tag); - self.write("`"); - - // Interleave strings and values - for (i, str_expr) in strings.iter().enumerate() { - // Print string content - if let ExpressionDesc::Pexp_constant(Constant::String(txt, _)) = &str_expr.pexp_desc { - self.print_template_string_contents(txt); - } - // Print value interpolation if exists - if i < values.len() { - self.write("${"); - self.print_expression(&values[i]); - self.write("}"); - } - } - - self.write("`"); - } - - // ======================================================================== - // Expression Printing - // ======================================================================== - - /// Print an expression. - pub fn print_expression(&mut self, expr: &Expression) { - self.print_expression_with_comments(expr, false); - } - - fn print_expression_in_subexpr(&mut self, expr: &Expression) { - self.print_expression_with_comments(expr, true); - } - - fn print_expression_with_comments(&mut self, expr: &Expression, needs_parens: bool) { - if self.comments_enabled() { - self.print_comments_before_loc(&expr.pexp_loc); - } - self.print_expression_inner(expr, needs_parens); - if self.comments_enabled() { - self.print_trailing_comments_for_loc(&expr.pexp_loc); - } - } - - /// Check if an attribute is internal and shouldn't be printed. - /// Based on OCaml's is_printable_attribute in res_parsetree_viewer.ml - fn is_internal_attribute(attr: &Attribute) -> bool { - let name = &attr.0.txt; - matches!( - name.as_str(), - "res.iflet" - | "res.braces" - | "ns.braces" - | "JSX" - | "res.await" - | "res.template" - | "res.taggedTemplate" - | "res.ternary" - | "res.inlineRecordDefinition" - ) - } - - /// Check if an expression has the res.braces/ns.braces attribute. - fn has_braces_attribute(expr: &Expression) -> bool { - expr.pexp_attributes - .iter() - .any(|attr| matches!(attr.0.txt.as_str(), "res.braces" | "ns.braces")) - } - - /// Strip res.braces/ns.braces attributes from an expression. - fn strip_braces_attribute(expr: &Expression) -> Expression { - let mut result = expr.clone(); - result.pexp_attributes = expr - .pexp_attributes - .iter() - .filter(|attr| !matches!(attr.0.txt.as_str(), "res.braces" | "ns.braces")) - .cloned() - .collect(); - result - } - - fn is_unit_pattern(pat: &Pattern) -> bool { - matches!( - &pat.ppat_desc, - PatternDesc::Ppat_construct(lid, None) if lid.txt.to_string() == "()" - ) - } - - fn expr_needs_parens_for_attribute(&self, expr: &Expression) -> bool { - match &expr.pexp_desc { - ExpressionDesc::Pexp_apply { funct, args, .. } => { - self.as_binary_expr(funct, args).is_some() || self.as_unary_expr(funct, args).is_some() - } - ExpressionDesc::Pexp_sequence(..) - | ExpressionDesc::Pexp_ifthenelse(..) - | ExpressionDesc::Pexp_match(..) - | ExpressionDesc::Pexp_try(..) - // Note: Pexp_fun does NOT need parens - `@attr x => y` is valid - | ExpressionDesc::Pexp_let(..) - | ExpressionDesc::Pexp_letmodule(..) - | ExpressionDesc::Pexp_letexception(..) - | ExpressionDesc::Pexp_open(..) - | ExpressionDesc::Pexp_for(..) - | ExpressionDesc::Pexp_while(..) - | ExpressionDesc::Pexp_constraint(..) - | ExpressionDesc::Pexp_coerce(..) - | ExpressionDesc::Pexp_newtype(..) => true, - _ => false, - } - } - - fn expr_needs_parens_in_subexpr(&self, expr: &Expression) -> bool { - match &expr.pexp_desc { - ExpressionDesc::Pexp_apply { funct, args, .. } => { - // Check if this is a binary expression - if let Some((op, _, _)) = self.as_binary_expr(funct, args) { - // Pipe operator doesn't need parens in subexpr - op != "->" - } else { - self.as_unary_expr(funct, args).is_some() - } - } - ExpressionDesc::Pexp_fun { .. } - | ExpressionDesc::Pexp_ifthenelse(..) - | ExpressionDesc::Pexp_match(..) - | ExpressionDesc::Pexp_try(..) - | ExpressionDesc::Pexp_for(..) - | ExpressionDesc::Pexp_while(..) - | ExpressionDesc::Pexp_newtype(..) - | ExpressionDesc::Pexp_constraint(..) - | ExpressionDesc::Pexp_coerce(..) - | ExpressionDesc::Pexp_setfield(..) - | ExpressionDesc::Pexp_sequence(..) - | ExpressionDesc::Pexp_let(..) - | ExpressionDesc::Pexp_letmodule(..) - | ExpressionDesc::Pexp_letexception(..) - | ExpressionDesc::Pexp_open(..) - | ExpressionDesc::Pexp_assert(..) => true, - _ => false, - } - } - - fn print_apply_funct(&mut self, funct: &Expression) { - let has_attrs = funct - .pexp_attributes - .iter() - .any(|attr| !Self::is_internal_attribute(attr)); - if has_attrs { - self.write("("); - self.print_expression(funct); - self.write(")"); - } else { - self.print_expression_in_subexpr(funct); - } - } - - /// Print an expression with optional parentheses context. - fn print_expression_inner(&mut self, expr: &Expression, needs_parens: bool) { - let attrs: Vec<&Attribute> = expr - .pexp_attributes - .iter() - .filter(|attr| !Self::is_internal_attribute(attr)) - .collect(); - let has_attrs = !attrs.is_empty(); - - if needs_parens && matches!(&expr.pexp_desc, ExpressionDesc::Pexp_sequence(..)) { - for attr in &attrs { - self.write("@"); - self.print_attribute(attr); - self.space(); - } - self.write("{"); - self.indent(); - self.newline(); - self.print_block_body_inner(expr, false); - self.dedent(); - self.newline(); - self.write("}"); - return; - } - - if needs_parens && self.expr_needs_parens_in_subexpr(expr) { - for attr in &attrs { - self.write("@"); - self.print_attribute(attr); - self.space(); - } - self.write("("); - self.print_expression_desc(expr, needs_parens); - self.write(")"); - return; - } - - if has_attrs && self.expr_needs_parens_for_attribute(expr) { - for attr in &attrs { - self.write("@"); - self.print_attribute(attr); - self.space(); - } - self.write("("); - self.print_expression_desc(expr, needs_parens); - self.write(")"); - return; - } - - for attr in &attrs { - self.write("@"); - self.print_attribute(attr); - self.space(); - } - - self.print_expression_desc(expr, needs_parens); - } - - fn print_expression_desc(&mut self, expr: &Expression, needs_parens: bool) { - match &expr.pexp_desc { - ExpressionDesc::Pexp_ident(lid) => { - // Use print_lident to escape keywords (e.g., \"type", \"let") - self.print_lident(&lid.txt); - } - ExpressionDesc::Pexp_constant(c) => { - // Check if this is a template literal string - let is_template = expr - .pexp_attributes - .iter() - .any(|(n, _)| n.txt == "res.template"); - if is_template { - if let Constant::String(txt, _) = c { - self.write("`"); - self.print_template_string_contents(txt); - self.write("`"); - return; - } - } - // Also check for empty delimiter (Some("")) - if let Constant::String(txt, Some(delim)) = c { - if delim.is_empty() || delim == "js" { - self.write("`"); - self.print_template_string_contents(txt); - self.write("`"); - return; - } - } - self.print_constant(c); - } - ExpressionDesc::Pexp_let(rec_flag, bindings, body) => { - self.write("{"); - self.indent(); - self.newline(); - self.print_let_bindings(*rec_flag, bindings); - self.newline(); - // Use print_block_body for continuation to avoid nested braces - self.print_block_body(body); - self.dedent(); - self.newline(); - self.write("}"); - } - ExpressionDesc::Pexp_fun { is_async, .. } => { - if *is_async { - self.write("async "); - } - self.print_fun_expr(expr); - } - ExpressionDesc::Pexp_apply { - funct, - args, - partial, - .. - } => { - // Check for tagged template literal: tag([strings], [values]) - if expr - .pexp_attributes - .iter() - .any(|(n, _)| n.txt == "res.taggedTemplate") - { - self.print_tagged_template_literal(funct, args); - return; - } - // Check for untagged template literal: str ++ val ++ str... - if expr - .pexp_attributes - .iter() - .any(|(n, _)| n.txt == "res.template") - { - self.print_template_literal(expr); - return; - } - // Check for array access syntax: arr[index] - if expr - .pexp_attributes - .iter() - .any(|(n, _)| n.txt == "res.array.access") - && args.len() == 2 - { - self.print_expression_in_subexpr(&args[0].1); - self.write("["); - self.print_expression_in_subexpr(&args[1].1); - self.write("]"); - return; - } - // Check for array set syntax: arr[index] = value - if expr - .pexp_attributes - .iter() - .any(|(n, _)| n.txt == "res.array.set") - && args.len() == 3 - { - self.print_expression_in_subexpr(&args[0].1); - self.write("["); - self.print_expression_in_subexpr(&args[1].1); - self.write("] = "); - self.print_expression_in_subexpr(&args[2].1); - return; - } - // Check for object property access: ##(obj, "prop") -> obj["prop"] - if let ExpressionDesc::Pexp_ident(lid) = &funct.pexp_desc { - if matches!(&lid.txt, Longident::Lident(s) if s == "##") && args.len() == 2 { - self.print_expression_in_subexpr(&args[0].1); - self.write("[\""); - // Print the member - if it's an identifier, just use the name - if let ExpressionDesc::Pexp_ident(member_lid) = &args[1].1.pexp_desc { - self.print_longident(&member_lid.txt); - } else { - self.print_expression_in_subexpr(&args[1].1); - } - self.write("\"]"); - return; - } - // Check for object property set: #=(lhs, rhs) -> lhs = rhs - if matches!(&lid.txt, Longident::Lident(s) if s == "#=") && args.len() == 2 { - self.print_expression_in_subexpr(&args[0].1); - self.write(" = "); - self.print_expression_in_subexpr(&args[1].1); - return; - } - } - // Check if this is a binary expression and print in infix notation - if let Some((operator, left, right)) = self.as_binary_expr(funct, args) { - self.print_expression_in_subexpr(left); - // Pipe operator (->) doesn't have spaces around it - if operator == "->" { - self.write(operator); - } else { - self.space(); - self.write(operator); - self.space(); - } - self.print_expression_in_subexpr(right); - } else if let Some((operator, operand)) = self.as_unary_expr(funct, args) { - self.write(operator); - self.print_expression_in_subexpr(operand); - } else { - self.print_apply_funct(funct); - self.write("("); - // Check if this is a single unit argument - if so, don't print it - // f() is syntactic sugar for f(()) - let is_single_unit_arg = args.len() == 1 - && matches!(args[0].0, ArgLabel::Nolabel) - && matches!( - &args[0].1.pexp_desc, - ExpressionDesc::Pexp_construct(lid, None) - if matches!(&lid.txt, Longident::Lident(s) if s == "()") - ); - let args_to_print: Vec<_> = if is_single_unit_arg { - vec![] - } else { - args.iter().collect() - }; - for (i, (label, arg)) in args_to_print.iter().enumerate() { - if i > 0 { - self.write(", "); - } - // Check for punning: ~foo where arg is ghost ident "foo" - if self.is_punned_arg(label, arg) { - match label { - ArgLabel::Labelled(s) => { - self.write("~"); - self.write_ident(&s.txt); - } - ArgLabel::Optional(s) => { - self.write("~"); - self.write_ident(&s.txt); - self.write("?"); - } - ArgLabel::Nolabel => {} - } - } else { - self.print_arg_label(label); - self.print_expression_in_subexpr(arg); - } - } - // Print partial application marker - if *partial { - if !args.is_empty() { - self.write(", "); - } - self.write("..."); - } - self.write(")"); - } - } - ExpressionDesc::Pexp_match(scrutinee, cases) => { - self.write("switch "); - self.print_expression_in_subexpr(scrutinee); - self.write(" {"); - // Cases are NOT indented - they align with 'switch' - for case in cases { - self.newline(); - self.write("| "); - self.print_pattern(&case.pc_lhs); - if let Some(guard) = &case.pc_guard { - self.write(" if "); - self.print_expression(guard); - } - self.write(" => "); - self.print_expression_in_subexpr(&case.pc_rhs); - } - self.newline(); - self.write("}"); - } - ExpressionDesc::Pexp_try(body, cases) => { - self.write("try "); - self.print_expression_in_subexpr(body); - self.write(" catch {"); - // Cases are NOT indented - they align with 'try' - for case in cases { - self.newline(); - self.write("| "); - self.print_pattern(&case.pc_lhs); - if let Some(guard) = &case.pc_guard { - self.write(" when "); - self.print_expression(guard); - } - self.write(" => "); - self.print_expression_in_subexpr(&case.pc_rhs); - } - self.newline(); - self.write("}"); - } - ExpressionDesc::Pexp_tuple(exprs) => { - if exprs.len() == 1 { - self.print_expression_with_comments(&exprs[0], needs_parens); - return; - } - self.write("("); - for (i, e) in exprs.iter().enumerate() { - if i > 0 { - self.write(", "); - } - self.print_expression_in_subexpr(e); - } - self.write(")"); - } - ExpressionDesc::Pexp_construct(lid, arg) => { - // Handle special constructors: (), [], :: - match &lid.txt { - // Unit: () - Longident::Lident(s) if s == "()" => { - self.write("()"); - } - // Empty list: list{} - Longident::Lident(s) if s == "[]" => { - self.write("list{}"); - } - // List cons: list{a, b, ...rest} - Longident::Lident(s) if s == "::" => { - let (exprs, spread) = Self::collect_list_expressions(expr); - self.print_list_with_doc(&exprs, spread); - } - // Generic constructor - _ => { - if self.comments_enabled() { - self.print_comments_before_loc(&lid.loc); - } - self.print_longident(&lid.txt); - if self.comments_enabled() { - self.print_trailing_comments_for_loc(&lid.loc); - } - if let Some(arg) = arg { - self.write("("); - // If the argument is a tuple, unwrap it to avoid double parens - match &arg.pexp_desc { - ExpressionDesc::Pexp_tuple(exprs) => { - for (i, e) in exprs.iter().enumerate() { - if i > 0 { - self.write(", "); - } - self.print_expression_in_subexpr(e); - } - } - ExpressionDesc::Pexp_construct(inner_lid, None) - if inner_lid.txt.to_string() == "()" => - { - // Unit argument - print nothing inside parens - } - _ => self.print_expression_in_subexpr(arg), - } - self.write(")"); - } - } - } - } - ExpressionDesc::Pexp_variant(label, arg) => { - self.write("#"); - self.write(label); - if let Some(arg) = arg { - self.write("("); - // If the argument is a tuple, unwrap it to avoid double parens - match &arg.pexp_desc { - ExpressionDesc::Pexp_tuple(exprs) => { - for (i, e) in exprs.iter().enumerate() { - if i > 0 { - self.write(", "); - } - self.print_expression_in_subexpr(e); - } - } - ExpressionDesc::Pexp_construct(lid, None) - if lid.txt.to_string() == "()" => - { - // Unit argument - print nothing inside parens - } - _ => self.print_expression_in_subexpr(arg), - } - self.write(")"); - } - } - ExpressionDesc::Pexp_record(fields, spread) => { - self.print_record_with_doc(fields, spread.as_deref(), &expr.pexp_loc); - } - ExpressionDesc::Pexp_field(expr, lid) => { - self.print_expression_in_subexpr(expr); - self.write("."); - if self.comments_enabled() { - self.print_comments_before_loc(&lid.loc); - } - // Use print_lident to escape keywords like \"type" - self.print_lident(&lid.txt); - if self.comments_enabled() { - self.print_trailing_comments_for_loc(&lid.loc); - } - } - ExpressionDesc::Pexp_setfield(expr, lid, value) => { - self.print_expression_in_subexpr(expr); - self.write("."); - if self.comments_enabled() { - self.print_comments_before_loc(&lid.loc); - } - // Use print_lident to escape keywords like \"type" - self.print_lident(&lid.txt); - if self.comments_enabled() { - self.print_trailing_comments_for_loc(&lid.loc); - } - self.write(" = "); - self.print_expression_in_subexpr(value); - } - ExpressionDesc::Pexp_array(items) => { - self.print_array_with_doc(items); - } - ExpressionDesc::Pexp_ifthenelse(cond, then_branch, else_branch) => { - // Check for ternary attribute - let is_ternary = expr - .pexp_attributes - .iter() - .any(|(name, _)| name.txt == "res.ternary"); - if is_ternary { - self.print_expression_in_subexpr(cond); - self.write(" ? "); - self.print_expression_in_subexpr(then_branch); - self.write(" : "); - if let Some(else_br) = else_branch { - self.print_expression_in_subexpr(else_br); - } - } else { - self.write("if "); - self.print_expression_in_subexpr(cond); - self.write(" {"); - self.indent(); - self.newline(); - self.print_expression(then_branch); - self.dedent(); - self.newline(); - self.write("}"); - if let Some(else_br) = else_branch { - self.write(" else "); - // Check if else branch is another if - if matches!(else_br.pexp_desc, ExpressionDesc::Pexp_ifthenelse(..)) { - self.print_expression(else_br); - } else { - self.write("{"); - self.indent(); - self.newline(); - self.print_expression(else_br); - self.dedent(); - self.newline(); - self.write("}"); - } - } - } - } - ExpressionDesc::Pexp_sequence(first, second) => { - self.print_expression(first); - self.newline(); - self.print_expression(second); - } - ExpressionDesc::Pexp_while(cond, body) => { - self.write("while "); - self.print_expression_in_subexpr(cond); - self.write(" {"); - self.indent(); - self.newline(); - self.print_expression(body); - self.dedent(); - self.newline(); - self.write("}"); - } - ExpressionDesc::Pexp_for(pat, start, finish, dir, body) => { - self.write("for "); - self.print_pattern(pat); - self.write(" in "); - self.print_expression_in_subexpr(start); - match dir { - DirectionFlag::Upto => self.write(" to "), - DirectionFlag::Downto => self.write(" downto "), - } - self.print_expression_in_subexpr(finish); - self.write(" {"); - self.indent(); - self.newline(); - self.print_expression(body); - self.dedent(); - self.newline(); - self.write("}"); - } - ExpressionDesc::Pexp_constraint(expr, typ) => { - self.write("("); - self.print_expression_in_subexpr(expr); - self.write(": "); - self.print_core_type(typ); - self.write(")"); - } - ExpressionDesc::Pexp_coerce(expr, _from, to) => { - self.write("("); - self.print_expression_in_subexpr(expr); - self.write(" :> "); - self.print_core_type(to); - self.write(")"); - } - ExpressionDesc::Pexp_send(expr, meth) => { - // Object method send: obj["method"] - self.print_expression_in_subexpr(expr); - self.write("[\""); - self.write(&meth.txt); - self.write("\"]"); - } - ExpressionDesc::Pexp_letmodule(name, modexpr, body) => { - self.write("{"); - self.indent(); - self.newline(); - self.write("module "); - self.write(&name.txt); - self.write(" = "); - self.print_module_expr(modexpr); - self.newline(); - // Use print_block_body for continuation to avoid nested braces - self.print_block_body(body); - self.dedent(); - self.newline(); - self.write("}"); - } - ExpressionDesc::Pexp_letexception(ext, body) => { - self.write("{"); - self.indent(); - self.newline(); - self.write("exception "); - self.print_extension_constructor(ext); - self.newline(); - // Use print_block_body for continuation to avoid nested braces - self.print_block_body(body); - self.dedent(); - self.newline(); - self.write("}"); - } - ExpressionDesc::Pexp_assert(expr) => { - self.write("assert("); - self.print_expression(expr); - self.write(")"); - } - ExpressionDesc::Pexp_pack(modexpr) => { - self.write("module("); - self.print_module_expr(modexpr); - self.write(")"); - } - ExpressionDesc::Pexp_open(_override_flag, lid, expr) => { - self.write("{"); - self.indent(); - self.newline(); - self.write("open "); - self.print_longident(&lid.txt); - self.newline(); - // Use print_block_body for continuation to avoid nested braces - self.print_block_body(expr); - self.dedent(); - self.newline(); - self.write("}"); - } - ExpressionDesc::Pexp_extension(ext) => { - // Regex literal: `/pattern/flags` - if ext.0.txt == "res.regex" { - if let Payload::PStr(items) = &ext.1 { - let get_str = |idx: usize| -> Option<&str> { - let item = items.get(idx)?; - match &item.pstr_desc { - StructureItemDesc::Pstr_eval(expr, _) => match &expr.pexp_desc { - ExpressionDesc::Pexp_constant(Constant::String(s, _)) => { - Some(s.as_str()) - } - _ => None, - }, - _ => None, - } - }; - - if let (Some(pattern), Some(flags)) = (get_str(0), get_str(1)) { - self.write("/"); - self.write(pattern); - self.write("/"); - self.write(flags); - return; - } - } - } - - // Check for %obj extension (JS object literal) - if ext.0.txt == "obj" { - if let Payload::PStr(items) = &ext.1 { - if let Some(item) = items.first() { - if let StructureItemDesc::Pstr_eval(expr, _) = &item.pstr_desc { - if let ExpressionDesc::Pexp_record(fields, _) = &expr.pexp_desc { - self.write("{"); - for (i, field) in fields.iter().enumerate() { - if i > 0 { - self.write(", "); - } - // Print field key as quoted string - self.write("\""); - self.print_longident(&field.lid.txt); - self.write("\": "); - self.print_expression_in_subexpr(&field.expr); - } - self.write("}"); - return; - } - } - } - } - } - // Check for res.list extension - if ext.0.txt == "res.list" || ext.0.txt == "res.list.spread" { - self.write("list{"); - if let Payload::PStr(items) = &ext.1 { - for (i, item) in items.iter().enumerate() { - if i > 0 { - self.write(", "); - } - if let StructureItemDesc::Pstr_eval(e, _) = &item.pstr_desc { - if let ExpressionDesc::Pexp_extension((name, payload)) = &e.pexp_desc - && name.txt == "res.spread" - && let Payload::PStr(spread_items) = payload - && let Some(spread_item) = spread_items.first() - && let StructureItemDesc::Pstr_eval(spread_expr, _) = - &spread_item.pstr_desc - { - self.write("..."); - self.print_expression_in_subexpr(spread_expr); - } else { - self.print_expression_in_subexpr(e); - } - } - } - } - // Check for spread in attributes - if ext.0.txt == "res.list.spread" { - if let Some((_attr_name, attr_payload)) = expr - .pexp_attributes - .iter() - .find(|(n, _)| n.txt == "res.spread") - { - if !matches!(&ext.1, Payload::PStr(items) if items.is_empty()) { - self.write(", "); - } - self.write("..."); - if let Payload::PStr(spread_items) = attr_payload { - if let Some(item) = spread_items.first() { - if let StructureItemDesc::Pstr_eval(e, _) = &item.pstr_desc { - self.print_expression_in_subexpr(e); - } - } - } - } - } - self.write("}"); - return; - } - self.write("%"); - // Extension names are not escaped (e.g., %let not %\"let") - self.write(&ext.0.txt); - self.print_extension_payload(&ext.1); - } - ExpressionDesc::Pexp_newtype(name, body) => { - self.write("(type "); - self.write(&name.txt); - self.write(") => "); - self.print_expression_with_comments(body, true); - } - ExpressionDesc::Pexp_await(expr) => { - self.write("await "); - self.print_expression_in_subexpr(expr); - } - ExpressionDesc::Pexp_jsx_element(elem) => { - self.print_jsx_element(elem); - } - } - } - - // ======================================================================== - // Pattern Printing - // ======================================================================== - - /// Print a pattern. - pub fn print_pattern(&mut self, pat: &Pattern) { - if self.comments_enabled() { - self.print_comments_before_loc(&pat.ppat_loc); - } - // Print pattern attributes - for attr in &pat.ppat_attributes { - self.write("@"); - self.print_attribute(attr); - self.write(" "); - } - match &pat.ppat_desc { - PatternDesc::Ppat_any => { - self.write("_"); - } - PatternDesc::Ppat_var(name) => { - self.write_ident(&name.txt); - } - PatternDesc::Ppat_alias(pat, name) => { - self.print_pattern(pat); - self.write(" as "); - self.write_ident(&name.txt); - } - PatternDesc::Ppat_constant(c) => { - self.print_constant(c); - } - PatternDesc::Ppat_interval(c1, c2) => { - self.print_constant(c1); - self.write(".."); - self.print_constant(c2); - } - PatternDesc::Ppat_tuple(pats) => { - self.write("("); - for (i, p) in pats.iter().enumerate() { - if i > 0 { - self.write(", "); - } - self.print_pattern(p); - } - // Single-element tuples need trailing comma to distinguish from grouping parens - if pats.len() == 1 { - self.write(","); - } - self.write(")"); - } - PatternDesc::Ppat_construct(lid, arg) => { - // Handle special constructors: (), [], :: - match &lid.txt { - // Unit: () - Longident::Lident(s) if s == "()" => { - self.write("()"); - } - // Empty list: list{} - Longident::Lident(s) if s == "[]" => { - self.write("list{}"); - } - // List cons: list{a, b, ...rest} - Longident::Lident(s) if s == "::" => { - let (pats, tail) = Self::collect_list_patterns(pat); - self.write("list{"); - for (i, p) in pats.iter().enumerate() { - if i > 0 { - self.write(", "); - } - self.print_pattern(p); - } - // Check if tail is empty list `[]` or a spread pattern - let is_empty_list = matches!( - &tail.ppat_desc, - PatternDesc::Ppat_construct(lid, None) - if matches!(&lid.txt, Longident::Lident(s) if s == "[]") - ); - if !is_empty_list { - if !pats.is_empty() { - self.write(", "); - } - self.write("..."); - self.print_pattern(tail); - } - self.write("}"); - } - // Generic constructor - _ => { - if self.comments_enabled() { - self.print_comments_before_loc(&lid.loc); - } - self.print_longident(&lid.txt); - if self.comments_enabled() { - self.print_trailing_comments_for_loc(&lid.loc); - } - if let Some(arg) = arg { - self.write("("); - self.print_pattern(arg); - self.write(")"); - } - } - } - } - PatternDesc::Ppat_variant(label, arg) => { - self.write("#"); - self.write(label); - if let Some(arg) = arg { - self.write("("); - self.print_pattern(arg); - self.write(")"); - } - } - PatternDesc::Ppat_record(fields, closed) => { - self.write("{"); - for (i, field) in fields.iter().enumerate() { - if i > 0 { - self.write(", "); - } - if self.comments_enabled() { - self.print_comments_before_loc(&field.lid.loc); - } - self.print_longident(&field.lid.txt); - if self.comments_enabled() { - self.print_trailing_comments_for_loc(&field.lid.loc); - } - self.write(": "); - // Print optional marker if present - if field.opt { - self.write("? "); - // If the pattern is a constraint, wrap in parens to avoid ambiguity - let needs_parens = - matches!(field.pat.ppat_desc, PatternDesc::Ppat_constraint(..)); - if needs_parens { - self.write("("); - } - self.print_pattern(&field.pat); - if needs_parens { - self.write(")"); - } - } else { - self.print_pattern(&field.pat); - } - } - if *closed == ClosedFlag::Open { - if !fields.is_empty() { - self.write(", "); - } - self.write("_"); - } - self.write("}"); - } - PatternDesc::Ppat_array(pats) => { - self.write("["); - for (i, p) in pats.iter().enumerate() { - if i > 0 { - self.write(", "); - } - self.print_pattern(p); - } - self.write("]"); - } - PatternDesc::Ppat_or(left, right) => { - self.print_pattern(left); - self.write(" | "); - self.print_pattern(right); - } - PatternDesc::Ppat_constraint(pat, typ) => { - self.print_pattern(pat); - self.write(": "); - self.print_core_type(typ); - } - PatternDesc::Ppat_type(lid) => { - // Type pattern with spread: #...Foo.t - self.write("#..."); - if self.comments_enabled() { - self.print_comments_before_loc(&lid.loc); - } - self.print_longident(&lid.txt); - if self.comments_enabled() { - self.print_trailing_comments_for_loc(&lid.loc); - } - } - PatternDesc::Ppat_unpack(name) => { - self.write("module("); - self.write(&name.txt); - self.write(")"); - } - PatternDesc::Ppat_exception(pat) => { - self.write("exception "); - self.print_pattern(pat); - } - PatternDesc::Ppat_extension(ext) => { - // Dict pattern: dict{"key": pat} - if ext.0.txt == "res.dict" { - if let Payload::PPat(pat, _) = &ext.1 { - if let PatternDesc::Ppat_record(fields, _closed) = &pat.ppat_desc { - self.write("dict{"); - for (i, field) in fields.iter().enumerate() { - if i > 0 { - self.write(", "); - } - self.write("\""); - self.write(&field.lid.txt.to_string()); - self.write("\": "); - if field.opt { - self.write("?"); - } - self.print_pattern(&field.pat); - } - self.write("}"); - return; - } - } - } - - self.write("%"); - self.write(&ext.0.txt); - } - PatternDesc::Ppat_open(lid, pat) => { - if self.comments_enabled() { - self.print_comments_before_loc(&lid.loc); - } - self.print_longident(&lid.txt); - if self.comments_enabled() { - self.print_trailing_comments_for_loc(&lid.loc); - } - self.write(".("); - self.print_pattern(pat); - self.write(")"); - } - } - if self.comments_enabled() { - self.print_trailing_comments_for_loc(&pat.ppat_loc); - } - } - - // ======================================================================== - // Type Printing - // ======================================================================== - - /// Print a core type. - pub fn print_core_type(&mut self, typ: &CoreType) { - self.print_core_type_with_comments(typ, true); - } - - fn print_core_type_with_comments(&mut self, typ: &CoreType, allow_breaks: bool) { - if self.comments_enabled() { - self.print_comments_before_loc(&typ.ptyp_loc); - } - let attrs: Vec<&Attribute> = typ - .ptyp_attributes - .iter() - .filter(|attr| !Self::is_internal_attribute(attr)) - .collect(); - for attr in attrs { - self.write("@"); - self.print_attribute(attr); - self.space(); - } - self.print_core_type_inner(typ, allow_breaks); - if self.comments_enabled() { - self.print_trailing_comments_for_loc(&typ.ptyp_loc); - } - } - - fn print_core_type_inner(&mut self, typ: &CoreType, allow_breaks: bool) { - match &typ.ptyp_desc { - CoreTypeDesc::Ptyp_any => { - self.write("_"); - } - CoreTypeDesc::Ptyp_var(name) => { - self.write("'"); - self.write_type_var(name); - } - CoreTypeDesc::Ptyp_arrow { .. } => { - self.print_arrow_type(typ, allow_breaks); - } - CoreTypeDesc::Ptyp_tuple(typs) => { - let inline_len = self.inline_tuple_len(typs); - let fits_inline = !allow_breaks || self.line_len + inline_len <= self.max_width; - - if fits_inline { - self.write("("); - for (i, t) in typs.iter().enumerate() { - if i > 0 { - self.write(", "); - } - self.print_core_type_with_comments(t, allow_breaks); - } - self.write(")"); - } else { - self.write("("); - self.indent(); - for t in typs { - self.newline(); - self.print_core_type_with_comments(t, allow_breaks); - self.write(","); - } - self.dedent(); - self.newline(); - self.write(")"); - } - } - CoreTypeDesc::Ptyp_constr(lid, args) => { - // ReScript uses angle bracket syntax: constr - // Use print_lident to escape the final segment (e.g., Module.\"type") - self.print_lident(&lid.txt); - if !args.is_empty() { - self.write("<"); - for (i, arg) in args.iter().enumerate() { - if i > 0 { - self.write(", "); - } - self.print_core_type_with_comments(arg, allow_breaks); - } - self.write(">"); - } - } - CoreTypeDesc::Ptyp_object(fields, closed) => { - let is_open = *closed == ClosedFlag::Open; - if is_open { - self.write("{.."); - if fields.is_empty() { - self.write("}"); - return; - } - self.write(" "); - } else if fields.is_empty() { - self.write("{.}"); - return; - } else { - self.write("{"); - } - - for (i, field) in fields.iter().enumerate() { - if i > 0 { - self.write(", "); - } - match field { - ObjectField::Otag(name, attrs, typ) => { - for attr in attrs.iter().filter(|attr| !Self::is_internal_attribute(attr)) - { - self.write("@"); - self.print_attribute(attr); - self.space(); - } - self.write("\""); - self.write(&name.txt); - self.write("\""); - self.write(": "); - self.print_core_type_with_comments(typ, allow_breaks); - } - ObjectField::Oinherit(typ) => { - self.write("..."); - self.print_core_type_with_comments(typ, allow_breaks); - } - } - } - self.write("}"); - } - CoreTypeDesc::Ptyp_alias(typ, name) => { - // Arrow types need parens when inside an alias - let needs_parens = matches!(typ.ptyp_desc, CoreTypeDesc::Ptyp_arrow { .. }); - if needs_parens { - self.write("("); - } - self.print_core_type_with_comments(typ, allow_breaks); - if needs_parens { - self.write(")"); - } - self.write(" as '"); - self.write(name); - } - CoreTypeDesc::Ptyp_variant(fields, closed, _labels) => { - self.write("["); - if *closed == ClosedFlag::Open { - self.write("> "); - } - for (i, field) in fields.iter().enumerate() { - if i > 0 { - self.write(" | "); - } - self.print_row_field(field); - } - self.write("]"); - } - CoreTypeDesc::Ptyp_poly(vars, typ) => { - for var in vars { - self.write("'"); - self.write(&var.txt); - self.write(" "); - } - self.write(". "); - self.print_core_type_with_comments(typ, allow_breaks); - } - CoreTypeDesc::Ptyp_package(pkg) => { - self.write("module("); - self.print_longident(&pkg.0.txt); - if !pkg.1.is_empty() { - self.write(" with "); - for (i, (lid, typ)) in pkg.1.iter().enumerate() { - if i > 0 { - self.write(" and "); - } - self.write("type "); - self.print_longident(&lid.txt); - self.write(" = "); - self.print_core_type_with_comments(typ, allow_breaks); - } - } - self.write(")"); - } - CoreTypeDesc::Ptyp_extension(ext) => { - self.write("%"); - self.write(&ext.0.txt); - } - } - } - - fn print_arrow_type(&mut self, typ: &CoreType, allow_breaks: bool) { - // Get the arity from the outermost arrow type - let arity = if let CoreTypeDesc::Ptyp_arrow { arity, .. } = &typ.ptyp_desc { - *arity - } else { - Arity::Unknown - }; - - // Collect arguments up to the arity limit - let max_arity = match arity { - Arity::Full(n) => n, - Arity::Unknown => usize::MAX, - }; - - let mut args: Vec<&TypeArg> = vec![]; - let mut current = typ; - while let CoreTypeDesc::Ptyp_arrow { arg, ret, .. } = ¤t.ptyp_desc { - if args.len() >= max_arity { - break; - } - args.push(arg.as_ref()); - current = ret.as_ref(); - } - - // Shouldn't happen, but keep it safe. - if args.is_empty() { - self.print_core_type_with_comments(current, allow_breaks); - return; - } - - let has_label = args.iter().any(|arg| !matches!(arg.lbl, ArgLabel::Nolabel)); - let has_attrs = args.iter().any(|arg| !arg.attrs.is_empty()); - - // Use uncurried format (a, b) => c when: - // - there are labels, or - // - there are multiple arguments and arity is known - let use_uncurried = has_label - || has_attrs - || (args.len() > 1 && matches!(arity, Arity::Full(_))); - - if use_uncurried { - self.write("("); - for (i, arg) in args.iter().enumerate() { - if i > 0 { - self.write(", "); - } - - for attr in arg - .attrs - .iter() - .filter(|attr| !Self::is_internal_attribute(attr)) - { - self.write("@"); - self.print_attribute(attr); - self.space(); - } - - match &arg.lbl { - ArgLabel::Nolabel => {} - ArgLabel::Labelled(name) | ArgLabel::Optional(name) => { - self.write("~"); - self.write(&name.txt); - self.write(": "); - } - } - - self.print_core_type_with_comments(&arg.typ, allow_breaks); - - if matches!(arg.lbl, ArgLabel::Optional(_)) { - self.write("=?"); - } - } - self.write(") => "); - self.print_core_type_with_comments(current, allow_breaks); - return; - } - - // Curried format: a => b => c (single argument with no label) - for (i, arg) in args.iter().enumerate() { - if i > 0 { - self.write(" => "); - } - self.print_core_type_as_arrow_param(&arg.typ, allow_breaks); - } - self.write(" => "); - self.print_core_type_with_comments(current, allow_breaks); - } - - fn print_core_type_as_arrow_param(&mut self, typ: &CoreType, allow_breaks: bool) { - // Wrap arrow types and tuples in parens to disambiguate from multi-param arrow syntax - // Without this, ('a, 'b) => unit would be reparsed as 'a => 'b => unit - if matches!( - typ.ptyp_desc, - CoreTypeDesc::Ptyp_arrow { .. } | CoreTypeDesc::Ptyp_tuple(_) - ) { - self.write("("); - self.print_core_type_with_comments(typ, allow_breaks); - self.write(")"); - } else { - self.print_core_type_with_comments(typ, allow_breaks); - } - } - - fn inline_tuple_len(&self, typs: &[CoreType]) -> usize { - let mut len = 2; // opening and closing parens - for (i, typ) in typs.iter().enumerate() { - if i > 0 { - len += 2; // ", " - } - len += self.inline_type_len(typ); - } - len - } - - fn inline_type_len(&self, typ: &CoreType) -> usize { - let mut printer = Printer::with_width(self.max_width); - printer.print_core_type_inner(typ, false); - printer.output.len() - } - - /// Print a type argument. - fn print_type_arg_with_breaks(&mut self, arg: &TypeArg, allow_breaks: bool) { - let has_attrs = !arg.attrs.is_empty(); - if has_attrs { - self.write("("); - self.print_attributes(&arg.attrs); - } - match &arg.lbl { - ArgLabel::Nolabel => {} - ArgLabel::Labelled(name) | ArgLabel::Optional(name) => { - self.write("~"); - self.write(&name.txt); - self.write(": "); - } - } - self.print_core_type_with_comments(&arg.typ, allow_breaks); - if matches!(arg.lbl, ArgLabel::Optional(_)) { - self.write("=?"); - } - if has_attrs { - self.write(")"); - } - } - - /// Print a row field. - fn print_row_field(&mut self, field: &RowField) { - match field { - RowField::Rtag(label, _attrs, is_const, typs) => { - self.write("#"); - self.write(&label.txt); - if !*is_const && !typs.is_empty() { - self.write("("); - for (i, typ) in typs.iter().enumerate() { - if i > 0 { - self.write(", "); - } - self.print_core_type(typ); - } - self.write(")"); - } - } - RowField::Rinherit(typ) => { - self.print_core_type(typ); - } - } - } - - // ======================================================================== - // Module Printing - // ======================================================================== - - /// Print a module expression. - pub fn print_module_expr(&mut self, modexpr: &ModuleExpr) { - match &modexpr.pmod_desc { - ModuleExprDesc::Pmod_ident(lid) => { - self.print_longident(&lid.txt); - } - ModuleExprDesc::Pmod_structure(items) => { - self.write("{"); - let has_inner_comments = - self.comments_enabled() && self.has_comment_before_loc_end(&modexpr.pmod_loc); - if !items.is_empty() || has_inner_comments { - self.indent(); - for item in items { - self.newline(); - if self.comments_enabled() { - self.print_comments_before_loc(&item.pstr_loc); - } - self.print_structure_item(item); - if self.comments_enabled() { - self.print_trailing_comments_for_loc(&item.pstr_loc); - } - } - if has_inner_comments { - if items.is_empty() { - self.newline(); - } - self.print_comments_before_loc_end(&modexpr.pmod_loc); - } - self.dedent(); - self.newline(); - } - self.write("}"); - } - ModuleExprDesc::Pmod_functor(name, param, body) => { - self.write("("); - self.write(&name.txt); - if let Some(mt) = param { - self.write(": "); - self.print_module_type(mt); - } - self.write(") => "); - self.print_module_expr(body); - } - ModuleExprDesc::Pmod_apply(func, arg) => { - // Check if this is an await expression (has res.await attribute and __await__ functor) - let is_await = modexpr - .pmod_attributes - .iter() - .any(|(n, _)| n.txt == "res.await") - && matches!( - &func.pmod_desc, - ModuleExprDesc::Pmod_ident(lid) if lid.txt.to_string() == "__await__" - ); - if is_await { - self.write("await "); - self.print_module_expr(arg); - } else { - self.print_module_expr(func); - self.write("("); - self.print_module_expr(arg); - self.write(")"); - } - } - ModuleExprDesc::Pmod_constraint(expr, typ) => { - self.write("("); - self.print_module_expr(expr); - self.write(": "); - self.print_module_type(typ); - self.write(")"); - } - ModuleExprDesc::Pmod_unpack(expr) => { - self.write("unpack("); - self.print_expression(expr); - self.write(")"); - } - ModuleExprDesc::Pmod_extension(ext) => { - self.print_extension(ext); - } - } - } - - /// Print a module type. - pub fn print_module_type(&mut self, modtype: &ModuleType) { - match &modtype.pmty_desc { - ModuleTypeDesc::Pmty_ident(lid) => { - self.print_longident(&lid.txt); - } - ModuleTypeDesc::Pmty_signature(items) => { - self.write("{"); - if !items.is_empty() { - self.indent(); - for item in items { - self.newline(); - self.print_signature_item(item); - } - self.dedent(); - self.newline(); - } - self.write("}"); - } - ModuleTypeDesc::Pmty_functor(name, param, body) => { - self.write("("); - self.write(&name.txt); - if let Some(mt) = param { - self.write(": "); - self.print_module_type(mt); - } - self.write(") => "); - self.print_module_type(body); - } - ModuleTypeDesc::Pmty_with(typ, constraints) => { - // If the inner type is also a Pmty_with, we need parentheses - let needs_parens = matches!(typ.pmty_desc, ModuleTypeDesc::Pmty_with(..)); - if needs_parens { - self.write("("); - } - self.print_module_type(typ); - if needs_parens { - self.write(")"); - } - self.write(" with "); - for (i, constraint) in constraints.iter().enumerate() { - if i > 0 { - self.write(" and "); - } - self.print_with_constraint(constraint); - } - } - ModuleTypeDesc::Pmty_typeof(modexpr) => { - self.write("module type of "); - self.print_module_expr(modexpr); - } - ModuleTypeDesc::Pmty_extension(ext) => { - self.write("%"); - self.write(&ext.0.txt); - } - ModuleTypeDesc::Pmty_alias(lid) => { - self.write("module "); - self.print_longident(&lid.txt); - } - } - } - - /// Print a signature (interface file content). - pub fn print_signature(&mut self, signature: &[SignatureItem]) { - let mut prev_loc_end_line = 0; - for (i, item) in signature.iter().enumerate() { - if i > 0 { - // Add blank line only if there was a blank line in the source - let item_start_line = item.psig_loc.loc_start.line; - if item_start_line - prev_loc_end_line > 1 { - self.newline(); - self.newline(); - } else { - self.newline(); - } - } - if self.comments_enabled() { - self.print_comments_before_loc(&item.psig_loc); - } - self.print_signature_item(item); - if self.comments_enabled() { - self.print_trailing_comments_for_loc(&item.psig_loc); - } - prev_loc_end_line = item.psig_loc.loc_end.line; - } - if self.comments_enabled() { - self.flush_remaining_comments(); - } - } - - /// Print a signature item. - pub fn print_signature_item(&mut self, item: &SignatureItem) { - match &item.psig_desc { - SignatureItemDesc::Psig_value(vd) => { - self.print_value_description(vd); - } - SignatureItemDesc::Psig_type(rec_flag, decls) => { - self.print_type_declarations(*rec_flag, decls); - } - SignatureItemDesc::Psig_typext(ext) => { - self.print_type_extension(ext); - } - SignatureItemDesc::Psig_exception(ext) => { - self.write("exception "); - self.print_extension_constructor(ext); - } - SignatureItemDesc::Psig_module(md) => { - self.write("module "); - self.write(&md.pmd_name.txt); - // Handle module alias (module X = M) vs module type annotation (module X: T) - if let ModuleTypeDesc::Pmty_alias(lid) = &md.pmd_type.pmty_desc { - self.write(" = "); - self.print_longident(&lid.txt); - } else { - self.write(": "); - self.print_module_type(&md.pmd_type); - } - } - SignatureItemDesc::Psig_recmodule(mds) => { - for (i, md) in mds.iter().enumerate() { - if i == 0 { - self.write("module rec "); - } else { - self.newline(); - self.write("and "); - } - self.write(&md.pmd_name.txt); - self.write(": "); - self.print_module_type(&md.pmd_type); - } - } - SignatureItemDesc::Psig_modtype(mtd) => { - self.print_module_type_declaration(mtd); - } - SignatureItemDesc::Psig_open(od) => { - self.print_attributes(&od.popen_attributes); - self.write("open"); - if od.popen_override == OverrideFlag::Override { - self.write("!"); - } - self.write(" "); - self.print_longident(&od.popen_lid.txt); - } - SignatureItemDesc::Psig_include(incl) => { - self.write("include "); - self.print_module_type(&incl.pincl_mod); - } - SignatureItemDesc::Psig_attribute(attr) => { - self.write("@@"); - self.print_attribute(attr); - } - SignatureItemDesc::Psig_extension(ext, _attrs) => { - self.write("%"); - self.write(&ext.0.txt); - } - } - } - - /// Print a module binding. - fn print_module_binding(&mut self, mb: &ModuleBinding) { - self.write("module "); - if self.comments_enabled() { - self.print_comments_before_loc(&mb.pmb_name.loc); - } - self.write(&mb.pmb_name.txt); - if self.comments_enabled() { - self.print_trailing_comments_for_loc(&mb.pmb_name.loc); - } - self.write(" = "); - self.print_module_expr(&mb.pmb_expr); - } - - /// Print a module type declaration. - fn print_module_type_declaration(&mut self, mtd: &ModuleTypeDeclaration) { - self.write("module type "); - if self.comments_enabled() { - self.print_comments_before_loc(&mtd.pmtd_name.loc); - } - self.write(&mtd.pmtd_name.txt); - if self.comments_enabled() { - self.print_trailing_comments_for_loc(&mtd.pmtd_name.loc); - } - if let Some(typ) = &mtd.pmtd_type { - self.write(" = "); - self.print_module_type(typ); - } - } - - /// Print a with constraint. - fn print_with_constraint(&mut self, constraint: &WithConstraint) { - match constraint { - WithConstraint::Pwith_type(lid, decl) => { - self.write("type "); - self.print_longident(&lid.txt); - self.write(" = "); - if let Some(manifest) = &decl.ptype_manifest { - self.print_core_type(manifest); - } - } - WithConstraint::Pwith_module(lid1, lid2) => { - self.write("module "); - self.print_longident(&lid1.txt); - self.write(" = "); - self.print_longident(&lid2.txt); - } - WithConstraint::Pwith_typesubst(lid, decl) => { - self.write("type "); - self.print_longident(&lid.txt); - self.write(" := "); - if let Some(manifest) = &decl.ptype_manifest { - self.print_core_type(manifest); - } - } - WithConstraint::Pwith_modsubst(lid1, lid2) => { - self.write("module "); - self.print_longident(&lid1.txt); - self.write(" := "); - self.print_longident(&lid2.txt); - } - } - } - - // ======================================================================== - // Type Declarations - // ======================================================================== - - /// Print type declarations. - fn print_type_declarations(&mut self, rec_flag: RecFlag, decls: &[TypeDeclaration]) { - for (i, decl) in decls.iter().enumerate() { - // Print type declaration attributes before the type keyword - for attr in &decl.ptype_attributes { - if !Self::is_internal_attribute(attr) { - self.write("@"); - self.print_attribute(attr); - self.newline(); - } - } - if i == 0 { - self.write("type "); - if rec_flag == RecFlag::Recursive && decls.len() > 1 { - self.write("rec "); - } - } else { - self.newline(); - self.write("and "); - } - self.print_type_declaration(decl); - } - } - - /// Print a single type declaration. - fn print_type_declaration(&mut self, decl: &TypeDeclaration) { - // Print type name first (ReScript style: type option<'a> not 'a option) - if self.comments_enabled() { - self.print_comments_before_loc(&decl.ptype_name.loc); - } - // Use write_ident to escape keywords (e.g., type \"import" = ...) - self.write_ident(&decl.ptype_name.txt); - if self.comments_enabled() { - self.print_trailing_comments_for_loc(&decl.ptype_name.loc); - } - - // Print type parameters in angle brackets (ReScript style) - if !decl.ptype_params.is_empty() { - self.write("<"); - for (i, (typ, _var)) in decl.ptype_params.iter().enumerate() { - if i > 0 { - self.write(", "); - } - self.print_core_type(typ); - } - self.write(">"); - } - - // Print kind or manifest - match &decl.ptype_kind { - TypeKind::Ptype_abstract => { - if let Some(manifest) = &decl.ptype_manifest { - self.write(" = "); - if decl.ptype_private == PrivateFlag::Private { - self.write("private "); - } - self.print_core_type(manifest); - } - } - TypeKind::Ptype_variant(constructors) => { - // Print manifest if present (e.g., type t = User.t = ...) - if let Some(manifest) = &decl.ptype_manifest { - self.write(" = "); - self.print_core_type(manifest); - } - self.write(" ="); - if decl.ptype_private == PrivateFlag::Private { - self.write(" private"); - } - self.print_constructor_declarations(constructors, &decl.ptype_loc); - } - TypeKind::Ptype_record(fields) => { - // Print manifest if present (e.g., type t = User.t = {...}) - if let Some(manifest) = &decl.ptype_manifest { - self.write(" = "); - self.print_core_type(manifest); - } - self.write(" = "); - if decl.ptype_private == PrivateFlag::Private { - self.write("private "); - } - self.print_record_declaration(fields, &decl.ptype_loc); - } - TypeKind::Ptype_open => { - self.write(" = "); - if decl.ptype_private == PrivateFlag::Private { - self.write("private "); - } - self.write(".."); - } - } - - // Print type constraints - self.print_type_constraints(&decl.ptype_cstrs); - } - - /// Print constructor declarations for a variant type. - fn print_constructor_declarations( - &mut self, - constructors: &[ConstructorDeclaration], - loc: &Location, - ) { - if constructors.is_empty() { - return; - } - - // Check if the variant should be printed on multiple lines - // Based on whether it spans multiple lines in the source - let force_break = if let (Some(first), Some(last)) = - (constructors.first(), constructors.last()) - { - first.pcd_loc.loc_start.line < last.pcd_loc.loc_end.line - } else { - false - }; - - if force_break { - // Multi-line format with pipe before each constructor - for ctor in constructors { - self.newline(); - self.write(" | "); - self.print_constructor_declaration(ctor); - } - } else { - // Single-line format - self.write(" "); - for (i, ctor) in constructors.iter().enumerate() { - if i > 0 { - self.write(" | "); - } - self.print_constructor_declaration(ctor); - } - } - } - - /// Print type constraints (constraint 'a = 'b). - fn print_type_constraints(&mut self, cstrs: &[(CoreType, CoreType, Location)]) { - for (t1, t2, _loc) in cstrs { - self.write(" constraint "); - self.print_core_type(t1); - self.write(" = "); - self.print_core_type(t2); - } - } - - /// Print a record declaration with proper formatting. - /// Uses single-line format for short records and multi-line for longer ones. - fn print_record_declaration(&mut self, fields: &[LabelDeclaration], loc: &Location) { - if fields.is_empty() { - self.write("{}"); - return; - } - - // Check if the record should be printed on multiple lines - // Based on whether it spans multiple lines in the source - let force_break = loc.loc_start.line < loc.loc_end.line; - - if force_break { - // Multi-line format - self.write("{"); - for field in fields { - self.newline(); - self.write(" "); - self.print_label_declaration(field); - self.write(","); - } - self.newline(); - self.write("}"); - } else { - // Single-line format - self.write("{"); - for (i, field) in fields.iter().enumerate() { - if i > 0 { - self.write(", "); - } - self.print_label_declaration(field); - } - self.write("}"); - } - } - - /// Print a constructor declaration. - fn print_constructor_declaration(&mut self, ctor: &ConstructorDeclaration) { - if self.comments_enabled() { - self.print_comments_before_loc(&ctor.pcd_loc); - } - // Handle spread syntax: ...typeName - if ctor.pcd_name.txt == "..." { - self.write("..."); - if let ConstructorArguments::Pcstr_tuple(typs) = &ctor.pcd_args { - if let Some(typ) = typs.first() { - self.print_core_type(typ); - } - } - if self.comments_enabled() { - self.print_trailing_comments_for_loc(&ctor.pcd_loc); - } - return; - } - // Constructor names are not escaped - they're expected to start with uppercase - self.write(&ctor.pcd_name.txt); - if self.comments_enabled() { - self.print_trailing_comments_for_loc(&ctor.pcd_name.loc); - } - match &ctor.pcd_args { - ConstructorArguments::Pcstr_tuple(typs) if !typs.is_empty() => { - self.write("("); - for (i, typ) in typs.iter().enumerate() { - if i > 0 { - self.write(", "); - } - self.print_core_type(typ); - } - self.write(")"); - } - ConstructorArguments::Pcstr_record(fields) => { - self.write("{"); - for (i, field) in fields.iter().enumerate() { - if i > 0 { - self.write(", "); - } - self.print_label_declaration(field); - } - self.write("}"); - } - _ => {} - } - if let Some(res) = &ctor.pcd_res { - self.write(": "); - self.print_core_type(res); - } - if self.comments_enabled() { - self.print_trailing_comments_for_loc(&ctor.pcd_loc); - } - } - - /// Print a label declaration. - fn print_label_declaration(&mut self, field: &LabelDeclaration) { - if self.comments_enabled() { - self.print_comments_before_loc(&field.pld_loc); - } - // Print attributes inline before the field - self.print_attributes_inline(&field.pld_attributes); - if field.pld_mutable == MutableFlag::Mutable { - self.write("mutable "); - } - if self.comments_enabled() { - self.print_comments_before_loc(&field.pld_name.loc); - } - // Use write_ident to escape keywords like "module", "let", etc. - self.write_ident(&field.pld_name.txt); - // Print optional marker after field name - if field.pld_optional { - self.write("?"); - } - if self.comments_enabled() { - self.print_trailing_comments_for_loc(&field.pld_name.loc); - } - self.write(": "); - self.print_core_type(&field.pld_type); - if self.comments_enabled() { - self.print_trailing_comments_for_loc(&field.pld_loc); - } - } - - /// Print attributes inline (without newlines). - fn print_attributes_inline(&mut self, attrs: &Attributes) { - for attr in attrs { - if !Self::is_internal_attribute(attr) { - self.write("@"); - self.print_attribute(attr); - self.write(" "); - } - } - } - - /// Print an extension constructor. - fn print_extension_constructor(&mut self, ext: &ExtensionConstructor) { - if self.comments_enabled() { - self.print_comments_before_loc(&ext.pext_loc); - } - self.write(&ext.pext_name.txt); - if self.comments_enabled() { - self.print_trailing_comments_for_loc(&ext.pext_name.loc); - } - match &ext.pext_kind { - ExtensionConstructorKind::Pext_decl(args, res) => { - match args { - ConstructorArguments::Pcstr_tuple(typs) if !typs.is_empty() => { - self.write("("); - for (i, typ) in typs.iter().enumerate() { - if i > 0 { - self.write(", "); - } - self.print_core_type(typ); - } - self.write(")"); - } - ConstructorArguments::Pcstr_record(fields) => { - self.write("{"); - for (i, field) in fields.iter().enumerate() { - if i > 0 { - self.write(", "); - } - self.print_label_declaration(field); - } - self.write("}"); - } - _ => {} - } - if let Some(res) = res { - self.write(": "); - self.print_core_type(res); - } - } - ExtensionConstructorKind::Pext_rebind(lid) => { - self.write(" = "); - self.print_longident(&lid.txt); - } - } - if self.comments_enabled() { - self.print_trailing_comments_for_loc(&ext.pext_loc); - } - } - - /// Print a type extension. - fn print_type_extension(&mut self, ext: &TypeExtension) { - self.write("type "); - // Use print_lident to escape keywords in the type path - self.print_lident(&ext.ptyext_path.txt); - - // Print type parameters if any - if !ext.ptyext_params.is_empty() { - self.write("<"); - for (i, (typ, _variance)) in ext.ptyext_params.iter().enumerate() { - if i > 0 { - self.write(", "); - } - self.print_core_type(typ); - } - self.write(">"); - } - - self.write(" +="); - if ext.ptyext_private == PrivateFlag::Private { - self.write(" private"); - } - - // Determine if we should break to a new line - // Based on OCaml: break if first constructor is on different line than path ends, - // or if constructors span multiple lines - let force_break = match ( - ext.ptyext_constructors.first(), - ext.ptyext_constructors.last(), - ) { - (Some(first), Some(last)) => { - first.pext_loc.loc_start.line > ext.ptyext_path.loc.loc_end.line - || first.pext_loc.loc_start.line < last.pext_loc.loc_end.line - } - _ => false, - }; - - if force_break { - for ctor in &ext.ptyext_constructors { - self.newline(); - self.write("| "); - self.print_extension_constructor(ctor); - } - } else { - // Single constructor on same line - print inline with space - for (i, ctor) in ext.ptyext_constructors.iter().enumerate() { - if i > 0 { - self.newline(); - self.write("| "); - } else { - self.write(" "); - } - self.print_extension_constructor(ctor); - } - } - } - - /// Print a value description. - fn print_value_description(&mut self, vd: &ValueDescription) { - // Print attributes first - self.print_attributes(&vd.pval_attributes); - - // "external" if there are primitives, otherwise "let" - let is_external = !vd.pval_prim.is_empty(); - if is_external { - self.write("external "); - } else { - self.write("let "); - } - - if self.comments_enabled() { - self.print_comments_before_loc(&vd.pval_name.loc); - } - self.write_ident(&vd.pval_name.txt); - if self.comments_enabled() { - self.print_trailing_comments_for_loc(&vd.pval_name.loc); - } - self.write(": "); - self.print_core_type(&vd.pval_type); - - if is_external { - self.write(" = "); - for (i, prim) in vd.pval_prim.iter().enumerate() { - if i > 0 { - self.space(); - } - self.write("\""); - self.write(prim); - self.write("\""); - } - } - } - - // ======================================================================== - // JSX - // ======================================================================== - - /// Print a JSX element. - fn print_jsx_element(&mut self, elem: &JsxElement) { - match elem { - JsxElement::Unary(unary) => { - self.write("<"); - self.print_jsx_tag_name(&unary.tag_name.txt); - for prop in &unary.props { - self.space(); - self.print_jsx_prop(prop); - } - self.write(" />"); - } - JsxElement::Container(container) => { - self.write("<"); - self.print_jsx_tag_name(&container.tag_name_start.txt); - for prop in &container.props { - self.space(); - self.print_jsx_prop(prop); - } - self.write(">"); - for child in &container.children { - self.print_jsx_child(child); - } - self.write(""); - } - JsxElement::Fragment(fragment) => { - self.write("<>"); - for child in &fragment.children { - self.print_jsx_child(child); - } - self.write(""); - } - } - } - - /// Print a JSX child expression. - /// JSX elements and exotic identifiers don't need braces. - fn print_jsx_child(&mut self, child: &Expression) { - match &child.pexp_desc { - // JSX elements don't need braces - ExpressionDesc::Pexp_jsx_element(_) => { - self.print_expression(child); - } - // Exotic identifiers can be printed bare in JSX - ExpressionDesc::Pexp_ident(lid) => { - if let Longident::Lident(name) = &lid.txt { - if name.starts_with('"') && name.ends_with('"') { - // Exotic identifier - print with backslash prefix - self.write(" "); - self.write_ident(name); - return; - } - } - // Regular identifiers need braces - self.write("{"); - self.print_expression(child); - self.write("}"); - } - // String constants don't need braces in JSX - ExpressionDesc::Pexp_constant(Constant::String(s, delim)) => { - self.write(" "); - if let Some(d) = delim { - self.write(d); - self.write(s); - self.write(d); - } else { - self.write("\""); - self.write(s); - self.write("\""); - } - } - // Other expressions need braces - _ => { - // Strip res.braces attribute since we're adding our own braces - let stripped = Self::strip_braces_attribute(child); - self.write(" {"); - self.print_expression(&stripped); - self.write("} "); - } - } - } - - /// Print a JSX tag name. - fn print_jsx_tag_name(&mut self, name: &JsxTagName) { - match name { - JsxTagName::Lower(s) => self.write(s), - JsxTagName::QualifiedLower { path, name } => { - self.print_longident(path); - self.write("."); - self.write(name); - } - JsxTagName::Upper(lid) => self.print_longident(lid), - JsxTagName::Invalid(s) => self.write(s), - } - } - - /// Print a JSX prop. - fn print_jsx_prop(&mut self, prop: &JsxProp) { - match prop { - JsxProp::Value { - name, - optional, - value, - } => { - self.write_ident(&name.txt); - if *optional { - self.write("=?"); - } else { - self.write("="); - } - // Check if the value is a string constant - print without braces - if let ExpressionDesc::Pexp_constant(Constant::String(s, delim)) = &value.pexp_desc - { - // For string constants, print directly as "value" - let needs_escape = delim.is_none(); - if needs_escape { - self.write("\""); - self.write(s); - self.write("\""); - } else if let Some(d) = delim { - self.write(d); - self.write(s); - self.write(d); - } - } else if let ExpressionDesc::Pexp_ident(lid) = &value.pexp_desc { - // Check if it's an exotic identifier (quoted name) - if let Longident::Lident(ident_name) = &lid.txt { - if ident_name.starts_with('"') && ident_name.ends_with('"') { - // Exotic identifier - print as string value "value" - self.write_ident(ident_name); - return; - } - } - // Regular identifier - needs braces - self.write("{"); - self.print_expression(value); - self.write("}"); - } else { - self.write("{"); - self.print_expression(value); - self.write("}"); - } - } - JsxProp::Punning { optional, name } => { - if *optional { - self.write("?"); - } - self.write_ident(&name.txt); - } - JsxProp::Spreading { expr, .. } => { - self.write("{..."); - self.print_expression(expr); - self.write("}"); - } - } - } - - // ======================================================================== - // Helpers - // ======================================================================== - - /// Print a longident. - /// Print a longident without any escaping. - /// This is used for module paths where all segments are expected to be valid module names. - /// Matches OCaml's print_longident function. - fn print_longident(&mut self, lid: &Longident) { - match lid { - Longident::Lident(s) => self.write(s), - Longident::Ldot(prefix, s) => { - self.print_longident(prefix); - self.write("."); - self.write(s); - } - Longident::Lapply(f, arg) => { - self.print_longident(f); - self.write("("); - self.print_longident(arg); - self.write(")"); - } - } - } - - /// Print a longident with escaping for the final segment only. - /// Path segments (module names) are not escaped, but the final segment is escaped - /// if it's a keyword or exotic identifier. - /// Matches OCaml's print_lident function. - fn print_lident(&mut self, lid: &Longident) { - match lid { - Longident::Lident(s) => self.write_ident(s), - Longident::Ldot(prefix, s) => { - // Print the prefix path without escaping - self.print_longident_path_only(prefix); - self.write("."); - // Escape the final segment - self.write_ident(s); - } - Longident::Lapply(_, _) => { - // Lapply is not supported for lident - self.write("printLident: Longident.Lapply is not supported"); - } - } - } - - /// Print the path part of a longident (all segments except final) without escaping. - fn print_longident_path_only(&mut self, lid: &Longident) { - match lid { - Longident::Lident(s) => self.write(s), - Longident::Ldot(prefix, s) => { - self.print_longident_path_only(prefix); - self.write("."); - self.write(s); - } - Longident::Lapply(f, arg) => { - self.print_longident_path_only(f); - self.write("("); - self.print_longident_path_only(arg); - self.write(")"); - } - } - } - - /// Print a constant. - fn print_constant(&mut self, c: &Constant) { - match c { - Constant::Integer(s, suffix) => { - self.write(s); - if let Some(suffix) = suffix { - self.write(&suffix.to_string()); - } - } - Constant::Char(code) => { - // Print simple printable ASCII characters directly, others as Unicode escapes - let c = if *code >= 0 { - char::from_u32(*code as u32) - } else { - None - }; - match c { - Some(ch) if ch.is_ascii() && !ch.is_ascii_control() && ch != '\'' && ch != '\\' => { - self.write(&format!("'{}'", ch)); - } - Some('\\') => { - self.write("'\\\\'"); - } - Some('\'') => { - self.write("'\\''"); - } - Some('\n') => { - self.write("'\\n'"); - } - Some('\r') => { - self.write("'\\r'"); - } - Some('\t') => { - self.write("'\\t'"); - } - _ => { - self.write(&format!("'\\u{{{:04x}}}'", code)); - } - } - } - Constant::String(s, _delim) => { - self.write("\""); - // The string is stored exactly as it appeared in source (between quotes), - // so we output it directly. The escape sequences are already present. - self.write(s); - self.write("\""); - } - Constant::Float(s, suffix) => { - self.write(s); - if let Some(suffix) = suffix { - self.write(&suffix.to_string()); - } - } - } - } - - /// Print a function expression, collecting all parameters and handling labeled args properly. - fn print_fun_expr(&mut self, expr: &Expression) { - // Collect all function parameters along with their attributes - // Stop collecting when we encounter a Pexp_fun with its own attributes - // (those should be printed as nested arrow functions) - let mut params: Vec<(&Attributes, &ArgLabel, Option<&Expression>, &Pattern)> = Vec::new(); - let mut current = expr; - let mut first = true; - - while let ExpressionDesc::Pexp_fun { - arg_label, - default, - lhs, - rhs, - .. - } = ¤t.pexp_desc - { - // Stop collecting if this Pexp_fun has attributes (except for the first one, - // whose attributes are printed as an outer wrapper by the caller) - if !first && !current.pexp_attributes.is_empty() { - break; - } - first = false; - params.push((¤t.pexp_attributes, arg_label, default.as_deref(), lhs)); - current = rhs; - } - - let has_unit_param = params.len() == 1 && Self::is_unit_pattern(params[0].3); - - // Check if there's a return type annotation (body is a constraint) - let has_return_type = matches!( - ¤t.pexp_desc, - ExpressionDesc::Pexp_constraint(_, _) - ); - - // Check if we need parentheses: - // - Any labeled parameter - // - Multiple parameters - // - Any default value - // - Any parameter with attributes - // - Return type annotation (to distinguish (a): int => x from a: int => x) - // A single unit pattern doesn't need extra parens - it already has () - let has_complex_single_param = params.len() == 1 - && !Self::is_simple_arrow_param(params[0].3) - && !Self::is_unit_pattern(params[0].3); - // Check if any pattern has attributes (ppat_attributes) - let has_attrs = params.iter().any(|(_, _, _, pat)| !pat.ppat_attributes.is_empty()); - let needs_parens = params.len() > 1 - || params - .iter() - .any(|(_, label, default, _)| !matches!(label, ArgLabel::Nolabel) || default.is_some()); - let needs_parens = needs_parens || has_complex_single_param || has_attrs || has_return_type; - - // Print parameters - if needs_parens { - self.write("("); - } - - for (i, (_attrs, label, default, pat)) in params.iter().enumerate() { - if i > 0 { - self.write(", "); - } - // Note: expression attributes (from Pexp_fun.pexp_attributes) are NOT printed here. - // The first Pexp_fun's attributes are printed by the caller (print_expression_inner). - // Pattern attributes (ppat_attributes) are printed in print_fun_param. - self.print_fun_param(label, *default, pat); - } - - if needs_parens { - self.write(")"); - } - - // Check if the body is a constraint - if so, print as return type annotation - // (params): type => body instead of (params) => (body: type) - if let ExpressionDesc::Pexp_constraint(inner_body, return_type) = ¤t.pexp_desc { - self.write(": "); - self.print_core_type(return_type); - self.write(" => "); - // Function body: sequences need braces, other complex expressions don't need parens - self.print_function_body(inner_body); - } else { - self.write(" => "); - // Function body: sequences need braces, other complex expressions don't need parens - self.print_function_body(current); - } - } - - /// Print a function body expression. - /// Sequences need braces, other complex expressions don't need parens. - fn print_function_body(&mut self, body: &Expression) { - // Check for sequences - they need braces - if matches!(&body.pexp_desc, ExpressionDesc::Pexp_sequence(..)) { - self.write("{"); - self.indent(); - self.newline(); - self.print_block_body_inner(body, false); - self.dedent(); - self.newline(); - self.write("}"); - } else if let ExpressionDesc::Pexp_fun { is_async, .. } = &body.pexp_desc { - // For nested arrow functions with attributes (like `@attr (c, d) => ()`), - // we need to print the attributes and the function without extra parens. - // First print any non-internal attributes - for attr in &body.pexp_attributes { - if !Self::is_internal_attribute(attr) { - self.write("@"); - self.print_attribute(attr); - self.space(); - } - } - if *is_async { - self.write("async "); - } - self.print_fun_expr(body); - } else { - // Other expressions don't need parens in function body context - self.print_expression_with_comments(body, false); - } - } - - fn is_simple_arrow_param(pat: &Pattern) -> bool { - matches!(&pat.ppat_desc, PatternDesc::Ppat_var(_) | PatternDesc::Ppat_any) - } - - /// Print a single function parameter, using punning when possible. - fn print_fun_param(&mut self, label: &ArgLabel, default: Option<&Expression>, pat: &Pattern) { - match label { - ArgLabel::Nolabel => { - self.print_pattern(pat); - if let Some(def) = default { - self.write("="); - self.print_expression(def); - } - } - ArgLabel::Labelled(name) => { - // For labeled args, pattern attributes are printed in two cases: - // 1. If punned (no alias): print attrs before ~label - // 2. If not punned (has alias): print attrs as part of the aliased pattern - // This avoids double-printing attributes. - let (is_punned, _) = Self::punned_pattern_type(&name.txt, pat); - if is_punned { - // Print pattern attributes before the label only when punned - for attr in &pat.ppat_attributes { - self.write("@"); - self.print_attribute(attr); - self.write(" "); - } - } - self.write("~"); - self.write_ident(&name.txt); - let (is_punned, punned_type) = Self::punned_pattern_type(&name.txt, pat); - if let Some(typ) = punned_type { - self.write(": "); - self.print_core_type(typ); - } else if !is_punned { - self.write(" as "); - self.print_pattern(pat); - } - if let Some(def) = default { - self.write("="); - self.print_expression(def); - } - } - ArgLabel::Optional(name) => { - // For optional args, pattern attributes are printed in two cases: - // 1. If punned (no alias): print attrs before ~label - // 2. If not punned (has alias): print attrs as part of the aliased pattern - let (is_punned, _) = Self::punned_pattern_type(&name.txt, pat); - if is_punned { - for attr in &pat.ppat_attributes { - self.write("@"); - self.print_attribute(attr); - self.write(" "); - } - } - self.write("~"); - self.write_ident(&name.txt); - let (is_punned, punned_type) = Self::punned_pattern_type(&name.txt, pat); - if let Some(typ) = punned_type { - self.write(": "); - self.print_core_type(typ); - } else if !is_punned { - self.write(" as "); - self.print_pattern(pat); - } - if let Some(def) = default { - self.write("="); - self.print_expression(def); - } else { - self.write("=?"); - } - } - } - } - - /// Check if pattern is a simple variable with the same name (for punning). - fn is_punned_pattern(name: &str, pat: &Pattern) -> bool { - match &pat.ppat_desc { - PatternDesc::Ppat_var(var) => var.txt == name, - PatternDesc::Ppat_constraint(inner, _) => Self::is_punned_pattern(name, inner), - _ => false, - } - } - - fn punned_pattern_type<'a>(name: &str, pat: &'a Pattern) -> (bool, Option<&'a CoreType>) { - match &pat.ppat_desc { - PatternDesc::Ppat_constraint(inner, typ) if Self::is_punned_pattern(name, inner) => { - (true, Some(typ)) - } - _ => (Self::is_punned_pattern(name, pat), None), - } - } - - /// Print an argument label (used for function application arguments). - fn print_arg_label(&mut self, label: &ArgLabel) { - match label { - ArgLabel::Nolabel => {} - ArgLabel::Labelled(s) => { - self.write("~"); - self.write_ident(&s.txt); - self.write("="); - } - ArgLabel::Optional(s) => { - self.write("~"); - self.write_ident(&s.txt); - self.write("=?"); - } - } - } - - /// Print attributes. - fn print_attributes(&mut self, attrs: &Attributes) { - self.print_attributes_with_sep(attrs, true); - } - - /// Print attributes with optional newline separator. - /// If `with_newline` is true, each attribute ends with a newline. - /// If false, each attribute ends with a space. - fn print_attributes_with_sep(&mut self, attrs: &Attributes, with_newline: bool) { - for attr in attrs { - if Self::is_internal_attribute(attr) { - continue; - } - self.write("@"); - self.print_attribute(attr); - if with_newline { - self.newline(); - } else { - self.write(" "); - } - } - } - - /// Print a single attribute (without the @ prefix). - fn print_attribute(&mut self, attr: &Attribute) { - self.write(&attr.0.txt); - match &attr.1 { - Payload::PStr(items) if items.is_empty() => {} - Payload::PStr(items) => { - // Check if it's a simple string payload like @as("foo") - if items.len() == 1 { - if let StructureItemDesc::Pstr_eval(expr, _) = &items[0].pstr_desc { - if let ExpressionDesc::Pexp_constant(Constant::String(s, _)) = - &expr.pexp_desc - { - self.write("(\""); - self.write(s); - self.write("\")"); - return; - } - } - } - // Fallback for complex payloads - self.write("("); - for item in items { - self.print_structure_item(item); - } - self.write(")"); - } - _ => { - self.write("(...)"); - } - } - } - - /// Print a single attribute with @ prefix. - fn print_attribute_with_at(&mut self, attr: &Attribute) { - self.write("@"); - self.print_attribute(attr); - } - - /// Print an extension (name + payload). - fn print_extension(&mut self, ext: &Extension) { - self.write("%"); - self.write_ident(&ext.0.txt); - self.print_extension_payload(&ext.1); - } - - fn print_extension_payload(&mut self, payload: &Payload) { - match payload { - Payload::PStr(items) => { - if !items.is_empty() { - self.write("("); - for item in items { - self.print_structure_item(item); - } - self.write(")"); - } - } - Payload::PSig(_) => self.write("(: ...)"), - Payload::PTyp(typ) => { - self.write("(: "); - self.print_core_type(typ); - self.write(")"); - } - Payload::PPat(pat, expr) => { - self.write("("); - self.print_pattern(pat); - if let Some(e) = expr { - self.write(" when "); - self.print_expression(e); - } - self.write(")"); - } - } - } -} - -// Implement get_attributes for StructureItemDesc -impl StructureItemDesc { - fn get_attributes(&self) -> Attributes { - match self { - StructureItemDesc::Pstr_eval(_, attrs) => attrs.clone(), - StructureItemDesc::Pstr_extension(_, attrs) => attrs.clone(), - StructureItemDesc::Pstr_primitive(vd) => vd.pval_attributes.clone(), - StructureItemDesc::Pstr_module(mb) => mb.pmb_attributes.clone(), - StructureItemDesc::Pstr_open(od) => od.popen_attributes.clone(), - StructureItemDesc::Pstr_include(id) => id.pincl_attributes.clone(), - StructureItemDesc::Pstr_modtype(mtd) => mtd.pmtd_attributes.clone(), - StructureItemDesc::Pstr_typext(te) => te.ptyext_attributes.clone(), - StructureItemDesc::Pstr_exception(ec) => ec.pext_attributes.clone(), - // Type and value have their attributes on individual items within the vec - // These are handled separately in their specific print functions - _ => vec![], - } - } -} - -// ============================================================================ -// Convenience Functions -// ============================================================================ - -/// Print a structure to a string. -pub fn print_structure(structure: &Structure) -> String { - let mut printer = Printer::new(); - printer.print_structure(structure); - printer.into_output() -} - -pub fn print_structure_with_width(structure: &Structure, max_width: usize) -> String { - let mut printer = Printer::with_width(max_width); - printer.print_structure(structure); - printer.into_output() -} - -pub fn print_structure_with_comments(structure: &Structure, comments: &[Comment]) -> String { - let mut printer = Printer::with_comments(comments.to_vec()); - printer.print_structure(structure); - printer.into_output() -} - -pub fn print_structure_with_comments_and_width( - structure: &Structure, - comments: &[Comment], - max_width: usize, -) -> String { - let mut printer = Printer::with_comments_and_width(comments.to_vec(), max_width); - printer.print_structure(structure); - printer.into_output() -} - -/// Print an expression to a string. -pub fn print_expression(expr: &Expression) -> String { - let mut printer = Printer::new(); - printer.print_expression(expr); - printer.into_output() -} - -/// Print a pattern to a string. -pub fn print_pattern(pat: &Pattern) -> String { - let mut printer = Printer::new(); - printer.print_pattern(pat); - printer.into_output() -} - -/// Print a core type to a string. -pub fn print_core_type(typ: &CoreType) -> String { - let mut printer = Printer::new(); - printer.print_core_type(typ); - printer.into_output() -} - -/// Print a signature (interface file) to a string. -pub fn print_signature(signature: &[SignatureItem]) -> String { - let mut printer = Printer::new(); - printer.print_signature(signature); - printer.into_output() -} - -// ============================================================================ -// Tests -// ============================================================================ - -#[cfg(test)] -mod tests { - use super::*; - use crate::parser::{Parser, module}; - use std::sync::mpsc; - use std::thread; - use std::time::Duration; - - /// Default timeout for parsing operations (5 seconds - very generous for ms-scale ops) - const PARSE_TIMEOUT: Duration = Duration::from_secs(5); - - /// Parse and print source code with a timeout. - /// Panics if parsing/printing takes longer than PARSE_TIMEOUT. - fn roundtrip(source: &str) -> String { - let source_owned = source.to_string(); - let source_for_error = source_owned.clone(); - let (tx, rx) = mpsc::channel(); - - thread::spawn(move || { - let mut parser = Parser::new("test.res", &source_owned); - let structure = module::parse_structure(&mut parser); - let result = print_structure_with_comments(&structure, parser.comments()); - let _ = tx.send(result); - }); - - match rx.recv_timeout(PARSE_TIMEOUT) { - Ok(result) => result, - Err(mpsc::RecvTimeoutError::Timeout) => { - panic!( - "Parser timed out after {:?} for input: {}", - PARSE_TIMEOUT, - if source_for_error.len() > 100 { - format!("{}...", &source_for_error[..100]) - } else { - source_for_error - } - ) - } - Err(mpsc::RecvTimeoutError::Disconnected) => { - panic!("Parser thread panicked for input: {}", source_for_error) - } - } - } - - fn roundtrip_twice(source: &str) -> String { - let first = roundtrip(source); - let second = roundtrip(&first); - assert_eq!(first, second, "Roundtrip not idempotent"); - first - } - - fn roundtrip_with_width(source: &str, max_width: usize) -> String { - let source_owned = source.to_string(); - let source_for_error = source_owned.clone(); - let (tx, rx) = mpsc::channel(); - - thread::spawn(move || { - let mut parser = Parser::new("test.res", &source_owned); - let structure = module::parse_structure(&mut parser); - let result = - print_structure_with_comments_and_width(&structure, parser.comments(), max_width); - let _ = tx.send(result); - }); - - match rx.recv_timeout(PARSE_TIMEOUT) { - Ok(result) => result, - Err(mpsc::RecvTimeoutError::Timeout) => { - panic!( - "Parser timed out after {:?} for input: {}", - PARSE_TIMEOUT, - if source_for_error.len() > 100 { - format!("{}...", &source_for_error[..100]) - } else { - source_for_error - } - ) - } - Err(mpsc::RecvTimeoutError::Disconnected) => { - panic!("Parser thread panicked for input: {}", source_for_error) - } - } - } - - #[test] - fn test_print_let_binding() { - let result = roundtrip("let x = 42"); - assert!(result.contains("let x = 42")); - } - - #[test] - fn test_print_let_binding_with_string() { - let result = roundtrip("let s = \"hello\""); - assert!(result.contains("let s = \"hello\"")); - } - - #[test] - fn test_print_type_declaration() { - let result = roundtrip("type t = int"); - assert!(result.contains("type t = int")); - } - - #[test] - fn test_print_variant_type() { - let result = roundtrip("type color = | Red | Green | Blue"); - assert!(result.contains("type color =")); - assert!(result.contains("| Red")); - assert!(result.contains("| Green")); - assert!(result.contains("| Blue")); - } - - #[test] - fn test_print_record_type() { - let result = roundtrip("type person = { name: string, age: int }"); - assert!(result.contains("type person = {")); - assert!(result.contains("name: string")); - assert!(result.contains("age: int")); - } - - #[test] - fn test_print_open() { - let result = roundtrip("open Belt"); - assert!(result.contains("open Belt")); - } - - #[test] - fn test_print_module() { - let result = roundtrip("module M = { let x = 1 }"); - assert!(result.contains("module M = {")); - assert!(result.contains("let x = 1")); - } - - #[test] - fn test_print_external() { - let result = roundtrip("external log: string => unit = \"console.log\""); - assert!(result.contains("external log: string => unit")); - assert!(result.contains("\"console.log\"")); - } - - #[test] - fn test_print_exception() { - let result = roundtrip("exception MyError"); - assert!(result.contains("exception MyError")); - } - - #[test] - fn test_print_array() { - let result = roundtrip("let arr = [1, 2, 3]"); - assert!(result.contains("[1, 2, 3]")); - } - - #[test] - fn test_print_tuple() { - let result = roundtrip("let t = (1, 2)"); - assert!(result.contains("(1, 2)")); - } - - #[test] - fn test_print_if() { - let result = roundtrip("let x = if true { 1 } else { 2 }"); - assert!(result.contains("if true")); - } - - #[test] - fn test_print_switch() { - let result = roundtrip("let x = switch y { | 1 => true | _ => false }"); - assert!(result.contains("switch y")); - assert!(result.contains("| 1 => true")); - } - - #[test] - fn test_printer_is_send_sync() { - fn assert_send_sync() {} - assert_send_sync::(); - } - - // Additional roundtrip tests - - #[test] - fn test_print_function() { - let result = roundtrip("let f = (x) => x + 1"); - assert!(result.contains("=>")); - } - - #[test] - fn test_print_function_application() { - let result = roundtrip("let y = f(1, 2)"); - assert!(result.contains("f(1, 2)")); - } - - #[test] - fn test_print_record_expression() { - let result = roundtrip("let r = {name: \"test\", age: 30}"); - assert!(result.contains("name:")); - assert!(result.contains("age:")); - } - - #[test] - fn test_print_field_access() { - let result = roundtrip("let n = person.name"); - assert!(result.contains("person.name")); - } - - #[test] - fn test_print_while_loop() { - let result = roundtrip("let _ = while true { () }"); - assert!(result.contains("while true")); - } - - #[test] - fn test_print_for_loop() { - let result = roundtrip("for i in 0 to 10 { () }"); - assert!(result.contains("for i in")); - assert!(result.contains("to")); - } - - #[test] - fn test_print_polymorphic_variant() { - let result = roundtrip("let x = #Red"); - assert!(result.contains("#Red") || result.contains("Red")); - } - - #[test] - fn test_print_try_catch() { - let result = roundtrip("let x = try f() catch { | Exn => 0 }"); - assert!(result.contains("try")); - assert!(result.contains("catch")); - } - - #[test] - fn test_print_type_with_params() { - // ReScript uses angle bracket syntax for type parameters: type option<'a> - let result = roundtrip("type option<'a> = | None | Some('a)"); - assert!( - result.contains("option<'a>"), - "Expected \"option<'a>\" but got: {}", - result - ); - assert!(result.contains("| None")); - assert!(result.contains("| Some")); - } - - #[test] - fn test_print_type_and_chain() { - let result = roundtrip_twice("type t = string and s = int and u = float"); - assert!(result.contains("and s = int"), "Missing second type: {}", result); - assert!(result.contains("and u = float"), "Missing third type: {}", result); - } - - #[test] - fn test_print_type_constructor_tuple_arg() { - let result = roundtrip("type t = constr<(string, int)>"); - assert!(result.contains("constr<(string, int)>"), "Unexpected output: {}", result); - } - - #[test] - fn test_long_tuple_type_breaks() { - let source = "type t = (superLongTypeNameThatWillBreak, superLongTypeNameThatWillBreak, superLongTypeNameThatWillBreak, superLongTypeNameThatWillBreak)"; - let result = roundtrip_with_width(source, 60); - assert!(result.contains("(\n"), "Expected multiline tuple type: {}", result); - } - - #[test] - fn test_print_labeled_function() { - let result = roundtrip("let f = (~x, ~y) => x + y"); - assert!(result.contains("~x")); - assert!(result.contains("~y")); - } - - #[test] - fn test_print_pattern_with_constructor() { - let result = roundtrip("let Some(x) = opt"); - assert!(result.contains("Some(x)")); - } - - #[test] - fn test_print_constraint() { - let result = roundtrip("let x: int = 42"); - // The pattern constraint might be parsed differently - assert!(result.contains("int") || result.contains("x = 42")); - } - - // TODO: assert parsing needs to be implemented - // #[test] - // fn test_print_assert() { - // let result = roundtrip("let _ = assert(x > 0)"); - // eprintln!("Assert result: {}", result); - // assert!(result.contains("assert")); - // } - - #[test] - fn test_print_await() { - let result = roundtrip("let x = await promise"); - assert!(result.contains("await promise")); - } - - #[test] - fn test_print_sequence() { - let result = roundtrip("let _ = { f(); g() }"); - // The parser might parse this differently - assert!(result.contains("f") && result.contains("g")); - } - - #[test] - fn test_roundtrip_sequence_in_fun_body() { - let result = roundtrip_twice("let f = x => { a(); b() }"); - assert!(result.contains("=> {"), "Expected block body in output: {}", result); - } - - #[test] - fn test_roundtrip_sequence_in_binary_rhs() { - let result = roundtrip_twice("let x = a && { b(); c() }"); - assert!( - result.contains("&& {"), - "Expected block RHS in output: {}", - result - ); - } - - #[test] - fn test_roundtrip_attribute_parens() { - let result = roundtrip_twice("let x = @attr (a + b)"); - assert!( - result.contains("@attr (a + b)"), - "Expected parentheses preserved: {}", - result - ); - } - - #[test] - fn test_roundtrip_comment_preservation() { - let result = roundtrip_twice("let /*a*/ x /*b*/ = 1 /*c*/"); - assert!(result.contains("/*a*/"), "Missing /*a*/ in output: {}", result); - assert!(result.contains("/*b*/"), "Missing /*b*/ in output: {}", result); - assert!(result.contains("/*c*/"), "Missing /*c*/ in output: {}", result); - } - - #[test] - fn test_roundtrip_unit_param() { - let result = roundtrip_twice("let f = (()) => 1"); - assert!( - result.contains("(()) =>"), - "Expected unit param to keep extra parens: {}", - result - ); - } - - #[test] - fn test_roundtrip_single_element_tuple_construct() { - let result = roundtrip_twice("let x = Some((foo()))"); - assert!( - result.contains("Some(foo())"), - "Expected single-element tuple to avoid double parens: {}", - result - ); - } - - #[test] - fn test_print_binary_operators() { - let result = roundtrip("let x = 1 + 2 * 3"); - assert!(result.contains("1")); - assert!(result.contains("2")); - assert!(result.contains("3")); - } - - #[test] - fn test_print_module_type() { - let result = roundtrip("module type S = { type t let x: t }"); - assert!(result.contains("module type S")); - } - - #[test] - fn test_print_include() { - let result = roundtrip("include Belt"); - assert!(result.contains("include Belt")); - } - - #[test] - fn test_print_or_pattern() { - let result = roundtrip("let x = switch y { | 1 | 2 => true | _ => false }"); - assert!(result.contains("1 | 2")); - } - - #[test] - fn test_print_constructor_with_args() { - let result = roundtrip("type t = | Point(int, int)"); - assert!(result.contains("Point(int, int)")); - } - - // JSX tests - #[test] - fn test_print_jsx_unary() { - let result = roundtrip("let x =
"); - assert!(result.contains("")); - } - - #[test] - fn test_print_jsx_container() { - let result = roundtrip("let x =
{child}
"); - assert!(result.contains("
")); - assert!(result.contains("
")); - } - - #[test] - fn test_print_jsx_fragment() { - let result = roundtrip("let x = <> {child} "); - assert!(result.contains("<>")); - assert!(result.contains("")); - } - - #[test] - fn test_print_jsx_with_props() { - let result = roundtrip("let x =