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
//! Accessor and field access parsing for Nash.
//!
//! Ported from Elm's `Parse/Expression.hs` (accessor, accessible).
use nash_region::{Located, Position, Region};
use nash_source::Expr;
use crate::Parser;
use crate::error;
impl<'a> Parser<'a> {
/// Parse field accessor `.fieldName`.
///
/// Mirrors Elm's `accessor`:
/// ```haskell
/// accessor start =
/// do word1 0x2E {-.-} E.Dot
/// field <- Var.lower E.Access
/// addEnd start (Src.Accessor field)
/// ```
pub(crate) fn accessor(
&mut self,
start: Position,
) -> Result<&'a Located<Expr<'a>>, error::Expr<'a>> {
self.word1(b'.', error::Expr::Dot)?;
let field = self.lower_name(error::Expr::Access)?;
Ok(self.add_end(start, Expr::Accessor(field)))
}
/// Handle field access chains like `foo.bar.baz`.
///
/// Mirrors Elm's `accessible`:
/// ```haskell
/// accessible start expr =
/// oneOfWithFallback
/// [ do word1 0x2E {-.-} E.Dot
/// pos <- getPosition
/// field <- Var.lower E.Access
/// end <- getPosition
/// accessible start $
/// A.at start end (Src.Access expr (A.at pos end field))
/// ]
/// expr
/// ```
pub(crate) fn accessible(
&mut self,
start: Position,
expr: &'a Located<Expr<'a>>,
) -> Result<&'a Located<Expr<'a>>, error::Expr<'a>> {
let mut expr = expr;
while self.peek() == Some(b'.') {
self.advance();
let pos = self.get_position();
let field = self.lower_name(error::Expr::Access)?;
let end = self.get_position();
let field = self.alloc(Located::at(Region::new(pos, end), field));
expr = self.alloc(Located::at(
Region::new(start, end),
Expr::Access {
record: expr,
field,
},
));
}
Ok(expr)
}
}
#[cfg(test)]
mod tests {
use crate::expression::assert_expr_snapshot;
#[test]
fn accessor_simple() {
assert_expr_snapshot!(".name");
}
#[test]
fn accessor_long() {
assert_expr_snapshot!(".firstName");
}
#[test]
fn field_access_simple() {
assert_expr_snapshot!("foo.bar");
}
#[test]
fn field_access_chain() {
assert_expr_snapshot!("foo.bar.baz");
}
#[test]
fn record_field_access() {
assert_expr_snapshot!("{ x = 1 }.x");
}
}