1use crate::ast::*;
9use crate::error::CompileError;
10use crate::lexer::{
11 Token, TokenKind, comment_body, comment_is_legacy, doc_block_content, doc_fence_len,
12 doc_line_is_legacy, doc_line_text, has_blank_line_between, legacy_comment_error,
13 legacy_doc_line_error,
14};
15use crate::span::Span;
16mod declarations;
17mod duration;
18mod expressions;
19mod staircase;
20mod statements;
21mod types;
22
23#[derive(Debug, Default)]
32struct TriviaTable {
33 leading: Vec<Vec<Comment>>,
39 trailing: Vec<Option<String>>,
44 blank_before: Vec<bool>,
48 epilogue: Vec<Comment>,
52 legacy: Vec<CompileError>,
58}
59
60impl TriviaTable {
61 fn take_leading(&mut self, index: usize) -> Vec<Comment> {
62 match self.leading.get_mut(index) {
63 Some(v) => std::mem::take(v),
64 None => Vec::new(),
65 }
66 }
67
68 fn blank_before(&self, index: usize) -> bool {
69 self.blank_before.get(index).copied().unwrap_or(false)
70 }
71
72 fn take_trailing(&mut self, index: usize) -> Option<String> {
73 self.trailing.get_mut(index).and_then(|s| s.take())
74 }
75
76 fn take_epilogue(&mut self) -> Vec<Comment> {
77 std::mem::take(&mut self.epilogue)
78 }
79
80 fn is_fully_drained(&self) -> bool {
97 self.leading.iter().all(Vec::is_empty)
98 && self.trailing.iter().all(Option::is_none)
99 && self.epilogue.is_empty()
100 }
101
102 fn epilogue_is_empty(&self) -> bool {
110 self.epilogue.is_empty()
111 }
112}
113
114fn split_trivia(tokens: &[Token], source: &str) -> (Vec<Token>, TriviaTable) {
125 let mut filtered: Vec<Token> = Vec::with_capacity(tokens.len());
126 let mut table = TriviaTable::default();
127 let mut pending_leading: Vec<Comment> = Vec::new();
128 let mut last_content_end: Option<usize> = None;
129 let mut last_leading_end: Option<usize> = None;
136 let mut pending_blank_before = false;
138 for tok in tokens {
139 if !pending_leading.is_empty()
140 && let Some(end) = last_leading_end
141 && source[end..tok.span.start].matches('\n').count() >= 2
142 {
143 pending_leading.push(Comment::Blank);
144 }
145 if tok.kind == TokenKind::DocLine && doc_line_is_legacy(source, tok.span) {
146 table.legacy.push(legacy_doc_line_error(source, tok.span));
147 }
148 if tok.kind == TokenKind::Comment {
149 if comment_is_legacy(source, tok.span) {
150 table.legacy.push(legacy_comment_error(tok.span));
151 }
152 let body = comment_body(source, tok.span).into_owned();
153 if pending_leading.is_empty()
165 && filtered.last().is_some_and(|t| {
166 !matches!(
167 t.kind,
168 TokenKind::DocBlock
169 | TokenKind::DocLine
170 | TokenKind::LBrace
171 | TokenKind::LBracket
172 | TokenKind::LParen
173 )
174 })
175 && let Some(prev_end) = last_content_end
176 && !source[prev_end..tok.span.start].contains('\n')
177 {
178 let last_idx = filtered.len() - 1;
179 if table.trailing[last_idx].is_none() {
182 table.trailing[last_idx] = Some(body);
183 continue;
184 }
185 }
186 let own_line = !pending_leading.is_empty()
190 || filtered
191 .last()
192 .is_none_or(|t| matches!(t.kind, TokenKind::DocBlock | TokenKind::DocLine))
193 || last_content_end.is_some_and(|end| source[end..tok.span.start].contains('\n'));
194 if pending_leading.is_empty() {
195 pending_blank_before = own_line
196 && last_content_end
197 .is_some_and(|end| source[end..tok.span.start].matches('\n').count() >= 2);
198 }
199 pending_leading.push(Comment::Line(body));
200 last_leading_end = own_line.then_some(tok.span.end);
201 continue;
202 }
203 filtered.push(*tok);
204 table.leading.push(std::mem::take(&mut pending_leading));
205 table.trailing.push(None);
206 table
207 .blank_before
208 .push(std::mem::take(&mut pending_blank_before));
209 last_content_end = Some(tok.span.end);
210 last_leading_end = None;
211 }
212 table.epilogue = pending_leading;
213 (filtered, table)
214}
215
216pub fn parse(tokens: &[Token], source: &str) -> Result<Commons, Vec<CompileError>> {
222 parse_with_warnings(tokens, source).map(|(c, _warnings)| c)
223}
224
225pub fn parse_with_warnings(
228 tokens: &[Token],
229 source: &str,
230) -> Result<(Commons, Vec<CompileError>), Vec<CompileError>> {
231 let (unit, warnings) = parse_unit_with_warnings(tokens, source)?;
232 match unit {
233 SourceUnit::Commons(c) => Ok((c, warnings)),
234 SourceUnit::Context(ctx) => Err(vec![
235 CompileError::new(
236 "bynk.parse.unexpected_context",
237 ctx.span,
238 "expected a `commons` declaration but found a `context` declaration",
239 )
240 .with_note(
241 "contexts must be compiled as part of a project — pass the source directory, e.g. `bynk compile --target bundle --output out src`",
242 ),
243 ]),
244 SourceUnit::Suite(t) => Err(vec![
245 CompileError::new(
246 "bynk.parse.unexpected_suite",
247 t.span,
248 "expected a `commons` declaration but found a `suite` declaration",
249 )
250 .with_note(
251 "tests must be compiled as part of a project — pass the source directory, e.g. `bynk compile --target bundle --output out src`",
252 ),
253 ]),
254 SourceUnit::Adapter(a) => Err(vec![
255 CompileError::new(
256 "bynk.parse.unexpected_adapter",
257 a.span,
258 "expected a `commons` declaration but found an `adapter` declaration",
259 )
260 .with_note(
261 "adapters must be compiled as part of a project — pass the source directory, e.g. `bynk compile --target bundle --output out src`",
262 ),
263 ]),
264 }
265}
266
267pub fn parse_unit_with_recovery(
282 tokens: &[Token],
283 source: &str,
284) -> (Option<SourceUnit>, Vec<CompileError>) {
285 let (units, errors) = parse_units_with_recovery(tokens, source);
286 (units.into_iter().next(), errors)
287}
288
289pub fn parse_units_with_recovery(
294 tokens: &[Token],
295 source: &str,
296) -> (Vec<SourceUnit>, Vec<CompileError>) {
297 let recovered = parse_units_recovering(tokens, source);
298 (recovered.units, recovered.errors)
299}
300
301#[derive(Debug)]
304pub struct Recovered {
305 pub units: Vec<SourceUnit>,
306 pub errors: Vec<CompileError>,
307 pub broken_decl_names: Vec<String>,
310}
311
312pub fn merge_syntax_errors(
319 strict: Vec<CompileError>,
320 recovered: Vec<CompileError>,
321) -> Vec<CompileError> {
322 let mut out = strict;
323 for e in recovered {
324 if !out.iter().any(|o| o.span.start == e.span.start) {
325 out.push(e);
326 }
327 }
328 out
329}
330
331pub fn parse_units_recovering(tokens: &[Token], source: &str) -> Recovered {
334 parse_units_recovering_from(tokens, source, &mut 0)
335}
336
337pub fn parse_units_recovering_from(tokens: &[Token], source: &str, next_id: &mut u32) -> Recovered {
343 let (filtered, trivia) = split_trivia(tokens, source);
344 let mut warnings = Vec::new();
345 let mut p = Parser::new(&filtered, source, trivia, &mut warnings);
346 p.recover_mode = true;
347 p.next_expr_id = *next_id;
348 let mut units = Vec::new();
349 loop {
350 match p.parse_unit() {
351 Ok(u) => units.push(u),
352 Err(e) => {
353 p.recovered_errors.push(e);
354 break;
355 }
356 }
357 if p.peek().is_none() {
363 break;
364 }
365 }
366 let broken_decl_names = std::mem::take(&mut p.broken_decl_names);
367 *next_id = p.next_expr_id;
368 let mut all_errors = p.recovered_errors;
369 all_errors.append(&mut p.doc_errors);
370 all_errors.append(&mut warnings);
371 Recovered {
372 units,
373 errors: all_errors,
374 broken_decl_names,
375 }
376}
377
378pub fn parse_unit(tokens: &[Token], source: &str) -> Result<SourceUnit, Vec<CompileError>> {
382 parse_unit_with_warnings(tokens, source).map(|(unit, _warnings)| unit)
383}
384
385pub fn parse_unit_with_warnings(
388 tokens: &[Token],
389 source: &str,
390) -> Result<(SourceUnit, Vec<CompileError>), Vec<CompileError>> {
391 parse_unit_with_warnings_from(tokens, source, &mut 0)
392}
393
394pub fn parse_unit_with_warnings_from(
408 tokens: &[Token],
409 source: &str,
410 next_id: &mut u32,
411) -> Result<(SourceUnit, Vec<CompileError>), Vec<CompileError>> {
412 let (filtered, trivia) = split_trivia(tokens, source);
413 let mut warnings = Vec::new();
414 let mut p = Parser::new(&filtered, source, trivia, &mut warnings);
415 p.next_expr_id = *next_id;
416 let result = match p.parse_unit() {
417 Ok(u) => {
418 if let Some(extra) = p.peek() {
419 Err(vec![
420 CompileError::new(
421 "bynk.parse.extra_tokens",
422 extra.span,
423 "unexpected token after top-level declaration",
424 )
425 .with_note(
426 "a `.bynk` file contains exactly one `commons` or `context` declaration",
427 ),
428 ])
429 } else {
430 Ok(u)
431 }
432 }
433 Err(e) => Err(vec![e]),
434 };
435 let result = match (result, std::mem::take(&mut p.doc_errors)) {
438 (r, docs) if docs.is_empty() => r,
439 (Ok(_), docs) => Err(docs),
440 (Err(mut errs), mut docs) => {
441 errs.append(&mut docs);
442 Err(errs)
443 }
444 };
445 *next_id = p.next_expr_id;
446 match result {
449 Ok(u) => {
450 debug_assert!(
453 p.trivia.epilogue_is_empty(),
454 "a file-trailing comment was left undrained after a successful parse"
455 );
456 Ok((u, warnings))
457 }
458 Err(mut errs) => {
459 errs.append(&mut warnings);
460 Err(errs)
461 }
462 }
463}
464
465pub fn parse_units(tokens: &[Token], source: &str) -> Result<Vec<SourceUnit>, Vec<CompileError>> {
474 parse_units_with_warnings(tokens, source).map(|(units, _warnings)| units)
475}
476
477pub fn parse_units_with_warnings(
483 tokens: &[Token],
484 source: &str,
485) -> Result<(Vec<SourceUnit>, Vec<CompileError>), Vec<CompileError>> {
486 parse_units_with_drain_check(tokens, source)
487 .map(|(units, warnings, _drained)| (units, warnings))
488}
489
490pub fn parse_units_with_warnings_from(
497 tokens: &[Token],
498 source: &str,
499 next_id: &mut u32,
500) -> Result<(Vec<SourceUnit>, Vec<CompileError>), Vec<CompileError>> {
501 parse_units_with_drain_check_from(tokens, source, next_id)
502 .map(|(units, warnings, _drained)| (units, warnings))
503}
504
505pub fn parse_units_with_drain_check(
516 tokens: &[Token],
517 source: &str,
518) -> Result<(Vec<SourceUnit>, Vec<CompileError>, bool), Vec<CompileError>> {
519 parse_units_with_drain_check_from(tokens, source, &mut 0)
520}
521
522pub fn parse_units_with_drain_check_from(
525 tokens: &[Token],
526 source: &str,
527 next_id: &mut u32,
528) -> Result<(Vec<SourceUnit>, Vec<CompileError>, bool), Vec<CompileError>> {
529 parse_units_drain(tokens, source, next_id, false)
530}
531
532pub fn parse_units_migrating(
537 tokens: &[Token],
538 source: &str,
539) -> Result<(Vec<SourceUnit>, Vec<CompileError>, bool), Vec<CompileError>> {
540 parse_units_drain(tokens, source, &mut 0, true)
541}
542
543fn parse_units_drain(
544 tokens: &[Token],
545 source: &str,
546 next_id: &mut u32,
547 migrate: bool,
548) -> Result<(Vec<SourceUnit>, Vec<CompileError>, bool), Vec<CompileError>> {
549 let (filtered, trivia) = split_trivia(tokens, source);
550 let mut warnings = Vec::new();
551 let mut p = Parser::new(&filtered, source, trivia, &mut warnings);
552 if migrate {
553 p.doc_errors.clear();
554 }
555 p.next_expr_id = *next_id;
556 let mut units = Vec::new();
557 let mut errors: Vec<CompileError> = Vec::new();
558 while p.peek().is_some() {
559 match p.parse_unit() {
560 Ok(u) => units.push(u),
561 Err(e) => {
562 errors.push(e);
563 break;
564 }
565 }
566 }
567 errors.append(&mut p.doc_errors);
569 *next_id = p.next_expr_id;
570 let eof = p.eof_span();
571 let fully_drained = p.trivia.is_fully_drained();
572 if !errors.is_empty() {
575 errors.append(&mut warnings);
576 return Err(errors);
577 }
578 if units.is_empty() {
579 return Err(vec![CompileError::new(
580 "bynk.parse.unexpected_eof",
581 eof,
582 "expected `commons`, `context`, or `suite` to start the file, found end of file",
583 )]);
584 }
585 debug_assert!(
593 p.trivia.epilogue_is_empty(),
594 "a file-trailing comment was left undrained after a successful parse"
595 );
596 Ok((units, warnings, fully_drained))
597}
598
599enum SignedNumLit {
602 Int(IntBound),
603 Float(FloatBound),
604 Decimal(DecimalBound),
605}
606
607struct Parser<'a> {
608 tokens: &'a [Token],
609 source: &'a str,
610 pos: usize,
611 warnings: &'a mut Vec<CompileError>,
614 recover_mode: bool,
620 recovered_errors: Vec<CompileError>,
623 pub(crate) item_start: Option<usize>,
627 broken_decl_names: Vec<String>,
632 trivia: TriviaTable,
635 depth: usize,
642 no_record_literal: bool,
651 in_guard: bool,
655 is_pattern_tail: bool,
663 brace_depth: usize,
674 item_loop_baseline: Vec<usize>,
681 next_expr_id: u32,
685 doc_errors: Vec<CompileError>,
691 doc_probe: bool,
695}
696
697impl<'a> Parser<'a> {
698 fn new(
699 tokens: &'a [Token],
700 source: &'a str,
701 mut trivia: TriviaTable,
702 warnings: &'a mut Vec<CompileError>,
703 ) -> Self {
704 let doc_errors = std::mem::take(&mut trivia.legacy);
705 Self {
706 tokens,
707 source,
708 pos: 0,
709 warnings,
710 recover_mode: false,
711 recovered_errors: Vec::new(),
712 item_start: None,
713 broken_decl_names: Vec::new(),
714 trivia,
715 depth: 0,
716 no_record_literal: false,
717 in_guard: false,
718 is_pattern_tail: false,
719 brace_depth: 0,
720 item_loop_baseline: Vec::new(),
721 next_expr_id: 0,
722 doc_errors,
723 doc_probe: false,
724 }
725 }
726
727 fn alloc_expr_id(&mut self) -> ExprId {
732 let id = ExprId(self.next_expr_id);
733 self.next_expr_id += 1;
734 id
735 }
736
737 fn enter_recursion(&mut self, what: &str) -> Result<(), CompileError> {
745 self.depth += 1;
746 if self.depth > crate::MAX_NESTING_DEPTH {
747 self.depth -= 1;
748 let span = self
749 .peek()
750 .map(|t| t.span)
751 .unwrap_or_else(|| self.eof_span());
752 return Err(self.nesting_too_deep(span, what));
753 }
754 Ok(())
755 }
756
757 fn nesting_too_deep(&self, span: Span, what: &str) -> CompileError {
760 CompileError::new(
761 "bynk.parse.nesting_too_deep",
762 span,
763 format!(
764 "{what} nests more than {} levels deep",
765 crate::MAX_NESTING_DEPTH
766 ),
767 )
768 .with_note(
769 "deeply nested source is rejected to keep the parser from overflowing its \
770 stack and aborting; flatten or split the construct",
771 )
772 }
773
774 fn expression_too_long(&self, span: Span) -> CompileError {
780 CompileError::new(
781 "bynk.parse.nesting_too_deep",
782 span,
783 format!(
784 "this expression is more than {} levels deep",
785 crate::MAX_NESTING_DEPTH
786 ),
787 )
788 .with_note(
789 "a long operator or member chain is rejected to keep the compiler from overflowing \
790 its stack; split it across `let` bindings, or reduce a sequence with \
791 `.sum()`/`.fold(...)`",
792 )
793 }
794
795 fn enter_chain_fold(&mut self, folds: &mut usize, span: Span) -> Result<(), CompileError> {
815 self.depth += 1;
816 *folds += 1;
817 if self.depth > crate::MAX_NESTING_DEPTH {
818 self.depth -= *folds;
819 *folds = 0;
820 return Err(self.expression_too_long(span));
821 }
822 Ok(())
823 }
824
825 fn deepen_spine(&mut self, span: Span) -> Result<(), CompileError> {
834 self.depth += 1;
835 if self.depth > crate::MAX_NESTING_DEPTH {
836 return Err(self.expression_too_long(span));
837 }
838 Ok(())
839 }
840
841 fn take_leading_trivia(&mut self) -> Vec<Comment> {
851 let mut comments = self.take_unit_leading_trivia();
852 comments.retain(|c| *c != Comment::Blank);
853 comments
854 }
855
856 fn take_unit_leading_trivia(&mut self) -> Vec<Comment> {
859 self.trivia.take_leading(self.pos)
860 }
861
862 fn take_epilogue_trivia(&mut self) -> Vec<Comment> {
865 self.trivia.take_epilogue()
866 }
867
868 fn take_trailing_trivia(&mut self) -> Option<String> {
872 if self.pos == 0 {
873 return None;
874 }
875 self.trivia.take_trailing(self.pos - 1)
876 }
877
878 fn handle_item_err(&mut self, e: CompileError) -> Result<(), CompileError> {
882 if self.recover_mode {
883 self.recovered_errors.push(e);
884 if let Some(start) = self.item_start.take() {
885 self.broken_decl_names.extend(self.decl_names_at(start));
886 }
887 let before = self.pos;
888 self.recover_to_top_item();
889 let baseline = self.item_loop_baseline.last().copied().unwrap_or(0);
902 let closes_body = baseline > 0
903 && self.brace_depth == baseline
904 && self.peek_kind() == Some(TokenKind::RBrace);
905 if self.pos == before && !closes_body {
906 self.bump();
907 self.recover_to_top_item();
912 }
913 Ok(())
914 } else {
915 Err(e)
916 }
917 }
918
919 fn decl_names_at(&self, start: usize) -> Vec<String> {
924 let kind_at = |i: usize| self.tokens.get(i).map(|t| t.kind);
925 let ident_at = |i: usize| {
926 self.tokens
927 .get(i)
928 .filter(|t| t.kind == TokenKind::Ident)
929 .map(|t| self.slice(t.span).to_string())
930 };
931 match kind_at(start) {
932 Some(
933 TokenKind::Type
934 | TokenKind::Event
935 | TokenKind::Capability
936 | TokenKind::Service
937 | TokenKind::Agent
938 | TokenKind::Actor,
939 ) => ident_at(start + 1).into_iter().collect(),
940 Some(TokenKind::Fn) => match (ident_at(start + 1), kind_at(start + 2)) {
941 (Some(owner), Some(TokenKind::Dot)) => match ident_at(start + 3) {
944 Some(method) => vec![format!("{owner}.{method}")],
945 None => Vec::new(),
946 },
947 (Some(name), _) => vec![name],
948 (None, _) => Vec::new(),
949 },
950 _ => Vec::new(),
951 }
952 }
953
954 fn recover_to_top_item(&mut self) {
967 let baseline = self.item_loop_baseline.last().copied().unwrap_or(0);
968 while let Some(t) = self.peek() {
969 match t.kind {
970 TokenKind::RBrace if self.brace_depth == baseline => return,
971 _ if self.brace_depth == baseline && is_item_start(t.kind) => return,
972 _ => {
973 self.bump();
974 }
975 }
976 }
977 }
978
979 fn enter_item_loop(&mut self) {
986 self.item_loop_baseline.push(self.brace_depth);
987 }
988
989 fn exit_item_loop(&mut self) {
991 self.item_loop_baseline.pop();
992 }
993
994 fn peek(&self) -> Option<Token> {
995 self.tokens.get(self.pos).copied()
996 }
997
998 fn peek_kind(&self) -> Option<TokenKind> {
999 self.peek().map(|t| t.kind)
1000 }
1001
1002 fn take_private_modifier(&mut self, allowed: bool) -> Result<Option<Span>, CompileError> {
1014 let Some(t) = self.peek() else {
1015 return Ok(None);
1016 };
1017 if t.kind != TokenKind::Ident || self.slice(t.span) != "private" {
1018 return Ok(None);
1019 }
1020 let Some(next) = self.nth(1) else {
1021 return Ok(None);
1022 };
1023 let modifiable = matches!(
1024 next.kind,
1025 TokenKind::Fn
1026 | TokenKind::Type
1027 | TokenKind::Messages
1028 | TokenKind::Asset
1029 | TokenKind::Embed
1030 | TokenKind::Const
1031 );
1032 let declaration = modifiable
1033 || matches!(
1034 next.kind,
1035 TokenKind::Service
1036 | TokenKind::Agent
1037 | TokenKind::Capability
1038 | TokenKind::Provides
1039 | TokenKind::Actor
1040 | TokenKind::Event
1041 );
1042 if !declaration {
1043 return Ok(None);
1044 }
1045 self.bump();
1046 if modifiable && allowed {
1047 return Ok(Some(t.span));
1048 }
1049 let what = self.slice(next.span);
1050 let err = if allowed {
1051 CompileError::new(
1052 "bynk.visibility.private_not_allowed",
1053 t.span,
1054 format!("`private` does not apply to `{what}` declarations"),
1055 )
1056 .with_note(
1057 "`private` applies to `fn`, `type`, `messages`, `asset`, `embed` and `const`; a context's `exports` and `consumes` govern how far its services, agents, capabilities, providers, actors and events reach",
1058 )
1059 } else {
1060 CompileError::new(
1061 "bynk.visibility.private_not_allowed",
1062 t.span,
1063 "`private` applies only to declarations in a commons or context, not in an adapter",
1064 )
1065 .with_note("an adapter's `exports` governs what its consumers see")
1066 };
1067 if self.recover_mode {
1068 self.recovered_errors.push(err);
1069 Ok(None)
1070 } else {
1071 Err(err)
1072 }
1073 }
1074
1075 fn nth(&self, n: usize) -> Option<Token> {
1077 self.tokens.get(self.pos + n).copied()
1078 }
1079
1080 fn nth_kind(&self, n: usize) -> Option<TokenKind> {
1081 self.nth(n).map(|t| t.kind)
1082 }
1083
1084 fn nth_text(&self, n: usize) -> &'a str {
1086 self.nth(n).map(|t| self.slice(t.span)).unwrap_or("")
1087 }
1088
1089 fn prev_span(&self) -> Span {
1092 self.tokens
1093 .get(self.pos.wrapping_sub(1))
1094 .or_else(|| self.peek_ref())
1095 .map(|t| t.span)
1096 .unwrap_or_default()
1097 }
1098
1099 fn peek_ref(&self) -> Option<&Token> {
1100 self.tokens.get(self.pos)
1101 }
1102
1103 fn bump(&mut self) -> Option<Token> {
1104 let t = self.peek();
1105 if let Some(t) = t {
1106 match t.kind {
1107 TokenKind::LBrace => self.brace_depth += 1,
1108 TokenKind::RBrace => self.brace_depth = self.brace_depth.saturating_sub(1),
1109 _ => {}
1110 }
1111 self.pos += 1;
1112 }
1113 t
1114 }
1115
1116 fn eat(&mut self, kind: TokenKind) -> Option<Token> {
1117 if self.peek_kind() == Some(kind) {
1118 self.bump()
1119 } else {
1120 None
1121 }
1122 }
1123
1124 fn slice(&self, span: Span) -> &'a str {
1125 &self.source[span.range()]
1126 }
1127
1128 fn next_token_on_new_line(&self, prev: Span) -> bool {
1133 match self.peek() {
1134 Some(t) if prev.end <= t.span.start => {
1135 self.source[prev.end..t.span.start].contains('\n')
1136 }
1137 _ => false,
1138 }
1139 }
1140
1141 fn eof_span(&self) -> Span {
1146 let end = self.source.len();
1147 let start = (0..end)
1148 .rev()
1149 .find(|&i| self.source.is_char_boundary(i))
1150 .unwrap_or(0);
1151 Span::new(start, end)
1152 }
1153
1154 fn expect(&mut self, kind: TokenKind, ctx: &str) -> Result<Token, CompileError> {
1155 match self.peek() {
1156 Some(t) if t.kind == kind => {
1157 self.bump();
1158 Ok(t)
1159 }
1160 Some(t) => Err(CompileError::new(
1161 "bynk.parse.expected_token",
1162 t.span,
1163 format!(
1164 "expected {} {ctx}, found {}",
1165 kind.describe(),
1166 t.kind.describe()
1167 ),
1168 )),
1169 None => Err(CompileError::new(
1170 "bynk.parse.unexpected_eof",
1171 self.eof_span(),
1172 format!("expected {} {ctx}, found end of file", kind.describe()),
1173 )),
1174 }
1175 }
1176
1177 fn expect_ident(&mut self, ctx: &str) -> Result<Ident, CompileError> {
1178 match self.peek() {
1179 Some(t) if t.kind == TokenKind::Ident => {
1180 self.bump();
1181 Ok(Ident {
1182 name: self.slice(t.span).to_string(),
1183 span: t.span,
1184 })
1185 }
1186 Some(t) if crate::keywords::is_reserved_contextual(self.slice(t.span)) => {
1201 self.bump();
1202 Ok(Ident {
1203 name: self.slice(t.span).to_string(),
1204 span: t.span,
1205 })
1206 }
1207 Some(t) if is_reserved_keyword(t.kind) => Err(CompileError::new(
1208 "bynk.parse.reserved_keyword",
1209 t.span,
1210 format!(
1211 "expected identifier {ctx}, but `{}` is a reserved keyword",
1212 self.slice(t.span)
1213 ),
1214 )
1215 .with_note("rename the identifier to something that is not a keyword")),
1216 Some(t) => Err(CompileError::new(
1217 "bynk.parse.expected_token",
1218 t.span,
1219 format!("expected identifier {ctx}, found {}", t.kind.describe()),
1220 )),
1221 None => Err(CompileError::new(
1222 "bynk.parse.unexpected_eof",
1223 self.eof_span(),
1224 format!("expected identifier {ctx}, found end of file"),
1225 )),
1226 }
1227 }
1228
1229 fn at_keyword_label(&self) -> bool {
1233 matches!(self.peek(), Some(t) if is_reserved_keyword(t.kind))
1234 && self.tokens.get(self.pos + 1).map(|t| t.kind) == Some(TokenKind::Colon)
1235 }
1236
1237 pub(crate) fn expect_label(&mut self, ctx: &str) -> Result<Ident, CompileError> {
1243 if self.at_keyword_label() {
1244 let t = self.bump().expect("peeked a keyword");
1245 return Ok(Ident {
1246 name: self.slice(t.span).to_string(),
1247 span: t.span,
1248 });
1249 }
1250 self.expect_ident(ctx)
1251 }
1252
1253 pub(crate) fn keyword_shorthand_error(&self, pattern: bool) -> Option<CompileError> {
1265 let t = self.peek()?;
1266 if !is_reserved_keyword(t.kind) {
1267 return None;
1268 }
1269 let next = self.tokens.get(self.pos + 1).map(|t| t.kind);
1270 let shorthand = match next {
1271 Some(TokenKind::Comma | TokenKind::RBrace) => true,
1272 Some(TokenKind::DotDot) => pattern,
1273 _ => false,
1274 };
1275 if !shorthand {
1276 return None;
1277 }
1278 let word = self.slice(t.span);
1279 let mut err = CompileError::new(
1280 "bynk.parse.keyword_field_shorthand",
1281 t.span,
1282 format!("`{word}` is a reserved keyword, so it cannot be a field shorthand"),
1283 );
1284 if pattern {
1285 let taken = |name: &str| {
1286 self.tokens
1287 .iter()
1288 .any(|k| k.kind == TokenKind::Ident && self.slice(k.span) == name)
1289 };
1290 let mut binding = format!("{word}_");
1291 let mut n = 2;
1292 while taken(&binding) {
1293 binding = format!("{word}_{n}");
1294 n += 1;
1295 }
1296 err = err
1297 .with_note(format!(
1298 "the shorthand binds a variable named `{word}`; name the binding instead"
1299 ))
1300 .with_suggestion(
1301 format!("bind the `{word}` field as `{binding}`"),
1302 vec![(t.span, format!("{word}: {binding}"))],
1303 crate::error::Applicability::MaybeIncorrect,
1304 );
1305 } else {
1306 err = err.with_note(format!(
1307 "write `{word}: <value>`; a keyword names the field but cannot name a variable"
1308 ));
1309 }
1310 Some(err)
1311 }
1312
1313 pub(crate) fn expect_member_name(
1318 &mut self,
1319 ctx: &str,
1320 dot: Span,
1321 ) -> Result<Ident, CompileError> {
1322 if matches!(self.peek(), Some(t) if is_reserved_keyword(t.kind))
1323 && !self.next_token_on_new_line(dot)
1324 {
1325 let t = self.bump().expect("peeked a keyword");
1326 return Ok(Ident {
1327 name: self.slice(t.span).to_string(),
1328 span: t.span,
1329 });
1330 }
1331 self.expect_ident(ctx)
1332 }
1333
1334 fn take_doc_block(&mut self) -> Option<(Doc, Span)> {
1352 let first = self.take_one_doc()?;
1353 let mut docs = vec![first.clone()];
1354 while let Some(next) = self.peek()
1355 && matches!(next.kind, TokenKind::DocBlock | TokenKind::DocLine)
1356 && !has_blank_line_between(self.source, docs[docs.len() - 1].1.end, next.span.start)
1357 {
1358 docs.push(self.take_one_doc().expect("a doc token was peeked"));
1359 }
1360 if docs.len() > 1 && !self.doc_probe {
1361 self.doc_errors.push(multiple_docs(self.source, &docs));
1362 }
1363 Some(first)
1364 }
1365
1366 fn take_one_doc(&mut self) -> Option<(Doc, Span)> {
1368 match self.peek_kind()? {
1369 TokenKind::DocBlock => {
1370 let t = self.bump().unwrap();
1371 let body = doc_block_content(self.source, t.span);
1372 if !self.doc_probe && doc_content_is_code(&body) {
1373 self.doc_errors.push(doc_block_contains_code(t.span));
1374 }
1375 Some((Doc::new(body, DocForm::Block), t.span))
1376 }
1377 TokenKind::DocLine => {
1378 let t = self.bump().unwrap();
1379 let text = doc_line_text(self.source, t.span);
1380 Some((Doc::new(text, DocForm::Lines), t.span))
1381 }
1382 _ => None,
1383 }
1384 }
1385
1386 fn collect_item_lead(&mut self) -> (Vec<Comment>, Option<DocLead>) {
1399 self.collect_lead(Self::take_unit_leading_trivia)
1400 }
1401
1402 fn collect_body_item_lead(&mut self) -> (Vec<Comment>, Option<DocLead>) {
1405 self.collect_lead(Self::take_leading_trivia)
1406 }
1407
1408 fn collect_lead(
1409 &mut self,
1410 take: fn(&mut Self) -> Vec<Comment>,
1411 ) -> (Vec<Comment>, Option<DocLead>) {
1412 let mut leading = take(self);
1413 let doc = self.take_doc_block().map(|(content, span)| DocLead {
1414 content,
1415 span,
1416 at: leading.len(),
1417 });
1418 if doc.is_some() {
1419 leading.extend(take(self));
1420 }
1421 (leading, doc)
1422 }
1423
1424 fn collect_member_lead(&mut self, close: TokenKind) -> (Vec<Comment>, Option<Doc>) {
1433 let (mut leading, doc) = self.collect_body_item_lead();
1434 let Some(doc) = doc else {
1435 return (leading, None);
1436 };
1437 match self.peek() {
1438 Some(t) if t.kind != close => {
1439 let doc = self.finalize_doc(Some(doc), t.span, &mut leading);
1440 (leading, doc)
1441 }
1442 _ => {
1443 self.warnings.push(CompileError::new(
1444 "bynk.parse.orphan_doc_block",
1445 doc.span,
1446 "documentation has no following member to attach to",
1447 ));
1448 keep_orphan(&mut leading, doc);
1449 (leading, None)
1450 }
1451 }
1452 }
1453
1454 fn peek_past_docs(&self) -> Option<TokenKind> {
1458 self.tokens[self.pos.min(self.tokens.len())..]
1459 .iter()
1460 .map(|t| t.kind)
1461 .find(|k| !matches!(k, TokenKind::DocBlock | TokenKind::DocLine))
1462 }
1463
1464 fn finalize_doc(
1468 &mut self,
1469 doc: Option<DocLead>,
1470 next_span: Span,
1471 leading: &mut Vec<Comment>,
1472 ) -> Option<Doc> {
1473 let doc = doc?;
1474 let doc_span = doc.span;
1475 if has_blank_line_between(self.source, doc_span.end, next_span.start) {
1477 self.warnings.push(
1478 CompileError::new(
1479 "bynk.parse.orphan_doc_block",
1480 doc_span,
1481 "documentation block is separated from the following declaration by a blank line; it will not be attached",
1482 )
1483 .with_note(
1484 "remove the blank line to attach the doc to the next declaration, \
1485 or remove the doc block if it is not meant to document anything",
1486 ),
1487 );
1488 keep_orphan(leading, doc);
1489 return None;
1490 }
1491 Some(doc.content)
1492 }
1493}
1494
1495pub(crate) struct DocLead {
1499 pub(crate) content: Doc,
1500 pub(crate) span: Span,
1501 pub(crate) at: usize,
1502}
1503
1504fn keep_orphan(leading: &mut Vec<Comment>, doc: DocLead) {
1508 let at = doc.at.min(leading.len());
1509 leading.insert(at, Comment::OrphanDoc(doc.content));
1510}
1511
1512fn multiple_docs(source: &str, docs: &[(Doc, Span)]) -> CompileError {
1517 let (_, first) = docs[0];
1518 let (_, last) = docs[docs.len() - 1];
1519 let mut err = CompileError::new(
1520 "bynk.parse.multiple_docs",
1521 docs[1].1,
1522 "this declaration or member already has a doc; a target has one doc",
1523 )
1524 .with_label(first, "the first doc is here")
1525 .with_note(
1526 "a doc of more than one line is a block: a `---` line, the text, and another `---` line",
1527 );
1528 let one_liners = docs
1529 .iter()
1530 .all(|(d, span)| d.form == DocForm::Lines && !doc_line_is_legacy(source, *span));
1531 if one_liners {
1532 let line_start = source[..first.start].rfind('\n').map_or(0, |i| i + 1);
1533 let indent = &source[line_start..first.start];
1534 let text = docs
1535 .iter()
1536 .map(|(d, _)| d.as_str())
1537 .collect::<Vec<_>>()
1538 .join("\n");
1539 let fence = "-".repeat(doc_fence_len(&text));
1540 let mut block = fence.clone();
1541 for line in text.lines() {
1542 block.push('\n');
1543 if !line.is_empty() {
1544 block.push_str(indent);
1545 block.push_str(line);
1546 }
1547 }
1548 block.push('\n');
1549 block.push_str(indent);
1550 block.push_str(&fence);
1551 let end = source[..last.end].trim_end_matches(['\n', '\r']).len();
1552 err = err.with_suggestion(
1553 "join the docs into one `---` block",
1554 vec![(Span::new_in(first.file, first.start, end), block)],
1555 crate::error::Applicability::MachineApplicable,
1556 );
1557 }
1558 err
1559}
1560
1561fn doc_block_contains_code(span: Span) -> CompileError {
1564 CompileError::new(
1565 "bynk.parse.doc_block_contains_code",
1566 span,
1567 "this documentation block contains declarations, so they are not compiled",
1568 )
1569 .with_note(
1570 "a line of three or more dashes opens or closes a doc block, so two dash \
1571 dividers turn the code between them into documentation; for a divider use a \
1572 line comment with text, such as `// Helpers`, and to show code in a doc \
1573 block put it in a Markdown code fence (```)",
1574 )
1575}
1576
1577const DECLARATION_KEYWORDS: &[TokenKind] = &[
1581 TokenKind::Type,
1582 TokenKind::Fn,
1583 TokenKind::Capability,
1584 TokenKind::Provides,
1585 TokenKind::Service,
1586 TokenKind::Agent,
1587 TokenKind::Actor,
1588 TokenKind::Messages,
1589 TokenKind::Event,
1590 TokenKind::Asset,
1591 TokenKind::Embed,
1592 TokenKind::Const,
1593 TokenKind::Uses,
1594 TokenKind::Consumes,
1595 TokenKind::Exports,
1596 TokenKind::Binding,
1597];
1598
1599fn doc_content_is_code(content: &str) -> bool {
1614 doc_content_is_code_at(content, 0)
1615}
1616
1617const DOC_PROBE_MAX_DEPTH: usize = 4;
1621
1622fn doc_content_is_code_at(content: &str, depth: usize) -> bool {
1623 let stripped = strip_code_fences(content);
1624 let tokens = match crate::lexer::tokenize(&stripped) {
1625 Ok(tokens) => tokens,
1626 Err(_) => {
1627 let unmarked = blank_marker_lines(&stripped);
1630 if unmarked == stripped {
1631 return false;
1632 }
1633 return doc_content_is_code_at(&unmarked, depth);
1634 }
1635 };
1636 if depth < DOC_PROBE_MAX_DEPTH
1637 && tokens.iter().any(|t| {
1638 t.kind == TokenKind::DocBlock
1639 && doc_content_is_code_at(&doc_block_content(&stripped, t.span), depth + 1)
1640 })
1641 {
1642 return true;
1643 }
1644 if !tokens
1645 .iter()
1646 .any(|t| DECLARATION_KEYWORDS.contains(&t.kind))
1647 {
1648 return false;
1649 }
1650 let (filtered, trivia) = split_trivia(&tokens, &stripped);
1651 let mut warnings = Vec::new();
1652 let mut p = Parser::new(&filtered, &stripped, trivia, &mut warnings);
1653 p.doc_probe = true;
1654 let at = Span::new(0, 0);
1655 let name = QualifiedName {
1656 parts: Vec::new(),
1657 span: at,
1658 };
1659 match p.parse_adapter_body(at, name, None, false) {
1660 Ok(a) => {
1661 p.peek().is_none()
1662 && (!a.items.is_empty()
1663 || !a.uses.is_empty()
1664 || !a.consumes.is_empty()
1665 || !a.exports.is_empty()
1666 || a.binding.is_some())
1667 }
1668 Err(_) => false,
1669 }
1670}
1671
1672fn blank_marker_lines(content: &str) -> String {
1675 let mut out = String::with_capacity(content.len());
1676 for line in content.lines() {
1677 let trimmed = line.trim();
1678 if !(trimmed.len() >= 3 && trimmed.bytes().all(|b| b == b'-')) {
1679 out.push_str(line);
1680 }
1681 out.push('\n');
1682 }
1683 out
1684}
1685
1686fn strip_code_fences(content: &str) -> String {
1691 let mut out = String::with_capacity(content.len());
1692 let mut open: Option<(char, usize)> = None;
1693 for line in content.lines() {
1694 let trimmed = line.trim();
1695 let fence = ['`', '~'].into_iter().find_map(|c| {
1696 let n = trimmed.chars().take_while(|&x| x == c).count();
1697 (n >= 3).then_some((c, n))
1698 });
1699 match (open, fence) {
1700 (None, Some(f)) => open = Some(f),
1701 (Some((c, n)), Some((fc, fnum)))
1702 if fc == c && fnum >= n && trimmed.len() == fnum * c.len_utf8() =>
1703 {
1704 open = None;
1705 }
1706 (None, None) => out.push_str(line),
1707 (Some(_), _) => {}
1708 }
1709 out.push('\n');
1710 }
1711 out
1712}
1713
1714fn parse_string_literal(lexeme: &str, span: Span) -> Result<String, CompileError> {
1717 crate::lexer::decode_string_literal(lexeme, span)
1718}
1719
1720pub fn is_reserved_keyword(kind: TokenKind) -> bool {
1721 use TokenKind::*;
1722 matches!(
1723 kind,
1724 Commons
1725 | Type
1726 | Fn
1727 | Where
1728 | True
1729 | False
1730 | Int
1731 | String
1732 | Bool
1733 | Let
1734 | If
1735 | Else
1736 | Ok
1737 | Err
1738 | Result
1739 | ValidationError
1740 | Enum
1741 | Match
1742 | Option
1743 | Record
1744 | Self_
1745 | Some
1746 | None
1747 | Is
1748 | Opaque
1749 | Uses
1750 | Context
1751 | Consumes
1752 | Exports
1753 | Transparent
1754 | Agent
1755 | As
1756 | Capability
1757 | Effect
1758 | Do
1759 | Given
1760 | On
1761 | Http
1762 | Provides
1763 | Stub
1764 | Service
1765 | Actor
1766 | Expect
1767 | Suite
1768 | Case
1769 | Float
1770 | Duration
1771 | Instant
1772 | Bytes
1773 | Decimal
1774 | DecodeError
1775 | JsonErrorDeprecated
1776 | Property
1777 | Adapter
1778 | Binding
1779 | Cron
1780 | Queue
1781 | From
1782 | Protocol
1783 | Invariant
1784 | Implies
1785 | Requires
1786 | Ensures
1787 | Transition
1788 )
1789}
1790
1791fn is_item_start(kind: TokenKind) -> bool {
1802 use TokenKind::*;
1803 matches!(
1804 kind,
1805 Commons | Context | Adapter | Suite
1807 | Type | Fn | Messages | Event | Asset | Embed | Const | Uses
1809 | Consumes | Exports | Capability | Provides | Service | Agent | Actor
1811 | Binding
1813 | Stub | Case | Property
1815 )
1816}
1817
1818#[cfg(test)]
1819mod tests {
1820 use super::*;
1821 use crate::lexer::tokenize;
1822
1823 fn parse_str(src: &str) -> Result<Commons, Vec<CompileError>> {
1824 let toks = tokenize(src).map_err(|e| vec![e])?;
1825 parse(&toks, src)
1826 }
1827
1828 fn parse_recover_str(src: &str) -> (Option<SourceUnit>, Vec<CompileError>) {
1829 let toks = match tokenize(src) {
1830 Ok(t) => t,
1831 Err(e) => return (None, vec![e]),
1832 };
1833 parse_unit_with_recovery(&toks, src)
1834 }
1835
1836 #[test]
1840 fn contract_clause_name_before_next_line_brace_is_not_a_record() {
1841 for src in [
1842 "commons m\n\nconst Limit: Int = 10\n\nfn small(n: Int) -> Int\n requires small: n <= Limit\n{\n n\n}\n",
1843 "commons m\n\nfn f(n: Int) -> Int\n ensures same: result == n\n{\n n\n}\n",
1844 "commons m\n\nfn f(n: Int) -> Int\n requires r: n <= Limit {\n n\n}\n",
1845 ] {
1846 assert!(parse_str(src).is_ok(), "{src}\n{:?}", parse_str(src).err());
1847 }
1848 let src = "commons m\n\ntype P = { x: Int }\n\nfn f(p: P) -> Int\n requires r: (p == P { x: 1 })\n{\n 1\n}\n";
1850 assert!(parse_str(src).is_ok(), "{:?}", parse_str(src).err());
1851 }
1852
1853 #[test]
1856 fn contract_clause_unparenthesised_record_literal_is_rejected() {
1857 let src = "commons m\n\ntype P = { x: Int }\n\nfn f(p: P) -> Int\n requires r: p == P { x: 1 }\n{\n 1\n}\n";
1858 assert!(parse_str(src).is_err());
1859 }
1860
1861 #[test]
1867 fn parse_units_with_recovery_keeps_every_top_level_unit() {
1868 let src =
1869 "commons m {\n fn f() -> Int { 1 }\n}\n\nsuite m\n\ncase \"c\" {\n expect true\n}\n";
1870 let toks = tokenize(src).unwrap();
1871 let (units, errors) = parse_units_with_recovery(&toks, src);
1872 assert!(errors.is_empty(), "{errors:?}");
1873 assert_eq!(units.len(), 2, "expected both units, got {units:?}");
1874 assert!(matches!(units[0], SourceUnit::Commons(_)));
1875 assert!(matches!(units[1], SourceUnit::Suite(_)));
1876
1877 let (unit, errors) = parse_unit_with_recovery(&toks, src);
1879 assert!(errors.is_empty(), "{errors:?}");
1880 assert!(matches!(unit, Some(SourceUnit::Commons(_))));
1881 }
1882
1883 #[test]
1890 fn empty_input_still_reports_an_error_through_the_plural_entry_point() {
1891 let toks = tokenize("").unwrap();
1892 let (units, errors) = parse_units_with_recovery(&toks, "");
1893 assert!(units.is_empty());
1894 assert!(
1895 !errors.is_empty(),
1896 "an empty file must still produce a diagnostic, not silently no units and no error"
1897 );
1898
1899 let (unit, unit_errors) = parse_unit_with_recovery(&toks, "");
1900 assert!(unit.is_none());
1901 assert_eq!(
1902 errors.len(),
1903 unit_errors.len(),
1904 "the singular wrapper must see the same error(s) as the plural entry point"
1905 );
1906 }
1907
1908 #[test]
1915 fn drain_check_reports_expression_interior_comments_as_undrained() {
1916 let ordinary = "commons x {\n// note\ntype T = Int where Positive\n}\n";
1917 let toks = tokenize(ordinary).unwrap();
1918 let (_, _, drained) = parse_units_with_drain_check(&toks, ordinary).unwrap();
1919 assert!(
1920 drained,
1921 "a declaration-leading comment must be fully drained"
1922 );
1923
1924 let lossy = "commons x {\n fn f() -> Int {\n 1 + // note\n 2\n }\n}\n";
1925 let toks = tokenize(lossy).unwrap();
1926 let (_, _, drained) = parse_units_with_drain_check(&toks, lossy).unwrap();
1927 assert!(
1928 !drained,
1929 "a comment inside a binop expression must be reported as undrained"
1930 );
1931 }
1932
1933 #[test]
1934 fn eof_span_never_splits_a_multibyte_codepoint() {
1935 for src in [
1940 "commons x {\n // ends with an arrow →",
1941 "agent A {\n key k: String\n // note 🦀",
1942 "commons y {\n type T = é",
1943 ] {
1944 let (_unit, errors) = parse_recover_str(src);
1945 for e in &errors {
1946 assert!(
1947 src.is_char_boundary(e.span.start) && src.is_char_boundary(e.span.end),
1948 "span {:?} splits a codepoint in {src:?}",
1949 e.span,
1950 );
1951 }
1952 }
1953 }
1954
1955 #[test]
1956 fn reserved_contextual_keywords_readable_in_expression_position() {
1957 for kw in [
1967 "asset", "case", "const", "embed", "event", "messages", "on", "suite",
1968 ] {
1969 let src = format!("commons x\n\nfn f({kw}: Int) -> Int {{\n {kw}\n}}\n");
1970 let result = parse_str(&src);
1971 assert!(
1972 result.is_ok(),
1973 "a parameter named `{kw}` must be readable in expression position: {:?}",
1974 result.err()
1975 );
1976 }
1977 }
1978
1979 #[test]
1983 fn contextual_keywords_open_a_record_literal() {
1984 for kw in [
1985 "asset", "case", "const", "embed", "event", "messages", "on", "suite",
1986 ] {
1987 let src = format!(
1988 "commons x\n\ntype R = {{ {kw}: Int, other: Int }}\n\n\
1989 fn first() -> R {{\n R {{ {kw}: 1, other: 2 }}\n}}\n\n\
1990 fn last() -> R {{\n R {{ other: 2, {kw}: 1 }}\n}}\n"
1991 );
1992 let result = parse_str(&src);
1993 assert!(
1994 result.is_ok(),
1995 "a record literal with `{kw}` as a field label must parse: {:?}",
1996 result.err()
1997 );
1998 }
1999 }
2000
2001 #[test]
2002 fn recovery_skips_garbage_between_decls() {
2003 let src = "commons x {\n\
2006 type A = Int where NonNegative\n\
2007 ??? !!!\n\
2008 type B = String where NonEmpty\n\
2009 }";
2010 let (unit, errors) = parse_recover_str(src);
2011 let unit = unit.expect("recovery should produce a partial AST");
2012 let SourceUnit::Commons(c) = unit else {
2013 panic!("expected commons")
2014 };
2015 let names: Vec<_> = c
2017 .items
2018 .iter()
2019 .map(|i| match i {
2020 CommonsItem::Type(t) => t.name.name.clone(),
2021 _ => panic!("expected only types"),
2022 })
2023 .collect();
2024 assert!(
2025 names.contains(&"A".to_string()) && names.contains(&"B".to_string()),
2026 "expected both A and B; got {names:?}",
2027 );
2028 assert!(!errors.is_empty(), "expected at least one parse error");
2029 }
2030
2031 #[test]
2032 fn recovery_handles_bad_first_decl_then_good_second() {
2033 let src = "commons x {\n\
2035 type A Int where NonNegative\n\
2036 type B = String where NonEmpty\n\
2037 }";
2038 let (unit, errors) = parse_recover_str(src);
2039 let unit = unit.expect("recovery should produce a partial AST");
2040 let SourceUnit::Commons(c) = unit else {
2041 panic!("expected commons")
2042 };
2043 let names: Vec<_> = c
2044 .items
2045 .iter()
2046 .filter_map(|i| match i {
2047 CommonsItem::Type(t) => Some(t.name.name.clone()),
2048 _ => None,
2049 })
2050 .collect();
2051 assert!(
2052 names.contains(&"B".to_string()),
2053 "B should be parsed after A's failure; got {names:?}"
2054 );
2055 assert!(!errors.is_empty(), "expected at least one parse error");
2056 }
2057
2058 #[test]
2073 fn recovery_keeps_the_bodys_closing_brace_after_a_bodiless_item() {
2074 let src = "commons m {\n fn f() -> Int\n}\n";
2075 let (unit, errors) = parse_recover_str(src);
2076 assert!(unit.is_some(), "recovery should produce a partial AST");
2077 let categories: Vec<_> = errors.iter().map(|e| e.category).collect();
2078 assert_eq!(
2079 categories.len(),
2080 1,
2081 "one syntax error, no follow-on: {categories:?}"
2082 );
2083 assert!(
2084 !categories.contains(&"bynk.parse.unexpected_eof"),
2085 "the commons' closing brace must survive: {categories:?}"
2086 );
2087 }
2088
2089 #[test]
2094 fn recovery_skips_a_rejected_item_whole() {
2095 let src = "commons m\n\nagent Counter {\n key id: String\n}\n\nfn g() -> Int { 2 }\n";
2096 let recovered = parse_units_recovering(&crate::lexer::tokenize(src).unwrap(), src);
2097 assert_eq!(
2098 recovered.errors.len(),
2099 1,
2100 "one syntax error, no follow-on: {:?}",
2101 recovered
2102 .errors
2103 .iter()
2104 .map(|e| e.category)
2105 .collect::<Vec<_>>()
2106 );
2107 let Some(SourceUnit::Commons(c)) = recovered.units.first() else {
2108 panic!("expected commons")
2109 };
2110 assert!(
2111 c.items.iter().any(|i| matches!(i, CommonsItem::Fn(_))),
2112 "the `fn g` after the skipped agent must still parse"
2113 );
2114 assert_eq!(recovered.broken_decl_names, ["Counter"]);
2115 }
2116
2117 #[test]
2118 fn recovery_skips_a_nested_blocks_own_closing_brace() {
2119 let src = "commons m {\n \
2120 fn f() -> Int {\n \
2121 match 1 {\n \
2122 is 1 -> { let z = }\n \
2123 is _ -> 2\n \
2124 }\n \
2125 }\n \
2126 fn g() -> Int { 2 }\n\
2127 }\n";
2128 let (unit, errors) = parse_recover_str(src);
2129 let unit = unit.expect("recovery should produce a partial AST");
2130 let SourceUnit::Commons(c) = unit else {
2131 panic!("expected commons")
2132 };
2133 let names: Vec<_> = c
2134 .items
2135 .iter()
2136 .filter_map(|i| match i {
2137 CommonsItem::Fn(f) => match &f.name {
2138 FnName::Free(id) => Some(id.name.clone()),
2139 _ => None,
2140 },
2141 _ => None,
2142 })
2143 .collect();
2144 assert_eq!(
2145 names,
2146 vec!["g".to_string()],
2147 "g must still be recovered as an item; got {names:?}"
2148 );
2149 assert!(
2150 !errors
2151 .iter()
2152 .any(|e| e.category == "bynk.parse.expected_unit_header"),
2153 "the outer body's own closing brace must not be mistaken for \
2154 end-of-file: {errors:?}"
2155 );
2156 }
2157
2158 #[test]
2159 fn doc_block_attaches_to_type() {
2160 let c =
2161 parse_str("commons x {\n---\nA descriptive doc.\n---\ntype T = Int where Positive\n}")
2162 .unwrap();
2163 let CommonsItem::Type(t) = &c.items[0] else {
2164 panic!()
2165 };
2166 assert!(t.documentation.is_some());
2167 assert!(
2168 t.documentation
2169 .as_ref()
2170 .unwrap()
2171 .contains("A descriptive doc.")
2172 );
2173 }
2174
2175 #[test]
2176 fn interpolated_string_parses_into_parts() {
2177 let c = parse_str("commons x\n\nfn f(name: String) -> String {\n \"Hi, \\(name)!\"\n}\n")
2179 .unwrap();
2180 let CommonsItem::Fn(f) = &c.items[0] else {
2181 panic!("expected fn")
2182 };
2183 let ExprKind::InterpStr(parts) = &f.body.tail.kind else {
2184 panic!("expected InterpStr, got {:?}", f.body.tail.kind)
2185 };
2186 assert_eq!(parts.len(), 3);
2187 assert!(matches!(&parts[0], InterpPart::Chunk(s) if s == "Hi, "));
2188 assert!(
2189 matches!(&parts[1], InterpPart::Hole(h) if matches!(&h.kind, ExprKind::Ident(id) if id.name == "name"))
2190 );
2191 assert!(matches!(&parts[2], InterpPart::Chunk(s) if s == "!"));
2192 }
2193
2194 #[test]
2195 fn interpolated_hole_parses_a_full_expression() {
2196 let c =
2198 parse_str("commons x\n\nfn f(a: Int, b: Int) -> String {\n \"sum = \\(a + b)\"\n}\n")
2199 .unwrap();
2200 let CommonsItem::Fn(f) = &c.items[0] else {
2201 panic!("expected fn")
2202 };
2203 let ExprKind::InterpStr(parts) = &f.body.tail.kind else {
2204 panic!("expected InterpStr")
2205 };
2206 assert!(matches!(&parts[1], InterpPart::Hole(h) if matches!(&h.kind, ExprKind::BinOp(..))));
2207 }
2208
2209 #[test]
2210 fn empty_interpolation_hole_is_rejected() {
2211 let errs = parse_str("commons x\n\nfn f() -> String {\n \"\\()\"\n}\n").unwrap_err();
2212 assert!(
2213 errs.iter()
2214 .any(|e| e.category == "bynk.parse.empty_interpolation"),
2215 "expected empty_interpolation; got {errs:?}"
2216 );
2217 }
2218
2219 #[test]
2220 fn interpolation_hole_lex_error_span_is_rebased() {
2221 let cases = [
2227 "commons x\n\nfn f() -> String {\n \"a \\($)\"\n}\n",
2229 "commons x\n\nfn f() -> String {\n \"n = \\(99999999999999999999)\"\n}\n",
2231 "commons x\n\nfn f() -> String {\n \"é \\($)\"\n}\n",
2234 ];
2235 for src in cases {
2236 let errs = parse_str(src).unwrap_err();
2237 assert!(!errs.is_empty(), "expected a lex error for {src:?}");
2238 for e in &errs {
2239 assert!(
2240 src.is_char_boundary(e.span.start) && src.is_char_boundary(e.span.end),
2241 "span {:?} splits a codepoint in {src:?}",
2242 e.span,
2243 );
2244 let hole_start = src.find("\\(").expect("case has a hole") + 2;
2247 assert!(
2248 e.span.start >= hole_start,
2249 "span {:?} precedes the hole (starts at {hole_start}) in {src:?}",
2250 e.span,
2251 );
2252 }
2253 }
2254 }
2255
2256 #[test]
2257 fn fragment_form_parses() {
2258 let c = parse_str("commons x.y\n\ntype T = Int where NonNegative\n").unwrap();
2259 assert_eq!(c.form, CommonsForm::Fragment);
2260 assert_eq!(c.items.len(), 1);
2261 }
2262
2263 #[test]
2264 fn uses_parses() {
2265 let c = parse_str("commons x\n\nuses other.lib\n").unwrap();
2266 assert_eq!(c.uses.len(), 1);
2267 assert_eq!(c.uses[0].target.joined(), "other.lib");
2268 }
2269
2270 #[test]
2272 fn percent_is_a_targeted_error_with_a_fix_for_simple_operands() {
2273 let err = |expr: &str| {
2274 let src = format!("commons m\n\nfn f(n: Int, k: Int) -> Int {{ {expr} }}\n");
2275 let errs = parse_str(&src).unwrap_err();
2276 assert_eq!(
2277 errs[0].category, "bynk.parse.no_remainder_operator",
2278 "{expr}"
2279 );
2280 errs.into_iter().next().unwrap()
2281 };
2282 let fix = err("n % 2");
2283 assert_eq!(fix.suggestions.len(), 1);
2284 assert_eq!(
2285 fix.notes,
2286 [
2287 "use `a.rem(b)` for the C-family remainder, which takes the dividend's sign, \
2288 or `a.mod(b)` for the modulo, which takes the divisor's sign"
2289 ]
2290 );
2291 assert_eq!(fix.suggestions[0].edits[0].1, "n.rem(2)");
2292 assert_eq!(
2293 fix.suggestions[0].applicability,
2294 crate::error::Applicability::MaybeIncorrect
2295 );
2296 assert_eq!(err("n % k").suggestions[0].edits[0].1, "n.rem(k)");
2297 for complex in [
2298 "(n + 1) % k",
2299 "n * 2 % k",
2300 "n % (k + 1)",
2301 "-n % k",
2302 "n % -k",
2303 ] {
2304 assert!(err(complex).suggestions.is_empty(), "{complex}");
2305 }
2306 }
2307
2308 fn parse_unit_str(src: &str) -> Result<SourceUnit, Vec<CompileError>> {
2309 let toks = tokenize(src).map_err(|e| vec![e])?;
2310 parse_unit(&toks, src)
2311 }
2312
2313 #[test]
2314 fn minimal_context_parses() {
2315 let u = parse_unit_str("context commerce.orders {}").unwrap();
2316 let SourceUnit::Context(c) = u else {
2317 panic!("expected context");
2318 };
2319 assert_eq!(c.name.joined(), "commerce.orders");
2320 assert!(c.items.is_empty());
2321 }
2322
2323 #[test]
2324 fn context_consumes_and_exports_parse() {
2325 let src = "context commerce.orders {\n uses commerce.money\n consumes commerce.payment\n exports opaque { OrderId }\n exports transparent { OrderError }\n type OrderId = String where Matches(\"ORD-[0-9]+\")\n type OrderError = enum { CartEmpty, BadInput }\n}";
2326 let u = parse_unit_str(src).unwrap();
2327 let SourceUnit::Context(c) = u else { panic!() };
2328 assert_eq!(c.uses.len(), 1);
2329 assert_eq!(c.consumes.len(), 1);
2330 assert_eq!(c.exports.len(), 2);
2331 assert_eq!(c.exports[0].kind, ExportKind::Type(Visibility::Opaque));
2332 assert_eq!(c.exports[1].kind, ExportKind::Type(Visibility::Transparent));
2333 }
2334
2335 #[test]
2336 fn context_fragment_form_parses() {
2337 let src = "context x.y\n\nuses other.lib\nconsumes other.ctx\nexports opaque { T }\n\ntype T = Int where NonNegative\n";
2338 let u = parse_unit_str(src).unwrap();
2339 let SourceUnit::Context(c) = u else { panic!() };
2340 assert_eq!(c.form, CommonsForm::Fragment);
2341 assert_eq!(c.uses.len(), 1);
2342 assert_eq!(c.consumes.len(), 1);
2343 assert_eq!(c.exports.len(), 1);
2344 }
2345
2346 #[test]
2347 fn opaque_type_parses() {
2348 let c = parse_str("commons x { type T = opaque Int where NonNegative }").unwrap();
2349 let CommonsItem::Type(t) = &c.items[0] else {
2350 panic!()
2351 };
2352 assert!(matches!(t.body, TypeBody::Opaque { .. }));
2353 }
2354
2355 #[test]
2356 fn empty_commons() {
2357 let c = parse_str("commons fitness.units {}").unwrap();
2358 assert_eq!(c.name.joined(), "fitness.units");
2359 assert!(c.items.is_empty());
2360 }
2361
2362 #[test]
2363 fn one_type_decl() {
2364 let c = parse_str("commons x { type Metres = Int where NonNegative }").unwrap();
2365 assert_eq!(c.items.len(), 1);
2366 let CommonsItem::Type(t) = &c.items[0] else {
2367 panic!()
2368 };
2369 assert_eq!(t.name.name, "Metres");
2370 match &t.body {
2371 TypeBody::Refined {
2372 base, refinement, ..
2373 } => {
2374 assert_eq!(*base, BaseType::Int);
2375 assert!(refinement.is_some());
2376 }
2377 _ => panic!("expected refined body"),
2378 }
2379 }
2380
2381 #[test]
2382 fn function_decl() {
2383 let c = parse_str("commons x { fn add(a: Int, b: Int) -> Int { a + b } }").unwrap();
2384 let CommonsItem::Fn(f) = &c.items[0] else {
2385 panic!()
2386 };
2387 assert_eq!(f.name.ident().name, "add");
2388 assert_eq!(f.params.len(), 2);
2389 }
2390
2391 #[test]
2392 fn chained_comparison_is_error() {
2393 let errs = parse_str("commons x { fn f(a: Int, b: Int, c: Int) -> Bool { a < b < c } }")
2394 .unwrap_err();
2395 assert_eq!(errs[0].category, "bynk.parse.non_associative");
2396 }
2397
2398 #[test]
2399 fn chained_equality_is_error() {
2400 let errs = parse_str("commons x { fn f(a: Int, b: Int, c: Int) -> Bool { a == b == c } }")
2401 .unwrap_err();
2402 assert_eq!(errs[0].category, "bynk.parse.non_associative");
2403 }
2404
2405 fn on_big_stack<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> T {
2414 std::thread::Builder::new()
2415 .stack_size(64 * 1024 * 1024)
2416 .spawn(f)
2417 .unwrap()
2418 .join()
2419 .unwrap()
2420 }
2421
2422 #[test]
2423 fn deeply_nested_parens_are_bounded_not_overflowed() {
2424 let errs = on_big_stack(|| {
2430 let depth = crate::MAX_NESTING_DEPTH + 8;
2431 let src = format!(
2432 "commons x {{ fn f() -> Int {{ {}0{} }} }}",
2433 "(".repeat(depth),
2434 ")".repeat(depth),
2435 );
2436 parse_str(&src).unwrap_err()
2437 });
2438 assert_eq!(errs[0].category, "bynk.parse.nesting_too_deep");
2439 }
2440
2441 #[test]
2442 fn deeply_nested_types_are_bounded_not_overflowed() {
2443 let errs = on_big_stack(|| {
2448 let depth = crate::MAX_NESTING_DEPTH + 8;
2449 let src = format!(
2450 "commons x {{ fn f(x: {}Int{}) -> Int {{ 0 }} }}",
2451 "Result[Int, ".repeat(depth),
2452 "]".repeat(depth),
2453 );
2454 parse_str(&src).unwrap_err()
2455 });
2456 assert_eq!(errs[0].category, "bynk.parse.nesting_too_deep");
2457 }
2458
2459 #[test]
2460 fn deeply_nested_patterns_are_bounded_not_overflowed() {
2461 let errs = on_big_stack(|| {
2466 let depth = crate::MAX_NESTING_DEPTH + 8;
2467 let src = format!(
2468 "commons x {{ fn f(n: Int) -> Int {{ match n {{ {}n{} => 0 }} }} }}",
2469 "Ok(".repeat(depth),
2470 ")".repeat(depth),
2471 );
2472 parse_str(&src).unwrap_err()
2473 });
2474 assert_eq!(errs[0].category, "bynk.parse.nesting_too_deep");
2475 }
2476
2477 #[test]
2478 fn nesting_below_the_limit_still_parses() {
2479 let ok = on_big_stack(|| {
2482 let depth = crate::MAX_NESTING_DEPTH - 8;
2483 let src = format!(
2484 "commons x {{ fn f() -> Int {{ {}0{} }} }}",
2485 "(".repeat(depth),
2486 ")".repeat(depth),
2487 );
2488 parse_str(&src).is_ok()
2489 });
2490 assert!(ok, "well-nested source under the limit should parse");
2491 }
2492
2493 #[test]
2494 fn let_statement_parses() {
2495 let c = parse_str("commons x { fn f(n: Int) -> Int { let y = n + 1\n y } }").unwrap();
2496 let CommonsItem::Fn(f) = &c.items[0] else {
2497 panic!()
2498 };
2499 assert_eq!(f.body.statements.len(), 1);
2500 match &f.body.statements[0] {
2501 Statement::Let(l) => {
2502 assert_eq!(l.name.name, "y");
2503 assert!(l.type_annot.is_none());
2504 }
2505 _ => panic!("expected a pure `let` statement"),
2506 }
2507 }
2508
2509 #[test]
2510 fn let_with_annotation() {
2511 let c = parse_str("commons x { fn f(n: Int) -> Int { let y: Int = n\n y } }").unwrap();
2512 let CommonsItem::Fn(f) = &c.items[0] else {
2513 panic!()
2514 };
2515 match &f.body.statements[0] {
2516 Statement::Let(l) => assert!(l.type_annot.is_some()),
2517 _ => panic!("expected a pure `let` statement"),
2518 }
2519 }
2520
2521 #[test]
2522 fn if_else_parses_as_expression() {
2523 let c = parse_str("commons x { fn f(b: Bool) -> Int { if b { 1 } else { 0 } } }").unwrap();
2524 let CommonsItem::Fn(f) = &c.items[0] else {
2525 panic!()
2526 };
2527 assert!(matches!(f.body.tail.kind, ExprKind::If { .. }));
2528 }
2529
2530 #[test]
2531 fn else_if_chain_parses() {
2532 let c = parse_str(
2533 "commons x { fn f(n: Int) -> Int { if n < 0 { -1 } else if n == 0 { 0 } else { 1 } } }",
2534 )
2535 .unwrap();
2536 let CommonsItem::Fn(f) = &c.items[0] else {
2537 panic!()
2538 };
2539 let ExprKind::If { else_block, .. } = &f.body.tail.kind else {
2540 panic!()
2541 };
2542 assert!(else_block.statements.is_empty());
2544 assert!(matches!(else_block.tail.kind, ExprKind::If { .. }));
2545 }
2546
2547 #[test]
2548 fn ok_and_err_parse_as_expressions() {
2549 let c = parse_str("commons x { fn f(n: Int) -> Result[Int, String] { Ok(n) } }").unwrap();
2550 let CommonsItem::Fn(f) = &c.items[0] else {
2551 panic!()
2552 };
2553 assert!(matches!(f.body.tail.kind, ExprKind::Ok(_)));
2554
2555 let c =
2556 parse_str("commons x { fn f(n: Int) -> Result[Int, String] { Err(\"x\") } }").unwrap();
2557 let CommonsItem::Fn(f) = &c.items[0] else {
2558 panic!()
2559 };
2560 assert!(matches!(f.body.tail.kind, ExprKind::Err(_)));
2561 }
2562
2563 #[test]
2564 fn question_postfix_parses() {
2565 let c = parse_str(
2566 "commons x { type T = Int where Positive\n fn f(n: Int) -> Result[T, ValidationError] { let x = T.of(n)?\n Ok(x) } }",
2567 )
2568 .unwrap();
2569 let CommonsItem::Fn(f) = &c.items[1] else {
2570 panic!()
2571 };
2572 let Statement::Let(l) = &f.body.statements[0] else {
2573 panic!("expected a pure `let` statement");
2574 };
2575 assert!(matches!(l.value.kind, ExprKind::Question(_)));
2576 }
2577
2578 #[test]
2579 fn constructor_call_parses() {
2580 let c = parse_str(
2581 "commons x { type T = Int where Positive\n fn f(n: Int) -> Result[T, ValidationError] { T.of(n) } }",
2582 )
2583 .unwrap();
2584 let CommonsItem::Fn(f) = &c.items[1] else {
2585 panic!()
2586 };
2587 let ExprKind::MethodCall {
2590 receiver, method, ..
2591 } = &f.body.tail.kind
2592 else {
2593 panic!("expected MethodCall, got {:?}", f.body.tail.kind)
2594 };
2595 let ExprKind::Ident(id) = &receiver.kind else {
2596 panic!("expected receiver Ident");
2597 };
2598 assert_eq!(id.name, "T");
2599 assert_eq!(method.name, "of");
2600 }
2601
2602 #[test]
2603 fn result_type_ref_parses() {
2604 let c = parse_str("commons x { fn f(n: Int) -> Result[Int, String] { Ok(n) } }").unwrap();
2605 let CommonsItem::Fn(f) = &c.items[0] else {
2606 panic!()
2607 };
2608 assert!(matches!(f.return_type, TypeRef::Result(_, _, _)));
2609 }
2610
2611 #[test]
2612 fn result_missing_arg_count_errors() {
2613 let errs = parse_str("commons x { fn f(n: Int) -> Result[Int] { Ok(n) } }").unwrap_err();
2614 assert_eq!(errs[0].category, "bynk.parse.generic_arg_count");
2615 }
2616
2617 #[test]
2618 fn field_access_parses_in_v0_2() {
2619 let c =
2622 parse_str("commons x { type R = { foo: Int }\n fn f(r: R) -> Int { r.foo } }").unwrap();
2623 let CommonsItem::Fn(f) = &c.items[1] else {
2624 panic!()
2625 };
2626 assert!(matches!(f.body.tail.kind, ExprKind::FieldAccess { .. }));
2627 }
2628
2629 #[test]
2632 fn leading_line_comment_attaches_to_next_decl() {
2633 let src = "commons x {\n// explain the type\ntype T = Int where NonNegative\n}";
2634 let c = parse_str(src).unwrap();
2635 let CommonsItem::Type(t) = &c.items[0] else {
2636 panic!()
2637 };
2638 assert_eq!(
2639 t.trivia.leading,
2640 vec![Comment::Line(" explain the type".to_string())]
2641 );
2642 assert!(t.trivia.trailing.is_none());
2643 }
2644
2645 #[test]
2646 fn trailing_line_comment_attaches_to_prev_decl() {
2647 let src = "commons x {\ntype T = Int where NonNegative // trailing note\n}";
2648 let c = parse_str(src).unwrap();
2649 let CommonsItem::Type(t) = &c.items[0] else {
2650 panic!()
2651 };
2652 assert!(t.trivia.leading.is_empty());
2653 assert_eq!(t.trivia.trailing.as_deref(), Some(" trailing note"));
2654 }
2655
2656 #[test]
2657 fn grouped_leading_comments_attach_together() {
2658 let src = "commons x {\n// one\n// two\n// three\ntype T = Int where Positive\n}";
2659 let c = parse_str(src).unwrap();
2660 let CommonsItem::Type(t) = &c.items[0] else {
2661 panic!()
2662 };
2663 assert_eq!(
2664 t.trivia.leading,
2665 vec![
2666 Comment::Line(" one".to_string()),
2667 Comment::Line(" two".to_string()),
2668 Comment::Line(" three".to_string())
2669 ],
2670 );
2671 }
2672
2673 #[test]
2674 fn comment_with_doc_block_keeps_both() {
2675 let src = "commons x {\n// intro\n---\ndocs\n---\ntype T = Int where Positive\n}";
2677 let c = parse_str(src).unwrap();
2678 let CommonsItem::Type(t) = &c.items[0] else {
2679 panic!()
2680 };
2681 assert_eq!(t.trivia.leading, vec![Comment::Line(" intro".to_string())]);
2682 assert_eq!(t.documentation.as_deref(), Some("docs"));
2683 }
2684
2685 #[test]
2686 fn messages_keyword_does_not_collide_with_a_commons_name_segment() {
2687 let src = "commons app.messages {\ntype T = Int where Positive\n}";
2693 let c = parse_str(src).unwrap();
2694 assert_eq!(c.name.joined(), "app.messages");
2695 }
2696
2697 #[test]
2698 fn messages_decl_parses_tag_annotation_and_entries() {
2699 let src = "commons app.messages {\n\
2701 // intro\n\
2702 ---\n\
2703 docs\n\
2704 ---\n\
2705 messages \"en\" @reference {\n\
2706 \"greeting\" => \"Hello, {name}!\"\n\
2707 \"farewell\" => \"Bye\"\n\
2708 } // trailing\n\
2709 }";
2710 let c = parse_str(src).unwrap();
2711 let CommonsItem::Messages(m) = &c.items[0] else {
2712 panic!("expected a messages item, got {:?}", c.items[0]);
2713 };
2714 assert_eq!(m.tag, "en");
2715 assert_eq!(m.annotations.len(), 1);
2716 assert_eq!(m.annotations[0].name.name, "reference");
2717 assert!(m.annotations[0].args.is_empty());
2718 assert_eq!(m.entries.len(), 2);
2719 assert_eq!(m.entries[0].code, "greeting");
2720 assert_eq!(m.entries[0].template, "Hello, {name}!");
2721 assert_eq!(m.entries[1].code, "farewell");
2722 assert_eq!(m.entries[1].template, "Bye");
2723 assert_eq!(m.trivia.leading, vec![Comment::Line(" intro".to_string())]);
2724 assert_eq!(m.documentation.as_deref(), Some("docs"));
2725 assert_eq!(m.trivia.trailing.as_deref(), Some(" trailing"));
2726 }
2727
2728 #[test]
2729 fn messages_decl_parses_with_no_annotation_and_no_entries() {
2730 let src = "commons app.messages {\nmessages \"en\" {\n}\n}";
2734 let c = parse_str(src).unwrap();
2735 let CommonsItem::Messages(m) = &c.items[0] else {
2736 panic!("expected a messages item, got {:?}", c.items[0]);
2737 };
2738 assert_eq!(m.tag, "en");
2739 assert!(m.annotations.is_empty());
2740 assert!(m.entries.is_empty());
2741 }
2742
2743 #[test]
2744 fn messages_decl_parses_syntactically_inside_a_context_too() {
2745 let src = "context app.svc {\nmessages \"en\" @reference {\n\"a\" => \"b\"\n}\n}";
2750 let toks = tokenize(src).unwrap();
2751 let (unit, errors) = parse_unit_with_recovery(&toks, src);
2752 assert!(errors.is_empty(), "unexpected parse errors: {errors:?}");
2753 let Some(SourceUnit::Context(ctx)) = unit else {
2754 panic!("expected a context")
2755 };
2756 let CommonsItem::Messages(m) = &ctx.items[0] else {
2757 panic!("expected a messages item, got {:?}", ctx.items[0]);
2758 };
2759 assert_eq!(m.tag, "en");
2760 }
2761
2762 #[test]
2763 fn comment_before_let_statement_attaches() {
2764 let src = "commons x {\nfn f(n: Int) -> Int {\n// pick a value\nlet y = n + 1\ny\n}\n}";
2765 let c = parse_str(src).unwrap();
2766 let CommonsItem::Fn(f) = &c.items[0] else {
2767 panic!()
2768 };
2769 let Statement::Let(l) = &f.body.statements[0] else {
2770 panic!()
2771 };
2772 assert_eq!(
2773 l.trivia.leading,
2774 vec![Comment::Line(" pick a value".to_string())]
2775 );
2776 }
2777
2778 #[test]
2779 fn comment_before_tail_attaches_to_block_tail() {
2780 let src = "commons x {\nfn f(n: Int) -> Int {\nlet y = n + 1\n// result\ny\n}\n}";
2781 let c = parse_str(src).unwrap();
2782 let CommonsItem::Fn(f) = &c.items[0] else {
2783 panic!()
2784 };
2785 assert_eq!(
2786 f.body.tail_leading_comments,
2787 vec![Comment::Line(" result".to_string())],
2788 );
2789 }
2790
2791 #[test]
2797 fn contextual_keywords_are_valid_identifiers() {
2798 let c = parse_str("commons demo {\n type R = { on: Int, suite: String, case: Bool }\n}")
2800 .expect("`on`/`suite`/`case` are valid field names");
2801 let CommonsItem::Type(_) = &c.items[0] else {
2802 panic!("expected a type decl")
2803 };
2804
2805 parse_str("commons demo {\n fn f(on: Int, case: Int) -> Int { 0 }\n}")
2807 .expect("`on`/`case` are valid parameter names");
2808
2809 parse_str("commons demo {\n type R = { suite: Int }\n}")
2811 .expect("`suite` is a valid field name");
2812 }
2813
2814 #[test]
2817 fn keywords_are_labels_and_members_not_bindings() {
2818 for src in [
2819 "commons demo {\n type A = { type: String, from: Int, self: Bool }\n}",
2820 "commons demo {\n type S = | P(from: String, type: String)\n}",
2821 "commons demo {\n type A = { type: String }\n fn f(a: A) -> String { a.type }\n}",
2822 "commons demo {\n type A = { type: String }\n fn f() -> A { A { type: \"x\" } }\n}",
2823 "commons demo {\n type A = { type: String }\n fn f(a: A) -> String { match a { A { type: t, .. } => t } }\n}",
2824 "commons demo {\n type S = | P(from: String)\n fn f(s: S) -> String { match s { P(from: x) => x } }\n}",
2825 "commons demo {\n type S = { n: Int }\n fn S.from(n: Int) -> S { S { n: n } }\n fn g() -> S { S.from(1) }\n}",
2826 ] {
2827 parse_str(src).unwrap_or_else(|e| panic!("should parse: {src}\n{e:?}"));
2828 }
2829 for src in [
2830 "commons demo {\n fn f(type: Int) -> Int { 1 }\n}",
2831 "commons demo {\n fn f() -> Int { let from = 1\n from }\n}",
2832 "commons demo {\n type A = { type String }\n}",
2833 "commons demo {\n fn f(a: Int) -> Int {\n a.\n let x = 1\n x\n }\n}",
2835 ] {
2836 let errs = parse_str(src).expect_err(src);
2837 assert_eq!(errs[0].category, "bynk.parse.reserved_keyword", "{src}");
2838 }
2839 }
2840
2841 #[test]
2845 fn keyword_shorthand_is_a_targeted_error() {
2846 let pat = |extra: &str| {
2847 format!(
2848 "commons demo {{\n type A = {{ type: String }}\n fn f(a: A) -> String {{ {extra} match a {{ A {{ type, .. }} => \"x\" }} }}\n}}"
2849 )
2850 };
2851 let errs = parse_str(&pat("")).expect_err("pattern shorthand");
2852 assert_eq!(errs[0].category, "bynk.parse.keyword_field_shorthand");
2853 let fix = &errs[0].suggestions[0];
2854 assert_eq!(fix.edits[0].1, "type: type_");
2855 assert!(matches!(
2856 fix.applicability,
2857 crate::error::Applicability::MaybeIncorrect
2858 ));
2859
2860 let errs = parse_str(&pat("let type_ = 1")).expect_err("pattern shorthand");
2861 assert_eq!(errs[0].suggestions[0].edits[0].1, "type: type_2");
2862
2863 let errs = parse_str(
2864 "commons demo {\n type A = { type: String }\n fn f() -> A { A { type } }\n}",
2865 )
2866 .expect_err("construction shorthand");
2867 assert_eq!(errs[0].category, "bynk.parse.keyword_field_shorthand");
2868 assert!(errs[0].suggestions.is_empty());
2869 }
2870
2871 #[test]
2879 fn is_reserved_keyword_covers_every_lexer_keyword() {
2880 let lexer_src = include_str!("lexer.rs");
2881 let mut words = Vec::new();
2882 for line in lexer_src.lines() {
2883 let t = line.trim();
2884 if let Some(rest) = t.strip_prefix("#[token(\"")
2885 && let Some(word) = rest.split('"').next()
2886 && word.chars().next().is_some_and(|c| c.is_ascii_alphabetic())
2887 && word.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
2888 {
2889 words.push(word.to_string());
2890 }
2891 }
2892 assert!(
2893 words.len() > 30,
2894 "keyword extraction looks broken: only {} words",
2895 words.len()
2896 );
2897 use crate::keywords::RESERVED_CONTEXTUAL;
2900 let mut unclassified = Vec::new();
2901 for word in &words {
2902 let tokens = crate::lexer::tokenize(word).expect("keyword lexes");
2903 let kind = tokens.first().expect("keyword yields a token").kind;
2904 if !is_reserved_keyword(kind) && !RESERVED_CONTEXTUAL.contains(&word.as_str()) {
2905 unclassified.push(word.clone());
2906 }
2907 }
2908 assert!(
2909 unclassified.is_empty(),
2910 "keywords missing from is_reserved_keyword (add them, or document \
2911 them as contextual): {unclassified:?}"
2912 );
2913 }
2914
2915 #[test]
2926 fn is_item_start_matches_the_pinned_keyword_set() {
2927 use TokenKind::*;
2928 let expected_true = [
2929 Commons, Context, Adapter, Suite, Type, Fn, Messages, Event, Asset, Embed, Const, Uses,
2930 Consumes, Exports, Capability, Provides, Service, Agent, Actor, Binding, Stub, Case,
2931 Property,
2932 ];
2933 for kind in expected_true {
2934 assert!(is_item_start(kind), "{kind:?} must be an item start");
2935 }
2936 let expected_false = [
2937 Ident, Plus, Minus, Colon, Dot, Eq, LBrace, RBrace, LParen, RParen, If, Else, Let,
2938 Where, True, False, Match, Is, On, Given,
2939 ];
2940 for kind in expected_false {
2941 assert!(!is_item_start(kind), "{kind:?} must not be an item start");
2942 }
2943 }
2944
2945 #[test]
2950 fn recovery_makes_progress_on_context_only_keyword_in_commons() {
2951 let src = "commons demo\n\ncapability Logger {\n fn log(m: String) -> Effect[()]\n}\n";
2952 let tokens = crate::lexer::tokenize(src).unwrap();
2953 let (unit, errors) = parse_unit_with_recovery(&tokens, src);
2954 assert!(unit.is_some(), "the commons header still parses");
2955 assert!(
2956 errors
2957 .iter()
2958 .any(|e| e.category == "bynk.capability.outside_context"),
2959 "the misplaced capability is reported: {errors:?}"
2960 );
2961 assert!(errors.len() < 10, "recovery repeated itself: {errors:?}");
2964 }
2965
2966 #[test]
2967 fn trailing_file_comment_becomes_unit_trailing() {
2968 let src = "commons x\n\ntype T = Int where Positive\n// afterword\n";
2972 let c = parse_str(src).unwrap();
2973 assert_eq!(
2974 c.trailing_comments,
2975 vec![Comment::Line(" afterword".to_string())]
2976 );
2977 }
2978
2979 #[test]
2980 fn trailing_file_comment_after_a_brace_form_commons_is_not_dropped() {
2981 let src = "commons x {\n type T = Int where Positive\n}\n// afterword\n";
2988 let c = parse_str(src).unwrap();
2989 assert_eq!(
2990 c.trailing_comments,
2991 vec![Comment::Line(" afterword".to_string())]
2992 );
2993 }
2994
2995 #[test]
2996 fn trailing_file_comment_after_a_brace_form_context_is_not_dropped() {
2997 let src = "context x {\n type T = Int where Positive\n}\n// afterword\n";
2999 let SourceUnit::Context(c) = parse_unit_str(src).unwrap() else {
3000 panic!("expected context");
3001 };
3002 assert_eq!(
3003 c.trailing_comments,
3004 vec![Comment::Line(" afterword".to_string())]
3005 );
3006 }
3007
3008 #[test]
3009 fn trailing_file_comment_after_a_brace_form_suite_is_not_dropped() {
3010 let src = "suite x {\n case \"c\" {\n expect 1 == 1\n }\n}\n// afterword\n";
3012 let SourceUnit::Suite(s) = parse_unit_str(src).unwrap() else {
3013 panic!("expected suite");
3014 };
3015 assert_eq!(
3016 s.trailing_comments,
3017 vec![Comment::Line(" afterword".to_string())]
3018 );
3019 }
3020
3021 #[test]
3028 fn trailing_file_comment_after_a_brace_form_adapter_is_not_dropped() {
3029 let src = "adapter x {\n binding \"./x.ts\"\n}\n// afterword\n";
3030 let SourceUnit::Adapter(a) = parse_unit_str(src).unwrap() else {
3031 panic!("expected adapter");
3032 };
3033 assert_eq!(
3034 a.trailing_comments,
3035 vec![Comment::Line(" afterword".to_string())]
3036 );
3037 }
3038
3039 #[test]
3042 fn binding_includes_list_parses_before_requires() {
3043 let src = "adapter x {\n binding \"./x.ts\" includes [\"./a.wasm\", \"b/c.wasm\"] requires { \"p\": \"^1\" }\n}\n";
3044 let SourceUnit::Adapter(a) = parse_unit_str(src).unwrap() else {
3045 panic!("expected adapter");
3046 };
3047 let b = a.binding.unwrap();
3048 let paths: Vec<_> = b.includes.iter().map(|i| i.path.as_str()).collect();
3049 assert_eq!(paths, ["./a.wasm", "b/c.wasm"]);
3050 assert_eq!(b.requires.len(), 1);
3051 assert!(parse_unit_str("adapter x {\n binding \"./x.ts\" includes [\"a.wasm\"").is_err());
3052 assert!(parse_unit_str("adapter x {\n binding \"./x.ts\" includes [a]\n}\n").is_err());
3053 }
3054
3055 #[test]
3062 fn commons_fragment_rejects_uses_after_a_decl() {
3063 let src = "commons x\n\ntype T = Int where Positive\nuses bynk.list\n";
3064 let errs = parse_str(src).unwrap_err();
3065 assert!(
3066 errs.iter()
3067 .any(|e| e.category == "bynk.parse.uses_after_decls"),
3068 "{errs:?}"
3069 );
3070 }
3071
3072 #[test]
3075 fn commons_brace_allows_uses_after_a_decl() {
3076 let src = "commons x {\n type T = Int where Positive\n uses bynk.list\n}\n";
3077 parse_str(src).expect("brace form must not enforce fragment's uses-ordering rule");
3078 }
3079
3080 #[test]
3082 fn context_fragment_rejects_consumes_after_a_decl() {
3083 let src = "context x\n\ntype T = Int where Positive\nconsumes bynk\n";
3084 let errs = parse_unit_str(src).unwrap_err();
3085 assert!(
3086 errs.iter()
3087 .any(|e| e.category == "bynk.parse.consumes_after_decls"),
3088 "{errs:?}"
3089 );
3090 }
3091
3092 #[test]
3094 fn context_fragment_rejects_exports_after_a_decl() {
3095 let src = "context x\n\ntype T = Int where Positive\nexports opaque { T }\n";
3096 let errs = parse_unit_str(src).unwrap_err();
3097 assert!(
3098 errs.iter()
3099 .any(|e| e.category == "bynk.parse.exports_after_decls"),
3100 "{errs:?}"
3101 );
3102 }
3103
3104 #[test]
3106 fn context_brace_allows_consumes_and_exports_after_a_decl() {
3107 let src = "context x {\n type T = Int where Positive\n consumes bynk\n exports opaque { T }\n}\n";
3108 parse_unit_str(src)
3109 .expect("brace form must not enforce fragment's consumes/exports-ordering rules");
3110 }
3111
3112 #[test]
3114 fn test_fragment_rejects_uses_after_a_decl() {
3115 let src = "suite m\n\ncase \"c\" {\n expect true\n}\nuses bynk.list\n";
3116 let errs = parse_unit_str(src).unwrap_err();
3117 assert!(
3118 errs.iter()
3119 .any(|e| e.category == "bynk.parse.uses_after_decls"),
3120 "{errs:?}"
3121 );
3122 }
3123
3124 #[test]
3126 fn test_brace_allows_uses_after_a_decl() {
3127 let src = "suite m {\n case \"c\" {\n expect true\n }\n uses bynk.list\n}\n";
3128 parse_unit_str(src).expect("brace form must not enforce fragment's uses-ordering rule");
3129 }
3130
3131 fn body_tail(body: &str) -> ExprKind {
3135 let src = format!("commons x\n\nfn f() -> Int {{\n {body}\n}}\n");
3136 let c = parse_str(&src).unwrap_or_else(|e| panic!("parse failed for {body:?}: {e:?}"));
3137 let CommonsItem::Fn(f) = &c.items[0] else {
3138 panic!("expected fn, got {:?}", c.items[0]);
3139 };
3140 f.body.tail.kind.clone()
3141 }
3142
3143 fn body_err(body: &str) -> Vec<CompileError> {
3144 let src = format!("commons x\n\nfn f() -> Int {{\n {body}\n}}\n");
3145 parse_str(&src).expect_err(&format!("expected a parse error for {body:?}"))
3146 }
3147
3148 fn body_of(body: &str) -> Block {
3152 let src = format!("commons x\n\nfn f() -> Int {{\n {body}\n}}\n");
3153 let c = parse_str(&src).unwrap_or_else(|e| panic!("parse failed for {body:?}: {e:?}"));
3154 let CommonsItem::Fn(f) = &c.items[0] else {
3155 panic!("expected fn, got {:?}", c.items[0]);
3156 };
3157 f.body.clone()
3158 }
3159
3160 fn effect_let_principal(stmt: &Statement) -> Option<&CallSiteActor> {
3161 match stmt {
3162 Statement::EffectLet(l) => l.principal.as_ref(),
3163 other => panic!("expected an effect-let, got {other:?}"),
3164 }
3165 }
3166
3167 #[test]
3168 fn by_is_an_ordinary_name_in_every_identifier_position() {
3169 for src in [
3172 "commons x\n\nfn f(by: Int) -> Int { by }\n",
3173 "commons x\n\nfn f(xs: List[Int], by: Int) -> List[Int] { xs.map((x) => x + by) }\n",
3174 "commons x\n\nfn f() -> Int { let by = 1 by }\n",
3175 "commons x\n\ntype S = { by: Int }\n\nfn f() -> S { let by = 1 S { by } }\n",
3176 "commons x\n\ntype S = { by: Int }\n\nfn f(s: S) -> Int { let S { by, .. } = s by }\n",
3177 "commons x\n\nfn f() -> Int { let g = (by: Int) => by g(1) }\n",
3178 ] {
3179 parse_str(src).unwrap_or_else(|e| panic!("{src:?}: {e:?}"));
3180 }
3181 let agent = "context x\n\nagent A {\n key id: String\n store by: Cell[Int]\n on call by(n: Int) -> Effect[Int] {\n Effect.pure(n)\n }\n}\n";
3183 let (_, errors) = parse_recover_str(agent);
3184 assert!(errors.is_empty(), "{errors:?}");
3185 }
3186
3187 #[test]
3188 fn by_still_starts_a_call_site_actor_clause_on_the_values_line() {
3189 let block = body_of("let r <- g() by User(\"bob\")\n 1");
3190 let actor = effect_let_principal(&block.statements[0]).expect("a clause");
3191 assert_eq!(actor.actor.name, "User");
3192 let block = body_of("let r <- g() by Nobody\n 1");
3194 assert_eq!(
3195 effect_let_principal(&block.statements[0])
3196 .unwrap()
3197 .actor
3198 .name,
3199 "Nobody"
3200 );
3201 }
3202
3203 #[test]
3204 fn a_by_on_the_next_line_after_an_effect_let_is_a_statement_not_a_clause() {
3205 let block = body_of("let a <- g()\n by");
3206 assert!(effect_let_principal(&block.statements[0]).is_none());
3207 assert!(matches!(&block.tail.kind, ExprKind::Ident(i) if i.name == "by"));
3208 let src = "commons x\n\nfn f() -> Int {\n let a <- g()\n by\n User\n}\n";
3210 let c = parse_str(src);
3211 assert!(c.is_err(), "{c:?}");
3214 }
3215
3216 #[test]
3217 fn a_by_not_followed_by_an_identifier_is_a_tail_even_on_the_values_line() {
3218 let src = "commons x\n\nfn f() -> Effect[Int] { let by = 1 let a <- g() by }\n";
3219 let c = parse_str(src).unwrap_or_else(|e| panic!("{e:?}"));
3220 let CommonsItem::Fn(f) = &c.items[0] else {
3221 panic!("expected fn")
3222 };
3223 assert!(effect_let_principal(&f.body.statements[1]).is_none());
3224 assert!(matches!(&f.body.tail.kind, ExprKind::Ident(i) if i.name == "by"));
3225 }
3226
3227 #[test]
3228 fn advance_still_reads_its_by_and_admits_a_variable_amount() {
3229 for stmt in ["advance Clock by 15.minutes", "advance Clock by by"] {
3230 let src = format!("suite x\n\ncase \"c\" {{\n let by = 1.minute\n {stmt}\n}}\n");
3231 let toks = tokenize(&src).unwrap();
3232 let unit = parse_unit_with_recovery(&toks, &src);
3233 assert!(unit.1.is_empty(), "{stmt}: {:?}", unit.1);
3234 }
3235 }
3236
3237 #[test]
3238 fn a_handler_actor_clause_still_follows_the_return_type() {
3239 let src = "context x\n\nservice api from http {\n on GET(\"/\") () -> Effect[HttpResult[String]] by v: Visitor {\n Ok(\"x\")\n }\n}\n";
3240 let (unit, errors) = parse_recover_str(src);
3241 assert!(errors.is_empty(), "{errors:?}");
3242 assert!(unit.is_some());
3243 let src = "context x\n\nservice api from http {\n on GET(\"/\") (by: Int) -> Effect[HttpResult[String]] by by: Visitor {\n Ok(\"x\")\n }\n}\n";
3245 let (_, errors) = parse_recover_str(src);
3246 assert!(errors.is_empty(), "{errors:?}");
3247 }
3248
3249 #[test]
3250 fn another_keyword_is_still_refused_as_a_field_shorthand() {
3251 let errs = parse_str(
3253 "commons x\n\ntype S = { type: Int }\n\nfn f() -> S { let type = 1 S { type } }\n",
3254 )
3255 .expect_err("`type` is reserved");
3256 assert!(!errs.is_empty());
3257 }
3258
3259 fn apply_fix(src: &str, err: &CompileError) -> String {
3263 assert_eq!(
3264 err.suggestions[0].applicability,
3265 crate::error::Applicability::MachineApplicable
3266 );
3267 apply_quick_fix(src, err)
3268 }
3269
3270 fn apply_quick_fix(src: &str, err: &CompileError) -> String {
3273 let s = &err.suggestions[0];
3274 let mut edits = s.edits.clone();
3275 edits.sort_by_key(|(span, _)| std::cmp::Reverse(span.start));
3276 let mut out = src.to_string();
3277 for (span, text) in edits {
3278 out.replace_range(span.start..span.end, &text);
3279 }
3280 out
3281 }
3282
3283 const BARE: &str = "bynk.parse.bare_expression_statement";
3286
3287 #[test]
3288 fn a_bare_effectful_call_suggests_let_arrow() {
3289 let src = "commons x\n\nfn f() -> Int {\n Logger.info(\"hi\")\n 1\n}\n";
3290 let errs = parse_str(src).expect_err("bare call");
3291 assert_eq!(errs[0].category, BARE, "{errs:?}");
3292 assert_eq!(
3293 apply_fix(src, &errs[0]),
3294 "commons x\n\nfn f() -> Int {\n let _ <- Logger.info(\"hi\")\n 1\n}\n"
3295 );
3296 }
3297
3298 #[test]
3299 fn a_bare_cell_update_and_agent_call_suggest_let_arrow() {
3300 for call in ["n.update((v) => v + 1)", "Counter(\"a\").bump(1)"] {
3301 let src = format!("commons x\n\nfn f() -> Int {{\n {call}\n n\n}}\n");
3302 let errs = parse_str(&src).expect_err(call);
3303 assert_eq!(errs[0].category, BARE, "{call}: {errs:?}");
3304 assert!(apply_fix(&src, &errs[0]).contains(&format!("let _ <- {call}")));
3305 }
3306 }
3307
3308 #[test]
3309 fn a_bare_pure_static_call_suggests_let_equals() {
3310 for call in [
3313 "Json.encode(x)",
3314 "Set.of(xs)",
3315 "List.empty()",
3316 "Bytes.fromUtf8(s).toHex()",
3317 "Map.empty()",
3318 ] {
3319 let src = format!("commons x\n\nfn f() -> Int {{\n {call}\n 1\n}}\n");
3320 let errs = parse_str(&src).expect_err(call);
3321 assert_eq!(errs[0].category, BARE, "{call}: {errs:?}");
3322 let fixed = apply_quick_fix(&src, &errs[0]);
3323 assert!(
3324 fixed.contains(&format!("let _ = {call}")),
3325 "{call}: {fixed}"
3326 );
3327 }
3328 }
3329
3330 #[test]
3331 fn a_bare_pure_expression_suggests_let_equals() {
3332 let src = "commons x\n\nfn f() -> Int {\n g(1)\n let y = 2\n y\n}\n";
3333 let errs = parse_str(src).expect_err("bare call");
3334 assert_eq!(errs[0].category, BARE, "{errs:?}");
3335 assert_eq!(
3337 errs[0].suggestions[0].applicability,
3338 crate::error::Applicability::MaybeIncorrect
3339 );
3340 assert_eq!(
3341 apply_quick_fix(src, &errs[0]),
3342 "commons x\n\nfn f() -> Int {\n let _ = g(1)\n let y = 2\n y\n}\n"
3343 );
3344 }
3345
3346 #[test]
3347 fn parsing_continues_after_a_bare_expression() {
3348 let src =
3351 "commons x\n\nfn f() -> Int {\n g(1)\n let = 2\n 3\n}\n\nfn h() -> Int { 4 }\n";
3352 let (unit, errors) = parse_recover_str(src);
3353 let cats: Vec<_> = errors.iter().map(|e| e.category).collect();
3354 assert_eq!(cats[0], BARE, "{cats:?}");
3355 assert!(cats.len() >= 2, "a later error is still reported: {cats:?}");
3356 let Some(SourceUnit::Commons(c)) = unit else {
3357 panic!("expected commons")
3358 };
3359 assert!(
3360 c.items
3361 .iter()
3362 .any(|i| matches!(i, CommonsItem::Fn(f) if f.name.ident().name == "h")),
3363 "`fn h` after the broken block still parses"
3364 );
3365 }
3366
3367 #[test]
3368 fn a_bare_expression_alone_in_the_recovered_ast_keeps_the_function() {
3369 let src = "commons x\n\nfn f() -> Int {\n g(1)\n 2\n}\n";
3370 let (unit, errors) = parse_recover_str(src);
3371 assert_eq!(errors.len(), 1, "{errors:?}");
3372 assert_eq!(errors[0].category, BARE);
3373 let Some(SourceUnit::Commons(c)) = unit else {
3374 panic!("expected commons")
3375 };
3376 assert!(c.items.iter().any(|i| matches!(i, CommonsItem::Fn(_))));
3377 }
3378
3379 #[test]
3380 fn a_stray_token_after_a_tail_keeps_the_generic_report() {
3381 let errs = body_err("1\n )");
3383 assert_eq!(errs[0].category, "bynk.parse.expected_token", "{errs:?}");
3384 let errs = body_err("1 2");
3386 assert_ne!(errs[0].category, BARE, "{errs:?}");
3387 }
3388
3389 #[test]
3390 fn a_second_match_keeps_its_own_report() {
3391 let errs = body_err("match 1 {\n _ => 1\n }\n match 2 {\n _ => 2\n }");
3392 assert_eq!(errs[0].category, "bynk.parse.match_ends_block", "{errs:?}");
3393 }
3394
3395 #[test]
3398 fn list_patterns_parse_in_every_shape() {
3399 let ExprKind::Match { arms, .. } = body_tail(
3400 "match xs { [] => 0\n [a] => 1\n [a, b, ..] => 2\n [a, ..rest] => 3\n [..all] => 4\n [..] => 5\n [a, ..,] => 6\n Some([x, ..]) => 7 }",
3401 ) else {
3402 panic!("expected Match");
3403 };
3404 let shape = |i: usize| match &arms[i].pattern {
3405 Pattern::List { elems, rest, .. } => (
3406 elems.len(),
3407 rest.as_ref()
3408 .map(|r| r.binder.as_ref().map(|b| b.name.clone())),
3409 ),
3410 other => panic!("arm {i}: expected a list pattern, got {other:?}"),
3411 };
3412 assert_eq!(shape(0), (0, None));
3413 assert_eq!(shape(1), (1, None));
3414 assert_eq!(shape(2), (2, Some(None)));
3415 assert_eq!(shape(3), (1, Some(Some("rest".to_string()))));
3416 assert_eq!(shape(4), (0, Some(Some("all".to_string()))));
3417 assert_eq!(shape(5), (0, Some(None)));
3418 assert_eq!(shape(6), (1, Some(None)));
3419 assert!(matches!(&arms[7].pattern, Pattern::Variant { bindings, .. }
3420 if matches!(bindings[0].pattern(), Pattern::List { .. })));
3421 assert!(!arms[0].pattern.is_irrefutable());
3423 assert!(!arms[2].pattern.is_irrefutable());
3424 assert!(arms[4].pattern.is_irrefutable());
3425 assert!(arms[5].pattern.is_irrefutable());
3426 }
3427
3428 #[test]
3429 fn list_pattern_after_is_closes_at_the_bracket() {
3430 for body in [
3431 "if xs is [_, ..] { 1 } else { 2 }",
3432 "if xs is [] { 1 } else { 2 }",
3433 "if xs is [a, ..rest] { 1 } else { 2 }",
3434 "if xs is [S { n: 1, .. }, ..] { 1 } else { 2 }",
3435 "if xs is [] | [_] { 1 } else { 2 }",
3436 ] {
3437 let src = format!("commons x\n\nfn f() -> Int {{\n {body}\n}}\n");
3438 parse_str(&src).unwrap_or_else(|e| panic!("{body:?}: {e:?}"));
3439 }
3440 }
3441
3442 #[test]
3443 fn list_rest_must_be_last() {
3444 for body in [
3445 "match xs { [.., last] => 1 }",
3446 "match xs { [..r, last] => 1 }",
3447 "match xs { [.., ..] => 1 }",
3448 "match xs { [a, .., b, c] => 1 }",
3449 ] {
3450 let errs = body_err(body);
3451 assert_eq!(errs[0].category, "bynk.parse.list_rest_not_last", "{body}");
3452 assert!(
3453 errs[0].suggestions.is_empty(),
3454 "{body}: only trailing wildcards earn a fix"
3455 );
3456 }
3457 }
3458
3459 #[test]
3460 fn list_rest_followed_by_wildcards_has_a_fix() {
3461 for (body, fixed) in [
3462 ("match xs { [.., _] => 1 }", "match xs { [_, ..] => 1 }"),
3463 (
3464 "match xs { [a, .., _, _] => 1 }",
3465 "match xs { [a, _, _, ..] => 1 }",
3466 ),
3467 ] {
3468 let errs = body_err(body);
3469 assert_eq!(errs[0].category, "bynk.parse.list_rest_not_last");
3470 let src = format!("commons x\n\nfn f() -> Int {{\n {body}\n}}\n");
3471 let got = apply_fix(&src, &errs[0]);
3472 assert!(got.contains(fixed), "{body}: fixed to {got:?}");
3473 parse_str(&got).unwrap_or_else(|e| panic!("{body:?} fixed to {got:?}: {e:?}"));
3474 }
3475 }
3476
3477 #[test]
3478 fn list_rest_followed_by_an_integer_is_a_range_element() {
3479 for body in [
3481 "match xs { [..9] => 1 _ => 0 }",
3482 "match xs { [a, ..-1] => 1 _ => 0 }",
3483 "match xs { [0..9, ..rest] => 1 _ => 0 }",
3484 "match xs { [18.., ..] => 1 _ => 0 }",
3485 ] {
3486 let ExprKind::Match { arms, .. } = body_tail(body) else {
3487 panic!("expected Match: {body}");
3488 };
3489 let Pattern::List { elems, .. } = &arms[0].pattern else {
3490 panic!("expected a list pattern: {body}");
3491 };
3492 assert!(
3493 elems.iter().any(|e| matches!(e, Pattern::Range(_))),
3494 "{body}"
3495 );
3496 }
3497 for body in ["match xs { [..\"a\"] => 1 }", "match xs { [..true] => 1 }"] {
3499 let errs = body_err(body);
3500 assert_eq!(errs[0].category, "bynk.parse.expected_token", "{body}");
3501 }
3502 let errs = body_err("match xs { [a, .._] => 1 }");
3504 assert_eq!(errs[0].category, "bynk.parse.expected_token");
3505 }
3506
3507 #[test]
3508 fn int_range_patterns_parse_in_every_form() {
3509 let range = |body: &str| {
3510 let ExprKind::Match { arms, .. } = body_tail(body) else {
3511 panic!("expected Match: {body}");
3512 };
3513 match &arms[0].pattern {
3514 Pattern::Range(r) => (r.lo, r.hi),
3515 other => panic!("expected a range: {body}: {other:?}"),
3516 }
3517 };
3518 assert_eq!(range("match n { 0..12 => 1 _ => 0 }"), (Some(0), Some(12)));
3519 assert_eq!(range("match n { 18.. => 1 _ => 0 }"), (Some(18), None));
3520 assert_eq!(range("match n { ..-1 => 1 _ => 0 }"), (None, Some(-1)));
3521 assert_eq!(
3522 range("match n { -5..-1 => 1 _ => 0 }"),
3523 (Some(-5), Some(-1))
3524 );
3525 assert_eq!(
3526 range("match n { 1_000..2_000 => 1 _ => 0 }"),
3527 (Some(1000), Some(2000))
3528 );
3529 let ExprKind::Match { arms, .. } = body_tail("match n { 18.. => 1 5 => 2 _ => 0 }") else {
3531 panic!("expected Match");
3532 };
3533 assert!(matches!(arms[0].pattern, Pattern::Range(_)));
3534 assert!(matches!(arms[1].pattern, Pattern::Literal { .. }));
3535 }
3536
3537 #[test]
3538 fn a_range_is_not_an_event_pattern_value() {
3539 let src = "service S from Events(E { n: 1..5 }) { }";
3541 assert!(parse_str(src).is_err());
3542 }
3543
3544 #[test]
3545 fn record_pattern_parses_in_a_match_arm_and_nested() {
3546 let ExprKind::Match { arms, .. } = body_tail(
3547 "match o { Order { status: Paid, total, .. } => 1 Some(Order { .. }) => 2 _ => 3 }",
3548 ) else {
3549 panic!("expected Match");
3550 };
3551 let Pattern::Record {
3552 type_name, fields, ..
3553 } = &arms[0].pattern
3554 else {
3555 panic!("expected a record pattern, got {:?}", arms[0].pattern);
3556 };
3557 assert_eq!(type_name.name, "Order");
3558 assert_eq!(fields.len(), 2);
3559 assert!(fields[0].1.is_some(), "`status: Paid` has a sub-pattern");
3560 assert!(fields[1].1.is_none(), "`total` is shorthand");
3561 let Pattern::Variant { bindings, .. } = &arms[1].pattern else {
3562 panic!("expected Some(..)");
3563 };
3564 assert!(matches!(bindings[0].pattern(), Pattern::Record { .. }));
3565 }
3566
3567 #[test]
3568 fn record_pattern_without_rest_is_an_error_with_a_fix() {
3569 for body in [
3570 "match o { Order { total } => 1 }",
3571 "match o { Order { total, } => 1 }",
3572 "match o { Order { status: Paid, total } => 1 }",
3573 "match o { Order { } => 1 }",
3574 ] {
3575 let errs = body_err(body);
3576 assert_eq!(errs[0].category, "bynk.parse.record_pattern_without_rest");
3577 let src = format!("commons x\n\nfn f() -> Int {{\n {body}\n}}\n");
3578 let fixed = apply_fix(&src, &errs[0]);
3579 parse_str(&fixed).unwrap_or_else(|e| panic!("{body:?} fixed to {fixed:?}: {e:?}"));
3580 }
3581 }
3582
3583 #[test]
3584 fn record_pattern_after_is_must_be_parenthesised() {
3585 for body in [
3586 "if o is Order { status: Paid, .. } { 1 } else { 2 }",
3587 "if o is None | Order { .. } { 1 } else { 2 }",
3588 ] {
3589 let errs = body_err(body);
3590 assert_eq!(
3591 errs[0].category,
3592 "bynk.parse.record_pattern_in_is_unparenthesised"
3593 );
3594 let src = format!("commons x\n\nfn f() -> Int {{\n {body}\n}}\n");
3595 if body.contains("None |") {
3596 continue; }
3598 let fixed = apply_fix(&src, &errs[0]);
3599 parse_str(&fixed).unwrap_or_else(|e| panic!("{body:?} fixed to {fixed:?}: {e:?}"));
3600 }
3601 for body in [
3603 "if o is (Order { status: Paid, .. }) { 1 } else { 2 }",
3604 "if o is Some(Order { .. }) { 1 } else { 2 }",
3605 "if o is (None | Order { .. }) { 1 } else { 2 }",
3606 "if o is Paid { 1 } else { 2 }",
3607 ] {
3608 body_tail(body);
3609 }
3610 }
3611
3612 #[test]
3613 fn if_condition_ending_in_ident_does_not_swallow_a_single_ident_branch() {
3614 for src in [
3617 "if ready { result } else { fallback }",
3618 "if ready { fallback } else { result }",
3619 "if !ready { result } else { fallback }",
3620 "if a == b { result } else { fallback }",
3621 "if a && b { result } else { fallback }",
3622 ] {
3623 let ExprKind::If {
3624 then_block,
3625 else_block,
3626 ..
3627 } = body_tail(src)
3628 else {
3629 panic!("expected If for {src:?}, got {:?}", body_tail(src));
3630 };
3631 assert!(
3634 matches!(&then_block.tail.kind, ExprKind::Ident(_)),
3635 "then-branch tail not an ident for {src:?}: {:?}",
3636 then_block.tail.kind,
3637 );
3638 assert!(
3639 matches!(&else_block.tail.kind, ExprKind::Ident(_)),
3640 "else-branch tail not an ident for {src:?}: {:?}",
3641 else_block.tail.kind,
3642 );
3643 }
3644 }
3645
3646 #[test]
3647 fn else_less_if_with_single_ident_branch_parses() {
3648 let ExprKind::If { then_block, .. } = body_tail("if ready { result }") else {
3650 panic!("expected If");
3651 };
3652 assert!(matches!(&then_block.tail.kind, ExprKind::Ident(_)));
3653 }
3654
3655 #[test]
3656 fn record_construction_still_parses_in_value_position() {
3657 assert!(matches!(
3660 body_tail("Point { x }"),
3661 ExprKind::RecordConstruction { .. }
3662 ));
3663 assert!(matches!(
3664 body_tail("Point { x: 1, y: 2 }"),
3665 ExprKind::RecordConstruction { .. }
3666 ));
3667 assert!(matches!(
3668 body_tail("Empty {}"),
3669 ExprKind::RecordConstruction { .. }
3670 ));
3671 }
3672
3673 #[test]
3674 fn parenthesised_record_is_allowed_in_condition_head() {
3675 let ExprKind::If { cond, .. } =
3678 body_tail("if (ready { result }) { branch } else { other }")
3679 else {
3680 panic!("expected If");
3681 };
3682 let ExprKind::Paren(inner) = &cond.kind else {
3683 panic!("expected a parenthesised condition, got {:?}", cond.kind);
3684 };
3685 assert!(
3686 matches!(&inner.kind, ExprKind::RecordConstruction { .. }),
3687 "parenthesised record in condition head should still construct: {:?}",
3688 inner.kind,
3689 );
3690 }
3691
3692 #[test]
3693 fn record_in_call_arg_within_condition_still_constructs() {
3694 let ExprKind::If { cond, .. } = body_tail("if check(Point { x: 1 }) { a } else { b }")
3697 else {
3698 panic!("expected If");
3699 };
3700 let ExprKind::Call { args, .. } = &cond.kind else {
3701 panic!("expected Call in condition, got {:?}", cond.kind);
3702 };
3703 assert!(matches!(&args[0].kind, ExprKind::RecordConstruction { .. }));
3704 }
3705
3706 #[test]
3707 fn safe_condition_shapes_are_unaffected() {
3708 assert!(matches!(
3710 body_tail("if ready == true { result } else { fallback }"),
3711 ExprKind::If { .. }
3712 ));
3713 assert!(matches!(
3714 body_tail("if (ready) { result } else { fallback }"),
3715 ExprKind::If { .. }
3716 ));
3717 assert!(matches!(
3718 body_tail("if ready { \"a\" } else { \"b\" }"),
3719 ExprKind::If { .. }
3720 ));
3721 }
3722
3723 fn body_block(body: &str) -> Block {
3724 let src = format!("commons x\n\nfn f() -> Int {{\n {body}\n}}\n");
3725 let c = parse_str(&src).unwrap_or_else(|e| panic!("parse failed for {body:?}: {e:?}"));
3726 let CommonsItem::Fn(f) = &c.items[0] else {
3727 panic!("expected fn, got {:?}", c.items[0]);
3728 };
3729 f.body.clone()
3730 }
3731
3732 fn has_error(errs: &[CompileError], code: &str) -> bool {
3733 errs.iter().any(|e| e.category == code)
3734 }
3735
3736 fn lambda_of(body: &str) -> LambdaExpr {
3739 let b = body_block(body);
3740 let ExprKind::Lambda(l) = &b.tail.kind else {
3741 panic!("expected a lambda tail, got {:?}", b.tail.kind);
3742 };
3743 l.clone()
3744 }
3745
3746 #[test]
3747 fn a_record_pattern_parameter_desugars_to_a_hidden_binder_and_a_let() {
3748 let l = lambda_of("(Item { qty, .. }) => qty");
3750 assert_eq!(l.params.len(), 1);
3751 let p = &l.params[0];
3752 assert!(p.name.name.starts_with(LAMBDA_ARG_BINDER_PREFIX));
3753 assert!(is_generated_binding(&p.name.name));
3754 assert_eq!(
3755 p.name.span.start, p.name.span.end,
3756 "the binder has no extent"
3757 );
3758 assert!(p.type_ref.is_none());
3759 assert!(matches!(p.pattern, Some(Pattern::Record { .. })));
3760 assert!(!l.block_body);
3761 let ExprKind::Block(b) = &l.body.kind else {
3762 panic!("expected a block body, got {:?}", l.body.kind);
3763 };
3764 let Statement::Let(hidden) = &b.statements[0] else {
3765 panic!("expected the hidden `let`, got {:?}", b.statements[0]);
3766 };
3767 assert_eq!(
3768 hidden.let_else.as_ref().map(|le| le.form),
3769 Some(LetElseForm::Plain)
3770 );
3771 assert!(b.tail.is_let_else_match());
3772 assert!(
3773 matches!(&hidden.value.kind, ExprKind::Ident(i) if i.name == p.name.name),
3774 "the `let` destructures the hidden parameter"
3775 );
3776 }
3777
3778 #[test]
3779 fn name_and_pattern_parameters_mix_and_each_binder_is_distinct() {
3780 let l = lambda_of("(a, Item { qty, .. }, b: Int, Box { v, .. }) => a");
3781 let names: Vec<_> = l.params.iter().map(|p| p.name.name.as_str()).collect();
3782 assert_eq!(names[0], "a");
3783 assert_eq!(names[2], "b");
3784 assert!(names[1].starts_with(LAMBDA_ARG_BINDER_PREFIX));
3785 assert!(names[3].starts_with(LAMBDA_ARG_BINDER_PREFIX));
3786 assert_ne!(names[1], names[3]);
3787 assert!(l.params[0].pattern.is_none() && l.params[2].type_ref.is_some());
3788 let ExprKind::Block(outer) = &l.body.kind else {
3790 panic!("expected a block body");
3791 };
3792 let ExprKind::Match { arms, .. } = &outer.tail.kind else {
3793 panic!("expected the first pattern's match");
3794 };
3795 let MatchBody::Block(inner) = &arms[0].body else {
3796 panic!("expected the arm's block");
3797 };
3798 assert!(inner.tail.is_let_else_match(), "the second pattern nests");
3799 }
3800
3801 #[test]
3802 fn a_block_body_is_kept_as_the_pattern_arms_block() {
3803 let l = lambda_of("(Item { qty, .. }) => { let x = qty\n x }");
3804 assert!(l.block_body);
3805 }
3806
3807 #[test]
3808 fn a_lambda_without_pattern_parameters_is_unchanged() {
3809 let l = lambda_of("(a, b: Int) => a");
3810 assert!(l.params.iter().all(|p| p.pattern.is_none()));
3811 assert!(matches!(l.body.kind, ExprKind::Ident(_)));
3812 }
3813
3814 #[test]
3815 fn a_lambda_pattern_parameter_that_is_refutable_names_its_first_failing_field() {
3816 let errs = body_err("(Item { status: Paid, qty, .. }) => qty");
3817 assert_eq!(errs[0].category, "bynk.parse.lambda_pattern_refutable");
3818 assert!(
3819 errs[0].notes.iter().any(|n| n.contains("status: Paid")),
3820 "{:?}",
3821 errs[0].notes
3822 );
3823 }
3824
3825 #[test]
3826 fn a_lambda_pattern_parameter_must_be_a_record_pattern() {
3827 for body in [
3828 "(Some(x)) => x",
3829 "(a, [x, ..]) => x",
3830 "(0..9) => 1",
3831 "(1) => 1",
3832 "(None) => 1",
3833 "(Status.Paid) => 1",
3834 ] {
3835 let errs = body_err(body);
3836 assert_eq!(
3837 errs[0].category, "bynk.parse.lambda_pattern_not_record",
3838 "{body}"
3839 );
3840 }
3841 }
3842
3843 #[test]
3844 fn an_annotated_lambda_pattern_parameter_offers_to_remove_the_annotation() {
3845 let body = "(Item { qty, .. }: Item) => qty";
3846 let errs = body_err(body);
3847 assert_eq!(errs[0].category, "bynk.parse.lambda_pattern_annotation");
3848 let src = format!("commons x\n\nfn f() -> Int {{\n {body}\n}}\n");
3849 let fixed = apply_fix(&src, &errs[0]);
3850 assert!(fixed.contains("(Item { qty, .. }) => qty"), "{fixed}");
3851 parse_str(&fixed).unwrap_or_else(|e| panic!("fixed to {fixed:?}: {e:?}"));
3852 }
3853
3854 #[test]
3855 fn a_missing_rest_in_a_lambda_pattern_parameter_has_slice_ones_fix() {
3856 let body = "(a, Item { qty }) => qty";
3857 let errs = body_err(body);
3858 assert_eq!(errs[0].category, "bynk.parse.record_pattern_without_rest");
3859 let src = format!("commons x\n\nfn f() -> Int {{\n {body}\n}}\n");
3860 let fixed = apply_fix(&src, &errs[0]);
3861 parse_str(&fixed).unwrap_or_else(|e| panic!("fixed to {fixed:?}: {e:?}"));
3862 }
3863
3864 #[test]
3865 fn let_else_desugars_to_a_hidden_binding_and_a_match() {
3866 let b = body_block("let x = 1\n let Some(n) = find(x) else { 0 }\n n + x");
3869 assert_eq!(
3870 b.statements.len(),
3871 2,
3872 "the plain let and the hidden binding"
3873 );
3874 let Statement::Let(hidden) = &b.statements[1] else {
3875 panic!("expected a pure hidden binding, got {:?}", b.statements[1]);
3876 };
3877 assert!(
3878 is_generated_binding(&hidden.name.name),
3879 "{}",
3880 hidden.name.name
3881 );
3882 assert_eq!(
3883 hidden.name.span.start, hidden.name.span.end,
3884 "the binder has no extent"
3885 );
3886 let le = hidden
3887 .let_else
3888 .as_ref()
3889 .expect("the binding records the sugar");
3890 assert_eq!(le.form, LetElseForm::Block);
3891 let ExprKind::Match { discriminant, arms } = &b.tail.kind else {
3892 panic!("expected a match tail, got {:?}", b.tail.kind);
3893 };
3894 assert!(matches!(&discriminant.kind, ExprKind::Ident(i) if i.name == hidden.name.name));
3895 assert_eq!(arms.len(), 2);
3896 assert!(matches!(arms[0].pattern, Pattern::Variant { .. }));
3897 let MatchBody::Block(rest) = &arms[0].body else {
3898 panic!("the pattern's arm runs the rest of the block");
3899 };
3900 assert!(rest.statements.is_empty());
3901 assert!(
3902 !matches!(rest.tail.kind, ExprKind::UnitLit),
3903 "{:?}",
3904 rest.tail.kind
3905 );
3906 assert!(matches!(arms[1].pattern, Pattern::Wildcard(_)));
3907 }
3908
3909 #[test]
3911 fn par_block_holds_its_statements_in_source_order() {
3912 let b = body_block(
3913 "par {\n let a <- one()\n do two()\n let b: Int <- three()\n }\n a",
3914 );
3915 let Statement::Par(p) = &b.statements[0] else {
3916 panic!("expected a par block, got {:?}", b.statements[0]);
3917 };
3918 assert_eq!(p.statements.len(), 3);
3919 assert!(matches!(&p.statements[0], Statement::EffectLet(l) if l.name.name == "a"));
3920 assert!(matches!(&p.statements[1], Statement::Do(_)));
3921 assert!(
3922 matches!(&p.statements[2], Statement::EffectLet(l) if l.name.name == "b" && l.type_annot.is_some())
3923 );
3924 }
3925
3926 #[test]
3928 fn par_is_an_identifier_outside_its_statement_shape() {
3929 let b = body_block("let par = 1\n let x = par + 1\n x");
3930 assert_eq!(b.statements.len(), 2);
3931 assert!(matches!(&b.statements[0], Statement::Let(l) if l.name.name == "par"));
3932 }
3933
3934 #[test]
3937 fn par_block_admits_statements_for_the_checker_to_refuse() {
3938 let b = body_block(
3939 "par {\n let a = 1\n do notify().detach()\n par {\n do x()\n }\n }\n 1",
3940 );
3941 let Statement::Par(p) = &b.statements[0] else {
3942 panic!("expected a par block");
3943 };
3944 assert!(matches!(&p.statements[0], Statement::Let(_)));
3945 assert!(matches!(&p.statements[1], Statement::Do(_)));
3946 assert!(matches!(&p.statements[2], Statement::Par(_)));
3947 }
3948
3949 #[test]
3950 fn par_block_refuses_a_refutable_let_and_a_stray_expression() {
3951 assert!(has_error(
3952 &body_err("par {\n let Ok(v) <- load() else { 0 }\n }\n 1"),
3953 "bynk.par.invalid_statement"
3954 ));
3955 assert!(has_error(
3956 &body_err("par {\n load()\n }\n 1"),
3957 "bynk.par.invalid_statement"
3958 ));
3959 }
3960
3961 #[test]
3962 fn effectful_let_else_binds_with_an_arrow() {
3963 let b = body_block("let Ok(v) <- load() else { Effect.pure(0) }\n v");
3964 assert!(matches!(&b.statements[0], Statement::EffectLet(l) if l.let_else.is_some()));
3965 }
3966
3967 #[test]
3968 fn let_else_chain_nests_each_step_in_the_previous_arm() {
3969 let b = body_block(
3972 "let Ok(a) = one() else { 1 }\n let y = a\n let Ok(b) = two(y) else { 2 }\n let Ok(c) = three(b) else { 3 }\n c",
3973 );
3974 let ExprKind::Match { arms, .. } = &b.tail.kind else {
3975 panic!("expected a match tail");
3976 };
3977 let MatchBody::Block(second) = &arms[0].body else {
3978 panic!("expected a block arm");
3979 };
3980 assert_eq!(
3981 second.statements.len(),
3982 2,
3983 "`let y` and the second hidden binding"
3984 );
3985 assert!(matches!(&second.statements[0], Statement::Let(l) if l.name.name == "y"));
3986 let ExprKind::Match { arms, .. } = &second.tail.kind else {
3987 panic!("expected the second step's match");
3988 };
3989 let MatchBody::Block(third) = &arms[0].body else {
3990 panic!("expected a block arm");
3991 };
3992 let ExprKind::Match { arms, .. } = &third.tail.kind else {
3993 panic!("expected the third step's match");
3994 };
3995 let MatchBody::Block(last) = &arms[0].body else {
3996 panic!("expected a block arm");
3997 };
3998 assert!(matches!(&last.tail.kind, ExprKind::Ident(i) if i.name == "c"));
3999 }
4000
4001 #[test]
4002 fn else_match_arms_follow_the_patterns_arm() {
4003 let b = body_block("let Ok(v) = r else match { Err(e) => 0 }\n v");
4004 let Statement::Let(l) = &b.statements[0] else {
4005 panic!("expected the hidden binding");
4006 };
4007 assert_eq!(l.let_else.as_ref().unwrap().form, LetElseForm::Match);
4008 let ExprKind::Match { arms, .. } = &b.tail.kind else {
4009 panic!("expected a match tail");
4010 };
4011 assert_eq!(arms.len(), 2);
4012 assert!(
4013 matches!(&arms[1].pattern, Pattern::Variant { variant, .. } if variant.name == "Err")
4014 );
4015 }
4016
4017 #[test]
4018 fn an_irrefutable_record_let_needs_no_else() {
4019 for body in [
4022 "let Item { sku, qty: n, .. } = item\n n",
4023 "let (Item { sku, .. }) = item\n sku",
4024 "let Item { sku: _, inner: Inner { x, .. }, .. } <- load(1)\n x",
4025 "let Item { sku, .. } <- load(1) by Admin(\"a\")\n sku",
4026 ] {
4027 let b = body_block(body);
4028 let (Statement::Let(l) | Statement::EffectLet(l)) = &b.statements[0] else {
4029 panic!("{body:?}: expected the hidden binding");
4030 };
4031 let le = l.let_else.as_ref().expect("the binding records the sugar");
4032 assert_eq!(le.form, LetElseForm::Plain, "{body:?}");
4033 assert_eq!(le.else_span.start, le.else_span.end, "no `else` extent");
4034 let ExprKind::Match { arms, .. } = &b.tail.kind else {
4035 panic!("{body:?}: expected a match tail");
4036 };
4037 assert_eq!(arms.len(), 1, "{body:?}: only the pattern's arm");
4038 assert!(matches!(arms[0].pattern, Pattern::Record { .. }));
4039 }
4040 }
4041
4042 #[test]
4043 fn a_refutable_record_let_without_else_names_the_refutable_field() {
4044 for (body, field) in [
4045 (
4046 "let Order { status: Paid, total, .. } = o\n total",
4047 "status: Paid",
4048 ),
4049 (
4050 "let Order { total, c: Cust { kind: Gold, .. }, .. } = o\n total",
4051 "kind: Gold",
4052 ),
4053 ("let Order { id: 1, .. } <- load()\n 1", "id: 1"),
4054 ] {
4055 let errs = body_err(body);
4056 assert_eq!(errs[0].category, "bynk.parse.let_pattern_without_else");
4057 assert!(
4058 errs[0]
4059 .notes
4060 .iter()
4061 .any(|n| n.contains(&format!("`{field}` can fail to match"))),
4062 "{body:?}: {:?}",
4063 errs[0].notes
4064 );
4065 }
4066 for body in [
4068 "let Ok(n) = r\n n",
4069 "let (Ok(n)) = r\n n",
4070 "let Item { sku, .. } | Other = r\n 1",
4071 ] {
4072 let errs = body_err(body);
4073 assert_eq!(
4074 errs[0].category, "bynk.parse.let_pattern_without_else",
4075 "{body:?}"
4076 );
4077 }
4078 }
4079
4080 #[test]
4081 fn a_record_let_keeps_an_else_when_one_is_written() {
4082 let b = body_block("let Item { sku, .. } = item else { 0 }\n 1");
4083 let Statement::Let(l) = &b.statements[0] else {
4084 panic!("expected the hidden binding");
4085 };
4086 assert_eq!(l.let_else.as_ref().unwrap().form, LetElseForm::Block);
4087 }
4088
4089 #[test]
4090 fn a_capitalised_binding_is_not_a_record_pattern() {
4091 for body in ["let Total = 1\n Total", "let Total: Int = 1\n Total"] {
4093 let b = body_block(body);
4094 let Statement::Let(l) = &b.statements[0] else {
4095 panic!("{body:?}: expected a plain let");
4096 };
4097 assert!(l.let_else.is_none(), "{body:?}");
4098 }
4099 let errs = body_err("let Item { sku } = item\n 1");
4101 assert_eq!(errs[0].category, "bynk.parse.record_pattern_without_rest");
4102 }
4103
4104 #[test]
4105 fn let_else_as_the_last_statement_leaves_a_unit_rest() {
4106 let b = body_block("let Some(n) = find(1) else { () }");
4107 let ExprKind::Match { arms, .. } = &b.tail.kind else {
4108 panic!("expected a match tail");
4109 };
4110 let MatchBody::Block(rest) = &arms[0].body else {
4111 panic!("expected a block arm");
4112 };
4113 assert!(rest.implicit_tail && rest.statements.is_empty());
4114 }
4115
4116 #[test]
4117 fn let_pattern_forms_are_recognised() {
4118 for src in [
4119 "let None = o else { 0 }\n 1",
4120 "let Status.Done = s else { 0 }\n 1",
4121 "let Shipped(at) = s else { 0 }\n at",
4122 "let 0 = n else { 1 }\n 0",
4123 "let -1 = n else { 1 }\n 0",
4124 "let \"a\" = s else { 1 }\n 0",
4125 "let (Ok(x) | Err(x)) = r else { 1 }\n x",
4126 ] {
4127 let b = body_block(src);
4128 assert!(
4129 matches!(&b.statements[0], Statement::Let(l) if l.let_else.is_some()),
4130 "{src:?} should parse as a let-else"
4131 );
4132 }
4133 let b = body_block("let Total = 1\n Total");
4135 assert!(
4136 matches!(&b.statements[0], Statement::Let(l) if l.let_else.is_none() && l.name.name == "Total")
4137 );
4138 }
4139
4140 #[test]
4141 fn let_pattern_without_else_is_refused() {
4142 assert!(has_error(
4143 &body_err("let Ok(v) = r\n v"),
4144 "bynk.parse.let_pattern_without_else"
4145 ));
4146 assert!(has_error(
4147 &body_err("let Ok(v) <- r()\n v"),
4148 "bynk.parse.let_pattern_without_else"
4149 ));
4150 }
4151
4152 #[test]
4153 fn else_on_a_plain_binding_is_refused() {
4154 assert!(has_error(
4155 &body_err("let v = r else { 0 }\n v"),
4156 "bynk.parse.let_else_on_binding"
4157 ));
4158 assert!(has_error(
4159 &body_err("let v <- r() else { 0 }\n v"),
4160 "bynk.parse.let_else_on_binding"
4161 ));
4162 }
4163
4164 #[test]
4165 fn annotated_let_pattern_is_refused() {
4166 assert!(has_error(
4167 &body_err("let Ok(v): Int = r else { 0 }\n v"),
4168 "bynk.parse.let_pattern_annotation"
4169 ));
4170 }
4171
4172 #[test]
4173 fn empty_else_match_is_refused() {
4174 assert!(has_error(
4175 &body_err("let Ok(v) = r else match { }\n v"),
4176 "bynk.parse.empty_match"
4177 ));
4178 }
4179
4180 #[test]
4181 fn let_else_steps_count_against_the_nesting_budget() {
4182 let chain = |n: usize| -> String {
4186 let steps: String = (0..n)
4187 .map(|i| format!("let Ok(v{i}) = step() else {{ {i} }}\n "))
4188 .collect();
4189 format!("{steps}0")
4190 };
4191 body_block(&chain(40));
4192 let errs = body_err(&chain(400));
4193 assert!(
4194 errs.iter()
4195 .any(|e| e.category == "bynk.parse.nesting_too_deep"),
4196 "{errs:?}"
4197 );
4198 }
4199
4200 #[test]
4201 fn empty_match_reports_its_own_diagnostic() {
4202 let errs = body_err("match result {}");
4206 assert!(
4207 errs.iter().any(|e| e.category == "bynk.parse.empty_match"),
4208 "expected empty_match; got {errs:?}",
4209 );
4210 }
4211
4212 #[test]
4213 fn match_discriminant_ending_in_ident_parses() {
4214 assert!(matches!(
4216 body_tail("match ready { x => x }"),
4217 ExprKind::Match { .. }
4218 ));
4219 }
4220
4221 #[test]
4230 fn identifier_statement_followed_by_unit_tail_does_not_merge_into_a_call() {
4231 let src = "commons c\n\nfn f() -> Int {\n status := Paid\n ()\n}\n";
4232 let c = parse_str(src).unwrap_or_else(|e| panic!("parse failed: {e:?}"));
4233 let CommonsItem::Fn(f) = &c.items[0] else {
4234 panic!("expected fn, got {:?}", c.items[0]);
4235 };
4236 assert_eq!(
4237 f.body.statements.len(),
4238 1,
4239 "expected exactly one Assign statement, got {:?}",
4240 f.body.statements
4241 );
4242 let Statement::Assign(a) = &f.body.statements[0] else {
4243 panic!(
4244 "expected an Assign statement, got {:?}",
4245 f.body.statements[0]
4246 );
4247 };
4248 assert!(
4249 matches!(a.value.kind, ExprKind::Ident(_)),
4250 "assign value must stay the bare identifier `Paid`, got {:?}",
4251 a.value.kind
4252 );
4253 assert!(
4254 matches!(f.body.tail.kind, ExprKind::UnitLit),
4255 "the `()` must remain the block's own tail, got {:?}",
4256 f.body.tail.kind
4257 );
4258 }
4259
4260 #[test]
4265 fn variant_pattern_followed_by_unit_tail_does_not_take_it_as_bindings() {
4266 for (name, pat) in [("user variant", "Paid"), ("built-in variant", "None")] {
4267 let src = format!("commons c\n\nfn f() -> () {{\n let b = r is {pat}\n ()\n}}\n");
4268 let c = parse_str(&src).unwrap_or_else(|e| panic!("{name}: parse failed: {e:?}"));
4269 let CommonsItem::Fn(f) = &c.items[0] else {
4270 panic!("expected fn, got {:?}", c.items[0]);
4271 };
4272 let Statement::Let(l) = &f.body.statements[0] else {
4273 panic!("{name}: expected a Let, got {:?}", f.body.statements[0]);
4274 };
4275 let ExprKind::Is { pattern, .. } = &l.value.kind else {
4276 panic!("{name}: expected an `is` test, got {:?}", l.value.kind);
4277 };
4278 let Pattern::Variant { variant, span, .. } = pattern.as_ref() else {
4279 panic!("{name}: expected a variant pattern, got {pattern:?}");
4280 };
4281 assert_eq!(
4282 span.end, variant.span.end,
4283 "{name}: the pattern must end at `{pat}`, not take the `()` below it"
4284 );
4285 assert!(
4286 matches!(f.body.tail.kind, ExprKind::UnitLit),
4287 "{name}: the `()` must remain the block's own tail, got {:?}",
4288 f.body.tail.kind
4289 );
4290 }
4291 }
4292
4293 #[test]
4296 fn variant_pattern_payload_on_the_same_line_still_binds() {
4297 for (name, pat) in [
4298 ("user variant", "Paid(\n x\n )"),
4299 ("built-in variant", "Some(x)"),
4300 ] {
4301 let src = format!("commons c\n\nfn f() -> Bool {{\n r is {pat}\n}}\n");
4302 let c = parse_str(&src).unwrap_or_else(|e| panic!("{name}: parse failed: {e:?}"));
4303 let CommonsItem::Fn(f) = &c.items[0] else {
4304 panic!("expected fn, got {:?}", c.items[0]);
4305 };
4306 let ExprKind::Is { pattern, .. } = &f.body.tail.kind else {
4307 panic!("{name}: expected an `is` tail, got {:?}", f.body.tail.kind);
4308 };
4309 assert!(
4310 matches!(pattern.as_ref(), Pattern::Variant { bindings, .. } if bindings.len() == 1),
4311 "{name}: expected one binding, got {pattern:?}"
4312 );
4313 }
4314 }
4315
4316 #[test]
4322 fn match_arm_pattern_payload_on_a_later_line_is_rejected() {
4323 let src = "commons c\n\nfn f() -> Int {\n match m {\n Settled\n (amount) => 1,\n _ => 0,\n }\n}\n";
4324 assert!(
4325 parse_str(src).is_err(),
4326 "a next-line `(` after an arm's variant must not open its payload list"
4327 );
4328 let same_line = src.replace("Settled\n (amount)", "Settled(amount)");
4329 parse_str(&same_line).unwrap_or_else(|e| panic!("same-line form must parse: {e:?}"));
4330 }
4331
4332 #[test]
4336 fn method_reference_followed_by_unit_tail_does_not_merge_into_a_call() {
4337 let src = "commons c\n\nfn f() -> Int {\n let y = x.field\n ()\n}\n";
4338 let c = parse_str(src).unwrap_or_else(|e| panic!("parse failed: {e:?}"));
4339 let CommonsItem::Fn(f) = &c.items[0] else {
4340 panic!("expected fn, got {:?}", c.items[0]);
4341 };
4342 let Statement::Let(l) = &f.body.statements[0] else {
4343 panic!("expected a Let statement, got {:?}", f.body.statements[0]);
4344 };
4345 assert!(
4346 matches!(l.value.kind, ExprKind::FieldAccess { .. }),
4347 "let value must stay a field access, got {:?}",
4348 l.value.kind
4349 );
4350 assert!(
4351 matches!(f.body.tail.kind, ExprKind::UnitLit),
4352 "the `()` must remain the block's own tail, got {:?}",
4353 f.body.tail.kind
4354 );
4355 }
4356
4357 #[test]
4358 fn unparenthesised_record_in_condition_head_now_errors() {
4359 assert!(
4365 !body_err("match Point { x: 1 } { p => p }").is_empty(),
4366 "unparenthesised record discriminant should not parse",
4367 );
4368 let ExprKind::Match { discriminant, .. } = body_tail("match (Point { x: 1 }) { p => p }")
4370 else {
4371 panic!("expected Match for the parenthesised form");
4372 };
4373 let ExprKind::Paren(inner) = &discriminant.kind else {
4374 panic!(
4375 "expected a parenthesised discriminant, got {:?}",
4376 discriminant.kind
4377 );
4378 };
4379 assert!(matches!(&inner.kind, ExprKind::RecordConstruction { .. }));
4380 }
4381
4382 fn strict_codes(src: &str) -> Vec<&'static str> {
4384 let toks = tokenize(src).unwrap();
4385 match parse_units_with_warnings(&toks, src) {
4386 Ok((_, warnings)) => warnings.iter().map(|e| e.category).collect(),
4387 Err(errs) => errs.iter().map(|e| e.category).collect(),
4388 }
4389 }
4390
4391 #[test]
4395 fn a_divider_pair_around_code_is_doc_block_contains_code() {
4396 let src =
4397 "commons m\n\n--------\nfn helper() -> Int { 1 }\n--------\nfn f() -> Int { 2 }\n";
4398 assert_eq!(strict_codes(src), ["bynk.parse.doc_block_contains_code"]);
4399 let errs = parse_str(src).unwrap_err();
4400 assert_eq!(errs[0].category, "bynk.parse.doc_block_contains_code");
4401 assert_eq!(
4403 &src[errs[0].span.range()],
4404 "--------\nfn helper() -> Int { 1 }\n--------\n"
4405 );
4406 let (unit, errs) = parse_recover_str(src);
4407 assert!(unit.is_some(), "recovery keeps the unit");
4408 assert!(
4409 errs.iter()
4410 .any(|e| e.category == "bynk.parse.doc_block_contains_code"),
4411 "{errs:?}"
4412 );
4413 }
4414
4415 #[test]
4418 fn the_divider_the_doc_block_note_suggests_parses() {
4419 let src =
4420 "commons m\n\n--------\nfn helper() -> Int { 1 }\n--------\nfn f() -> Int { 2 }\n";
4421 let errs = parse_str(src).unwrap_err();
4422 let note = &errs[0].notes[0];
4423 let divider = note
4424 .split('`')
4425 .nth(1)
4426 .expect("the note quotes a divider in backticks");
4427 let fixed = format!("commons m\n\n{divider}\nfn helper() -> Int {{ 1 }}\n");
4428 assert_eq!(strict_codes(&fixed), [] as [&str; 0], "{divider:?}");
4429 }
4430
4431 #[test]
4434 fn an_orphaned_or_trailing_divider_pair_is_doc_block_contains_code() {
4435 let orphan = "commons m\n\n---\nfn helper() -> Int { 1 }\n---\n\nfn f() -> Int { 2 }\n";
4436 let codes = strict_codes(orphan);
4437 assert!(
4438 codes.contains(&"bynk.parse.doc_block_contains_code"),
4439 "{codes:?}"
4440 );
4441 let trailing = "commons m\n\nfn f() -> Int { 2 }\n\n---\ntype Id = Int\n---\n";
4442 let codes = strict_codes(trailing);
4443 assert!(
4444 codes.contains(&"bynk.parse.doc_block_contains_code"),
4445 "{codes:?}"
4446 );
4447 }
4448
4449 #[test]
4453 fn near_miss_prose_and_fenced_code_are_not_code() {
4454 for doc in [
4455 "type of the thing",
4456 "fn is used here",
4457 "The type Id is an Int.",
4458 "uses the clock",
4459 "Event handler.\nfn helper() -> Int { 1 }",
4460 "Example:\n```bynk\nfn helper() -> Int { 1 }\n```",
4461 "~~~~\ntype Id = Int\n~~~~",
4462 "---\nA nested doc.\n---",
4463 "",
4464 ] {
4465 assert!(!doc_content_is_code(doc), "{doc:?} read as code");
4466 }
4467 for doc in [
4468 "fn helper() -> Int { 1 }",
4469 "type Id = Int\nfn f() -> Int { 1 }",
4470 "```\nan example\n```\nfn helper() -> Int { 1 }",
4471 "---\nA nested doc.\n---\nfn helper() -> Int { 1 }",
4472 ] {
4473 assert!(doc_content_is_code(doc), "{doc:?} not read as code");
4474 }
4475 }
4476
4477 #[test]
4481 fn code_inside_a_nested_doc_or_beside_a_rule_is_code() {
4482 let nested =
4483 "commons m\n\n----\n---\nfn helper() -> Int { 1 }\n---\n----\nfn f() -> Int { 2 }\n";
4484 assert_eq!(strict_codes(nested), ["bynk.parse.doc_block_contains_code"]);
4485 let ruled = "commons m\n\n----\n---\nfn helper() -> Int { 1 }\n----\nfn f() -> Int { 2 }\n";
4486 assert_eq!(strict_codes(ruled), ["bynk.parse.doc_block_contains_code"]);
4487 assert!(doc_content_is_code(
4489 "----\n---\nfn helper() -> Int { 1 }\n---\n----"
4490 ));
4491 for doc in [
4492 "---\nAn inner doc.\n---",
4493 "Intro.\n\n---\n\nfn is used here",
4494 "---\n```\nfn helper() -> Int { 1 }\n```\n---",
4495 ] {
4496 assert!(!doc_content_is_code(doc), "{doc:?} read as code");
4497 }
4498 let mut deep = "fn helper() -> Int { 1 }".to_string();
4500 for n in (3..3 + DOC_PROBE_MAX_DEPTH + 1).rev() {
4501 let fence = "-".repeat(n);
4502 deep = format!("{fence}\n{deep}\n{fence}");
4503 }
4504 assert!(!doc_content_is_code(&deep));
4505 }
4506
4507 #[test]
4510 fn a_fenced_nested_doc_example_parses_clean() {
4511 let src = "commons m\n\n----\nShows a doc.\n\n```bynk\n---\nInner.\n---\nfn example() -> Int { 1 }\n```\n----\nfn f() -> Int { 2 }\n";
4512 assert!(strict_codes(src).is_empty(), "{:?}", strict_codes(src));
4513 let c = parse_str(src).unwrap();
4514 let CommonsItem::Fn(f) = &c.items[0] else {
4515 panic!("expected fn")
4516 };
4517 assert!(
4518 f.documentation
4519 .as_deref()
4520 .is_some_and(|d| d.contains("---\nInner.\n---")),
4521 "{:?}",
4522 f.documentation
4523 );
4524 }
4525
4526 #[test]
4530 fn private_modifier_is_contextual() {
4531 let src = "commons m\n\n--- Hidden.\nprivate type T = Int\n\nprivate fn T.get(self) -> Int { 1 }\n\nfn f(private: Int) -> Int { private }\n";
4532 let c = parse_str(src).unwrap();
4533 let t = type_at(&c, 0);
4534 let at = src.find("private type").unwrap();
4535 assert_eq!(t.private.map(|s| s.start), Some(at));
4536 assert_eq!(t.span.start, at);
4537 assert_eq!(doc_of(&t.documentation), Some(("Hidden.", DocForm::Lines)));
4538 assert!(c.items[1].is_private());
4539 assert!(!c.items[2].is_private());
4540 }
4541
4542 #[test]
4545 fn private_modifier_on_a_constant() {
4546 let src = "commons m\n\nprivate const Max: Int = 3\n\nconst Min: Int = 1\n";
4547 let c = parse_str(src).unwrap();
4548 let CommonsItem::Const(k) = &c.items[0] else {
4549 panic!("a constant");
4550 };
4551 assert_eq!(
4552 k.private.map(|s| s.start),
4553 Some(src.find("private").unwrap())
4554 );
4555 assert_eq!(k.span.start, src.find("private").unwrap());
4556 assert!(c.items[0].is_private());
4557 assert!(!c.items[1].is_private());
4558 }
4559
4560 #[test]
4562 fn private_on_a_service_is_rejected() {
4563 let src =
4564 "context m\n\nprivate service s {\n on call() -> Effect[Int] by Caller { 1 }\n}\n";
4565 let tokens = crate::lexer::tokenize(src).unwrap();
4566 let errs = parse_units(&tokens, src).unwrap_err();
4567 assert_eq!(errs[0].category, "bynk.visibility.private_not_allowed");
4568 }
4569
4570 fn type_at(c: &Commons, i: usize) -> &TypeDecl {
4572 let CommonsItem::Type(t) = &c.items[i] else {
4573 panic!("expected a type at {i}")
4574 };
4575 t
4576 }
4577
4578 fn doc_of(d: &Option<Doc>) -> Option<(&str, DocForm)> {
4579 d.as_ref().map(|d| (d.as_str().trim_end(), d.form))
4582 }
4583
4584 #[test]
4587 fn doc_lines_document_a_declaration() {
4588 let src = "commons m\n\n--- A commit SHA.\ntype Commit = String\n\n---- First. ----\nfn f() -> Int { 1 }\n";
4589 let c = parse_str(src).unwrap();
4590 assert_eq!(
4591 doc_of(&type_at(&c, 0).documentation),
4592 Some(("A commit SHA.", DocForm::Lines))
4593 );
4594 let CommonsItem::Fn(f) = &c.items[1] else {
4595 panic!("expected fn")
4596 };
4597 assert_eq!(doc_of(&f.documentation), Some(("First.", DocForm::Lines)));
4598 assert!(strict_codes(src).is_empty(), "{:?}", strict_codes(src));
4599 }
4600
4601 #[test]
4605 fn legacy_spellings_parse_and_are_each_reported() {
4606 let src =
4607 "-- a header\ncommons m\n\n--| A run.\ntype Run = {\n repo: String, -- trailing\n}\n";
4608 assert_eq!(
4609 strict_codes(src),
4610 [
4611 "bynk.lex.legacy_comment",
4612 "bynk.lex.legacy_doc_line",
4613 "bynk.lex.legacy_comment"
4614 ]
4615 );
4616 let tokens = tokenize(src).unwrap();
4617 let (units, _, _) = parse_units_migrating(&tokens, src).unwrap();
4618 let SourceUnit::Commons(c) = &units[0] else {
4619 panic!("commons")
4620 };
4621 assert_eq!(
4622 doc_of(&type_at(c, 0).documentation),
4623 Some(("A run.", DocForm::Lines))
4624 );
4625 }
4626
4627 #[test]
4630 fn consecutive_doc_lines_are_multiple_docs_with_a_block_fix() {
4631 let src = "commons m\n\ntype R = {\n --- First.\n --- Second.\n a: Int,\n}\n";
4632 let tokens = tokenize(src).unwrap();
4633 let errs = parse_units(&tokens, src).unwrap_err();
4634 assert_eq!(errs.len(), 1, "{errs:?}");
4635 assert_eq!(errs[0].category, "bynk.parse.multiple_docs");
4636 let (span, block) = &errs[0].suggestions[0].edits[0];
4637 assert_eq!(&src[span.range()], "--- First.\n --- Second.");
4638 assert_eq!(block, "---\n First.\n Second.\n ---");
4639 }
4640
4641 #[test]
4645 fn members_take_docs_in_either_form() {
4646 let src = "commons m\n\ntype Run = {\n --- The repository.\n repo: String,\n ---\n The version.\n ---\n version: String,\n // a note\n sha: String, // trailing\n}\n\ntype Outcome = enum {\n --- Passed.\n Pass,\n Fail,\n}\n\ntype Shape =\n --- Round.\n | Circle(\n --- The radius.\n r: Int,\n )\n | Dot\n\n--- After the sum.\nfn f() -> Int { 1 }\n\nmessages \"en\" @reference {\n --- Greets.\n \"hi\" => \"Hello\"\n}\n";
4647 assert!(strict_codes(src).is_empty(), "{:?}", strict_codes(src));
4648 let c = parse_str(src).unwrap();
4649 let TypeBody::Record(r) = &type_at(&c, 0).body else {
4650 panic!("record")
4651 };
4652 assert_eq!(
4653 doc_of(&r.fields[0].documentation),
4654 Some(("The repository.", DocForm::Lines))
4655 );
4656 assert_eq!(
4657 doc_of(&r.fields[1].documentation),
4658 Some(("The version.", DocForm::Block))
4659 );
4660 assert_eq!(r.fields[2].documentation, None);
4661 assert_eq!(
4662 r.fields[2].trivia.leading,
4663 vec![Comment::Line(" a note".into())]
4664 );
4665 assert_eq!(r.fields[2].trivia.trailing.as_deref(), Some(" trailing"));
4666 let TypeBody::Sum(e) = &type_at(&c, 1).body else {
4667 panic!("enum")
4668 };
4669 assert_eq!(
4670 doc_of(&e.variants[0].documentation),
4671 Some(("Passed.", DocForm::Lines))
4672 );
4673 assert_eq!(e.variants[1].documentation, None);
4674 let TypeBody::Sum(p) = &type_at(&c, 2).body else {
4675 panic!("sum")
4676 };
4677 assert_eq!(
4678 doc_of(&p.variants[0].documentation),
4679 Some(("Round.", DocForm::Lines))
4680 );
4681 assert_eq!(
4682 doc_of(&p.variants[0].payload[0].documentation),
4683 Some(("The radius.", DocForm::Lines))
4684 );
4685 assert_eq!(p.variants[1].documentation, None);
4686 let CommonsItem::Fn(f) = &c.items[3] else {
4688 panic!("expected fn")
4689 };
4690 assert_eq!(
4691 doc_of(&f.documentation),
4692 Some(("After the sum.", DocForm::Lines))
4693 );
4694 let CommonsItem::Messages(m) = &c.items[4] else {
4695 panic!("expected messages")
4696 };
4697 assert_eq!(
4698 doc_of(&m.entries[0].documentation),
4699 Some(("Greets.", DocForm::Lines))
4700 );
4701 }
4702
4703 #[test]
4707 fn two_docs_on_one_target_is_multiple_docs() {
4708 for src in [
4709 "commons m\n\n---\nBlock.\n---\n--- Lines.\nfn f() -> Int { 1 }\n",
4710 "commons m\n\n--- Lines.\n---\nBlock.\n---\nfn f() -> Int { 1 }\n",
4711 "commons m\n\n---\nOne.\n---\n---\nTwo.\n---\nfn f() -> Int { 1 }\n",
4712 "commons m\n\n--- One.\n--- Two.\nfn f() -> Int { 1 }\n",
4713 "commons m\n\ntype R = {\n --- Lines.\n ---\n Block.\n ---\n a: Int,\n}\n",
4714 ] {
4715 assert_eq!(strict_codes(src), ["bynk.parse.multiple_docs"], "{src}");
4716 let (unit, errs) = parse_recover_str(src);
4717 assert!(unit.is_some());
4718 assert!(
4719 errs.iter()
4720 .any(|e| e.category == "bynk.parse.multiple_docs")
4721 );
4722 }
4723 }
4724
4725 #[test]
4728 fn a_dangling_doc_before_a_payload_close_is_only_an_orphan() {
4729 let src =
4730 "commons m\n\ntype S =\n | Circle(\n r: Int,\n --- dangling\n )\n | Dot\n";
4731 assert_eq!(strict_codes(src), ["bynk.parse.orphan_doc_block"]);
4732 let c = parse_str(src).unwrap();
4733 let TypeBody::Sum(s) = &type_at(&c, 0).body else {
4734 panic!("sum")
4735 };
4736 assert_eq!(s.variants[0].payload.len(), 1);
4737 assert_eq!(s.variants[0].payload[0].documentation, None);
4738 }
4739
4740 #[test]
4743 fn an_unattached_member_doc_is_an_orphan() {
4744 let src = "commons m\n\ntype R = {\n --- Spaced.\n\n a: Int,\n --- Dangling.\n}\n";
4745 assert_eq!(
4746 strict_codes(src),
4747 ["bynk.parse.orphan_doc_block", "bynk.parse.orphan_doc_block"]
4748 );
4749 let c = parse_str(src).unwrap();
4750 let TypeBody::Record(r) = &type_at(&c, 0).body else {
4751 panic!("record")
4752 };
4753 assert_eq!(r.fields[0].documentation, None);
4754 assert!(matches!(
4755 &r.fields[0].trivia.leading[..],
4756 [Comment::OrphanDoc(d)] if d.as_str() == "Spaced." && d.form == DocForm::Lines
4757 ));
4758 assert!(matches!(
4759 &r.trailing_comments[..],
4760 [Comment::OrphanDoc(d)] if d.as_str() == "Dangling."
4761 ));
4762 }
4763}
4764
4765#[cfg(test)]
4766mod paren_guard_2721 {
4767 use super::*;
4768 use crate::lexer::tokenize;
4769
4770 fn ok(src: &str) {
4771 let toks = tokenize(src).unwrap();
4772 parse(&toks, src).unwrap_or_else(|e| panic!("{src}\n{e:?}"));
4773 }
4774
4775 fn wrap(guard: &str) -> String {
4776 format!(
4777 "commons t {{\n fn f(n: Int, flag: Bool) -> Int {{\n match n {{\n n if {guard} => n,\n _ => 0,\n }}\n }}\n}}\n"
4778 )
4779 }
4780
4781 #[test]
4782 fn parenthesised_guards_parse() {
4783 ok(&wrap("(flag)"));
4784 ok(&wrap("(n > 0 && flag)"));
4785 ok(&wrap("(n > 0) && flag"));
4786 ok(&wrap("!(flag)"));
4787 ok(&wrap("()"));
4788 }
4789
4790 #[test]
4791 fn lambda_still_parses_when_parenthesised_in_guard() {
4792 ok(&wrap("pred(((x: Int) => x > 0))"));
4793 }
4794}