From 33060c5ee91e468a688bdcc4207f63e3ce14fa03 Mon Sep 17 00:00:00 2001 From: Jaap Frolich Date: Wed, 28 Jan 2026 19:41:52 +0100 Subject: [PATCH 001/464] Add arena and parse_arena modules for location storage Split into two modules for better separation of concerns: arena.rs - Generic arena infrastructure: - ArenaIdx trait for typed indices - Arena with typed index support - Methods: push, get, get_mut, iter, len, is_empty, as_slice parse_arena.rs - Parser-specific location storage: - PosIdx/LocIdx lightweight index types (4 bytes each) - InternedLocation storing positions by index - ParseArena with position and location arenas - Located using LocIdx for minimal memory footprint The existing location.rs with PositionId/LocationId remains unchanged. This adds infrastructure without migrating any existing code. Co-Authored-By: Claude Opus 4.5 --- compiler-rust/src/arena.rs | 211 +++++++++++++++ compiler-rust/src/lib.rs | 2 + compiler-rust/src/parse_arena.rs | 448 +++++++++++++++++++++++++++++++ 3 files changed, 661 insertions(+) create mode 100644 compiler-rust/src/arena.rs create mode 100644 compiler-rust/src/parse_arena.rs 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/lib.rs b/compiler-rust/src/lib.rs index bb3b8b43f21..3fdd91f7442 100644 --- a/compiler-rust/src/lib.rs +++ b/compiler-rust/src/lib.rs @@ -44,8 +44,10 @@ pub mod context; pub mod diagnostics; #[allow(unsafe_code)] // FFI requires unsafe pub mod ffi; +pub mod arena; pub mod ident; pub mod js_ir; +pub mod parse_arena; pub mod lambda; pub mod location; pub mod parser; diff --git a/compiler-rust/src/parse_arena.rs b/compiler-rust/src/parse_arena.rs new file mode 100644 index 00000000000..02f2db0d9e2 --- /dev/null +++ b/compiler-rust/src/parse_arena.rs @@ -0,0 +1,448 @@ +//! 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 serde::{Deserialize, Serialize}; + +use crate::arena::{Arena, ArenaIdx}; +use crate::location::{Location, Position}; + +// ============================================================================ +// 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 + } +} + +// ============================================================================ +// 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 +/// +/// Note: This does NOT deduplicate values. Each push creates a new entry. +/// The ParseArena is typically created once at the start of parsing and +/// passed through the parser. After parsing, it can be used during +/// marshalling to look up actual values. +#[derive(Debug, Default)] +pub struct ParseArena { + /// Arena of positions (returns PosIdx). + positions: Arena, + /// Arena of locations (returns LocIdx). + locations: Arena, +} + +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 position and location at index 0 + // This way LocIdx::default() == LocIdx(0) is always valid + let none_pos = Position::new("_none_", 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); + arena + } + + // ========== Position methods ========== + + /// Push a position into the arena and return its index. + pub fn push_position(&mut self, pos: Position) -> PosIdx { + self.positions.push(pos) + } + + /// Push a position from components. + pub fn push_pos(&mut self, file_name: impl Into, line: i32, bol: i32, cnum: i32) -> PosIdx { + self.push_position(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). + pub fn mk_loc_from_positions(&mut self, start: &Position, end: &Position) -> LocIdx { + let start_idx = self.push_position(start.clone()); + let end_idx = self.push_position(end.clone()); + self.mk_loc(start_idx, end_idx) + } + + /// Create a location spanning from one location's start to another's end. + pub fn mk_loc_spanning(&mut self, start_loc: LocIdx, end_loc: LocIdx) -> LocIdx { + let start_pos = self.loc_start(start_loc).clone(); + let end_pos = self.loc_end(end_loc).clone(); + self.mk_loc_from_positions(&start_pos, &end_pos) + } + + /// 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 + } + + /// 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::from_positions( + self.get_position(loc.loc_start).clone(), + self.get_position(loc.loc_end).clone(), + ) + } +} + +// ============================================================================ +// 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, +} + +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); + } +} From ed807c40d10c0335fd767da119202a25ce10fb0f Mon Sep 17 00:00:00 2001 From: Jaap Frolich Date: Wed, 28 Jan 2026 20:08:32 +0100 Subject: [PATCH 002/464] Add ParseArena to Parser for arena-based location storage Phase 1 of LocIdx migration: integrate ParseArena into Parser without changing existing Location-based code. New Parser methods for arena-based locations: - arena() / arena_mut() - access the arena - push_pos() / push_start_pos() / push_end_pos() / push_prev_end_pos() - mk_loc_idx() / mk_loc_from_positions() / mk_loc_spanning() - loc_start() / loc_end() / loc_start_idx() / loc_end_idx() - loc_ghost() / to_location() / none_loc() The existing mk_loc() method remains for backwards compatibility. ParserSnapshot updated to track arena state (counts only, no truncation). Co-Authored-By: Claude Opus 4.5 --- compiler-rust/src/parser/state.rs | 101 +++++++++++++++++++++++++++++- 1 file changed, 100 insertions(+), 1 deletion(-) diff --git a/compiler-rust/src/parser/state.rs b/compiler-rust/src/parser/state.rs index 09dc34f343b..232ed022991 100644 --- a/compiler-rust/src/parser/state.rs +++ b/compiler-rust/src/parser/state.rs @@ -7,6 +7,7 @@ use std::sync::atomic::{AtomicU32, Ordering}; use crate::location::{Location, LocationId, Position}; +use crate::parse_arena::{LocIdx, ParseArena, PosIdx}; use super::comment::Comment; use super::diagnostics::{DiagnosticCategory, ParserDiagnostic}; @@ -49,6 +50,10 @@ pub struct ParserSnapshot { diagnostics_len: usize, comments_len: usize, location_id_counter: u32, + /// Arena position count at snapshot time (for truncation on restore). + arena_positions_len: usize, + /// Arena location count at snapshot time (for truncation on restore). + arena_locations_len: usize, } /// Parser state for ReScript. @@ -58,6 +63,7 @@ pub struct ParserSnapshot { /// - Scanner for lexical analysis /// - Breadcrumbs for error recovery /// - Collected errors, diagnostics, and comments +/// - Arena for interned positions and locations pub struct Parser<'src> { /// Parser mode. pub mode: ParserMode, @@ -79,10 +85,13 @@ pub struct Parser<'src> { comments: Vec, /// Stack of region statuses for error deduplication. regions: Vec, - /// Counter for generating unique LocationIds. + /// Counter for generating unique LocationIds (legacy, for Location-based code). /// Each call to `mk_loc` gets a new ID, enabling identity-based sharing in Marshal. /// Uses atomic to allow mk_loc to take &self (avoiding borrow conflicts). location_id_counter: AtomicU32, + /// Arena for interned positions and locations. + /// Used for efficient location storage with LocIdx/PosIdx indices. + arena: ParseArena, /// Whether we're currently parsing an external definition. /// Used for arity calculation of @as(_) labeled parameters. pub in_external: bool, @@ -109,6 +118,7 @@ impl<'src> Parser<'src> { comments: Vec::new(), regions: vec![RegionStatus::Report], location_id_counter: AtomicU32::new(1), // Start at 1, 0 is reserved for default/uninitialized + arena: ParseArena::new(), in_external: false, }; // Scan the first token @@ -128,6 +138,88 @@ impl<'src> Parser<'src> { Location::from_positions_with_id(start.clone(), end.clone(), LocationId::from_raw(id)) } + // ========== Arena-based location methods ========== + + /// Get a reference to the parse arena. + pub fn arena(&self) -> &ParseArena { + &self.arena + } + + /// Get a mutable reference to the parse arena. + pub fn arena_mut(&mut self) -> &mut ParseArena { + &mut self.arena + } + + /// Push a position into the arena and return its index. + pub fn push_pos(&mut self, pos: Position) -> PosIdx { + self.arena.push_position(pos) + } + + /// Push the current start position into the arena. + pub fn push_start_pos(&mut self) -> PosIdx { + self.arena.push_position(self.start_pos.clone()) + } + + /// Push the current end position into the arena. + pub fn push_end_pos(&mut self) -> PosIdx { + self.arena.push_position(self.end_pos.clone()) + } + + /// Push the previous end position into the arena. + pub fn push_prev_end_pos(&mut self) -> PosIdx { + self.arena.push_position(self.prev_end_pos.clone()) + } + + /// Create and push a location from position indices. + pub fn mk_loc_idx(&mut self, start: PosIdx, end: PosIdx) -> LocIdx { + self.arena.mk_loc(start, end) + } + + /// Create and push a location from raw positions. + pub fn mk_loc_from_positions(&mut self, start: &Position, end: &Position) -> LocIdx { + self.arena.mk_loc_from_positions(start, end) + } + + /// Get the "none" location index. + pub fn none_loc(&self) -> LocIdx { + self.arena.none_loc() + } + + /// Get the start position of a location. + pub fn loc_start(&self, loc: LocIdx) -> &Position { + self.arena.loc_start(loc) + } + + /// Get the end position of a location. + pub fn loc_end(&self, loc: LocIdx) -> &Position { + self.arena.loc_end(loc) + } + + /// Get the start position index of a location. + pub fn loc_start_idx(&self, loc: LocIdx) -> PosIdx { + self.arena.loc_start_idx(loc) + } + + /// Get the end position index of a location. + pub fn loc_end_idx(&self, loc: LocIdx) -> PosIdx { + self.arena.loc_end_idx(loc) + } + + /// Check if a location is ghost. + pub fn loc_ghost(&self, loc: LocIdx) -> bool { + self.arena.loc_ghost(loc) + } + + /// Convert a LocIdx to a full Location struct. + pub fn to_location(&self, loc: LocIdx) -> Location { + self.arena.to_location(loc) + } + + /// Create a location spanning from one location's start to another's end. + pub fn mk_loc_spanning(&mut self, start_loc: LocIdx, end_loc: LocIdx) -> LocIdx { + self.arena.mk_loc_spanning(start_loc, end_loc) + } + /// Record a diagnostic error. /// /// Errors are only recorded if the current region has `Report` status. @@ -333,12 +425,16 @@ impl<'src> Parser<'src> { diagnostics_len: self.diagnostics.len(), comments_len: self.comments.len(), location_id_counter: self.location_id_counter.load(Ordering::Relaxed), + arena_positions_len: self.arena.position_count(), + arena_locations_len: self.arena.location_count(), } } /// Restore parser state from a snapshot. /// /// Used to backtrack after speculative parsing. + /// Note: Arena allocations made during speculative parsing are not freed, + /// but the indices won't be stored in the AST since we're restoring state. pub fn restore(&mut self, snapshot: ParserSnapshot) { self.scanner.restore(snapshot.scanner_snapshot); self.token = snapshot.token; @@ -349,6 +445,9 @@ impl<'src> Parser<'src> { self.diagnostics.truncate(snapshot.diagnostics_len); self.comments.truncate(snapshot.comments_len); self.location_id_counter.store(snapshot.location_id_counter, Ordering::Relaxed); + // Note: We don't truncate arena allocations as it's harmless to keep them. + // The indices from speculative parsing won't be stored in the final AST. + let _ = (snapshot.arena_positions_len, snapshot.arena_locations_len); } /// Check if parsing made progress. From a1ad6106beb9be189a09c636edb09fa273eb9013 Mon Sep 17 00:00:00 2001 From: Jaap Frolich Date: Wed, 28 Jan 2026 20:12:23 +0100 Subject: [PATCH 003/464] Add arena-based position/location marshalling methods Adds write_pos_idx() and write_loc_idx() methods to MarshalWriter that work with arena indices (PosIdx, LocIdx) for sharing. Same index = same object will be shared in output, matching the arena allocation semantics. Co-Authored-By: Claude Opus 4.5 --- compiler-rust/src/binary_ast/marshal.rs | 83 +++++++++++++++++++++++++ 1 file changed, 83 insertions(+) diff --git a/compiler-rust/src/binary_ast/marshal.rs b/compiler-rust/src/binary_ast/marshal.rs index 01f90d31e59..e759ce745c2 100644 --- a/compiler-rust/src/binary_ast/marshal.rs +++ b/compiler-rust/src/binary_ast/marshal.rs @@ -27,6 +27,7 @@ use std::collections::HashMap; use crate::location::{LocationId, PositionId}; +use crate::parse_arena::{LocIdx, ParseArena, PosIdx}; /// Magic number for small Marshal format const MAGIC_NUMBER_SMALL: u32 = 0x8495A6BE; @@ -105,6 +106,14 @@ pub struct MarshalWriter { /// Uses LocationId to determine when locations should be shared (like OCaml's pointer sharing) pub location_id_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 LocIdx to object counter (for arena-based Location sharing) + /// Same index = same object, will be shared in output + location_idx_table: HashMap, + /// Current object counter (incremented each time we record a sharable object) obj_counter: u32, @@ -133,6 +142,8 @@ impl MarshalWriter { location_content_table: HashMap::new(), location_table: HashMap::new(), location_id_table: HashMap::new(), + position_idx_table: HashMap::new(), + location_idx_table: HashMap::new(), obj_counter: 0, size_32: 0, size_64: 0, @@ -150,6 +161,8 @@ impl MarshalWriter { location_content_table: HashMap::new(), location_table: HashMap::new(), location_id_table: HashMap::new(), + position_idx_table: HashMap::new(), + location_idx_table: HashMap::new(), obj_counter: 0, size_32: 0, size_64: 0, @@ -168,6 +181,8 @@ impl MarshalWriter { self.string_table.clear(); self.position_table.clear(); self.location_table.clear(); + self.position_idx_table.clear(); + self.location_idx_table.clear(); self.obj_counter = 0; self.size_32 = 0; self.size_64 = 0; @@ -525,6 +540,74 @@ impl MarshalWriter { true } + // ========== Arena-based position/location methods ========== + + /// Write a Position by arena index with 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. + /// + /// Same index = same object, will be shared in output. + pub fn write_pos_idx(&mut self, idx: PosIdx, arena: &ParseArena) -> 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 + let pos = 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(&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 by arena index with sharing. + /// + /// 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. + /// + /// Same index = same object, will be shared in output. + pub fn write_loc_idx(&mut self, idx: LocIdx, arena: &ParseArena) -> bool { + // 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); + return false; + } + + // Look up the location in the arena + let loc = arena.get_location(idx); + + // Record the object index BEFORE writing + let obj_idx = self.obj_counter; + + // 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, arena); + self.write_pos_idx(loc.loc_end, arena); + self.write_int(if loc.loc_ghost { 1 } else { 0 }); + + // Record for future sharing + self.location_idx_table.insert(idx, obj_idx); + + true + } + /// Write a block header in Marshal format /// /// Blocks represent OCaml heap objects: records, tuples, and variant constructors From 82ac0567db99c7c23059af765248aa995b8d29b5 Mon Sep 17 00:00:00 2001 From: Jaap Frolich Date: Wed, 28 Jan 2026 20:54:57 +0100 Subject: [PATCH 004/464] WIP Arena --- compiler-rust/src/binary_ast/marshal.rs | 28 +++ compiler-rust/src/binary_ast/types.rs | 40 ++- compiler-rust/src/parse_arena.rs | 29 +++ compiler-rust/src/parser/ast.rs | 7 +- compiler-rust/src/parser/core.rs | 49 ++-- compiler-rust/src/parser/expr.rs | 312 ++++++++++++------------ compiler-rust/src/parser/module.rs | 17 +- compiler-rust/src/parser/pattern.rs | 26 +- compiler-rust/src/parser/state.rs | 67 +++-- 9 files changed, 358 insertions(+), 217 deletions(-) diff --git a/compiler-rust/src/binary_ast/marshal.rs b/compiler-rust/src/binary_ast/marshal.rs index e759ce745c2..8ab8852b7ed 100644 --- a/compiler-rust/src/binary_ast/marshal.rs +++ b/compiler-rust/src/binary_ast/marshal.rs @@ -114,6 +114,11 @@ pub struct MarshalWriter { /// Same index = same object, will be shared in output location_idx_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, @@ -144,6 +149,7 @@ impl MarshalWriter { location_id_table: HashMap::new(), position_idx_table: HashMap::new(), location_idx_table: HashMap::new(), + arena: None, obj_counter: 0, size_32: 0, size_64: 0, @@ -163,12 +169,34 @@ impl MarshalWriter { location_id_table: HashMap::new(), position_idx_table: HashMap::new(), location_idx_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 diff --git a/compiler-rust/src/binary_ast/types.rs b/compiler-rust/src/binary_ast/types.rs index b3c9318fb7c..0c31a4ff45d 100644 --- a/compiler-rust/src/binary_ast/types.rs +++ b/compiler-rust/src/binary_ast/types.rs @@ -6,6 +6,7 @@ use super::marshal::MarshalWriter; use super::serialize::Marshal; use crate::location::{Located, Location, Position}; +use crate::parse_arena::{self, LocIdx, PosIdx}; use crate::parser::longident::Longident; // ========== Position (Lexing.position) ========== @@ -87,7 +88,7 @@ impl Marshal for Location { } } -// ========== Located ('a loc) ========== +// ========== Located ('a loc) from crate::location ========== impl Marshal for Located { /// Serialize a Located to Marshal format. @@ -105,6 +106,43 @@ 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) { + let arena = w.get_arena(); + w.write_pos_idx(*self, arena); + } +} + +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) { + let arena = w.get_arena(); + w.write_loc_idx(*self, arena); + } +} + +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 Longident { diff --git a/compiler-rust/src/parse_arena.rs b/compiler-rust/src/parse_arena.rs index 02f2db0d9e2..2e2feee3657 100644 --- a/compiler-rust/src/parse_arena.rs +++ b/compiler-rust/src/parse_arena.rs @@ -69,6 +69,19 @@ impl ArenaIdx for LocIdx { } } +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) + } +} + // ============================================================================ // InternedLocation (stored in arena) // ============================================================================ @@ -272,6 +285,22 @@ impl ParseArena { self.get_position(loc.loc_end).clone(), ) } + + /// Convert a full Location to a LocIdx by pushing its positions to the arena. + /// Useful for migrating code that creates Location values. + pub fn from_location(&mut self, loc: &Location) -> LocIdx { + let start_idx = self.push_position(loc.loc_start.clone()); + let end_idx = self.push_position(loc.loc_end.clone()); + 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), + } + } } // ============================================================================ diff --git a/compiler-rust/src/parser/ast.rs b/compiler-rust/src/parser/ast.rs index a33d724fd02..8e429d57b6d 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::{Located, LocIdx}; 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; diff --git a/compiler-rust/src/parser/core.rs b/compiler-rust/src/parser/core.rs index 928f73c5eca..5798e46513b 100644 --- a/compiler-rust/src/parser/core.rs +++ b/compiler-rust/src/parser/core.rs @@ -3,7 +3,8 @@ //! 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::location::Position; +use crate::parse_arena::{Located, LocIdx}; use super::ast::*; use super::diagnostics::DiagnosticCategory; @@ -16,21 +17,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 +44,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 +54,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 +64,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 +73,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,7 +82,7 @@ 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![], } } @@ -504,21 +501,19 @@ pub mod ast_helper { 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 ghost location for the empty list constructor + let nil_loc = LocIdx::none(); + let nil = with_loc(Longident::Lident("[]".to_string()), 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(Longident::Lident("::".to_string()), cons_loc); result = make_pat( PatternDesc::Ppat_construct(cons, Some(Box::new(tuple))), cons_loc, @@ -612,7 +607,7 @@ pub fn make_unary_expr( }; 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 loc = p.mk_loc(&start_pos, &p.loc_end(operand.pexp_loc)); ast_helper::make_apply(op_expr, vec![(ArgLabel::Nolabel, operand)], loc) } @@ -934,7 +929,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 +942,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/expr.rs b/compiler-rust/src/parser/expr.rs index 3de544d737f..77b9fc2a000 100644 --- a/compiler-rust/src/parser/expr.rs +++ b/compiler-rust/src/parser/expr.rs @@ -3,7 +3,8 @@ //! 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::{Located, LocIdx}; use super::ast::*; use super::core::{ExprContext, ast_helper, make_braces_attr, mknoloc, recover, with_loc}; @@ -154,7 +155,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![], }; @@ -209,27 +210,27 @@ fn parse_value_path_after_dot(p: &mut Parser<'_>) -> Located { } } - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); with_loc(path, loc) } Token::Lident(name) => { let path = Longident::Lident(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); with_loc(path, loc) } Token::String(name) => { // Quoted field: ."switch" let path = Longident::Lident(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); with_loc(path, loc) } _ => { p.err(DiagnosticCategory::Message( "Expected identifier after dot".to_string(), )); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); with_loc(Longident::Lident("_".to_string()), loc) } } @@ -269,7 +270,7 @@ 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 loc = p.mk_loc_to_prev_end(&start_pos); // Check if it's a constructor (all uppercase components) if path_parts @@ -286,7 +287,7 @@ pub fn parse_value_or_constructor(p: &mut Parser<'_>) -> Expression { 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 }, @@ -300,7 +301,7 @@ pub fn parse_value_or_constructor(p: &mut Parser<'_>) -> Expression { 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); ast_helper::make_ident(Longident::Lident(name), loc) } _ => { @@ -323,7 +324,7 @@ 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 loc = p.mk_loc_to_prev_end(&start_pos); let lid = Longident::Lident("()".to_string()); Some(Expression { pexp_desc: ExpressionDesc::Pexp_construct(with_loc(lid, loc.clone()), None), @@ -350,7 +351,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 +365,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 +402,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, @@ -421,7 +422,7 @@ pub fn parse_expr_with_context(p: &mut Parser<'_>, context: ExprContext) -> Expr 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, @@ -444,10 +445,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,7 +508,7 @@ 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 loc = p.mk_loc_to_prev_end(&start_pos); let ident = ast_helper::make_ident(Longident::Lident("async".to_string()), loc); (parse_primary_expr(p, ident, false), false) } @@ -520,7 +518,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 +604,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 +672,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, @@ -806,7 +804,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 +837,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() { @@ -996,11 +995,11 @@ fn parse_parameter(p: &mut Parser<'_>) -> Option { // OCaml: label location is just the name, not including ~ let lbl_located = Located::new(lbl_name.clone(), 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 loc = p.mk_loc_to_prev_end(&start_pos); let pat = ast_helper::make_var_pat(lbl_name.clone(), loc); (ArgLabel::Labelled(lbl_located), pat, None) } @@ -1010,13 +1009,13 @@ 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); let pat = Pattern { @@ -1033,7 +1032,7 @@ fn parse_parameter(p: &mut Parser<'_>) -> Option { (ArgLabel::Labelled(lbl_located), pat, None) } _ => { - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); let pat = ast_helper::make_var_pat(lbl_name.clone(), loc); (ArgLabel::Labelled(lbl_located), pat, None) } @@ -1058,7 +1057,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, @@ -1094,7 +1093,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, @@ -1142,7 +1141,7 @@ fn parse_lident(p: &mut Parser<'_>) -> (String, Location) { p.err(DiagnosticCategory::Message( "Expected lowercase identifier".to_string(), )); - ("_".to_string(), Location::none()) + ("_".to_string(), LocIdx::none()) } } } @@ -1158,7 +1157,7 @@ fn parse_attributes(p: &mut Parser<'_>) -> Attributes { } } Token::DocComment { loc, content } => { - let loc = loc.clone(); + let loc = p.from_location(loc); let content = content.clone(); p.next(); attrs.push(super::core::doc_comment_to_attribute(loc, content)); @@ -1246,7 +1245,7 @@ fn parse_attribute_id(p: &mut Parser<'_>, start_pos: Position) -> Located) -> Payload { // Create a structure item with the string expression 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: p.mk_loc_to_prev_end(&start_pos), 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: p.mk_loc_to_prev_end(&start_pos), }]); } @@ -1357,7 +1356,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,8 +1375,8 @@ 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); + let op_loc = p.mk_loc_from_positions(&op_start, &op_end); // Build application expression let op_expr = ast_helper::make_ident(Longident::Lident(token.to_string()), op_loc); @@ -1456,7 +1455,7 @@ 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 loc = p.mk_loc_to_prev_end(&start_pos); let lid = Longident::Lident(if is_true { "true" } else { "false" }.to_string()); Expression { pexp_desc: ExpressionDesc::Pexp_construct(with_loc(lid, loc.clone()), None), @@ -1466,14 +1465,14 @@ pub fn parse_atomic_expr(p: &mut Parser<'_>) -> Expression { } 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,7 +1493,7 @@ 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![], } } @@ -1504,7 +1503,7 @@ pub fn parse_atomic_expr(p: &mut Parser<'_>) -> Expression { if p.token == Token::Rparen { // Unit: () p.next(); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); let lid = Longident::Lident("()".to_string()); Expression { pexp_desc: ExpressionDesc::Pexp_construct(with_loc(lid, loc.clone()), None), @@ -1543,7 +1542,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 +1580,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 +1595,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 +1607,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 => { @@ -1646,7 +1645,7 @@ 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); Some(Box::new(Expression { pexp_desc: ExpressionDesc::Pexp_construct( with_loc(Longident::Lident("()".to_string()), unit_loc.clone()), @@ -1731,7 +1730,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, @@ -1745,7 +1744,7 @@ pub fn parse_atomic_expr(p: &mut Parser<'_>) -> Expression { } 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); ast_helper::make_ident(Longident::Lident("_".to_string()), loc) } Token::Eof => { @@ -1780,10 +1779,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 +1796,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 +1807,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, @@ -1834,7 +1833,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 { @@ -1851,7 +1850,7 @@ pub fn parse_primary_expr(p: &mut Parser<'_>, operand: Expression, no_call: bool if p.token == Token::Equal { p.next(); let value = parse_expr(p); - 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_setfield( Box::new(expr), @@ -1862,7 +1861,7 @@ pub fn parse_primary_expr(p: &mut Parser<'_>, operand: Expression, no_call: bool 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), @@ -1883,7 +1882,7 @@ pub fn parse_primary_expr(p: &mut Parser<'_>, operand: Expression, no_call: bool if p.token == Token::Equal { p.next(); let value = parse_expr(p); - 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_setfield( Box::new(expr), @@ -1894,7 +1893,7 @@ pub fn parse_primary_expr(p: &mut Parser<'_>, operand: Expression, no_call: bool 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), @@ -1909,7 +1908,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,7 +1929,8 @@ 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); } @@ -1966,7 +1966,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 { @@ -1999,7 +1999,7 @@ 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( @@ -2111,11 +2111,11 @@ fn parse_call_args(p: &mut Parser<'_>) -> (Vec<(ArgLabel, Expression)>, bool) { pexp_desc: ExpressionDesc::Pexp_construct( Loc { txt: Longident::Lident("()".to_string()), - loc: Location::none(), + loc: LocIdx::none(), }, None, ), - pexp_loc: Location::none(), + pexp_loc: LocIdx::none(), pexp_attributes: vec![], }; args.push((ArgLabel::Nolabel, unit_expr)); @@ -2196,7 +2196,8 @@ fn parse_argument(p: &mut Parser<'_>) -> (ArgLabel, Expression) { // 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 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, @@ -2231,7 +2232,7 @@ 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); if elements.len() < 2 { p.err(DiagnosticCategory::Message( @@ -2272,7 +2273,7 @@ fn parse_array_expr(p: &mut Parser<'_>) -> Expression { } 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); @@ -2380,7 +2381,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 +2390,13 @@ fn parse_list_expr(p: &mut Parser<'_>, start_pos: Position) -> Expression { match segments.len() { 0 => { // Empty list: list{} → [] - make_empty_list(&loc) + make_empty_list(loc) } 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 @@ -2494,16 +2495,16 @@ fn split_list_by_spread( } /// Build an empty list expression `[]` -fn make_empty_list(loc: &Location) -> Expression { +fn make_empty_list(loc: Location) -> Expression { Expression { pexp_desc: ExpressionDesc::Pexp_construct( Loc { txt: Longident::Lident("[]".to_string()), - loc: loc.clone(), + loc, }, None, ), - pexp_loc: loc.clone(), + pexp_loc: loc, pexp_attributes: vec![], } } @@ -2513,7 +2514,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: &Parser<'_>, + loc: Location, exprs: Vec, spread: Option, ) -> Expression { @@ -2521,23 +2523,23 @@ 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()); + .map(|s| p.loc_end(s.pexp_loc)) + .unwrap_or_else(|| p.loc_end(loc)); 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()); + let cons_loc = p.mk_loc(&p.loc_start(item.pexp_loc), &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 { pexp_desc: ExpressionDesc::Pexp_construct( Loc { txt: Longident::Lident("::".to_string()), - loc: cons_loc.clone(), + loc: cons_loc, }, Some(Box::new(tuple)), ), @@ -2560,15 +2562,15 @@ fn make_list_expression_with_loc( let seg_loc = p.mk_loc(&seg_start, &seg_end); // Build the list using cons cells - let list_end = seg_loc.loc_end.clone(); + let list_end = seg_end; let tail = 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(), + loc: ghost_loc, }, None, ), @@ -2578,17 +2580,17 @@ 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()); + let cons_loc = p.mk_loc(&p.loc_start(item.pexp_loc), &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 { pexp_desc: ExpressionDesc::Pexp_construct( Loc { txt: Longident::Lident("::".to_string()), - loc: cons_loc.clone(), + loc: cons_loc, }, Some(Box::new(tuple)), ), @@ -2626,16 +2628,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 +2658,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 { @@ -2699,7 +2701,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 +2721,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 +2731,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, @@ -2792,7 +2794,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, @@ -2890,7 +2892,7 @@ fn parse_braced_arrow_ident(p: &mut Parser<'_>, start_pos: Position) -> Expressi 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 +2906,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); @@ -2926,7 +2928,7 @@ fn parse_expr_block(p: &mut Parser<'_>) -> Expression { // 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()) + .map(|e| p.loc_end(e.pexp_loc)) .unwrap_or_else(|| p.prev_end_pos.clone()); let loc = p.mk_loc(&start_pos, &end_pos); @@ -2941,7 +2943,7 @@ fn parse_block_expr(p: &mut Parser<'_>, start_pos: Position) -> Expression { let body = parse_block_body(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); let mut expr = body.unwrap_or_else(|| ast_helper::make_unit(loc.clone())); @@ -2999,7 +3001,7 @@ fn parse_block_body(p: &mut Parser<'_>) -> Option { }); // 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, @@ -3025,7 +3027,7 @@ fn parse_block_body(p: &mut Parser<'_>) -> Option { // 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 +3055,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), @@ -3076,7 +3078,7 @@ fn parse_block_body(p: &mut Parser<'_>) -> Option { }); // 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, @@ -3107,7 +3109,7 @@ fn parse_block_body(p: &mut Parser<'_>) -> Option { }); // 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, @@ -3127,7 +3129,7 @@ fn parse_block_body(p: &mut Parser<'_>) -> Option { // 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, @@ -3160,7 +3162,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(); @@ -3221,7 +3223,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 +3238,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 +3319,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 +3331,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, @@ -3414,7 +3416,7 @@ fn parse_module_longident(p: &mut Parser<'_>) -> Located { } let lid = super::core::build_longident(&parts); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); with_loc(lid, loc) } @@ -3478,7 +3480,7 @@ fn parse_record_fields(p: &mut Parser<'_>) -> Vec { } 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 loc = p.mk_loc_to_prev_end(&expr_start); let expr = ast_helper::make_ident(Longident::Lident(pun_name), loc.clone()); (with_loc(lid_unloc, loc), expr, opt_punning) }; @@ -3535,7 +3537,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 { @@ -3590,7 +3592,7 @@ fn parse_if_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_ifthenelse( @@ -3639,7 +3641,7 @@ fn parse_switch_case_body(p: &mut Parser<'_>) -> Option { }); // 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 +3665,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, @@ -3690,7 +3692,7 @@ fn parse_switch_case_body(p: &mut Parser<'_>) -> Option { }); // 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, @@ -3721,7 +3723,7 @@ fn parse_switch_case_body(p: &mut Parser<'_>) -> Option { }); // 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 +3739,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 +3784,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 +3796,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 +3827,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 +3839,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, @@ -3858,7 +3860,7 @@ fn parse_let_in_switch_case(p: &mut Parser<'_>) -> Expression { }); // 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 +3907,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 +3919,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) @@ -3988,7 +3991,7 @@ fn parse_switch_expr(p: &mut Parser<'_>) -> 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); Expression { pexp_desc: ExpressionDesc::Pexp_match(Box::new(scrutinee), cases), @@ -4008,7 +4011,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,7 +4039,7 @@ 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 loc = p.mk_loc_to_prev_end(&lparen_pos); let unit_pat = super::pattern::make_unit_construct_pattern(loc); let pat = super::pattern::parse_alias_pattern(p, unit_pat, vec![]); (pat, false) @@ -4099,7 +4102,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( @@ -4156,7 +4159,7 @@ fn parse_try_expr(p: &mut Parser<'_>) -> 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); Expression { pexp_desc: ExpressionDesc::Pexp_try(Box::new(body), cases), @@ -4182,7 +4185,7 @@ fn parse_jsx(p: &mut Parser<'_>) -> Expression { // 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); @@ -4191,7 +4194,7 @@ fn parse_jsx(p: &mut Parser<'_>) -> Expression { 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); Expression { pexp_desc: ExpressionDesc::Pexp_jsx_element(JsxElement::Unary(JsxUnaryElement { @@ -4214,7 +4217,7 @@ fn parse_jsx(p: &mut Parser<'_>) -> Expression { let _closing_tag_name = parse_jsx_tag_name(p); 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::Container( @@ -4244,7 +4247,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 { @@ -4344,7 +4347,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; @@ -4464,7 +4467,8 @@ fn parse_jsx_children(p: &mut Parser<'_>) -> Vec { let name = name.clone(); let name_loc = p.mk_loc(&p.start_pos, &p.end_pos); 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), @@ -4476,7 +4480,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 +4497,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, @@ -4542,7 +4546,7 @@ 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); + let loc = p.mk_loc_to_prev_end(&lbrace_start); ast_helper::make_unit(loc) } } @@ -4647,7 +4651,7 @@ fn parse_template_literal_with_prefix( } } - 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 { @@ -4668,12 +4672,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 +4717,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; } @@ -4733,12 +4737,12 @@ fn parse_template_literal_with_prefix( // Fold with ++ operator let hidden_operator = Expression { pexp_desc: ExpressionDesc::Pexp_ident(mknoloc(Longident::Lident("++".to_string()))), - pexp_loc: Location::none(), + 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 +4766,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![])); @@ -4839,12 +4843,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 +4857,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/module.rs b/compiler-rust/src/parser/module.rs index e41f23bf130..b57f013d5dd 100644 --- a/compiler-rust/src/parser/module.rs +++ b/compiler-rust/src/parser/module.rs @@ -5,9 +5,12 @@ use std::cell::RefCell; -use crate::location::{Located, Location, Position}; +use crate::location::Position; +use crate::parse_arena::{Located, LocIdx}; +// Import Location as alias to LocIdx from ast use super::ast::*; +use super::ast::Location; use super::core::{is_es6_arrow_functor, mknoloc, recover, with_loc}; use super::diagnostics::DiagnosticCategory; use super::expr; @@ -270,7 +273,7 @@ pub fn parse_structure_item(p: &mut Parser<'_>) -> Option { } Token::ModuleComment { loc, content } => { // Module-level doc comment (triple star /*** ... */) becomes a standalone res.doc attribute - let loc = loc.clone(); + let loc = p.from_location(loc); let content = content.clone(); p.next(); let attr = super::core::doc_comment_to_attribute(loc, content); @@ -526,7 +529,7 @@ pub fn parse_signature_item(p: &mut Parser<'_>) -> Option { } Token::ModuleComment { loc, content } => { // Module-level doc comment (triple star /*** ... */) becomes a standalone res.doc attribute - let loc = loc.clone(); + let loc = p.from_location(loc); let content = content.clone(); p.next(); let attr = super::core::doc_comment_to_attribute(loc, content); @@ -806,7 +809,7 @@ 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), @@ -893,7 +896,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, @@ -1096,8 +1099,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( diff --git a/compiler-rust/src/parser/pattern.rs b/compiler-rust/src/parser/pattern.rs index 49f49a397c7..f4432402581 100644 --- a/compiler-rust/src/parser/pattern.rs +++ b/compiler-rust/src/parser/pattern.rs @@ -9,7 +9,8 @@ use super::diagnostics::DiagnosticCategory; 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}; // ============================================================================ // Attribute Parsing for Patterns @@ -26,7 +27,7 @@ fn parse_attributes(p: &mut Parser<'_>) -> Attributes { } } Token::DocComment { loc, content } => { - let loc = loc.clone(); + let loc = p.from_location(loc); let content = content.clone(); p.next(); attrs.push(super::core::doc_comment_to_attribute(loc, content)); @@ -105,7 +106,7 @@ fn parse_payload(p: &mut Parser<'_>) -> 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) { @@ -218,11 +219,11 @@ fn parse_single_pattern(p: &mut Parser<'_>) -> Pattern { // 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, @@ -321,7 +322,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, @@ -340,7 +341,7 @@ pub fn parse_constrained_pattern(p: &mut Parser<'_>) -> Pattern { // 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); + 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 +353,8 @@ 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) +pub fn make_unit_construct_pattern(loc: Location) -> Pattern { + ast_helper::make_construct_pat(Longident::Lident("()".to_string()), None, loc, loc) } /// Parse an optional alias `as name` after a pattern. @@ -365,7 +366,7 @@ pub fn parse_alias_pattern( mut pat: Pattern, _attrs: Vec, ) -> Pattern { - let start_pos = pat.ppat_loc.loc_start.clone(); + let start_pos = p.loc_start(pat.ppat_loc); while p.token == Token::As { p.next(); let name = match &p.token { @@ -530,7 +531,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, @@ -562,7 +563,8 @@ 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 diff --git a/compiler-rust/src/parser/state.rs b/compiler-rust/src/parser/state.rs index 232ed022991..d209ca9c6ce 100644 --- a/compiler-rust/src/parser/state.rs +++ b/compiler-rust/src/parser/state.rs @@ -126,20 +126,50 @@ impl<'src> Parser<'src> { parser } - /// Create a location with a unique ID for identity-based sharing in Marshal. + /// Create a location from positions and push to arena. /// - /// Each call generates a new LocationId. When the returned Location is cloned, - /// the clones share the same ID (and will be shared in the Marshal output). - /// - /// Uses atomic counter to take &self, avoiding borrow conflicts when - /// passing position references like `p.mk_loc(&start_pos, &p.prev_end_pos)`. - pub fn mk_loc(&self, start: &Position, end: &Position) -> Location { - let id = self.location_id_counter.fetch_add(1, Ordering::Relaxed); - Location::from_positions_with_id(start.clone(), end.clone(), LocationId::from_raw(id)) + /// Returns a LocIdx that can be used to look up the location later. + /// Note: Positions must be cloned before calling this to avoid borrow conflicts. + pub fn mk_loc(&mut self, start: &Position, end: &Position) -> LocIdx { + self.arena.mk_loc_from_positions(start, end) + } + + /// Create a location from start position to prev_end_pos. + /// This is a common pattern that avoids borrow conflicts. + pub fn mk_loc_to_prev_end(&mut self, start: &Position) -> LocIdx { + let end = self.prev_end_pos.clone(); + self.arena.mk_loc_from_positions(start, &end) + } + + /// Create a location from start position to end_pos. + /// This is a common pattern that avoids borrow conflicts. + pub fn mk_loc_to_end(&mut self, start: &Position) -> LocIdx { + let end = self.end_pos.clone(); + self.arena.mk_loc_from_positions(start, &end) + } + + /// Create a location for the current token (start_pos to end_pos). + pub fn mk_loc_current(&mut self) -> LocIdx { + let start = self.start_pos.clone(); + let end = self.end_pos.clone(); + self.arena.mk_loc_from_positions(&start, &end) + } + + /// Create a location from start_pos to prev_end_pos. + pub fn mk_loc_start_to_prev_end(&mut self) -> LocIdx { + let start = self.start_pos.clone(); + let end = self.prev_end_pos.clone(); + self.arena.mk_loc_from_positions(&start, &end) } // ========== Arena-based location methods ========== + /// Get the internal ParseArena for marshalling. + /// Only use this after parsing is complete. + pub fn into_arena(self) -> ParseArena { + self.arena + } + /// Get a reference to the parse arena. pub fn arena(&self) -> &ParseArena { &self.arena @@ -185,14 +215,14 @@ impl<'src> Parser<'src> { self.arena.none_loc() } - /// Get the start position of a location. - pub fn loc_start(&self, loc: LocIdx) -> &Position { - self.arena.loc_start(loc) + /// Get the start position of a location (cloned). + pub fn loc_start(&self, loc: LocIdx) -> Position { + self.arena.loc_start(loc).clone() } - /// Get the end position of a location. - pub fn loc_end(&self, loc: LocIdx) -> &Position { - self.arena.loc_end(loc) + /// Get the end position of a location (cloned). + pub fn loc_end(&self, loc: LocIdx) -> Position { + self.arena.loc_end(loc).clone() } /// Get the start position index of a location. @@ -215,6 +245,13 @@ impl<'src> Parser<'src> { self.arena.to_location(loc) } + /// Convert a full Location struct to LocIdx (push to arena). + /// Use this when converting from Token locations (which use crate::location::Location) + /// to AST locations (which use LocIdx). + pub fn from_location(&mut self, loc: &Location) -> LocIdx { + self.arena.from_location(loc) + } + /// Create a location spanning from one location's start to another's end. pub fn mk_loc_spanning(&mut self, start_loc: LocIdx, end_loc: LocIdx) -> LocIdx { self.arena.mk_loc_spanning(start_loc, end_loc) From f03afe7bdcd43d0006b6e8fd5db6c8bdc0340cee Mon Sep 17 00:00:00 2001 From: Jaap Frolich Date: Wed, 28 Jan 2026 21:19:25 +0100 Subject: [PATCH 005/464] WIP --- compiler-rust/src/parser/comment_table.rs | 1301 +++++++++++---------- 1 file changed, 671 insertions(+), 630 deletions(-) diff --git a/compiler-rust/src/parser/comment_table.rs b/compiler-rust/src/parser/comment_table.rs index bd18cd89e82..c97ab205fda 100644 --- a/compiler-rust/src/parser/comment_table.rs +++ b/compiler-rust/src/parser/comment_table.rs @@ -6,7 +6,18 @@ //! 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::{LocIdx, ParseArena}; +use crate::parser::ast::{ + self, ArgLabel, Attribute, Case, ConstructorArguments, ConstructorDeclaration, CoreType, + CoreTypeDesc, Expression, ExpressionDesc, ExpressionRecordField, Extension, + ExtensionConstructor, ExtensionConstructorKind, IncludeDeclaration, IncludeDescription, + JsxClosingTag, JsxContainerElement, JsxElement, JsxFragment, JsxProp, JsxUnaryElement, + LabelDeclaration, Loc, ModuleBinding, ModuleDeclaration, ModuleExpr, ModuleExprDesc, + ModuleType, ModuleTypeDeclaration, ModuleTypeDesc, ObjectField, OpenDescription, Pattern, + PatternDesc, PatternRecordField, Payload, RowField, Signature, SignatureItem, + SignatureItemDesc, Structure, 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; @@ -103,7 +114,7 @@ impl CommentTable { /// /// 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) { + pub fn walk_structure_simple(&mut self, structure: &[StructureItem], comments: Vec, arena: &ParseArena) { if comments.is_empty() || structure.is_empty() { if !comments.is_empty() { // Attach remaining comments to "inside" of the file @@ -116,7 +127,7 @@ impl CommentTable { let mut remaining_comments = comments; for (i, item) in structure.iter().enumerate() { - let loc = &item.pstr_loc; + let loc = arena.to_location(item.pstr_loc); // Find comments that belong to this item let (leading, rest): (Vec, Vec) = remaining_comments @@ -125,7 +136,7 @@ impl CommentTable { // 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 + arena.to_location(structure[i + 1].pstr_loc).loc_start.cnum } else { i32::MAX }; @@ -341,77 +352,77 @@ 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: &ParseArena) -> Location { 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 + let start = arena.loc_start(case.pc_lhs.ppat_loc); + let end = arena.loc_end(case.pc_rhs.pexp_loc); + Location::from_positions(start.clone(), end.clone()) } - Node::CoreType(ct) => ct.ptyp_loc.clone(), - Node::ExprArgument { loc, .. } => loc.clone(), + Node::CoreType(ct) => arena.to_location(ct.ptyp_loc), + Node::ExprArgument { loc, .. } => arena.to_location(*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 arena.to_location(attr.0.loc); } } - e.pexp_loc.clone() + arena.to_location(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); + 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) => arena.to_location(ec.pext_loc), + Node::LabelDeclaration(ld) => arena.to_location(ld.pld_loc), + Node::ModuleBinding(mb) => arena.to_location(mb.pmb_loc), + Node::ModuleDeclaration(md) => arena.to_location(md.pmd_loc), + Node::ModuleExpr(me) => arena.to_location(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); + Location::from_positions(start.clone(), end.clone()) } - ObjectField::Oinherit(typ) => typ.ptyp_loc.clone(), + ObjectField::Oinherit(typ) => arena.to_location(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); + Location::from_positions(start.clone(), end.clone()) } - Node::Pattern(p) => p.ppat_loc.clone(), + Node::Pattern(p) => arena.to_location(p.ppat_loc), Node::PatternRecordRow(li, p) => { - let mut loc = li.loc.clone(); - loc.loc_end = p.ppat_loc.loc_end.clone(); - loc + let start = arena.loc_start(li.loc); + let end = arena.loc_end(p.ppat_loc); + 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) => arena.to_location(tag.loc), + RowField::Rinherit(typ) => arena.to_location(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) => arena.to_location(si.psig_loc), + Node::StructureItem(si) => arena.to_location(si.pstr_loc), + Node::TypeDeclaration(td) => arena.to_location(td.ptype_loc), + Node::ValueBinding(vb) => arena.to_location(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: &ParseArena) -> Location { match prop { - JsxProp::Punning { name, .. } => name.loc.clone(), + JsxProp::Punning { name, .. } => arena.to_location(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); + Location::from_positions(start.clone(), end.clone()) } - JsxProp::Spreading { loc, .. } => loc.clone(), + JsxProp::Spreading { loc, .. } => arena.to_location(*loc), } } @@ -511,7 +522,7 @@ 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: &Structure, t: &mut CommentTable, comments: Vec, arena: &ParseArena) { if comments.is_empty() { return; } @@ -521,11 +532,11 @@ pub fn walk_structure(structure: &Structure, t: &mut CommentTable, comments: Vec } 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: &Signature, t: &mut CommentTable, comments: Vec, arena: &ParseArena) { if comments.is_empty() { return; } @@ -535,15 +546,15 @@ pub fn walk_signature(signature: &Signature, t: &mut CommentTable, comments: Vec } 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: &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: &ParseArena) { if comments.is_empty() { return; } @@ -556,7 +567,7 @@ fn walk_list_impl(nodes: &[Node<'_>], t: &mut CommentTable, comments: Vec], t: &mut CommentTable, comments: Vec, t: &mut CommentTable, comments: Vec) { +fn walk_node(node: &Node<'_>, t: &mut CommentTable, comments: Vec, arena: &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), + 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) { +fn walk_structure_item(si: &StructureItem, t: &mut CommentTable, comments: Vec, arena: &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: &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: &ParseArena) { + let (leading, trailing) = partition_leading_trailing(comments, &arena.to_location(vd.pval_name.loc)); + CommentTable::attach(&mut t.leading, arena.to_location(vd.pval_name.loc), leading); - 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(&arena.to_location(vd.pval_name.loc), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(vd.pval_name.loc), after_name); 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); + walk_core_type(&vd.pval_type, t, inside, arena); CommentTable::attach(&mut t.trailing, vd.pval_type.ptyp_loc.clone(), after); } -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: &ParseArena) { + let (leading, trailing) = partition_leading_trailing(comments, &arena.to_location(te.ptyext_path.loc)); + CommentTable::attach(&mut t.leading, arena.to_location(te.ptyext_path.loc), leading); - 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(&arena.to_location(te.ptyext_path.loc), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(te.ptyext_path.loc), after_path); // Type params let rest = if te.ptyext_params.is_empty() { @@ -688,11 +699,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: &ParseArena) { + let (before, inside, after) = partition_by_loc(comments, &arena.to_location(id.pincl_mod.pmod_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(id.pincl_mod.pmod_loc), before); + walk_module_expr(&id.pincl_mod, t, inside, arena); + CommentTable::attach(&mut t.trailing, arena.to_location(id.pincl_mod.pmod_loc), after); } -fn walk_include_description(id: &IncludeDescription, t: &mut CommentTable, comments: Vec) { +fn walk_include_description(id: &IncludeDescription, t: &mut CommentTable, comments: Vec, arena: &ParseArena) { 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); + walk_mod_type(&id.pincl_mod, t, inside, arena); CommentTable::attach(&mut t.trailing, id.pincl_mod.pmty_loc.clone(), after); } @@ -722,6 +734,7 @@ fn walk_module_type_declaration( mtd: &ModuleTypeDeclaration, t: &mut CommentTable, comments: Vec, + arena: &ParseArena, ) { let (leading, trailing) = partition_leading_trailing(comments, &mtd.pmtd_name.loc); CommentTable::attach(&mut t.leading, mtd.pmtd_name.loc.clone(), leading); @@ -736,13 +749,13 @@ fn walk_module_type_declaration( 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); + walk_mod_type(mod_type, t, inside, arena); CommentTable::attach(&mut t.trailing, mod_type.pmty_loc.clone(), after); } } } -fn walk_module_binding(mb: &ModuleBinding, t: &mut CommentTable, comments: Vec) { +fn walk_module_binding(mb: &ModuleBinding, t: &mut CommentTable, comments: Vec, arena: &ParseArena) { let (leading, trailing) = partition_leading_trailing(comments, &mb.pmb_name.loc); CommentTable::attach(&mut t.leading, mb.pmb_name.loc.clone(), leading); @@ -754,17 +767,17 @@ fn walk_module_binding(mb: &ModuleBinding, t: &mut CommentTable, comments: Vec { 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); + CommentTable::attach(&mut t.leading, arena.to_location(mb.pmb_expr.pmod_loc), leading); + walk_module_expr(&mb.pmb_expr, t, inside, arena); } } - CommentTable::attach(&mut t.trailing, mb.pmb_expr.pmod_loc.clone(), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(mb.pmb_expr.pmod_loc), trailing); } -fn walk_module_declaration(md: &ModuleDeclaration, t: &mut CommentTable, comments: Vec) { +fn walk_module_declaration(md: &ModuleDeclaration, t: &mut CommentTable, comments: Vec, arena: &ParseArena) { let (leading, trailing) = partition_leading_trailing(comments, &md.pmd_name.loc); CommentTable::attach(&mut t.leading, md.pmd_name.loc.clone(), leading); @@ -773,28 +786,28 @@ fn walk_module_declaration(md: &ModuleDeclaration, t: &mut CommentTable, comment 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); + walk_mod_type(&md.pmd_type, t, inside, arena); CommentTable::attach(&mut t.trailing, md.pmd_type.pmty_loc.clone(), trailing); } -fn walk_open_description(od: &OpenDescription, t: &mut CommentTable, comments: Vec) { +fn walk_open_description(od: &OpenDescription, t: &mut CommentTable, comments: Vec, arena: &ParseArena) { 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_value_bindings(vbs: &[ValueBinding], t: &mut CommentTable, comments: Vec) { +fn walk_value_bindings(vbs: &[ValueBinding], t: &mut CommentTable, comments: Vec, arena: &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: &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) { +fn walk_value_binding(vb: &ValueBinding, t: &mut CommentTable, comments: Vec, arena: &ParseArena) { let pattern_loc = &vb.pvb_pat.ppat_loc; let expr_loc = &vb.pvb_expr.pexp_loc; @@ -802,7 +815,7 @@ fn walk_value_binding(vb: &ValueBinding, t: &mut CommentTable, comments: Vec) { +fn walk_type_declaration(td: &TypeDeclaration, t: &mut CommentTable, comments: Vec, arena: &ParseArena) { let (before_name, rest) = partition_leading_trailing(comments, &td.ptype_name.loc); CommentTable::attach(&mut t.leading, td.ptype_name.loc.clone(), before_name); @@ -836,22 +849,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| 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, &arena.to_location(typexpr.ptyp_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(typexpr.ptyp_loc), before_typ); + walk_core_type(typexpr, t, inside_typ, arena); + let (after_typ_adj, rest) = partition_adjacent_trailing(&arena.to_location(typexpr.ptyp_loc), after_typ); + CommentTable::attach(&mut t.trailing, arena.to_location(typexpr.ptyp_loc), after_typ_adj); rest } None => rest, @@ -861,21 +875,21 @@ 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); + CommentTable::attach(&mut t.inside, arena.to_location(td.ptype_loc), rest); 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); + CommentTable::attach(&mut t.trailing, arena.to_location(td.ptype_loc), rest); } -fn walk_label_declaration(ld: &LabelDeclaration, t: &mut CommentTable, comments: Vec) { +fn walk_label_declaration(ld: &LabelDeclaration, t: &mut CommentTable, comments: Vec, arena: &ParseArena) { let (before_name, rest) = partition_leading_trailing(comments, &ld.pld_name.loc); CommentTable::attach(&mut t.leading, ld.pld_name.loc.clone(), before_name); @@ -884,7 +898,7 @@ fn walk_label_declaration(ld: &LabelDeclaration, t: &mut CommentTable, comments: 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); + walk_core_type(&ld.pld_type, t, inside_typ, arena); CommentTable::attach(&mut t.trailing, ld.pld_type.ptyp_loc.clone(), after_typ); } @@ -892,14 +906,16 @@ fn walk_constructor_declarations( cds: &[ConstructorDeclaration], t: &mut CommentTable, comments: Vec, + arena: &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| walk_constructor_declaration(cd, t, comments, arena), t, comments, false, + arena, ) } @@ -907,6 +923,7 @@ fn walk_constructor_declaration( cd: &ConstructorDeclaration, t: &mut CommentTable, comments: Vec, + arena: &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); @@ -914,47 +931,50 @@ fn walk_constructor_declaration( 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 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, &arena.to_location(typexpr.ptyp_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(typexpr.ptyp_loc), before_typ); + walk_core_type(typexpr, t, inside_typ, arena); + let (after_typ_adj, rest) = partition_adjacent_trailing(&arena.to_location(typexpr.ptyp_loc), after_typ); + CommentTable::attach(&mut t.trailing, arena.to_location(typexpr.ptyp_loc), after_typ_adj); rest } None => rest, }; - CommentTable::attach(&mut t.trailing, cd.pcd_loc.clone(), rest); + CommentTable::attach(&mut t.trailing, arena.to_location(cd.pcd_loc), rest); } fn walk_constructor_arguments( args: &ConstructorArguments, t: &mut CommentTable, comments: Vec, + arena: &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| 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| walk_label_declaration(ld, t, comments, arena), t, comments, false, + arena, ) } } @@ -964,6 +984,7 @@ fn walk_extension_constructor( ec: &ExtensionConstructor, t: &mut CommentTable, comments: Vec, + arena: &ParseArena, ) { let (leading, trailing) = partition_leading_trailing(comments, &ec.pext_name.loc); CommentTable::attach(&mut t.leading, ec.pext_name.loc.clone(), leading); @@ -973,75 +994,76 @@ fn walk_extension_constructor( 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, &arena.to_location(typexpr.ptyp_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(typexpr.ptyp_loc), before_typ); + walk_core_type(typexpr, t, inside_typ, arena); + CommentTable::attach(&mut t.trailing, arena.to_location(typexpr.ptyp_loc), after_typ); } } 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, &arena.to_location(lid.loc)); + CommentTable::attach(&mut t.leading, arena.to_location(lid.loc), leading); + CommentTable::attach(&mut t.trailing, arena.to_location(lid.loc), trailing); } } } -fn walk_expression(expr: &Expression, t: &mut CommentTable, comments: Vec) { +fn walk_expression(expr: &Expression, t: &mut CommentTable, comments: Vec, arena: &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, &arena.to_location(expr.pexp_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(expr.pexp_loc), leading); + CommentTable::attach(&mut t.trailing, arena.to_location(expr.pexp_loc), trailing); } 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, &arena.to_location(longident.loc)); + CommentTable::attach(&mut t.leading, arena.to_location(longident.loc), leading); + CommentTable::attach(&mut t.trailing, arena.to_location(longident.loc), trailing); } 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); + 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| 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, &arena.to_location(body.pexp_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(body.pexp_loc), leading); + walk_expression(body, t, inside, arena); + CommentTable::attach(&mut t.trailing, arena.to_location(body.pexp_loc), trailing); } } } ExpressionDesc::Pexp_sequence(lhs, rhs) => { - let (leading, inside, trailing) = partition_by_loc(comments, &lhs.pexp_loc); + let (leading, inside, trailing) = partition_by_loc(comments, &arena.to_location(lhs.pexp_loc)); 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(&arena.to_location(lhs.pexp_loc), trailing); let combined: Vec = leading .into_iter() .chain(inside.into_iter()) @@ -1050,41 +1072,43 @@ 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 = lid.loc.loc_end.clone(); + let (leading, comments) = partition_leading_trailing(comments, &arena.to_location(expr.pexp_loc)); + let combined_loc = Location::from_positions( + arena.loc_start(expr.pexp_loc).clone(), + arena.loc_end(lid.loc).clone(), + ); CommentTable::attach(&mut t.leading, combined_loc, leading); - 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, &arena.to_location(lid.loc)); + CommentTable::attach(&mut t.leading, arena.to_location(lid.loc), leading); let (after_longident, rest) = partition_by_on_same_line(&lid.loc, trailing); - CommentTable::attach(&mut t.trailing, lid.loc.clone(), after_longident); + CommentTable::attach(&mut t.trailing, arena.to_location(lid.loc), after_longident); 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, &arena.to_location(body.pexp_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(body.pexp_loc), leading); + walk_expression(body, t, inside, arena); + CommentTable::attach(&mut t.trailing, arena.to_location(body.pexp_loc), trailing); } } ExpressionDesc::Pexp_extension(ext) => { @@ -1099,157 +1123,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(); + let (leading, comments) = partition_leading_trailing(comments, &arena.to_location(expr.pexp_loc)); + let combined_loc = Location::from_positions( + arena.loc_start(expr.pexp_loc).clone(), + arena.loc_end(ext.pext_loc).clone(), + ); CommentTable::attach(&mut t.leading, combined_loc, leading); - 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, &arena.to_location(ext.pext_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(ext.pext_loc), leading); + 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(&arena.to_location(ext.pext_loc), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(ext.pext_loc), after_ext_constr); 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, &arena.to_location(body.pexp_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(body.pexp_loc), leading); + walk_expression(body, t, inside, arena); + CommentTable::attach(&mut t.trailing, arena.to_location(body.pexp_loc), trailing); } } 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(); + let (leading, comments) = partition_leading_trailing(comments, &arena.to_location(expr.pexp_loc)); + let combined_loc = Location::from_positions( + arena.loc_start(expr.pexp_loc).clone(), + arena.loc_end(module.pmod_loc).clone(), + ); CommentTable::attach(&mut t.leading, combined_loc, leading); - 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, &arena.to_location(name.loc)); + CommentTable::attach(&mut t.leading, arena.to_location(name.loc), leading); - 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(&arena.to_location(name.loc), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(name.loc), after_string); 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); + partition_by_loc(rest, &arena.to_location(module.pmod_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(module.pmod_loc), before_mod_expr); walk_module_expr(module, t, inside_mod_expr); - 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(&arena.to_location(module.pmod_loc), after_mod_expr); + CommentTable::attach(&mut t.trailing, arena.to_location(module.pmod_loc), after_mod_expr_adj); 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, &arena.to_location(body.pexp_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(body.pexp_loc), leading); + walk_expression(body, t, inside, arena); + CommentTable::attach(&mut t.trailing, arena.to_location(body.pexp_loc), trailing); } } 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, &arena.to_location(inner.pexp_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(inner.pexp_loc), leading); + walk_expression(inner, t, inside, arena); + CommentTable::attach(&mut t.trailing, arena.to_location(inner.pexp_loc), trailing); } } 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, &arena.to_location(inner.pexp_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(inner.pexp_loc), leading); + 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(&arena.to_location(inner.pexp_loc), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(inner.pexp_loc), after_expr); - 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, &arena.to_location(typ.ptyp_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(typ.ptyp_loc), leading); + walk_core_type(typ, t, inside, arena); + CommentTable::attach(&mut t.trailing, arena.to_location(typ.ptyp_loc), trailing); } 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, &arena.to_location(inner.pexp_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(inner.pexp_loc), leading); + 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(&arena.to_location(inner.pexp_loc), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(inner.pexp_loc), after_expr); - 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, &arena.to_location(typ.ptyp_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(typ.ptyp_loc), leading); + walk_core_type(typ, t, inside, arena); + CommentTable::attach(&mut t.trailing, arena.to_location(typ.ptyp_loc), trailing); } ExpressionDesc::Pexp_tuple(exprs) if exprs.is_empty() => { - CommentTable::attach(&mut t.inside, expr.pexp_loc.clone(), comments); + CommentTable::attach(&mut t.inside, arena.to_location(expr.pexp_loc), comments); } ExpressionDesc::Pexp_array(exprs) if exprs.is_empty() => { - CommentTable::attach(&mut t.inside, expr.pexp_loc.clone(), comments); + CommentTable::attach(&mut t.inside, arena.to_location(expr.pexp_loc), comments); } ExpressionDesc::Pexp_construct(name, None) if name.txt == Longident::Lident("[]".to_string()) => { - CommentTable::attach(&mut t.inside, expr.pexp_loc.clone(), comments); + CommentTable::attach(&mut t.inside, arena.to_location(expr.pexp_loc), comments); } ExpressionDesc::Pexp_construct(name, Some(_)) if name.txt == Longident::Lident("::".to_string()) => { let list_exprs = collect_list_exprs(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, &arena.to_location(name.loc)); + CommentTable::attach(&mut t.leading, arena.to_location(name.loc), leading); 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(&arena.to_location(name.loc), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(name.loc), after_longident); + walk_expression(arg_expr, t, rest, arena); } None => { - CommentTable::attach(&mut t.trailing, name.loc.clone(), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(name.loc), trailing); } } } 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); + CommentTable::attach(&mut t.inside, arena.to_location(expr.pexp_loc), comments); } 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, &arena.to_location(spread_expr.pexp_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(spread_expr.pexp_loc), leading); + 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(&arena.to_location(spread_expr.pexp_loc), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(spread_expr.pexp_loc), after_expr); rest } }; @@ -1258,14 +1286,14 @@ 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, &arena.to_location(inner.pexp_loc)); 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(&arena.to_location(inner.pexp_loc), trailing); let combined: Vec = leading .into_iter() .chain(inside.into_iter()) @@ -1274,23 +1302,23 @@ fn walk_expression(expr: &Expression, t: &mut CommentTable, comments: Vec { - let (leading, inside, trailing) = partition_by_loc(comments, &obj.pexp_loc); + let (leading, inside, trailing) = partition_by_loc(comments, &arena.to_location(obj.pexp_loc)); 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(&arena.to_location(obj.pexp_loc), trailing); let combined: Vec = leading .into_iter() .chain(inside.into_iter()) @@ -1299,36 +1327,36 @@ fn walk_expression(expr: &Expression, t: &mut CommentTable, comments: Vec { - 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, &arena.to_location(expr.pexp_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(expr.pexp_loc), leading); - let (leading, inside, trailing) = partition_by_loc(rest, &cond.pexp_loc); + let (leading, inside, trailing) = partition_by_loc(rest, &arena.to_location(cond.pexp_loc)); 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(&arena.to_location(cond.pexp_loc), trailing); let combined: Vec = leading .into_iter() .chain(inside.into_iter()) @@ -1337,18 +1365,18 @@ fn walk_expression(expr: &Expression, t: &mut CommentTable, comments: Vec = leading .into_iter() .chain(inside.into_iter()) @@ -1357,31 +1385,31 @@ fn walk_expression(expr: &Expression, t: &mut CommentTable, comments: Vec { - let (leading, inside, trailing) = partition_by_loc(comments, &cond.pexp_loc); + let (leading, inside, trailing) = partition_by_loc(comments, &arena.to_location(cond.pexp_loc)); 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(&arena.to_location(cond.pexp_loc), trailing); let combined: Vec = leading .into_iter() .chain(inside.into_iter()) @@ -1390,66 +1418,66 @@ fn walk_expression(expr: &Expression, t: &mut CommentTable, comments: Vec { - 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, &arena.to_location(pat.ppat_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(pat.ppat_loc), leading); + 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(&arena.to_location(pat.ppat_loc), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(pat.ppat_loc), after_pat); - 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, &arena.to_location(from.pexp_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(from.pexp_loc), leading); + 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(&arena.to_location(from.pexp_loc), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(from.pexp_loc), after_expr); - 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, &arena.to_location(to.pexp_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(to.pexp_loc), leading); + 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(&arena.to_location(to.pexp_loc), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(to.pexp_loc), after_expr); 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, &arena.to_location(body.pexp_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(body.pexp_loc), leading); + walk_expression(body, t, inside, arena); + CommentTable::attach(&mut t.trailing, arena.to_location(body.pexp_loc), trailing); } } 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, &arena.to_location(mod_expr.pmod_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(mod_expr.pmod_loc), before); + walk_module_expr(mod_expr, t, inside, arena); + CommentTable::attach(&mut t.trailing, arena.to_location(mod_expr.pmod_loc), after); } 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, &arena.to_location(match_expr.pexp_loc)); let after = if is_block_expr(match_expr) { let (after_expr, rest) = - partition_adjacent_trailing(&match_expr.pexp_loc, after); + partition_adjacent_trailing(&arena.to_location(match_expr.pexp_loc), after); let combined: Vec = before .into_iter() .chain(inside.into_iter()) @@ -1458,16 +1486,16 @@ fn walk_expression(expr: &Expression, t: &mut CommentTable, comments: 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 @@ -1480,10 +1508,10 @@ fn walk_expression(expr: &Expression, t: &mut CommentTable, comments: Vec { // Walk through the function parameters and body - walk_expression(body, t, comments); + walk_expression(body, t, comments, 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, t, comments, arena); } } } -fn walk_jsx_element(jsx: &JsxElement, t: &mut CommentTable, comments: Vec) { +fn walk_jsx_element(jsx: &JsxElement, t: &mut CommentTable, comments: Vec, arena: &ParseArena) { if comments.is_empty() { return; } @@ -1514,7 +1542,7 @@ fn walk_jsx_element(jsx: &JsxElement, t: &mut CommentTable, comments: Vec { let nodes: Vec> = fragment.children.iter().map(|e| Node::Expression(e)).collect(); - walk_list(&nodes, t, comments); + walk_list(&nodes, t, comments, arena); } JsxElement::Unary(unary) => { // Walk the props @@ -1531,32 +1559,32 @@ fn walk_jsx_element(jsx: &JsxElement, t: &mut CommentTable, comments: Vec> = container.children.iter().map(|e| Node::Expression(e)).collect(); - walk_list(&nodes, t, comments); + walk_list(&nodes, t, comments, arena); } } } -fn walk_jsx_prop(prop: &JsxProp, t: &mut CommentTable, comments: Vec) { +fn walk_jsx_prop(prop: &JsxProp, t: &mut CommentTable, comments: Vec, arena: &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, &arena.to_location(name.loc)); + CommentTable::attach(&mut t.leading, arena.to_location(name.loc), leading); + CommentTable::attach(&mut t.trailing, arena.to_location(name.loc), trailing); } JsxProp::Value { name, value, .. } => { - 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, &arena.to_location(name.loc)); + CommentTable::attach(&mut t.leading, arena.to_location(name.loc), leading); - let (after_lbl, rest) = partition_adjacent_trailing(&name.loc, trailing); - CommentTable::attach(&mut t.trailing, name.loc.clone(), after_lbl); + let (after_lbl, rest) = partition_adjacent_trailing(&arena.to_location(name.loc), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(name.loc), 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); + let (before, inside, after) = partition_by_loc(rest, &arena.to_location(value.pexp_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(value.pexp_loc), before); + walk_expression(value, t, inside, arena); + CommentTable::attach(&mut t.trailing, arena.to_location(value.pexp_loc), after); } JsxProp::Spreading { expr, .. } => { - walk_expression(expr, t, comments); + walk_expression(expr, t, comments, arena); } } } @@ -1566,52 +1594,54 @@ fn walk_apply_expr( arguments: &[(ArgLabel, Expression)], t: &mut CommentTable, comments: Vec, + arena: &ParseArena, ) { - let (before, inside, after) = partition_by_loc(comments, &call_expr.pexp_loc); + let (before, inside, after) = partition_by_loc(comments, &arena.to_location(call_expr.pexp_loc)); 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(&arena.to_location(call_expr.pexp_loc), after); 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); + CommentTable::attach(&mut t.leading, arena.to_location(call_expr.pexp_loc), before); + 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(&arena.to_location(call_expr.pexp_loc), after); + CommentTable::attach(&mut t.trailing, arena.to_location(call_expr.pexp_loc), after_expr); 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: &ParseArena, ) { - walk_expression(expr, t, comments); + walk_expression(expr, t, comments, arena); } fn walk_expr_record_row( @@ -1619,176 +1649,178 @@ fn walk_expr_record_row( expr: &Expression, t: &mut CommentTable, comments: Vec, + arena: &ParseArena, ) { - let (leading, trailing) = partition_leading_trailing(comments, &li.loc); - CommentTable::attach(&mut t.leading, li.loc.clone(), leading); + let li_loc = arena.to_location(li.loc); + let (leading, trailing) = partition_leading_trailing(comments, &li_loc); + CommentTable::attach(&mut t.leading, li_loc.clone(), leading); - 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); + CommentTable::attach(&mut t.trailing, li_loc, after_li); - 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, &arena.to_location(expr.pexp_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(expr.pexp_loc), before); + walk_expression(expr, t, inside, arena); + CommentTable::attach(&mut t.trailing, arena.to_location(expr.pexp_loc), after); } -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: &ParseArena) { + let (before, inside, after) = partition_by_loc(comments, &arena.to_location(case.pc_lhs.ppat_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(case.pc_lhs.ppat_loc), before); + walk_pattern(&case.pc_lhs, t, inside, 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(&arena.to_location(case.pc_lhs.ppat_loc), after); + CommentTable::attach(&mut t.trailing, arena.to_location(case.pc_lhs.ppat_loc), after_pat); // Handle guard 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, &arena.to_location(guard.pexp_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(guard.pexp_loc), before); + walk_expression(guard, t, inside, arena); + let (after_guard, rest) = partition_adjacent_trailing(&arena.to_location(guard.pexp_loc), after); + CommentTable::attach(&mut t.trailing, arena.to_location(guard.pexp_loc), after_guard); 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, &arena.to_location(case.pc_rhs.pexp_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(case.pc_rhs.pexp_loc), before); + walk_expression(&case.pc_rhs, t, inside, arena); + CommentTable::attach(&mut t.trailing, arena.to_location(case.pc_rhs.pexp_loc), after); } } -fn walk_pattern(pattern: &Pattern, t: &mut CommentTable, comments: Vec) { +fn walk_pattern(pattern: &Pattern, t: &mut CommentTable, comments: Vec, arena: &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, &arena.to_location(pattern.ppat_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(pattern.ppat_loc), leading); + CommentTable::attach(&mut t.trailing, arena.to_location(pattern.ppat_loc), trailing); } 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, &arena.to_location(name.loc)); + CommentTable::attach(&mut t.leading, arena.to_location(name.loc), leading); + CommentTable::attach(&mut t.trailing, arena.to_location(name.loc), trailing); } 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, &arena.to_location(pat.ppat_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(pat.ppat_loc), before); + 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(&arena.to_location(pat.ppat_loc), after); + CommentTable::attach(&mut t.trailing, arena.to_location(pat.ppat_loc), after_pat); 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); + CommentTable::attach(&mut t.leading, arena.to_location(name.loc), leading); + CommentTable::attach(&mut t.trailing, arena.to_location(name.loc), trailing); } PatternDesc::Ppat_tuple(pats) if pats.is_empty() => { - CommentTable::attach(&mut t.inside, pattern.ppat_loc.clone(), comments); + CommentTable::attach(&mut t.inside, arena.to_location(pattern.ppat_loc), comments); } PatternDesc::Ppat_array(pats) if pats.is_empty() => { - CommentTable::attach(&mut t.inside, pattern.ppat_loc.clone(), comments); + CommentTable::attach(&mut t.inside, arena.to_location(pattern.ppat_loc), comments); } PatternDesc::Ppat_construct(name, None) if name.txt == Longident::Lident("[]".to_string()) => { - CommentTable::attach(&mut t.inside, pattern.ppat_loc.clone(), comments); + CommentTable::attach(&mut t.inside, arena.to_location(pattern.ppat_loc), comments); } PatternDesc::Ppat_construct(name, Some(_)) if name.txt == Longident::Lident("::".to_string()) => { let list_pats = collect_list_patterns(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, &arena.to_location(name.loc)); + CommentTable::attach(&mut t.leading, arena.to_location(name.loc), leading); 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(&arena.to_location(name.loc), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(name.loc), after_longident); + walk_pattern(arg_pat, t, rest, arena); } None => { - CommentTable::attach(&mut t.trailing, name.loc.clone(), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(name.loc), trailing); } } } 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 (before, inside, after) = partition_by_loc(comments, &arena.to_location(lhs.ppat_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(lhs.ppat_loc), before); + walk_pattern(lhs, t, inside, arena); - let (after_lhs, rest) = partition_adjacent_trailing(&lhs.ppat_loc, after); - CommentTable::attach(&mut t.trailing, lhs.ppat_loc.clone(), after_lhs); + let (after_lhs, rest) = partition_adjacent_trailing(&arena.to_location(lhs.ppat_loc), after); + CommentTable::attach(&mut t.trailing, arena.to_location(lhs.ppat_loc), 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); + let (before, inside, after) = partition_by_loc(rest, &arena.to_location(rhs.ppat_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(rhs.ppat_loc), before); + walk_pattern(rhs, t, inside, arena); + CommentTable::attach(&mut t.trailing, arena.to_location(rhs.ppat_loc), after); } 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, &arena.to_location(pat.ppat_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(pat.ppat_loc), before); + 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(&arena.to_location(pat.ppat_loc), after); + CommentTable::attach(&mut t.trailing, arena.to_location(pat.ppat_loc), after_pat); - 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, &arena.to_location(typ.ptyp_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(typ.ptyp_loc), before); + walk_core_type(typ, t, inside, arena); + CommentTable::attach(&mut t.trailing, arena.to_location(typ.ptyp_loc), after); } 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, &arena.to_location(lid.loc)); + CommentTable::attach(&mut t.leading, arena.to_location(lid.loc), leading); + CommentTable::attach(&mut t.trailing, arena.to_location(lid.loc), trailing); } 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, &arena.to_location(name.loc)); + CommentTable::attach(&mut t.leading, arena.to_location(name.loc), leading); + CommentTable::attach(&mut t.trailing, arena.to_location(name.loc), trailing); } 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, &arena.to_location(lid.loc)); + CommentTable::attach(&mut t.leading, arena.to_location(lid.loc), leading); - 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(&arena.to_location(lid.loc), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(lid.loc), after_lid); - walk_pattern(pat, t, rest); + walk_pattern(pat, t, rest, arena); } } } @@ -1798,152 +1830,156 @@ fn walk_pattern_record_row( pat: &Pattern, t: &mut CommentTable, comments: Vec, + arena: &ParseArena, ) { - let (leading, trailing) = partition_leading_trailing(comments, &li.loc); - CommentTable::attach(&mut t.leading, li.loc.clone(), leading); + let li_loc = arena.to_location(li.loc); + let (leading, trailing) = partition_leading_trailing(comments, &li_loc); + CommentTable::attach(&mut t.leading, li_loc.clone(), leading); - 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); + CommentTable::attach(&mut t.trailing, li_loc, after_li); - 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, &arena.to_location(pat.ppat_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(pat.ppat_loc), before); + walk_pattern(pat, t, inside, arena); + CommentTable::attach(&mut t.trailing, arena.to_location(pat.ppat_loc), after); } -fn walk_core_type(ct: &CoreType, t: &mut CommentTable, comments: Vec) { +fn walk_core_type(ct: &CoreType, t: &mut CommentTable, comments: Vec, arena: &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, &arena.to_location(ct.ptyp_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(ct.ptyp_loc), leading); + CommentTable::attach(&mut t.trailing, arena.to_location(ct.ptyp_loc), trailing); } 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, &arena.to_location(name.loc)); + CommentTable::attach(&mut t.leading, arena.to_location(name.loc), leading); if args.is_empty() { - CommentTable::attach(&mut t.trailing, name.loc.clone(), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(name.loc), trailing); } 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(&arena.to_location(name.loc), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(name.loc), after_name); 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| 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); + walk_core_type(&arg.typ, t, inside, arena); let (after_arg, rest) = partition_adjacent_trailing(&arg.typ.ptyp_loc, after); CommentTable::attach(&mut t.trailing, arg.typ.ptyp_loc.clone(), after_arg); - 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); + let (before, inside, after) = partition_by_loc(rest, &arena.to_location(ret.ptyp_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(ret.ptyp_loc), before); + walk_core_type(ret, t, inside, arena); + CommentTable::attach(&mut t.trailing, arena.to_location(ret.ptyp_loc), after); } 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); + walk_core_type(typ, t, comments, 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, &arena.to_location(name.loc)); + CommentTable::attach(&mut t.leading, arena.to_location(name.loc), leading); if constraints.is_empty() { - CommentTable::attach(&mut t.trailing, name.loc.clone(), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(name.loc), trailing); } 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(&arena.to_location(name.loc), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(name.loc), after_name); 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, &arena.to_location(typ.ptyp_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(typ.ptyp_loc), before); + walk_core_type(typ, t, inside, arena); + CommentTable::attach(&mut t.trailing, arena.to_location(typ.ptyp_loc), after); } 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) { +fn walk_object_field(field: &ObjectField, t: &mut CommentTable, comments: Vec, arena: &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, &arena.to_location(lbl.loc)); + CommentTable::attach(&mut t.leading, arena.to_location(lbl.loc), leading); - 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(&arena.to_location(lbl.loc), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(lbl.loc), after_lbl); - 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, &arena.to_location(typ.ptyp_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(typ.ptyp_loc), before); + walk_core_type(typ, t, inside, arena); + CommentTable::attach(&mut t.trailing, arena.to_location(typ.ptyp_loc), after); } 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: &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, &arena.to_location(tag.loc)); + CommentTable::attach(&mut t.leading, arena.to_location(tag.loc), leading); if args.is_empty() { - CommentTable::attach(&mut t.trailing, tag.loc.clone(), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(tag.loc), trailing); } else { let (after_tag, rest) = partition_adjacent_trailing(&tag.loc, trailing); - CommentTable::attach(&mut t.trailing, tag.loc.clone(), after_tag); + CommentTable::attach(&mut t.trailing, arena.to_location(tag.loc), after_tag); 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| 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); } } } @@ -1953,47 +1989,49 @@ fn walk_package_constraint( typ: &CoreType, t: &mut CommentTable, comments: Vec, + arena: &ParseArena, ) { - let (leading, trailing) = partition_leading_trailing(comments, &li.loc); - CommentTable::attach(&mut t.leading, li.loc.clone(), leading); + let li_loc = arena.to_location(li.loc); + let (leading, trailing) = partition_leading_trailing(comments, &li_loc); + CommentTable::attach(&mut t.leading, li_loc.clone(), leading); - 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); + CommentTable::attach(&mut t.trailing, li_loc, after_li); - 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, &arena.to_location(typ.ptyp_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(typ.ptyp_loc), before); + walk_core_type(typ, t, inside, arena); + CommentTable::attach(&mut t.trailing, arena.to_location(typ.ptyp_loc), after); } -fn walk_module_expr(me: &ModuleExpr, t: &mut CommentTable, comments: Vec) { +fn walk_module_expr(me: &ModuleExpr, t: &mut CommentTable, comments: Vec, arena: &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, &arena.to_location(lid.loc)); + CommentTable::attach(&mut t.leading, arena.to_location(lid.loc), leading); + CommentTable::attach(&mut t.trailing, arena.to_location(lid.loc), trailing); } 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 (leading, trailing) = partition_leading_trailing(comments, &arena.to_location(name.loc)); + CommentTable::attach(&mut t.leading, arena.to_location(name.loc), leading); - 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(&arena.to_location(name.loc), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(name.loc), 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); + walk_mod_type(mod_type, t, inside, arena); 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); @@ -2002,74 +2040,74 @@ fn walk_module_expr(me: &ModuleExpr, t: &mut CommentTable, comments: Vec 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(rest, &arena.to_location(body.pmod_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(body.pmod_loc), before); + walk_module_expr(body, t, inside, arena); + CommentTable::attach(&mut t.trailing, arena.to_location(body.pmod_loc), after); } 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 (before, inside, after) = partition_by_loc(comments, &arena.to_location(funct.pmod_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(funct.pmod_loc), before); + walk_module_expr(funct, t, inside, arena); - let (after_funct, rest) = partition_adjacent_trailing(&funct.pmod_loc, after); - CommentTable::attach(&mut t.trailing, funct.pmod_loc.clone(), after_funct); + let (after_funct, rest) = partition_adjacent_trailing(&arena.to_location(funct.pmod_loc), after); + CommentTable::attach(&mut t.trailing, arena.to_location(funct.pmod_loc), 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); + let (before, inside, after) = partition_by_loc(rest, &arena.to_location(arg.pmod_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(arg.pmod_loc), before); + walk_module_expr(arg, t, inside, arena); + CommentTable::attach(&mut t.trailing, arena.to_location(arg.pmod_loc), after); } 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 (before, inside, after) = partition_by_loc(comments, &arena.to_location(module_expr.pmod_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(module_expr.pmod_loc), before); + walk_module_expr(module_expr, t, inside, arena); - 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 (after_mod, rest) = partition_adjacent_trailing(&arena.to_location(module_expr.pmod_loc), after); + CommentTable::attach(&mut t.trailing, arena.to_location(module_expr.pmod_loc), 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); + walk_mod_type(mod_type, t, inside, arena); CommentTable::attach(&mut t.trailing, mod_type.pmty_loc.clone(), after); } 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) { +fn walk_mod_type(mt: &ModuleType, t: &mut CommentTable, comments: Vec, arena: &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, &arena.to_location(lid.loc)); + CommentTable::attach(&mut t.leading, arena.to_location(lid.loc), leading); + CommentTable::attach(&mut t.trailing, arena.to_location(lid.loc), trailing); } 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 (leading, trailing) = partition_leading_trailing(comments, &arena.to_location(name.loc)); + CommentTable::attach(&mut t.leading, arena.to_location(name.loc), leading); - 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(&arena.to_location(name.loc), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(name.loc), 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); + walk_mod_type(mod_type, t, inside, arena); 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); @@ -2080,13 +2118,13 @@ fn walk_mod_type(mt: &ModuleType, t: &mut CommentTable, comments: Vec) 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); + walk_mod_type(ret, t, inside, arena); CommentTable::attach(&mut t.trailing, ret.pmty_loc.clone(), after); } 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); + 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); @@ -2097,32 +2135,32 @@ fn walk_mod_type(mt: &ModuleType, t: &mut CommentTable, comments: Vec) 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); + CommentTable::attach(&mut t.leading, arena.to_location(lid.loc), leading); + 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(), &arena.to_location(mod_lid.loc)); + CommentTable::attach(&mut t.leading, arena.to_location(mod_lid.loc), leading); + let (after_mod, rest2) = partition_adjacent_trailing(&arena.to_location(mod_lid.loc), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(mod_lid.loc), after_mod); + let (leading, trailing) = partition_leading_trailing(rest2, &arena.to_location(target_lid.loc)); + CommentTable::attach(&mut t.leading, arena.to_location(target_lid.loc), leading); + CommentTable::attach(&mut t.trailing, arena.to_location(target_lid.loc), trailing); } } } } ModuleTypeDesc::Pmty_typeof(me) => { - walk_module_expr(me, t, comments); + walk_module_expr(me, t, comments, 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, &arena.to_location(lid.loc)); + CommentTable::attach(&mut t.leading, arena.to_location(lid.loc), leading); + CommentTable::attach(&mut t.trailing, arena.to_location(lid.loc), trailing); } } } @@ -2131,38 +2169,38 @@ fn walk_attribute(_attr: &Attribute, _t: &mut CommentTable, _comments: Vec) { +fn walk_extension(ext: &Extension, t: &mut CommentTable, comments: Vec, arena: &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, &arena.to_location(name.loc)); + CommentTable::attach(&mut t.leading, arena.to_location(name.loc), leading); 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); + let (after_name, rest) = partition_adjacent_trailing(&arena.to_location(name.loc), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(name.loc), after_name); walk_structure(items, t, rest); } else { - CommentTable::attach(&mut t.trailing, name.loc.clone(), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(name.loc), trailing); } } 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); + let (after_name, rest) = partition_adjacent_trailing(&arena.to_location(name.loc), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(name.loc), after_name); walk_signature(items, t, rest); } else { - CommentTable::attach(&mut t.trailing, name.loc.clone(), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(name.loc), trailing); } } 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(&arena.to_location(name.loc), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(name.loc), after_name); + 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); + let (after_name, rest) = partition_adjacent_trailing(&arena.to_location(name.loc), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(name.loc), after_name); walk_pattern(pat, t, rest.clone()); if let Some(guard_expr) = guard { walk_expression(guard_expr, t, Vec::new()); @@ -2174,23 +2212,25 @@ fn walk_extension(ext: &Extension, t: &mut CommentTable, comments: Vec) /// 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, + get_loc: impl Fn(&'a T, &ParseArena) -> LocIdx, walk_node: impl Fn(&'a T, &mut CommentTable, Vec), t: &mut CommentTable, comments: Vec, newline_delimited: bool, + arena: &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, + get_loc: impl Fn(&'a T, &ParseArena) -> LocIdx, walk_node: impl Fn(&'a T, &mut CommentTable, Vec), t: &mut CommentTable, comments: Vec, newline_delimited: bool, prev_loc: Option, + arena: &ParseArena, ) -> Vec { if comments.is_empty() { return Vec::new(); @@ -2212,9 +2252,9 @@ fn visit_list_impl<'a, T>( let node = &nodes[0]; let rest_nodes = &nodes[1..]; - let curr_loc = get_loc(node); + let curr_loc = arena.to_location(get_loc(node, arena)); - let (leading, inside, trailing) = partition_by_loc(comments, curr_loc); + let (leading, inside, trailing) = partition_by_loc(comments, &curr_loc); match &prev_loc { None => { @@ -2230,7 +2270,7 @@ fn visit_list_impl<'a, T>( } 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); + let (before_curr, _, _) = partition_by_loc(after_prev, &curr_loc); CommentTable::attach(&mut t.leading, curr_loc.clone(), before_curr); } } @@ -2244,7 +2284,8 @@ fn visit_list_impl<'a, T>( t, trailing, newline_delimited, - Some(curr_loc.clone()), + Some(curr_loc), + arena, ) } From 6fe9ccfb277fe4c45d942c07dc6d8f7f433c02a7 Mon Sep 17 00:00:00 2001 From: Jaap Frolich Date: Wed, 28 Jan 2026 22:26:43 +0100 Subject: [PATCH 006/464] WIP --- compiler-rust/src/bin/res_parser.rs | 4 +- compiler-rust/src/binary_ast/mapper_from0.rs | 2036 ++++---- compiler-rust/src/binary_ast/mapper_to0.rs | 2233 +++++---- compiler-rust/src/binary_ast/writer.rs | 21 +- compiler-rust/src/parse_arena.rs | 8 + compiler-rust/src/parser/comment_table.rs | 100 +- compiler-rust/src/parser/core.rs | 6 +- compiler-rust/src/parser/expr.rs | 98 +- compiler-rust/src/parser/jsx_ppx.rs | 290 +- compiler-rust/src/parser/mod.rs | 5 - compiler-rust/src/parser/module.rs | 211 +- compiler-rust/src/parser/parens.rs | 8 +- compiler-rust/src/parser/parsetree_viewer.rs | 12 +- compiler-rust/src/parser/pattern.rs | 101 +- compiler-rust/src/parser/printer.rs | 4664 ------------------ compiler-rust/src/parser/printer2.rs | 2 +- compiler-rust/src/parser/state.rs | 14 + compiler-rust/src/parser/typ.rs | 147 +- 18 files changed, 2724 insertions(+), 7236 deletions(-) delete mode 100644 compiler-rust/src/parser/printer.rs diff --git a/compiler-rust/src/bin/res_parser.rs b/compiler-rust/src/bin/res_parser.rs index 00b620919c5..7789c84e53c 100644 --- a/compiler-rust/src/bin/res_parser.rs +++ b/compiler-rust/src/bin/res_parser.rs @@ -175,7 +175,7 @@ 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 { @@ -262,7 +262,7 @@ 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 { diff --git a/compiler-rust/src/binary_ast/mapper_from0.rs b/compiler-rust/src/binary_ast/mapper_from0.rs index 9fe64c76df8..52c52a11aa6 100644 --- a/compiler-rust/src/binary_ast/mapper_from0.rs +++ b/compiler-rust/src/binary_ast/mapper_from0.rs @@ -13,35 +13,30 @@ //! //! This mirrors `compiler/ml/ast_mapper_from0.ml`. -use crate::location::{Located, Location}; +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 +136,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 +181,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 +201,135 @@ 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()) + } + + /// Create a Located value with given text and location + fn mkloc(&mut self, txt: T, loc: &FullLocation) -> Located { + Located { + txt, + loc: self.loc(loc), } - 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, - }; + } + + // ========== 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)))) + } + } + } + + // ========== 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 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 +337,350 @@ fn map_core_type(typ: &pt0::CoreType) -> current::CoreType { } } } + + current::CoreTypeDesc::Ptyp_constr(self.map_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_loc(l), self.map_core_type(t))) + .collect(); + current::CoreTypeDesc::Ptyp_package((self.map_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()) - } - 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)) + current::CoreType { + ptyp_desc: desc, + ptyp_loc: loc, + ptyp_attributes: attrs, } - 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_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_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_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_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 ========== -fn map_expression(expr: &pt0::Expression) -> current::Expression { - let loc = expr.pexp_loc.clone(); - let attrs = 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_await(Box::new(map_expression(&inner_expr))), - pexp_loc: loc, - pexp_attributes: vec![], - }; + // ========== Expression mapping ========== + + /// 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 matches!(&lid.txt, Longident::Lident(s) if s == "::") => + { + 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 matches!(&lid.txt, Longident::Lident(s) if s == "[]") => + { + 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) if name == "_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) => { + // 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: self.map_loc(lid).map(|_| name.clone()), + }); + } + } + } + Some(current::JsxProp::Value { + name: Located::mknoloc(name.clone()), + optional: false, + value: self.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: self.map_loc(lid).map(|_| name.clone()), + }); + } + } + } + Some(current::JsxProp::Value { + name: Located::mknoloc(name.clone()), + 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) if name == "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(), + /// Converts a longident to a JSX tag name + fn longident_to_jsx_tag(&self, 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(), } - } else { - func.as_ref().clone() - }; + } + other => current::JsxTagName::Upper(other.clone()), + } + } + 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_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 +688,664 @@ 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 new_name = match name.as_str() { + "|." => "->", + "^" => "++", + "<>" => "!=", + "!=" => "!==", + "=" => "==", + "==" => "===", + _ => name.as_str(), }; - let new_attrs = remove_arity_attribute(&attrs); + if new_name != name { + pt0::Expression { + pexp_desc: pt0::ExpressionDesc::Ident(OldLocated { + 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(), + } + } 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 { + if name == "[]" || name == "::" { + 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 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_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_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_loc(lid)) + } + pt0::ExpressionDesc::Setfield(e1, lid, e2) => current::ExpressionDesc::Pexp_setfield( + Box::new(self.map_expression(e1)), + self.map_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_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_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_loc(lid)), + pt0::ModuleTypeDesc::Alias(lid) => current::ModuleTypeDesc::Pmty_alias(self.map_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_loc(lid), self.map_type_declaration(td)) + } + pt0::WithConstraint::Module(lid1, lid2) => { + current::WithConstraint::Pwith_module(self.map_loc(lid1), self.map_loc(lid2)) + } + pt0::WithConstraint::TypeSubst(lid, td) => { + current::WithConstraint::Pwith_typesubst(self.map_loc(lid), self.map_type_declaration(td)) + } + pt0::WithConstraint::ModSubst(lid1, lid2) => { + current::WithConstraint::Pwith_modsubst(self.map_loc(lid1), self.map_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_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_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_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..4ec75687b65 100644 --- a/compiler-rust/src/binary_ast/mapper_to0.rs +++ b/compiler-rust/src/binary_ast/mapper_to0.rs @@ -14,1246 +14,1303 @@ //! //! This mirrors `compiler/common/ast_mapper_to0.ml`. -use crate::location::{Located, Location}; +use crate::location::{Location as FullLocation, Located as OldLocated}; +use crate::parse_arena::{Located, LocIdx, ParseArena}; use crate::parser::ast::{self as current}; 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: &ParseArena, str: &[current::StructureItem]) -> pt0::Structure { + let 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: &ParseArena, sig: &[current::SignatureItem]) -> pt0::Signature { + let mapper = Mapper::new(arena); + mapper.map_signature(sig) } -// ========== Helper functions ========== +// ========== Mapper struct ========== -fn mkloc(txt: T, loc: &Location) -> Located { - Located { - txt, - loc: loc.clone(), - } +/// 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 ParseArena, } -fn mk_optional_attr(loc: &Location) -> pt0::Attribute { - ( - Located::new("res.optional".to_string(), loc.clone()), - pt0::Payload::PStr(vec![]), - ) -} +impl<'a> Mapper<'a> { + pub fn new(arena: &'a ParseArena) -> Self { + Self { arena } + } -fn mk_async_attr(loc: &Location) -> pt0::Attribute { - ( - Located::new("res.async".to_string(), loc.clone()), - pt0::Payload::PStr(vec![]), - ) -} + /// Convert a LocIdx to full Location + fn loc(&self, idx: LocIdx) -> FullLocation { + self.arena.to_location(idx) + } -fn mk_await_attr(loc: &Location) -> pt0::Attribute { - ( - Located::new("res.await".to_string(), loc.clone()), - pt0::Payload::PStr(vec![]), - ) -} + /// Convert an arena-based Located to a full Located + fn map_loc(&self, located: &Located) -> OldLocated { + OldLocated { + txt: located.txt.clone(), + loc: self.loc(located.loc), + } + } -fn mk_partial_attr(loc: &Location) -> pt0::Attribute { - ( - Located::new("res.partial".to_string(), loc.clone()), - pt0::Payload::PStr(vec![]), - ) -} + /// Create an OldLocated from text and location index + #[allow(dead_code)] + fn mkloc(&self, txt: T, loc: LocIdx) -> OldLocated { + OldLocated { + txt, + loc: self.loc(loc), + } + } -#[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(), - }]), - ) -} + // ========== Public API methods ========== -// ========== JSX helpers ========== + /// Convert a structure from current parsetree to parsetree0 + pub fn map_structure(&self, str: &[current::StructureItem]) -> pt0::Structure { + str.iter().map(|item| self.map_structure_item(item)).collect() + } -fn mk_jsx_attr(loc: &Location) -> pt0::Attribute { - ( - Located::new("JSX".to_string(), loc.clone()), - pt0::Payload::PStr(vec![]), - ) -} + /// Convert a signature from current parsetree to parsetree0 + pub fn map_signature(&self, sig: &[current::SignatureItem]) -> pt0::Signature { + sig.iter().map(|item| self.map_signature_item(item)).collect() + } -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![], + // ========== Helper functions ========== + + #[allow(dead_code)] + fn mk_optional_attr(&self, loc: LocIdx) -> pt0::Attribute { + ( + OldLocated::new("res.optional".to_string(), self.loc(loc)), + pt0::Payload::PStr(vec![]), + ) } -} -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![], + #[allow(dead_code)] + fn mk_async_attr(&self, loc: LocIdx) -> pt0::Attribute { + ( + OldLocated::new("res.async".to_string(), self.loc(loc)), + pt0::Payload::PStr(vec![]), + ) } -} -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() -} + fn mk_await_attr(&self, loc: LocIdx) -> pt0::Attribute { + ( + OldLocated::new("res.await".to_string(), self.loc(loc)), + pt0::Payload::PStr(vec![]), + ) + } -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()) + #[allow(dead_code)] + fn mk_partial_attr(&self, loc: LocIdx) -> pt0::Attribute { + ( + OldLocated::new("res.partial".to_string(), self.loc(loc)), + pt0::Payload::PStr(vec![]), + ) + } + + #[allow(dead_code)] + fn mk_arity_attr(&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, + }]), + ) + } + + // ========== JSX helpers ========== + + fn mk_jsx_attr(&self, loc: LocIdx) -> pt0::Attribute { + ( + OldLocated::new("JSX".to_string(), self.loc(loc)), + pt0::Payload::PStr(vec![]), + ) + } + + fn mk_unit_expr(&self, loc: LocIdx) -> pt0::Expression { + let full_loc = self.loc(loc); + pt0::Expression { + pexp_desc: pt0::ExpressionDesc::Construct( + OldLocated::new( + crate::parser::longident::Longident::Lident("()".to_string()), + full_loc.clone(), + ), + None, + ), + pexp_loc: full_loc, + pexp_attributes: vec![], } } -} -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); + fn mk_nil_expr(&self, loc: LocIdx) -> pt0::Expression { + let full_loc = self.loc(loc); pt0::Expression { pexp_desc: pt0::ExpressionDesc::Construct( - Located::new( - crate::parser::longident::Longident::Lident("::".to_string()), - loc.clone(), + OldLocated::new( + crate::parser::longident::Longident::Lident("[]".to_string()), + full_loc.clone(), ), - Some(Box::new(pt0::Expression { - pexp_desc: pt0::ExpressionDesc::Tuple(vec![child_expr, acc]), - pexp_loc: loc.clone(), - pexp_attributes: vec![], - })), + None, ), - pexp_loc: loc.clone(), + pexp_loc: full_loc, pexp_attributes: vec![], } - }) -} + } -// ========== Flag conversions ========== + fn map_jsx_props(&self, props: &[current::JsxProp], _loc: LocIdx) -> Vec<(pt0::ArgLabel, pt0::Expression)> { + props + .iter() + .map(|prop| match prop { + current::JsxProp::Punning { optional, name } => { + let name_loc = self.loc(name.loc); + let ident_expr = pt0::Expression { + pexp_desc: pt0::ExpressionDesc::Ident(OldLocated::new( + crate::parser::longident::Longident::Lident(name.txt.clone()), + name_loc.clone(), + )), + pexp_loc: name_loc, + 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, self.map_expression(value)) + } + current::JsxProp::Spreading { expr, .. } => { + (pt0::ArgLabel::Labelled("_spreadProps".to_string()), self.map_expression(expr)) + } + }) + .collect() + } -fn map_rec_flag(flag: current::RecFlag) -> pt0::RecFlag { - match flag { - current::RecFlag::Nonrecursive => pt0::RecFlag::Nonrecursive, - current::RecFlag::Recursive => pt0::RecFlag::Recursive, + fn jsx_tag_to_longident(&self, 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()) + } + } } -} -fn map_direction_flag(flag: current::DirectionFlag) -> pt0::DirectionFlag { - match flag { - current::DirectionFlag::Upto => pt0::DirectionFlag::Upto, - current::DirectionFlag::Downto => pt0::DirectionFlag::Downto, + fn map_jsx_children_to_list(&self, children: &[current::Expression], loc: LocIdx) -> pt0::Expression { + // Convert children to a list expression (cons cells ending with []) + let nil = self.mk_nil_expr(loc); + let full_loc = self.loc(loc); + children.iter().rev().fold(nil, |acc, child| { + let child_expr = self.map_expression(child); + pt0::Expression { + pexp_desc: pt0::ExpressionDesc::Construct( + OldLocated::new( + crate::parser::longident::Longident::Lident("::".to_string()), + full_loc.clone(), + ), + Some(Box::new(pt0::Expression { + pexp_desc: pt0::ExpressionDesc::Tuple(vec![child_expr, acc]), + pexp_loc: full_loc.clone(), + pexp_attributes: vec![], + })), + ), + pexp_loc: full_loc.clone(), + pexp_attributes: vec![], + } + }) } -} -fn map_closed_flag(flag: current::ClosedFlag) -> pt0::ClosedFlag { - match flag { - current::ClosedFlag::Closed => pt0::ClosedFlag::Closed, - current::ClosedFlag::Open => pt0::ClosedFlag::Open, + // ========== Flag conversions ========== + + fn map_rec_flag(&self, flag: current::RecFlag) -> pt0::RecFlag { + match flag { + current::RecFlag::Nonrecursive => pt0::RecFlag::Nonrecursive, + current::RecFlag::Recursive => pt0::RecFlag::Recursive, + } } -} -fn map_override_flag(flag: current::OverrideFlag) -> pt0::OverrideFlag { - match flag { - current::OverrideFlag::Fresh => pt0::OverrideFlag::Fresh, - current::OverrideFlag::Override => pt0::OverrideFlag::Override, + fn map_direction_flag(&self, flag: current::DirectionFlag) -> pt0::DirectionFlag { + match flag { + current::DirectionFlag::Upto => pt0::DirectionFlag::Upto, + current::DirectionFlag::Downto => pt0::DirectionFlag::Downto, + } } -} -fn map_mutable_flag(flag: current::MutableFlag) -> pt0::MutableFlag { - match flag { - current::MutableFlag::Immutable => pt0::MutableFlag::Immutable, - current::MutableFlag::Mutable => pt0::MutableFlag::Mutable, + fn map_closed_flag(&self, flag: current::ClosedFlag) -> pt0::ClosedFlag { + match flag { + current::ClosedFlag::Closed => pt0::ClosedFlag::Closed, + current::ClosedFlag::Open => pt0::ClosedFlag::Open, + } } -} -fn map_private_flag(flag: current::PrivateFlag) -> pt0::PrivateFlag { - match flag { - current::PrivateFlag::Private => pt0::PrivateFlag::Private, - current::PrivateFlag::Public => pt0::PrivateFlag::Public, + fn map_override_flag(&self, flag: current::OverrideFlag) -> pt0::OverrideFlag { + match flag { + current::OverrideFlag::Fresh => pt0::OverrideFlag::Fresh, + current::OverrideFlag::Override => pt0::OverrideFlag::Override, + } } -} -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 map_mutable_flag(&self, flag: current::MutableFlag) -> pt0::MutableFlag { + match flag { + current::MutableFlag::Immutable => pt0::MutableFlag::Immutable, + current::MutableFlag::Mutable => pt0::MutableFlag::Mutable, + } } -} -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 map_private_flag(&self, flag: current::PrivateFlag) -> pt0::PrivateFlag { + match flag { + current::PrivateFlag::Private => pt0::PrivateFlag::Private, + current::PrivateFlag::Public => pt0::PrivateFlag::Public, + } } -} -// ========== 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(), - }; - pt0::Constant::String(s.clone(), mapped_delim) + fn map_variance(&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, } - current::Constant::Float(s, opt) => pt0::Constant::Float(s.clone(), *opt), } -} -// ========== Attributes ========== + fn map_arg_label(&self, 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 map_attribute(attr: ¤t::Attribute) -> pt0::Attribute { - let (name, payload) = attr; - ( - Located::new(name.txt.clone(), name.loc.clone()), - map_payload(payload), - ) -} + // ========== Constant ========== + + fn map_constant(&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), + } + } -fn map_attributes(attrs: ¤t::Attributes) -> pt0::Attributes { - attrs.iter().map(map_attribute).collect() -} + // ========== Attributes ========== -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 map_attribute(&self, attr: ¤t::Attribute) -> pt0::Attribute { + let (name, payload) = attr; + ( + self.map_loc(name), + self.map_payload(payload), + ) + } + + fn map_attributes(&self, attrs: ¤t::Attributes) -> pt0::Attributes { + attrs.iter().map(|a| self.map_attribute(a)).collect() + } + + fn map_payload(&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))), + ) + } } } -} -// ========== 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(), + // ========== Core Types ========== + + pub fn map_core_type(&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 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, ), - vec![arrow_type, arity_type], - ), - ptyp_loc: loc, - ptyp_attributes: vec![], + ptyp_loc: loc.clone(), + ptyp_attributes: vec![], + }; + pt0::CoreType { + ptyp_desc: pt0::CoreTypeDesc::Constr( + OldLocated::new( + crate::parser::longident::Longident::Lident("function$".to_string()), + loc.clone(), + ), + vec![arrow_type, arity_type], + ), + 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), + } 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), + } } } -} -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), - ) - } - current::CoreTypeDesc::Ptyp_alias(ty, s) => { - pt0::CoreTypeDesc::Alias(Box::new(map_core_type(ty)), s.clone()) - } - current::CoreTypeDesc::Ptyp_variant(fields, flag, labels) => { - pt0::CoreTypeDesc::Variant( - fields.iter().map(map_row_field).collect(), - map_closed_flag(*flag), - labels.clone(), - ) - } - 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)), - ) - } - current::CoreTypeDesc::Ptyp_package(pkg) => { - pt0::CoreTypeDesc::Package(map_package_type(pkg)) - } - current::CoreTypeDesc::Ptyp_extension(ext) => { - pt0::CoreTypeDesc::Extension(map_extension(ext)) + fn map_core_type_desc(&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_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)) + } } } -} -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_package_type(&self, pkg: ¤t::PackageType) -> pt0::PackageType { + let (lid, constraints) = pkg; + ( + self.map_loc(lid), + constraints + .iter() + .map(|(lid, ty)| (self.map_loc(lid), self.map_core_type(ty))) + .collect(), + ) + } -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_row_field(&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)), } - 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), - ) + fn map_object_field(&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)), } - 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), - ) -} + fn map_extension(&self, ext: ¤t::Extension) -> pt0::Extension { + let (name, payload) = ext; + ( + self.map_loc(name), + self.map_payload(payload), + ) + } -// ========== Patterns ========== + // ========== Patterns ========== -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), + pub fn map_pattern(&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_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)) - } - current::PatternDesc::Ppat_unpack(s) => { - pt0::PatternDesc::Unpack(mkloc(s.txt.clone(), &s.loc)) - } - current::PatternDesc::Ppat_exception(pat) => { - pt0::PatternDesc::Exception(Box::new(map_pattern(pat))) - } - 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_pattern_desc(&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_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_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_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_loc(lid), Box::new(self.map_pattern(pat))) + } } } -} -// ========== Expressions ========== + // ========== Expressions ========== -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)); - } - pt0::Expression { - pexp_desc: map_expression_desc(&expr.pexp_desc, &expr.pexp_loc), - pexp_loc: expr.pexp_loc.clone(), - pexp_attributes: attrs, - } -} - -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)) - } - current::ExpressionDesc::Pexp_constant(c) => { - pt0::ExpressionDesc::Constant(map_constant(c)) + pub fn map_expression(&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(&self, desc: ¤t::ExpressionDesc, loc: LocIdx) -> pt0::ExpressionDesc { + match desc { + current::ExpressionDesc::Pexp_ident(lid) => { + pt0::ExpressionDesc::Ident(self.map_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) => - { - 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 Some(new_name) = new_op { - let new_lid = Located { - txt: crate::parser::longident::Longident::Lident(new_name.to_string()), - loc: lid.loc.clone(), + 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 + 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) => + { + if let crate::parser::longident::Longident::Lident(op) = &lid.txt { + let new_op = match op.as_str() { + "->" => Some("|."), + "++" => Some("^"), + "!=" => Some("<>"), + "!==" => Some("!="), + "===" => Some("=="), + "==" => Some("="), + _ => None, }; - 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(new_name) = new_op { + let new_lid = Located { + txt: crate::parser::longident::Longident::Lident(new_name.to_string()), + loc: lid.loc, + }; + current::Expression { + pexp_desc: current::ExpressionDesc::Pexp_ident(new_lid), + pexp_loc: funct.pexp_loc, + pexp_attributes: funct.pexp_attributes.clone(), + } + } else { + funct.as_ref().clone() } } else { funct.as_ref().clone() } - } else { - funct.as_ref().clone() } + _ => funct.as_ref().clone(), + }; + pt0::ExpressionDesc::Apply { + funct: Box::new(self.map_expression(&mapped_funct)), + args: args + .iter() + .map(|(label, e)| (self.map_arg_label(label), self.map_expression(e))) + .collect(), + partial: *partial, + transformed_jsx: *transformed_jsx, } - _ => 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(), - )), - pexp_loc: unary.tag_name.loc.clone(), - pexp_attributes: vec![], - }), - args, - partial: false, - transformed_jsx: false, + 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_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_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_loc(lid), + ) + } + current::ExpressionDesc::Pexp_setfield(e1, lid, e2) => { + pt0::ExpressionDesc::Setfield( + Box::new(self.map_expression(e1)), + self.map_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_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::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, + 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 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(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 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(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(&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(&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(&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(&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(&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(&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(&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(&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(&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_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(&self, te: ¤t::TypeExtension) -> pt0::TypeExtension { + pt0::TypeExtension { + ptyext_path: self.map_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(&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(&self, desc: ¤t::ModuleTypeDesc) -> pt0::ModuleTypeDesc { + match desc { + current::ModuleTypeDesc::Pmty_ident(lid) => { + pt0::ModuleTypeDesc::Ident(self.map_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_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(&self, wc: ¤t::WithConstraint) -> pt0::WithConstraint { + match wc { + current::WithConstraint::Pwith_type(lid, td) => { + pt0::WithConstraint::Type(self.map_loc(lid), self.map_type_declaration(td)) + } + current::WithConstraint::Pwith_module(lid1, lid2) => { + pt0::WithConstraint::Module( + self.map_loc(lid1), + self.map_loc(lid2), + ) + } + current::WithConstraint::Pwith_typesubst(lid, td) => { + pt0::WithConstraint::TypeSubst(self.map_loc(lid), self.map_type_declaration(td)) + } + current::WithConstraint::Pwith_modsubst(lid1, lid2) => { + pt0::WithConstraint::ModSubst( + self.map_loc(lid1), + self.map_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(&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(&self, desc: ¤t::ModuleExprDesc) -> pt0::ModuleExprDesc { + match desc { + current::ModuleExprDesc::Pmod_ident(lid) => { + pt0::ModuleExprDesc::Ident(self.map_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(&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(&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(&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(&self, od: ¤t::OpenDescription) -> pt0::OpenDescription { + pt0::OpenDescription { + popen_lid: self.map_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(&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(&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(&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(&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(&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(&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(&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 +1321,39 @@ 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 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()))); + let label = mapper.map_arg_label(¤t::ArgLabel::Labelled(Located::mknoloc("x".to_string()))); assert!(matches!(label, pt0::ArgLabel::Labelled(s) if s == "x")); - let opt = map_arg_label(¤t::ArgLabel::Optional(Located::mknoloc("y".to_string()))); + let opt = mapper.map_arg_label(¤t::ArgLabel::Optional(Located::mknoloc("y".to_string()))); assert!(matches!(opt, pt0::ArgLabel::Optional(s) if s == "y")); } #[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/writer.rs b/compiler-rust/src/binary_ast/writer.rs index 0061baae6dc..5967d552300 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,13 +57,14 @@ const MAGIC_SEP_CHAR: u8 = b'\n'; pub fn write_structure_ast( output_path: &Path, source_path: &str, + arena: &ParseArena, ast: &Structure, ) -> io::Result<()> { // 1. Extract dependencies let deps = extract_structure_deps(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) @@ -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,13 +85,14 @@ pub fn write_structure_ast( pub fn write_signature_ast( output_path: &Path, source_path: &str, + arena: &ParseArena, ast: &Signature, ) -> io::Result<()> { // 1. Extract dependencies let deps = extract_signature_deps(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) @@ -169,16 +170,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 { +pub fn write_structure_ast_to_vec(source_path: &str, arena: &ParseArena, ast: &Structure) -> Vec { let deps = extract_structure_deps(ast); - let ast0 = map_structure(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 { +pub fn write_signature_ast_to_vec(source_path: &str, arena: &ParseArena, ast: &Signature) -> Vec { let deps = extract_signature_deps(ast); - let ast0 = map_signature(ast); + let ast0 = map_signature(arena, ast); write_ast_to_vec(source_path, &deps, &ast0) } diff --git a/compiler-rust/src/parse_arena.rs b/compiler-rust/src/parse_arena.rs index 2e2feee3657..83895ca3aef 100644 --- a/compiler-rust/src/parse_arena.rs +++ b/compiler-rust/src/parse_arena.rs @@ -301,6 +301,14 @@ impl ParseArena { 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), + } + } } // ============================================================================ diff --git a/compiler-rust/src/parser/comment_table.rs b/compiler-rust/src/parser/comment_table.rs index c97ab205fda..d60518b40a4 100644 --- a/compiler-rust/src/parser/comment_table.rs +++ b/compiler-rust/src/parser/comment_table.rs @@ -736,16 +736,16 @@ fn walk_module_type_declaration( comments: Vec, arena: &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, &arena.to_location(mtd.pmtd_name.loc)); + CommentTable::attach(&mut t.leading, arena.to_location(mtd.pmtd_name.loc), leading); match &mtd.pmtd_type { None => { - CommentTable::attach(&mut t.trailing, mtd.pmtd_name.loc.clone(), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(mtd.pmtd_name.loc), trailing); } 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(&arena.to_location(mtd.pmtd_name.loc), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(mtd.pmtd_name.loc), after_name); let (before, inside, after) = partition_by_loc(rest, &mod_type.pmty_loc); CommentTable::attach(&mut t.leading, mod_type.pmty_loc.clone(), before); @@ -756,11 +756,11 @@ fn walk_module_type_declaration( } fn walk_module_binding(mb: &ModuleBinding, t: &mut CommentTable, comments: Vec, arena: &ParseArena) { - let (leading, trailing) = partition_leading_trailing(comments, &mb.pmb_name.loc); - CommentTable::attach(&mut t.leading, mb.pmb_name.loc.clone(), leading); + let (leading, trailing) = partition_leading_trailing(comments, &arena.to_location(mb.pmb_name.loc)); + CommentTable::attach(&mut t.leading, arena.to_location(mb.pmb_name.loc), leading); - 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(&arena.to_location(mb.pmb_name.loc), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(mb.pmb_name.loc), after_name); let (leading, inside, trailing) = partition_by_loc(rest, &mb.pmb_expr.pmod_loc); @@ -778,11 +778,11 @@ fn walk_module_binding(mb: &ModuleBinding, t: &mut CommentTable, comments: Vec, arena: &ParseArena) { - let (leading, trailing) = partition_leading_trailing(comments, &md.pmd_name.loc); - CommentTable::attach(&mut t.leading, md.pmd_name.loc.clone(), leading); + let (leading, trailing) = partition_leading_trailing(comments, &arena.to_location(md.pmd_name.loc)); + CommentTable::attach(&mut t.leading, arena.to_location(md.pmd_name.loc), leading); - 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(&arena.to_location(md.pmd_name.loc), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(md.pmd_name.loc), after_name); 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); @@ -808,19 +808,19 @@ fn walk_type_declarations(tds: &[TypeDeclaration], t: &mut CommentTable, comment } fn walk_value_binding(vb: &ValueBinding, t: &mut CommentTable, comments: Vec, arena: &ParseArena) { - let pattern_loc = &vb.pvb_pat.ppat_loc; - let expr_loc = &vb.pvb_expr.pexp_loc; + let pattern_loc = arena.to_location(vb.pvb_pat.ppat_loc); + let expr_loc = arena.to_location(vb.pvb_expr.pexp_loc); - let (leading, inside, trailing) = partition_by_loc(comments, pattern_loc); + let (leading, inside, trailing) = partition_by_loc(comments, &pattern_loc); // 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, 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); + CommentTable::attach(&mut t.trailing, pattern_loc, after_pat); - 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); if is_block_expr(&vb.pvb_expr) { let combined: Vec = before_expr @@ -828,20 +828,20 @@ fn walk_value_binding(vb: &ValueBinding, t: &mut CommentTable, comments: Vec, arena: &ParseArena) { - let (before_name, rest) = partition_leading_trailing(comments, &td.ptype_name.loc); - CommentTable::attach(&mut t.leading, td.ptype_name.loc.clone(), before_name); + let (before_name, rest) = partition_leading_trailing(comments, &arena.to_location(td.ptype_name.loc)); + CommentTable::attach(&mut t.leading, arena.to_location(td.ptype_name.loc), before_name); - 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(&arena.to_location(td.ptype_name.loc), rest); + CommentTable::attach(&mut t.trailing, arena.to_location(td.ptype_name.loc), after_name); // Type params let rest = if td.ptype_params.is_empty() { @@ -890,11 +890,11 @@ fn walk_type_declaration(td: &TypeDeclaration, t: &mut CommentTable, comments: V } fn walk_label_declaration(ld: &LabelDeclaration, t: &mut CommentTable, comments: Vec, arena: &ParseArena) { - let (before_name, rest) = partition_leading_trailing(comments, &ld.pld_name.loc); - CommentTable::attach(&mut t.leading, ld.pld_name.loc.clone(), before_name); + let (before_name, rest) = partition_leading_trailing(comments, &arena.to_location(ld.pld_name.loc)); + CommentTable::attach(&mut t.leading, arena.to_location(ld.pld_name.loc), before_name); - 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(&arena.to_location(ld.pld_name.loc), rest); + CommentTable::attach(&mut t.trailing, arena.to_location(ld.pld_name.loc), after_name); 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); @@ -925,11 +925,11 @@ fn walk_constructor_declaration( comments: Vec, arena: &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, &arena.to_location(cd.pcd_name.loc)); + CommentTable::attach(&mut t.leading, arena.to_location(cd.pcd_name.loc), before_name); - 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(&arena.to_location(cd.pcd_name.loc), rest); + CommentTable::attach(&mut t.trailing, arena.to_location(cd.pcd_name.loc), after_name); let rest = walk_constructor_arguments(&cd.pcd_args, t, rest, arena); @@ -986,11 +986,11 @@ fn walk_extension_constructor( comments: Vec, arena: &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, &arena.to_location(ec.pext_name.loc)); + CommentTable::attach(&mut t.leading, arena.to_location(ec.pext_name.loc), leading); - 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(&arena.to_location(ec.pext_name.loc), trailing); + CommentTable::attach(&mut t.trailing, arena.to_location(ec.pext_name.loc), after_name); match &ec.pext_kind { ExtensionConstructorKind::Pext_decl(args, res) => { @@ -1069,7 +1069,7 @@ fn walk_expression(expr: &Expression, t: &mut CommentTable, comments: Vec, let (after_pat, rest) = partition_adjacent_trailing(&arena.to_location(pat.ppat_loc), after); CommentTable::attach(&mut t.trailing, arena.to_location(pat.ppat_loc), after_pat); - let (leading, trailing) = partition_leading_trailing(rest, &name.loc); + let (leading, trailing) = partition_leading_trailing(rest, &arena.to_location(name.loc)); CommentTable::attach(&mut t.leading, arena.to_location(name.loc), leading); CommentTable::attach(&mut t.trailing, arena.to_location(name.loc), trailing); } @@ -1878,12 +1878,12 @@ fn walk_core_type(ct: &CoreType, t: &mut CommentTable, comments: Vec, a } } 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); + let (before, inside, after) = partition_by_loc(comments, &arena.to_location(arg.typ.ptyp_loc)); + CommentTable::attach(&mut t.leading, arena.to_location(arg.typ.ptyp_loc), before); walk_core_type(&arg.typ, t, inside, arena); - let (after_arg, rest) = partition_adjacent_trailing(&arg.typ.ptyp_loc, after); - CommentTable::attach(&mut t.trailing, arg.typ.ptyp_loc.clone(), after_arg); + let (after_arg, rest) = partition_adjacent_trailing(&arena.to_location(arg.typ.ptyp_loc), after); + CommentTable::attach(&mut t.trailing, arena.to_location(arg.typ.ptyp_loc), after_arg); let (before, inside, after) = partition_by_loc(rest, &arena.to_location(ret.ptyp_loc)); CommentTable::attach(&mut t.leading, arena.to_location(ret.ptyp_loc), before); @@ -1964,7 +1964,7 @@ fn walk_row_field(field: &RowField, t: &mut CommentTable, comments: Vec if args.is_empty() { CommentTable::attach(&mut t.trailing, arena.to_location(tag.loc), trailing); } else { - let (after_tag, rest) = partition_adjacent_trailing(&tag.loc, trailing); + let (after_tag, rest) = partition_adjacent_trailing(&arena.to_location(tag.loc), trailing); CommentTable::attach(&mut t.trailing, arena.to_location(tag.loc), after_tag); visit_list_but_continue_with_remaining_comments( @@ -2134,7 +2134,7 @@ fn walk_mod_type(mt: &ModuleType, t: &mut CommentTable, comments: Vec, match constraint { WithConstraint::Pwith_type(lid, td) | WithConstraint::Pwith_typesubst(lid, td) => { - let (leading, trailing) = partition_leading_trailing(rest.clone(), &lid.loc); + let (leading, trailing) = partition_leading_trailing(rest.clone(), &arena.to_location(lid.loc)); CommentTable::attach(&mut t.leading, arena.to_location(lid.loc), leading); walk_type_declaration(td, t, trailing, arena); } @@ -2165,7 +2165,7 @@ fn walk_mod_type(mt: &ModuleType, t: &mut CommentTable, comments: Vec, } } -fn walk_attribute(_attr: &Attribute, _t: &mut CommentTable, _comments: Vec) { +fn walk_attribute(_attr: &Attribute, _t: &mut CommentTable, _comments: Vec, _arena: &ParseArena) { // Attributes don't have much structure to walk } diff --git a/compiler-rust/src/parser/core.rs b/compiler-rust/src/parser/core.rs index 5798e46513b..d8da8d21e3e 100644 --- a/compiler-rust/src/parser/core.rs +++ b/compiler-rust/src/parser/core.rs @@ -492,7 +492,7 @@ pub mod ast_helper { /// Create a list pattern `[a, b, ...rest]`. pub fn make_list_pattern( - p: &Parser<'_>, + p: &mut Parser<'_>, loc: Location, items: Vec, spread: Option, @@ -556,7 +556,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, @@ -614,7 +614,7 @@ pub fn make_unary_expr( /// Create an infix operator expression. pub fn make_infix_operator( - p: &Parser<'_>, + p: &mut Parser<'_>, token: Token, start_pos: Position, end_pos: Position, diff --git a/compiler-rust/src/parser/expr.rs b/compiler-rust/src/parser/expr.rs index 77b9fc2a000..0f1848357f2 100644 --- a/compiler-rust/src/parser/expr.rs +++ b/compiler-rust/src/parser/expr.rs @@ -1121,7 +1121,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)); } @@ -1133,7 +1133,7 @@ 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) } @@ -1157,9 +1157,10 @@ fn parse_attributes(p: &mut Parser<'_>) -> Attributes { } } Token::DocComment { loc, content } => { - let loc = p.from_location(loc); + 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, @@ -1843,7 +1844,7 @@ 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(); p.next(); // Check for field assignment: expr.field = value @@ -1875,7 +1876,7 @@ 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(); p.next(); // Check for field assignment: expr."field" = value @@ -2514,7 +2515,7 @@ fn make_empty_list(loc: Location) -> Expression { /// `[e1, e2]` → `e1 :: (e2 :: [])` /// `[e1, e2, ...rest]` → `e1 :: (e2 :: rest)` fn make_list_expression_simple( - p: &Parser<'_>, + p: &mut Parser<'_>, loc: Location, exprs: Vec, spread: Option, @@ -2523,19 +2524,20 @@ 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| p.loc_end(s.pexp_loc)) - .unwrap_or_else(|| p.loc_end(loc)); - 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 = p.mk_loc(&p.loc_start(item.pexp_loc), &list_end); + .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(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, pexp_attributes: vec![], }; - Expression { + acc = Expression { pexp_desc: ExpressionDesc::Pexp_construct( Loc { txt: Longident::Lident("::".to_string()), @@ -2545,25 +2547,26 @@ fn make_list_expression_simple( ), 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); // Build the list using cons cells let list_end = seg_end; - let tail = spread.unwrap_or_else(|| { + let mut acc = spread.unwrap_or_else(|| { // Empty list with ghost location (same as OCaml's make_list_expression) let ghost_loc = LocIdx::none(); Expression { @@ -2579,14 +2582,15 @@ fn make_list_expression_with_loc( } }); - let expr = exprs.into_iter().rev().fold(tail, |acc, item| { - let cons_loc = p.mk_loc(&p.loc_start(item.pexp_loc), &list_end); + 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, pexp_attributes: vec![], }; - Expression { + acc = Expression { pexp_desc: ExpressionDesc::Pexp_construct( Loc { txt: Longident::Lident("::".to_string()), @@ -2596,13 +2600,13 @@ fn make_list_expression_with_loc( ), 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 } } @@ -2996,7 +3000,7 @@ fn parse_block_body(p: &mut Parser<'_>) -> Option { 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); + let loc = p.mk_loc_current(); ast_helper::make_unit(loc) }); @@ -3073,7 +3077,7 @@ fn parse_block_body(p: &mut Parser<'_>) -> Option { 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); + let loc = p.mk_loc_current(); ast_helper::make_unit(loc) }); @@ -3104,7 +3108,7 @@ fn parse_block_body(p: &mut Parser<'_>) -> Option { 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); + let loc = p.mk_loc_current(); ast_helper::make_unit(loc) }); @@ -3348,7 +3352,7 @@ fn parse_let_in_block_with_continuation_and_attrs( 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); + let loc = p.mk_loc_current(); ast_helper::make_unit(loc) }); @@ -3370,7 +3374,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) } @@ -3636,7 +3640,7 @@ 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); + let loc = p.mk_loc_current(); ast_helper::make_unit(loc) }); @@ -3687,7 +3691,7 @@ 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); + let loc = p.mk_loc_current(); ast_helper::make_unit(loc) }); @@ -3718,7 +3722,7 @@ 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); + let loc = p.mk_loc_current(); ast_helper::make_unit(loc) }); @@ -3855,7 +3859,7 @@ 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); + let loc = p.mk_loc_current(); ast_helper::make_unit(loc) }); @@ -3951,7 +3955,7 @@ 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); + let loc = p.mk_loc_current(); ast_helper::make_unit(loc) }) } @@ -4355,7 +4359,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 { @@ -4389,7 +4393,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, @@ -4400,7 +4404,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 { @@ -4465,7 +4469,7 @@ 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(); p.next(); let loc_start_pos = p.loc_start(expr.pexp_loc); let loc = p.mk_loc_to_prev_end(&loc_start_pos); @@ -4590,8 +4594,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, @@ -4610,8 +4615,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, @@ -4623,7 +4629,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, @@ -4785,8 +4791,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()); @@ -4800,8 +4807,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()); @@ -4811,7 +4819,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, diff --git a/compiler-rust/src/parser/jsx_ppx.rs b/compiler-rust/src/parser/jsx_ppx.rs index 87cd9ea1850..fe8d0a96622 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::{Located, LocIdx, ParseArena}; use super::ast::*; use super::longident::Longident; @@ -51,8 +52,8 @@ 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 = &arena.loc_start(*loc).file_name; if file_name.is_empty() { return String::new(); } @@ -104,11 +105,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 +120,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 +142,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,7 +154,7 @@ 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" { @@ -169,19 +170,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 +191,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 +216,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 +226,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 +238,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 +246,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)); } } @@ -302,6 +304,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 { @@ -353,7 +356,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() { @@ -688,6 +691,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 { @@ -832,7 +836,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,7 +844,7 @@ 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 transformed_expr = transform_expression(binding.pvb_expr, config, arena); let constrained_expr = wrap_function_body_with_constraint(transformed_expr, config); // OCaml line 905-909: clear pexp_attributes (they were moved to wrapper_expr) let constrained_expr = Expression { @@ -1215,6 +1219,7 @@ fn build_props_pattern_and_body( expr: &Expression, args: &[ExtractedArg], config: &JsxConfig, + arena: &mut ParseArena, ) -> (Vec, Expression) { let mut patterns = vec![]; @@ -1251,7 +1256,7 @@ 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); @@ -1382,7 +1387,7 @@ 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" { @@ -1399,12 +1404,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 +1418,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 { @@ -1538,6 +1544,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 { @@ -2530,54 +2537,54 @@ 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) => { // 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); } ModuleTypeDesc::Pmty_signature(result) @@ -2585,12 +2592,12 @@ fn transform_module_type(mty: ModuleType, config: &mut JsxConfig) -> ModuleType 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 +2606,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 +2623,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 +2632,49 @@ 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 { 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); } 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 +2683,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 +2696,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 +2851,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 +2869,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,19 +2888,20 @@ 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); @@ -2968,6 +2977,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 +2985,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 { @@ -3026,12 +3036,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() }; @@ -3049,7 +3057,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 +3085,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 +3103,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 +3129,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 { @@ -3163,7 +3167,7 @@ fn mk_record_from_props( txt: Longident::Lident(name.txt.clone()), loc: name.loc.clone(), }, - expr: transform_expression(value.clone(), config), + expr: transform_expression(value.clone(), config, arena), opt: *optional, }) } @@ -3201,6 +3205,7 @@ fn transform_jsx_fragment( config: &JsxConfig, loc: &Location, attrs: &Attributes, + arena: &mut ParseArena, ) -> ExpressionDesc { let children = fragment.children; @@ -3223,6 +3228,7 @@ fn transform_jsx_fragment( fragment_expr, vec![], // No props for fragments children, + arena, ) } @@ -3231,6 +3237,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,6 +3256,7 @@ fn transform_jsx_unary( component_name_expr, unary.props, vec![], + arena, ) } JsxTagName::Upper(path) => { @@ -3269,6 +3277,7 @@ fn transform_jsx_unary( make_id, unary.props, vec![], + arena, ) } JsxTagName::QualifiedLower { path, name } => { @@ -3289,6 +3298,7 @@ fn transform_jsx_unary( make_id, unary.props, vec![], + arena, ) } JsxTagName::Invalid(name) => { @@ -3303,6 +3313,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,6 +3332,7 @@ fn transform_jsx_container( component_name_expr, container.props, container.children, + arena, ) } JsxTagName::Upper(path) => { @@ -3341,6 +3353,7 @@ fn transform_jsx_container( make_id, container.props, container.children, + arena, ) } JsxTagName::QualifiedLower { path, name } => { @@ -3361,6 +3374,7 @@ fn transform_jsx_container( make_id, container.props, container.children, + arena, ) } JsxTagName::Invalid(name) => { 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 b57f013d5dd..3ba196252ca 100644 --- a/compiler-rust/src/parser/module.rs +++ b/compiler-rust/src/parser/module.rs @@ -138,7 +138,7 @@ 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); + let loc = p.mk_loc_to_prev_end(&open_start); Some(StructureItemDesc::Pstr_open(OpenDescription { popen_lid: lid, popen_override: override_flag, @@ -252,7 +252,7 @@ pub fn parse_structure_item(p: &mut Parser<'_>) -> Option { let mod_expr = parse_module_expr(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(), })) } @@ -271,13 +271,17 @@ pub fn parse_structure_item(p: &mut Parser<'_>) -> Option { Some(StructureItemDesc::Pstr_attribute(attr)) } } - Token::ModuleComment { loc, content } => { + Token::ModuleComment { .. } => { // Module-level doc comment (triple star /*** ... */) becomes a standalone res.doc attribute - let loc = p.from_location(loc); - let content = content.clone(); - p.next(); - let attr = super::core::doc_comment_to_attribute(loc, content); - Some(StructureItemDesc::Pstr_attribute(attr)) + // Extract data by taking ownership of the token + if let Token::ModuleComment { loc, content } = std::mem::replace(&mut p.token, Token::Eof) { + let loc = p.from_location(&loc); + p.next(); + let attr = super::core::doc_comment_to_attribute(loc, content); + Some(StructureItemDesc::Pstr_attribute(attr)) + } else { + unreachable!() + } } Token::PercentPercent => { // Structure-level extension (%%raw(...), %%private(...), etc.) @@ -315,7 +319,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(); @@ -355,7 +359,7 @@ pub fn parse_structure_item(p: &mut Parser<'_>) -> Option { desc.map(|d| StructureItem { pstr_desc: d, - pstr_loc: p.mk_loc(&start_pos, &p.prev_end_pos), + pstr_loc: p.mk_loc_to_prev_end(&start_pos), }) } @@ -405,7 +409,7 @@ 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); + let loc = p.mk_loc_to_prev_end(&open_start); Some(SignatureItemDesc::Psig_open(OpenDescription { popen_lid: lid, popen_override: override_flag, @@ -510,7 +514,7 @@ pub fn parse_signature_item(p: &mut Parser<'_>) -> Option { let mod_type = parse_module_type(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(), })) } @@ -527,13 +531,16 @@ pub fn parse_signature_item(p: &mut Parser<'_>) -> Option { Some(SignatureItemDesc::Psig_attribute(attr)) } } - Token::ModuleComment { loc, content } => { + Token::ModuleComment { .. } => { // Module-level doc comment (triple star /*** ... */) becomes a standalone res.doc attribute - let loc = p.from_location(loc); - let content = content.clone(); - p.next(); - let attr = super::core::doc_comment_to_attribute(loc, content); - Some(SignatureItemDesc::Psig_attribute(attr)) + if let Token::ModuleComment { loc, content } = std::mem::replace(&mut p.token, Token::Eof) { + let loc = p.from_location(&loc); + p.next(); + let attr = super::core::doc_comment_to_attribute(loc, content); + Some(SignatureItemDesc::Psig_attribute(attr)) + } else { + unreachable!() + } } Token::Percent | Token::PercentPercent => { let ext = parse_extension(p); @@ -619,14 +626,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, @@ -700,7 +707,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 @@ -728,7 +735,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![], } } @@ -737,7 +744,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, @@ -754,7 +761,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, @@ -765,7 +772,7 @@ fn parse_primary_module_expr(p: &mut Parser<'_>) -> ModuleExpr { 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); + let loc = p.mk_loc_to_prev_end(&start_pos); ModuleExpr { pmod_loc: loc, ..inner @@ -776,7 +783,7 @@ fn parse_primary_module_expr(p: &mut Parser<'_>) -> ModuleExpr { 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, @@ -819,7 +826,7 @@ fn parse_primary_module_expr(p: &mut Parser<'_>) -> ModuleExpr { }; // 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), @@ -832,7 +839,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, @@ -865,7 +872,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, @@ -960,7 +967,7 @@ fn parse_functor_arg(p: &mut Parser<'_>) -> Option { _ => break, } } - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + 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_loc: loc, @@ -994,7 +1001,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 { @@ -1008,7 +1015,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), @@ -1064,7 +1071,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, }] @@ -1192,7 +1199,7 @@ fn parse_module_type_impl(p: &mut Parser<'_>, es6_arrow: bool, parse_with: bool) 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 loc = p.mk_loc_to_prev_end(&start_pos); let mut result = ModuleType { pmty_desc: ModuleTypeDesc::Pmty_with(Box::new(typ), constraints), pmty_loc: loc, @@ -1224,7 +1231,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()), @@ -1280,7 +1287,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, @@ -1297,7 +1304,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(); @@ -1323,7 +1330,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) } @@ -1358,7 +1365,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, @@ -1393,7 +1400,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 @@ -1432,7 +1439,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![], } } @@ -1441,7 +1448,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, @@ -1454,7 +1461,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 } } @@ -1466,7 +1473,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, @@ -1482,7 +1489,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, @@ -1580,7 +1587,7 @@ fn parse_with_constraint(p: &mut Parser<'_>) -> Option { 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); + let loc = p.mk_loc_to_end(&cstr_start); p.next(); CoreType { ptyp_desc: CoreTypeDesc::Ptyp_var(name), @@ -1592,7 +1599,7 @@ fn parse_with_constraint(p: &mut Parser<'_>) -> Option { }; 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 { @@ -1710,7 +1717,7 @@ fn parse_module_long_ident(p: &mut Parser<'_>) -> Loc { } let lid = super::core::build_longident(&path_parts); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); with_loc(lid, loc) } @@ -1747,7 +1754,7 @@ fn parse_type_long_ident(p: &mut Parser<'_>) -> Loc { } let lid = super::core::build_longident(&path_parts); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); with_loc(lid, loc) } @@ -1839,7 +1846,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, @@ -1854,7 +1861,7 @@ fn parse_let_bindings( let mut expr = expr::parse_expr(p); // 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); + let binding_loc = p.mk_loc_to_prev_end(&binding_start); // For locally abstract types, OCaml uses the binding location for the pattern constraint and Ptyp_poly let pat = if is_locally_abstract { @@ -2086,7 +2093,7 @@ 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 path = with_loc(super::core::build_longident(&parts), p.mk_loc_to_prev_end(&start_pos)); // Optional type params: <'a, +'b, -'c> let params = if p.token == Token::LessThan { @@ -2151,7 +2158,7 @@ fn parse_type_declaration_with_context( 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) } @@ -2347,7 +2354,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)); @@ -2514,7 +2521,7 @@ 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), @@ -2523,7 +2530,7 @@ fn parse_type_declaration_with_context( // For unqualified (Lident), the CoreType uses full extent. let manifest = manifest.map(fix_type_manifest_location); - 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, @@ -2542,7 +2549,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); } @@ -2563,15 +2570,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, @@ -2586,7 +2589,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 @@ -2657,7 +2660,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), @@ -2679,7 +2682,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), @@ -2729,7 +2732,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), @@ -2775,7 +2778,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)); @@ -2800,7 +2803,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)); @@ -2808,7 +2811,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, @@ -2827,7 +2830,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 { @@ -2864,7 +2867,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), @@ -2876,7 +2879,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), @@ -3005,10 +3008,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) } @@ -3158,7 +3161,7 @@ fn parse_constructor_impl(p: &mut Parser<'_>, 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) } @@ -3340,7 +3343,7 @@ fn parse_label_declaration( 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())); 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("."); @@ -3372,7 +3375,7 @@ fn parse_label_declaration( }; // 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, @@ -3397,14 +3400,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) } @@ -3436,7 +3439,7 @@ fn parse_value_description( 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, @@ -3459,7 +3462,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![], }); @@ -3479,7 +3482,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, } } @@ -3517,7 +3520,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) } @@ -3542,7 +3545,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), @@ -3557,7 +3560,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), }) }; @@ -3634,7 +3637,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) } @@ -3669,7 +3672,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, @@ -3744,7 +3747,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) } @@ -3766,7 +3769,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() }; @@ -3790,11 +3793,13 @@ fn parse_attributes(p: &mut Parser<'_>) -> Attributes { p.next(); attrs.push(parse_attribute_body(p, attr_start)); } - Token::DocComment { loc, content } => { - let loc = loc.clone(); - let content = content.clone(); - p.next(); - attrs.push(super::core::doc_comment_to_attribute(loc, content)); + Token::DocComment { .. } => { + // Extract data by taking ownership of the token to avoid borrow conflict + if let Token::DocComment { loc, content } = std::mem::replace(&mut p.token, Token::Eof) { + let loc = p.from_location(&loc); + p.next(); + attrs.push(super::core::doc_comment_to_attribute(loc, content)); + } } _ => break, } @@ -3830,7 +3835,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; @@ -3937,7 +3942,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![]), @@ -3997,7 +4002,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..c00ce9d77b3 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,7 +14,7 @@ pub enum ParenKind { /// Parentheses are needed Parenthesized, /// Braces are needed at the given location - Braced(Location), + Braced(LocIdx), /// No wrapping needed Nothing, } @@ -238,7 +238,7 @@ 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 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); @@ -264,7 +264,7 @@ 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 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); diff --git a/compiler-rust/src/parser/parsetree_viewer.rs b/compiler-rust/src/parser/parsetree_viewer.rs index bcb5fc6168d..31a86cab325 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; use crate::parser::ast::*; use crate::parser::longident::Longident; @@ -120,7 +120,7 @@ pub enum IfConditionKind<'a> { /// 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>) { +) -> (Vec<(&LocIdx, IfConditionKind<'_>, &Expression)>, Option<&Expression>) { let mut acc = Vec::new(); let mut current = expr; @@ -187,7 +187,7 @@ 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) + not_ghost_operator(op, ident.loc.is_none()) } else { false } @@ -209,7 +209,7 @@ 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) { + if not_ghost_operator(op, ident.loc.is_none()) { return Some(op.clone()); } } @@ -704,8 +704,8 @@ 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 == "++") } // ============================================================================ diff --git a/compiler-rust/src/parser/pattern.rs b/compiler-rust/src/parser/pattern.rs index f4432402581..25b732014e9 100644 --- a/compiler-rust/src/parser/pattern.rs +++ b/compiler-rust/src/parser/pattern.rs @@ -27,9 +27,10 @@ fn parse_attributes(p: &mut Parser<'_>) -> Attributes { } } Token::DocComment { loc, content } => { - let loc = p.from_location(loc); + 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, @@ -91,7 +92,7 @@ fn parse_attribute_id(p: &mut Parser<'_>, start_pos: Position) -> Located) -> Pattern { Constant::Integer("0".to_string(), None) } }; - 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_interval(from, to), ppat_loc: loc, @@ -254,7 +255,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) } @@ -262,7 +263,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) } }; @@ -270,9 +271,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, @@ -372,7 +373,7 @@ pub fn parse_alias_pattern( 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) } @@ -380,10 +381,10 @@ 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); + let loc = p.mk_loc_to_prev_end(&start_pos); pat = Pattern { ppat_desc: PatternDesc::Ppat_alias(Box::new(pat), name), ppat_loc: loc, @@ -422,7 +423,7 @@ pub fn parse_tuple_pattern( } 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); Pattern { ppat_desc: PatternDesc::Ppat_tuple(patterns), @@ -442,7 +443,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, @@ -452,7 +453,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 { @@ -461,8 +462,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( @@ -482,7 +483,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, @@ -492,7 +493,7 @@ 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 loc = p.mk_loc_to_prev_end(&start_pos); let lid = Longident::Lident(if is_true { "true" } else { "false" }.to_string()); ast_helper::make_construct_pat(lid, None, loc.clone(), loc) } @@ -501,7 +502,7 @@ fn parse_atomic_pattern(p: &mut Parser<'_>) -> Pattern { if p.token == Token::Rparen { // Unit pattern: () p.next(); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); ast_helper::make_construct_pat(Longident::Lident("()".to_string()), None, loc.clone(), loc) } else { // Parenthesized pattern or tuple @@ -513,7 +514,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 } } @@ -546,7 +547,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) } @@ -554,7 +555,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()) } }; @@ -571,7 +572,7 @@ fn parse_atomic_pattern(p: &mut Parser<'_>) -> Pattern { }; 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. @@ -610,7 +611,7 @@ fn parse_atomic_pattern(p: &mut Parser<'_>) -> Pattern { } else { p.next(); - let lid_loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let lid_loc = p.mk_loc_to_prev_end(&start_pos); let lid = mknoloc(Longident::Lident("::".to_string())); let arg = if p.token == Token::Lparen { @@ -619,7 +620,7 @@ 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); Some(ast_helper::make_construct_pat( Longident::Lident("()".to_string()), None, @@ -645,7 +646,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, @@ -656,7 +657,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, @@ -670,7 +671,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, @@ -706,7 +707,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, @@ -721,7 +722,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, @@ -792,7 +793,7 @@ fn parse_constructor_pattern(p: &mut Parser<'_>) -> Pattern { } let lid = super::core::build_longident(&path_parts); - let loc = p.mk_loc(&start_pos, &p.prev_end_pos); + let loc = p.mk_loc_to_prev_end(&start_pos); // Check for constructor argument let arg = if p.token == Token::Lparen { @@ -803,7 +804,7 @@ 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); Some(ast_helper::make_construct_pat( Longident::Lident("()".to_string()), None, @@ -833,7 +834,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, @@ -844,7 +845,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, @@ -858,7 +859,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, @@ -874,7 +875,7 @@ 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() }; @@ -901,7 +902,7 @@ fn parse_array_pattern(p: &mut Parser<'_>) -> Pattern { } 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), @@ -935,7 +936,7 @@ fn parse_list_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); ast_helper::make_list_pattern(p, loc, patterns, spread) } @@ -1015,13 +1016,13 @@ fn parse_record_pattern(p: &mut Parser<'_>) -> Pattern { } 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) } 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) }; @@ -1034,7 +1035,7 @@ 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); Pattern { ppat_desc: PatternDesc::Ppat_record(fields, closed), @@ -1053,7 +1054,7 @@ 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(); p.next(); p.expect(Token::Colon); @@ -1083,7 +1084,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 @@ -1127,7 +1128,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 { @@ -1139,7 +1140,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)), @@ -1192,7 +1193,7 @@ fn parse_template_literal_pattern(p: &mut Parser<'_>, start_pos: crate::location } } - 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()))), @@ -1217,8 +1218,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, @@ -1258,7 +1259,7 @@ 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(); Some(Box::new(ast_helper::make_construct_pat( Longident::Lident("()".to_string()), @@ -1279,7 +1280,7 @@ 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); + 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, @@ -1294,7 +1295,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 =