pine-sema 0.1.0

Semantic analysis for Pine Script.
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
//! The semantic analyzer: a scope-aware walk that emits Tier 1 (name
//! resolution) and Tier 4 (structural) errors.
//!
//! This intentionally does **not** use the shared [`pine_ast::Visitor`]. That
//! traversal is for observational passes; sema needs to push/pop a scope at
//! every block boundary, hoist declarations, and track context (loop depth,
//! global-vs-local), which the default recurse-everything walk doesn't express.
//! So we hand-write the recursion and interleave the scope bookkeeping.

use std::collections::HashMap;

use pine_ast::{Argument, Expr, Literal, Program, Stmt};
use pine_interpreter::{BuiltinSignature, PineOutput, Value};

use crate::scope::{is_global_only, ScopeStack, SymbolKind};
use pine_diagnostics::Diagnostic;

pub struct Analyzer<'a, O: PineOutput> {
    scopes: ScopeStack,
    diagnostics: Vec<Diagnostic>,
    /// Number of enclosing loops in the *current function*. Reset across
    /// function boundaries — a loop never spans a function.
    loop_depth: u32,
    /// The runtime's registered built-ins — namespaces, global functions, and
    /// per-bar variables that exist without a user declaration. Supplied by the
    /// caller rather than hardcoded here. Kept as the full value map (not just
    /// names) so later passes can inspect the objects' types.
    builtins: &'a HashMap<String, Value<O>>,
    /// How many script declarations (`indicator`/`strategy`/`library`) have been
    /// seen. A script may have at most one.
    declarations: u32,
}

/// The script-declaration functions — a script must have exactly one.
const SCRIPT_DECLARATIONS: &[&str] = &["study", "indicator", "strategy", "library"];

/// The called name as written, for diagnostics: `plot` or `ta.sma`.
fn callee_name(callee: &Expr) -> String {
    match callee {
        Expr::Variable(name) => name.clone(),
        Expr::MemberAccess { object, member } => match object.as_ref() {
            Expr::Variable(namespace) => format!("{namespace}.{member}"),
            _ => member.clone(),
        },
        _ => String::new(),
    }
}

/// How to name a literal's type in a diagnostic.
fn describe_literal(literal: &Literal) -> &'static str {
    match literal {
        Literal::Int(_) | Literal::Number(_) => "a number",
        Literal::String(_) => "a string",
        Literal::Bool(_) => "a bool",
        Literal::HexColor(_) => "a color",
        Literal::Na => "na",
    }
}

impl<'a, O: PineOutput> Analyzer<'a, O> {
    pub fn new(builtins: &'a HashMap<String, Value<O>>) -> Self {
        Self {
            scopes: ScopeStack::new(),
            diagnostics: Vec::new(),
            loop_depth: 0,
            builtins,
            declarations: 0,
        }
    }

    fn is_builtin(&self, name: &str) -> bool {
        self.builtins.contains_key(name)
    }

    /// The arguments the called builtin accepts, if the callee names one.
    ///
    /// Resolves both a bare name (`plot`) and a namespaced one (`ta.sma`, whose
    /// namespace is an object of builtins). A name the script has declared
    /// itself shadows the builtin, and a builtin written by hand carries no
    /// parameters — both yield `None`, so nothing is checked.
    fn builtin_signature(&self, callee: &Expr) -> Option<BuiltinSignature> {
        let value = match callee {
            Expr::Variable(name) => {
                if self.scopes.resolve(name).is_some() {
                    return None;
                }
                self.builtins.get(name)?.clone()
            }
            Expr::MemberAccess { object, member } => {
                let Expr::Variable(namespace) = object.as_ref() else {
                    return None;
                };
                if self.scopes.resolve(namespace).is_some() {
                    return None;
                }
                match self.builtins.get(namespace)? {
                    Value::Object { fields, .. } => fields.borrow().get(member)?.clone(),
                    _ => return None,
                }
            }
            _ => return None,
        };

        match value {
            Value::BuiltinFunction(builtin) if !builtin.signature.params.is_empty() => {
                Some(builtin.signature)
            }
            _ => None,
        }
    }

    /// Check a call's arguments against the builtin's parameters: too many
    /// arguments, an unknown named argument, and an argument whose literal type
    /// the parameter cannot accept.
    fn check_builtin_args(
        &mut self,
        name: &str,
        signature: &BuiltinSignature,
        args: &[Argument],
        pos: Option<(u32, u32)>,
    ) {
        let positional = args
            .iter()
            .filter(|arg| matches!(arg, Argument::Positional(_)))
            .count();

        if let Some(max) = signature.max_positional() {
            if positional > max {
                self.emit(
                    "too-many-arguments",
                    pos,
                    format!("`{name}` takes at most {max} arguments, found {positional}"),
                );
            }
        }

        let mut index = 0;
        for arg in args {
            let (param, value) = match arg {
                Argument::Positional(value) => {
                    let param = signature.positional(index);
                    index += 1;
                    (param, value)
                }
                Argument::Named { name: label, value } => match signature.named(label) {
                    Some(param) => (Some(param), value),
                    None => {
                        self.emit(
                            "unknown-argument",
                            pos,
                            format!("`{name}` has no argument named `{label}`"),
                        );
                        continue;
                    }
                },
            };

            // Only a literal's type is known without inference; anything else
            // is left to the runtime.
            let (Some(param), Expr::Literal(literal)) = (param, value) else {
                continue;
            };
            if !param.ty.accepts(literal) {
                let found = describe_literal(literal);
                let expected = param.ty.describe();
                let label = param.name.clone();
                self.emit(
                    "argument-type",
                    pos,
                    format!("`{name}` expects {expected} for `{label}`, found {found}"),
                );
            }
        }
    }

    /// Analyze a whole program, returning the errors found.
    pub fn analyze(mut self, program: &Program) -> Vec<Diagnostic> {
        for stmt in &program.statements {
            self.check_stmt(stmt);
        }
        self.diagnostics
    }

    fn emit(&mut self, rule: &'static str, pos: Option<(u32, u32)>, message: impl Into<String>) {
        self.diagnostics.push(Diagnostic::error(rule, pos, message));
    }

    /// Declare `name` in the current scope, reporting a duplicate if it already
    /// exists there. Pine has no hoisting — names become visible in source
    /// order — so this is called at each declaration's position.
    fn declare(&mut self, name: &str, kind: SymbolKind) {
        if self.scopes.declare(name, kind).is_some() {
            self.emit(
                "duplicate-declaration",
                None,
                format!("`{name}` is already declared in this scope"),
            );
        }
    }

    /// Visit a non-loop nested block (an `if`/`else` branch) in its own scope.
    fn block(&mut self, body: &[Stmt]) {
        self.scopes.push();
        for stmt in body {
            self.check_stmt(stmt);
        }
        self.scopes.pop();
    }

    /// Visit a loop body: its own scope, with `loop_depth` raised so
    /// `break`/`continue` are legal inside it.
    fn loop_body(&mut self, body: &[Stmt]) {
        self.loop_depth += 1;
        for stmt in body {
            self.check_stmt(stmt);
        }
        self.loop_depth -= 1;
    }

    /// Visit a function/method/lambda body in a fresh scope with `params`
    /// bound. Loop context does not cross into a function.
    fn function_body<'p>(
        &mut self,
        params: impl Iterator<Item = (&'p str, Option<&'p Expr>)>,
        body: &[Stmt],
    ) {
        self.scopes.push();
        let saved_loop_depth = self.loop_depth;
        self.loop_depth = 0;
        for (name, default) in params {
            if let Some(default) = default {
                self.check_expr(default);
            }
            self.scopes.declare(name, SymbolKind::Var);
        }
        for stmt in body {
            self.check_stmt(stmt);
        }
        self.loop_depth = saved_loop_depth;
        self.scopes.pop();
    }

    fn check_stmt(&mut self, stmt: &Stmt) {
        match stmt {
            Stmt::VarDecl {
                name, initializer, ..
            } => {
                // Check the initializer *before* declaring the name, so a
                // self-reference (`x = x`) resolves against the outer scope.
                if let Some(init) = initializer {
                    self.check_expr(init);
                }
                if self.scopes.declare(name, SymbolKind::Var).is_some() {
                    self.emit(
                        "duplicate-declaration",
                        None,
                        format!(
                            "`{name}` is already declared in this scope (use `:=` to reassign)"
                        ),
                    );
                }
            }
            Stmt::Assignment { target, value } => {
                self.check_expr(value);
                self.check_assign_target(target);
            }
            Stmt::TupleAssignment { names, value } => {
                self.check_expr(value);
                for name in names {
                    if self.scopes.declare(name, SymbolKind::Var).is_some() {
                        self.emit(
                            "duplicate-declaration",
                            None,
                            format!("`{name}` is already declared in this scope"),
                        );
                    }
                }
            }
            Stmt::Expression(expr) => self.check_expr(expr),
            Stmt::If {
                condition,
                then_branch,
                else_if_branches,
                else_branch,
            } => {
                self.check_expr(condition);
                self.block(then_branch);
                for (cond, body) in else_if_branches {
                    self.check_expr(cond);
                    self.block(body);
                }
                if let Some(body) = else_branch {
                    self.block(body);
                }
            }
            Stmt::For {
                var_name,
                from,
                to,
                body,
            } => {
                self.check_expr(from);
                self.check_expr(to);
                self.scopes.push();
                self.scopes.declare(var_name, SymbolKind::Var);
                self.loop_body(body);
                self.scopes.pop();
            }
            Stmt::ForIn {
                index_var,
                item_var,
                collection,
                body,
            } => {
                self.check_expr(collection);
                self.scopes.push();
                if let Some(idx) = index_var {
                    self.scopes.declare(idx, SymbolKind::Var);
                }
                self.scopes.declare(item_var, SymbolKind::Var);
                self.loop_body(body);
                self.scopes.pop();
            }
            Stmt::While { condition, body } => {
                self.check_expr(condition);
                self.scopes.push();
                self.loop_body(body);
                self.scopes.pop();
            }
            Stmt::Break => self.check_loop_keyword("break"),
            Stmt::Continue => self.check_loop_keyword("continue"),
            Stmt::FunctionDecl {
                name, params, body, ..
            } => {
                // Declare the name first so the body may reference it.
                self.declare(name, SymbolKind::Function);
                self.function_body(
                    params
                        .iter()
                        .map(|p| (p.name.as_str(), p.default_value.as_ref())),
                    body,
                );
            }
            Stmt::MethodDecl { params, body, .. } => {
                // Methods may share a name (overload by receiver type), so the
                // name is not declared/duplicate-checked; just check the body.
                self.function_body(
                    params
                        .iter()
                        .map(|p| (p.name.as_str(), p.default_value.as_ref())),
                    body,
                );
            }
            Stmt::TypeDecl { name, .. } => self.declare(name, SymbolKind::Type),
            Stmt::EnumDecl { name, .. } => self.declare(name, SymbolKind::Enum),
            Stmt::Import { alias, .. } => self.declare(alias, SymbolKind::Import),
            // `export` re-exports an already-declared item; nothing to resolve.
            Stmt::Export { .. } => {}
        }
    }

    fn check_loop_keyword(&mut self, keyword: &str) {
        if self.loop_depth == 0 {
            self.emit(
                "break-outside-loop",
                None,
                format!("`{keyword}` is only valid inside a loop"),
            );
        }
    }

    /// Validate the left-hand side of a `:=` reassignment.
    fn check_assign_target(&mut self, target: &Expr) {
        match target {
            Expr::Variable(name) => match self.scopes.resolve(name) {
                Some(SymbolKind::Var) => {}
                Some(other) => self.emit(
                    "invalid-assignment",
                    None,
                    format!("cannot assign to `{name}`, it is a {}", other.noun()),
                ),
                None if self.is_builtin(name) => self.emit(
                    "reassign-builtin",
                    None,
                    format!("cannot reassign built-in `{name}`"),
                ),
                None => self.emit(
                    "invalid-assignment",
                    None,
                    format!(
                        "cannot assign to undeclared variable `{name}` (declare it with `=` first)"
                    ),
                ),
            },
            // `obj.field := …` or `arr[i] := …`: validate the object/index.
            other => self.check_expr(other),
        }
    }

    fn check_expr(&mut self, expr: &Expr) {
        match expr {
            Expr::Variable(name) => {
                if self.scopes.resolve(name).is_none() && !self.is_builtin(name) {
                    self.emit(
                        "undeclared-variable",
                        None,
                        format!("undeclared variable `{name}`"),
                    );
                }
            }
            Expr::Call {
                callee, args, loc, ..
            } => {
                if let Expr::Variable(fname) = callee.as_ref() {
                    let pos = loc.position();
                    if is_global_only(fname) && !self.scopes.at_global() {
                        self.emit(
                            "global-scope-required",
                            pos,
                            format!("`{fname}` may only be called in the global scope"),
                        );
                    }
                    if SCRIPT_DECLARATIONS.contains(&fname.as_str()) {
                        self.declarations += 1;
                        if self.declarations > 1 {
                            self.emit(
                                "duplicate-declaration",
                                pos,
                                "a script may only have one indicator/strategy/library declaration",
                            );
                        }
                    }
                    if self.scopes.resolve(fname).is_none() && !self.is_builtin(fname) {
                        self.emit(
                            "unknown-function",
                            pos,
                            format!("unknown function `{fname}`"),
                        );
                    }
                } else {
                    self.check_expr(callee);
                }
                if let Some(signature) = self.builtin_signature(callee) {
                    let name = callee_name(callee);
                    self.check_builtin_args(&name, &signature, args, loc.position());
                }
                for arg in args {
                    match arg {
                        Argument::Positional(e) => self.check_expr(e),
                        Argument::Named { value, .. } => self.check_expr(value),
                    }
                }
            }
            Expr::Binary { left, right, .. } => {
                self.check_expr(left);
                self.check_expr(right);
            }
            Expr::Unary { expr, .. } => self.check_expr(expr),
            Expr::Index { expr, index } => {
                self.check_expr(expr);
                self.check_expr(index);
            }
            // Members are not validated (that is Tier 3 signature checking);
            // only the base object must resolve.
            Expr::MemberAccess { object, .. } => self.check_expr(object),
            Expr::Ternary {
                condition,
                then_expr,
                else_expr,
            } => {
                self.check_expr(condition);
                self.check_expr(then_expr);
                self.check_expr(else_expr);
            }
            Expr::IfExpr {
                condition,
                then_expr,
                else_if_branches,
                else_expr,
            } => {
                self.check_expr(condition);
                self.check_expr(then_expr);
                for (cond, e) in else_if_branches {
                    self.check_expr(cond);
                    self.check_expr(e);
                }
                if let Some(e) = else_expr {
                    self.check_expr(e);
                }
            }
            Expr::Switch { value, cases } => {
                self.check_expr(value);
                for (pattern, result) in cases {
                    self.check_expr(pattern);
                    self.check_expr(result);
                }
            }
            Expr::Array(elements) => {
                for e in elements {
                    self.check_expr(e);
                }
            }
            // A lambda: its own scope with parameters bound.
            Expr::Function { params, body } => {
                self.function_body(
                    params
                        .iter()
                        .map(|p| (p.name.as_str(), p.default_value.as_ref())),
                    body,
                );
            }
            Expr::Literal(_) => {}
        }
    }
}