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
// Function declaration parsing
use crate::ast::*;
use crate::lexer::{KeywordKind, TokenKind};
use tsv_lang::{Error, Span};
use super::super::Parser;
use super::super::expression::alloc_expr;
impl<'a, 'arena> Parser<'a, 'arena> {
pub(super) fn parse_return_statement(&mut self) -> Result<Statement<'arena>, Error> {
let (start, _) = self.current_pos();
// Consume 'return' keyword
debug_assert!(matches!(
self.current_kind(),
TokenKind::Keyword(KeywordKind::Return)
));
self.advance()?;
// ASI Rule: If semicolon present or can insert semicolon, return has no argument.
// This handles: `return\n1+2` → `return;` (then `1+2;` as separate statement)
// The `1+2` becomes an unreachable expression statement.
if self.eat(TokenKind::Semicolon)? || self.can_insert_semicolon() {
let end = self.prev_token_end() as u32;
return Ok(Statement {
span: Span::new(start as u32, end),
kind: StatementKind::ReturnStatement(ReturnStatement { argument: None }),
});
}
// No ASI - parse the return value expression
let argument_token = self.current_pos().0;
let argument = self.parse_expression_ref()?;
self.restricted_argument_pair(argument, argument_token)?;
let end = self.semicolon_end()?;
Ok(Statement {
span: Span::new(start as u32, end),
kind: StatementKind::ReturnStatement(ReturnStatement {
argument: Some(argument),
}),
})
}
pub(super) fn parse_function_declaration(&mut self) -> Result<Statement<'arena>, Error> {
self.parse_function_or_overload(false, None)
}
/// Parse function declaration or overload signature
///
/// Function overloads end with semicolon instead of body:
/// ```typescript
/// function check(x: unknown): x is string; // overload - TSDeclareFunction
/// function check(x: unknown): x is number; // overload - TSDeclareFunction
/// function check(x: unknown) { ... } // implementation - FunctionDeclaration
/// ```
///
/// `start_override` is the statement's own start when the caller consumed a
/// leading token of its own (`async`), so the span is built right rather than
/// patched afterwards — both variants are arena-boxed and a `&'arena` head has
/// no `&mut` to patch through.
fn parse_function_or_overload(
&mut self,
is_async: bool,
start_override: Option<usize>,
) -> Result<Statement<'arena>, Error> {
let start = start_override.unwrap_or_else(|| self.current_pos().0);
// Consume 'function' keyword
debug_assert!(matches!(
self.current_kind(),
TokenKind::Keyword(KeywordKind::Function)
));
self.advance()?;
// Check for generator: function*
let is_generator = self.eat(TokenKind::Star)?;
// Parse function name (required for declarations)
// Keywords like `object` and `async` can be function names; `await` is a
// valid name only at Script `[~Await]` (reserved at Module / `[+Await]`).
let (id_start, id_end) = self.current_pos();
let Some(name) = self.try_function_name() else {
return Err(self.error_expected_after("function name", "function"));
};
self.advance()?;
let id = Identifier::simple(name, Span::new(id_start as u32, id_end as u32));
// Parse type parameters (TypeScript generics): function foo<T>()
let type_parameters = self.parse_optional_type_parameters()?;
// Capture paren position before parsing params (for comment detection)
let (params_start, _) = self.current_pos();
// Parse parameter list (in the function's own `[Await]`/`[Yield]` context —
// async/generator params are `[+Await]`/`[+Yield]`).
let params: &'arena [Expression<'arena>] = self
.with_fn_context(is_async, is_generator, Self::parse_parameter_list)?
.into_bump_slice();
// Check for return type annotation
let return_type = self.parse_optional_return_type()?;
// Check if this is an overload (ends with ; or no body) or implementation (has body)
// Overload signatures don't have a body block - they end with ; or ASI
if !matches!(self.current_kind(), TokenKind::BraceOpen) {
// Function overload signature - parse as TSDeclareFunction
let end = self.semicolon_end()?;
Ok(Statement::from_ts_declare_function(self.arena.alloc(
TSDeclareFunction {
id,
type_parameters,
params,
return_type,
declare: false, // Not a `declare function`, just an overload
r#async: is_async,
generator: is_generator,
span: Span::new(start as u32, end),
},
)))
} else {
// Function implementation - parse body (the function's `[Await]`/`[Yield]` context).
let body = self.with_fn_context(is_async, is_generator, Self::parse_function_body)?;
let end = body.span.end;
Ok(Statement::from_function_declaration(self.arena.alloc(
FunctionDeclaration {
id: Some(id),
type_parameters,
params,
return_type,
body,
generator: is_generator,
r#async: is_async,
params_start: params_start as u32,
span: Span::new(start as u32, end),
},
)))
}
}
/// Parse async function declaration: `async function foo() {}` or `async function* foo() {}`
pub(super) fn parse_async_function_declaration(&mut self) -> Result<Statement<'arena>, Error> {
let (start, _) = self.current_pos();
// Consume 'async' keyword
debug_assert!(matches!(
self.current_kind(),
TokenKind::Keyword(KeywordKind::Async)
));
self.advance()?;
// Parse the function (which may be an overload signature or implementation),
// handing it the `async` keyword's position so its span covers it.
self.parse_function_or_overload(true, Some(start))
}
/// Inner function that can return either FunctionDeclaration or TSDeclareFunction
///
/// Used by export default and export named to handle both regular and ambient contexts
pub(super) fn parse_function_declaration_or_declare(
&mut self,
is_async: bool,
) -> Result<ExportFunctionDeclaration<'arena>, Error> {
let (start, _) = self.current_pos();
// Consume 'function' keyword
debug_assert!(matches!(
self.current_kind(),
TokenKind::Keyword(KeywordKind::Function)
));
self.advance()?;
// Check for generator: function*
let is_generator = self.eat(TokenKind::Star)?;
// Parse function name (required for declarations, optional for export default)
// Keywords like `object` and `async` can be function names; `await` is a
// valid name only at Script `[~Await]` (reserved at Module / `[+Await]`).
let id = if let Some(name) = self.try_function_name() {
let (id_start, id_end) = self.current_pos();
self.advance()?;
Some(Identifier::simple(
name,
Span::new(id_start as u32, id_end as u32),
))
} else {
None
};
// Parse type parameters
let type_parameters = self.parse_optional_type_parameters()?;
// Capture paren position before parsing params (for comment detection)
let (params_start, _) = self.current_pos();
// Parse parameter list (in the function's own `[Await]`/`[Yield]` context).
let params: &'arena [Expression<'arena>] = self
.with_fn_context(is_async, is_generator, Self::parse_parameter_list)?
.into_bump_slice();
// Check for return type annotation
let return_type = self.parse_optional_return_type()?;
// Check if this is an overload signature (no body) or implementation (has body)
if !matches!(self.current_kind(), TokenKind::BraceOpen) {
// No body - this is a declare function (ambient context)
let end = self.semicolon_end()?;
Ok(ExportFunctionDeclaration::Declare(TSDeclareFunction {
id: id.unwrap_or_else(|| {
// Anonymous: empty name over a zero-width span (span-identity).
Identifier::simple(
IdentName {
escaped: None,
raw_len: 0,
// An empty name holds no byte, width-relevant or not.
plain_ascii: true,
},
Span::new(start as u32, start as u32),
)
}),
type_parameters,
params,
return_type,
declare: false,
r#async: is_async,
generator: is_generator,
span: Span::new(start as u32, end),
}))
} else {
// Has body - regular function declaration (the function's `[Await]`/`[Yield]` context).
let body = self.with_fn_context(is_async, is_generator, Self::parse_function_body)?;
let end = body.span.end;
Ok(ExportFunctionDeclaration::Declaration(
FunctionDeclaration {
id,
type_parameters,
params,
return_type,
body,
generator: is_generator,
r#async: is_async,
params_start: params_start as u32,
span: Span::new(start as u32, end),
},
))
}
}
/// Parse a function expression: `function() {}` or `function name<T>() {}`
///
/// Function expressions are similar to function declarations but:
/// - The name is always optional
/// - They appear in expression position
pub(in crate::parser) fn parse_function_expression(
&mut self,
) -> Result<&'arena Expression<'arena>, Error> {
let (start, _) = self.current_pos();
self.parse_function_expression_inner(start, false)
}
/// Parse an async function expression: `async function() {}` or `async function*() {}`
///
/// Called when we've already seen `async` and are at `function`.
pub(in crate::parser) fn parse_async_function_expression(
&mut self,
start: usize,
) -> Result<&'arena Expression<'arena>, Error> {
self.parse_function_expression_inner(start, true)
}
/// Core function expression parsing logic
fn parse_function_expression_inner(
&mut self,
start: usize,
is_async: bool,
) -> Result<&'arena Expression<'arena>, Error> {
// Consume 'function' keyword
debug_assert!(matches!(
self.current_kind(),
TokenKind::Keyword(KeywordKind::Function)
));
self.advance()?;
// Check for generator: function*
let is_generator = self.eat(TokenKind::Star)?;
// Parse the optional name in the function expression's own `[Await]`
// context: a `FunctionExpression` name is `[~Await]` (non-async) /
// `[+Await]` (async), so `await` is a valid name in a non-async function
// expression even inside a `[+Await]` enclosing scope (e.g. a static
// block), but not in an async one.
//
// `try_function_name` is the same channel the DECLARATION path above takes,
// and carries that `await` rule itself. Reading the token kind here instead
// saw only the words the lexer never made a `Keyword`, so the declaration
// `function string() {}` parsed while the expression form did not.
//
// ⚠️ Sharing the channel inherits its width, deliberately: `can_be_identifier`
// also admits `let` / `yield`, whose bar is a strict-mode early error tsv defers
// (tsc's parser accepts them too). That is one question to answer in one place;
// re-narrowing here would mint a third name channel and restore the very
// asymmetry this call avoids. `void` does NOT belong —
// it is a genuine `ReservedWord`, and this is the only position that can see
// the difference, which is why the answer lives in `can_be_identifier` itself.
let id = self.with_fn_context(is_async, is_generator, |p| {
if let Some(name) = p.try_function_name() {
let (id_start, id_end) = p.current_pos();
p.advance()?;
Ok(Some(Identifier::simple(
name,
Span::new(id_start as u32, id_end as u32),
)))
} else {
Ok(None)
}
})?;
// Parse type parameters (TypeScript generics): function<T>()
let type_parameters = self.parse_optional_type_parameters()?;
// Capture paren position before parsing params (for comment detection)
let (params_start, _) = self.current_pos();
// Param defaults (`[+In]`) and the function body are a fresh `[+In]`
// context, so `in` is the binary operator even when this function
// expression sits in a for-header init.
let (params, return_type, body) = self.with_fn_context(is_async, is_generator, |p| {
p.with_body_frame(|p| {
let params: &'arena [Expression<'arena>] =
p.parse_parameter_list()?.into_bump_slice();
let return_type = p.parse_optional_return_type()?;
// three wire levels: the `FunctionExpression`, its body's `BlockStatement`
// and its statements — a declaration's own level is its statement's
let body = p.parse_function_body_levels(3)?;
Ok((params, return_type, body))
})
})?;
let end = body.span.end;
Ok(alloc_expr(
self.arena,
Expression::from_function_expression(self.arena.alloc(FunctionExpression {
id,
type_parameters,
params,
return_type,
body,
generator: is_generator,
r#async: is_async,
params_start: params_start as u32,
span: Span::new(start as u32, end),
})),
))
}
}