1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
//! Module parsing for Nash.
//!
//! Ported from Elm's `Parse/Module.hs`.
//!
//! Parses full modules including:
//! - Module header: `module Main exposing (main)`
//! - Imports: `import List exposing (map)`
//! - Declarations: values, types, aliases
use nash_region::{Located, Region};
use nash_source::{Alias, Docs, Exposing, Import, Infix, Module, Union, Value};
use crate::Parser;
use crate::declaration::Decl;
use crate::error;
impl<'a> Parser<'a> {
/// Parse a module header.
///
/// Mirrors Elm's `chompHeader` (simplified - no port/effect modules):
/// ```text
/// module_header = 'module' module_name 'exposing' exposing_list
/// ```
///
/// Returns the module name and exports as a tuple.
pub fn module_header(
&mut self,
) -> Result<(&'a Located<&'a str>, &'a Located<Exposing<'a>>), error::Module<'a>> {
// Match 'module' keyword
self.keyword_module(error::Module::Problem)?;
self.chomp_and_check_indent(error::Module::Space, error::Module::Name)?;
// Parse module name (e.g., "Json.Decode")
let start = self.get_position();
let name = self.module_name(error::Module::Name)?;
let module_name = self.add_end(start, name);
// Consume whitespace
self.chomp(error::Module::Space)?;
// Must have 'exposing' keyword
self.keyword_exposing(|row, col| {
error::Module::Exposing(self.bump.alloc(error::Exposing::Start(row, col)), row, col)
})?;
self.chomp_and_check_indent(error::Module::Space, |row, col| {
error::Module::Exposing(
self.bump.alloc(error::Exposing::IndentValue(row, col)),
row,
col,
)
})?;
// Parse the exposing list, wrapping errors
let exposing_start = self.get_position();
let exposing = self.specialize(
|bump, err, row, col| error::Module::Exposing(bump.alloc(err), row, col),
|p| p.exposing(),
)?;
let exposing_located = self.add_end(exposing_start, exposing);
Ok((module_name, exposing_located))
}
/// Parse zero or more import statements.
///
/// Mirrors Elm's `chompImports`:
/// ```haskell
/// chompImports :: [Src.Import] -> Parser E.Module [Src.Import]
/// chompImports imports =
/// oneOfWithFallback
/// [ do i <- chompImport
/// chompImports (i:imports)
/// ]
/// (reverse imports)
/// ```
fn imports(&mut self) -> Result<&'a [&'a Import<'a>], error::Module<'a>> {
let mut imports = Vec::new();
loop {
// Save state in case import keyword doesn't match
let state = self.save_state();
match self.import() {
Ok(import) => {
imports.push(import);
// import() already ensures fresh line at the end
}
Err(_) => {
// If we didn't consume input, we're done with imports
if self.pos == state.pos {
self.restore_state(state);
break;
}
// Otherwise propagate the error
return Err(error::Module::ImportStart(self.row, self.col));
}
}
}
Ok(self.alloc_slice_copy(&imports))
}
/// Parse zero or more declarations.
///
/// Mirrors Elm's `chompDecls`:
/// ```haskell
/// chompDecls :: [Decl.Decl] -> Parser E.Decl [Decl.Decl]
/// chompDecls decls =
/// do (decl, _) <- Decl.declaration
/// oneOfWithFallback
/// [ do Space.checkFreshLine E.DeclStart
/// chompDecls (decl:decls)
/// ]
/// (reverse (decl:decls))
/// ```
fn declarations(&mut self) -> Result<Vec<Decl<'a>>, error::Module<'a>> {
let mut decls = Vec::new();
loop {
// Save state in case no declaration starts
let state = self.save_state();
// Try to parse a declaration
match self.specialize(
|bump, err, row, col| error::Module::Declarations(bump.alloc(err), row, col),
|p| p.declaration(),
) {
Ok((decl, _end)) => {
decls.push(decl);
// Chomp any trailing whitespace
self.chomp(error::Module::Space)?;
// Check for fresh line (another declaration might follow)
if self.is_eof() {
break;
}
// If not at fresh line, we're done
if self.col != 1 {
break;
}
}
Err(_) => {
// If we didn't consume input, we're done with declarations
if self.pos == state.pos {
self.restore_state(state);
break;
}
// Otherwise propagate the error
return Err(error::Module::Declarations(
self.bump.alloc(error::Decl::Start(self.row, self.col)),
self.row,
self.col,
));
}
}
}
Ok(decls)
}
/// Parse zero or more infix declarations.
///
/// Infixes are parsed at module level (before regular declarations).
fn infixes(&mut self) -> Result<Vec<&'a Located<Infix<'a>>>, error::Module<'a>> {
let mut infixes = Vec::new();
loop {
let state = self.save_state();
match self.infix_decl() {
Ok(infix) => {
infixes.push(infix);
// infix_decl already ensures fresh line
}
Err(_) => {
// If we didn't consume input, we're done
if self.pos == state.pos {
self.restore_state(state);
break;
}
return Err(error::Module::Infix(self.row, self.col));
}
}
}
Ok(infixes)
}
/// Parse a complete module.
///
/// Mirrors Elm's `chompModule`:
/// ```text
/// module = [ module_header ] { import } { infix } { declaration }
/// ```
pub fn module(&mut self) -> Result<Module<'a>, error::Module<'a>> {
// Consume initial whitespace
self.chomp(error::Module::Space)?;
let start_pos = self.get_position();
// Try to parse module header (optional)
let (name, exports) = {
let state = self.save_state();
match self.module_header() {
Ok((n, e)) => {
// Consume whitespace after header and check fresh line
self.chomp(error::Module::Space)?;
self.check_fresh_line(error::Module::FreshLine)?;
(Some(n), e)
}
Err(_) => {
// No header - restore and use defaults
if self.pos == state.pos {
self.restore_state(state);
}
// Default: name = None, exports = Open
let default_exports = self.alloc(Located::at(Region::one(), Exposing::Open));
(None, default_exports)
}
}
};
// Parse imports
let imports = self.imports()?;
// Parse infixes
let infix_vec = self.infixes()?;
let binops = self.alloc_slice_copy(&infix_vec);
// Parse declarations
let decls = self.declarations()?;
// Categorize declarations into values, unions, aliases
let (values, unions, aliases) = self.categorize_decls(decls);
// Build docs (simplified: no module-level docs for now)
let docs = self.alloc(Docs::NoDocs(Region::new(start_pos, self.get_position())));
Ok(Module {
name,
exports,
docs,
imports,
values,
unions,
aliases,
binops,
})
}
/// Categorize declarations into separate slices by type.
#[allow(clippy::type_complexity)]
fn categorize_decls(
&self,
decls: Vec<Decl<'a>>,
) -> (
&'a [&'a Located<Value<'a>>],
&'a [&'a Located<Union<'a>>],
&'a [&'a Located<Alias<'a>>],
) {
let mut values = Vec::new();
let mut unions = Vec::new();
let mut aliases = Vec::new();
for decl in decls {
match decl {
Decl::Value(_doc, value) => values.push(value),
Decl::Union(_doc, union) => unions.push(union),
Decl::Alias(_doc, alias) => aliases.push(alias),
}
}
(
self.alloc_slice_copy(&values),
self.alloc_slice_copy(&unions),
self.alloc_slice_copy(&aliases),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use bumpalo::Bump;
use indoc::indoc;
macro_rules! assert_module_header_snapshot {
($input:expr) => {{
let input = indoc!($input);
let bump = Bump::new();
let src = bump.alloc_str(input);
let mut parser = Parser::new(&bump, src.as_bytes());
let result = parser.module_header();
match result {
Ok((name, exposing)) => {
insta::with_settings!({
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_debug_snapshot!((name, exposing));
});
}
Err(e) => {
panic!("Expected successful parse, got error: {:?}", e);
}
}
}};
}
#[test]
fn module_header_simple_open() {
assert_module_header_snapshot!("module Foo exposing (..)");
}
#[test]
fn module_header_dotted() {
assert_module_header_snapshot!("module Foo.Bar exposing (baz)");
}
#[test]
fn module_header_mixed_exposing() {
assert_module_header_snapshot!("module Main exposing (main, Msg(..))");
}
#[test]
fn module_header_deeply_nested() {
assert_module_header_snapshot!("module Platform.Cmd.Extra exposing (batch, none)");
}
// =========================================================================
// Full module parsing tests
// =========================================================================
macro_rules! assert_module_snapshot {
($input:expr) => {{
let input = indoc!($input);
let bump = Bump::new();
let src = bump.alloc_str(input);
let mut parser = Parser::new(&bump, src.as_bytes());
let result = parser.module();
match result {
Ok(module) => {
insta::with_settings!({
description => format!("Code:\n\n{}", input),
omit_expression => true,
}, {
insta::assert_debug_snapshot!(module);
});
}
Err(e) => {
panic!("Expected successful parse, got error: {:?}", e);
}
}
}};
}
#[test]
fn module_header_only() {
assert_module_snapshot!("module Main exposing (..)\n");
}
#[test]
fn module_with_imports() {
assert_module_snapshot!(
r#"
module Main exposing (..)
import List
import Maybe exposing (Maybe(..))
"#
);
}
#[test]
fn module_with_value() {
assert_module_snapshot!(
r#"
module Main exposing (..)
main = 42
"#
);
}
#[test]
fn module_with_type() {
assert_module_snapshot!(
r#"
module Main exposing (..)
type Maybe a
= Just a
| Nothing
"#
);
}
#[test]
fn module_with_union_then_value() {
// A definition at column 1 must end the union's variant list, not
// be swallowed as extra constructor arguments.
assert_module_snapshot!(
r#"
module Main exposing (..)
type Wrap a
= Wrap a
f w = w
"#
);
}
#[test]
fn module_with_alias() {
assert_module_snapshot!(
r#"
module Main exposing (..)
type alias Point = { x : Int, y : Int }
"#
);
}
#[test]
fn module_full() {
assert_module_snapshot!(
r#"
module Main exposing (main, Model, Msg(..))
import Html exposing (div)
import Platform.Cmd as Cmd
type alias Model = { count : Int }
type Msg
= Increment
| Decrement
main = 0
"#
);
}
#[test]
fn module_no_header() {
// Without header, defaults to name=None, exports=Open
assert_module_snapshot!("x = 1\n");
}
#[test]
fn module_with_infix() {
assert_module_snapshot!(
r#"
module Main exposing (..)
infix left 6 (|>) = apR
apR f x = f x
"#
);
}
}