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
//! `switch` (ECMAScript §14.12).
//!
//! # A CaseBlock is one scope, and the clauses inside it are not scopes at all
//!
//! This is the whole reason `switch` needs anything said about it. `{ case 1: let a; case 2:
//! let a; }` looks like two declarations in two places and is a redeclaration, because §8.2.6
//! defines the `LexicallyDeclaredNames` of a `CaseBlock` as the concatenation across every
//! clause. Write the braces — `case 1: { let a; } case 2: { let a; }` — and the two are genuinely
//! separate. The clauses are labels to jump to, not bodies to enter.
//!
//! So §14.12.1 states the same two rules §14.2.1 states about a Block, over a list that is
//! stitched together from every clause. That stitching is the specification's own
//! list-concatenation, and [`super::scope`] does it that way rather than by walking a `Switch`.
//!
//! # `break` belongs here and `continue` does not
//!
//! §14.9.1 lets a `break` be inside "an IterationStatement or a SwitchStatement"; §14.8.1 gives
//! `continue` only the first. That asymmetry is the reason the parser counts two things instead
//! of one: a `switch` is somewhere to break out of, and never somewhere to continue.
//!
//! # At most one `default`, which the tree cannot say
//!
//! `CaseBlock : { CaseClauses_opt DefaultClause CaseClauses_opt }` — the grammar's way of
//! allowing one `default` anywhere among the clauses. The tree here keeps them in one flat list,
//! which is what every consumer wants and what evaluation order actually is, so the constraint
//! stops being structural and becomes a thing to check. It is still a missing production rather
//! than an early error, and it is named that way.
use super::expression::AllowIn;
use super::{ParseError, ParseErrorKind, Parser};
use crate::ast::{Stmt, StmtKind, SwitchCase, SwitchStatement};
use crate::lexer::{Goal, ReservedWord, TokenKind};
impl Parser<'_> {
/// `SwitchStatement : switch ( Expression ) CaseBlock` (§14.12).
pub(super) fn parse_switch(&mut self) -> Result<Stmt, ParseError> {
let keyword = self.advance(Goal::RegExp)?;
self.eat(TokenKind::LParen, Goal::RegExp, "`(`")?;
self.enter()?;
let discriminant = self.parse_expression(AllowIn::Yes);
self.leave();
let discriminant = discriminant?;
self.eat(TokenKind::RParen, Goal::RegExp, "`)`")?;
self.enter()?;
let cases = self.parse_case_block();
self.leave();
let (cases, end) = cases?;
Ok(Stmt {
span: keyword.span.to(end),
kind: StmtKind::Switch(Box::new(SwitchStatement {
discriminant,
cases,
})),
})
}
/// `CaseBlock` (§14.12), returning its clauses and the span of the closing brace.
fn parse_case_block(&mut self) -> Result<(Box<[SwitchCase]>, crate::span::Span), ParseError> {
self.eat(TokenKind::LBrace, Goal::RegExp, "`{`")?;
let mut cases: Vec<SwitchCase> = Vec::new();
let mut seen_default = false;
while self.current.kind != TokenKind::RBrace {
let case = self.parse_case_clause()?;
if case.test.is_none() {
// The grammar admits one `DefaultClause` between two runs of `CaseClauses`, so a
// second one has no derivation. Reported against the clause itself: the first is
// not the mistake, however far back it was.
if seen_default {
return Err(ParseError {
kind: ParseErrorKind::MultipleDefaultClauses,
span: case.span,
});
}
seen_default = true;
}
cases.push(case);
}
let close = self.eat(TokenKind::RBrace, Goal::RegExp, "`}`")?;
// §14.12.1, over the clauses stitched together — see `super::scope`.
super::scope::check_case_block_declared_names(&cases, self.strict)?;
Ok((cases.into_boxed_slice(), close.span))
}
/// One `CaseClause` or `DefaultClause` (§14.12).
fn parse_case_clause(&mut self) -> Result<SwitchCase, ParseError> {
let (keyword, test) = match self.current.kind {
TokenKind::Keyword(ReservedWord::Case) => {
let keyword = self.advance(Goal::RegExp)?;
self.enter()?;
// `case Expression :` — a full `Expression`, so `case a, b:` is a sequence and
// the comma does not separate two clauses.
let test = self.parse_expression(AllowIn::Yes);
self.leave();
(keyword, Some(test?))
}
TokenKind::Keyword(ReservedWord::Default) => (self.advance(Goal::RegExp)?, None),
_ => return Err(self.unexpected("`case` or `default`")),
};
self.eat(TokenKind::Colon, Goal::RegExp, "`:`")?;
let mut body = Vec::new();
let mut end = keyword.span;
// `StatementList_opt`, which ends where the next clause begins. A clause body is a
// StatementList and not a Statement, so `case 1: let a;` is a declaration — one that
// belongs to the whole CaseBlock rather than to this clause.
while !matches!(
self.current.kind,
TokenKind::RBrace
| TokenKind::Eof
| TokenKind::Keyword(ReservedWord::Case)
| TokenKind::Keyword(ReservedWord::Default)
) {
let stmt = self.parse_statement_list_item()?;
end = stmt.span;
body.push(stmt);
}
Ok(SwitchCase {
test,
body: body.into_boxed_slice(),
span: keyword.span.to(end),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::parser::parse_script;
use crate::parser::test_support::*;
use crate::span::Span;
#[test]
fn a_case_block_holds_clauses_and_nothing_else() {
assert_eq!(statements("switch (x) {}"), ["(switch x)"]);
assert_eq!(
statements("switch (x) { case 1: }"),
["(switch x (case 1 {}))"]
);
assert_eq!(
statements("switch (x) { case 1: a; }"),
["(switch x (case 1 {a}))"]
);
assert_eq!(
statements("switch (x) { default: }"),
["(switch x (default {}))"]
);
assert_eq!(
statements("switch (x) { case 1: a; default: b; case 2: c; }"),
["(switch x (case 1 {a}) (default {b}) (case 2 {c}))"]
);
// A clause with no statements falls through to the next, which is why the body is
// optional rather than merely allowed to be empty.
assert_eq!(
statements("switch (x) { case 1: case 2: a; }"),
["(switch x (case 1 {}) (case 2 {a}))"]
);
// The head is a full `Expression`, and so is a `case` — `case a, b:` is a sequence, not
// two clauses.
assert_eq!(
statements("switch (x, y) { case a, b: c; }"),
["(switch (, x y) (case (, a b) {c}))"]
);
// A statement outside a clause has nowhere to go.
assert_eq!(
script_error("switch (x) { a; }").kind,
ParseErrorKind::Unexpected {
expected: "`case` or `default`",
found: TokenKind::Identifier {
contains_escape: false
},
}
);
for source in [
"switch (x) case 1: a;",
"switch x {}",
"switch (x) { case: a; }",
"switch (x) { case 1 a; }",
"switch () {}",
"switch (x) { default a; }",
] {
assert!(parse_script(source).is_err(), "{source:?}");
}
let script = parse_script("switch (x) {}").expect("this parses");
assert_eq!(script.body[0].span, Span::new(0, 13));
}
#[test]
fn a_switch_may_have_one_default_and_it_may_stand_anywhere() {
assert!(parse_script("switch (x) { default: a; case 1: b; }").is_ok());
assert!(parse_script("switch (x) { case 1: b; default: a; }").is_ok());
assert!(parse_script("switch (x) { case 1: b; default: a; case 2: c; }").is_ok());
// `CaseBlock : { CaseClauses_opt DefaultClause CaseClauses_opt }` admits exactly one, so
// a second has no derivation.
assert_eq!(
script_error("switch (x) { default: a; default: b; }").kind,
ParseErrorKind::MultipleDefaultClauses
);
assert_eq!(
script_error("switch (x) { default: default: }").kind,
ParseErrorKind::MultipleDefaultClauses
);
assert_eq!(
script_error("switch (x) { default: a; case 1: b; default: c; }").kind,
ParseErrorKind::MultipleDefaultClauses
);
// Reported against the second clause, not the first — the first was fine.
let source = "switch (x) { default: default: }";
assert_eq!(script_error(source).span, Span::new(22, 29));
assert_eq!(
script_error(source).span.slice(source),
Some("default"),
"the second one, and it has no body to extend over"
);
// A nested switch has a default of its own, and it is not the outer one's second.
assert!(parse_script("switch (x) { default: switch (y) { default: } }").is_ok());
}
#[test]
fn a_switch_is_somewhere_to_break_out_of_and_never_somewhere_to_continue() {
// §14.9.1 admits "an IterationStatement or a SwitchStatement"; §14.8.1 admits only the
// first. Two counts, because the two rules genuinely differ.
assert_eq!(
statements("switch (x) { case 1: break; }"),
["(switch x (case 1 {break}))"]
);
assert_eq!(
script_error("switch (x) { case 1: continue; }").kind,
ParseErrorKind::ContinueOutsideLoop
);
// …and a loop outside the switch supplies what the switch cannot.
assert!(parse_script("while (y) { switch (x) { case 1: continue; } }").is_ok());
assert!(parse_script("while (y) { switch (x) { case 1: break; } }").is_ok());
assert!(parse_script("do { switch (x) { case 1: continue; } } while (y);").is_ok());
// A switch does not make a `continue` legal after it, and neither count leaks.
assert_eq!(
script_error("switch (x) {} break;").kind,
ParseErrorKind::BreakOutsideLoop
);
assert_eq!(
script_error("switch (x) { case 1: } continue;").kind,
ParseErrorKind::ContinueOutsideLoop
);
assert_eq!(
script_error("while (y) { switch (x) {} } break;").kind,
ParseErrorKind::BreakOutsideLoop
);
// …including when the block fails to parse, which is the case a stray `?` would break.
assert!(parse_script("switch (x) { case 1: @ }").is_err());
assert_eq!(
script_error("break;").kind,
ParseErrorKind::BreakOutsideLoop
);
}
#[test]
fn the_whole_case_block_is_one_scope_and_a_clause_is_not_a_scope_at_all() {
// §14.12.1, over the `LexicallyDeclaredNames` of the CaseBlock — which §8.2.6 defines as
// the concatenation across every clause. Two clauses are two labels, not two scopes.
assert_eq!(
script_error("switch (x) { case 1: let a; case 2: let a; }").kind,
ParseErrorKind::DuplicateLexicalBinding
);
assert_eq!(
script_error("switch (x) { case 1: let a; default: const a = 1; }").kind,
ParseErrorKind::DuplicateLexicalBinding
);
assert_eq!(
script_error("switch (x) { case 1: let a; case 2: var a; }").kind,
ParseErrorKind::ConflictingVarAndLexicalDeclaration
);
assert_eq!(
script_error("switch (x) { case 1: var a; case 2: let a; }").kind,
ParseErrorKind::ConflictingVarAndLexicalDeclaration
);
// Write the braces and they really are separate — which is the half that shows the rule
// is about scopes rather than about clauses.
assert!(parse_script("switch (x) { case 1: { let a; } case 2: { let a; } }").is_ok());
assert!(parse_script("switch (x) { case 1: let a; case 2: let b; }").is_ok());
assert!(parse_script("switch (x) { case 1: var a; case 2: var a; }").is_ok());
assert!(parse_script("switch (x) { case 1: let a; break; }").is_ok());
// A `var` in any clause hoists out of the switch entirely.
for source in [
"let a; switch (x) { case 1: var a; }",
"let a; switch (x) { case 1: { var a; } }",
"let a; switch (x) { default: if (y) var a; }",
"let a; switch (x) { case 1: while (y) var a; }",
] {
assert_eq!(
script_error(source).kind,
ParseErrorKind::ConflictingVarAndLexicalDeclaration,
"{source:?}"
);
}
// …while a lexical name inside the block stays inside it.
assert!(parse_script("let a; switch (x) { case 1: let b; }").is_ok());
assert!(parse_script("var a; switch (x) { case 1: let a; }").is_ok());
}
#[test]
fn no_switch_however_truncated_can_panic() {
let cases = [
"switch".to_string(),
"switch (".to_string(),
"switch (x".to_string(),
"switch (x)".to_string(),
"switch (x) {".to_string(),
"switch (x) { case".to_string(),
"switch (x) { case 1".to_string(),
"switch (x) { case 1:".to_string(),
"switch (x) { default".to_string(),
"case 1:".to_string(),
"default:".to_string(),
"switch (x) { case 1: ".repeat(1000),
format!("switch (x) {{ {} }}", "case 1: ".repeat(10_000)),
];
for source in &cases {
let _ = parse_script(source);
}
// A long flat list of clauses is a loop, so it is bounded by memory; nesting is not.
assert_eq!(
parse_script(&format!("switch (x) {{ {} }}", "case 1: ".repeat(10_000)))
.map(|script| script.body.len())
.ok(),
Some(1)
);
assert_eq!(
script_error(&"switch (x) { case 1: ".repeat(1000)).kind,
ParseErrorKind::TooDeeplyNested
);
}
}