1use 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#[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
54const FIELD_RULES: &[ArgRule] = &[rule("name", None, BaseType::String)];
56
57const STORE_RULES: &[ArgRule] = &[
59 rule("ttl", None, BaseType::Duration),
60 rule("retain", None, BaseType::Duration),
61];
62
63const EVENT_RULES: &[ArgRule] = &[rule("schema", None, BaseType::Int)];
65
66const 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
79struct Scope<'a> {
81 unit: &'a str,
82 tables: &'a HashMap<String, UnitTable>,
83 uses: &'a HashMap<String, Vec<String>>,
84 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
97fn 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 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
140fn 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
158fn 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
181fn 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 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
241fn 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
265pub 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
319pub 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
332pub 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}