Skip to main content

bynk_check/
annotation_consts.rs

1//! #3445 (ADR 0678 C, amended): a constant in a literal-only annotation
2//! argument.
3//!
4//! A bare reference to a constant counts as the literal it is bound to wherever
5//! an annotation argument takes a literal, as ADR 0762 already does for SQL
6//! text. The resolution is a lookup, not an evaluation: a constant's initialiser
7//! is a closed static set ([`crate::consts::static_error`]), so a reference
8//! resolves, by following constant-to-constant references, to literal text in
9//! the source.
10//!
11//! The pass runs once, over the parsed declarations, ahead of every validator
12//! and reader of annotation arguments (the checker, hover, the emitters, the
13//! OpenAPI readers of `wire_name()`), and replaces the argument's value with the
14//! resolved literal. Those consumers are syntactic and hold no constant table;
15//! resolving once upstream means none of them can miss it. The replaced value
16//! keeps the reference's span, and [`bynk_syntax::ast::AnnotationArg::from_const`] names the
17//! constant, so a diagnostic points at the reference and the IDE can find the
18//! use.
19//!
20//! An argument that does not resolve (not a constant, the wrong declared type,
21//! a refined constant, an initialiser that is not a plain literal, a name a
22//! local shadows) is left as written, so the annotation's existing "bad
23//! argument" diagnostic fires on it unchanged. No new diagnostic code.
24
25use std::collections::{BTreeMap, HashMap, HashSet};
26
27use bynk_syntax::ast::{
28    Annotation, BaseType, Commons, CommonsItem, ConstRef, ExprKind, Handler, RecordField,
29    Refinement, SourceUnit, TypeBody, TypeDecl, TypeRef,
30};
31use bynk_syntax::error::CompileError;
32
33use crate::index::{RefSink, SymbolKind};
34use crate::symbols::{UnitTable, build_unit_table};
35use bynk_project::{ParsedFile, UnitKind};
36
37/// One literal-only annotation argument: the annotation, its argument's label
38/// (`None` for the positional one), and the base type its constant must be.
39#[derive(Clone, Copy)]
40struct ArgRule {
41    annotation: &'static str,
42    label: Option<&'static str>,
43    base: BaseType,
44}
45
46const fn rule(annotation: &'static str, label: Option<&'static str>, base: BaseType) -> ArgRule {
47    ArgRule {
48        annotation,
49        label,
50        base,
51    }
52}
53
54/// The record-field annotations: `@name("…")` (ADR 0812 C).
55const FIELD_RULES: &[ArgRule] = &[rule("name", None, BaseType::String)];
56
57/// A `store` field's annotations: `@ttl(d)` and `@retain(d)`.
58const STORE_RULES: &[ArgRule] = &[
59    rule("ttl", None, BaseType::Duration),
60    rule("retain", None, BaseType::Duration),
61];
62
63/// An event's annotation: `@schema(n)`.
64const EVENT_RULES: &[ArgRule] = &[rule("schema", None, BaseType::Int)];
65
66/// A handler's annotations: `@cache(maxAge:, immutable:)`, `@limit(…)` and
67/// `@raw(contentType:)`. The keyword arguments (`@cache(scope: public)`,
68/// `@json(options: plain)`) and `@indexed(by:)` name words or fields, not
69/// values, so they have no rule.
70const HANDLER_RULES: &[ArgRule] = &[
71    rule("cache", Some("maxAge"), BaseType::Duration),
72    rule("cache", Some("immutable"), BaseType::Bool),
73    rule("limit", Some("maxBody"), BaseType::Int),
74    rule("limit", Some("maxFile"), BaseType::Int),
75    rule("limit", Some("maxParts"), BaseType::Int),
76    rule("raw", Some("contentType"), BaseType::String),
77];
78
79/// What the pass reads of the unit it is resolving in.
80struct Scope<'a> {
81    unit: &'a str,
82    tables: &'a HashMap<String, UnitTable>,
83    uses: &'a HashMap<String, Vec<String>>,
84    /// The constants declared in the file being rewritten, so a related span at
85    /// one is only offered where it indexes the same source.
86    file_consts: HashSet<String>,
87}
88
89impl<'a> Scope<'a> {
90    fn lookup(&self, u: &str) -> Option<(&'a UnitTable, &'a [String])> {
91        let table = self.tables.get(u)?;
92        let uses = self.uses.get(u).map(Vec::as_slice).unwrap_or(&[]);
93        Some((table, uses))
94    }
95}
96
97/// Rewrite the arguments of `annotations` named by `rules`. Returns whether any
98/// argument changed.
99fn rewrite_annotations(
100    annotations: &mut [Annotation],
101    rules: &[ArgRule],
102    scope: &Scope,
103    refs: &mut RefSink,
104) -> bool {
105    let mut changed = false;
106    for ann in annotations {
107        for arg in &mut ann.args {
108            let ExprKind::Ident(id) = &arg.value.kind else {
109                continue;
110            };
111            let Some(rule) = rules.iter().find(|r| {
112                r.annotation == ann.name.name
113                    && r.label == arg.label.as_ref().map(|l| l.name.as_str())
114            }) else {
115                continue;
116            };
117            let Some(found) = crate::consts::resolve_const_literal(
118                |u| scope.lookup(u),
119                scope.unit,
120                &id.name,
121                rule.base,
122            ) else {
123                continue;
124            };
125            let same_file = found.owner.is_none() && scope.file_consts.contains(&id.name);
126            arg.from_const = Some(ConstRef {
127                name: id.clone(),
128                decl_span: same_file.then_some(found.decl.name.span),
129            });
130            // The reference is a use of the constant: go-to-definition, hover,
131            // find-references and rename see it as one (#3445 H).
132            refs.record(id.span, SymbolKind::Const, &id.name);
133            arg.value.kind = found.literal.kind.clone();
134            changed = true;
135        }
136    }
137    changed
138}
139
140/// `@example(lit)` after a refinement: one literal of the refinement's base.
141fn rewrite_example(
142    refinement: &mut Option<Refinement>,
143    base: BaseType,
144    scope: &Scope,
145    refs: &mut RefSink,
146) -> bool {
147    let Some(r) = refinement else {
148        return false;
149    };
150    rewrite_annotations(
151        &mut r.annotations,
152        &[rule("example", None, base)],
153        scope,
154        refs,
155    )
156}
157
158/// The base a record field's inline refinement applies to (as
159/// `checker::refinements` reads it): the field's own base type, or that of a
160/// refined type it names in this unit.
161fn field_base(field: &RecordField, scope: &Scope) -> Option<BaseType> {
162    match &field.type_ref {
163        TypeRef::Base(b, _) => Some(*b),
164        TypeRef::Named(id) => match &scope.tables.get(scope.unit)?.types.get(&id.name)?.body {
165            TypeBody::Refined { base, .. } => Some(*base),
166            _ => None,
167        },
168        _ => None,
169    }
170}
171
172fn rewrite_handlers(handlers: &mut [Handler], scope: &Scope, refs: &mut RefSink) -> bool {
173    let mut changed = false;
174    for h in handlers {
175        changed |= rewrite_annotations(&mut h.annotations, HANDLER_RULES, scope, refs);
176        changed |= rewrite_schedule(h, scope, refs);
177    }
178    changed
179}
180
181/// #3875: `on schedule(Nightly)` — resolve the named constant to the literal it
182/// denotes and fill the handler's schedule expression with it, so the checker,
183/// the trigger table, dispatch and every reader see the literal text. A constant
184/// declared `String` or exactly `CronSchedule` resolves; anything else is left
185/// with its refusal recorded for `bynk.cron.invalid_schedule` (or the unknown
186/// name) to report. The literal is checked against `Cron` afterwards, where a
187/// literal schedule is.
188fn rewrite_schedule(h: &mut Handler, scope: &Scope, refs: &mut RefSink) -> bool {
189    use bynk_syntax::ast::{HandlerKind, ScheduleRefusal};
190    let Some(sc) = &mut h.schedule_const else {
191        return false;
192    };
193    let name = sc.name.name.clone();
194    match crate::consts::resolve_schedule_literal(|u| scope.lookup(u), scope.unit, &name) {
195        Ok(found) => {
196            let ExprKind::StrLit(text) = &found.literal.kind else {
197                return false;
198            };
199            let same_file = found.owner.is_none() && scope.file_consts.contains(&name);
200            sc.decl_span = same_file.then_some(found.decl.name.span);
201            refs.record(sc.name.span, SymbolKind::Const, &name);
202            h.kind = HandlerKind::Cron { expr: text.clone() };
203            true
204        }
205        Err(declared) => {
206            sc.refusal = Some(match declared {
207                None => ScheduleRefusal::Unknown,
208                Some(d) => {
209                    ScheduleRefusal::Declared(crate::context_checks::ts_type_ref_display(&d.ty))
210                }
211            });
212            // Changed: the unit's table is rebuilt, so the refusal reaches the
213            // checker with the handler.
214            true
215        }
216    }
217}
218
219fn rewrite_type(decl: &mut TypeDecl, scope: &Scope, refs: &mut RefSink) -> bool {
220    let mut changed = false;
221    match &mut decl.body {
222        TypeBody::Refined {
223            base, refinement, ..
224        }
225        | TypeBody::Opaque {
226            base, refinement, ..
227        } => changed |= rewrite_example(refinement, *base, scope, refs),
228        TypeBody::Record(rec) => {
229            for field in &mut rec.fields {
230                changed |= rewrite_annotations(&mut field.annotations, FIELD_RULES, scope, refs);
231                if let Some(base) = field_base(field, scope) {
232                    changed |= rewrite_example(&mut field.refinement, base, scope, refs);
233                }
234            }
235        }
236        _ => {}
237    }
238    changed
239}
240
241/// Rewrite every literal-only annotation argument of `items`.
242fn rewrite_items(items: &mut [CommonsItem], scope: &Scope, refs: &mut RefSink) -> bool {
243    let mut changed = false;
244    for item in items {
245        match item {
246            CommonsItem::Type(decl) => changed |= rewrite_type(decl, scope, refs),
247            CommonsItem::Event(ev) => {
248                changed |= rewrite_annotations(&mut ev.annotations, EVENT_RULES, scope, refs);
249            }
250            CommonsItem::Service(svc) => {
251                changed |= rewrite_handlers(&mut svc.handlers, scope, refs)
252            }
253            CommonsItem::Agent(agent) => {
254                for f in &mut agent.store_fields {
255                    changed |= rewrite_annotations(&mut f.annotations, STORE_RULES, scope, refs);
256                }
257                changed |= rewrite_handlers(&mut agent.handlers, scope, refs);
258            }
259            _ => {}
260        }
261    }
262    changed
263}
264
265/// Phase 5c: resolve a constant named by a literal-only annotation argument to
266/// the literal it denotes, in every production unit. Run after `uses` resolution
267/// (a used commons' public constants are in scope) and before anything reads an
268/// annotation argument. A unit whose declarations changed has its symbol table
269/// rebuilt from the rewritten files, so the table holds the resolved literals
270/// too; the rebuild's own diagnostics were already reported by the first build.
271pub fn resolve_annotation_consts(
272    groups: &BTreeMap<String, Vec<usize>>,
273    kinds: &BTreeMap<String, UnitKind>,
274    parsed: &mut [ParsedFile],
275    unit_tables: &mut HashMap<String, UnitTable>,
276    unit_uses: &HashMap<String, Vec<String>>,
277    refs: &mut RefSink,
278) {
279    let mut changed_units = Vec::new();
280    for (name, indices) in groups {
281        if !matches!(kinds.get(name), Some(UnitKind::Context | UnitKind::Commons)) {
282            continue;
283        }
284        let mut unit_changed = false;
285        for &i in indices {
286            let pf = &mut parsed[i];
287            refs.enter_file(&pf.identity_path(), name, pf.is_synthetic());
288            let items = match pf.unit_mut() {
289                SourceUnit::Commons(c) => &mut c.items,
290                SourceUnit::Context(c) => &mut c.items,
291                _ => continue,
292            };
293            let scope = Scope {
294                unit: name,
295                tables: &*unit_tables,
296                uses: unit_uses,
297                file_consts: items
298                    .iter()
299                    .filter_map(|it| match it {
300                        CommonsItem::Const(c) => Some(c.name.name.clone()),
301                        _ => None,
302                    })
303                    .collect(),
304            };
305            unit_changed |= rewrite_items(items, &scope, refs);
306        }
307        if unit_changed {
308            changed_units.push(name.clone());
309        }
310    }
311    for name in changed_units {
312        let kind = kinds[&name];
313        let mut discarded = Vec::new();
314        let table = build_unit_table(&name, kind, &groups[&name], parsed, &mut discarded);
315        unit_tables.insert(name, table);
316    }
317}
318
319/// Attach the constant's declaration to `err` as a related span, when the
320/// argument was a reference to a constant in the same file.
321pub fn with_const_origin(err: CompileError, arg: &bynk_syntax::ast::AnnotationArg) -> CompileError {
322    let Some(c) = &arg.from_const else {
323        return err;
324    };
325    let err = match c.decl_span {
326        Some(span) => err.with_label(span, format!("`{}` is declared here", c.name.name)),
327        None => err,
328    };
329    err.with_note(format!("the value comes from `const {}`", c.name.name))
330}
331
332/// The single-file form of [`resolve_annotation_consts`], for a commons checked
333/// on its own (`bynk check file.bynk`, the playground, the editor's single-file
334/// mode): no `uses`, so only the file's own constants are in scope. It runs the
335/// same pass over a one-unit project, so the rules cannot differ.
336pub fn resolve_single_file(commons: &mut Commons) {
337    use std::path::PathBuf;
338    let name = commons.name.joined();
339    let file = ParsedFile::synthetic(
340        PathBuf::from("single.bynk"),
341        PathBuf::from("single.bynk"),
342        String::new(),
343        SourceUnit::Commons(commons.clone()),
344        UnitKind::Commons,
345    );
346    let mut parsed = [file];
347    let groups = BTreeMap::from([(name.clone(), vec![0])]);
348    let kinds = BTreeMap::from([(name.clone(), UnitKind::Commons)]);
349    let mut discarded = Vec::new();
350    let table = build_unit_table(&name, UnitKind::Commons, &[0], &parsed, &mut discarded);
351    let mut tables = HashMap::from([(name, table)]);
352    resolve_annotation_consts(
353        &groups,
354        &kinds,
355        &mut parsed,
356        &mut tables,
357        &HashMap::new(),
358        &mut RefSink::new(),
359    );
360    if let SourceUnit::Commons(rewritten) = parsed[0].unit() {
361        *commons = rewritten.clone();
362    }
363}