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
//! Value definition parsing for Nash.
//!
//! Ported from Elm's `Parse/Declaration.hs` (valueDecl, chompDefArgsAndBody).
use bumpalo::collections::Vec as BumpVec;
use nash_region::{Located, Position};
use nash_source::{Attribute, Comment, Value};
use super::Decl;
use crate::Parser;
use crate::error::{self, DeclDef};
impl<'a> Parser<'a> {
/// Parse a value definition.
///
/// Mirrors Elm's `valueDecl`:
/// ```haskell
/// valueDecl maybeDocs start =
/// do name <- Var.lower E.DeclStart
/// end <- getPosition
/// specialize (E.DeclDef name) $
/// do Space.chompAndCheckIndent E.DeclDefSpace E.DeclDefIndentEquals
/// oneOf E.DeclDefEquals
/// [ -- type annotation: name : Type \n name args = body
/// , -- no annotation: name args = body
/// ]
/// ```
pub(super) fn value_decl(
&mut self,
maybe_docs: Option<&'a Comment<'a>>,
attributes: &'a [&'a Attribute<'a>],
start: Position,
) -> Result<(Decl<'a>, Position), error::Decl<'a>> {
let name = self.lower_name(error::Decl::Start)?;
let end = self.get_position();
self.specialize(
|bump, e, row, col| error::Decl::Def(name, bump.alloc(e), row, col),
|p| {
p.chomp_and_check_indent(DeclDef::Space, DeclDef::IndentEquals)?;
p.one_of(
DeclDef::Equals,
vec![
// Type annotation: name : Type \n name args = body
Box::new(|p: &mut Parser<'a>| {
p.word1(b':', DeclDef::Equals)?;
p.chomp_and_check_indent(DeclDef::Space, DeclDef::IndentType)?;
let (type_ann, _) = p.specialize(
|bump, e, row, col| DeclDef::Type(bump.alloc(e), row, col),
|p| p.type_scheme(),
)?;
// Must be on a fresh line for the definition
p.check_fresh_line(DeclDef::NameRepeat)?;
let def_name = p.chomp_matching_name_decl(name)?;
p.chomp_and_check_indent(DeclDef::Space, DeclDef::IndentEquals)?;
p.chomp_value_args_and_body(
maybe_docs,
attributes,
start,
def_name,
Some(type_ann),
)
}),
// No type annotation: name args = body
Box::new(|p: &mut Parser<'a>| {
let name_located =
p.alloc(Located::at(nash_region::Region::new(start, end), name));
p.chomp_value_args_and_body(
maybe_docs,
attributes,
start,
name_located,
None,
)
}),
],
)
},
)
}
/// Parse function arguments and body for a value definition.
///
/// Mirrors Elm's `chompDefArgsAndBody`.
fn chomp_value_args_and_body(
&mut self,
maybe_docs: Option<&'a Comment<'a>>,
attributes: &'a [&'a Attribute<'a>],
start: Position,
name: &'a Located<&'a str>,
type_ann: Option<&'a nash_source::Annotation<'a>>,
) -> Result<(Decl<'a>, Position), DeclDef<'a>> {
let mut args: BumpVec<'a, &'a Located<nash_source::Pattern<'a>>> =
BumpVec::new_in(self.bump);
loop {
let args_for_body = args.clone();
let result = self.one_of(
DeclDef::Equals,
vec![
// Parse an argument pattern
Box::new(|p: &mut Parser<'a>| {
let arg = p.specialize(
|bump, e, row, col| DeclDef::Arg(bump.alloc(e), row, col),
|p| p.pattern_term(),
)?;
p.chomp_and_check_indent(DeclDef::Space, DeclDef::IndentEquals)?;
args.push(arg);
Ok(ValueDeclState::MoreArgs)
}),
// Parse the body
Box::new(|p: &mut Parser<'a>| {
p.word1(b'=', DeclDef::Equals)?;
p.chomp_and_check_indent(DeclDef::Space, DeclDef::IndentBody)?;
let (body, end) = p.specialize(
|bump, e, row, col| DeclDef::Body(bump.alloc(e), row, col),
|p| p.expression(),
)?;
let args_slice = args_for_body.into_bump_slice();
let value = Value {
docs: maybe_docs,
name,
arguments: args_slice,
body,
annotation: type_ann,
attributes,
};
let located_value = p.add_end(start, value);
Ok(ValueDeclState::Done(Decl::Value(located_value), end))
}),
],
)?;
match result {
ValueDeclState::MoreArgs => continue,
ValueDeclState::Done(decl, end) => return Ok((decl, end)),
}
}
}
/// Check that the name matches the expected name (for type-annotated definitions).
fn chomp_matching_name_decl(
&mut self,
expected: &str,
) -> Result<&'a Located<&'a str>, DeclDef<'a>> {
let start = self.get_position();
let name = self.lower_name(DeclDef::NameRepeat)?;
let name_located = self.add_end(start, name);
if name == expected {
Ok(name_located)
} else {
let (row, col) = self.position();
Err(DeclDef::NameMatch(name, row, col))
}
}
}
/// State for parsing value definition arguments.
enum ValueDeclState<'a> {
MoreArgs,
Done(Decl<'a>, Position),
}
#[cfg(test)]
mod tests {
use super::super::assert_decl_snapshot;
#[test]
fn value_simple() {
assert_decl_snapshot!("foo = 1");
}
#[test]
fn value_with_args() {
assert_decl_snapshot!("add x y = x");
}
#[test]
fn value_with_type_annotation() {
assert_decl_snapshot!(
r#"
add : Int -> Int -> Int
add x y = x
"#
);
}
#[test]
fn value_with_constrained_annotation() {
assert_decl_snapshot!(
r#"
max : Ord 'a => 'a -> 'a -> 'a
max a b = a
"#
);
}
#[test]
fn value_multiline_body() {
assert_decl_snapshot!(
r#"
greet name =
name
"#
);
}
#[test]
fn value_with_doc_comment() {
assert_decl_snapshot!(
r#"
{-| A simple greeting function -}
greet name = name
"#
);
}
#[test]
fn value_with_doc_comment_multiline() {
assert_decl_snapshot!(
r#"
{-| Adds two numbers together.
This is a longer description.
-}
add : Int -> Int -> Int
add x y = x
"#
);
}
}