1use std::borrow::Cow;
41use std::collections::{BTreeMap, BTreeSet, HashMap};
42use std::path::{Path, PathBuf};
43use std::sync::{Arc, LazyLock};
44
45use bynk_check::checker::{NamedKind, Ty, TyId, Types};
46use bynk_check::kernel_methods;
47use bynk_check::locals::LocalBinding;
48use bynk_check::store_ops;
49use bynk_syntax::ast::{CommonsItem, ExportKind, FnName, SourceUnit, TypeBody, TypeRef, UsesDecl};
50use bynk_syntax::{keywords, lexer, parser};
51
52use crate::symbols::type_ref_str;
53
54#[derive(Clone, Copy, PartialEq, Eq)]
56pub enum CompletionKind {
57 Unit,
58 Capability,
59 Type,
60 Keyword,
61 Snippet,
62 Variant,
64 Member,
67 Field,
69 Constructor,
71 Function,
74 Constant,
77 Constraint,
80}
81
82pub struct Completion {
83 pub label: String,
84 pub kind: CompletionKind,
85 pub detail: Option<String>,
86 pub insert_text: Option<String>,
89 pub documentation: Option<String>,
92}
93
94impl Completion {
95 pub fn item(label: impl Into<String>, kind: CompletionKind, detail: Option<String>) -> Self {
96 Completion {
97 label: label.into(),
98 kind,
99 detail,
100 insert_text: None,
101 documentation: None,
102 }
103 }
104
105 fn with_doc(mut self, doc: Option<&str>) -> Self {
107 self.documentation = doc.map(str::to_owned);
108 self
109 }
110
111 fn snippet(label: &str, body: &str) -> Self {
112 Completion {
113 label: label.to_string(),
114 kind: CompletionKind::Snippet,
115 detail: Some(format!("{label} scaffold")),
116 insert_text: Some(body.to_string()),
117 documentation: None,
118 }
119 }
120}
121
122fn fixture_path_prefix(line_prefix: &str) -> Option<&str> {
125 let rest = line_prefix.trim_start().strip_prefix("fixture ")?;
126 let (name, after) = rest.split_once('=')?;
127 if name.trim().is_empty() || !name.trim().chars().all(|c| c.is_alphanumeric() || c == '_') {
128 return None;
129 }
130 let partial = after.trim_start().strip_prefix('"')?;
131 (!partial.contains('"')).then_some(partial)
132}
133
134pub fn complete(
140 line_prefix: &str,
141 doc_text: &str,
142 files: Option<&HashMap<PathBuf, String>>,
143) -> Vec<Completion> {
144 complete_in(None, line_prefix, doc_text, files)
145}
146
147pub fn complete_in(
150 project_root: Option<&Path>,
151 line_prefix: &str,
152 doc_text: &str,
153 files: Option<&HashMap<PathBuf, String>>,
154) -> Vec<Completion> {
155 let split = || split_dependency_files(files, project_root);
158 if let Some(partial) = fixture_path_prefix(line_prefix) {
161 let files = project_root
162 .and_then(|root| bynk_project::assets::list_fixture_files(root).ok())
163 .unwrap_or_default();
164 return files
165 .into_iter()
166 .filter(|f| f.starts_with(partial.trim_start_matches("./")))
167 .map(|f| {
168 Completion::item(
169 f,
170 CompletionKind::Constant,
171 Some("fixture file — test-only, never deployed".to_string()),
172 )
173 })
174 .collect();
175 }
176 if in_refinement_annotation_position(line_prefix) {
179 return vec![Completion::item(
180 "example",
181 CompletionKind::Keyword,
182 Some(
183 "@example(<literal>) — the value `Val` uses for this pattern; checked against it"
184 .to_string(),
185 ),
186 )];
187 }
188 if let Some(unit) = consumes_brace_unit(line_prefix) {
190 if names_a_brace_alias(line_prefix) {
193 return Vec::new();
194 }
195 return capabilities_of_unit(&unit, doc_text, &split())
196 .into_iter()
197 .map(|c| {
198 let detail = format!(
199 "capability exported by `{unit}`{}",
200 stability_suffix(experimental(&format!("{unit}.{c}")))
201 );
202 Completion::item(c, CompletionKind::Capability, Some(detail))
203 })
204 .collect();
205 }
206 if is_consumes_target(line_prefix) {
208 return consumable_units(doc_text, &split());
209 }
210 if is_uses_target(line_prefix) {
214 return usable_commons(doc_text, &split());
215 }
216 if is_given_position(line_prefix) {
218 return in_scope_capabilities(doc_text, &split());
219 }
220 if let Some(keys) = signed_cookie_key_candidates(line_prefix) {
222 return keys;
223 }
224 if auth_scheme_position(line_prefix) {
225 return auth_scheme_candidates();
226 }
227 if let Some((record, field)) = cookie_field_receiver(line_prefix) {
229 return cookie_field_members(&record, &field, doc_text, files);
230 }
231 if let Some(units) = crate::duration_completion::duration_unit_candidates(line_prefix) {
233 return units;
234 }
235 if let Some(receiver) = member_receiver(line_prefix) {
238 let mut items = member_candidates(&receiver, doc_text, files);
239 items.extend(cookie_record_fields(&receiver, doc_text, files));
240 return items;
241 }
242 if let Some((recv, listed)) = record_pattern_receiver(line_prefix) {
247 let mut fields = record_field_names(&recv, doc_text, files);
248 if !fields.is_empty() {
249 fields.retain(|c| !listed.contains(&c.label));
250 fields.push(Completion::item(
251 "..",
252 CompletionKind::Keyword,
253 Some("the rest of the fields — a record pattern is always open".to_string()),
254 ));
255 return fields;
256 }
257 }
258 if let Some(recv) = record_construction_receiver(line_prefix) {
260 let fields = record_field_names(&recv, doc_text, files);
261 if !fields.is_empty() {
262 return fields;
263 }
264 }
265 if after_clause_keyword(line_prefix, "from") {
267 return protocol_candidates();
268 }
269 if after_clause_keyword(line_prefix, "on") {
271 return handler_kind_candidates();
272 }
273 if is_by_clause_position(line_prefix) {
277 return actor_candidates(doc_text, files);
278 }
279 if after_clause_keyword(line_prefix, "exports") {
281 return export_kind_candidates();
282 }
283 if after_clause_keyword(line_prefix, "provides") {
285 return in_scope_capabilities(doc_text, &split());
286 }
287 if is_derives_list_position(line_prefix) {
290 return derivable_candidates();
291 }
292 if is_after_type_body(line_prefix, doc_text) {
293 return vec![derives_keyword_candidate()];
294 }
295 if is_constraint_position(line_prefix) {
298 return constraint_candidates();
299 }
300 if is_caller_refinement_where(line_prefix) {
302 return vec![Completion::snippet("IsContext", "IsContext(${1:context})")];
303 }
304 if after_clause_keyword(line_prefix, "where") && !is_for_all_where(line_prefix) {
312 return predicate_name_candidates();
313 }
314 if is_snapshot_clause_position(line_prefix) {
316 return vec![Completion::snippet(
317 "matches snapshot",
318 "matches snapshot \"${1:name}\"",
319 )];
320 }
321 if is_type_position(line_prefix) {
324 return type_candidates(doc_text, files);
325 }
326 if is_keyword_position(line_prefix) {
329 return keyword_and_snippet_candidates();
330 }
331 if is_expression_position(line_prefix) {
336 return expression_candidates(doc_text, files);
337 }
338 Vec::new()
339}
340
341fn is_snapshot_clause_position(line: &str) -> bool {
348 let rest = line.trim_start();
349 let Some(body) = rest.strip_prefix("expect") else {
350 return false;
351 };
352 if !body.starts_with(char::is_whitespace) || body.contains("matches") {
353 return false;
354 }
355 let typed = body
357 .rsplit(char::is_whitespace)
358 .next()
359 .filter(|w| !w.is_empty() && body.ends_with(*w));
360 let value = match typed {
361 Some(word) if "matches".starts_with(word) => body[..body.len() - word.len()].trim_end(),
362 Some(_) => return false,
363 None if body.ends_with(char::is_whitespace) => body.trim_end(),
364 None => return false,
365 };
366 let Some(last) = value.chars().last() else {
367 return false;
368 };
369 let ends_a_value = last.is_alphanumeric() || matches!(last, '_' | ')' | ']' | '}' | '"');
370 let last_word = value
372 .rsplit(|c: char| !(c.is_alphanumeric() || c == '_'))
373 .next();
374 ends_a_value
375 && !matches!(
376 last_word,
377 Some("and" | "or" | "not" | "is" | "if" | "else" | "match" | "faults" | "called")
378 )
379}
380
381fn consumes_brace_unit(line: &str) -> Option<String> {
383 let idx = line.rfind("consumes")?;
384 let after = &line[idx + "consumes".len()..];
385 let open = after.find('{')?;
386 if after[open + 1..].contains('}') {
388 return None;
389 }
390 let unit = after[..open].trim();
391 if unit.is_empty() || !is_qualified_name(unit) {
392 return None;
393 }
394 Some(unit.to_string())
395}
396
397fn names_a_brace_alias(line: &str) -> bool {
400 let tail = line.rsplit(['{', ',']).next().unwrap_or("");
401 let mut words = tail.split_whitespace().collect::<Vec<_>>();
402 if !tail.ends_with(char::is_whitespace) {
403 words.pop();
405 }
406 words.last() == Some(&"as")
407}
408
409fn is_consumes_target(line: &str) -> bool {
411 let Some(idx) = line.rfind("consumes") else {
412 return false;
413 };
414 if !line[..idx]
416 .chars()
417 .last()
418 .map(|c| c.is_whitespace())
419 .unwrap_or(true)
420 {
421 return false;
422 }
423 let after = &line[idx + "consumes".len()..];
424 after.starts_with(char::is_whitespace)
426 && !after.contains('{')
427 && !after.contains('}')
428 && !after.split_whitespace().any(|w| w == "as")
429}
430
431fn is_uses_target(line: &str) -> bool {
433 let trimmed = line.trim_start();
434 let Some(after) = trimmed.strip_prefix("uses") else {
435 return false;
436 };
437 after.starts_with(char::is_whitespace) && after.split_whitespace().count() <= 1
438}
439
440fn is_constraint_position(line: &str) -> bool {
445 let head = line
446 .trim_end_matches(|c: char| c.is_alphanumeric() || c == '_')
447 .trim_end();
448 if !(head.ends_with(':') && !head.ends_with("::") || head.ends_with('+')) {
449 return false;
450 }
451 if let Some(open) = head.rfind('[')
453 && !head[open..].contains(']')
454 {
455 let before = head[..open].trim_end();
456 let name_start = before
457 .rfind(|c: char| !(c.is_alphanumeric() || matches!(c, '_' | '.')))
458 .map_or(0, |i| i + 1);
459 let decl = before[..name_start].trim_end();
460 return decl.ends_with("fn") || decl.ends_with("type");
461 }
462 if let Some(w) = head.rfind("where")
464 && line[..w].contains("->")
465 && head[..w].chars().last().is_none_or(char::is_whitespace)
466 {
467 return head[w + "where".len()..]
468 .chars()
469 .all(|c| c.is_alphanumeric() || matches!(c, '_' | ':' | ',' | '+' | ' ' | '\t'));
470 }
471 false
472}
473
474const BOUND_CONSTRAINTS: &[(&str, &str)] = &[
477 ("Eq", "constraint: values of the type compare with `==`"),
478 (
479 "Ord",
480 "constraint: values of the type are ordered (`<`, `<=`, `>`, `>=`); implies `Eq`",
481 ),
482 (
483 "Key",
484 "constraint: values of the type key a `Map` or `Set`; implies `Eq`",
485 ),
486 (
487 "Codable",
488 "constraint: values of the type encode and decode with `Json`, and cross a capability operation as JSON",
489 ),
490];
491
492fn constraint_candidates() -> Vec<Completion> {
494 BOUND_CONSTRAINTS
495 .iter()
496 .map(|(name, doc)| {
497 Completion::item(*name, CompletionKind::Constraint, Some((*doc).to_string()))
498 })
499 .collect()
500}
501
502fn derivable_candidates() -> Vec<Completion> {
504 vec![Completion::item(
505 "Ord",
506 CompletionKind::Constraint,
507 Some("derive `Ord`: order the type by declaration order".to_string()),
508 )]
509}
510
511fn derives_keyword_candidate() -> Completion {
512 Completion::item(
513 "derives",
514 CompletionKind::Keyword,
515 Some(
516 "opt the type into a constraint (`derives Ord`): ordered by declaration order"
517 .to_string(),
518 ),
519 )
520}
521
522fn is_derives_list_position(line: &str) -> bool {
525 let head = line.trim_end_matches(|c: char| c.is_alphanumeric() || c == '_');
526 let before = head.trim_end();
527 if !(head.ends_with(char::is_whitespace) || before.ends_with('+')) {
529 return false;
530 }
531 let Some(at) = before.rfind("derives") else {
532 return false;
533 };
534 if !before[..at].chars().last().is_none_or(char::is_whitespace) {
536 return false;
537 }
538 let after = &before[at + "derives".len()..];
539 after
540 .chars()
541 .all(|c| c.is_alphanumeric() || matches!(c, '_' | '+' | ' ' | '\t'))
542 && (after.trim().is_empty() || after.trim_end().ends_with('+'))
543}
544
545fn is_after_type_body(line: &str, doc_text: &str) -> bool {
551 let head = line.trim_end_matches(|c: char| c.is_alphanumeric() || c == '_');
552 if !head.ends_with(char::is_whitespace) && !head.ends_with('}') {
554 return false;
555 }
556 let rest = head.trim_end();
557 if rest.is_empty() || line.split_whitespace().any(|w| w == "derives") {
558 return false;
559 }
560 let balanced = |s: &str| {
561 s.matches('{').count() == s.matches('}').count()
562 && s.matches('(').count() == s.matches(')').count()
563 && s.matches('[').count() == s.matches(']').count()
564 };
565 let trimmed = rest.trim_start();
566 if trimmed.starts_with("type ") || trimmed.starts_with("type\t") {
567 let Some(eq) = trimmed.find('=') else {
569 return false;
570 };
571 let body = trimmed[eq + 1..].trim();
572 if body.is_empty() || !balanced(trimmed) {
573 return false;
574 }
575 let last_word = body
576 .rsplit(|c: char| !(c.is_alphanumeric() || c == '_'))
577 .next()
578 .unwrap_or("");
579 let ends_open = body
580 .ends_with(['=', '|', ',', '+', ':', '.', '>', '<', '(', '{', '[', '&'])
581 || matches!(
582 last_word,
583 "where" | "enum" | "opaque" | "and" | "or" | "implies"
584 );
585 return !ends_open && !body.ends_with("->");
586 }
587 if rest == "}" && !line.starts_with(char::is_whitespace) {
589 return doc_text.lines().any(|l| {
590 l.starts_with("type ")
591 && l.matches('{').count() > l.matches('}').count()
592 && !l.contains("derives")
593 });
594 }
595 false
596}
597
598fn is_given_position(line: &str) -> bool {
600 let Some(idx) = line.rfind("given") else {
601 return false;
602 };
603 if !line[..idx]
604 .chars()
605 .last()
606 .map(|c| c.is_whitespace())
607 .unwrap_or(true)
608 {
609 return false;
610 }
611 let after = &line[idx + "given".len()..];
612 if !after.starts_with(char::is_whitespace) {
613 return false;
614 }
615 after
618 .chars()
619 .all(|c| c.is_alphanumeric() || matches!(c, '_' | '.' | ',' | ' ' | '\t'))
620}
621
622fn is_qualified_name(s: &str) -> bool {
623 !s.is_empty()
624 && s.split('.').all(|seg| {
625 !seg.is_empty()
626 && seg.chars().all(|c| c.is_alphanumeric() || c == '_')
627 && !seg.chars().next().unwrap().is_ascii_digit()
628 })
629}
630
631fn is_type_position(line: &str) -> bool {
641 let head = line
642 .trim_end_matches(|c: char| c.is_alphanumeric() || c == '_')
643 .trim_end();
644 head.ends_with("->") || (head.ends_with(':') && !head.ends_with("::")) || in_type_arg_list(head)
645}
646
647fn in_type_arg_list(head: &str) -> bool {
651 let chars: Vec<char> = head.chars().collect();
652 let mut depth = 0i32;
653 let mut opener_after_ident = false;
654 for (i, &c) in chars.iter().enumerate() {
655 match c {
656 '[' => {
657 depth += 1;
658 if depth == 1 {
659 opener_after_ident =
660 i > 0 && (chars[i - 1].is_alphanumeric() || chars[i - 1] == '_');
661 }
662 }
663 ']' => depth -= 1,
664 _ => {}
665 }
666 }
667 depth > 0 && opener_after_ident
668}
669
670pub fn is_keyword_position(line: &str) -> bool {
676 line.trim().chars().all(|c| c.is_alphanumeric() || c == '_')
677}
678
679pub fn is_expression_position(line: &str) -> bool {
684 let head = line
685 .trim_end_matches(|c: char| c.is_alphanumeric() || c == '_')
686 .trim_end();
687 if head.ends_with("->") {
688 return false; }
690 if head.ends_with("=>") {
691 return true; }
693 matches!(
694 head.chars().last(),
695 Some('=' | '(' | ',' | '[' | '+' | '-' | '*' | '/' | '<' | '>' | '&' | '|')
696 )
697}
698
699fn member_receiver(line: &str) -> Option<String> {
707 let head = line
709 .trim_end_matches(|c: char| c.is_alphanumeric() || c == '_')
710 .strip_suffix('.')?;
711 let start = head
715 .char_indices()
716 .rfind(|&(_, c)| !(c.is_alphanumeric() || c == '_'))
717 .map_or(0, |(i, c)| i + c.len_utf8());
718 let recv = &head[start..];
719 let first = recv.chars().next()?;
720 if !first.is_ascii_uppercase() {
721 return None;
722 }
723 if head[..start].ends_with('.') {
725 return None;
726 }
727 Some(recv.to_string())
728}
729
730fn cookie_field_receiver(line: &str) -> Option<(String, String)> {
733 let head = line
734 .trim_end_matches(|c: char| c.is_alphanumeric() || c == '_')
735 .strip_suffix('.')?;
736 let is_ident = |c: char| c.is_alphanumeric() || c == '_';
737 let field_start = head
738 .char_indices()
739 .rfind(|&(_, c)| !is_ident(c))
740 .map_or(0, |(i, c)| i + c.len_utf8());
741 let field = &head[field_start..];
742 if field.is_empty() || !field.starts_with(|c: char| c.is_ascii_lowercase()) {
743 return None;
744 }
745 let before = head[..field_start].strip_suffix('.')?;
746 let record = member_receiver(&format!("{before}."))?;
747 Some((record, field.to_string()))
748}
749
750pub(crate) fn cookie_record_fields_of(
753 record: &str,
754 doc_text: &str,
755 files: Option<&HashMap<PathBuf, String>>,
756) -> Option<Vec<(String, bynk_syntax::ast::TypeRef, String)>> {
757 use bynk_syntax::ast::{HandlerKind, TypeBody};
758 let mut decl: Option<Vec<(String, bynk_syntax::ast::TypeRef, String)>> = None;
759 let mut taken_as_cookies = false;
760 for_each_unit(doc_text, files, |unit| {
761 let items = match unit {
762 SourceUnit::Commons(c) => &c.items,
763 SourceUnit::Context(c) => &c.items,
764 _ => return,
765 };
766 for item in items {
767 match item {
768 CommonsItem::Type(t) if t.name.name == record => {
769 if let TypeBody::Record(r) = &t.body {
770 decl = Some(
771 r.fields
772 .iter()
773 .map(|f| {
774 (
775 f.name.name.clone(),
776 f.type_ref.clone(),
777 f.wire_name().unwrap_or_else(|| f.name.name.clone()),
778 )
779 })
780 .collect(),
781 );
782 }
783 }
784 CommonsItem::Service(svc) => {
785 taken_as_cookies |= svc.handlers.iter().any(|h| {
786 matches!(h.kind, HandlerKind::Http { .. })
787 && h.params.iter().any(|p| {
788 p.name.name == "cookies"
789 && matches!(&p.type_ref,
790 bynk_syntax::ast::TypeRef::Named(id) if id.name == record)
791 })
792 });
793 }
794 _ => {}
795 }
796 }
797 });
798 decl.filter(|_| taken_as_cookies)
799}
800
801fn cookie_record_fields(
804 record: &str,
805 doc_text: &str,
806 files: Option<&HashMap<PathBuf, String>>,
807) -> Vec<Completion> {
808 cookie_record_fields_of(record, doc_text, files)
809 .unwrap_or_default()
810 .into_iter()
811 .map(|(name, ty, wire)| {
812 Completion::item(
813 name,
814 CompletionKind::Field,
815 Some(format!(
816 "{} — cookie `{wire}` of `{record}`; `.cookie(v)` writes it, `.expire()` removes it",
817 crate::symbols::type_ref_str(&ty)
818 )),
819 )
820 })
821 .collect()
822}
823
824fn cookie_field_members(
826 record: &str,
827 field: &str,
828 doc_text: &str,
829 files: Option<&HashMap<PathBuf, String>>,
830) -> Vec<Completion> {
831 let Some(fields) = cookie_record_fields_of(record, doc_text, files) else {
832 return Vec::new();
833 };
834 let Some((_, ty, wire)) = fields.into_iter().find(|(n, _, _)| n == field) else {
835 return Vec::new();
836 };
837 let value = match &ty {
838 bynk_syntax::ast::TypeRef::Option(inner, _) => crate::symbols::type_ref_str(inner),
839 other => crate::symbols::type_ref_str(other),
840 };
841 vec![
842 Completion::item(
843 "cookie".to_string(),
844 CompletionKind::Member,
845 Some(format!(
846 "cookie(value: {value}) -> Cookie — the cookie `{wire}`, valued as `{record}`'s decoder reads it"
847 )),
848 ),
849 Completion::item(
850 "expire".to_string(),
851 CompletionKind::Member,
852 Some(format!("expire() -> Cookie — deletes the cookie `{wire}`")),
853 ),
854 ]
855}
856
857fn record_construction_receiver(line: &str) -> Option<String> {
863 let bytes = line.as_bytes();
865 let mut depth = 0i32;
866 let mut open = None;
867 for i in (0..bytes.len()).rev() {
868 match bytes[i] {
869 b'}' => depth += 1,
870 b'{' => {
871 if depth == 0 {
872 open = Some(i);
873 break;
874 }
875 depth -= 1;
876 }
877 _ => {}
878 }
879 }
880 let open = open?;
881 let current = line[open + 1..].rsplit(',').next().unwrap_or("");
884 if current.contains(':') {
885 return None;
886 }
887 let head = line[..open].trim_end();
889 let start = head
890 .char_indices()
891 .rfind(|&(_, c)| !(c.is_alphanumeric() || c == '_'))
892 .map_or(0, |(i, c)| i + c.len_utf8());
893 let recv = &head[start..];
894 if recv.chars().next()?.is_ascii_uppercase() {
895 Some(recv.to_string())
896 } else {
897 None
898 }
899}
900
901fn lambda_param_position(head: &str) -> bool {
908 let mut depth = 0i32;
909 let mut open = None;
910 for (i, c) in head.char_indices().rev() {
911 match c {
912 ')' => depth += 1,
913 '(' if depth == 0 => {
914 open = Some(i);
915 break;
916 }
917 '(' => depth -= 1,
918 _ => {}
919 }
920 }
921 let Some(open) = open else { return false };
922 let before = head[..open].trim_end();
923 if !(before.ends_with('(') || before.ends_with(',')) {
924 return false;
925 }
926 let mut segments = Vec::new();
927 let mut depth = 0i32;
928 let mut segment = String::new();
929 for c in head[open + 1..].chars() {
930 match c {
931 '(' | '{' | '[' => depth += 1,
932 ')' | '}' | ']' => depth -= 1,
933 ',' if depth == 0 => {
934 segments.push(std::mem::take(&mut segment));
935 continue;
936 }
937 _ => {}
938 }
939 segment.push(c);
940 }
941 let current = segment.trim().is_empty();
942 current
943 && segments.iter().all(|seg| {
944 let seg = seg.trim();
945 let name = seg.split(':').next().unwrap_or("").trim();
946 seg.ends_with('}')
947 || (!name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_'))
948 })
949}
950
951fn record_pattern_receiver(line: &str) -> Option<(String, Vec<String>)> {
956 let recv = record_construction_receiver(line)?;
957 let open = line.rfind('{')?;
958 let head = line[..open].trim_end();
960 let head = head.strip_suffix(recv.as_str())?;
961 let after_is = head
962 .rsplit_once(" is ")
963 .map_or(head, |(_, pattern)| pattern);
964 let mut rest = after_is.trim_start();
967 if let Some(after_let) = rest.strip_prefix("let ") {
970 rest = after_let;
971 }
972 loop {
973 let before = rest;
974 rest = rest.trim_start_matches(|c: char| c.is_whitespace() || c == '(' || c == '|');
975 let ident_end = rest
976 .find(|c: char| !(c.is_alphanumeric() || c == '_'))
977 .unwrap_or(rest.len());
978 let (ident, tail) = rest.split_at(ident_end);
979 let tail_trim = tail.trim_start();
980 if !ident.is_empty()
981 && ((tail_trim.starts_with('(') && ident.starts_with(|c: char| c.is_ascii_uppercase()))
982 || (tail_trim.starts_with(':') && !tail_trim.starts_with("::")))
983 {
984 rest = &tail_trim[1..];
985 }
986 if rest == before {
987 break;
988 }
989 }
990 if !rest.trim().is_empty() && !lambda_param_position(head) {
991 return None;
992 }
993 let mut listed = Vec::new();
995 let mut depth = 0i32;
996 let mut segment = String::new();
997 for c in line[open + 1..].chars() {
998 match c {
999 '(' | '{' | '[' => depth += 1,
1000 ')' | '}' | ']' => depth -= 1,
1001 ',' if depth == 0 => {
1002 let name = segment.split(':').next().unwrap_or("").trim();
1003 if !name.is_empty() {
1004 listed.push(name.to_string());
1005 }
1006 segment.clear();
1007 continue;
1008 }
1009 _ => {}
1010 }
1011 segment.push(c);
1012 }
1013 Some((recv, listed))
1014}
1015
1016pub const CORS_FIELDS: &[(&str, &str)] = &[
1020 (
1021 "origins",
1022 "the allowed origins — an exact allowlist, or `[\"*\"]`",
1023 ),
1024 (
1025 "headers",
1026 "the `Access-Control-Allow-Headers` a preflight advertises",
1027 ),
1028 (
1029 "credentials",
1030 "whether credentialed requests are allowed (`true`/`false`)",
1031 ),
1032 (
1033 "maxAge",
1034 "how long a browser may cache the preflight (a `Duration`)",
1035 ),
1036];
1037
1038pub const SECURITY_FIELDS: &[(&str, &str)] = &[
1041 (
1042 "nosniff",
1043 "stamp `X-Content-Type-Options: nosniff` (`true`/`false`, default `true`)",
1044 ),
1045 (
1046 "hsts",
1047 "opt in to `Strict-Transport-Security` — the `max-age` as a `Duration`",
1048 ),
1049];
1050
1051pub const LIMITS_FIELDS: &[(&str, &str)] = &[
1054 (
1055 "maxBody",
1056 "the maximum request body size in bytes (a positive `Int`)",
1057 ),
1058 (
1059 "maxFile",
1060 "the maximum size in bytes of one file part of a `@multipart` body (a positive `Int`)",
1061 ),
1062 (
1063 "maxParts",
1064 "the maximum number of parts of a `@multipart` body (a positive `Int`; default 64)",
1065 ),
1066];
1067
1068pub const JSON_FIELDS: &[(&str, &str)] = &[(
1072 "options",
1073 "how `Option` is written in response bodies: `tagged` (Bynk's `{\"kind\": …}` form) or `plain` (`v` / `null`)",
1074)];
1075
1076pub const JSON_OPTIONS_VALUES: &[(&str, &str)] = &[
1078 (
1079 "tagged",
1080 "Bynk's tagged form: `{\"kind\": \"Some\", \"value\": v}` / `{\"kind\": \"None\"}` (the default)",
1081 ),
1082 (
1083 "plain",
1084 "plain JSON for non-Bynk clients: `Some(v)` is `v`, `None` is `null`",
1085 ),
1086];
1087
1088pub fn in_refinement_annotation_position(line_prefix: &str) -> bool {
1092 let Some(at) = line_prefix.rfind('@') else {
1093 return false;
1094 };
1095 let partial = &line_prefix[at + 1..];
1096 if !partial.chars().all(|c| c.is_alphanumeric() || c == '_') {
1097 return false;
1098 }
1099 let before = &line_prefix[..at];
1100 before.contains(" where ")
1101 && (before.contains("Matches(") || before.contains("IsoDate") || before.contains("Cron"))
1102 && !before.contains("@example")
1103}
1104
1105pub const CACHE_ARGS: &[(&str, &str)] = &[
1111 (
1112 "maxAge",
1113 "the freshness window — a whole-second `Duration` (e.g. `5.minutes`) lowered to `Cache-Control: max-age`",
1114 ),
1115 (
1116 "scope",
1117 "`public` or `private` (default `private` — a shared cache stores only on `public`)",
1118 ),
1119 (
1120 "immutable",
1121 "`true` promises the response never changes (a content-addressed path) — appends `immutable` to `Cache-Control`; purge it through `EdgeCache` if it can change; default `false`",
1122 ),
1123];
1124
1125pub const LIMIT_ARGS: &[(&str, &str)] = &[
1130 (
1131 "maxBody",
1132 "the maximum request body size in bytes (a positive `Int`) — a `413` is synthesised past it",
1133 ),
1134 (
1135 "maxFile",
1136 "on a `@multipart` route, the maximum size in bytes of one file part — a `413` past it",
1137 ),
1138 (
1139 "maxParts",
1140 "on a `@multipart` route, the maximum number of parts — a `413` past it",
1141 ),
1142];
1143
1144pub const RAW_ARGS: &[(&str, &str)] = &[(
1148 "contentType",
1149 "the media type the route accepts, a string literal (`\"*/*\"` for any) — another `Content-Type` is a `415`",
1150)];
1151
1152pub const HTTP_PARAMS: &[(&str, &str, &str)] = &[
1156 (
1157 "query",
1158 "RequestQuery",
1159 "the query string: a record `T` decoded and validated before the handler runs (`400` on a violation), or a raw `RequestQuery` view",
1160 ),
1161 (
1162 "headers",
1163 "RequestHeaders",
1164 "the request's headers, read-only",
1165 ),
1166 (
1167 "cookies",
1168 "T",
1169 "the request's cookies: a record `T` decoded from the `Cookie` header and validated before the handler runs (`400` on a violation), or a raw `RequestCookies` view",
1170 ),
1171 (
1172 "cf",
1173 "RequestCf",
1174 "what Cloudflare derived about the connection (country, colo, ASN, …); every field is optional (Cloudflare only: `consumes bynk.cloudflare { RequestCf }`)",
1175 ),
1176 (
1177 "body",
1178 "T",
1179 "the request body, parsed and validated before the handler runs (not on `GET` or `DELETE`)",
1180 ),
1181];
1182
1183pub fn in_http_param_name_position(text: &str, offset: usize) -> bool {
1188 let Some(open) = innermost_open_paren(text, offset) else {
1189 return false;
1190 };
1191 let head = text[..open].trim_end();
1192 if !head.ends_with(')') {
1193 return false;
1194 }
1195 let Some(route_open) = innermost_open_paren(head, head.len() - 1) else {
1196 return false;
1197 };
1198 let before = text[..route_open].trim_end();
1199 let Some(method_start) = before
1200 .rfind(|c: char| !c.is_ascii_alphanumeric())
1201 .map(|i| i + 1)
1202 else {
1203 return false;
1204 };
1205 if !matches!(
1206 &before[method_start..],
1207 "GET" | "POST" | "PUT" | "PATCH" | "DELETE"
1208 ) {
1209 return false;
1210 }
1211 if !before[..method_start].trim_end().ends_with("on") {
1212 return false;
1213 }
1214 let Some(seg) = text.get(open + 1..offset.min(text.len())) else {
1215 return false;
1216 };
1217 let current = seg.rsplit(['\n', ',']).next().unwrap_or("");
1218 !current.contains(':')
1219}
1220
1221fn innermost_open_brace(text: &str, offset: usize) -> Option<usize> {
1225 let bytes = text.as_bytes();
1226 let end = offset.min(bytes.len());
1227 let mut depth = 0i32;
1228 for i in (0..end).rev() {
1229 match bytes[i] {
1230 b'}' => depth += 1,
1231 b'{' => {
1232 if depth == 0 {
1233 return Some(i);
1234 }
1235 depth -= 1;
1236 }
1237 _ => {}
1238 }
1239 }
1240 None
1241}
1242
1243fn word_before_brace(text: &str, open: usize) -> &str {
1246 let head = text[..open].trim_end();
1247 let start = head
1248 .char_indices()
1249 .rfind(|&(_, c)| !(c.is_alphanumeric() || c == '_'))
1250 .map_or(0, |(i, c)| i + c.len_utf8());
1251 &head[start..]
1252}
1253
1254pub fn in_par_block_position(text: &str, offset: usize) -> bool {
1257 innermost_open_brace(text, offset).is_some_and(|open| word_before_brace(text, open) == "par")
1258}
1259
1260pub fn par_block_candidates() -> Vec<Completion> {
1263 vec![
1264 Completion::snippet("let x <-", "let ${1:name} <- ${2:effect}"),
1265 Completion::item(
1266 "do",
1267 CompletionKind::Keyword,
1268 Some("run a unit effect alongside the others in this `par` block".to_string()),
1269 ),
1270 ]
1271}
1272
1273pub fn in_effectful_body_position(text: &str, offset: usize) -> bool {
1279 let mut at = offset.min(text.len());
1280 while let Some(open) = innermost_open_brace(text, at) {
1281 let before = &text[..open];
1282 let header_start = before.rfind(['{', '}']).map_or(0, |i| i + 1);
1283 let header = &before[header_start..];
1284 if let Some(arrow) = header.rfind("->") {
1285 return header[arrow + 2..].trim_start().starts_with("Effect[");
1286 }
1287 at = open;
1288 }
1289 false
1290}
1291
1292pub fn par_snippet() -> Completion {
1295 Completion::snippet(
1296 "par",
1297 "par {\n\tlet ${1:first} <- ${2:effect}\n\tlet ${3:second} <- ${4:effect}\n}",
1298 )
1299}
1300
1301pub fn in_cors_field_position(text: &str, offset: usize) -> bool {
1305 let Some(open) = innermost_open_brace(text, offset) else {
1306 return false;
1307 };
1308 if word_before_brace(text, open) != "cors" {
1309 return false;
1310 }
1311 let Some(seg) = text.get(open + 1..offset.min(text.len())) else {
1314 return false;
1315 };
1316 let current = seg.rsplit(['\n', ',']).next().unwrap_or("");
1317 !current.contains(':')
1318}
1319
1320pub fn in_security_field_position(text: &str, offset: usize) -> bool {
1324 let Some(open) = innermost_open_brace(text, offset) else {
1325 return false;
1326 };
1327 if word_before_brace(text, open) != "security" {
1328 return false;
1329 }
1330 let Some(seg) = text.get(open + 1..offset.min(text.len())) else {
1333 return false;
1334 };
1335 let current = seg.rsplit(['\n', ',']).next().unwrap_or("");
1336 !current.contains(':')
1337}
1338
1339pub fn in_limits_field_position(text: &str, offset: usize) -> bool {
1343 let Some(open) = innermost_open_brace(text, offset) else {
1344 return false;
1345 };
1346 if word_before_brace(text, open) != "limits" {
1347 return false;
1348 }
1349 let Some(seg) = text.get(open + 1..offset.min(text.len())) else {
1352 return false;
1353 };
1354 let current = seg.rsplit(['\n', ',']).next().unwrap_or("");
1355 !current.contains(':')
1356}
1357
1358pub fn in_json_field_position(text: &str, offset: usize) -> bool {
1361 let Some(open) = innermost_open_brace(text, offset) else {
1362 return false;
1363 };
1364 if word_before_brace(text, open) != "json" {
1365 return false;
1366 }
1367 let Some(seg) = text.get(open + 1..offset.min(text.len())) else {
1368 return false;
1369 };
1370 let current = seg.rsplit(['\n', ',']).next().unwrap_or("");
1371 !current.contains(':')
1372}
1373
1374pub fn in_json_options_value_position(text: &str, offset: usize) -> bool {
1377 let Some(head) = text.get(..offset.min(text.len())) else {
1378 return false;
1379 };
1380 let in_block = innermost_open_brace(text, offset)
1381 .is_some_and(|open| word_before_brace(text, open) == "json");
1382 let in_annotation = innermost_open_paren(text, offset).is_some_and(|open| {
1383 word_before_brace(text, open) == "json"
1384 && text[..open]
1385 .trim_end()
1386 .trim_end_matches("json")
1387 .trim_end()
1388 .ends_with('@')
1389 });
1390 if !in_block && !in_annotation {
1391 return false;
1392 }
1393 let line = head.rsplit(['\n', ',', '(', '{']).next().unwrap_or("");
1394 line.trim_start()
1395 .strip_prefix("options")
1396 .and_then(|rest| rest.trim_start().strip_prefix(':'))
1397 .is_some_and(|value| {
1398 value
1399 .chars()
1400 .all(|c| c.is_alphabetic() || c.is_whitespace())
1401 })
1402}
1403
1404pub fn in_json_arg_position(text: &str, offset: usize) -> bool {
1407 let Some(open) = innermost_open_paren(text, offset) else {
1408 return false;
1409 };
1410 if word_before_brace(text, open) != "json" {
1411 return false;
1412 }
1413 let head = text[..open].trim_end();
1414 let before = head[..head.len() - "json".len()].trim_end();
1415 if !before.ends_with('@') {
1416 return false;
1417 }
1418 let Some(seg) = text.get(open + 1..offset.min(text.len())) else {
1419 return false;
1420 };
1421 let current = seg.rsplit(['\n', ',']).next().unwrap_or("");
1422 !current.contains(':')
1423}
1424
1425pub fn in_env_name_position(text: &str, offset: usize) -> bool {
1429 let Some(open) = innermost_open_brace(text, offset) else {
1430 return false;
1431 };
1432 if word_before_brace(text, open) != "env" {
1433 return false;
1434 }
1435 let Some(seg) = text.get(open + 1..offset.min(text.len())) else {
1436 return false;
1437 };
1438 let current = seg.rsplit(['\n', ',']).next().unwrap_or("");
1439 !current.contains('=')
1440}
1441
1442pub fn env_name_candidates(
1447 doc_text: &str,
1448 files: Option<&HashMap<PathBuf, String>>,
1449) -> Vec<Completion> {
1450 let mut names: BTreeMap<String, &'static str> = BTreeMap::new();
1451 let mut scan = |src: &str| {
1452 for (marker, detail) in [
1453 ("secret = \"", "a secret an actor declares"),
1454 ("Secrets.get(\"", "a name `Secrets.get` reads"),
1455 ] {
1456 let mut rest = src;
1457 while let Some(i) = rest.find(marker) {
1458 rest = &rest[i + marker.len()..];
1459 if let Some(end) = rest.find('"') {
1460 let name = &rest[..end];
1461 if !name.is_empty() && !name.contains(char::is_whitespace) {
1462 names.entry(name.to_string()).or_insert(detail);
1463 }
1464 }
1465 }
1466 }
1467 };
1468 scan(doc_text);
1469 if let Some(files) = files {
1470 for src in files.values() {
1471 scan(src);
1472 }
1473 }
1474 names
1475 .into_iter()
1476 .map(|(name, detail)| {
1477 let mut c = Completion::item(name.clone(), CompletionKind::Field, Some(detail.into()));
1478 c.insert_text = Some(format!("{name} = \"\""));
1479 c
1480 })
1481 .collect()
1482}
1483
1484pub fn in_service_body_item_position(text: &str, offset: usize, line_prefix: &str) -> bool {
1489 if !is_keyword_position(line_prefix) {
1490 return false;
1491 }
1492 let Some(open) = innermost_open_brace(text, offset) else {
1493 return false;
1494 };
1495 let header_start = text[..open].rfind('\n').map_or(0, |i| i + 1);
1496 text[header_start..open].contains("service ")
1497}
1498
1499fn innermost_open_paren(text: &str, offset: usize) -> Option<usize> {
1502 let bytes = text.as_bytes();
1503 let end = offset.min(bytes.len());
1504 let mut depth = 0i32;
1505 for i in (0..end).rev() {
1506 match bytes[i] {
1507 b')' => depth += 1,
1508 b'(' => {
1509 if depth == 0 {
1510 return Some(i);
1511 }
1512 depth -= 1;
1513 }
1514 _ => {}
1515 }
1516 }
1517 None
1518}
1519
1520pub fn in_cache_arg_position(text: &str, offset: usize) -> bool {
1525 let Some(open) = innermost_open_paren(text, offset) else {
1526 return false;
1527 };
1528 if word_before_brace(text, open) != "cache" {
1529 return false;
1530 }
1531 let head = text[..open].trim_end();
1534 let before_cache = head[..head.len() - "cache".len()].trim_end();
1535 if !before_cache.ends_with('@') {
1536 return false;
1537 }
1538 let Some(seg) = text.get(open + 1..offset.min(text.len())) else {
1541 return false;
1542 };
1543 let current = seg.rsplit(['\n', ',']).next().unwrap_or("");
1544 !current.contains(':')
1545}
1546
1547pub fn in_limit_arg_position(text: &str, offset: usize) -> bool {
1552 let Some(open) = innermost_open_paren(text, offset) else {
1553 return false;
1554 };
1555 if word_before_brace(text, open) != "limit" {
1556 return false;
1557 }
1558 let head = text[..open].trim_end();
1561 let before_limit = head[..head.len() - "limit".len()].trim_end();
1562 if !before_limit.ends_with('@') {
1563 return false;
1564 }
1565 if on_capability_declaration(text, open) {
1568 return false;
1569 }
1570 let Some(seg) = text.get(open + 1..offset.min(text.len())) else {
1573 return false;
1574 };
1575 let current = seg.rsplit(['\n', ',']).next().unwrap_or("");
1576 !current.contains(':')
1577}
1578
1579fn on_capability_declaration(text: &str, open: usize) -> bool {
1582 let line_start = text[..open].rfind('\n').map_or(0, |i| i + 1);
1583 let line = text[line_start..open].trim_start();
1584 line.starts_with("capability ") && line.contains('=')
1585}
1586
1587pub fn instance_option_values(
1591 text: &str,
1592 offset: usize,
1593) -> &'static [(&'static str, &'static str)] {
1594 let Some(open) = innermost_open_paren(text, offset) else {
1595 return &[];
1596 };
1597 if !on_capability_declaration(text, open) {
1598 return &[];
1599 }
1600 let Some(seg) = text.get(open + 1..offset.min(text.len())) else {
1601 return &[];
1602 };
1603 if !seg.trim().is_empty() {
1604 return &[];
1605 }
1606 let head = text[..open].trim_end();
1607 let before = head[..head.len() - word_before_brace(text, open).len()].trim_end();
1608 if !before.ends_with('@') {
1609 return &[];
1610 }
1611 match word_before_brace(text, open) {
1612 "period" => RATELIMIT_PERIODS,
1613 _ => &[],
1614 }
1615}
1616
1617pub fn instance_declaration_completions(line: &str) -> Vec<(String, String, String)> {
1623 let line = line.trim_start();
1624 let Some(rest) = line.strip_prefix("capability ") else {
1625 return Vec::new();
1626 };
1627 let Some((_, after)) = rest.split_once('=') else {
1628 return Vec::new();
1629 };
1630 let kinds = || {
1631 bynk_check::firstparty::UNITS
1632 .iter()
1633 .flat_map(|u| u.instantiable.iter().map(move |i| (u.name, i)))
1634 };
1635 let typed = after.trim_start();
1636 if !typed.contains(char::is_whitespace) {
1637 return kinds()
1639 .filter(|(_, i)| i.capability.starts_with(typed))
1640 .map(|(unit, i)| {
1641 (
1642 i.capability.to_string(),
1643 format!("an instance of `{unit}`'s `{}`", i.capability),
1644 i.capability.to_string(),
1645 )
1646 })
1647 .collect();
1648 }
1649 let (base, tail) = typed.split_once(char::is_whitespace).unwrap_or((typed, ""));
1650 if !tail.trim().is_empty() {
1651 return Vec::new();
1652 }
1653 let Some((_, kind)) = kinds().find(|(_, i)| i.capability == base) else {
1654 return Vec::new();
1655 };
1656 if kind.required.is_empty() {
1657 return Vec::new();
1658 }
1659 let snippet: Vec<String> = kind
1660 .required
1661 .iter()
1662 .enumerate()
1663 .map(|(n, o)| format!("@{o}(${{{}:{}}})", n + 1, option_sample(o)))
1664 .collect();
1665 let label: Vec<String> = kind.required.iter().map(|o| format!("@{o}(…)")).collect();
1666 vec![(
1667 label.join(" "),
1668 format!("the options every `{base}` instance needs"),
1669 snippet.join(" "),
1670 )]
1671}
1672
1673fn option_sample(option: &str) -> &'static str {
1675 match option {
1676 "limit" => "100",
1677 "period" => "60.seconds",
1678 "jurisdiction" => "\"eu\"",
1679 "name" => "\"order-events\"",
1680 "store" => "\"payments\"",
1681 "secret" => "\"stripe-live\"",
1682 "to" => "\"[email protected]\"",
1683 "allowedRecipients" | "allowedSenders" => "[\"[email protected]\"]",
1684 _ => "\"legacy-billing\"",
1685 }
1686}
1687
1688pub const RATELIMIT_PERIODS: &[(&str, &str)] = &[
1690 (
1691 "10.seconds",
1692 "a 10-second window — one of the two the platform offers",
1693 ),
1694 (
1695 "60.seconds",
1696 "a 60-second window — one of the two the platform offers",
1697 ),
1698];
1699
1700pub fn in_raw_arg_position(text: &str, offset: usize) -> bool {
1703 let Some(open) = innermost_open_paren(text, offset) else {
1704 return false;
1705 };
1706 if word_before_brace(text, open) != "raw" {
1707 return false;
1708 }
1709 let head = text[..open].trim_end();
1710 let before_raw = head[..head.len() - "raw".len()].trim_end();
1711 if !before_raw.ends_with('@') {
1712 return false;
1713 }
1714 let Some(seg) = text.get(open + 1..offset.min(text.len())) else {
1715 return false;
1716 };
1717 let current = seg.rsplit(['\n', ',']).next().unwrap_or("");
1718 !current.contains(':')
1719}
1720
1721fn is_caller_refinement_where(line_prefix: &str) -> bool {
1724 let t = line_prefix.trim_start();
1725 t.starts_with("actor ") && t.contains("= Caller where")
1726}
1727
1728fn after_clause_keyword(line: &str, kw: &str) -> bool {
1734 let Some(idx) = line.rfind(kw) else {
1735 return false;
1736 };
1737 if !line[..idx]
1738 .chars()
1739 .last()
1740 .map(char::is_whitespace)
1741 .unwrap_or(true)
1742 {
1743 return false;
1744 }
1745 let after = &line[idx + kw.len()..];
1746 after.starts_with(char::is_whitespace)
1747 && after
1748 .trim_start()
1749 .chars()
1750 .all(|c| c.is_alphanumeric() || c == '_')
1751}
1752
1753pub(crate) fn is_by_clause_position(line: &str) -> bool {
1760 if !after_clause_keyword(line, "by") {
1761 return false;
1762 }
1763 let Some(idx) = line.rfind("by") else {
1764 return false;
1765 };
1766 let before = line[..idx].trim_start();
1767 if !before
1771 .trim_end()
1772 .chars()
1773 .last()
1774 .is_some_and(|c| c.is_alphanumeric() || matches!(c, '_' | ')' | ']' | '"' | '\''))
1775 {
1776 return false;
1777 }
1778 let after_return_type = before
1780 .rfind("->")
1781 .is_some_and(|i| !before[i..].contains('{'));
1782 after_return_type
1783 || before.contains("<-")
1784 || before.starts_with("service ")
1785 || before.starts_with("expect ")
1786}
1787
1788fn is_for_all_where(line: &str) -> bool {
1798 let Some(idx) = line.rfind("where") else {
1799 return false;
1800 };
1801 let head = line[..idx].trim_start();
1802 let Some(after_for) = head.strip_prefix("for") else {
1803 return false;
1804 };
1805 if !after_for.starts_with(char::is_whitespace) {
1808 return false;
1809 }
1810 let Some(after_all) = after_for.trim_start().strip_prefix("all") else {
1811 return false;
1812 };
1813 after_all.is_empty() || after_all.starts_with(char::is_whitespace)
1815}
1816
1817pub fn contract_clause_kind(line: &str) -> Option<bool> {
1823 let colon = line.rfind(':')?;
1824 let clause = line[..colon].trim();
1825 for (kw, is_ensures) in [("requires", false), ("ensures", true)] {
1826 if let Some(rest) = clause.strip_prefix(kw) {
1827 let rest = rest.trim();
1828 if !rest.is_empty() && rest.chars().all(|c| c.is_alphanumeric() || c == '_') {
1829 return Some(is_ensures);
1830 }
1831 }
1832 }
1833 None
1834}
1835
1836fn record_field_names(
1846 name: &str,
1847 doc_text: &str,
1848 files: Option<&HashMap<PathBuf, String>>,
1849) -> Vec<Completion> {
1850 let mut out: Vec<Completion> = Vec::new();
1851 let mut found = false;
1852 for_each_unit(doc_text, files, |unit| {
1853 if found {
1854 return;
1855 }
1856 let suite_types: Vec<CommonsItem> = match unit {
1858 SourceUnit::Suite(s) => s.types.iter().cloned().map(CommonsItem::Type).collect(),
1859 _ => Vec::new(),
1860 };
1861 let items = match unit {
1862 SourceUnit::Commons(c) => &c.items,
1863 SourceUnit::Context(c) => &c.items,
1864 SourceUnit::Adapter(a) => &a.items,
1865 SourceUnit::Suite(_) => &suite_types,
1866 };
1867 for item in items {
1868 if let CommonsItem::Type(t) = item
1869 && t.name.name == name
1870 && let TypeBody::Record(r) = &t.body
1871 {
1872 found = true;
1873 let (required, defaulted): (Vec<_>, Vec<_>) =
1877 r.fields.iter().partition(|f| f.init.is_none());
1878 for f in required.into_iter().chain(defaulted) {
1879 let detail = match &f.init {
1880 Some(init) => format!(
1881 "field of `{name}`, default `{}`",
1882 bynk_fmt::expr_to_string(init)
1883 ),
1884 None => format!("field of `{name}`"),
1885 };
1886 out.push(
1887 Completion::item(f.name.name.clone(), CompletionKind::Field, Some(detail))
1888 .with_doc(f.documentation.as_deref()),
1889 );
1890 }
1891 return;
1892 }
1893 }
1894 });
1895 out
1896}
1897
1898pub fn sum_type_variants(
1906 name: &str,
1907 doc_text: &str,
1908 files: Option<&HashMap<PathBuf, String>>,
1909) -> Vec<Completion> {
1910 let mut out: Vec<Completion> = Vec::new();
1911 let mut found = false;
1912 for_each_unit(doc_text, files, |unit| {
1913 if found {
1914 return;
1915 }
1916 let suite_types: Vec<CommonsItem> = match unit {
1918 SourceUnit::Suite(s) => s.types.iter().cloned().map(CommonsItem::Type).collect(),
1919 _ => Vec::new(),
1920 };
1921 let items = match unit {
1922 SourceUnit::Commons(c) => &c.items,
1923 SourceUnit::Context(c) => &c.items,
1924 SourceUnit::Adapter(a) => &a.items,
1925 SourceUnit::Suite(_) => &suite_types,
1926 };
1927 for item in items {
1928 if let CommonsItem::Type(t) = item
1929 && t.name.name == name
1930 && let TypeBody::Sum(s) = &t.body
1931 {
1932 found = true;
1933 for v in &s.variants {
1934 out.push(
1935 Completion::item(
1936 v.name.name.clone(),
1937 CompletionKind::Variant,
1938 Some(format!("variant of `{name}`")),
1939 )
1940 .with_doc(v.documentation.as_deref()),
1941 );
1942 }
1943 return;
1944 }
1945 }
1946 });
1947 out
1948}
1949
1950pub fn variants_for_ty(
1957 ty: TyId,
1958 tys: &Types,
1959 doc_text: &str,
1960 files: Option<&HashMap<PathBuf, String>>,
1961) -> Vec<Completion> {
1962 match &*tys.get(ty) {
1963 Ty::Named { name, .. } => sum_type_variants(name, doc_text, files),
1964 Ty::Result(..) => built_in_variants(&["Ok", "Err"], "Result"),
1965 Ty::Option(..) => built_in_variants(&["Some", "None"], "Option"),
1966 _ => Vec::new(),
1967 }
1968}
1969
1970pub fn nested_variant_completions(
1978 ty: TyId,
1979 tys: &Types,
1980 outer_variant: &str,
1981 doc_text: &str,
1982 files: Option<&HashMap<PathBuf, String>>,
1983) -> Vec<Completion> {
1984 match &*tys.get(ty) {
1985 Ty::Result(t, e) => match outer_variant {
1986 "Ok" => variants_for_ty(*t, tys, doc_text, files),
1987 "Err" => variants_for_ty(*e, tys, doc_text, files),
1988 _ => Vec::new(),
1989 },
1990 Ty::HttpResult(t) if outer_variant == "Ok" => variants_for_ty(*t, tys, doc_text, files),
1991 Ty::Option(t) if outer_variant == "Some" => variants_for_ty(*t, tys, doc_text, files),
1992 Ty::Named {
1993 kind: NamedKind::Sum,
1994 name,
1995 ..
1996 } => payload_type_ref_variants(name, outer_variant, doc_text, files),
1997 _ => Vec::new(),
1998 }
1999}
2000
2001fn built_in_variants(names: &[&str], of: &str) -> Vec<Completion> {
2003 names
2004 .iter()
2005 .map(|v| {
2006 Completion::item(
2007 (*v).to_string(),
2008 CompletionKind::Variant,
2009 Some(format!("variant of `{of}`")),
2010 )
2011 })
2012 .collect()
2013}
2014
2015fn payload_type_ref_variants(
2020 sum_name: &str,
2021 variant: &str,
2022 doc_text: &str,
2023 files: Option<&HashMap<PathBuf, String>>,
2024) -> Vec<Completion> {
2025 let mut field_ty: Option<TypeRef> = None;
2026 for_each_unit(doc_text, files, |unit| {
2027 let suite_types: Vec<CommonsItem> = match unit {
2029 SourceUnit::Suite(s) => s.types.iter().cloned().map(CommonsItem::Type).collect(),
2030 _ => Vec::new(),
2031 };
2032 let items = match unit {
2033 SourceUnit::Commons(c) => &c.items,
2034 SourceUnit::Context(c) => &c.items,
2035 SourceUnit::Adapter(a) => &a.items,
2036 SourceUnit::Suite(_) => &suite_types,
2037 };
2038 for item in items {
2039 if let CommonsItem::Type(t) = item
2040 && t.name.name == sum_name
2041 && let TypeBody::Sum(s) = &t.body
2042 && let Some(v) = s.variants.iter().find(|v| v.name.name == variant)
2043 && let Some(f) = v.payload.first()
2044 {
2045 field_ty = Some(f.type_ref.clone());
2046 }
2047 }
2048 });
2049 match field_ty {
2050 Some(tr) => variants_for_type_ref(&tr, doc_text, files),
2051 None => Vec::new(),
2052 }
2053}
2054
2055fn variants_for_type_ref(
2058 tr: &TypeRef,
2059 doc_text: &str,
2060 files: Option<&HashMap<PathBuf, String>>,
2061) -> Vec<Completion> {
2062 match tr {
2063 TypeRef::Named(id) => sum_type_variants(&id.name, doc_text, files),
2064 TypeRef::Result(..) => built_in_variants(&["Ok", "Err"], "Result"),
2065 TypeRef::Option(..) => built_in_variants(&["Some", "None"], "Option"),
2066 _ => Vec::new(),
2067 }
2068}
2069
2070fn protocol_candidates() -> Vec<Completion> {
2072 ["http", "cron", "queue", "websocket", "email"]
2073 .into_iter()
2074 .map(|p| Completion::item(p, CompletionKind::Keyword, Some("service protocol".into())))
2075 .collect()
2076}
2077
2078fn handler_kind_candidates() -> Vec<Completion> {
2080 [
2081 "call", "GET", "POST", "PUT", "PATCH", "DELETE", "schedule", "message", "open", "close",
2082 "rejected",
2083 ]
2084 .into_iter()
2085 .map(|k| Completion::item(k, CompletionKind::Keyword, Some("handler kind".into())))
2086 .collect()
2087}
2088
2089fn export_kind_candidates() -> Vec<Completion> {
2091 ["capability", "transparent", "opaque"]
2092 .into_iter()
2093 .map(|k| Completion::item(k, CompletionKind::Keyword, Some("export kind".into())))
2094 .collect()
2095}
2096
2097fn predicate_name_candidates() -> Vec<Completion> {
2101 [
2102 "Matches",
2103 "InRange",
2104 "MinLength",
2105 "MaxLength",
2106 "Length",
2107 "NonNegative",
2108 "Positive",
2109 "NonEmpty",
2110 "IsoDate",
2111 "Cron",
2112 ]
2113 .into_iter()
2114 .map(|k| {
2115 Completion::item(
2116 k,
2117 CompletionKind::Keyword,
2118 Some("refinement predicate".into()),
2119 )
2120 })
2121 .collect()
2122}
2123
2124fn actor_candidates(doc_text: &str, files: Option<&HashMap<PathBuf, String>>) -> Vec<Completion> {
2126 let mut out: Vec<Completion> = Vec::new();
2127 let in_suite = lexer::tokenize(doc_text).ok().is_some_and(|toks| {
2132 toks.iter()
2133 .find(|t| !matches!(t.kind, lexer::TokenKind::Comment))
2134 .is_some_and(|t| t.kind == lexer::TokenKind::Suite)
2135 });
2136 if in_suite {
2137 for (name, doc) in crate::symbols::RESERVED_PRINCIPALS {
2138 out.push(
2139 Completion::item(
2140 *name,
2141 CompletionKind::Type,
2142 Some("reserved test principal".into()),
2143 )
2144 .with_doc(Some(doc)),
2145 );
2146 }
2147 }
2148 let mut seen: BTreeSet<String> = BTreeSet::new();
2149 for_each_unit(doc_text, files, |unit| {
2150 let suite_types: Vec<CommonsItem> = match unit {
2152 SourceUnit::Suite(s) => s.types.iter().cloned().map(CommonsItem::Type).collect(),
2153 _ => Vec::new(),
2154 };
2155 let items = match unit {
2156 SourceUnit::Commons(c) => &c.items,
2157 SourceUnit::Context(c) => &c.items,
2158 SourceUnit::Adapter(a) => &a.items,
2159 SourceUnit::Suite(_) => &suite_types,
2160 };
2161 for item in items {
2162 if let CommonsItem::Actor(a) = item
2163 && seen.insert(a.name.name.clone())
2164 {
2165 out.push(Completion::item(
2166 a.name.name.clone(),
2167 CompletionKind::Type,
2168 Some("actor".into()),
2169 ));
2170 }
2171 }
2172 });
2173 out
2174}
2175
2176pub const BUILTIN_STATICS: &[(&str, &[(&str, &str)])] = &[
2183 ("Int", &[("parse", "parse(s: String) -> Option[Int]")]),
2184 (
2185 "Float",
2186 &[
2187 ("parse", "parse(s: String) -> Option[Float]"),
2188 ("pi", "pi: Float"),
2189 ("e", "e: Float"),
2190 ],
2191 ),
2192 ("Duration", &[("millis", "millis(n: Int) -> Duration")]),
2194 (
2195 "Instant",
2196 &[
2197 ("fromEpochMillis", "fromEpochMillis(n: Int) -> Instant"),
2198 ("fromIso", "fromIso(s: String) -> Option[Instant]"),
2199 ],
2200 ),
2201 (
2202 "Decimal",
2203 &[
2204 ("parse", "parse(s: String) -> Option[Decimal]"),
2205 ("fromInt", "fromInt(n: Int) -> Decimal"),
2206 ],
2207 ),
2208 (
2210 "RequestQuery",
2211 &[
2212 ("of", "of(pairs: List[String]) -> RequestQuery"),
2213 ("empty", "empty() -> RequestQuery"),
2214 ],
2215 ),
2216 (
2218 "RequestCookies",
2219 &[
2220 ("of", "of(pairs: List[String]) -> RequestCookies"),
2221 ("empty", "empty() -> RequestCookies"),
2222 ],
2223 ),
2224 (
2225 "RoundingMode",
2226 &[
2227 ("Down", "RoundingMode.Down - toward zero"),
2228 ("Up", "RoundingMode.Up - away from zero"),
2229 ("Floor", "RoundingMode.Floor - toward negative infinity"),
2230 ("Ceiling", "RoundingMode.Ceiling - toward positive infinity"),
2231 (
2232 "HalfUp",
2233 "RoundingMode.HalfUp - nearest, a tie away from zero",
2234 ),
2235 (
2236 "HalfDown",
2237 "RoundingMode.HalfDown - nearest, a tie toward zero",
2238 ),
2239 (
2240 "HalfEven",
2241 "RoundingMode.HalfEven - nearest, a tie to the even neighbour",
2242 ),
2243 ],
2244 ),
2245 (
2246 "Json",
2247 &[
2248 ("encode", "encode(value) -> String"),
2249 (
2250 "encodePlain",
2251 "encodePlain(value) -> String - Option as `v` / `null`",
2252 ),
2253 ("decode", "decode[T](s: String) -> Result[T, DecodeError]"),
2254 (
2255 "decodeSql",
2256 "decodeSql[T](s: String) -> Result[T, DecodeError]",
2257 ),
2258 ],
2259 ),
2260 (
2261 "Yaml",
2262 &[("decode", "decode[T](s: String) -> Result[T, DecodeError]")],
2263 ),
2264 (
2265 "Form",
2266 &[
2267 ("decode", "decode[T](s: String) -> Result[T, DecodeError]"),
2268 ("encode", "encode(v: T) -> String"),
2269 ],
2270 ),
2271 ("List", &[("empty", "empty() -> List[T]")]),
2272 ("Map", &[("empty", "empty() -> Map[K, V]")]),
2273 (
2274 "Set",
2275 &[
2276 ("empty", "empty() -> Set[T]"),
2277 ("of", "of(xs: List[T]) -> Set[T]"),
2278 ],
2279 ),
2280 ("Effect", &[("pure", "pure(value) -> Effect[T]")]),
2281 (
2282 "Bytes",
2283 &[
2284 ("fromUtf8", "fromUtf8(s: String) -> Bytes"),
2285 ("fromBase64", "fromBase64(s: String) -> Option[Bytes]"),
2286 ("fromHex", "fromHex(s: String) -> Option[Bytes]"),
2287 ("fromBase64Url", "fromBase64Url(s: String) -> Option[Bytes]"),
2288 ("empty", "empty() -> Bytes"),
2289 ],
2290 ),
2291];
2292
2293fn builtin_sum_variants(receiver: &str) -> Vec<(String, String)> {
2297 match receiver {
2298 "HttpResult" => bynk_syntax::ast::HTTP_VARIANTS
2299 .iter()
2300 .map(|v| {
2301 (
2302 v.name.to_string(),
2303 if v.status == bynk_syntax::ast::AUTHOR_CHOSEN_STATUS {
2304 "variant of `HttpResult` (4xx/5xx, author-chosen)".to_string()
2305 } else {
2306 format!("variant of `HttpResult` ({})", v.status)
2307 },
2308 )
2309 })
2310 .collect(),
2311 "QueueResult" => bynk_syntax::ast::QUEUE_VARIANTS
2312 .iter()
2313 .map(|v| (v.name.to_string(), "variant of `QueueResult`".to_string()))
2314 .collect(),
2315 "EmailVerdict" => [
2320 (
2321 "Accept",
2322 "variant of `EmailVerdict`: handled, nothing else happens",
2323 ),
2324 (
2325 "Reject",
2326 "variant of `EmailVerdict`: refuse with an SMTP rejection",
2327 ),
2328 (
2329 "Forward",
2330 "variant of `EmailVerdict`: pass to a verified destination",
2331 ),
2332 ("Reply", "variant of `EmailVerdict`: answer the sender"),
2333 ]
2334 .into_iter()
2335 .map(|(n, d)| (n.to_string(), d.to_string()))
2336 .collect(),
2337 _ => Vec::new(),
2338 }
2339}
2340
2341fn auth_scheme_position(line_prefix: &str) -> bool {
2348 let Some(i) = line_prefix.rfind("auth") else {
2349 return false;
2350 };
2351 line_prefix[i + "auth".len()..]
2352 .trim_start()
2353 .strip_prefix('=')
2354 .is_some_and(|r| {
2355 r.trim_start()
2356 .chars()
2357 .all(|c| c.is_alphanumeric() || c == '_')
2358 })
2359}
2360
2361fn auth_scheme_candidates() -> Vec<Completion> {
2363 [
2364 ("None", "anonymous: no credential"),
2365 ("Bearer", "a signed JWT in `Authorization: Bearer …`"),
2366 (
2367 "SignedCookie",
2368 "a signed, expiring session cookie that Bynk issues and verifies",
2369 ),
2370 ("Oidc", "an OIDC/JWKS provider token"),
2371 ("Signature", "a webhook HMAC signature"),
2372 ("Internal", "an in-system caller"),
2373 ("Foreign", "a caller that is not Bynk, signing the call"),
2374 ]
2375 .into_iter()
2376 .map(|(label, detail)| {
2377 Completion::item(
2378 label,
2379 CompletionKind::Keyword,
2380 Some(format!("auth scheme — {detail}")),
2381 )
2382 })
2383 .collect()
2384}
2385
2386fn signed_cookie_key_candidates(line_prefix: &str) -> Option<Vec<Completion>> {
2388 let open = line_prefix.rfind("SignedCookie(")? + "SignedCookie(".len();
2389 let args = &line_prefix[open..];
2390 if args.contains(')') {
2391 return None;
2392 }
2393 let current = args.rsplit(',').next().unwrap_or(args);
2395 if current.contains('=') {
2396 return Some(Vec::new());
2397 }
2398 let written: Vec<&str> = args
2399 .split(',')
2400 .filter_map(|part| part.split('=').next().map(str::trim))
2401 .collect();
2402 Some(
2403 [
2404 (
2405 "secret",
2406 "the environment variable holding the signing key (required)",
2407 ),
2408 (
2409 "ttl",
2410 "how long an issued cookie is valid, e.g. `12.hours` (required)",
2411 ),
2412 ("cookie", "the cookie's name; defaults to `__Host-session`"),
2413 (
2414 "previous",
2415 "the key being rotated out, accepted for verification only",
2416 ),
2417 (
2418 "sameSite",
2419 "`Lax` (the default), `Strict` or `Unrestricted`",
2420 ),
2421 ]
2422 .into_iter()
2423 .filter(|(key, _)| !written.contains(key))
2424 .map(|(key, detail)| {
2425 Completion::item(
2426 key,
2427 CompletionKind::Field,
2428 Some(format!("SignedCookie key — {detail}")),
2429 )
2430 })
2431 .collect(),
2432 )
2433}
2434
2435pub fn is_signed_cookie_actor(a: &bynk_syntax::ast::ActorDecl) -> bool {
2437 a.auth.as_ref().is_some_and(|s| s.name == "SignedCookie")
2438}
2439
2440pub fn signed_cookie_members(a: &bynk_syntax::ast::ActorDecl) -> [(&'static str, String); 2] {
2442 let identity = a
2443 .identity
2444 .as_ref()
2445 .map_or_else(|| "identity".to_string(), crate::symbols::type_ref_str);
2446 [
2447 (
2448 "issue",
2449 format!("issue(identity: {identity}) -> Effect[Cookie]"),
2450 ),
2451 ("expire", "expire() -> Cookie".to_string()),
2452 ]
2453}
2454
2455pub(crate) const D1_PEEK_SIGNATURE: &str = "peek(<participant>.<Capability>) -> D1Peek - a read-only handle on a participant's test database";
2458
2459fn member_candidates(
2460 receiver: &str,
2461 doc_text: &str,
2462 files: Option<&HashMap<PathBuf, String>>,
2463) -> Vec<Completion> {
2464 let mut out = member_candidates_from(receiver, doc_text, files, &mut BTreeSet::new());
2465 if receiver == "D1" && !out.iter().any(|c| c.label == "peek") {
2466 out.push(Completion::item(
2467 "peek",
2468 CompletionKind::Member,
2469 Some(D1_PEEK_SIGNATURE.to_string()),
2470 ));
2471 }
2472 out
2473}
2474
2475fn member_candidates_from(
2480 receiver: &str,
2481 doc_text: &str,
2482 files: Option<&HashMap<PathBuf, String>>,
2483 followed: &mut BTreeSet<String>,
2484) -> Vec<Completion> {
2485 followed.insert(receiver.to_string());
2486 if let Some((_, statics)) = BUILTIN_STATICS.iter().find(|(name, _)| *name == receiver) {
2487 return statics
2488 .iter()
2489 .map(|(label, sig)| {
2490 Completion::item(*label, CompletionKind::Member, Some(sig.to_string()))
2491 })
2492 .collect();
2493 }
2494 let mut out: Vec<Completion> = Vec::new();
2495 let mut seen: BTreeSet<String> = BTreeSet::new();
2496 let mut derived_base: Option<String> = None;
2501 for (label, detail) in builtin_sum_variants(receiver) {
2502 if seen.insert(label.clone()) {
2503 out.push(Completion::item(
2504 label,
2505 CompletionKind::Variant,
2506 Some(detail),
2507 ));
2508 }
2509 }
2510 for_each_unit(doc_text, files, |unit| {
2511 let suite_types: Vec<CommonsItem> = match unit {
2513 SourceUnit::Suite(s) => s.types.iter().cloned().map(CommonsItem::Type).collect(),
2514 _ => Vec::new(),
2515 };
2516 let items = match unit {
2517 SourceUnit::Commons(c) => &c.items,
2518 SourceUnit::Context(c) => &c.items,
2519 SourceUnit::Adapter(a) => &a.items,
2520 SourceUnit::Suite(_) => &suite_types,
2521 };
2522 for item in items {
2523 match item {
2524 CommonsItem::Type(t) if t.name.name == receiver => match &t.body {
2525 bynk_syntax::ast::TypeBody::Sum(s) => {
2526 for v in &s.variants {
2527 if seen.insert(v.name.name.clone()) {
2528 out.push(
2529 Completion::item(
2530 v.name.name.clone(),
2531 CompletionKind::Variant,
2532 Some(format!("variant of `{receiver}`")),
2533 )
2534 .with_doc(v.documentation.as_deref()),
2535 );
2536 }
2537 }
2538 }
2539 bynk_syntax::ast::TypeBody::Refined { .. }
2540 | bynk_syntax::ast::TypeBody::Opaque { .. } => {
2541 let of_sig = match &t.body {
2542 bynk_syntax::ast::TypeBody::Refined {
2544 base, refinement, ..
2545 } if bynk_syntax::ast::of_is_total(
2546 *base,
2547 refinement.as_ref(),
2548 false,
2549 ) =>
2550 {
2551 format!("of(value) -> {receiver}")
2552 }
2553 _ => format!("of(value) -> Result[{receiver}, ValidationError]"),
2554 };
2555 for (label, sig) in [
2556 ("of", of_sig),
2557 ("unsafe", format!("unsafe(value) -> {receiver}")),
2558 ] {
2559 if seen.insert(label.to_string()) {
2560 out.push(Completion::item(
2561 label,
2562 CompletionKind::Member,
2563 Some(sig),
2564 ));
2565 }
2566 }
2567 }
2568 _ => {}
2572 },
2573 CommonsItem::Capability(c) if c.name.name == receiver && c.derived.is_some() => {
2574 derived_base = c.derived.as_ref().map(|d| d.base.name.clone());
2575 }
2576 CommonsItem::Fn(f) => {
2581 if let FnName::Method {
2582 type_name,
2583 method_name,
2584 } = &f.name
2585 && !f.has_self
2586 && type_name.name == receiver
2587 && seen.insert(method_name.name.clone())
2588 {
2589 out.push(
2590 Completion::item(
2591 method_name.name.clone(),
2592 CompletionKind::Member,
2593 Some(free_fn_signature(&method_name.name, f)),
2594 )
2595 .with_doc(f.documentation.as_deref()),
2596 );
2597 }
2598 }
2599 CommonsItem::Actor(a) if a.name.name == receiver && is_signed_cookie_actor(a) => {
2601 for (label, sig) in signed_cookie_members(a) {
2602 if seen.insert(label.to_string()) {
2603 out.push(Completion::item(
2604 label,
2605 CompletionKind::Member,
2606 Some(format!("{sig} — session cookie of `{receiver}`")),
2607 ));
2608 }
2609 }
2610 }
2611 CommonsItem::Capability(c) if c.name.name == receiver => {
2612 for op in &c.ops {
2613 if seen.insert(op.name.name.clone()) {
2614 out.push(Completion::item(
2618 op.name.name.clone(),
2619 CompletionKind::Member,
2620 Some(format!(
2621 "{} — operation of `{receiver}`",
2622 capability_op_signature(op)
2623 )),
2624 ));
2625 }
2626 }
2627 }
2628 _ => {}
2629 }
2630 }
2631 });
2632 if let Some(base) = derived_base
2635 .as_deref()
2636 .filter(|b| crate::signature_help::TYPED_READ_BASES.contains(b))
2637 {
2638 for member in ["select", "firstAs"] {
2639 if let Some(sig) = crate::signature_help::typed_read(base, member)
2640 && seen.insert(member.to_string())
2641 {
2642 out.push(Completion::item(
2643 member.to_string(),
2644 CompletionKind::Member,
2645 Some(format!("{sig} — operation of `{receiver}`")),
2646 ));
2647 }
2648 }
2649 }
2650 if let Some(base) = derived_base.filter(|b| !followed.contains(b)) {
2651 for c in member_candidates_from(&base, doc_text, files, followed) {
2652 if seen.insert(c.label.clone()) {
2653 out.push(c);
2654 }
2655 }
2656 }
2657 out
2658}
2659
2660const BUILTIN_TYPES: &[&str] = &[
2666 bynk_check::builtin_names::types::INT,
2667 "Bool",
2668 bynk_check::builtin_names::types::FLOAT,
2669 "String",
2670 "Option",
2671 "Result",
2672 "Effect",
2673 bynk_check::builtin_names::types::LIST,
2674 bynk_check::builtin_names::types::MAP,
2675 bynk_check::builtin_names::types::SET,
2676];
2677
2678pub const SNIPPETS: &[(&str, &str)] = &[
2681 ("context", "context ${1:name} {\n\t$0\n}"),
2683 ("commons", "commons ${1:my.lib}\n\n$0"),
2684 (
2685 "adapter",
2686 "adapter ${1:name} {\n\tbinding \"${2:./module}\"\n\t$0\n}",
2687 ),
2688 ("uses", "uses ${1:module}"),
2690 ("consumes", "consumes ${1:bynk} { ${2:Random} }"),
2691 (
2693 "type record",
2694 "type ${1:Name} = {\n\t${2:field}: ${3:Int},\n}",
2695 ),
2696 ("type enum", "type ${1:Name} = enum {\n\t${2:Variant},\n}"),
2697 (
2698 "type refined",
2699 "type ${1:Name} = ${2:String} where ${3:MinLength(1)}",
2700 ),
2701 (
2702 "type opaque",
2703 "type ${1:Name} = opaque ${2:Int} where ${3:NonNegative}",
2704 ),
2705 (
2707 "fn",
2708 "fn ${1:name}(${2:x}: ${3:Int}) -> ${4:Int} {\n\t$0\n}",
2709 ),
2710 (
2711 "fn contract",
2712 "fn ${1:name}(${2:x}: ${3:Int}) -> ${4:Int}\n\trequires ${5:in_range}: ${6:x >= 0}\n\tensures ${7:non_negative}: ${8:result >= 0}\n{\n\t$0\n}",
2713 ),
2714 (
2716 "capability",
2717 "capability ${1:Name} {\n\tfn ${2:op}() -> Effect[${3:Unit}]\n}",
2718 ),
2719 (
2720 "provides",
2721 "provides ${1:Cap} = ${2:Impl} {\n\tfn ${3:op}(${4}) -> Effect[${5:()}] {\n\t\tEffect.pure(${6:()})\n\t}\n}",
2722 ),
2723 (
2725 "actor",
2726 "actor ${1:Name} { auth = ${2:Bearer(secret = \"AUTH_JWT_SECRET\")}, identity = ${3:UserId} }",
2727 ),
2728 (
2729 "agent",
2730 "agent ${1:Name} {\n\tkey ${2:id}: ${3:String}\n\n\tstore ${4:status}: Cell[${5:Int}] = ${6:0}\n\n\tinvariant ${7:non_negative}: ${8:status >= 0}\n\n\ttransition ${9:monotonic}: ${10:new.status >= old.status}\n\n\ton call ${11:op}(${12}) -> Effect[Result[${13:()}, String]] {\n\t\tOk(${14:()})\n\t}\n}",
2731 ),
2732 (
2734 "service",
2735 "service ${1:name} {\n\ton call(${2}) -> Effect[${3:Unit}] by Caller {\n\t\t$0\n\t}\n}",
2736 ),
2737 (
2738 "on call",
2739 "on call(${1}) -> Effect[${2:Unit}] by Caller {\n\t$0\n}",
2740 ),
2741 (
2742 "on http",
2743 "on ${1|GET,POST,PUT,DELETE,PATCH|}(\"${2:/path}\") (${3:body}: ${4:Req}) -> Effect[HttpResult[${5:Res}]] given ${6:Cap} {\n\t$0\n}",
2744 ),
2745 (
2746 "on cron",
2747 "on schedule(\"${1:0 * * * *}\") () -> Effect[Result[(), String]] {\n\t$0\n\tOk(())\n}",
2748 ),
2749 (
2751 "suite",
2752 "suite ${1:target}\n\ncase \"${2:it works}\" {\n\tlet ${3:actual} = ${4:0}\n\texpect ${5:actual == 0}\n}",
2753 ),
2754 (
2755 "property",
2756 "property \"${1:invariant holds}\" {\n\tfor all ${2:x}: ${3:Int} {\n\t\texpect ${4:x == x}\n\t}\n}",
2757 ),
2758 ("advance Clock by", "advance Clock by ${1:15.minutes}"),
2760];
2761
2762const CONSTRUCTORS: &[&str] = &["Ok", "Err", "Some", "None", "true", "false"];
2767
2768fn expression_candidates(
2774 doc_text: &str,
2775 files: Option<&HashMap<PathBuf, String>>,
2776) -> Vec<Completion> {
2777 let mut out: Vec<Completion> = CONSTRUCTORS
2778 .iter()
2779 .map(|&name| {
2780 Completion::item(
2781 name,
2782 CompletionKind::Constructor,
2783 keyword_doc(name).map(str::to_string),
2784 )
2785 })
2786 .collect();
2787 out.extend(type_candidates(doc_text, files));
2790 out.extend(free_function_candidates(doc_text, files));
2794 for info in keywords::BUILTIN_FUNCTIONS {
2796 if !out.iter().any(|c| c.label == info.word) {
2797 out.push(
2798 Completion::item(
2799 info.word,
2800 CompletionKind::Function,
2801 Some(format!("{}(message: String) -> never returns", info.word)),
2802 )
2803 .with_doc(Some(info.meaning)),
2804 );
2805 }
2806 }
2807 out
2808}
2809
2810fn unit_items_and_uses(unit: &SourceUnit) -> (&[CommonsItem], &[UsesDecl]) {
2813 match unit {
2814 SourceUnit::Commons(c) => (&c.items, &c.uses),
2815 SourceUnit::Context(c) => (&c.items, &c.uses),
2816 SourceUnit::Adapter(a) => (&a.items, &a.uses),
2817 _ => (&[], &[]),
2818 }
2819}
2820
2821fn current_unit_name(doc_text: &str) -> Option<String> {
2825 let tokens = lexer::tokenize(doc_text).ok()?;
2826 let (unit, _errs) = parser::parse_unit_with_recovery(&tokens, doc_text);
2827 Some(unit?.name().joined())
2828}
2829
2830fn experimental(path: &str) -> bool {
2832 bynk_check::firstparty::stability_of(path)
2833 == Some(bynk_check::firstparty::Stability::Experimental)
2834}
2835
2836fn stability_suffix(experimental: bool) -> &'static str {
2839 if experimental {
2840 " — experimental"
2841 } else {
2842 ""
2843 }
2844}
2845
2846pub fn capability_op_signature(op: &bynk_syntax::ast::CapabilityOp) -> String {
2850 let params = op
2851 .params
2852 .iter()
2853 .map(|p| format!("{}: {}", p.name.name, type_ref_str(&p.type_ref)))
2854 .collect::<Vec<_>>()
2855 .join(", ");
2856 let type_params = if op.type_params.is_empty() {
2858 String::new()
2859 } else {
2860 let names: Vec<&str> = op
2861 .type_params
2862 .iter()
2863 .map(|tp| tp.name.name.as_str())
2864 .collect();
2865 format!("[{}]", names.join(", "))
2866 };
2867 format!(
2868 "{}{type_params}({params}) -> {}",
2869 op.name.name,
2870 type_ref_str(&op.return_type)
2871 )
2872}
2873
2874pub fn free_fn_signature(name: &str, f: &bynk_syntax::ast::FnDecl) -> String {
2878 let params = f
2879 .params
2880 .iter()
2881 .map(|p| format!("{}: {}", p.name.name, type_ref_str(&p.type_ref)))
2882 .collect::<Vec<_>>()
2883 .join(", ");
2884 format!(
2885 "{name}{}({params}) -> {}{}{}",
2886 crate::symbols::fn_type_params_str(f),
2887 type_ref_str(&f.return_type),
2888 crate::symbols::fn_given_str(f),
2889 crate::symbols::fn_where_str(f)
2890 )
2891}
2892
2893fn free_function_candidates(
2900 doc_text: &str,
2901 files: Option<&HashMap<PathBuf, String>>,
2902) -> Vec<Completion> {
2903 let Some(current) = current_unit_name(doc_text) else {
2904 return Vec::new();
2905 };
2906 struct UnitFns {
2909 name: String,
2910 fns: Vec<(String, String, bool)>,
2911 assets: Vec<(String, String, Option<String>, bool)>,
2912 embeds: Vec<(String, String, Option<String>, bool)>,
2913 uses: Vec<String>,
2914 }
2915 let mut units: Vec<UnitFns> = Vec::new();
2916 for_each_unit(doc_text, files, |unit| {
2917 let (items, uses) = unit_items_and_uses(unit);
2918 let fns = items
2922 .iter()
2923 .filter_map(|it| match it {
2924 CommonsItem::Fn(f) => match &f.name {
2925 FnName::Free(id) => Some((
2926 id.name.clone(),
2927 free_fn_signature(&id.name, f),
2928 f.private.is_some(),
2929 )),
2930 FnName::Method { .. } => None,
2931 },
2932 _ => None,
2933 })
2934 .collect();
2935 let assets = items
2936 .iter()
2937 .filter_map(|it| match it {
2938 CommonsItem::Asset(a) => Some((
2939 a.name.name.clone(),
2940 format!(
2941 "asset {} = \"{}\"{}",
2942 a.name.name,
2943 bynk_fmt::escape_string(&a.path),
2944 a.at.as_ref()
2945 .map(|(p, _)| format!(" at \"{}\"", bynk_fmt::escape_string(p)))
2946 .unwrap_or_default()
2947 ),
2948 a.documentation.as_deref().map(str::to_string),
2949 a.private.is_some(),
2950 )),
2951 _ => None,
2952 })
2953 .collect();
2954 let embeds = items
2956 .iter()
2957 .filter_map(|it| match it {
2958 CommonsItem::Embed(e) => Some((
2959 e.name.name.clone(),
2960 format!(
2961 "embed {} = \"{}\"",
2962 e.name.name,
2963 bynk_fmt::escape_string(&e.path)
2964 ),
2965 e.documentation.as_deref().map(str::to_string),
2966 e.private.is_some(),
2967 )),
2968 CommonsItem::Const(c) => Some((
2970 c.name.name.clone(),
2971 format!(
2972 "const {}: {}",
2973 c.name.name,
2974 crate::symbols::type_ref_str(&c.ty)
2975 ),
2976 c.documentation.as_deref().map(str::to_string),
2977 c.private.is_some(),
2978 )),
2979 _ => None,
2980 })
2981 .collect();
2982 units.push(UnitFns {
2983 name: unit.name().joined(),
2984 fns,
2985 assets,
2986 embeds,
2987 uses: uses.iter().map(|u| u.target.joined()).collect(),
2988 });
2989 });
2990 let mut imported: BTreeSet<String> = BTreeSet::new();
2993 for u in &units {
2994 if u.name == current {
2995 imported.extend(u.uses.iter().cloned());
2996 }
2997 }
2998 let mut out: Vec<Completion> = Vec::new();
3000 let mut seen: BTreeSet<String> = BTreeSet::new();
3001 if let Some(SourceUnit::Suite(suite)) = parse_source_unit(doc_text) {
3004 for f in &suite.fixtures {
3005 if seen.insert(f.name.name.clone()) {
3006 out.push(
3007 Completion::item(
3008 f.name.name.clone(),
3009 CompletionKind::Constant,
3010 Some(format!(
3011 "fixture {} = \"{}\" — `this suite`",
3012 f.name.name,
3013 bynk_fmt::escape_string(&f.path)
3014 )),
3015 )
3016 .with_doc(f.documentation.as_deref()),
3017 );
3018 }
3019 }
3020 for c in &suite.consts {
3022 if seen.insert(c.name.name.clone()) {
3023 out.push(
3024 Completion::item(
3025 c.name.name.clone(),
3026 CompletionKind::Constant,
3027 Some(format!(
3028 "const {}: {} — `this suite`",
3029 c.name.name,
3030 type_ref_str(&c.ty)
3031 )),
3032 )
3033 .with_doc(c.documentation.as_deref()),
3034 );
3035 }
3036 }
3037 for f in &suite.fns {
3038 if let FnName::Free(id) = &f.name
3039 && seen.insert(id.name.clone())
3040 {
3041 out.push(
3042 Completion::item(
3043 id.name.clone(),
3044 CompletionKind::Function,
3045 Some(format!("{} — `this suite`", free_fn_signature(&id.name, f))),
3046 )
3047 .with_doc(f.documentation.as_deref()),
3048 );
3049 }
3050 }
3051 }
3052 for u in &units {
3053 let own = u.name == current;
3054 if !own && !imported.contains(&u.name) {
3055 continue;
3056 }
3057 let origin = if own { "this unit" } else { u.name.as_str() };
3058 for (name, sig, private) in &u.fns {
3059 if *private && !own {
3060 continue;
3061 }
3062 if seen.insert(name.clone()) {
3063 let marked = !own && experimental(&format!("{}.{name}", u.name));
3064 out.push(Completion::item(
3065 name.clone(),
3066 CompletionKind::Function,
3067 Some(format!("{sig} — `{origin}`{}", stability_suffix(marked))),
3068 ));
3069 }
3070 }
3071 for (name, decl, doc, private) in u.assets.iter().chain(&u.embeds) {
3072 if *private && !own {
3073 continue;
3074 }
3075 if seen.insert(name.clone()) {
3076 out.push(
3077 Completion::item(
3078 name.clone(),
3079 CompletionKind::Constant,
3080 Some(format!("{decl} — `{origin}`")),
3081 )
3082 .with_doc(doc.as_deref()),
3083 );
3084 }
3085 }
3086 }
3087 out
3088}
3089
3090pub fn keyword_doc(word: &str) -> Option<&'static str> {
3094 keywords::KEYWORDS
3095 .iter()
3096 .find(|k| k.word == word)
3097 .or_else(|| keywords::BUILTIN_FUNCTIONS.iter().find(|k| k.word == word))
3098 .map(|k| k.meaning)
3099}
3100
3101fn type_candidates(doc_text: &str, files: Option<&HashMap<PathBuf, String>>) -> Vec<Completion> {
3105 let mut out: Vec<Completion> = Vec::new();
3106 let mut seen: BTreeSet<String> = BTreeSet::new();
3107 for &name in BUILTIN_TYPES {
3108 if seen.insert(name.to_string()) {
3109 let detail = keyword_doc(name)
3110 .map(str::to_string)
3111 .or_else(|| match name {
3112 "List" => Some("The built-in list type, `List[T]`.".to_string()),
3113 "Map" => Some("The built-in map type, `Map[K, V]`.".to_string()),
3114 "Set" => Some("The built-in set type, `Set[T]`.".to_string()),
3115 _ => Some("built-in type".to_string()),
3116 });
3117 out.push(Completion::item(name, CompletionKind::Type, detail));
3118 }
3119 }
3120 let current = current_unit_name(doc_text);
3122 for_each_unit(doc_text, files, |unit| {
3123 let suite_types: Vec<CommonsItem> = match unit {
3125 SourceUnit::Suite(s) => s.types.iter().cloned().map(CommonsItem::Type).collect(),
3126 _ => Vec::new(),
3127 };
3128 let items = match unit {
3129 SourceUnit::Commons(c) => &c.items,
3130 SourceUnit::Context(c) => &c.items,
3131 SourceUnit::Adapter(a) => &a.items,
3132 SourceUnit::Suite(_) => &suite_types,
3133 };
3134 let own = current.as_deref() == Some(unit.name().joined().as_str());
3135 for item in items {
3136 if let CommonsItem::Type(t) = item
3137 && (own || t.private.is_none())
3138 && seen.insert(t.name.name.clone())
3139 {
3140 out.push(Completion::item(
3141 t.name.name.clone(),
3142 CompletionKind::Type,
3143 Some("type".to_string()),
3144 ));
3145 }
3146 }
3147 });
3148 out
3149}
3150
3151fn keyword_and_snippet_candidates() -> Vec<Completion> {
3156 let mut out: Vec<Completion> = keywords::KEYWORDS
3157 .iter()
3158 .filter(|k| k.word.chars().next().is_some_and(char::is_lowercase))
3159 .map(|k| Completion::item(k.word, CompletionKind::Keyword, Some(k.meaning.to_string())))
3160 .collect();
3161 if let Some(by) = keywords::CONTEXTUAL_KEYWORDS
3165 .iter()
3166 .find(|k| k.word == "by")
3167 {
3168 out.push(Completion::item(
3169 by.word,
3170 CompletionKind::Keyword,
3171 Some(by.meaning.to_string()),
3172 ));
3173 }
3174 for &(label, body) in SNIPPETS {
3175 out.push(Completion::snippet(label, body));
3176 }
3177 out
3178}
3179
3180fn parse_source_unit(src: &str) -> Option<SourceUnit> {
3185 let tokens = lexer::tokenize(src).ok()?;
3186 parser::parse_unit_with_recovery(&tokens, src).0
3187}
3188
3189static EMBEDDED_UNITS: LazyLock<Vec<Arc<SourceUnit>>> = LazyLock::new(|| {
3198 bynk_check::firstparty::FIRSTPARTY_SOURCES
3202 .iter()
3203 .filter_map(|(_, src)| parse_source_unit(src).map(Arc::new))
3204 .collect()
3205});
3206
3207pub(crate) fn embedded_capability(
3211 unit: &str,
3212 cap: &str,
3213) -> Option<bynk_syntax::ast::CapabilityDecl> {
3214 EMBEDDED_UNITS.iter().find_map(|u| {
3215 if u.name().joined() != unit {
3216 return None;
3217 }
3218 let SourceUnit::Adapter(a) = u.as_ref() else {
3219 return None;
3220 };
3221 a.items.iter().find_map(|item| match item {
3222 CommonsItem::Capability(c) if c.name.name == cap => Some(c.clone()),
3223 _ => None,
3224 })
3225 })
3226}
3227
3228fn cached_project_unit(path: &Path, content: &str) -> Option<Arc<SourceUnit>> {
3249 let (_file_id, result) = bynk_project::parse_cache::cached_parse(path, content);
3250 match result {
3251 Ok((units, _warnings)) => units.first().cloned().map(Arc::new),
3252 Err(_) => parse_source_unit(content).map(Arc::new),
3253 }
3254}
3255
3256pub fn for_each_unit(
3272 doc_text: &str,
3273 files: Option<&HashMap<PathBuf, String>>,
3274 mut f: impl FnMut(&SourceUnit),
3275) {
3276 for unit in EMBEDDED_UNITS.iter() {
3277 f(unit);
3278 }
3279 if let Some(unit) = parse_source_unit(doc_text) {
3280 f(&unit);
3281 }
3282 if let Some(content) = files {
3287 for (path, text) in content {
3288 if let Some(unit) = cached_project_unit(path, text) {
3289 f(&unit);
3290 }
3291 }
3292 }
3293}
3294
3295fn split_dependency_files<'f>(
3301 files: Option<&'f HashMap<PathBuf, String>>,
3302 project_root: Option<&Path>,
3303) -> SplitFiles<'f> {
3304 let Some(content) = files else {
3305 return SplitFiles::default();
3306 };
3307 let view = match project_root {
3308 Some(root) => crate::packages::DependencyView::for_root(root, content),
3309 None => crate::packages::DependencyView::from_files(content),
3310 };
3311 let Some(view) = view else {
3312 return SplitFiles {
3313 own: Some(Cow::Borrowed(content)),
3314 deps: Vec::new(),
3315 };
3316 };
3317 let mut own = HashMap::new();
3318 let mut deps = Vec::new();
3319 let mut keys: Vec<&PathBuf> = content.keys().collect();
3320 keys.sort();
3321 for path in keys {
3322 let text = &content[path];
3323 match view.package_of(path) {
3324 None => {
3325 own.insert(path.clone(), text.clone());
3326 }
3327 Some(id) => {
3328 if let Some(unit) = cached_project_unit(path, text) {
3329 for alias in view.aliases_of(id) {
3330 let declared = unit.name().joined();
3331 if view.exports(id, &declared) {
3332 deps.push((format!("{alias}.{declared}"), (*unit).clone()));
3333 }
3334 }
3335 }
3336 }
3337 }
3338 }
3339 SplitFiles {
3340 own: Some(Cow::Owned(own)),
3341 deps,
3342 }
3343}
3344
3345#[derive(Default)]
3349struct SplitFiles<'f> {
3350 own: Option<Cow<'f, HashMap<PathBuf, String>>>,
3351 deps: Vec<(String, SourceUnit)>,
3352}
3353
3354impl SplitFiles<'_> {
3355 fn own(&self) -> Option<&HashMap<PathBuf, String>> {
3356 self.own.as_deref()
3357 }
3358}
3359
3360fn usable_commons(doc_text: &str, split: &SplitFiles<'_>) -> Vec<Completion> {
3363 let mut seen: BTreeSet<String> = BTreeSet::new();
3364 let mut out: Vec<Completion> = Vec::new();
3365 for_each_unit(doc_text, split.own(), |unit| {
3366 if let SourceUnit::Commons(c) = unit {
3367 let name = c.name.joined();
3368 if seen.insert(name.clone()) {
3369 out.push(Completion::item(
3370 name,
3371 CompletionKind::Unit,
3372 Some("commons".to_string()),
3373 ));
3374 }
3375 }
3376 });
3377 for (label, unit) in &split.deps {
3378 if matches!(unit, SourceUnit::Commons(_)) && seen.insert(label.clone()) {
3379 out.push(Completion::item(
3380 label,
3381 CompletionKind::Unit,
3382 Some("commons from a dependency".to_string()),
3383 ));
3384 }
3385 }
3386 out
3387}
3388
3389fn consumable_units(doc_text: &str, split: &SplitFiles<'_>) -> Vec<Completion> {
3393 let files = split.own();
3394 let mut seen: BTreeSet<String> = BTreeSet::new();
3395 let mut out: Vec<Completion> = Vec::new();
3396 for (label, unit) in &split.deps {
3397 if matches!(unit, SourceUnit::Adapter(_)) && seen.insert(label.clone()) {
3398 out.push(Completion::item(
3399 label.clone(),
3400 CompletionKind::Unit,
3401 Some("adapter from a dependency".to_string()),
3402 ));
3403 }
3404 }
3405 for_each_unit(doc_text, files, |unit| {
3406 let (name, kind) = match unit {
3407 SourceUnit::Context(c) => (c.name.joined(), "context"),
3408 SourceUnit::Adapter(a) => (a.name.joined(), "adapter"),
3409 _ => return,
3410 };
3411 if seen.insert(name.clone()) {
3412 out.push(Completion::item(
3413 name,
3414 CompletionKind::Unit,
3415 Some(kind.to_string()),
3416 ));
3417 }
3418 });
3419 out
3420}
3421
3422fn capabilities_of_unit(unit: &str, doc_text: &str, split: &SplitFiles<'_>) -> Vec<String> {
3428 if let Some((_, dep)) = split.deps.iter().find(|(label, _)| label == unit) {
3431 let mut out: BTreeSet<String> = BTreeSet::new();
3432 if let SourceUnit::Adapter(a) = dep {
3433 for clause in &a.exports {
3434 if clause.kind == ExportKind::Capability {
3435 for n in clause.names.iter().map(|e| &e.name) {
3436 out.insert(n.name.clone());
3437 }
3438 }
3439 }
3440 }
3441 return out.into_iter().collect();
3442 }
3443 let files = split.own();
3444 let mut out: BTreeSet<String> = BTreeSet::new();
3445 let mut found = false;
3446 for_each_unit(doc_text, files, |u| {
3447 if found {
3448 return;
3449 }
3450 let (name, exports) = match u {
3451 SourceUnit::Context(c) => (c.name.joined(), &c.exports),
3452 SourceUnit::Adapter(a) => (a.name.joined(), &a.exports),
3453 _ => return,
3454 };
3455 if name != unit {
3456 return;
3457 }
3458 found = true;
3459 for clause in exports {
3460 if clause.kind == ExportKind::Capability {
3461 for n in clause.names.iter().map(|e| &e.name) {
3462 out.insert(n.name.clone());
3463 }
3464 }
3465 }
3466 });
3467 out.into_iter().collect()
3468}
3469
3470fn in_scope_capabilities(doc_text: &str, split: &SplitFiles<'_>) -> Vec<Completion> {
3474 let mut labels: BTreeSet<String> = BTreeSet::new();
3475 let Ok(tokens) = lexer::tokenize(doc_text) else {
3476 return Vec::new();
3477 };
3478 let (Some(unit), _errs) = parser::parse_unit_with_recovery(&tokens, doc_text) else {
3479 return Vec::new();
3480 };
3481 let (items, consumes) = match &unit {
3482 SourceUnit::Context(c) => (&c.items, &c.consumes),
3483 SourceUnit::Adapter(a) => (&a.items, &EMPTY_CONSUMES),
3484 _ => return Vec::new(),
3485 };
3486 for item in items {
3488 if let bynk_syntax::ast::CommonsItem::Capability(c) = item {
3489 labels.insert(c.name.name.clone());
3490 }
3491 }
3492 for c in consumes {
3494 let unit_name = c.target.joined();
3495 match &c.selected {
3496 Some(names) => {
3497 for n in names {
3498 labels.insert(n.name.name.clone());
3499 }
3500 }
3501 None => {
3502 let prefix = c
3503 .alias
3504 .as_ref()
3505 .map(|a| a.name.clone())
3506 .unwrap_or_else(|| unit_name.clone());
3507 for cap in capabilities_of_unit(&unit_name, doc_text, split) {
3508 labels.insert(format!("{prefix}.{cap}"));
3509 }
3510 }
3511 }
3512 }
3513 labels
3514 .into_iter()
3515 .map(|label| {
3516 Completion::item(
3517 label,
3518 CompletionKind::Capability,
3519 Some("capability in scope".to_string()),
3520 )
3521 })
3522 .collect()
3523}
3524
3525pub fn value_receiver_rewrite(text: &str, offset: usize) -> Option<(String, usize)> {
3537 let prefix = text.get(..offset)?;
3538 let head = prefix
3539 .trim_end_matches(|c: char| c.is_alphanumeric() || c == '_')
3540 .strip_suffix('.')?;
3541 let (recv, start) = ident_ending_at(head, head.len())?;
3542 let first = recv.chars().next()?;
3543 if !(first.is_ascii_lowercase() || first == '_') {
3544 return None; }
3546 if head[..start].ends_with('.') {
3547 return None; }
3549 let dot = head.len(); let rewritten = format!("{}{}", &text[..dot], &text[offset..]);
3551 Some((rewritten, dot.saturating_sub(1)))
3552}
3553
3554pub fn ident_ending_at(text: &str, end: usize) -> Option<(&str, usize)> {
3565 let before = text.get(..end)?;
3566 let start = before
3567 .char_indices()
3568 .rfind(|&(_, c)| !(c.is_alphanumeric() || c == '_'))
3569 .map_or(0, |(i, c)| i + c.len_utf8());
3570 let name = &before[start..];
3571 (!name.is_empty()).then_some((name, start))
3572}
3573
3574pub fn value_member_candidates(
3577 ty: TyId,
3578 tys: &Types,
3579 doc_text: &str,
3580 files: Option<&HashMap<PathBuf, String>>,
3581) -> Vec<Completion> {
3582 let mut out: Vec<Completion> = kernel_methods::methods_for(ty, tys)
3583 .iter()
3584 .map(|km| {
3585 Completion::item(
3586 km.name,
3587 CompletionKind::Member,
3588 Some(km.signature.to_string()),
3589 )
3590 })
3591 .collect();
3592 if matches!(&*tys.get(ty), Ty::Asset) {
3594 out.push(Completion::item(
3595 "url",
3596 CompletionKind::Field,
3597 Some("String — the URL the platform serves the asset at".to_string()),
3598 ));
3599 }
3600 if matches!(&*tys.get(ty), Ty::DecodeError) {
3603 for (name, doc) in [
3604 (
3605 "kind",
3606 "String — `Malformed`, `StructuralMismatch` or `RefinementViolation`",
3607 ),
3608 ("path", "String — where the decode failed, e.g. `$.qty`"),
3609 ("message", "String — a description of the failure"),
3610 ] {
3611 out.push(Completion::item(
3612 name,
3613 CompletionKind::Field,
3614 Some(doc.to_string()),
3615 ));
3616 }
3617 }
3618 if matches!(&*tys.get(ty), Ty::ValidationError) {
3620 for (name, doc) in [
3621 (
3622 "field",
3623 "String — the name of the refined type or field that failed validation",
3624 ),
3625 ("message", "String — a description of the failure"),
3626 ] {
3627 out.push(Completion::item(
3628 name,
3629 CompletionKind::Field,
3630 Some(doc.to_string()),
3631 ));
3632 }
3633 }
3634 if let Ty::Named { name, .. } = &*tys.get(ty) {
3636 let mut seen: BTreeSet<String> = BTreeSet::new();
3637 for_each_unit(doc_text, files, |unit| {
3638 let items = match unit {
3639 SourceUnit::Commons(c) => &c.items,
3640 SourceUnit::Context(c) => &c.items,
3641 SourceUnit::Adapter(a) => &a.items,
3642 _ => return,
3643 };
3644 for item in items {
3645 if let CommonsItem::Type(t) = item
3646 && &t.name.name == name
3647 && let TypeBody::Record(r) = &t.body
3648 {
3649 for f in &r.fields {
3650 if seen.insert(f.name.name.clone()) {
3651 out.push(
3652 Completion::item(
3653 f.name.name.clone(),
3654 CompletionKind::Field,
3655 Some(format!("field of `{name}`")),
3656 )
3657 .with_doc(f.documentation.as_deref()),
3658 );
3659 }
3660 }
3661 }
3662 }
3663 });
3664 }
3665 out
3666}
3667
3668pub fn run_id_member_candidates(rewritten: &str, recv_offset: usize) -> Vec<Completion> {
3673 let Some((name, start)) = ident_ending_at(rewritten, recv_offset + 1) else {
3674 return Vec::new();
3675 };
3676 if name != "run" || !crate::symbols::is_test_run_receiver(rewritten, start) {
3677 return Vec::new();
3678 }
3679 vec![
3680 Completion::item("id", CompletionKind::Field, Some("String".to_string()))
3681 .with_doc(Some(crate::symbols::RUN_ID_DOC)),
3682 ]
3683}
3684
3685pub fn store_field_member_candidates(
3700 rewritten: &str,
3701 recv_offset: usize,
3702 locals: &[LocalBinding],
3703) -> Vec<Completion> {
3704 let Some((kind_head, held)) =
3705 crate::symbols::store_field_kind_at(rewritten, recv_offset + 1, locals)
3706 else {
3707 return Vec::new();
3708 };
3709 let mut out: Vec<Completion> = store_ops::ops_for(&kind_head)
3710 .iter()
3711 .map(|o| {
3712 Completion::item(
3713 o.name,
3714 CompletionKind::Member,
3715 Some(o.signature.to_string()),
3716 )
3717 })
3718 .collect();
3719 if kind_head == "Map" && !held {
3720 out.extend(store_ops::MAP_QUERY_ACCESSORS.iter().map(|a| {
3721 Completion::item(a.name, CompletionKind::Field, Some(a.signature.to_string()))
3722 }));
3723 }
3724 out
3725}
3726
3727static EMPTY_CONSUMES: Vec<bynk_syntax::ast::ConsumesDecl> = Vec::new();
3728
3729#[cfg(test)]
3730mod tests {
3731 #[test]
3732 fn at_after_a_matches_refinement_offers_example() {
3733 let line = r#"type Code = String where Matches("[A-Z]{3}") @"#;
3734 assert!(in_refinement_annotation_position(line));
3735 let got = complete(line, line, None);
3736 assert_eq!(got.len(), 1);
3737 assert_eq!(got[0].label, "example");
3738 assert!(in_refinement_annotation_position(
3739 r#" code: String where IsoDate @ex"#
3740 ));
3741 assert!(!in_refinement_annotation_position(
3742 r#"type Sku = String where NonEmpty @"#
3743 ));
3744 assert!(!in_refinement_annotation_position(
3745 r#"type C = String where Matches("a") @example("a") @"#
3746 ));
3747 }
3748
3749 use super::*;
3750 use bynk_check::firstparty::BYNK_LIST_SRC;
3751
3752 #[test]
3755 fn completion_marks_experimental_items() {
3756 assert_eq!(stability_suffix(true), " — experimental");
3757 assert_eq!(stability_suffix(false), "");
3758 assert!(!experimental("bynk.cloudflare.Kv"));
3759 let caps = complete("consumes bynk.cloudflare { ", "context app.probe\n", None);
3760 let kv = caps
3761 .iter()
3762 .find(|c| c.label == "Kv")
3763 .expect("Kv is offered");
3764 assert_eq!(
3765 kv.detail.as_deref(),
3766 Some("capability exported by `bynk.cloudflare`")
3767 );
3768 }
3769
3770 fn labels(line: &str, doc: &str) -> Vec<String> {
3771 complete(line, doc, None)
3772 .into_iter()
3773 .map(|c| c.label)
3774 .collect()
3775 }
3776
3777 #[test]
3781 fn constraint_names_follow_a_bound_colon() {
3782 let doc = "commons m\n";
3783 let eq = |line: &str| {
3784 complete(line, doc, None)
3785 .into_iter()
3786 .filter(|c| c.kind == CompletionKind::Constraint)
3787 .map(|c| c.label)
3788 .collect::<Vec<_>>()
3789 };
3790 assert_eq!(eq("fn same[T: "), ["Eq", "Ord", "Key", "Codable"]);
3791 assert_eq!(eq("fn same[T: E"), ["Eq", "Ord", "Key", "Codable"]);
3792 assert_eq!(eq("fn same[T: Eq + "), ["Eq", "Ord", "Key", "Codable"]);
3793 assert_eq!(eq("fn same[A, T: "), ["Eq", "Ord", "Key", "Codable"]);
3794 assert_eq!(eq("type Pair[T: "), ["Eq", "Ord", "Key", "Codable"]);
3795 assert_eq!(
3796 eq("fn Box.has(self, x: A) -> Bool where A: "),
3797 ["Eq", "Ord", "Key", "Codable"]
3798 );
3799 assert_eq!(
3800 eq("fn f(self) -> Int where A: Eq, B: "),
3801 ["Eq", "Ord", "Key", "Codable"]
3802 );
3803 assert!(eq("fn f(x: ").is_empty());
3805 assert!(eq("fn f(x: Int) -> ").is_empty());
3806 assert!(eq("type Age = Int where ").is_empty());
3807 assert!(eq("fn f[T](x: ").is_empty());
3808 assert_eq!(eq("type P = { a: Int } derives "), ["Ord"]);
3810 }
3811
3812 fn labels_of(line: &str, doc: &str) -> Vec<String> {
3813 complete(line, doc, None)
3814 .into_iter()
3815 .map(|c| c.label)
3816 .collect()
3817 }
3818
3819 #[test]
3822 fn derives_follows_a_type_body() {
3823 let doc = "commons m\n";
3824 for line in [
3825 "type P = { a: Int } ",
3826 "type P = { a: Int } de",
3827 "type E = enum { A, B } ",
3828 "type E = A | B(x: Int) ",
3829 "type Age = Int ",
3830 "type Age = Int where self >= 0 ",
3831 "type Id = opaque Int ",
3832 "type Box[T: Ord] = { v: T } ",
3833 ] {
3834 assert!(
3835 labels_of(line, doc).contains(&"derives".to_string()),
3836 "{line:?}"
3837 );
3838 }
3839 let open = "commons m\n\ntype P = {\n a: Int\n}\n";
3841 assert!(labels_of("} ", open).contains(&"derives".to_string()));
3842 for line in [
3844 "type P = ",
3845 "type E = A | ",
3846 "type Age = Int where ",
3847 "type P = { a: Int } derives Ord ",
3848 "fn f() -> Int { 1 } ",
3849 ] {
3850 assert!(
3851 !labels_of(line, doc).contains(&"derives".to_string()),
3852 "{line:?}"
3853 );
3854 }
3855 assert!(!labels_of("} ", doc).contains(&"derives".to_string()));
3856 }
3857
3858 #[test]
3861 fn derives_list_offers_only_ord() {
3862 let doc = "commons m\n";
3863 for line in [
3864 "type P = { a: Int } derives ",
3865 "type P = { a: Int } derives O",
3866 "type P = { a: Int } derives Ord + ",
3867 "} derives ",
3868 ] {
3869 assert_eq!(labels_of(line, doc), ["Ord"], "{line:?}");
3870 }
3871 assert!(!labels_of("type P = { a: Int } derives Ord ", doc).contains(&"Ord".to_string()));
3872 assert!(labels_of("let derives = ", doc).iter().all(|l| l != "Ord"));
3873 }
3874
3875 #[test]
3879 fn constraint_names_match_the_checker() {
3880 for c in constraint_candidates() {
3881 let src = format!("commons m\n\nfn f[T: {}](x: T) -> T {{ x }}\n", c.label);
3882 assert!(crate::diagnose(&src).is_empty(), "{}", c.label);
3883 }
3884 let bad = crate::diagnose("commons m\n\nfn f[T: Nope](x: T) -> T { x }\n");
3885 let note = format!("{:?}", bad[0].error);
3886 for c in constraint_candidates() {
3887 assert!(note.contains(&c.label), "{note}");
3888 }
3889 }
3890
3891 #[test]
3892 fn consumes_target_suggests_units_including_bynk() {
3893 let doc = "adapter tokens {\n binding \"./b.ts\"\n capability Jwt { fn f() -> Effect[Int] }\n provides Jwt = X\n}\n";
3895 let got = labels(" consumes ", doc);
3896 assert!(got.contains(&"bynk".to_string()), "{got:?}");
3897 assert!(got.contains(&"tokens".to_string()), "{got:?}");
3898 }
3899
3900 #[test]
3901 fn consumes_brace_suggests_that_units_capabilities() {
3902 let got = labels(" consumes bynk { ", "context a.b\n");
3903 assert!(got.contains(&"Clock".to_string()), "{got:?}");
3905 assert!(got.contains(&"Random".to_string()), "{got:?}");
3906 assert!(got.contains(&"Logger".to_string()), "{got:?}");
3907 }
3908
3909 #[test]
3912 fn a_fn_given_suggests_capabilities() {
3913 let doc = "context a.b\n\
3914 consumes bynk { Clock }\n\
3915 capability Local { fn f() -> Effect[Int] }\n\
3916 fn step() -> Effect[Int] given Clock {\n\
3917 Clock.now()\n\
3918 }\n";
3919 let got = labels("fn step() -> Effect[Int] given ", doc);
3920 assert!(got.contains(&"Clock".to_string()), "flattened: {got:?}");
3921 assert!(got.contains(&"Local".to_string()), "local: {got:?}");
3922 }
3923
3924 #[test]
3925 fn given_suggests_local_and_flattened_capabilities() {
3926 let doc = "context a.b\n\
3927 consumes bynk { Clock }\n\
3928 capability Local { fn f() -> Effect[Int] }\n\
3929 service s {\n\
3930 on call() -> Effect[Int] by Caller given Clock {\n\
3931 1\n\
3932 }\n\
3933 }\n";
3934 let got = labels(" on call() -> Effect[Int] by Caller given ", doc);
3935 assert!(got.contains(&"Clock".to_string()), "flattened: {got:?}");
3936 assert!(got.contains(&"Local".to_string()), "local: {got:?}");
3937 }
3938
3939 #[test]
3940 fn expression_position_offers_constructors_and_types() {
3941 let doc = "commons m {\n type Order = { id: Int }\n}\n";
3946 let items = complete(" let x = ", doc, None);
3947 for &c in CONSTRUCTORS {
3948 assert!(
3949 find(&items, c, CompletionKind::Constructor).is_some(),
3950 "constructor {c}: {:?}",
3951 items.iter().map(|i| &i.label).collect::<Vec<_>>()
3952 );
3953 }
3954 assert!(
3955 find(&items, "Int", CompletionKind::Type).is_some(),
3956 "builtin type"
3957 );
3958 assert!(
3959 find(&items, "Order", CompletionKind::Type).is_some(),
3960 "project type"
3961 );
3962 }
3963
3964 #[test]
3965 fn expression_position_offers_the_fault_builtins_unless_shadowed() {
3966 let doc = "commons m {\n fn todo(s: String) -> Int { 1 }\n}\n";
3969 let items = complete(" let x = ", doc, None);
3970 assert!(
3971 find(&items, "unreachable", CompletionKind::Function).is_some(),
3972 "unreachable offered"
3973 );
3974 assert_eq!(
3975 items.iter().filter(|i| i.label == "todo").count(),
3976 1,
3977 "the user's `todo` shadows the built-in"
3978 );
3979 }
3980
3981 #[test]
3982 fn value_receiver_and_decimal_are_not_expression_positions() {
3983 assert!(complete(" let p = q.", "context a.b\n", None).is_empty());
3988 let units = complete(" let n = 1.", "context a.b\n", None);
3989 assert!(
3990 units
3991 .iter()
3992 .all(|c| c.detail.as_deref() == Some("`Duration` unit"))
3993 );
3994 assert_eq!(units.len(), 5);
3995 }
3996
3997 fn free_fn_names(src: &str) -> Vec<String> {
3999 let tokens = lexer::tokenize(src).unwrap();
4000 let (unit, _) = parser::parse_unit_with_recovery(&tokens, src);
4001 let unit = unit.unwrap();
4002 let (items, _) = unit_items_and_uses(&unit);
4003 items
4004 .iter()
4005 .filter_map(|it| match it {
4006 CommonsItem::Fn(f) => match &f.name {
4007 FnName::Free(id) => Some(id.name.clone()),
4008 FnName::Method { .. } => None,
4009 },
4010 _ => None,
4011 })
4012 .collect()
4013 }
4014
4015 #[test]
4016 fn free_functions_offered_for_own_unit_and_used_modules() {
4017 let doc = "commons app {\n uses bynk.list\n fn helper(x: Int) -> Int { x }\n}\n";
4020 let items = complete(" let y = ", doc, None);
4021 assert!(
4023 find(&items, "helper", CompletionKind::Function).is_some(),
4024 "own fn: {:?}",
4025 items.iter().map(|i| &i.label).collect::<Vec<_>>()
4026 );
4027 for name in free_fn_names(BYNK_LIST_SRC) {
4030 assert!(
4031 find(&items, &name, CompletionKind::Function).is_some(),
4032 "bynk.list.{name}: {:?}",
4033 items.iter().map(|i| &i.label).collect::<Vec<_>>()
4034 );
4035 }
4036 assert!(
4038 find(&items, "values", CompletionKind::Function).is_none(),
4039 "bynk.map.values leaked without `uses bynk.map`"
4040 );
4041 }
4042
4043 #[test]
4044 fn locale_functions_offered_when_bynk_locale_is_used() {
4045 let doc = "commons app {\n uses bynk.locale\n}\n";
4050 let items = complete(" let y = ", doc, None);
4051 for name in [
4052 "render",
4053 "message",
4054 "withText",
4055 "withWhole",
4056 "withNum",
4057 "withMoment",
4058 ] {
4059 assert!(
4060 find(&items, name, CompletionKind::Function).is_some(),
4061 "bynk.locale.{name} missing from completion: {:?}",
4062 items.iter().map(|i| &i.label).collect::<Vec<_>>()
4063 );
4064 }
4065 }
4066
4067 #[test]
4068 fn free_functions_require_a_uses_import() {
4069 let doc = "commons app {\n fn helper(x: Int) -> Int { x }\n}\n";
4071 let items = complete(" let y = ", doc, None);
4072 assert!(find(&items, "helper", CompletionKind::Function).is_some());
4073 for name in ["map", "filter", "reverse"] {
4074 assert!(
4075 find(&items, name, CompletionKind::Function).is_none(),
4076 "bynk.list.{name} offered without `uses bynk.list`"
4077 );
4078 }
4079 }
4080
4081 #[test]
4082 fn another_units_private_items_are_not_offered() {
4083 let doc = "commons app {\n uses lib\n private fn mine() -> Int { 1 }\n}\n";
4087 let mut files = HashMap::new();
4088 files.insert(
4089 PathBuf::from("/p/lib.bynk"),
4090 "commons lib {\n fn open() -> Int { 1 }\n private fn hidden() -> Int { 2 }\n private asset secret = \"s.css\"\n type Shown = Int\n private type Kept = Int\n private const Limit: Int = 3\n const Cap: Int = 4\n}\n"
4091 .to_string(),
4092 );
4093 let items = complete(" let y = ", doc, Some(&files));
4094 let labels = || items.iter().map(|i| &i.label).collect::<Vec<_>>();
4095 assert!(
4096 find(&items, "open", CompletionKind::Function).is_some(),
4097 "{:?}",
4098 labels()
4099 );
4100 assert!(
4101 find(&items, "mine", CompletionKind::Function).is_some(),
4102 "{:?}",
4103 labels()
4104 );
4105 assert!(
4106 find(&items, "Shown", CompletionKind::Type).is_some(),
4107 "{:?}",
4108 labels()
4109 );
4110 assert!(items.iter().any(|i| i.label == "Cap"), "{:?}", labels());
4111 for hidden in ["hidden", "secret", "Kept", "Limit"] {
4112 assert!(
4113 !items.iter().any(|i| i.label == hidden),
4114 "a used unit's private `{hidden}` leaked: {:?}",
4115 labels()
4116 );
4117 }
4118 }
4119
4120 #[test]
4121 fn assets_offered_by_the_free_function_scope_rule() {
4122 let doc = "context app.page {\n uses app.shared\n asset logo = \"logo.svg\"\n asset icon = \"favicon.ico\" at \"/favicon.ico\"\n}\n";
4126 let mut files = HashMap::new();
4127 files.insert(
4128 PathBuf::from("/p/shared.bynk"),
4129 "context app.shared {\n --- The site stylesheet.\n asset style = \"site.css\"\n}\n"
4130 .to_string(),
4131 );
4132 files.insert(
4133 PathBuf::from("/p/other.bynk"),
4134 "context app.other {\n asset banner = \"banner.png\"\n}\n".to_string(),
4135 );
4136 let items = complete(" let y = ", doc, Some(&files));
4137 let labels = || items.iter().map(|i| &i.label).collect::<Vec<_>>();
4138 let logo = find(&items, "logo", CompletionKind::Constant);
4139 assert!(logo.is_some(), "own asset: {:?}", labels());
4140 assert_eq!(
4141 logo.unwrap().detail.as_deref(),
4142 Some("asset logo = \"logo.svg\" — `this unit`")
4143 );
4144 assert_eq!(
4145 find(&items, "icon", CompletionKind::Constant).and_then(|c| c.detail.as_deref()),
4146 Some("asset icon = \"favicon.ico\" at \"/favicon.ico\" — `this unit`")
4147 );
4148 let style = find(&items, "style", CompletionKind::Constant);
4149 assert!(style.is_some(), "used unit's asset: {:?}", labels());
4150 assert_eq!(
4151 style.unwrap().documentation.as_deref(),
4152 Some("The site stylesheet.")
4153 );
4154 assert!(
4155 find(&items, "banner", CompletionKind::Constant).is_none(),
4156 "an asset of a unit not in `uses` leaked: {:?}",
4157 labels()
4158 );
4159 }
4160
4161 #[test]
4162 fn embeds_offered_by_the_free_function_scope_rule() {
4163 let doc =
4167 "context app.page {\n uses app.shared\n embed shell = \"embeds/shell.html\"\n}\n";
4168 let mut files = HashMap::new();
4169 files.insert(
4170 PathBuf::from("/p/shared.bynk"),
4171 "commons app.shared {\n --| The mail body.\n embed mail = \"embeds/mail.txt\"\n}\n"
4172 .to_string(),
4173 );
4174 files.insert(
4175 PathBuf::from("/p/other.bynk"),
4176 "context app.other {\n embed hidden = \"embeds/hidden.txt\"\n}\n".to_string(),
4177 );
4178 let items = complete(" let y = ", doc, Some(&files));
4179 let labels = || items.iter().map(|i| &i.label).collect::<Vec<_>>();
4180 assert_eq!(
4181 find(&items, "shell", CompletionKind::Constant).and_then(|c| c.detail.as_deref()),
4182 Some("embed shell = \"embeds/shell.html\" — `this unit`"),
4183 "own embed: {:?}",
4184 labels()
4185 );
4186 let mail = find(&items, "mail", CompletionKind::Constant);
4187 assert!(mail.is_some(), "used unit's embed: {:?}", labels());
4188 assert_eq!(
4189 mail.unwrap().documentation.as_deref(),
4190 Some("The mail body.")
4191 );
4192 assert!(
4193 find(&items, "hidden", CompletionKind::Constant).is_none(),
4194 "an embed of a unit not in `uses` leaked: {:?}",
4195 labels()
4196 );
4197 }
4198
4199 #[test]
4200 fn asset_member_completion_offers_url() {
4201 let asset = TYS.intern(Ty::Asset);
4203 let items = value_member_candidates(asset, &TYS, "context a.b\n", None);
4204 assert!(find(&items, "url", CompletionKind::Field).is_some());
4205 }
4206
4207 #[test]
4208 fn member_completion_reaches_inside_an_interpolation_hole() {
4209 let doc = "context a.b\n capability Timer { fn now() -> Effect[Int] }\n";
4213 let in_hole = complete(" \"the time is \\(Timer.", doc, None);
4214 assert!(
4215 find(&in_hole, "now", CompletionKind::Member).is_some(),
4216 "capability op not offered inside a hole: {:?}",
4217 in_hole.iter().map(|c| &c.label).collect::<Vec<_>>()
4218 );
4219 let statics = complete(" \"n=\\(Int.", "context a.b\n", None);
4221 assert!(find(&statics, "parse", CompletionKind::Member).is_some());
4222 }
4223
4224 #[test]
4225 fn consumes_brace_alias_position_suggests_nothing() {
4226 for prefix in [
4228 " consumes bynk.crypto { Crypto, Digest as ",
4229 " consumes bynk.crypto { Crypto, Digest as Cry",
4230 ] {
4231 let got = labels(prefix, "context a.b\n");
4232 assert!(got.is_empty(), "{prefix}: {got:?}");
4233 }
4234 assert!(
4236 !labels(" consumes bynk { Clock, ", "context a.b\n").is_empty(),
4237 "capabilities still complete after a comma"
4238 );
4239 }
4240
4241 #[test]
4242 fn consumes_with_as_is_not_a_target_completion() {
4243 assert!(!is_consumes_target("consumes platform.time as "));
4245 assert!(is_consumes_target("consumes platform"));
4246 }
4247
4248 fn find<'a>(
4249 items: &'a [Completion],
4250 label: &str,
4251 kind: CompletionKind,
4252 ) -> Option<&'a Completion> {
4253 items.iter().find(|c| c.label == label && c.kind == kind)
4254 }
4255
4256 #[test]
4257 fn type_annotation_suggests_builtins_surface_and_project_types() {
4258 let doc = "commons m {\n type Order = { id: Int }\n}\n";
4259 let got = labels(" let x: ", doc);
4260 for want in ["Int", "Option", "Result", "Effect", "List", "Map"] {
4263 assert!(got.contains(&want.to_string()), "built-in {want}: {got:?}");
4264 }
4265 assert!(got.contains(&"Uuid".to_string()), "surface: {got:?}");
4266 assert!(got.contains(&"Order".to_string()), "project: {got:?}");
4267 }
4268
4269 #[test]
4270 fn return_type_and_type_args_are_type_positions() {
4271 assert!(is_type_position(" on call() -> "));
4272 assert!(is_type_position(" let x: Option["));
4273 assert!(is_type_position(" let x: Result[Int, "));
4274 assert!(is_type_position(" -> Eff"));
4276 }
4277
4278 #[test]
4279 fn list_literal_is_not_a_type_position() {
4280 assert!(!is_type_position(" let xs = ["));
4282 let items = complete(" let xs = [", "context a.b\n", None);
4286 assert!(
4287 find(&items, "Some", CompletionKind::Constructor).is_some(),
4288 "{:?}",
4289 items.iter().map(|c| &c.label).collect::<Vec<_>>()
4290 );
4291 }
4292
4293 #[test]
4294 fn builtin_type_carries_its_registry_doc() {
4295 let items = complete(" let x: ", "context a.b\n", None);
4296 let int = find(&items, "Int", CompletionKind::Type).expect("Int present");
4297 assert_eq!(int.detail.as_deref(), keyword_doc("Int"));
4298 assert!(int.detail.is_some(), "Int should have a doc");
4299 }
4300
4301 #[test]
4302 fn keyword_position_suggests_keywords_and_snippets() {
4303 let items = complete(" ", "context a.b\n", None);
4304 assert!(find(&items, "capability", CompletionKind::Keyword).is_some());
4306 assert!(find(&items, "fn", CompletionKind::Keyword).is_some());
4307 assert!(find(&items, "let", CompletionKind::Keyword).is_some());
4308 assert!(find(&items, "Int", CompletionKind::Keyword).is_none());
4310 assert!(find(&items, "Some", CompletionKind::Keyword).is_none());
4311 let snip = find(&items, "service", CompletionKind::Snippet).expect("service snippet");
4313 let body = snip.insert_text.as_deref().unwrap_or("");
4314 assert!(body.contains("on call"), "snippet body: {body:?}");
4315 assert!(body.contains("${1"), "snippet tab stop: {body:?}");
4316 }
4317
4318 #[test]
4319 fn keyword_position_fires_on_an_empty_line() {
4320 assert!(is_keyword_position(""));
4321 assert!(is_keyword_position(" cap"));
4322 assert!(!is_keyword_position(" let x ="));
4323 assert!(!is_keyword_position(" x: "));
4324 assert!(!complete("", "context a.b\n", None).is_empty());
4325 }
4326
4327 #[test]
4328 fn a_cookie_record_completes_its_fields_then_cookie_and_expire() {
4329 let src = "context a.b\n\
4330 type Theme = enum { Light, Dark }\n\
4331 type Prefs = { theme: Theme = Light, @name(\"__Host-visits\") visits: Option[Int] }\n\
4332 service s from http {\n\
4333 on GET(\"/p\") (cookies: Prefs) -> Effect[HttpResult[String]] by v: Visitor { Ok(\"x\") }\n\
4334 }\n";
4335 let fields = complete(" Ok(\"x\").withCookie(Prefs.", src, None);
4336 let theme = complete(" Theme.", src, None);
4338 assert!(find(&theme, "Dark", CompletionKind::Variant).is_some());
4339 assert!(find(&fields, "theme", CompletionKind::Field).is_some());
4340 assert!(find(&fields, "visits", CompletionKind::Field).is_some());
4341 let members = complete(" Ok(\"x\").withCookie(Prefs.visits.", src, None);
4342 let cookie = find(&members, "cookie", CompletionKind::Member).expect("cookie");
4343 assert!(
4344 cookie
4345 .detail
4346 .as_deref()
4347 .unwrap_or("")
4348 .contains("value: Int"),
4349 "{:?}",
4350 cookie.detail
4351 );
4352 assert!(
4353 cookie
4354 .detail
4355 .as_deref()
4356 .unwrap_or("")
4357 .contains("__Host-visits"),
4358 "{:?}",
4359 cookie.detail
4360 );
4361 assert!(find(&members, "expire", CompletionKind::Member).is_some());
4362 let plain = "context a.b\ntype P = { x: Int }\n";
4364 assert!(complete(" P.x.", plain, None).is_empty());
4365 }
4366
4367 #[test]
4368 fn member_receiver_is_a_single_upper_ident_before_a_dot() {
4369 assert_eq!(member_receiver(" Color."), Some("Color".to_string()));
4370 assert_eq!(
4371 member_receiver(" let e = Email.o"),
4372 Some("Email".to_string())
4373 );
4374 assert_eq!(member_receiver(" x."), None); assert_eq!(member_receiver(" 1."), None); assert_eq!(member_receiver(" a.B."), None); assert_eq!(member_receiver(" Color"), None); }
4379
4380 #[test]
4381 fn receiver_extraction_survives_a_multibyte_char_before_the_receiver() {
4382 assert_eq!(member_receiver("\"Foo."), Some("Foo".to_string()));
4386 assert_eq!(member_receiver("€Color."), Some("Color".to_string()));
4387 assert_eq!(member_receiver("—Bar."), Some("Bar".to_string()));
4388 assert_eq!(word_before_brace("\"cors {", 6), "cors");
4389 assert_eq!(
4390 record_construction_receiver("\"€Order {"),
4391 Some("Order".to_string())
4392 );
4393 let _ = complete("let x = \"Foo.", "commons m {}\n", None);
4396 let _ = complete(" \"€42.", "commons m {}\n", None);
4397 assert_eq!(
4398 value_receiver_rewrite("\"email.", 7).map(|(_, r)| r),
4399 Some(5),
4400 );
4401 }
4402
4403 #[test]
4404 fn sum_member_suggests_variants() {
4405 let doc = "commons m {\n type Color = enum { Red, Green, Blue }\n}\n";
4406 let items = complete(" let c = Color.", doc, None);
4407 for v in ["Red", "Green", "Blue"] {
4408 assert!(
4409 find(&items, v, CompletionKind::Variant).is_some(),
4410 "variant {v}: {:?}",
4411 items.iter().map(|c| &c.label).collect::<Vec<_>>()
4412 );
4413 }
4414 }
4415
4416 #[test]
4417 fn refined_and_plain_alias_members_are_of_and_unsafe() {
4418 let doc = "commons m {\n type Email = String where NonEmpty\n}\n";
4420 let items = complete(" Email.", doc, None);
4421 assert!(find(&items, "of", CompletionKind::Member).is_some());
4422 assert!(find(&items, "unsafe", CompletionKind::Member).is_some());
4423 let doc = "commons m {\n type Id = Int\n}\n";
4426 assert!(find(&complete(" Id.", doc, None), "of", CompletionKind::Member).is_some());
4427 }
4428
4429 #[test]
4430 fn auth_completes_the_schemes_and_a_signed_cookie_its_keys() {
4431 let schemes = complete("actor User { auth = Sig", "context a.b\n", None);
4432 assert!(find(&schemes, "SignedCookie", CompletionKind::Keyword).is_some());
4433 assert!(find(&schemes, "Bearer", CompletionKind::Keyword).is_some());
4434 let keys = complete(
4435 "actor User { auth = SignedCookie(secret = \"K\", ",
4436 "context a.b\n",
4437 None,
4438 );
4439 assert!(find(&keys, "ttl", CompletionKind::Field).is_some());
4440 assert!(
4441 find(&keys, "secret", CompletionKind::Field).is_none(),
4442 "already written"
4443 );
4444 let value = complete(
4445 "actor User { auth = SignedCookie(ttl = ",
4446 "context a.b\n",
4447 None,
4448 );
4449 assert!(value.is_empty());
4450 assert!(!auth_scheme_position(
4452 "actor User { auth = Bearer(secret = \"K\"), identity = "
4453 ));
4454 }
4455
4456 #[test]
4457 fn a_signed_cookie_actor_offers_issue_and_expire() {
4458 let doc = "context a.b\n\ntype UserId = String where NonEmpty\n\nactor User { auth = SignedCookie(secret = \"K\", ttl = 1.hour), identity = UserId }\n";
4459 let items = complete(" User.", doc, None);
4460 let issue = find(&items, "issue", CompletionKind::Member).expect("`issue` offered");
4461 assert_eq!(
4462 issue.detail.as_deref(),
4463 Some("issue(identity: UserId) -> Effect[Cookie] — session cookie of `User`")
4464 );
4465 assert!(find(&items, "expire", CompletionKind::Member).is_some());
4466 let doc =
4468 "context a.b\n\nactor Admin { auth = Bearer(secret = \"K\"), identity = String }\n";
4469 assert!(
4470 find(
4471 &complete(" Admin.", doc, None),
4472 "issue",
4473 CompletionKind::Member
4474 )
4475 .is_none()
4476 );
4477 }
4478
4479 #[test]
4480 fn capability_member_suggests_ops() {
4481 let doc = "context a.b\n capability Timer { fn now() -> Effect[Int]\n fn at(t: Int) -> Effect[()] }\n";
4482 let items = complete(" Timer.", doc, None);
4483 let now = find(&items, "now", CompletionKind::Member).expect("`now` op offered");
4484 assert_eq!(
4487 now.detail.as_deref(),
4488 Some("now() -> Effect[Int] — operation of `Timer`")
4489 );
4490 let at = find(&items, "at", CompletionKind::Member).expect("`at` op offered");
4491 assert_eq!(
4492 at.detail.as_deref(),
4493 Some("at(t: Int) -> Effect[()] — operation of `Timer`")
4494 );
4495 }
4496
4497 #[test]
4499 fn a_derived_d1_offers_the_typed_reads() {
4500 let doc = "context a.b\n\nconsumes bynk.cloudflare { D1 }\n\ncapability Orders = D1\n";
4501 let items = complete(" Orders.", doc, None);
4502 for op in ["select", "firstAs", "all", "first"] {
4503 assert!(
4504 find(&items, op, CompletionKind::Member).is_some(),
4505 "`{op}` offered"
4506 );
4507 }
4508 }
4509
4510 #[test]
4512 fn the_d1_name_offers_peek() {
4513 let doc = "suite a.b as system {\n case \"c\" {\n let db = D1.\n }\n}\n";
4514 let items = complete(" let db = D1.", doc, None);
4515 let peek = find(&items, "peek", CompletionKind::Member).expect("`peek` offered");
4516 assert_eq!(peek.detail.as_deref(), Some(D1_PEEK_SIGNATURE));
4517 }
4518
4519 #[test]
4522 fn a_derived_postgres_offers_the_typed_reads_and_transaction() {
4523 let doc =
4524 "context a.b\n\nconsumes bynk.cloudflare { Postgres }\n\ncapability Main = Postgres\n";
4525 let items = complete(" Main.", doc, None);
4526 for op in ["select", "firstAs", "transaction", "all", "first", "run"] {
4527 assert!(
4528 find(&items, op, CompletionKind::Member).is_some(),
4529 "`{op}` offered"
4530 );
4531 }
4532 let select = find(&items, "select", CompletionKind::Member).expect("`select`");
4533 assert!(
4534 select
4535 .detail
4536 .as_deref()
4537 .is_some_and(|d| d.contains("PgReadError")),
4538 "{:?}",
4539 select.detail
4540 );
4541 }
4542
4543 #[test]
4544 fn statics_of_a_generic_type_are_offered() {
4545 let doc = "commons a.b
4548
4549type Box[T] = { value: T }
4550
4551fn Box.of(value: T) -> Box[T] { Box { value } }
4552
4553fn Box.size(self) -> Int { 1 }
4554";
4555 let items = complete(" Box.", doc, None);
4556 let of = find(&items, "of", CompletionKind::Member).expect("`of` offered");
4557 assert_eq!(of.detail.as_deref(), Some("of(value: T) -> Box[T]"));
4558 assert!(find(&items, "size", CompletionKind::Member).is_none());
4559 }
4560
4561 #[test]
4562 fn builtin_type_statics_are_offered() {
4563 assert!(
4564 find(
4565 &complete(" Int.", "context a.b\n", None),
4566 "parse",
4567 CompletionKind::Member
4568 )
4569 .is_some()
4570 );
4571 let j = complete(" Json.", "context a.b\n", None);
4572 assert!(find(&j, "encode", CompletionKind::Member).is_some());
4573 assert!(find(&j, "decode", CompletionKind::Member).is_some());
4574 let y = complete(" Yaml.", "context a.b\n", None);
4576 assert!(find(&y, "decode", CompletionKind::Member).is_some());
4577 assert!(find(&y, "encode", CompletionKind::Member).is_none());
4578 }
4579
4580 #[test]
4581 fn decimal_statics_and_rounding_modes_are_offered() {
4582 let d = complete(" Decimal.", "context a.b\n", None);
4584 assert!(find(&d, "parse", CompletionKind::Member).is_some());
4585 assert!(find(&d, "fromInt", CompletionKind::Member).is_some());
4586 let r = complete(" RoundingMode.", "context a.b\n", None);
4587 for mode in bynk_syntax::ast::RoundingMode::ALL {
4588 assert!(
4589 find(&r, mode.name(), CompletionKind::Member).is_some(),
4590 "RoundingMode.{} missing",
4591 mode.name()
4592 );
4593 }
4594 }
4595
4596 #[test]
4597 fn builtin_sum_variants_are_complete() {
4598 let http: Vec<&str> = bynk_syntax::ast::HTTP_VARIANTS
4603 .iter()
4604 .map(|v| v.name)
4605 .collect();
4606 let queue: Vec<&str> = bynk_syntax::ast::QUEUE_VARIANTS
4607 .iter()
4608 .map(|v| v.name)
4609 .collect();
4610 for (recv, names) in [("HttpResult", http), ("QueueResult", queue)] {
4611 let items = complete(&format!(" {recv}."), "context a.b\n", None);
4612 for name in names {
4613 assert!(
4614 find(&items, name, CompletionKind::Variant).is_some(),
4615 "{recv}.{name} missing: {:?}",
4616 items.iter().map(|c| &c.label).collect::<Vec<_>>()
4617 );
4618 }
4619 }
4620 }
4621
4622 #[test]
4623 fn builtin_statics_are_reachable() {
4624 for &(recv, members) in BUILTIN_STATICS {
4628 let items = complete(&format!(" {recv}."), "context a.b\n", None);
4629 for &(member, _) in members {
4630 assert!(
4631 find(&items, member, CompletionKind::Member).is_some(),
4632 "{recv}.{member} unreachable: {:?}",
4633 items.iter().map(|c| &c.label).collect::<Vec<_>>()
4634 );
4635 }
4636 }
4637 for (recv, member) in [("List", "empty"), ("Map", "empty"), ("Effect", "pure")] {
4640 let items = complete(&format!(" {recv}."), "context a.b\n", None);
4641 assert!(
4642 find(&items, member, CompletionKind::Member).is_some(),
4643 "{recv}.{member} missing from the statics table"
4644 );
4645 }
4646 }
4647
4648 #[test]
4649 fn record_value_and_decimal_receivers_yield_nothing() {
4650 let doc = "commons m {\n type Point = { x: Int }\n}\n";
4652 assert!(complete(" Point.", doc, None).is_empty(), "record");
4653 assert!(complete(" let p = q.", doc, None).is_empty(), "value");
4655 let units: Vec<_> = complete(" let n = 1.", doc, None)
4657 .into_iter()
4658 .map(|c| c.label)
4659 .collect();
4660 assert_eq!(units, ["millisecond", "second", "minute", "hour", "day"]);
4661 }
4662
4663 #[test]
4664 fn value_receiver_rewrite_drops_the_dot_for_lowercase_receivers() {
4665 let text = " let x = email.\n";
4666 let offset = text.find('.').unwrap() + 1; let (rewritten, recv) = value_receiver_rewrite(text, offset).expect("value receiver");
4668 assert_eq!(
4669 rewritten, " let x = email\n",
4670 "the trailing dot is dropped"
4671 );
4672 assert!(
4673 text.get(recv..=recv).is_some_and(|c| c == "l"),
4674 "the receiver offset lands inside `email`"
4675 );
4676 let text2 = " let x = email.ma\n";
4678 let off2 = text2.find(".ma").unwrap() + 3;
4679 assert_eq!(
4680 value_receiver_rewrite(text2, off2).map(|(r, _)| r),
4681 Some(" let x = email\n".to_string())
4682 );
4683 assert!(value_receiver_rewrite(" Email.", 8).is_none());
4685 assert!(value_receiver_rewrite(" let n = 1.", 12).is_none());
4686 assert!(value_receiver_rewrite(" email", 7).is_none());
4687 }
4688
4689 static TYS: std::sync::LazyLock<Types> = std::sync::LazyLock::new(Types::new);
4693
4694 #[test]
4697 fn run_member_offers_id_in_a_case_body() {
4698 let labels = |text: &str| {
4699 let offset = text.find("run.").expect("run.") + "run.".len();
4700 let (rewritten, recv) = value_receiver_rewrite(text, offset).expect("a value receiver");
4701 run_id_member_candidates(&rewritten, recv)
4702 .into_iter()
4703 .map(|c| c.label)
4704 .collect::<Vec<_>>()
4705 };
4706 assert_eq!(
4707 labels("suite rid.orders {\n case \"a\" {\n expect run. == \"local\"\n }\n}\n"),
4708 ["id"]
4709 );
4710 assert!(
4711 labels("suite rid.orders {\n case \"a\" {\n let run = 1\n expect run. == 1\n }\n}\n")
4712 .is_empty()
4713 );
4714 }
4715
4716 #[test]
4717 fn value_member_candidates_lists_kernel_methods() {
4718 use bynk_syntax::ast::BaseType;
4719 let list = TYS.intern(Ty::List(TYS.intern(Ty::Base(BaseType::Int))));
4720 let items = value_member_candidates(list, &TYS, "context a.b\n", None);
4721 assert!(find(&items, "fold", CompletionKind::Member).is_some());
4722 assert!(find(&items, "get", CompletionKind::Member).is_some());
4723
4724 let string = TYS.intern(Ty::Base(BaseType::String));
4725 let items = value_member_candidates(string, &TYS, "context a.b\n", None);
4726 assert!(find(&items, "split", CompletionKind::Member).is_some());
4727 assert!(find(&items, "trim", CompletionKind::Member).is_some());
4728 }
4729
4730 #[test]
4733 fn value_member_candidates_offers_within_on_any_effect() {
4734 use bynk_syntax::ast::BaseType;
4735 let int = TYS.intern(Ty::Base(BaseType::Int));
4736 let plain = TYS.intern(Ty::Effect(int));
4737 let items = value_member_candidates(plain, &TYS, "context a.b\n", None);
4738 let within = find(&items, "within", CompletionKind::Member).expect("within is offered");
4739 assert_eq!(
4740 within.detail.as_deref(),
4741 Some("within(d: Duration) -> Effect[Result[T, TimedOut]]")
4742 );
4743 assert!(find(&items, "mapOk", CompletionKind::Member).is_none());
4744 let race = find(&items, "race", CompletionKind::Member).expect("race is offered");
4746 assert_eq!(
4747 race.detail.as_deref(),
4748 Some("race(other: Effect[T]) -> Effect[T]")
4749 );
4750
4751 let detach = find(&items, "detach", CompletionKind::Member).expect("detach is offered");
4753 assert_eq!(detach.detail.as_deref(), Some("detach() -> Effect[()]"));
4754
4755 let result = TYS.intern(Ty::Result(int, int));
4756 let fallible = TYS.intern(Ty::Effect(result));
4757 let items = value_member_candidates(fallible, &TYS, "context a.b\n", None);
4758 assert!(find(&items, "detach", CompletionKind::Member).is_some());
4759 assert!(find(&items, "within", CompletionKind::Member).is_some());
4760 assert!(find(&items, "race", CompletionKind::Member).is_some());
4761 assert!(find(&items, "mapOk", CompletionKind::Member).is_some());
4762 }
4763
4764 #[test]
4765 fn value_member_candidates_lists_refined_inherited_kernel_methods() {
4766 use bynk_check::checker::NamedKind;
4769 use bynk_syntax::ast::BaseType;
4770 let name = TYS.intern(Ty::Named {
4771 name: "Name".to_string(),
4772 kind: NamedKind::Refined(BaseType::String),
4773 args: Vec::new(),
4774 });
4775 let items = value_member_candidates(
4776 name,
4777 &TYS,
4778 "commons m {\n type Name = String where NonEmpty\n}\n",
4779 None,
4780 );
4781 assert!(find(&items, "toUpper", CompletionKind::Member).is_some());
4782 assert!(find(&items, "length", CompletionKind::Member).is_some());
4783 }
4784
4785 #[test]
4786 fn expression_position_offers_locals() {
4787 assert!(is_expression_position(" let y = "));
4789 assert!(is_expression_position(" let y = a + lo")); assert!(is_expression_position(" f("));
4791 assert!(is_expression_position(" g(a, "));
4792 assert!(is_expression_position(" xs.fold(0, (acc, x) => ac")); assert!(is_expression_position(" let y = foo"));
4795 assert!(!is_expression_position(" let y: ")); assert!(!is_expression_position(" on call() -> ")); assert!(!is_expression_position(" tot")); }
4800
4801 #[test]
4802 fn value_member_candidates_lists_record_fields() {
4803 use bynk_check::checker::NamedKind;
4804 let order = TYS.intern(Ty::Named {
4805 name: "Order".to_string(),
4806 kind: NamedKind::Record,
4807 args: Vec::new(),
4808 });
4809 let doc = "commons m {\n type Order = { id: Int, total: Int }\n}\n";
4810 let items = value_member_candidates(order, &TYS, doc, None);
4811 assert!(
4812 find(&items, "id", CompletionKind::Field).is_some(),
4813 "{items:?}",
4814 items = items.iter().map(|c| &c.label).collect::<Vec<_>>()
4815 );
4816 assert!(find(&items, "total", CompletionKind::Field).is_some());
4817 }
4818
4819 #[test]
4820 fn value_member_candidates_lists_json_error_fields() {
4821 let err = TYS.intern(Ty::DecodeError);
4822 let items = value_member_candidates(err, &TYS, "commons m {\n}\n", None);
4823 for f in ["kind", "path", "message"] {
4824 assert!(find(&items, f, CompletionKind::Field).is_some(), "{f}");
4825 }
4826 }
4827
4828 #[test]
4829 fn value_member_candidates_lists_validation_error_fields() {
4830 let err = TYS.intern(Ty::ValidationError);
4831 let items = value_member_candidates(err, &TYS, "commons m {\n}\n", None);
4832 for f in ["field", "message"] {
4833 assert!(find(&items, f, CompletionKind::Field).is_some(), "{f}");
4834 }
4835 assert!(find(&items, "value", CompletionKind::Field).is_none());
4836 }
4837
4838 #[test]
4839 fn store_field_member_candidates_offers_entry_ops_and_query_accessors() {
4840 let doc = "context shop\n\nagent Inventory {\n key id: String\n store items: Map[String, Int]\n\n on call f() -> Effect[()] {\n items.\n }\n}\n";
4845 let offset = doc.find("items.").unwrap() + "items.".len();
4846 let (rewritten, recv_offset) = value_receiver_rewrite(doc, offset).expect("bare receiver");
4847 let items = store_field_member_candidates(&rewritten, recv_offset, &[]);
4848 assert!(
4849 find(&items, "put", CompletionKind::Member).is_some(),
4850 "{items:?}",
4851 items = items.iter().map(|c| &c.label).collect::<Vec<_>>()
4852 );
4853 assert!(find(&items, "get", CompletionKind::Member).is_some());
4854 assert!(find(&items, "update", CompletionKind::Member).is_some());
4855 assert!(find(&items, "entries", CompletionKind::Field).is_some());
4856 assert!(find(&items, "keys", CompletionKind::Field).is_some());
4857 assert!(find(&items, "values", CompletionKind::Field).is_some());
4858 }
4859
4860 #[test]
4861 fn store_field_member_candidates_empty_for_ordinary_local() {
4862 let doc = "context shop\n\nagent Inventory {\n key id: String\n\n on call f() -> Effect[()] {\n let items = 1\n items.\n }\n}\n";
4865 let offset = doc.rfind("items.").unwrap() + "items.".len();
4866 let (rewritten, recv_offset) = value_receiver_rewrite(doc, offset).expect("bare receiver");
4867 let items = store_field_member_candidates(&rewritten, recv_offset, &[]);
4868 assert!(items.is_empty());
4869 }
4870
4871 #[test]
4872 fn store_field_member_candidates_skips_query_accessors_on_held_map() {
4873 let doc = "context shop\n\nagent Room {\n key id: String\n store conns: Map[String, Connection[String]]\n\n on call f() -> Effect[()] {\n conns.\n }\n}\n";
4876 let offset = doc.find("conns.").unwrap() + "conns.".len();
4877 let (rewritten, recv_offset) = value_receiver_rewrite(doc, offset).expect("bare receiver");
4878 let items = store_field_member_candidates(&rewritten, recv_offset, &[]);
4879 assert!(find(&items, "put", CompletionKind::Member).is_some());
4880 assert!(find(&items, "entries", CompletionKind::Field).is_none());
4881 assert!(find(&items, "keys", CompletionKind::Field).is_none());
4882 assert!(find(&items, "values", CompletionKind::Field).is_none());
4883 }
4884
4885 #[test]
4886 fn store_field_member_candidates_offers_set_and_cache_vocabularies() {
4887 let doc = "context shop\n\nagent Inventory {\n key id: String\n store tags: Set[String]\n\n on call f() -> Effect[()] {\n tags.\n }\n}\n";
4890 let offset = doc.find("tags.").unwrap() + "tags.".len();
4891 let (rewritten, recv_offset) = value_receiver_rewrite(doc, offset).expect("bare receiver");
4892 let items = store_field_member_candidates(&rewritten, recv_offset, &[]);
4893 assert!(find(&items, "add", CompletionKind::Member).is_some());
4894 assert!(find(&items, "entries", CompletionKind::Field).is_none());
4895 }
4896
4897 #[test]
4900 fn record_construction_offers_field_names() {
4901 let doc = "commons m {\n type Order = { id: Int, total: Int }\n}\n";
4902 let got = labels(" let o = Order { ", doc);
4903 assert!(got.contains(&"id".to_string()), "{got:?}");
4904 assert!(got.contains(&"total".to_string()), "{got:?}");
4905 let got2 = labels(" let o = Order { id: 1, ", doc);
4907 assert!(got2.contains(&"total".to_string()), "{got2:?}");
4908 assert!(record_construction_receiver(" let o = Order { id: ").is_none());
4910 assert!(record_construction_receiver(" if x { ").is_none());
4912 }
4913
4914 #[test]
4915 fn record_construction_lists_defaulted_fields_last_with_their_default() {
4916 let doc = "commons m\n\ntype Opts = { retries: Int = 3, name: String }\n";
4919 let fields = record_field_names("Opts", doc, None);
4920 let names: Vec<&str> = fields.iter().map(|c| c.label.as_str()).collect();
4921 assert_eq!(names, ["name", "retries"], "{names:?}");
4922 assert_eq!(fields[0].detail.as_deref(), Some("field of `Opts`"));
4923 assert_eq!(
4924 fields[1].detail.as_deref(),
4925 Some("field of `Opts`, default `3`")
4926 );
4927 }
4928
4929 #[test]
4930 fn record_pattern_offers_the_unlisted_fields_then_rest() {
4931 let doc = "commons m {\n type Order = { id: Int, total: Int, note: String }\n}\n";
4932 for prefix in [
4933 " Order { ",
4934 " Some(Order { ",
4935 " if o is (Order { ",
4936 " Ok(Order { id: 1, ",
4937 " let Order { ",
4939 " let Order { id, ",
4940 " let (Order { ",
4941 " let Some(Order { ",
4942 " items.map((Order { ",
4944 " items.map((Order { id, ",
4945 " items.fold(0, (total, Order { ",
4946 " items.fold(0, (total, Order { id, ",
4947 " items.fold(0, (total: Int, Order { ",
4948 ] {
4949 let got = labels(prefix, doc);
4950 assert!(got.contains(&"..".to_string()), "{prefix}: {got:?}");
4951 assert!(got.contains(&"total".to_string()), "{prefix}: {got:?}");
4952 }
4953 let got = labels(" Order { id: Some(1, 2), total, ", doc);
4955 assert!(!got.contains(&"id".to_string()), "{got:?}");
4956 assert!(!got.contains(&"total".to_string()), "{got:?}");
4957 assert!(got.contains(&"note".to_string()), "{got:?}");
4958 let got = labels(" let o = Order { ", doc);
4960 assert!(
4961 got.contains(&"id".to_string()) && !got.contains(&"..".to_string()),
4962 "{got:?}"
4963 );
4964 let got = labels(" => Order { id: 1, ", doc);
4965 assert!(!got.contains(&"..".to_string()), "{got:?}");
4966 let got = labels(" let o = Order { ", doc);
4968 assert!(!got.contains(&"..".to_string()), "{got:?}");
4969 let got = labels(" let Order { id, ", doc);
4970 assert!(!got.contains(&"id".to_string()), "{got:?}");
4971 let got = labels(" items.map(Order { ", doc);
4974 assert!(!got.contains(&"..".to_string()), "{got:?}");
4975 let got = labels(" items.fold(0, f(1, Order { ", doc);
4976 assert!(!got.contains(&"..".to_string()), "{got:?}");
4977 let got = labels(" let o = (Order { ", doc);
4978 assert!(!got.contains(&"..".to_string()), "{got:?}");
4979 }
4980
4981 #[test]
4982 fn from_offers_protocols() {
4983 let got = labels(" service s from ", "context a.b\n");
4984 assert!(got.contains(&"http".to_string()), "{got:?}");
4985 assert!(got.contains(&"cron".to_string()) && got.contains(&"queue".to_string()));
4986 assert!(got.contains(&"email".to_string()), "{got:?}");
4988 }
4989
4990 #[test]
4992 fn email_verdict_variants_complete() {
4993 let items = complete(" EmailVerdict.", "context a.b\n", None);
4994 for name in ["Accept", "Reject", "Forward", "Reply"] {
4995 assert!(
4996 find(&items, name, CompletionKind::Variant).is_some(),
4997 "{name} missing: {:?}",
4998 items.iter().map(|c| &c.label).collect::<Vec<_>>()
4999 );
5000 }
5001 }
5002
5003 #[test]
5004 fn on_offers_handler_kinds() {
5005 let got = labels(" on ", "context a.b\n");
5006 assert!(got.contains(&"call".to_string()), "{got:?}");
5007 assert!(got.contains(&"GET".to_string()) && got.contains(&"schedule".to_string()));
5008 }
5009
5010 #[test]
5011 fn by_offers_project_actors() {
5012 let doc = "context a.b\n\nactor Caller { auth = Bearer }\n";
5013 let got = labels(" on call f() -> Effect[Int] by ", doc);
5014 assert!(got.contains(&"Caller".to_string()), "{got:?}");
5015 }
5016
5017 #[test]
5018 fn exports_offers_export_kinds() {
5019 let got = labels(" exports ", "adapter t {\n binding \"./b.ts\"\n}\n");
5020 assert!(got.contains(&"capability".to_string()), "{got:?}");
5021 assert!(got.contains(&"transparent".to_string()));
5022 }
5023
5024 #[test]
5025 fn provides_offers_in_scope_capabilities() {
5026 let doc = "context a.b\n\ncapability Store { fn get() -> Effect[Int] }\n";
5027 let got = labels(" provides ", doc);
5028 assert!(got.contains(&"Store".to_string()), "{got:?}");
5029 }
5030
5031 #[test]
5032 fn where_offers_predicate_names() {
5033 let got = labels(" type Code = Int where ", "context a.b\n");
5035 assert!(got.contains(&"InRange".to_string()), "{got:?}");
5036 assert!(got.contains(&"NonNegative".to_string()));
5037 assert!(got.contains(&"IsoDate".to_string()), "{got:?}");
5038 let got = labels(" _ where ", "context a.b\n");
5040 assert!(got.contains(&"Matches".to_string()), "{got:?}");
5041 assert!(got.contains(&"NonEmpty".to_string()));
5042 }
5043
5044 #[test]
5045 fn is_for_all_where_matches_only_the_for_all_binder() {
5046 assert!(is_for_all_where("\tfor all x: Int, y: Int where "));
5047 assert!(is_for_all_where("for all x: Int where "));
5048 assert!(!is_for_all_where("format(x) where "));
5051 assert!(!is_for_all_where("for allocate x where "));
5052 assert!(!is_for_all_where(" type Code = Int where "));
5054 assert!(!is_for_all_where(" _ where "));
5055 assert!(!is_for_all_where("no where here"));
5056 }
5057
5058 #[test]
5059 fn for_all_where_falls_through_to_expression_position_not_predicates() {
5060 let got = labels("\tfor all x: Int where ", "context a.b\n");
5064 assert!(!got.contains(&"InRange".to_string()), "{got:?}");
5065 assert!(!got.contains(&"NonNegative".to_string()), "{got:?}");
5066 }
5067
5068 #[test]
5069 fn clause_detectors_do_not_over_fire() {
5070 assert!(!after_clause_keyword(" session ", "on"));
5072 assert!(!after_clause_keyword(" let from = ", "from"));
5073 assert!(after_clause_keyword(" service s from ", "from"));
5075 assert!(after_clause_keyword(" by ", "by"));
5076 }
5077
5078 #[test]
5079 fn by_offers_actors_only_where_it_is_the_clause_word() {
5080 assert!(is_by_clause_position(
5082 " on GET(\"/\") () -> Effect[Int] by "
5083 ));
5084 assert!(is_by_clause_position("service api from http by "));
5085 assert!(is_by_clause_position(" let r <- svc.POST(\"/h\") by "));
5086 assert!(is_by_clause_position(" expect svc.GET(\"/h\") by "));
5087 assert!(!is_by_clause_position(" let x = a + by "));
5089 assert!(!is_by_clause_position(" fn shift(xs: List[Int], by "));
5090 assert!(!is_by_clause_position(" advance Clock by "));
5091 assert!(!is_by_clause_position(" let r <- f(a, by "));
5093 assert!(!is_by_clause_position(" on call f(g: (Int) -> Int, by "));
5094 assert!(!is_by_clause_position(" let r <- f(by "));
5095 assert!(!is_by_clause_position(" fn f(by: Int) -> Int { by "));
5097 assert!(!is_by_clause_position(" by "));
5098 }
5099
5100 #[test]
5101 fn contract_clause_kind_detects_requires_and_ensures() {
5102 assert_eq!(contract_clause_kind(" requires positive: "), Some(false));
5103 assert_eq!(contract_clause_kind(" ensures never_neg: "), Some(true));
5104 assert_eq!(contract_clause_kind(" id: Int"), None);
5106 assert_eq!(contract_clause_kind(" let x = 1"), None);
5107 }
5108
5109 #[test]
5110 fn cors_field_position_inside_cors_block() {
5111 let doc = "service api from http {\n cors {\n ";
5113 assert!(in_cors_field_position(doc, doc.len()));
5114 let doc2 = "service api from http {\n cors {\n origins: ";
5116 assert!(!in_cors_field_position(doc2, doc2.len()));
5117 let doc3 = "let x = Order {\n ";
5119 assert!(!in_cors_field_position(doc3, doc3.len()));
5120 }
5121
5122 #[test]
5125 fn par_block_positions_and_candidates() {
5126 let inside = "service s {\n on call() -> Effect[Int] by Caller {\n par {\n ";
5127 assert!(in_par_block_position(inside, inside.len()));
5128 let labels: Vec<String> = par_block_candidates()
5129 .into_iter()
5130 .map(|c| c.label)
5131 .collect();
5132 assert_eq!(labels, ["let x <-", "do"]);
5133 let after = "service s {\n on call() -> Effect[Int] by Caller {\n par {\n let a <- f()\n }\n ";
5135 assert!(!in_par_block_position(after, after.len()));
5136 assert!(in_effectful_body_position(after, after.len()));
5137 }
5138
5139 #[test]
5140 fn par_snippet_is_for_effectful_bodies_only() {
5141 let effectful = "fn f() -> Effect[Int] {\n if true {\n ";
5142 assert!(in_effectful_body_position(effectful, effectful.len()));
5143 let pure = "fn f() -> Int {\n ";
5144 assert!(!in_effectful_body_position(pure, pure.len()));
5145 let top = "context c\n\n";
5146 assert!(!in_effectful_body_position(top, top.len()));
5147 assert!(par_snippet().insert_text.unwrap().starts_with("par {"));
5148 }
5149
5150 #[test]
5151 fn security_field_position_inside_security_block() {
5152 let doc = "service api from http {\n security {\n ";
5154 assert!(in_security_field_position(doc, doc.len()));
5155 let doc2 = "service api from http {\n security {\n hsts: ";
5157 assert!(!in_security_field_position(doc2, doc2.len()));
5158 let doc3 = "service api from http {\n cors {\n ";
5160 assert!(!in_security_field_position(doc3, doc3.len()));
5161 }
5162
5163 #[test]
5167 fn field_position_probes_survive_non_ascii() {
5168 let doc = "service api from http {\n cors { // café\n ";
5169 assert!(in_cors_field_position(doc, doc.len()));
5170 let mid = doc.find('é').unwrap() + 1;
5172 assert!(!doc.is_char_boundary(mid));
5173 let _ = in_cors_field_position(doc, mid);
5174 let _ = in_security_field_position(doc, mid);
5175 let _ = in_limits_field_position(doc, mid);
5176 let _ = in_json_field_position(doc, mid);
5177 let _ = in_json_options_value_position(doc, mid);
5178 }
5179
5180 #[test]
5181 fn json_positions_inside_the_section_and_the_annotation() {
5182 let name = "service api from http {\n json {\n ";
5185 assert!(in_json_field_position(name, name.len()));
5186 assert!(!in_json_options_value_position(name, name.len()));
5187 let value = "service api from http {\n json {\n options: ";
5188 assert!(!in_json_field_position(value, value.len()));
5189 assert!(in_json_options_value_position(value, value.len()));
5190 let ann = "service api from http {\n @json(";
5191 assert!(in_json_arg_position(ann, ann.len()));
5192 let ann_value = "service api from http {\n @json(options: pl";
5193 assert!(in_json_options_value_position(ann_value, ann_value.len()));
5194 let limits = "service api from http {\n limits {\n options: ";
5196 assert!(!in_json_options_value_position(limits, limits.len()));
5197 let call = "fn f() { json(";
5198 assert!(!in_json_arg_position(call, call.len()));
5199 }
5200
5201 #[test]
5202 fn by_in_a_suite_offers_the_reserved_principals() {
5203 let suite = "suite pay.hooks as system {\n case \"c\" {\n let r <- webhooks.POST(\"/h\", \"x\") by ";
5206 let labels: Vec<String> =
5207 complete(" let r <- webhooks.POST(\"/h\", \"x\") by ", suite, None)
5208 .into_iter()
5209 .map(|c| c.label)
5210 .collect();
5211 for name in [
5212 "Nobody",
5213 "Forged",
5214 "Stale",
5215 "Expired",
5216 "WrongIssuer",
5217 "WrongAudience",
5218 "WrongAlgorithm",
5219 "NoSubject",
5220 ] {
5221 assert!(labels.iter().any(|l| l == name), "{name}: {labels:?}");
5222 }
5223 let context = "context pay.hooks\n\nservice api from http {\n on GET(\"/a\") () -> Effect[HttpResult[String]] by ";
5224 let labels: Vec<String> = complete(
5225 " on GET(\"/a\") () -> Effect[HttpResult[String]] by ",
5226 context,
5227 None,
5228 )
5229 .into_iter()
5230 .map(|c| c.label)
5231 .collect();
5232 assert!(!labels.iter().any(|l| l == "Forged"), "{labels:?}");
5233 }
5234
5235 #[test]
5236 fn env_name_position_and_candidates() {
5237 let doc = "suite shop.pay {\n env {\n ";
5239 assert!(in_env_name_position(doc, doc.len()));
5240 let doc2 = "suite shop.pay {\n env {\n A = ";
5242 assert!(!in_env_name_position(doc2, doc2.len()));
5243 let doc3 = "suite shop.pay {\n case \"c\" {\n ";
5245 assert!(!in_env_name_position(doc3, doc3.len()));
5246 let mut files = HashMap::new();
5247 files.insert(
5248 PathBuf::from("src/pay.bynk"),
5249 "actor User { auth = Bearer(secret = \"AUTH_JWT_SECRET\"), identity = String }\n\
5250 let p <- Secrets.get(\"PAYMENTS_PROCESSOR\")\n"
5251 .to_string(),
5252 );
5253 let labels: Vec<String> = env_name_candidates(doc, Some(&files))
5254 .into_iter()
5255 .map(|c| c.label)
5256 .collect();
5257 assert_eq!(labels, ["AUTH_JWT_SECRET", "PAYMENTS_PROCESSOR"]);
5258 }
5259
5260 #[test]
5261 fn limits_field_position_inside_limits_block() {
5262 let doc = "service api from http {\n limits {\n ";
5264 assert!(in_limits_field_position(doc, doc.len()));
5265 let doc2 = "service api from http {\n limits {\n maxBody: ";
5267 assert!(!in_limits_field_position(doc2, doc2.len()));
5268 let doc3 = "service api from http {\n security {\n ";
5270 assert!(!in_limits_field_position(doc3, doc3.len()));
5271 }
5272
5273 #[test]
5274 fn service_body_item_position_offers_cors() {
5275 let doc = "service api from http {\n ";
5277 assert!(in_service_body_item_position(doc, doc.len(), " "));
5278 let doc2 = "service api from http {\n cors {\n ";
5281 assert!(!in_service_body_item_position(doc2, doc2.len(), " "));
5282 }
5283
5284 #[test]
5285 fn cache_arg_position_inside_cache_annotation() {
5286 let doc = "service api from http {\n @cache(";
5288 assert!(in_cache_arg_position(doc, doc.len()));
5289 let doc2 = "service api from http {\n @cache(maxAge: 5.minutes, ";
5291 assert!(in_cache_arg_position(doc2, doc2.len()));
5292 let doc3 = "service api from http {\n @cache(maxAge: ";
5294 assert!(!in_cache_arg_position(doc3, doc3.len()));
5295 let doc4 = "let x = cache(";
5297 assert!(!in_cache_arg_position(doc4, doc4.len()));
5298 let doc5 = "on GET(\"/x\") by v: Visitor (";
5300 assert!(!in_cache_arg_position(doc5, doc5.len()));
5301 }
5302
5303 #[test]
5304 fn a_capability_declaration_completes_its_base_then_its_options() {
5305 let bases: Vec<String> = instance_declaration_completions("capability LoginLimit = ")
5307 .into_iter()
5308 .map(|(label, ..)| label)
5309 .collect();
5310 assert_eq!(
5311 bases,
5312 [
5313 "Kv",
5314 "Service",
5315 "R2",
5316 "RateLimit",
5317 "Queue",
5318 "Analytics",
5319 "D1",
5320 "EdgeCache",
5321 "StoredSecret",
5322 "Email",
5323 "Postgres",
5324 "MySql",
5325 "Vectorize",
5326 "Container",
5327 "AiSearch",
5328 "MtlsCertificate"
5329 ]
5330 );
5331 let narrowed: Vec<String> = instance_declaration_completions("capability L = Ra")
5332 .into_iter()
5333 .map(|(label, ..)| label)
5334 .collect();
5335 assert_eq!(narrowed, ["RateLimit"]);
5336 let options = instance_declaration_completions("capability LoginLimit = RateLimit ");
5338 assert_eq!(options.len(), 1);
5339 assert_eq!(options[0].0, "@limit(…) @period(…)");
5340 assert_eq!(options[0].2, "@limit(${1:100}) @period(${2:60.seconds})");
5341 let options = instance_declaration_completions("capability OrderEvents = Queue ");
5343 assert_eq!(options[0].0, "@name(…)");
5344 assert_eq!(options[0].2, "@name(${1:\"order-events\"})");
5345 let options = instance_declaration_completions("capability StripeKey = StoredSecret ");
5347 assert_eq!(options[0].0, "@store(…) @secret(…)");
5348 assert_eq!(
5349 options[0].2,
5350 "@store(${1:\"payments\"}) @secret(${2:\"stripe-live\"})"
5351 );
5352 assert!(instance_declaration_completions("capability A = R2 ").is_empty());
5355 assert!(instance_declaration_completions("capability Mail = Email ").is_empty());
5357 assert!(instance_declaration_completions("capability Main = Postgres ").is_empty());
5359 assert!(instance_declaration_completions("capability Legacy = MySql ").is_empty());
5361 assert!(instance_declaration_completions("capability Edge = EdgeCache ").is_empty());
5362 assert!(instance_declaration_completions("capability L = RateLimit @limit(1) ").is_empty());
5363 assert!(instance_declaration_completions("let x = R").is_empty());
5364 }
5365
5366 #[test]
5367 fn a_rate_limit_instance_option_is_not_the_limit_annotation() {
5368 let doc = "context a\ncapability LoginLimit = RateLimit @limit(";
5370 assert!(!in_limit_arg_position(doc, doc.len()));
5371 let doc = "context a\ncapability LoginLimit = RateLimit @limit(100) @period(";
5373 let offered: Vec<&str> = instance_option_values(doc, doc.len())
5374 .iter()
5375 .map(|(v, _)| *v)
5376 .collect();
5377 assert_eq!(offered, ["10.seconds", "60.seconds"]);
5378 assert!(instance_option_values("let x = period(", 15).is_empty());
5379 let doc = "service api from http {\n @period(";
5380 assert!(instance_option_values(doc, doc.len()).is_empty());
5381 }
5382
5383 #[test]
5384 fn limit_arg_position_inside_limit_annotation() {
5385 let doc = "service api from http {\n @limit(";
5387 assert!(in_limit_arg_position(doc, doc.len()));
5388 let doc2 = "service api from http {\n @limit(maxBody: 1048576, ";
5390 assert!(in_limit_arg_position(doc2, doc2.len()));
5391 let doc3 = "service api from http {\n @limit(maxBody: ";
5393 assert!(!in_limit_arg_position(doc3, doc3.len()));
5394 let doc4 = "let x = limit(";
5396 assert!(!in_limit_arg_position(doc4, doc4.len()));
5397 let doc5 = "on GET(\"/x\") by v: Visitor (";
5399 assert!(!in_limit_arg_position(doc5, doc5.len()));
5400 }
5401
5402 #[test]
5403 fn http_param_name_position_in_a_handler_header() {
5404 let doc = "service api from http {\n on GET(\"/x\") (";
5405 assert!(in_http_param_name_position(doc, doc.len()));
5406 let doc2 = "service api from http {\n on POST(\"/x/:id\") (id: String, ";
5407 assert!(in_http_param_name_position(doc2, doc2.len()));
5408 let doc3 = "service api from http {\n on GET(\"/x\") (query: ";
5410 assert!(!in_http_param_name_position(doc3, doc3.len()));
5411 let doc4 = "service api from http {\n on GET(";
5413 assert!(!in_http_param_name_position(doc4, doc4.len()));
5414 let doc5 = "fn f(x: Int) -> Int {\n g(";
5415 assert!(!in_http_param_name_position(doc5, doc5.len()));
5416 let doc6 = "service s from cron {\n on schedule(\"* * * * *\") (";
5418 assert!(!in_http_param_name_position(doc6, doc6.len()));
5419 }
5420
5421 #[test]
5422 fn raw_arg_position_inside_raw_annotation() {
5423 let doc = "service api from http {\n @raw(";
5424 assert!(in_raw_arg_position(doc, doc.len()));
5425 let doc2 = "service api from http {\n @raw(contentType: ";
5426 assert!(!in_raw_arg_position(doc2, doc2.len()));
5427 let doc3 = "let x = raw(";
5428 assert!(!in_raw_arg_position(doc3, doc3.len()));
5429 let doc4 = "service api from http {\n @limit(";
5430 assert!(!in_raw_arg_position(doc4, doc4.len()));
5431 }
5432
5433 #[test]
5434 fn sum_type_variants_lists_variants() {
5435 let doc = "commons m {\n type Status = enum { Pending, Shipped }\n}\n";
5436 let got: Vec<String> = sum_type_variants("Status", doc, None)
5437 .into_iter()
5438 .map(|c| c.label)
5439 .collect();
5440 assert!(got.contains(&"Pending".to_string()), "{got:?}");
5441 assert!(got.contains(&"Shipped".to_string()), "{got:?}");
5442 }
5443
5444 #[test]
5449 fn a_derivation_cycle_completes_nothing() {
5450 let doc = "context a\n\ncapability A = B\ncapability B = C\ncapability C = A\n";
5451 assert!(member_candidates("A", doc, None).is_empty());
5452 }
5453
5454 #[test]
5456 fn a_derived_capability_completes_its_bases_operations() {
5457 const DERIVED_DOC: &str =
5458 "context a\n\nconsumes bynk.cloudflare { Kv }\n\ncapability Sessions = Kv\n";
5459 let labels: Vec<String> = member_candidates("Sessions", DERIVED_DOC, None)
5460 .into_iter()
5461 .map(|c| c.label)
5462 .collect();
5463 for op in ["get", "put", "putTtl", "delete", "list"] {
5464 assert!(labels.iter().any(|l| l == op), "{op} missing: {labels:?}");
5465 }
5466 }
5467
5468 #[test]
5469 fn member_completions_carry_their_docs() {
5470 let doc = "commons m\n\ntype Rec = {\n --- The id.\n id: Int,\n n: Int,\n}\n\ntype Status = enum {\n ---\n Waiting.\n ---\n Pending,\n Shipped,\n}\n";
5471 let docs = |items: Vec<Completion>| -> Vec<(String, Option<String>)> {
5472 items
5473 .into_iter()
5474 .map(|c| (c.label, c.documentation.map(|d| d.trim_end().to_string())))
5475 .collect()
5476 };
5477 assert_eq!(
5478 docs(record_field_names("Rec", doc, None)),
5479 [("id".into(), Some("The id.".into())), ("n".into(), None)]
5480 );
5481 assert_eq!(
5482 docs(sum_type_variants("Status", doc, None)),
5483 [
5484 ("Pending".into(), Some("Waiting.".into())),
5485 ("Shipped".into(), None)
5486 ]
5487 );
5488 assert_eq!(
5489 docs(member_candidates("Status", doc, None))
5490 .into_iter()
5491 .filter(|(l, _)| l == "Pending")
5492 .collect::<Vec<_>>(),
5493 [("Pending".into(), Some("Waiting.".into()))]
5494 );
5495 }
5496
5497 #[test]
5498 fn variants_for_ty_offers_built_in_result_and_option() {
5499 use bynk_syntax::ast::BaseType;
5504 let result = TYS.intern(Ty::Result(
5505 TYS.intern(Ty::Base(BaseType::Int)),
5506 TYS.intern(Ty::Base(BaseType::String)),
5507 ));
5508 let got: Vec<String> = variants_for_ty(result, &TYS, "", None)
5509 .into_iter()
5510 .map(|c| c.label)
5511 .collect();
5512 assert_eq!(got, vec!["Ok".to_string(), "Err".to_string()]);
5513
5514 let option = TYS.intern(Ty::Option(TYS.intern(Ty::Base(BaseType::Int))));
5515 let got: Vec<String> = variants_for_ty(option, &TYS, "", None)
5516 .into_iter()
5517 .map(|c| c.label)
5518 .collect();
5519 assert_eq!(got, vec!["Some".to_string(), "None".to_string()]);
5520 }
5521
5522 #[test]
5523 fn nested_variant_completions_resolves_the_payload_type() {
5524 use bynk_check::checker::NamedKind;
5525 use bynk_syntax::ast::BaseType;
5526 let payload = TYS.intern(Ty::Result(
5529 TYS.intern(Ty::Base(BaseType::Int)),
5530 TYS.intern(Ty::Named {
5531 name: "E".to_string(),
5532 kind: NamedKind::Sum,
5533 args: Vec::new(),
5534 }),
5535 ));
5536 let scrut = TYS.intern(Ty::Option(payload));
5537 let got: Vec<String> = nested_variant_completions(scrut, &TYS, "Some", "", None)
5538 .into_iter()
5539 .map(|c| c.label)
5540 .collect();
5541 assert_eq!(got, vec!["Ok".to_string(), "Err".to_string()]);
5542
5543 let opt_int = TYS.intern(Ty::Option(TYS.intern(Ty::Base(BaseType::Int))));
5545 let inner = TYS.intern(Ty::Result(TYS.intern(Ty::Base(BaseType::Int)), opt_int));
5546 let got: Vec<String> = nested_variant_completions(inner, &TYS, "Err", "", None)
5547 .into_iter()
5548 .map(|c| c.label)
5549 .collect();
5550 assert_eq!(got, vec!["Some".to_string(), "None".to_string()]);
5551
5552 let doc = "commons m {\n type Inner = enum { A, B }\n \
5555 type Outer = | Wrap(inner: Inner) | Bare\n}\n";
5556 let outer = TYS.intern(Ty::Named {
5557 name: "Outer".to_string(),
5558 kind: NamedKind::Sum,
5559 args: Vec::new(),
5560 });
5561 let got: Vec<String> = nested_variant_completions(outer, &TYS, "Wrap", doc, None)
5562 .into_iter()
5563 .map(|c| c.label)
5564 .collect();
5565 assert!(got.contains(&"A".to_string()), "{got:?}");
5566 assert!(got.contains(&"B".to_string()), "{got:?}");
5567 }
5568
5569 #[test]
5570 fn literal_kind_scrutinee_suggests_no_variants() {
5571 let doc = "commons m {\n type Quantity = Int where InRange(1, 99)\n}\n";
5577 assert!(sum_type_variants("Quantity", doc, None).is_empty());
5578 assert!(sum_type_variants("Int", doc, None).is_empty());
5579 }
5580
5581 fn enumerated_units(doc_text: &str, files: Option<&HashMap<PathBuf, String>>) -> Vec<String> {
5585 let mut names = Vec::new();
5586 for_each_unit(doc_text, files, |u| names.push(u.name().joined()));
5587 names
5588 }
5589
5590 fn synthetic_path(name: &str) -> PathBuf {
5596 PathBuf::from(format!("/synthetic/{name}.bynk"))
5597 }
5598
5599 #[test]
5600 fn for_each_unit_yields_embedded_buffer_and_project_files() {
5601 let sibling = synthetic_path("sibling");
5602 let files = HashMap::from([(
5603 sibling,
5604 "commons proj.sibling {\n fn s() -> Int { 1 }\n}\n".to_string(),
5605 )]);
5606
5607 let names = enumerated_units(
5608 "commons proj.buffer {\n fn b() -> Int { 1 }\n}\n",
5609 Some(&files),
5610 );
5611 assert!(names.iter().any(|n| n == "bynk"), "embedded: {names:?}");
5613 assert!(
5614 names.iter().any(|n| n == "proj.buffer"),
5615 "buffer: {names:?}"
5616 );
5617 assert!(
5618 names.iter().any(|n| n == "proj.sibling"),
5619 "project file: {names:?}"
5620 );
5621 }
5622
5623 #[test]
5630 fn same_named_declarations_do_not_union_across_units() {
5631 let stale = HashMap::from([(
5632 synthetic_path("stale"),
5633 "commons m {\n \
5634 type Rec = { total: Int, old_field: Int }\n \
5635 type Status = enum { Pending, Retired }\n\
5636 }\n"
5637 .to_string(),
5638 )]);
5639
5640 let buffer = "commons m {\n \
5641 type Rec = { total: Int }\n \
5642 type Status = enum { Pending, Shipped }\n\
5643 }\n";
5644 let files = Some(&stale);
5645
5646 let fields: Vec<String> = record_field_names("Rec", buffer, files)
5647 .into_iter()
5648 .map(|c| c.label)
5649 .collect();
5650 assert_eq!(fields, vec!["total".to_string()], "{fields:?}");
5651
5652 let variants: Vec<String> = sum_type_variants("Status", buffer, files)
5653 .into_iter()
5654 .map(|c| c.label)
5655 .collect();
5656 assert_eq!(
5657 variants,
5658 vec!["Pending".to_string(), "Shipped".to_string()],
5659 "{variants:?}"
5660 );
5661 }
5662
5663 #[test]
5668 fn capabilities_of_unit_does_not_union_across_units() {
5669 let stale = HashMap::from([(
5670 synthetic_path("stale"),
5671 "adapter tokens {\n \
5672 exports capability { Jwt, Retired }\n\
5673 }\n"
5674 .to_string(),
5675 )]);
5676
5677 let buffer = "adapter tokens {\n exports capability { Jwt }\n}\n";
5678 let files = Some(&stale);
5679
5680 let caps = capabilities_of_unit("tokens", buffer, &split_dependency_files(files, None));
5681 assert_eq!(caps, vec!["Jwt".to_string()], "{caps:?}");
5682 }
5683
5684 #[test]
5685 fn project_unit_cache_invalidates_on_change() {
5686 let path = synthetic_path("unit");
5687
5688 let first_files = HashMap::from([(
5689 path.clone(),
5690 "commons proj.first {\n fn a() -> Int { 1 }\n}\n".to_string(),
5691 )]);
5692 let first = enumerated_units("context a.b\n", Some(&first_files));
5693 assert!(
5694 first.iter().any(|n| n == "proj.first"),
5695 "first read: {first:?}"
5696 );
5697
5698 let second_files = HashMap::from([(
5703 path,
5704 "commons proj.second.longer {\n fn a() -> Int { 1 }\n fn c() -> Int { 3 }\n}\n"
5705 .to_string(),
5706 )]);
5707 let second = enumerated_units("context a.b\n", Some(&second_files));
5708 assert!(
5709 second.iter().any(|n| n == "proj.second.longer"),
5710 "after change: {second:?}"
5711 );
5712 assert!(
5713 !second.iter().any(|n| n == "proj.first"),
5714 "stale served: {second:?}"
5715 );
5716 }
5717
5718 #[test]
5719 fn unparseable_project_file_is_skipped() {
5720 let files = HashMap::from([(synthetic_path("broken"), "not bynk source {{{".to_string())]);
5727 let names = enumerated_units("context a.b\n", Some(&files));
5728 let baseline = enumerated_units("context a.b\n", None);
5729 assert_eq!(names, baseline, "{names:?}");
5735 }
5736}
5737
5738#[cfg(test)]
5739mod snapshot_completion_tests {
5740 use super::*;
5741
5742 fn labels(line: &str) -> Vec<String> {
5743 complete(line, "", None)
5744 .into_iter()
5745 .map(|c| c.label)
5746 .collect()
5747 }
5748
5749 #[test]
5752 fn matches_snapshot_follows_an_expect_value() {
5753 let offered = |line: &str| labels(line).contains(&"matches snapshot".to_string());
5754 assert!(offered(" expect read(1) "));
5755 assert!(offered(" expect d.tags "));
5756 assert!(offered(" expect read(1) mat"));
5757 assert!(!offered(" expect read(1) matches snapshot \"x\" "));
5758 assert!(!offered(" expect read(1) =="));
5759 assert!(!offered(" expect read(1) and "));
5760 assert!(!offered(" expect read(1) other"));
5761 assert!(!offered(" let x = read(1) "));
5762 }
5763}