zust-parser 0.9.16

Lexer and parser for the Zust scripting language.
Documentation
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
use crate::try_parse;
use dynamic::{Dynamic, Type};

use super::{Expr, Parser, Pattern, Span, expr::ExprKind, pattern::PatternKind};
use anyhow::{Result, anyhow};
use smol_str::SmolStr;

#[derive(Debug, Clone)]
pub struct Stmt {
    pub kind: StmtKind,
    pub span: Span,
}

#[derive(Debug, Clone)]
pub enum StmtKind {
    Let { pat: Pattern, value: Box<Stmt> },
    Expr(Expr, bool),
    Block(Vec<Stmt>),
    Break,
    Continue,
    Return(Option<Expr>),
    While { cond: Expr, body: Box<Stmt> },
    Loop(Box<Stmt>),
    For { pat: Pattern, range: Expr, body: Box<Stmt> },
    Fn { name: SmolStr, generic_params: Vec<Type>, args: Vec<(SmolStr, Type)>, body: Box<Stmt>, is_pub: bool },
    Struct { name: SmolStr, def: Type, is_pub: bool },
    Impl { target: Type, body: Box<Stmt> },
    If { cond: Expr, then_body: Box<Stmt>, else_body: Option<Box<Stmt>> },
    Static { name: SmolStr, ty: Type, value: Option<Expr>, is_pub: bool },
    Const { name: SmolStr, ty: Type, value: Expr, is_pub: bool },
}

impl Stmt {
    pub fn new(kind: StmtKind, span: Span) -> Self {
        Self { kind, span }
    }

    pub fn expr(&self) -> Option<Expr> {
        if let StmtKind::Expr(expr, _) = &self.kind { Some(expr.clone()) } else { None }
    }

    pub fn is_return(&self) -> bool {
        matches!(self.kind, StmtKind::Return(_))
    }

    pub fn last_return(&mut self) -> bool {
        match &mut self.kind {
            StmtKind::Block(stmts) => stmts.last_mut().map(|stmt| stmt.last_return()).unwrap_or(false),
            StmtKind::If { then_body, else_body, .. } => {
                let then_returns = then_body.last_return();
                let else_returns = else_body.as_mut().map(|body| body.last_return()).unwrap_or(false);
                then_returns && else_returns
            }
            StmtKind::Expr(e, close) => {
                if !*close {
                    let span = e.span;
                    *self = Self::new(StmtKind::Return(Some(std::mem::take(e))), span);
                    true
                } else {
                    false
                }
            }
            StmtKind::Return(_) => true,
            _ => false,
        }
    }

    pub fn get_type(&self) -> Option<Type> {
        match &self.kind {
            StmtKind::Expr(expr, _) => Some(expr.get_type()),
            StmtKind::Block(stmts) => stmts.last().and_then(|stmt| stmt.get_type()),
            StmtKind::If { then_body, .. } => then_body.get_type(),
            _ => None,
        }
    }

    fn get_assign(idx: u32, expr: Expr) -> Self {
        let span = expr.span;
        Self::new(StmtKind::Expr(Expr::new(ExprKind::Binary { left: Box::new(Expr::new(ExprKind::Var(idx), span)), op: crate::BinaryOp::Assign, right: Box::new(expr) }, span), true), span)
    }

    fn get_idx_assign(pat: Expr, idx: usize, expr: Expr) -> Self {
        let span = pat.span.merge(expr.span);
        let right = Expr::new(ExprKind::Binary { left: Box::new(expr), op: crate::BinaryOp::Idx, right: Box::new(Expr::new(ExprKind::Value((idx as u32).into()), span)) }, span);
        Self::new(StmtKind::Expr(Expr::new(ExprKind::Binary { left: Box::new(pat), op: crate::BinaryOp::Assign, right: Box::new(right) }, span), true), span)
    }

    fn get_assign_expr(pat: Expr, expr: Expr) -> Self {
        let span = pat.span.merge(expr.span);
        Self::new(StmtKind::Expr(Expr::new(ExprKind::Binary { left: Box::new(pat), op: crate::BinaryOp::Assign, right: Box::new(expr) }, span), true), span)
    }

    pub fn bind_pattern(&mut self, pat: Pattern) -> Result<()> {
        if let Some(expr) = self.expr() {
            let stmt = match pat.kind {
                PatternKind::Var { idx, ty } => {
                    if expr.get_type() != ty {
                        Self::get_assign(idx, Expr::new(ExprKind::Typed { value: Box::new(expr), ty }, pat.span))
                    } else {
                        Self::get_assign(idx, expr)
                    }
                }
                PatternKind::Tuple(list) => {
                    let mut stmts = Vec::new();
                    for (idx, p) in list.into_iter().enumerate() {
                        match p.expr() {
                            Ok(p) => stmts.push(Self::get_idx_assign(p, idx, expr.clone())),
                            Err(e) => return Err(e),
                        }
                    }
                    Self::new(StmtKind::Block(stmts), self.span)
                }
                PatternKind::List { elems, has_rest } => {
                    let mut stmts = Vec::new();
                    let prefix_count = if has_rest { elems.len() - 1 } else { elems.len() };
                    for (idx, p) in elems.iter().take(prefix_count).enumerate() {
                        match p.expr() {
                            Ok(p) => stmts.push(Self::get_idx_assign(p, idx, expr.clone())),
                            Err(e) => return Err(e),
                        }
                    }
                    if has_rest {
                        // 最后一个元素是 `..rest`,把它绑定为 expr[prefix_count..] 的切片。
                        let rest_pat = elems.last().unwrap();
                        let rest_expr = match &rest_pat.kind {
                            PatternKind::Ident { name, .. } => Expr::new(ExprKind::Ident(name.clone()), rest_pat.span),
                            PatternKind::Var { idx, .. } => Expr::new(ExprKind::Var(*idx), rest_pat.span),
                            _ => return Err(anyhow!("..rest 后的模式必须是标识符")),
                        };
                        let from = Expr::new(ExprKind::Value((prefix_count as u32).into()), rest_pat.span);
                        let slice_idx = Expr::new(
                            ExprKind::Binary {
                                left: Box::new(expr.clone()),
                                op: crate::BinaryOp::Idx,
                                right: Box::new(Expr::new(
                                    ExprKind::Binary { left: Box::new(from), op: crate::BinaryOp::RangeOpen, right: Box::new(Expr::new(ExprKind::Value(Dynamic::Null), rest_pat.span)) },
                                    rest_pat.span,
                                )),
                            },
                            rest_pat.span,
                        );
                        stmts.push(Self::get_assign_expr(rest_expr, slice_idx));
                    }
                    Self::new(StmtKind::Block(stmts), self.span)
                }
                p => return Err(anyhow!("不支持的模式绑定: {:?}", p)),
            };
            let _ = std::mem::replace(self, stmt);
        } else {
            match &mut self.kind {
                StmtKind::Block(stmts) => {
                    if let Some(stmt) = stmts.last_mut() {
                        stmt.bind_pattern(pat)?;
                    }
                }
                StmtKind::If { then_body, else_body, .. } => {
                    then_body.bind_pattern(pat.clone())?;
                    if let Some(e) = else_body {
                        e.bind_pattern(pat)?;
                    }
                }
                _ => {}
            }
        }
        Ok(())
    }
}

use std::fmt;
impl fmt::Display for Stmt {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.kind {
            StmtKind::Let { pat, value } => writeln!(f, "let {:?} = {}", pat, value)?,
            StmtKind::Block(stmts) => stmts.iter().for_each(|s| {
                let _ = write!(f, "{}", s);
            }),
            StmtKind::Expr(expr, close) => writeln!(f, "{:?}[{}]", expr, close)?,
            StmtKind::Break => writeln!(f, "break")?,
            StmtKind::Continue => writeln!(f, "continue")?,
            StmtKind::Return(r) => writeln!(f, "return {:?}", r)?,
            StmtKind::While { cond, body } => write!(f, "while {:?}\n{}", cond, body)?,
            StmtKind::Loop(body) => write!(f, "loop\n{}", body)?,
            StmtKind::For { pat, range, body } => writeln!(f, "for {:?} in {:?} \n{}", pat, range, body)?,
            StmtKind::If { cond, then_body, else_body } => {
                write!(f, "if {:?}\nthen-> {}\n", cond, then_body)?;
                if let Some(e) = else_body {
                    writeln!(f, "{}", e)?;
                }
            }
            StmtKind::Fn { name, generic_params, args, body, is_pub } => {
                let generic_suffix = if generic_params.is_empty() { String::new() } else { format!("<{:?}>", generic_params) };
                if *is_pub {
                    write!(f, "pub fn {:?}{} {:?}\n", name, generic_suffix, args)?
                } else {
                    write!(f, "fn {:?}{} {:?}\n", name, generic_suffix, args)?
                }
                write!(f, "{}", body)?;
            }
            _ => write!(f, "(todo display: {:?})", self.kind)?,
        }
        fmt::Result::Ok(())
    }
}

impl Parser {
    pub fn ident_typed(&mut self) -> Result<(SmolStr, Type)> {
        let name = self.ident()?;
        self.whitespace()?;
        if self.take(b':').is_ok() { Ok((name, self.get_type()?)) } else { Ok((name, Type::Any)) }
    }

    pub fn ident_generic(&mut self) -> Result<(SmolStr, Vec<Type>)> {
        self.whitespace()?;
        let name = self.ident()?;
        self.whitespace()?;
        let params = if self.get()? == b'<' {
            self.pos += 1;
            crate::parse_list!(self, Vec::new(), b'>', b',', self.get_type_param()?)
        } else {
            Vec::new()
        };
        Ok((name, params))
    }

    pub fn block(&mut self) -> Result<Stmt> {
        self.check_fatal()?;
        self.whitespace()?;
        let start = self.current_pos();
        if self.get()? == b'{' {
            self.pos += 1;
            self.enter_depth()?;
            self.push_decl_scope();
            let result = (|| -> Result<Stmt> {
                let body = crate::parse_list!(self, Vec::new(), b'}', 0, self.stmt(false)?);
                Ok(Stmt::new(StmtKind::Block(body), self.span_from(start)))
            })();
            self.pop_decl_scope();
            self.exit_depth();
            result
        } else {
            Err(anyhow!("not code block"))
        }
    }

    pub fn if_block(&mut self) -> Result<Stmt> {
        let start = self.spans.last().copied().unwrap_or_else(|| self.current_pos());
        let cond = self.get_expr_without_struct_literal()?;
        let then_body = Box::new(self.block()?);
        self.whitespace()?;
        let else_body = if self.keyword("else").is_ok() {
            self.whitespace()?;
            let body = if self.keyword("if").is_ok() { self.if_block()? } else { self.block()? };
            Some(Box::new(body))
        } else {
            None
        };
        Ok(Stmt::new(StmtKind::If { cond, then_body, else_body }, Span::new(start, self.current_pos())))
    }

    pub fn stmt(&mut self, is_pub: bool) -> Result<Stmt> {
        self.check_fatal()?;
        self.whitespace()?;
        self.spans.push(self.pos);
        let start = self.current_pos();
        // 函数体内不允许 fn / struct / impl / const / static 顶层声明。
        // 编译器对这些位置直接 panic,这里前置到 parser,让错误落到用户可见的地方。
        if self.fn_body_depth > 0 {
            for kw in &["fn", "struct", "impl", "const", "static"] {
                if self.keyword(kw).is_ok() {
                    return Err(anyhow!("函数体内不能定义 {};请移到顶层或改用闭包", kw));
                }
            }
        }
        // impl body 允许 fn(方法)和 pub fn,但拒绝嵌套 struct / impl / const / static。
        if self.impl_body_depth > 0 {
            for kw in &["struct", "impl", "const", "static"] {
                if self.keyword(kw).is_ok() {
                    return Err(anyhow!("impl 体内不能定义 {};请移到顶层", kw));
                }
            }
        }
        let stmt = if self.keyword("let").is_ok() {
            let pat = self.pattern()?;
            self.declare_pattern_symbols(&pat)?;
            self.until(b'=')?;
            self.whitespace()?;
            let value = if self.get()? == b'{' {
                if self.looks_like_dict() {
                    self.get_expr()?
                } else {
                    // 块作为表达式:{ stmts; expr } 的值是最后一条语句的值。
                    let span = self.current_pos();
                    let block_stmt = self.block()?;
                    Expr::new(ExprKind::Stmt(Box::new(block_stmt)), Span::new(span, self.current_pos()))
                }
            } else {
                self.get_expr()?
            };
            self.whitespace()?;
            let close = self.take(b';').is_ok();
            let stmt = Stmt::new(StmtKind::Expr(value, close), Span::new(start, self.current_pos()));
            Stmt::new(StmtKind::Let { pat, value: Box::new(stmt) }, Span::new(start, self.current_pos()))
        } else if self.keyword("break").is_ok() {
            self.until(b';')?;
            Stmt::new(StmtKind::Break, Span::new(start, self.current_pos()))
        } else if self.keyword("continue").is_ok() {
            self.until(b';')?;
            Stmt::new(StmtKind::Continue, Span::new(start, self.current_pos()))
        } else if self.keyword("return").is_ok() {
            self.whitespace()?;
            let expr = if matches!(self.get(), Ok(b';' | b'}')) { None } else { Some(self.get_expr()?) };
            self.whitespace()?;
            if self.take(b';').is_err() && !matches!(self.get(), Ok(b'}')) {
                self.until(b';')?;
            }
            Stmt::new(StmtKind::Return(expr), Span::new(start, self.current_pos()))
        } else if self.keyword("if").is_ok() {
            self.if_block()?
        } else if self.keyword("loop").is_ok() {
            Stmt::new(StmtKind::Loop(Box::new(self.block()?)), Span::new(start, self.current_pos()))
        } else if self.keyword("while").is_ok() {
            self.whitespace()?;
            let cond = self.get_expr()?;
            let body = Box::new(self.block()?);
            Stmt::new(StmtKind::While { cond, body }, Span::new(start, self.current_pos()))
        } else if self.keyword("for").is_ok() {
            self.whitespace()?;
            let pat = self.pattern()?;
            self.whitespace()?;
            self.keyword("in")?;
            self.whitespace()?;
            let range = self.get_expr()?;
            self.push_decl_scope();
            let result: Result<Stmt> = (|| {
                self.declare_pattern_symbols(&pat)?;
                let body = Box::new(self.block()?);
                Ok(Stmt::new(StmtKind::For { pat, range, body }, Span::new(start, self.current_pos())))
            })();
            self.pop_decl_scope();
            result?
        } else if self.keyword("fn").is_ok() {
            self.whitespace()?;
            let (name, generic_params) = self.ident_generic()?;
            self.declare_function_name(&name)?;
            self.until(b'(')?;
            let args = crate::parse_list!(self, Vec::new(), b')', b',', self.ident_typed()?);
            let body = Box::new(self.function_body(&args)?);
            Stmt::new(StmtKind::Fn { name, generic_params, args, body, is_pub }, Span::new(start, self.current_pos()))
        } else if self.keyword("struct").is_ok() {
            let (name, params) = self.ident_generic()?;
            self.declare_symbol(&name)?;
            if self.until(b'{').is_ok() {
                let fields = crate::parse_list!(self, Vec::new(), b'}', b',', self.ident_typed()?);
                if let Some(f) = fields.iter().find(|f| f.1.is_any()) {
                    return Err(anyhow!("字段 {} 的类型未知", f.0));
                }
                Stmt::new(StmtKind::Struct { name, def: Type::Struct { params, fields }, is_pub }, Span::new(start, self.current_pos()))
            } else {
                self.until(b';')?;
                Stmt::new(StmtKind::Struct { name, def: Type::Struct { params, fields: Vec::new() }, is_pub }, Span::new(start, self.current_pos()))
            }
        } else if self.keyword("const").is_ok() {
            self.whitespace()?;
            let (name, ty) = self.ident_typed()?;
            self.declare_symbol(&name)?;
            self.until(b'=')?;
            let value = self.get_expr()?;
            self.until(b';')?;
            Stmt::new(StmtKind::Const { name, ty, value, is_pub }, Span::new(start, self.current_pos()))
        } else if self.keyword("static").is_ok() {
            self.whitespace()?;
            let (name, ty) = self.ident_typed()?;
            self.declare_symbol(&name)?;
            self.whitespace()?;
            if self.take(b'=').is_ok() {
                let expr = self.get_expr()?;
                self.until(b';')?;
                Stmt::new(StmtKind::Static { name, ty, value: Some(expr), is_pub }, Span::new(start, self.current_pos()))
            } else {
                self.until(b';')?;
                Stmt::new(StmtKind::Static { name, ty, value: None, is_pub }, Span::new(start, self.current_pos()))
            }
        } else if self.keyword("impl").is_ok() {
            self.whitespace()?;
            let target = self.get_type()?;
            Stmt::new(StmtKind::Impl { target, body: Box::new(self.impl_body()?) }, Span::new(start, self.current_pos()))
        } else if self.keyword("pub").is_ok() {
            self.stmt(true)?
        } else {
            let expr = if self.get()? == b'{' {
                if self.looks_like_empty_dict() {
                    self.dict()?
                } else if let Ok(block) = try_parse!(self, self.block()) {
                    let _ = self.spans.pop();
                    return Ok(block);
                } else if let Ok(dict) = try_parse!(self, self.dict()) {
                    dict
                } else {
                    let block = self.block()?;
                    let _ = self.spans.pop();
                    return Ok(block);
                }
            } else {
                self.get_expr()?
            };
            self.whitespace()?;
            if self.is_eof() {
                Stmt::new(StmtKind::Expr(expr, false), Span::new(start, self.current_pos()))
            } else if self.get()? == b';' {
                self.pos += 1;
                Stmt::new(StmtKind::Expr(expr, true), Span::new(start, self.current_pos()))
            } else if self.get()? == b'}' {
                Stmt::new(StmtKind::Expr(expr, false), Span::new(start, self.current_pos()))
            } else {
                return Err(anyhow!("未结束的表达式"));
            }
        };
        let _ = self.spans.pop();
        Ok(stmt)
    }
}