1use std::collections::{BTreeMap, HashMap, HashSet};
16use std::sync::Arc;
17
18use bynk_syntax::ast::{
19 BaseType, CommonsItem, ConstDecl, Expr, ExprKind, FnName, Ident, TypeBody, TypeDecl, TypeRef,
20 UnaryOp,
21};
22use bynk_syntax::error::CompileError;
23
24use crate::project_model::UnitInfo;
25use crate::symbols::UnitTable;
26
27pub fn is_constant_name(name: &str) -> bool {
30 let mut chars = name.chars();
31 chars.next().is_some_and(|c| c.is_ascii_uppercase())
32 && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
33}
34
35pub fn name_case_error(c: &ConstDecl) -> Option<CompileError> {
37 if is_constant_name(&c.name.name) {
38 return None;
39 }
40 let mut err = CompileError::new(
41 "bynk.resolve.const_name_case",
42 c.name.span,
43 format!(
44 "constant `{}` must be named in upper-camel case",
45 c.name.name
46 ),
47 )
48 .with_note(
49 "a constant's name starts with a capital letter and continues with letters, digits or `_` (`MaxRetries`)",
50 );
51 if let Some(suggested) = upper_camel(&c.name.name) {
52 err = err.with_note(format!("rename it `{suggested}`"));
53 }
54 Some(err)
55}
56
57fn upper_camel(name: &str) -> Option<String> {
60 let mut out = String::new();
61 let mut upper_next = true;
62 for c in name.chars() {
63 if c == '_' || c == '-' {
64 upper_next = true;
65 } else if upper_next {
66 out.extend(c.to_uppercase());
67 upper_next = false;
68 } else {
69 out.push(c);
70 }
71 }
72 is_constant_name(&out).then_some(out)
73}
74
75pub fn placement_error(c: &ConstDecl) -> CompileError {
77 CompileError::new(
78 "bynk.resolve.const_outside_context_or_commons",
79 c.span,
80 "`const` declarations are only allowed inside a context or a commons",
81 )
82 .with_note("an adapter is the host boundary; declare the constant in a commons or a context")
83}
84
85pub fn name_error(
92 c: &ConstDecl,
93 prev_const: Option<&Ident>,
94 prev_embed: Option<&Ident>,
95 prev_asset: Option<&Ident>,
96 prev_fn: Option<&Ident>,
97 prev_type: Option<&Ident>,
98) -> Option<CompileError> {
99 let name = &c.name.name;
100 if let Some(prev) = prev_const {
101 return Some(
102 CompileError::new(
103 "bynk.resolve.duplicate_const",
104 c.name.span,
105 format!("constant `{name}` is already declared"),
106 )
107 .with_label(prev.span, "previously declared here"),
108 );
109 }
110 let (kind, prev) = prev_embed
111 .map(|p| ("an embed", p))
112 .or_else(|| prev_asset.map(|p| ("an asset", p)))
113 .or_else(|| prev_fn.map(|p| ("a function", p)))
114 .or_else(|| prev_type.map(|p| ("a type", p)))?;
115 Some(
116 CompileError::new(
117 "bynk.resolve.name_conflict",
118 c.name.span,
119 format!("constant `{name}` conflicts with {kind} of the same name"),
120 )
121 .with_label(prev.span, "declared here"),
122 )
123}
124
125pub fn builtin_name_error(c: &ConstDecl) -> Option<CompileError> {
130 bynk_syntax::keywords::is_builtin_type_name(&c.name.name).then(|| {
131 CompileError::new(
132 "bynk.resolve.name_conflict",
133 c.name.span,
134 format!(
135 "constant `{}` conflicts with the built-in type of the same name",
136 c.name.name
137 ),
138 )
139 .with_note("choose another name for the constant")
140 })
141}
142
143pub fn variant_conflict_error(
147 c: &ConstDecl,
148 types: &HashMap<String, Arc<TypeDecl>>,
149 unselected: &std::collections::HashSet<String>,
150) -> Option<CompileError> {
151 let mut owners: Vec<&TypeDecl> = types
153 .values()
154 .map(Arc::as_ref)
155 .filter(|t| {
156 !unselected.contains(&t.name.name)
157 && matches!(&t.body, TypeBody::Sum(s)
158 if s.variants.iter().any(|v| v.name.name == c.name.name))
159 })
160 .collect();
161 owners.sort_by(|a, b| a.name.name.cmp(&b.name.name));
162 let owner = match owners.first() {
165 Some(t) => t.name.name.as_str(),
166 None if bynk_syntax::ast::http_variant(&c.name.name).is_some() => "HttpResult",
167 None => return None,
168 };
169 Some(
170 CompileError::new(
171 "bynk.resolve.name_conflict",
172 c.name.span,
173 format!(
174 "constant `{}` conflicts with a variant of `{owner}`",
175 c.name.name
176 ),
177 )
178 .with_note("a bare name would read as either; choose another name for the constant"),
179 )
180}
181
182pub fn static_error(
187 c: &ConstDecl,
188 consts: &HashMap<String, ConstDecl>,
189 types: &HashMap<String, Arc<TypeDecl>>,
190) -> Option<CompileError> {
191 let (span, what) = first_non_static(&c.init, consts, types)?;
192 Some(
193 CompileError::new(
194 "bynk.resolve.bad_const_initialiser",
195 span,
196 format!(
197 "the initialiser of constant `{}` must be a static value, but {what} is not",
198 c.name.name
199 ),
200 )
201 .with_note(
202 "a constant's initialiser is a literal (a string without interpolation, or a negative \
203 number), a `Duration` literal, a record, list or sum-variant construction over static \
204 values, `Some`/`None`/`Ok`/`Err`, `T.unsafe(lit)` for an opaque type, \
205 `List.empty()`/`Map.empty()`/`Set.empty()`, or another constant",
206 ),
207 )
208}
209
210fn sum_has_variant(types: &HashMap<String, Arc<TypeDecl>>, ty: &str, variant: &str) -> bool {
211 types.get(ty).is_some_and(|t| {
212 matches!(&t.body, TypeBody::Sum(s) if s.variants.iter().any(|v| v.name.name == variant))
213 })
214}
215
216fn is_any_variant(types: &HashMap<String, Arc<TypeDecl>>, variant: &str) -> bool {
217 types.values().any(|t| {
218 matches!(&t.body, TypeBody::Sum(s) if s.variants.iter().any(|v| v.name.name == variant))
219 })
220}
221
222fn is_literal(e: &Expr) -> bool {
223 match &e.kind {
224 ExprKind::IntLit { .. }
225 | ExprKind::FloatLit { .. }
226 | ExprKind::DecimalLit { .. }
227 | ExprKind::StrLit(_)
228 | ExprKind::BoolLit(_)
229 | ExprKind::UnitLit => true,
230 ExprKind::UnaryOp(UnaryOp::Neg, inner) => {
231 matches!(
232 inner.kind,
233 ExprKind::IntLit { .. } | ExprKind::FloatLit { .. } | ExprKind::DecimalLit { .. }
234 )
235 }
236 ExprKind::Paren(inner) => is_literal(inner),
237 _ => false,
238 }
239}
240
241fn first_non_static(
243 e: &Expr,
244 consts: &HashMap<String, ConstDecl>,
245 types: &HashMap<String, Arc<TypeDecl>>,
246) -> Option<(bynk_syntax::span::Span, &'static str)> {
247 let all = |items: std::slice::Iter<'_, Expr>| {
248 items
249 .map(|x| first_non_static(x, consts, types))
250 .find(Option::is_some)
251 .flatten()
252 };
253 match &e.kind {
254 ExprKind::IntLit { .. }
255 | ExprKind::FloatLit { .. }
256 | ExprKind::DecimalLit { .. }
257 | ExprKind::DurationLit { .. }
258 | ExprKind::StrLit(_)
259 | ExprKind::BoolLit(_)
260 | ExprKind::UnitLit
261 | ExprKind::None => None,
262 ExprKind::UnaryOp(UnaryOp::Neg, inner)
263 if matches!(
264 inner.kind,
265 ExprKind::IntLit { .. } | ExprKind::FloatLit { .. } | ExprKind::DecimalLit { .. }
266 ) =>
267 {
268 None
269 }
270 ExprKind::Paren(inner)
271 | ExprKind::Some(inner)
272 | ExprKind::Ok(inner)
273 | ExprKind::Err(inner) => first_non_static(inner, consts, types),
274 ExprKind::ListLit(items, ..) => all(items.iter()),
275 ExprKind::RecordConstruction { fields, .. } => {
276 for f in fields {
277 match &f.value {
278 Some(v) => {
279 if let Some(bad) = first_non_static(v, consts, types) {
280 return Some(bad);
281 }
282 }
283 None => return Some((f.span, "a shorthand field (a reference to a binding)")),
284 }
285 }
286 None
287 }
288 ExprKind::Ident(id) if consts.contains_key(&id.name) || is_any_variant(types, &id.name) => {
290 None
291 }
292 ExprKind::Call { name, args, .. } if is_any_variant(types, &name.name) => all(args.iter()),
294 ExprKind::FieldAccess { receiver, field } if matches!(&receiver.kind, ExprKind::Ident(t) if sum_has_variant(types, &t.name, &field.name)) => {
296 None
297 }
298 ExprKind::MethodCall {
299 receiver,
300 method,
301 args,
302 ..
303 } => {
304 let ExprKind::Ident(t) = &receiver.kind else {
305 return Some((e.span, "a method call"));
306 };
307 if sum_has_variant(types, &t.name, &method.name) {
308 all(args.iter())
310 } else if method.name == "empty"
311 && args.is_empty()
312 && matches!(t.name.as_str(), "List" | "Map" | "Set")
313 {
314 None
315 } else if method.name == "unsafe"
316 && types
317 .get(&t.name)
318 .is_some_and(|d| matches!(d.body, TypeBody::Opaque { .. }))
319 {
320 match args.as_slice() {
321 [lit] if is_literal(lit) => None,
322 _ => Some((e.span, "`.unsafe` of anything but a literal")),
323 }
324 } else {
325 Some((e.span, "a function or method call"))
326 }
327 }
328 ExprKind::Ident(_) => Some((e.span, "a reference to something other than a constant")),
329 ExprKind::Call { .. } => Some((e.span, "a function call")),
330 ExprKind::InterpStr(_) => Some((e.span, "an interpolated string")),
331 ExprKind::BinOp(..) | ExprKind::UnaryOp(..) => Some((e.span, "an operator expression")),
332 ExprKind::RecordSpread { .. } => Some((e.span, "a record spread")),
333 ExprKind::FieldAccess { .. } => Some((e.span, "a field access")),
334 ExprKind::Lambda(_) => Some((e.span, "a lambda")),
335 ExprKind::If { .. } | ExprKind::Match { .. } | ExprKind::Block(_) => {
336 Some((e.span, "a control-flow expression"))
337 }
338 _ => Some((e.span, "this expression")),
339 }
340}
341
342pub fn referenced_consts<'a>(
344 e: &'a Expr,
345 consts: &HashMap<String, ConstDecl>,
346 out: &mut Vec<&'a Ident>,
347) {
348 if let ExprKind::Ident(id) = &e.kind
349 && consts.contains_key(&id.name)
350 {
351 out.push(id);
352 }
353 for child in bynk_syntax::ast::expr_children(e) {
354 referenced_consts(child, consts, out);
355 }
356}
357
358pub fn cycle_errors(
362 local: &[&ConstDecl],
363 consts: &HashMap<String, ConstDecl>,
364) -> Vec<CompileError> {
365 let order: HashMap<&str, usize> = local
366 .iter()
367 .enumerate()
368 .map(|(i, c)| (c.name.name.as_str(), i))
369 .collect();
370 let mut errors = Vec::new();
371 for (i, c) in local.iter().enumerate() {
372 let Some(path) = find_cycle(&c.name.name, consts) else {
373 continue;
374 };
375 if path
377 .iter()
378 .any(|n| order.get(n.as_str()).is_some_and(|&j| j < i))
379 {
380 continue;
381 }
382 let shown = path
383 .iter()
384 .chain(std::iter::once(&c.name.name))
385 .map(|n| format!("`{n}`"))
386 .collect::<Vec<_>>()
387 .join(" → ");
388 errors.push(
389 CompileError::new(
390 "bynk.resolve.const_cycle",
391 c.name.span,
392 format!("constant `{}` refers to itself: {shown}", c.name.name),
393 )
394 .with_note(
395 "a constant's value cannot depend on itself; break the cycle with a literal",
396 ),
397 );
398 }
399 errors
400}
401
402fn find_cycle(start: &str, consts: &HashMap<String, ConstDecl>) -> Option<Vec<String>> {
405 fn dfs(
406 node: &str,
407 start: &str,
408 consts: &HashMap<String, ConstDecl>,
409 path: &mut Vec<String>,
410 visited: &mut HashSet<String>,
411 ) -> bool {
412 let Some(decl) = consts.get(node) else {
413 return false;
414 };
415 path.push(node.to_string());
416 let mut refs = Vec::new();
417 referenced_consts(&decl.init, consts, &mut refs);
418 for r in refs {
419 if r.name == start {
420 return true;
421 }
422 if visited.insert(r.name.clone()) && dfs(&r.name, start, consts, path, visited) {
423 return true;
424 }
425 }
426 path.pop();
427 false
428 }
429 let mut path = Vec::new();
430 let mut visited = HashSet::new();
431 dfs(start, start, consts, &mut path, &mut visited).then_some(path)
432}
433
434pub fn single_file_const_errors(items: &[CommonsItem]) -> Vec<CompileError> {
441 let mut fns: HashMap<&str, &Ident> = HashMap::new();
442 let mut types: HashMap<&str, &Ident> = HashMap::new();
443 let mut assets: HashMap<&str, &Ident> = HashMap::new();
444 let mut embeds: HashMap<&str, &Ident> = HashMap::new();
445 for item in items {
446 match item {
447 CommonsItem::Fn(f) => {
448 if let FnName::Free(id) = &f.name {
449 fns.entry(id.name.as_str()).or_insert(id);
450 }
451 }
452 CommonsItem::Type(t) => {
453 types.entry(t.name.name.as_str()).or_insert(&t.name);
454 }
455 CommonsItem::Event(ev) => {
456 types.entry(ev.name.name.as_str()).or_insert(&ev.name);
457 }
458 CommonsItem::Asset(a) => {
459 assets.entry(a.name.name.as_str()).or_insert(&a.name);
460 }
461 CommonsItem::Embed(e) => {
462 embeds.entry(e.name.name.as_str()).or_insert(&e.name);
463 }
464 _ => {}
465 }
466 }
467 let mut consts: HashMap<&str, &Ident> = HashMap::new();
468 let mut errors = Vec::new();
469 for item in items {
470 let CommonsItem::Const(c) = item else {
471 continue;
472 };
473 let key = c.name.name.as_str();
474 match name_error(
475 c,
476 consts.get(key).copied(),
477 embeds.get(key).copied(),
478 assets.get(key).copied(),
479 fns.get(key).copied(),
480 types.get(key).copied(),
481 )
482 .or_else(|| builtin_name_error(c))
483 {
484 Some(err) => errors.push(err),
485 None => {
486 consts.insert(key, &c.name);
487 }
488 }
489 }
490 errors
491}
492
493pub fn compose_unit_consts(
500 name: &str,
501 unit_info: &BTreeMap<String, UnitInfo>,
502) -> HashMap<String, ConstDecl> {
503 let Some(info) = unit_info.get(name) else {
504 return HashMap::new();
505 };
506 visible_consts(&info.table, &info.uses, |u| {
507 unit_info.get(u).map(|i| &i.table)
508 })
509 .into_iter()
510 .map(|(n, c)| {
511 let mut decl = c.decl.clone();
512 if let Some(owner) = c.owner
518 && matches!(decl.init.kind, ExprKind::Ident(_))
519 && let Some(text) = alias_literal(
520 |u| unit_info.get(u).map(|i| (&i.table, i.uses.as_slice())),
521 owner,
522 &decl,
523 )
524 {
525 decl.init.kind = ExprKind::StrLit(text);
526 }
527 (n, decl)
528 })
529 .collect()
530}
531
532pub fn is_literal_of(kind: &ExprKind, base: BaseType) -> bool {
536 let numeric = |k: &ExprKind| match base {
537 BaseType::Int => matches!(k, ExprKind::IntLit { .. }),
538 BaseType::Float => matches!(k, ExprKind::FloatLit { .. }),
539 BaseType::Decimal => matches!(k, ExprKind::DecimalLit { .. }),
540 _ => false,
541 };
542 match kind {
543 ExprKind::StrLit(_) => base == BaseType::String,
544 ExprKind::BoolLit(_) => base == BaseType::Bool,
545 ExprKind::DurationLit { .. } => base == BaseType::Duration,
546 ExprKind::UnaryOp(UnaryOp::Neg, inner) => numeric(&inner.kind),
548 k => numeric(k),
549 }
550}
551
552pub fn chain_literal<'a>(
561 start: &'a ConstDecl,
562 base: BaseType,
563 limit: usize,
564 mut next: impl FnMut(&str) -> Option<&'a ConstDecl>,
565) -> Option<&'a Expr> {
566 let mut current = start;
567 for _ in 0..=limit {
568 if !matches!(current.ty, TypeRef::Base(b, _) if b == base) {
569 return None;
570 }
571 match ¤t.init.kind {
572 k if is_literal_of(k, base) => return Some(¤t.init),
573 ExprKind::Ident(n) => current = next(n.name.as_str())?,
574 _ => return None,
575 }
576 }
577 None
578}
579
580pub fn alias_literal<'a>(
583 unit: impl Fn(&str) -> Option<(&'a UnitTable, &'a [String])>,
584 owner: &str,
585 start: &'a ConstDecl,
586) -> Option<String> {
587 let mut at = owner;
588 let lit = chain_literal(start, BaseType::String, 64, |name| {
589 let (table, uses) = unit(at)?;
590 let vis = visible_consts(table, uses, |u| unit(u).map(|(t, _)| t));
591 let found = vis.get(name)?;
592 if let Some(o) = found.owner {
593 at = o;
594 }
595 Some(found.decl)
596 })?;
597 match &lit.kind {
598 ExprKind::StrLit(s) => Some(s.clone()),
599 _ => None,
600 }
601}
602
603pub struct ResolvedConst<'a> {
606 pub decl: &'a ConstDecl,
608 pub literal: &'a Expr,
610 pub owner: Option<&'a str>,
612}
613
614pub fn resolve_const_literal<'a>(
618 unit: impl Fn(&str) -> Option<(&'a UnitTable, &'a [String])>,
619 at: &'a str,
620 name: &str,
621 base: BaseType,
622) -> Option<ResolvedConst<'a>> {
623 let (table, uses) = unit(at)?;
624 let vis = visible_consts(table, uses, |u| unit(u).map(|(t, _)| t));
625 let first = vis.get(name)?;
626 let (decl, owner) = (first.decl, first.owner);
627 let mut scope = owner.unwrap_or(at);
628 let literal = chain_literal(decl, base, 64, |n| {
629 let (table, uses) = unit(scope)?;
630 let vis = visible_consts(table, uses, |u| unit(u).map(|(t, _)| t));
631 let found = vis.get(n)?;
632 if let Some(o) = found.owner {
633 scope = o;
634 }
635 Some(found.decl)
636 })?;
637 Some(ResolvedConst {
638 decl,
639 literal,
640 owner,
641 })
642}
643
644pub struct VisibleConst<'a> {
646 pub decl: &'a ConstDecl,
647 pub owner: Option<&'a str>,
649}
650
651pub fn visible_consts<'a>(
658 table: &'a UnitTable,
659 uses: &'a [String],
660 used_table: impl Fn(&str) -> Option<&'a UnitTable>,
661) -> HashMap<String, VisibleConst<'a>> {
662 let mut combined: HashMap<String, VisibleConst<'a>> = table
663 .consts
664 .iter()
665 .map(|(n, decl)| (n.clone(), VisibleConst { decl, owner: None }))
666 .collect();
667 for used in uses {
668 let Some(used_table) = used_table(used) else {
669 continue;
670 };
671 for (const_name, decl) in used_table
673 .consts
674 .iter()
675 .filter(|(_, d)| d.private.is_none())
676 {
677 if crate::symbols::local_value_kind(table, const_name).is_some() {
678 continue;
679 }
680 combined.entry(const_name.clone()).or_insert(VisibleConst {
681 decl,
682 owner: Some(used.as_str()),
683 });
684 }
685 }
686 combined
687}
688
689#[cfg(test)]
690mod tests {
691 use super::*;
692
693 #[test]
694 fn constant_names_are_upper_camel() {
695 assert!(is_constant_name("MaxRetries"));
696 assert!(is_constant_name("A"));
697 assert!(is_constant_name("HTTP_2"));
698 assert!(!is_constant_name("maxRetries"));
699 assert!(!is_constant_name("_Max"));
700 assert!(!is_constant_name(""));
701 assert_eq!(upper_camel("max_retries").as_deref(), Some("MaxRetries"));
702 assert_eq!(upper_camel("timeout").as_deref(), Some("Timeout"));
703 }
704}