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 }
177 changed
178}
179
180fn rewrite_type(decl: &mut TypeDecl, scope: &Scope, refs: &mut RefSink) -> bool {
181 let mut changed = false;
182 match &mut decl.body {
183 TypeBody::Refined {
184 base, refinement, ..
185 }
186 | TypeBody::Opaque {
187 base, refinement, ..
188 } => changed |= rewrite_example(refinement, *base, scope, refs),
189 TypeBody::Record(rec) => {
190 for field in &mut rec.fields {
191 changed |= rewrite_annotations(&mut field.annotations, FIELD_RULES, scope, refs);
192 if let Some(base) = field_base(field, scope) {
193 changed |= rewrite_example(&mut field.refinement, base, scope, refs);
194 }
195 }
196 }
197 _ => {}
198 }
199 changed
200}
201
202fn rewrite_items(items: &mut [CommonsItem], scope: &Scope, refs: &mut RefSink) -> bool {
204 let mut changed = false;
205 for item in items {
206 match item {
207 CommonsItem::Type(decl) => changed |= rewrite_type(decl, scope, refs),
208 CommonsItem::Event(ev) => {
209 changed |= rewrite_annotations(&mut ev.annotations, EVENT_RULES, scope, refs);
210 }
211 CommonsItem::Service(svc) => {
212 changed |= rewrite_handlers(&mut svc.handlers, scope, refs)
213 }
214 CommonsItem::Agent(agent) => {
215 for f in &mut agent.store_fields {
216 changed |= rewrite_annotations(&mut f.annotations, STORE_RULES, scope, refs);
217 }
218 changed |= rewrite_handlers(&mut agent.handlers, scope, refs);
219 }
220 _ => {}
221 }
222 }
223 changed
224}
225
226pub fn resolve_annotation_consts(
233 groups: &BTreeMap<String, Vec<usize>>,
234 kinds: &BTreeMap<String, UnitKind>,
235 parsed: &mut [ParsedFile],
236 unit_tables: &mut HashMap<String, UnitTable>,
237 unit_uses: &HashMap<String, Vec<String>>,
238 refs: &mut RefSink,
239) {
240 let mut changed_units = Vec::new();
241 for (name, indices) in groups {
242 if !matches!(kinds.get(name), Some(UnitKind::Context | UnitKind::Commons)) {
243 continue;
244 }
245 let mut unit_changed = false;
246 for &i in indices {
247 let pf = &mut parsed[i];
248 refs.enter_file(&pf.identity_path(), name, pf.is_synthetic());
249 let items = match pf.unit_mut() {
250 SourceUnit::Commons(c) => &mut c.items,
251 SourceUnit::Context(c) => &mut c.items,
252 _ => continue,
253 };
254 let scope = Scope {
255 unit: name,
256 tables: &*unit_tables,
257 uses: unit_uses,
258 file_consts: items
259 .iter()
260 .filter_map(|it| match it {
261 CommonsItem::Const(c) => Some(c.name.name.clone()),
262 _ => None,
263 })
264 .collect(),
265 };
266 unit_changed |= rewrite_items(items, &scope, refs);
267 }
268 if unit_changed {
269 changed_units.push(name.clone());
270 }
271 }
272 for name in changed_units {
273 let kind = kinds[&name];
274 let mut discarded = Vec::new();
275 let table = build_unit_table(&name, kind, &groups[&name], parsed, &mut discarded);
276 unit_tables.insert(name, table);
277 }
278}
279
280pub fn with_const_origin(err: CompileError, arg: &bynk_syntax::ast::AnnotationArg) -> CompileError {
283 let Some(c) = &arg.from_const else {
284 return err;
285 };
286 let err = match c.decl_span {
287 Some(span) => err.with_label(span, format!("`{}` is declared here", c.name.name)),
288 None => err,
289 };
290 err.with_note(format!("the value comes from `const {}`", c.name.name))
291}
292
293pub fn resolve_single_file(commons: &mut Commons) {
298 use std::path::PathBuf;
299 let name = commons.name.joined();
300 let file = ParsedFile::synthetic(
301 PathBuf::from("single.bynk"),
302 PathBuf::from("single.bynk"),
303 String::new(),
304 SourceUnit::Commons(commons.clone()),
305 UnitKind::Commons,
306 );
307 let mut parsed = [file];
308 let groups = BTreeMap::from([(name.clone(), vec![0])]);
309 let kinds = BTreeMap::from([(name.clone(), UnitKind::Commons)]);
310 let mut discarded = Vec::new();
311 let table = build_unit_table(&name, UnitKind::Commons, &[0], &parsed, &mut discarded);
312 let mut tables = HashMap::from([(name, table)]);
313 resolve_annotation_consts(
314 &groups,
315 &kinds,
316 &mut parsed,
317 &mut tables,
318 &HashMap::new(),
319 &mut RefSink::new(),
320 );
321 if let SourceUnit::Commons(rewritten) = parsed[0].unit() {
322 *commons = rewritten.clone();
323 }
324}