1use bynk_syntax::ast::*;
54use bynk_syntax::error::CompileError;
55use bynk_syntax::lexer::{
56 Token, TokenKind, comment_is_legacy, doc_fence_len, doc_line_is_legacy, one_line_doc, tokenize,
57 tokenize_legacy,
58};
59use bynk_syntax::parser::parse_units_migrating;
60use bynk_syntax::print::{
61 LambdaBodySrc, WrittenForms, binop_prec, call_site_actor_src, else_if_tail, escape_string,
62 expr_to_string, expr_with_prec, is_pattern_src, lambda_body_src, lambda_param_src,
63 let_else_binding, let_pattern_src, literal_text, matches_argument_span, omit_unit_tail,
64 pattern_to_string, type_ref_to_string,
65};
66use bynk_syntax::span::Span;
67
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
71pub enum IndentStyle {
72 #[default]
73 Tab,
74 Spaces(u8),
75}
76
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub struct FormatOptions {
83 pub indent: IndentStyle,
84 pub max_line_width: u32,
85 pub trailing_comma: bool,
86}
87
88impl Default for FormatOptions {
89 fn default() -> Self {
90 Self {
91 indent: IndentStyle::Tab,
92 max_line_width: 100,
93 trailing_comma: true,
94 }
95 }
96}
97
98#[derive(Debug, Clone)]
101pub struct FormatError {
102 pub errors: Vec<CompileError>,
103}
104
105pub fn format_source(source: &str, opts: &FormatOptions) -> Result<String, FormatError> {
110 let source = &*normalize_line_endings(source);
115 let tokens = migration_tokens(source).map_err(|e| FormatError { errors: vec![e] })?;
116 let (units, _warnings, _) =
122 parse_units_migrating(&tokens, source).map_err(|errors| FormatError { errors })?;
123 let output = render_units(&units, source, opts);
124 if let Some(error) = comment_loss(source, &tokens, &output) {
136 return Err(FormatError {
137 errors: vec![error],
138 });
139 }
140 if let Some(error) = doc_block_loss(source, &tokens, &output) {
147 return Err(FormatError {
148 errors: vec![error],
149 });
150 }
151 if let Some(error) = roundtrip_divergence(&tokens, source, &output, opts) {
160 return Err(FormatError {
161 errors: vec![error],
162 });
163 }
164 Ok(output)
165}
166
167fn migration_tokens(source: &str) -> Result<Vec<Token>, CompileError> {
180 let is_legacy = |t: &Token| match t.kind {
181 TokenKind::Comment => comment_is_legacy(source, t.span),
182 TokenKind::DocLine => doc_line_is_legacy(source, t.span),
183 _ => false,
184 };
185 let current = tokenize(source);
186 if current.as_ref().is_ok_and(|t| !t.iter().any(is_legacy)) {
187 return current;
188 }
189 let old = match tokenize_legacy(source) {
190 Ok(old) if old.iter().any(is_legacy) => old,
191 _ => return current,
192 };
193 let Ok(new) = ¤t else {
194 return Ok(old);
195 };
196 let key = |t: &Token| (t.span.start, t.span.end);
197 let shared: std::collections::HashSet<_> =
198 new.iter().filter(|t| is_legacy(t)).map(key).collect();
199 let rest = |tokens: &[Token]| -> Vec<Token> {
200 tokens
201 .iter()
202 .filter(|t| !(is_legacy(t) && shared.contains(&key(t))))
203 .copied()
204 .collect()
205 };
206 let (old_rest, new_rest) = (rest(&old), rest(new));
207 let differ = old_rest
208 .iter()
209 .zip(&new_rest)
210 .find(|(a, b)| a.kind != b.kind || key(a) != key(b))
211 .map(|(a, b)| {
212 if a.span.start <= b.span.start {
213 a.span
214 } else {
215 b.span
216 }
217 })
218 .or_else(|| {
219 (old_rest.len() != new_rest.len()).then(|| {
220 let n = old_rest.len().min(new_rest.len());
221 old_rest
222 .get(n)
223 .or(new_rest.get(n))
224 .expect("one is longer")
225 .span
226 })
227 });
228 match differ {
229 None => Ok(old),
230 Some(span) => Err(mixed_comment_syntax(source, span)),
231 }
232}
233
234fn mixed_comment_syntax(source: &str, span: Span) -> CompileError {
237 let line_start = source[..span.start].rfind('\n').map_or(0, |i| i + 1);
238 let line_end = source[span.start..]
239 .find('\n')
240 .map_or(source.len(), |i| span.start + i);
241 let line = Span::new_in(span.file, line_start, line_end);
242 CompileError::new(
243 "bynk.fmt.mixed_comment_syntax",
244 line,
245 "this file uses the retired `--` comment or `--|` doc spelling, and this line \
246 reads differently under the old and new comment rules — the file was left unchanged",
247 )
248 .with_label(
249 line,
250 "under the old rules a `--` here is a comment, and `--- text` is a comment, not a doc",
251 )
252 .with_note(
253 "change the retired `--` comments and `--|` docs to `//` and `--- ` (VS Code's Fix All \
254 does this), or rewrite this line, then format again",
255 )
256}
257
258pub fn normalize_line_endings(source: &str) -> std::borrow::Cow<'_, str> {
270 if !source.contains("\r\n") {
271 return std::borrow::Cow::Borrowed(source);
272 }
273 let mut out = String::with_capacity(source.len());
274 let mut pending_crs = 0usize;
275 for c in source.chars() {
276 match c {
277 '\r' => pending_crs += 1,
278 '\n' => {
279 pending_crs = 0;
280 out.push('\n');
281 }
282 _ => {
283 out.extend(std::iter::repeat_n('\r', pending_crs));
284 pending_crs = 0;
285 out.push(c);
286 }
287 }
288 }
289 out.extend(std::iter::repeat_n('\r', pending_crs));
290 std::borrow::Cow::Owned(out)
291}
292
293fn render_units(units: &[SourceUnit], source: &str, opts: &FormatOptions) -> String {
299 let _written_forms = WrittenForms::enter(source);
300 let parts: Vec<String> = units
301 .iter()
302 .map(|unit| {
303 let mut f = Formatter::new(opts);
304 f.format_unit(unit);
305 f.finish()
306 })
307 .collect();
308 parts.join("\n")
309}
310
311fn code_only_canonical(source: &str, opts: &FormatOptions) -> Result<String, Vec<CompileError>> {
318 let tokens = tokenize(source).map_err(|e| vec![e])?;
319 code_only_canonical_from_tokens(&tokens, source, opts)
320}
321
322fn code_only_canonical_from_tokens(
327 tokens: &[Token],
328 source: &str,
329 opts: &FormatOptions,
330) -> Result<String, Vec<CompileError>> {
331 let code: Vec<Token> = tokens
332 .iter()
333 .filter(|t| t.kind != TokenKind::Comment)
334 .cloned()
335 .collect();
336 let (units, _, _) = parse_units_migrating(&code, source)?;
337 Ok(render_units(&units, source, opts))
338}
339
340fn roundtrip_divergence(
355 tokens: &[Token],
356 source: &str,
357 output: &str,
358 opts: &FormatOptions,
359) -> Option<CompileError> {
360 let canon_out = match code_only_canonical(output, opts) {
363 Ok(canon) => canon,
364 Err(_) => {
365 return Some(roundtrip_error(
366 "the formatter produced output that no longer parses",
367 ));
368 }
369 };
370 let canon_in = code_only_canonical_from_tokens(tokens, source, opts).ok()?;
376 (canon_in != canon_out)
377 .then(|| roundtrip_error("the formatter's output does not round-trip to the same code"))
378}
379
380fn roundtrip_error(what: &str) -> CompileError {
391 CompileError {
392 category: "bynk.fmt.roundtrip",
393 span: Span::default(),
394 message: format!("{what} — the file was left unchanged"),
395 labels: Vec::new(),
396 notes: vec![
397 "this is a formatter bug, not a problem with your source; please report it \
398 with the file that triggered it"
399 .to_string(),
400 ],
401 suggestions: Vec::new(),
402 }
403}
404
405fn comment_loss(source: &str, tokens: &[Token], output: &str) -> Option<CompileError> {
412 use bynk_syntax::lexer::comment_body;
413 let in_comments: Vec<Span> = tokens
414 .iter()
415 .filter(|t| t.kind == TokenKind::Comment)
416 .map(|t| t.span)
417 .collect();
418 if in_comments.is_empty() {
419 return None;
420 }
421 let mut out_bodies: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
424 if let Ok(out_tokens) = tokenize(output) {
425 for t in &out_tokens {
426 if t.kind == TokenKind::Comment {
427 *out_bodies
428 .entry(comment_body(output, t.span).trim().to_string())
429 .or_insert(0) += 1;
430 }
431 }
432 }
433 let mut lost = 0usize;
434 let mut first_lost: Option<Span> = None;
435 for span in &in_comments {
436 let body = comment_body(source, *span).trim().to_string();
437 match out_bodies.get_mut(&body) {
438 Some(n) if *n > 0 => *n -= 1,
439 _ => {
440 lost += 1;
441 first_lost.get_or_insert(*span);
442 }
443 }
444 }
445 let span = first_lost?;
446 Some(CompileError {
447 category: "bynk.fmt.comment_loss",
448 span,
449 message: format!(
450 "formatting would lose {lost} comment{} — the file was left unchanged",
451 if lost == 1 { "" } else { "s" }
452 ),
453 labels: vec![(
454 span,
455 "this comment sits where the formatter cannot yet re-attach it".to_string(),
456 )],
457 notes: vec![
458 "comments inside expression subtrees are not yet preserved; move the comment onto \
459 its own line before the enclosing statement to format this file"
460 .to_string(),
461 ],
462 suggestions: Vec::new(),
463 })
464}
465
466fn source_docs(source: &str, tokens: &[Token]) -> Vec<(Span, DocForm, String)> {
471 use bynk_syntax::lexer::{doc_block_content, doc_line_text};
472 let normalise = |content: &str| {
473 content
474 .lines()
475 .map(str::trim)
476 .collect::<Vec<_>>()
477 .join("\n")
478 };
479 tokens
480 .iter()
481 .filter_map(|t| match t.kind {
482 TokenKind::DocLine => Some((
483 t.span,
484 DocForm::Lines,
485 normalise(doc_line_text(source, t.span)),
486 )),
487 TokenKind::DocBlock => Some((
488 t.span,
489 DocForm::Block,
490 normalise(&doc_block_content(source, t.span)),
491 )),
492 _ => None,
493 })
494 .collect()
495}
496
497fn doc_block_loss(source: &str, tokens: &[Token], output: &str) -> Option<CompileError> {
511 let in_docs = source_docs(source, tokens);
512 if in_docs.is_empty() {
513 return None;
514 }
515 let out_tokens = tokenize(output).ok()?;
516 let mut out_docs: std::collections::HashMap<(DocForm, String), usize> =
517 std::collections::HashMap::new();
518 for (_, form, content) in source_docs(output, &out_tokens) {
519 *out_docs.entry((form, content)).or_insert(0) += 1;
520 }
521 let mut lost = 0usize;
522 let mut first_lost: Option<Span> = None;
523 for (span, form, content) in in_docs {
524 match out_docs.get_mut(&(form, content)) {
525 Some(n) if *n > 0 => *n -= 1,
526 _ => {
527 lost += 1;
528 first_lost.get_or_insert(span);
529 }
530 }
531 }
532 let span = first_lost?;
533 Some(CompileError {
534 category: "bynk.fmt.comment_loss",
535 span,
536 message: format!(
537 "formatting would lose {lost} doc{} — the file was left unchanged",
538 if lost == 1 { "" } else { "s" }
539 ),
540 labels: vec![(
541 span,
542 "this doc has no counterpart in the formatted output".to_string(),
543 )],
544 notes: vec![
545 "a doc (a `---` block or `--|` lines) attaches to the declaration or member \
546 directly below it; one separated from it by a blank line, or with nothing after \
547 it, attaches to nothing. Remove the blank line to attach it, or make it a `--` \
548 comment if it documents nothing"
549 .to_string(),
550 "if the block is already directly above a declaration, this is a formatter bug; \
551 please report it with the file that triggered it"
552 .to_string(),
553 ],
554 suggestions: Vec::new(),
555 })
556}
557
558struct Formatter<'a> {
561 opts: &'a FormatOptions,
562 out: String,
563 indent_level: u32,
564 at_line_start: bool,
567}
568
569impl<'a> Formatter<'a> {
570 fn new(opts: &'a FormatOptions) -> Self {
571 Self {
572 opts,
573 out: String::new(),
574 indent_level: 0,
575 at_line_start: true,
576 }
577 }
578
579 fn finish(mut self) -> String {
580 while self.out.ends_with("\n\n") {
582 self.out.pop();
583 }
584 if !self.out.ends_with('\n') {
585 self.out.push('\n');
586 }
587 self.out
588 }
589
590 fn indent_unit(&self) -> String {
591 match self.opts.indent {
592 IndentStyle::Tab => "\t".to_string(),
593 IndentStyle::Spaces(n) => " ".repeat(n as usize),
594 }
595 }
596
597 fn emit_indent(&mut self) {
598 let unit = self.indent_unit();
599 for _ in 0..self.indent_level {
600 self.out.push_str(&unit);
601 }
602 }
603
604 fn push(&mut self, s: &str) {
605 if self.at_line_start && !s.starts_with('\n') {
606 self.emit_indent();
607 self.at_line_start = false;
608 }
609 if s.contains('\n') {
610 self.push_reindented(s);
611 } else {
612 self.out.push_str(s);
613 }
614 }
615
616 fn push_reindented(&mut self, s: &str) {
626 let prefix = self.indent_unit().repeat(self.indent_level as usize);
627 for (i, line) in s.split('\n').enumerate() {
628 if i > 0 {
629 self.out.push('\n');
630 if !line.is_empty() {
631 self.out.push_str(&prefix);
632 }
633 }
634 self.out.push_str(line);
635 }
636 }
637
638 fn newline(&mut self) {
639 self.out.push('\n');
640 self.at_line_start = true;
641 }
642
643 fn header_comment_gap(&mut self, any_before: bool, blank_before: bool, leading: &[Comment]) {
651 if any_before && blank_before && !leading.is_empty() {
652 self.blank_line();
653 }
654 }
655
656 fn blank_line(&mut self) {
657 if !self.out.ends_with('\n') {
658 self.out.push('\n');
659 }
660 if !self.out.ends_with("\n\n") {
661 self.out.push('\n');
662 }
663 self.at_line_start = true;
664 }
665
666 fn indented<F: FnOnce(&mut Self)>(&mut self, f: F) {
667 self.indent_level += 1;
668 f(self);
669 self.indent_level -= 1;
670 }
671
672 fn try_layout<F: FnOnce(&mut Self)>(&mut self, reserve: usize, body: F) -> bool {
682 self.try_layout_if(reserve, body, || true)
683 }
684
685 fn try_layout_if<F: FnOnce(&mut Self), A: FnOnce() -> bool>(
689 &mut self,
690 reserve: usize,
691 body: F,
692 accept: A,
693 ) -> bool {
694 let line_start = self.out.rfind('\n').map_or(0, |i| i + 1);
695 let mut sub = Formatter {
696 opts: self.opts,
697 out: self.out[line_start..].to_string(),
698 indent_level: self.indent_level,
699 at_line_start: self.at_line_start,
700 };
701 let produced_from = sub.out.len();
702 body(&mut sub);
703 if !sub.every_line_within_budget(reserve) || !accept() {
704 return false;
705 }
706 self.out.push_str(&sub.out[produced_from..]);
709 self.at_line_start = sub.at_line_start;
710 true
711 }
712
713 fn every_line_within_budget(&self, reserve: usize) -> bool {
716 let tab = self.indent_width();
717 let mut lines = self.out.split('\n').peekable();
718 let mut last = "";
719 while let Some(line) = lines.next() {
720 if lines.peek().is_none() {
721 last = line;
722 break;
723 }
724 if display_width(line, tab) > self.opts.max_line_width as usize {
725 return false;
726 }
727 }
728 let last_width = if self.at_line_start {
729 self.indent_level as usize * tab
731 } else {
732 display_width(last, tab)
733 };
734 last_width + reserve <= self.opts.max_line_width as usize
735 }
736
737 fn emit_doc(&mut self, doc: &Doc) {
752 if doc.form == DocForm::Lines {
753 self.push(&one_line_doc(doc));
754 self.newline();
755 return;
756 }
757 let fence = "-".repeat(doc_fence_len(doc));
758 self.push(&fence);
759 self.newline();
760 for line in doc.lines() {
761 if line.is_empty() {
762 self.newline();
763 } else {
764 self.push(line);
765 self.newline();
766 }
767 }
768 self.push(&fence);
769 self.newline();
770 }
771
772 fn emit_leading_comments(&mut self, comments: &[Comment]) {
781 self.emit_comments(comments, true);
782 }
783
784 fn emit_trailing_comments(&mut self, comments: &[Comment]) {
789 self.emit_comments(comments, false);
790 }
791
792 fn emit_comments(&mut self, comments: &[Comment], blank_after_last: bool) {
793 for (i, comment) in comments.iter().enumerate() {
794 let blank_after = i + 1 < comments.len() || blank_after_last;
795 match comment {
796 Comment::Line(body) => {
797 self.push("//");
798 self.push(body);
799 self.newline();
800 }
801 Comment::OrphanDoc(doc) => {
802 self.emit_doc(doc);
803 if blank_after {
804 self.newline();
805 }
806 }
807 Comment::Blank if blank_after => self.blank_line(),
808 Comment::Blank => {}
809 }
810 }
811 }
812
813 fn emit_trailing_comment(&mut self, body: Option<&str>) {
816 if let Some(body) = body {
817 while self.out.ends_with('\n') {
820 self.out.pop();
821 }
822 self.out.push_str(" //");
823 self.out.push_str(body);
824 self.newline();
825 }
826 }
827
828 fn emit_trailing_comment_or_newline(&mut self, trailing: Option<&str>) {
833 if trailing.is_some() {
834 self.emit_trailing_comment(trailing);
835 } else {
836 self.newline();
837 }
838 }
839
840 fn format_unit(&mut self, unit: &SourceUnit) {
843 match unit {
844 SourceUnit::Commons(c) => self.format_commons(c),
845 SourceUnit::Context(c) => self.format_context(c),
846 SourceUnit::Suite(t) => self.format_test(t),
847 SourceUnit::Adapter(a) => self.format_adapter(a),
848 }
849 }
850
851 fn format_adapter(&mut self, a: &AdapterDecl) {
852 self.emit_leading_comments(&a.trivia.leading);
853 if let Some(doc) = &a.documentation {
854 self.emit_doc(doc);
855 }
856 let header = format!("adapter {}", a.name.joined());
857 match a.form {
858 CommonsForm::Brace => {
859 self.push(&header);
860 self.push(" {");
861 self.newline();
862 self.indented(|f| {
863 f.format_adapter_body(a);
864 });
865 self.push("}");
866 self.newline();
867 }
868 CommonsForm::Fragment => {
869 self.push(&header);
870 self.newline();
871 self.newline();
872 self.format_adapter_body(a);
873 }
874 }
875 }
876
877 fn format_adapter_body(&mut self, a: &AdapterDecl) {
878 let mut any_header = false;
879 if let Some(b) = &a.binding {
880 self.emit_leading_comments(&b.trivia.leading);
881 self.push(&format!("binding {:?}", b.module));
882 if !b.includes.is_empty() {
883 let entries: Vec<String> =
884 b.includes.iter().map(|i| format!("{:?}", i.path)).collect();
885 self.push(&format!(" includes [{}]", entries.join(", ")));
886 }
887 if !b.requires.is_empty() {
888 let entries: Vec<String> = b
889 .requires
890 .iter()
891 .map(|r| format!("{:?}: {:?}", r.package, r.range))
892 .collect();
893 self.push(&format!(" requires {{ {} }}", entries.join(", ")));
894 }
895 self.emit_trailing_comment_or_newline(b.trivia.trailing.as_deref());
896 any_header = true;
897 }
898 for u in &a.uses {
899 self.header_comment_gap(any_header, u.blank_before, &u.trivia.leading);
900 self.emit_leading_comments(&u.trivia.leading);
901 self.push(&format!("uses {}", u.target.joined()));
902 self.emit_trailing_comment_or_newline(u.trivia.trailing.as_deref());
903 any_header = true;
904 }
905 for c in &a.consumes {
906 self.format_consumes(c, any_header);
907 any_header = true;
908 }
909 for e in &a.exports {
910 self.header_comment_gap(any_header, e.blank_before, &e.trivia.leading);
911 self.emit_leading_comments(&e.trivia.leading);
912 self.format_exports(e);
913 if e.trivia.trailing.is_some() {
914 self.emit_trailing_comment(e.trivia.trailing.as_deref());
915 }
916 any_header = true;
917 }
918 if any_header && !a.items.is_empty() {
919 self.newline();
920 }
921 let mut first = true;
922 for item in &a.items {
923 if !first {
924 self.newline();
925 }
926 self.format_item(item);
927 first = false;
928 }
929 if !a.trailing_comments.is_empty() {
930 if !a.items.is_empty() || any_header {
931 self.newline();
932 }
933 self.emit_trailing_comments(&a.trailing_comments);
934 }
935 }
936
937 fn format_test(&mut self, t: &SuiteDecl) {
938 self.emit_leading_comments(&t.trivia.leading);
939 if let Some(doc) = &t.documentation {
940 self.emit_doc(doc);
941 }
942 let mut header = format!("suite {}", t.target.joined());
943 if let Some(tier) = t.tier {
944 header.push_str(&format!(" as {}", tier.as_str()));
945 }
946 match t.form {
947 CommonsForm::Brace => {
948 self.push(&header);
949 self.push(" {");
950 self.newline();
951 self.indented(|f| {
952 f.format_test_body(
953 &t.uses,
954 &t.consumes,
955 &t.envs,
956 &t.stubs,
957 &t.fixtures,
958 &t.types,
959 &t.consts,
960 &t.fns,
961 &t.cases,
962 &t.properties,
963 &t.trailing_comments,
964 );
965 });
966 self.push("}");
967 self.newline();
968 }
969 CommonsForm::Fragment => {
970 self.push(&header);
971 self.newline();
972 self.newline();
973 self.format_test_body(
974 &t.uses,
975 &t.consumes,
976 &t.envs,
977 &t.stubs,
978 &t.fixtures,
979 &t.types,
980 &t.consts,
981 &t.fns,
982 &t.cases,
983 &t.properties,
984 &t.trailing_comments,
985 );
986 }
987 }
988 }
989
990 #[allow(clippy::too_many_arguments)]
991 fn format_test_body(
992 &mut self,
993 uses: &[UsesDecl],
994 consumes: &[ConsumesDecl],
995 envs: &[EnvClause],
996 stubs: &[StubClause],
997 fixtures: &[FixtureDecl],
998 types: &[TypeDecl],
999 consts: &[ConstDecl],
1000 fns: &[FnDecl],
1001 cases: &[Case],
1002 properties: &[PropertyDecl],
1003 trailing_comments: &[Comment],
1004 ) {
1005 let mut first = true;
1006 for u in uses {
1007 if !first {
1008 self.newline();
1009 }
1010 self.emit_leading_comments(&u.trivia.leading);
1011 self.push(&format!("uses {}", u.target.joined()));
1012 self.emit_trailing_comment_or_newline(u.trivia.trailing.as_deref());
1013 first = false;
1014 }
1015 for (i, c) in consumes.iter().enumerate() {
1017 if !first && i == 0 {
1018 self.newline();
1019 }
1020 self.format_consumes(c, i > 0);
1021 first = false;
1022 }
1023 for e in envs {
1024 if !first {
1025 self.newline();
1026 }
1027 self.format_env_clause(e);
1028 first = false;
1029 }
1030 for pv in stubs {
1031 if !first {
1032 self.newline();
1033 }
1034 self.format_stub_clause(pv);
1035 first = false;
1036 }
1037 enum Member<'a> {
1040 Fixture(&'a FixtureDecl),
1041 Type(&'a TypeDecl),
1042 Const(&'a ConstDecl),
1043 Fn(&'a FnDecl),
1044 Case(&'a Case),
1045 Property(&'a PropertyDecl),
1046 }
1047 let mut members: Vec<(usize, Member)> = fixtures
1048 .iter()
1049 .map(|f| (f.span.start, Member::Fixture(f)))
1050 .chain(types.iter().map(|t| (t.span.start, Member::Type(t))))
1051 .chain(consts.iter().map(|c| (c.span.start, Member::Const(c))))
1052 .chain(fns.iter().map(|f| (f.span.start, Member::Fn(f))))
1053 .chain(cases.iter().map(|c| (c.name_span.start, Member::Case(c))))
1054 .chain(
1055 properties
1056 .iter()
1057 .map(|p| (p.name_span.start, Member::Property(p))),
1058 )
1059 .collect();
1060 members.sort_by_key(|(start, _)| *start);
1061 for (_, member) in members {
1062 if !first {
1063 self.newline();
1064 }
1065 match member {
1066 Member::Fixture(f) => self.format_fixture_decl(f),
1067 Member::Type(t) => self.format_type_decl(t),
1068 Member::Const(c) => self.format_const_decl(c),
1069 Member::Fn(f) => self.format_fn_decl(f),
1070 Member::Case(c) => self.format_case(c),
1071 Member::Property(p) => self.format_property(p),
1072 }
1073 first = false;
1074 }
1075 self.emit_trailing_comments(trailing_comments);
1076 }
1077
1078 fn format_fixture_decl(&mut self, f: &FixtureDecl) {
1080 self.emit_leading_comments(&f.trivia.leading);
1081 if let Some(doc) = &f.documentation {
1082 self.emit_doc(doc);
1083 }
1084 self.push(&format!(
1085 "fixture {} = \"{}\"",
1086 f.name.name,
1087 escape_string(&f.path)
1088 ));
1089 self.emit_trailing_comment_or_newline(f.trivia.trailing.as_deref());
1090 }
1091
1092 fn format_case(&mut self, c: &Case) {
1093 self.emit_leading_comments(&c.trivia.leading);
1094 if let Some(doc) = &c.documentation {
1095 self.emit_doc(doc);
1096 }
1097 let mut ch = format!("case \"{}\"", escape_string(&c.name));
1098 if let Some(tier) = c.tier {
1099 ch.push_str(&format!(" as {}", tier.as_str()));
1100 }
1101 ch.push(' ');
1102 self.push(&ch);
1103 self.format_case_block(&c.body, &c.envs, &c.stubs);
1104 self.newline();
1105 }
1106
1107 fn format_property(&mut self, p: &PropertyDecl) {
1108 self.emit_leading_comments(&p.trivia.leading);
1109 if let Some(doc) = &p.documentation {
1110 self.emit_doc(doc);
1111 }
1112 self.push(&format!("property \"{}\" {{", escape_string(&p.name)));
1113 self.newline();
1114 self.indented(|f| f.format_for_all(&p.forall));
1115 self.push("}");
1116 self.newline();
1117 }
1118
1119 fn format_stub_clause(&mut self, pv: &StubClause) {
1123 self.emit_leading_comments(&pv.trivia.leading);
1124 if let Some(doc) = &pv.documentation {
1125 self.emit_doc(doc);
1126 }
1127 self.push(&stub_clause_to_string(pv));
1128 self.emit_trailing_comment_or_newline(pv.trivia.trailing.as_deref());
1129 }
1130
1131 fn format_env_clause(&mut self, e: &EnvClause) {
1134 self.emit_leading_comments(&e.trivia.leading);
1135 if let Some(doc) = &e.documentation {
1136 self.emit_doc(doc);
1137 }
1138 self.push("env {");
1139 self.newline();
1140 self.indented(|f| {
1141 for entry in &e.entries {
1142 f.push(&format!(
1143 "{} = {}",
1144 entry.name.name,
1145 expr_to_string(&entry.value)
1146 ));
1147 f.newline();
1148 }
1149 });
1150 self.push("}");
1151 self.emit_trailing_comment_or_newline(e.trivia.trailing.as_deref());
1152 }
1153
1154 fn format_case_block(&mut self, b: &Block, envs: &[EnvClause], stubs: &[StubClause]) {
1158 if stubs.is_empty() && envs.is_empty() {
1159 self.format_block(b);
1160 return;
1161 }
1162 self.push("{");
1163 self.newline();
1164 self.indented(|f| {
1165 for e in envs {
1166 f.format_env_clause(e);
1167 }
1168 for pv in stubs {
1169 f.format_stub_clause(pv);
1170 }
1171 f.format_block_body(b);
1174 });
1175 self.push("}");
1176 }
1177
1178 fn format_for_all(&mut self, fa: &ForAll) {
1181 let bindings = fa
1182 .bindings
1183 .iter()
1184 .map(|b| format!("{}: {}", b.name.name, type_ref_to_string(&b.type_ref)))
1185 .collect::<Vec<_>>()
1186 .join(", ");
1187 let mut header = format!("for all {bindings}");
1188 if let Some(w) = &fa.where_pred {
1189 header.push_str(&format!(" where {}", expr_to_string(w)));
1190 }
1191 self.push(&format!("{header} "));
1192 self.format_block(&fa.body);
1193 self.newline();
1194 }
1195
1196 fn format_commons(&mut self, c: &Commons) {
1197 self.emit_leading_comments(&c.trivia.leading);
1198 if let Some(doc) = &c.documentation {
1199 self.emit_doc(doc);
1200 }
1201 let header = format!("commons {}", c.name.joined());
1202 match c.form {
1203 CommonsForm::Brace => {
1204 self.push(&header);
1205 self.push(" {");
1206 self.newline();
1207 self.indented(|f| {
1208 f.format_commons_body(&c.uses, &c.items, &c.trailing_comments);
1209 });
1210 self.push("}");
1211 self.newline();
1212 }
1213 CommonsForm::Fragment => {
1214 self.push(&header);
1215 self.newline();
1216 self.newline();
1217 self.format_commons_body(&c.uses, &c.items, &c.trailing_comments);
1218 }
1219 }
1220 }
1221
1222 fn format_commons_body(
1223 &mut self,
1224 uses: &[UsesDecl],
1225 items: &[CommonsItem],
1226 trailing_comments: &[Comment],
1227 ) {
1228 let mut any_uses = false;
1229 for u in uses {
1230 self.header_comment_gap(any_uses, u.blank_before, &u.trivia.leading);
1231 self.emit_leading_comments(&u.trivia.leading);
1232 self.push(&format!("uses {}", u.target.joined()));
1233 self.emit_trailing_comment_or_newline(u.trivia.trailing.as_deref());
1234 any_uses = true;
1235 }
1236 if any_uses && !items.is_empty() {
1237 self.newline();
1238 }
1239 let mut first = true;
1240 for item in items {
1241 if !first {
1242 self.newline();
1243 }
1244 self.format_item(item);
1245 first = false;
1246 }
1247 if !trailing_comments.is_empty() {
1248 if !items.is_empty() || any_uses {
1251 self.newline();
1252 }
1253 self.emit_trailing_comments(trailing_comments);
1254 }
1255 }
1256
1257 fn format_context(&mut self, c: &Context) {
1258 self.emit_leading_comments(&c.trivia.leading);
1259 if let Some(doc) = &c.documentation {
1260 self.emit_doc(doc);
1261 }
1262 let header = format!("context {}", c.name.joined());
1263 match c.form {
1264 CommonsForm::Brace => {
1265 self.push(&header);
1266 self.push(" {");
1267 self.newline();
1268 self.indented(|f| {
1269 f.format_context_body(
1270 &c.uses,
1271 &c.consumes,
1272 &c.exports,
1273 &c.items,
1274 &c.removed_agents,
1275 &c.trailing_comments,
1276 );
1277 });
1278 self.push("}");
1279 self.newline();
1280 }
1281 CommonsForm::Fragment => {
1282 self.push(&header);
1283 self.newline();
1284 self.newline();
1285 self.format_context_body(
1286 &c.uses,
1287 &c.consumes,
1288 &c.exports,
1289 &c.items,
1290 &c.removed_agents,
1291 &c.trailing_comments,
1292 );
1293 }
1294 }
1295 }
1296
1297 fn format_consumes(&mut self, c: &ConsumesDecl, any_before: bool) {
1301 self.header_comment_gap(any_before, c.blank_before, &c.trivia.leading);
1302 self.emit_leading_comments(&c.trivia.leading);
1303 match (&c.alias, &c.selected) {
1304 (Some(alias), _) => {
1305 self.push(&format!("consumes {} as {}", c.target.joined(), alias.name))
1306 }
1307 (None, Some(selected)) if selected.is_empty() => {
1308 self.push(&format!("consumes {} {{ }}", c.target.joined()));
1309 }
1310 (None, Some(selected)) => {
1311 let names: Vec<String> = selected
1312 .iter()
1313 .map(|i| match &i.alias {
1314 Some(a) => format!("{} as {}", i.name.name, a.name),
1315 None => i.name.name.clone(),
1316 })
1317 .collect();
1318 self.push(&format!(
1319 "consumes {} {{ {} }}",
1320 c.target.joined(),
1321 names.join(", ")
1322 ));
1323 }
1324 (None, None) => self.push(&format!("consumes {}", c.target.joined())),
1325 }
1326 self.emit_trailing_comment_or_newline(c.trivia.trailing.as_deref());
1327 }
1328
1329 fn format_context_body(
1330 &mut self,
1331 uses: &[UsesDecl],
1332 consumes: &[ConsumesDecl],
1333 exports: &[ExportsDecl],
1334 items: &[CommonsItem],
1335 removed_agents: &[RemovedAgentDecl],
1336 trailing_comments: &[Comment],
1337 ) {
1338 let mut any_header = false;
1339 for u in uses {
1340 self.header_comment_gap(any_header, u.blank_before, &u.trivia.leading);
1341 self.emit_leading_comments(&u.trivia.leading);
1342 self.push(&format!("uses {}", u.target.joined()));
1343 self.emit_trailing_comment_or_newline(u.trivia.trailing.as_deref());
1344 any_header = true;
1345 }
1346 for c in consumes {
1347 self.format_consumes(c, any_header);
1348 any_header = true;
1349 }
1350 for e in exports {
1351 self.header_comment_gap(any_header, e.blank_before, &e.trivia.leading);
1352 self.emit_leading_comments(&e.trivia.leading);
1353 self.format_exports(e);
1354 if e.trivia.trailing.is_some() {
1358 self.emit_trailing_comment(e.trivia.trailing.as_deref());
1359 }
1360 any_header = true;
1361 }
1362 if any_header && (!items.is_empty() || !removed_agents.is_empty()) {
1363 self.newline();
1364 }
1365 let mut first = true;
1366 for item in items {
1367 if !first {
1368 self.newline();
1369 }
1370 self.format_item(item);
1371 first = false;
1372 }
1373 for r in removed_agents {
1376 if !first {
1377 self.newline();
1378 }
1379 self.emit_leading_comments(&r.trivia.leading);
1380 if let Some(doc) = &r.documentation {
1381 self.emit_doc(doc);
1382 }
1383 self.push(&format!("removed agent {}", r.name.name));
1384 self.emit_trailing_comment_or_newline(r.trivia.trailing.as_deref());
1385 first = false;
1386 }
1387 if !trailing_comments.is_empty() {
1388 if !items.is_empty() || !removed_agents.is_empty() || any_header {
1389 self.newline();
1390 }
1391 self.emit_trailing_comments(trailing_comments);
1392 }
1393 }
1394
1395 fn format_exports(&mut self, e: &ExportsDecl) {
1396 let vis = match e.kind {
1397 ExportKind::Type(Visibility::Opaque) => "opaque",
1398 ExportKind::Type(Visibility::Transparent) => "transparent",
1399 ExportKind::Capability => "capability",
1400 };
1401 let has_comments = !e.trailing_comments.is_empty()
1403 || e.names
1404 .iter()
1405 .any(|n| !n.trivia.leading.is_empty() || n.trivia.trailing.is_some());
1406 if e.names.is_empty() && !has_comments {
1407 self.push(&format!("exports {} {{}}", vis));
1408 self.newline();
1409 return;
1410 }
1411 if !has_comments {
1413 let oneline = format!(
1414 "exports {} {{ {} }}",
1415 vis,
1416 e.names
1417 .iter()
1418 .map(|n| n.name.name.as_str())
1419 .collect::<Vec<_>>()
1420 .join(", ")
1421 );
1422 if self.fits(&oneline, 0) {
1423 self.push(&oneline);
1424 self.newline();
1425 return;
1426 }
1427 }
1428 self.push(&format!("exports {} {{", vis));
1430 self.newline();
1431 self.indented(|f| {
1432 for (i, n) in e.names.iter().enumerate() {
1433 f.emit_leading_comments(&n.trivia.leading);
1434 f.push(&n.name.name);
1435 if i + 1 < e.names.len() || f.opts.trailing_comma {
1436 f.push(",");
1437 }
1438 f.emit_trailing_comment_or_newline(n.trivia.trailing.as_deref());
1439 }
1440 f.emit_trailing_comments(&e.trailing_comments);
1441 });
1442 self.push("}");
1443 self.newline();
1444 }
1445
1446 fn indent_width(&self) -> usize {
1450 match self.opts.indent {
1451 IndentStyle::Tab => 4,
1452 IndentStyle::Spaces(n) => n as usize,
1453 }
1454 }
1455
1456 fn current_column(&self) -> usize {
1462 if self.at_line_start {
1463 return self.indent_level as usize * self.indent_width();
1465 }
1466 let line = match self.out.rfind('\n') {
1467 Some(i) => &self.out[i + 1..],
1468 None => self.out.as_str(),
1469 };
1470 display_width(line, self.indent_width())
1471 }
1472
1473 fn fits(&self, candidate: &str, reserve: usize) -> bool {
1479 if candidate.contains('\n') {
1480 return false;
1481 }
1482 let column =
1483 self.current_column() + display_width(candidate, self.indent_width()) + reserve;
1484 column <= self.opts.max_line_width as usize
1485 }
1486
1487 fn format_item(&mut self, item: &CommonsItem) {
1488 match item {
1489 CommonsItem::Type(t) => self.format_type_decl(t),
1490 CommonsItem::Fn(f) => self.format_fn_decl(f),
1491 CommonsItem::Capability(c) => self.format_capability(c),
1492 CommonsItem::Provider(p) => self.format_provider(p),
1493 CommonsItem::Service(s) => self.format_service(s),
1494 CommonsItem::Agent(a) => self.format_agent(a),
1495 CommonsItem::Actor(a) => self.format_actor(a),
1496 CommonsItem::Messages(m) => self.format_messages(m),
1497 CommonsItem::Event(e) => self.format_event_decl(e),
1498 CommonsItem::Asset(a) => self.format_asset_decl(a),
1499 CommonsItem::Embed(e) => self.format_embed_decl(e),
1500 CommonsItem::Const(c) => self.format_const_decl(c),
1501 }
1502 }
1503
1504 fn format_asset_decl(&mut self, a: &AssetDecl) {
1506 self.emit_leading_comments(&a.trivia.leading);
1507 if let Some(doc) = &a.documentation {
1508 self.emit_doc(doc);
1509 }
1510 if a.private.is_some() {
1512 self.push("private ");
1513 }
1514 self.push(&format!(
1515 "asset {} = \"{}\"",
1516 a.name.name,
1517 escape_string(&a.path)
1518 ));
1519 if let Some((at, _)) = &a.at {
1520 self.push(&format!(" at \"{}\"", escape_string(at)));
1521 }
1522 self.emit_trailing_comment_or_newline(a.trivia.trailing.as_deref());
1523 }
1524
1525 fn format_embed_decl(&mut self, e: &EmbedDecl) {
1527 self.emit_leading_comments(&e.trivia.leading);
1528 if let Some(doc) = &e.documentation {
1529 self.emit_doc(doc);
1530 }
1531 if e.private.is_some() {
1533 self.push("private ");
1534 }
1535 self.push(&format!(
1536 "embed {} = \"{}\"",
1537 e.name.name,
1538 escape_string(&e.path)
1539 ));
1540 self.emit_trailing_comment_or_newline(e.trivia.trailing.as_deref());
1541 }
1542
1543 fn format_const_decl(&mut self, c: &ConstDecl) {
1546 self.emit_leading_comments(&c.trivia.leading);
1547 if let Some(doc) = &c.documentation {
1548 self.emit_doc(doc);
1549 }
1550 if c.private.is_some() {
1552 self.push("private ");
1553 }
1554 self.push("const ");
1555 self.push(&c.name.name);
1556 self.push(": ");
1557 self.format_type_ref(&c.ty);
1558 self.push(" = ");
1559 self.format_expr(&c.init);
1560 self.emit_trailing_comment_or_newline(c.trivia.trailing.as_deref());
1561 }
1562
1563 fn format_event_decl(&mut self, e: &EventDecl) {
1564 self.emit_leading_comments(&e.trivia.leading);
1565 if let Some(doc) = &e.documentation {
1566 self.emit_doc(doc);
1567 }
1568 self.push(&format!("event {}", e.name.name));
1569 for ann in &e.annotations {
1572 self.push(" ");
1573 self.push(&annotation_to_string(ann));
1574 }
1575 self.push(" = ");
1576 self.format_record_body(&e.body);
1577 self.emit_trailing_comment_or_newline(e.trivia.trailing.as_deref());
1578 }
1579
1580 fn format_messages(&mut self, m: &MessagesDecl) {
1581 self.emit_leading_comments(&m.trivia.leading);
1582 if let Some(doc) = &m.documentation {
1583 self.emit_doc(doc);
1584 }
1585 if m.private.is_some() {
1587 self.push("private ");
1588 }
1589 self.push(&format!("messages \"{}\"", escape_string(&m.tag)));
1590 for ann in &m.annotations {
1591 self.push(" ");
1592 self.push(&annotation_to_string(ann));
1593 }
1594 self.push(" {");
1595 self.newline();
1596 self.indented(|f| {
1597 for entry in &m.entries {
1598 if let Some(doc) = &entry.documentation {
1599 f.emit_doc(doc);
1600 }
1601 f.push(&format!(
1602 "{} => {}",
1603 literal_text(entry.code_span, &entry.code),
1604 literal_text(entry.template_span, &entry.template)
1605 ));
1606 f.newline();
1607 }
1608 });
1609 self.push("}");
1610 self.emit_trailing_comment_or_newline(m.trivia.trailing.as_deref());
1611 }
1612
1613 fn format_type_decl(&mut self, t: &TypeDecl) {
1616 self.emit_leading_comments(&t.trivia.leading);
1617 if let Some(doc) = &t.documentation {
1618 self.emit_doc(doc);
1619 }
1620 if t.private.is_some() {
1622 self.push("private ");
1623 }
1624 let params = if t.type_params.is_empty() {
1626 String::new()
1627 } else {
1628 let names: Vec<String> = t.type_params.iter().map(type_param_text).collect();
1629 format!("[{}]", names.join(", "))
1630 };
1631 self.push(&format!("type {}{} = ", t.name.name, params));
1632 self.format_type_body(&t.body);
1633 if !t.derives.is_empty() {
1634 let names: Vec<&str> = t.derives.iter().map(|d| d.name.as_str()).collect();
1635 let clause = format!("derives {}", names.join(" + "));
1636 if matches!(&t.body, TypeBody::Sum(s) if s.variants.iter().any(|v| !v.payload.is_empty()))
1639 {
1640 self.indented(|f| {
1641 f.newline();
1642 f.push(&clause);
1643 });
1644 } else {
1645 self.push(&format!(" {clause}"));
1646 }
1647 }
1648 self.emit_trailing_comment_or_newline(t.trivia.trailing.as_deref());
1649 }
1650
1651 fn format_type_body(&mut self, body: &TypeBody) {
1652 match body {
1653 TypeBody::Refined {
1654 base, refinement, ..
1655 } => {
1656 self.push(base.name());
1657 if let Some(r) = refinement {
1658 self.push(" where ");
1659 self.format_refinement(r);
1660 }
1661 }
1662 TypeBody::Opaque {
1663 base, refinement, ..
1664 } => {
1665 self.push("opaque ");
1666 self.push(base.name());
1667 if let Some(r) = refinement {
1668 self.push(" where ");
1669 self.format_refinement(r);
1670 }
1671 }
1672 TypeBody::Record(r) => self.format_record_body(r),
1673 TypeBody::Sum(s) => self.format_sum_body(s),
1674 }
1675 }
1676
1677 fn format_refinement(&mut self, r: &Refinement) {
1678 for (i, p) in r.predicates.iter().enumerate() {
1679 if i > 0 {
1680 self.push(" && ");
1681 }
1682 self.format_pred(p);
1683 }
1684 for ann in &r.annotations {
1686 self.push(" ");
1687 self.push(&annotation_to_string(ann));
1688 }
1689 }
1690
1691 fn format_pred(&mut self, p: &RefinementPred) {
1692 let arg = |n: i64| p.arg_text.clone().unwrap_or_else(|| n.to_string());
1693 match &p.kind {
1694 PredKind::Matches(re) => self.push(&format!(
1695 "Matches({})",
1696 literal_text(matches_argument_span(p), re)
1697 )),
1698 PredKind::InRange(a, b) => self.push(&format!("InRange({}, {})", a.lexeme, b.lexeme)),
1699 PredKind::InRangeF(a, b) => self.push(&format!("InRange({}, {})", a.lexeme, b.lexeme)),
1700 PredKind::InRangeD(a, b) => self.push(&format!("InRange({}, {})", a.lexeme, b.lexeme)),
1701 PredKind::MinLength(n) => self.push(&format!("MinLength({})", arg(*n))),
1702 PredKind::MaxLength(n) => self.push(&format!("MaxLength({})", arg(*n))),
1703 PredKind::Length(n) => self.push(&format!("Length({})", arg(*n))),
1704 PredKind::NonNegative => self.push("NonNegative"),
1705 PredKind::Positive => self.push("Positive"),
1706 PredKind::NonEmpty => self.push("NonEmpty"),
1707 PredKind::IsoDate => self.push("IsoDate"),
1708 PredKind::Cron => self.push("Cron"),
1709 }
1710 }
1711
1712 fn format_record_body(&mut self, r: &RecordBody) {
1713 let has_comments = !r.trailing_comments.is_empty()
1715 || r.fields.iter().any(|f| {
1716 !f.trivia.leading.is_empty()
1717 || f.trivia.trailing.is_some()
1718 || f.documentation.is_some()
1719 });
1720 if r.fields.is_empty() && !has_comments {
1721 self.push("{}");
1722 return;
1723 }
1724 self.push("{");
1726 self.newline();
1727 self.indented(|f| {
1728 for (i, field) in r.fields.iter().enumerate() {
1729 f.emit_leading_comments(&field.trivia.leading);
1730 if let Some(doc) = &field.documentation {
1731 f.emit_doc(doc);
1732 }
1733 f.format_record_field(field);
1734 if i + 1 < r.fields.len() || f.opts.trailing_comma {
1735 f.push(",");
1736 }
1737 f.emit_trailing_comment_or_newline(field.trivia.trailing.as_deref());
1738 }
1739 f.emit_trailing_comments(&r.trailing_comments);
1740 });
1741 self.push("}");
1742 }
1743
1744 fn format_record_field(&mut self, field: &RecordField) {
1745 for ann in &field.annotations {
1747 self.push(&format!("{} ", annotation_to_string(ann)));
1748 }
1749 self.push(&format!("{}: ", field.name.name));
1750 self.format_type_ref(&field.type_ref);
1751 if let Some(r) = &field.refinement {
1752 self.push(" where ");
1753 self.format_refinement(r);
1754 }
1755 if let Some(init) = &field.init {
1756 self.push(" = ");
1757 self.format_expr(init);
1758 }
1759 }
1760
1761 fn format_sum_body(&mut self, s: &SumBody) {
1762 let any_payload = s.variants.iter().any(|v| !v.payload.is_empty());
1766 if !any_payload {
1767 let has_comments = !s.trailing_comments.is_empty()
1770 || s.variants.iter().any(|v| {
1771 !v.trivia.leading.is_empty()
1772 || v.trivia.trailing.is_some()
1773 || v.documentation.is_some()
1774 });
1775 if !has_comments {
1776 let names: Vec<&str> = s.variants.iter().map(|v| v.name.name.as_str()).collect();
1777 let oneline = format!("enum {{ {} }}", names.join(", "));
1778 if self.fits(&oneline, 0) {
1779 self.push(&oneline);
1780 return;
1781 }
1782 }
1783 self.push("enum {");
1784 self.newline();
1785 self.indented(|f| {
1786 for (i, v) in s.variants.iter().enumerate() {
1787 f.emit_leading_comments(&v.trivia.leading);
1788 if let Some(doc) = &v.documentation {
1789 f.emit_doc(doc);
1790 }
1791 f.push(&v.name.name);
1792 if i + 1 < s.variants.len() || f.opts.trailing_comma {
1793 f.push(",");
1794 }
1795 f.emit_trailing_comment_or_newline(v.trivia.trailing.as_deref());
1796 }
1797 f.emit_trailing_comments(&s.trailing_comments);
1798 });
1799 self.push("}");
1800 return;
1801 }
1802 while self.out.ends_with(' ') {
1806 self.out.pop();
1807 }
1808 self.indented(|f| {
1809 for (i, v) in s.variants.iter().enumerate() {
1810 if i == 0 || s.variants[i - 1].trivia.trailing.is_none() {
1811 f.newline();
1812 }
1813 f.emit_leading_comments(&v.trivia.leading);
1814 if let Some(doc) = &v.documentation {
1815 f.emit_doc(doc);
1816 }
1817 f.push("| ");
1818 f.push(&v.name.name);
1819 if v.payload.iter().any(|p| p.documentation.is_some()) {
1820 f.push("(");
1823 f.newline();
1824 let last = v.payload.len() - 1;
1825 f.indented(|f| {
1826 for (j, p) in v.payload.iter().enumerate() {
1827 if let Some(doc) = &p.documentation {
1828 f.emit_doc(doc);
1829 }
1830 f.push(&format!(
1831 "{}: {}",
1832 p.name.name,
1833 type_ref_to_string(&p.type_ref)
1834 ));
1835 if j < last || f.opts.trailing_comma {
1836 f.push(",");
1837 }
1838 f.newline();
1839 }
1840 });
1841 f.push(")");
1842 } else if !v.payload.is_empty() {
1843 f.push("(");
1844 let parts: Vec<String> = v
1845 .payload
1846 .iter()
1847 .map(|p| format!("{}: {}", p.name.name, type_ref_to_string(&p.type_ref)))
1848 .collect();
1849 f.push(&parts.join(", "));
1850 f.push(")");
1851 }
1852 f.emit_trailing_comment(v.trivia.trailing.as_deref());
1853 }
1854 if !s.embeds.is_empty() {
1859 if s.variants
1860 .last()
1861 .is_none_or(|v| v.trivia.trailing.is_none())
1862 {
1863 f.newline();
1864 }
1865 f.emit_trailing_comments(&s.trailing_comments);
1866 let parts: Vec<String> = s
1867 .embeds
1868 .iter()
1869 .map(|e| {
1870 format!(
1871 "{} as {}",
1872 type_ref_to_string(&e.source_type),
1873 e.variant.name
1874 )
1875 })
1876 .collect();
1877 f.push(&format!("embeds {}", parts.join(", ")));
1878 }
1879 });
1880 }
1881
1882 fn format_type_ref(&mut self, t: &TypeRef) {
1883 self.push(&type_ref_to_string(t));
1884 }
1885
1886 fn format_fn_decl(&mut self, f: &FnDecl) {
1889 self.emit_leading_comments(&f.trivia.leading);
1890 if let Some(doc) = &f.documentation {
1891 self.emit_doc(doc);
1892 }
1893 if f.private.is_some() {
1895 self.push("private ");
1896 }
1897 self.push("fn ");
1898 self.push(&f.name.display());
1899 if !f.type_params.is_empty() {
1901 let names: Vec<String> = f.type_params.iter().map(type_param_text).collect();
1902 self.push(&format!("[{}]", names.join(", ")));
1903 }
1904 let given_text = if f.given.is_empty() {
1907 String::new()
1908 } else {
1909 let names: Vec<String> = f.given.iter().map(cap_ref_src).collect();
1910 format!(" given {}", names.join(", "))
1911 };
1912 let where_text = if f.where_bounds.is_empty() {
1914 String::new()
1915 } else {
1916 let entries: Vec<String> = f
1917 .where_bounds
1918 .iter()
1919 .map(|wb| format!("{}: {}", wb.param.name, bounds_text(&wb.bounds)))
1920 .collect();
1921 format!(" where {}", entries.join(", "))
1922 };
1923 let tail = format!(
1927 " -> {}{given_text}{where_text}",
1928 type_ref_to_string(&f.return_type)
1929 );
1930 let reserve = if f.requires.is_empty() && f.ensures.is_empty() {
1931 tail.chars().count() + " {".len()
1932 } else {
1933 tail.chars().count()
1934 };
1935 self.format_params(&f.params, f.has_self, reserve);
1936 self.push(" -> ");
1937 self.format_type_ref(&f.return_type);
1938 self.push(&given_text);
1939 self.push(&where_text);
1940 if f.requires.is_empty() && f.ensures.is_empty() {
1943 self.push(" ");
1944 } else {
1945 self.newline();
1946 self.indented(|f2| {
1947 for c in &f.requires {
1948 f2.push(&format!(
1949 "requires {}: {}",
1950 c.name.name,
1951 expr_to_string(&c.predicate)
1952 ));
1953 f2.newline();
1954 }
1955 for c in &f.ensures {
1956 f2.push(&format!(
1957 "ensures {}: {}",
1958 c.name.name,
1959 expr_to_string(&c.predicate)
1960 ));
1961 f2.newline();
1962 }
1963 });
1964 }
1965 self.format_block_multiline(&f.body);
1966 self.emit_trailing_comment_or_newline(f.trivia.trailing.as_deref());
1967 }
1968
1969 fn format_params(&mut self, params: &[Param], has_self: bool, reserve: usize) {
1974 let mut rendered: Vec<String> = Vec::new();
1975 if has_self {
1976 rendered.push("self".to_string());
1977 }
1978 for p in params {
1981 rendered.push(format!(
1982 "{}: {}",
1983 p.name.name,
1984 type_ref_to_string(&p.type_ref)
1985 ));
1986 }
1987 let oneline = format!("({})", rendered.join(", "));
1988 if rendered.is_empty() || self.fits(&oneline, reserve) {
1990 self.push(&oneline);
1991 return;
1992 }
1993 let closing_line = self.indent_level as usize * self.indent_width() + 1 + reserve;
1997 if closing_line > self.opts.max_line_width as usize {
1998 self.push(&oneline);
1999 return;
2000 }
2001 self.push("(");
2003 self.newline();
2004 self.indented(|f| {
2005 for (i, r) in rendered.iter().enumerate() {
2006 f.push(r);
2007 if i + 1 < rendered.len() {
2013 f.push(",");
2014 }
2015 f.newline();
2016 }
2017 });
2018 self.push(")");
2019 }
2020
2021 fn format_capability(&mut self, c: &CapabilityDecl) {
2024 self.emit_leading_comments(&c.trivia.leading);
2025 if let Some(doc) = &c.documentation {
2026 self.emit_doc(doc);
2027 }
2028 if let Some(d) = &c.derived {
2031 self.push(&format!("capability {} = {}", c.name.name, d.base.name));
2032 for ann in &d.annotations {
2033 self.push(&format!(" {}", annotation_to_string(ann)));
2034 }
2035 self.emit_trailing_comment_or_newline(c.trivia.trailing.as_deref());
2036 return;
2037 }
2038 self.push(&format!("capability {} {{", c.name.name));
2039 self.newline();
2040 self.indented(|f| {
2041 for op in &c.ops {
2042 f.emit_leading_comments(&op.trivia.leading);
2043 if let Some(doc) = &op.documentation {
2044 f.emit_doc(doc);
2045 }
2046 f.push("fn ");
2047 f.push(&op.name.name);
2048 if !op.type_params.is_empty() {
2050 let names: Vec<String> = op.type_params.iter().map(type_param_text).collect();
2051 f.push(&format!("[{}]", names.join(", ")));
2052 }
2053 let reserve = 4 + type_ref_to_string(&op.return_type).chars().count();
2054 f.format_params(&op.params, false, reserve);
2055 f.push(" -> ");
2056 f.format_type_ref(&op.return_type);
2057 for ann in &op.annotations {
2059 f.push(&format!(" {}", annotation_to_string(ann)));
2060 }
2061 f.emit_trailing_comment_or_newline(op.trivia.trailing.as_deref());
2062 }
2063 if !c.trailing_comments.is_empty() {
2065 if !c.ops.is_empty() {
2066 f.newline();
2067 }
2068 f.emit_trailing_comments(&c.trailing_comments);
2069 }
2070 });
2071 self.push("}");
2072 self.emit_trailing_comment_or_newline(c.trivia.trailing.as_deref());
2073 }
2074
2075 fn format_provider(&mut self, p: &ProviderDecl) {
2076 self.emit_leading_comments(&p.trivia.leading);
2077 if let Some(doc) = &p.documentation {
2078 self.emit_doc(doc);
2079 }
2080 self.push(&format!(
2081 "provides {} = {}",
2082 p.capability.name, p.provider_name.name
2083 ));
2084 if !p.given.is_empty() {
2085 self.push(" given ");
2086 let names: Vec<String> = p.given.iter().map(cap_ref_src).collect();
2087 self.push(&names.join(", "));
2088 }
2089 if p.external {
2091 self.emit_trailing_comment_or_newline(p.trivia.trailing.as_deref());
2092 return;
2093 }
2094 self.push(" {");
2095 self.newline();
2096 self.indented(|f| {
2097 for (i, op) in p.ops.iter().enumerate() {
2098 if i > 0 {
2099 f.newline();
2100 }
2101 f.emit_leading_comments(&op.trivia.leading);
2102 f.push("fn ");
2103 f.push(&op.name.name);
2104 let reserve = 4 + type_ref_to_string(&op.return_type).chars().count() + 2;
2105 f.format_params(&op.params, false, reserve);
2106 f.push(" -> ");
2107 f.format_type_ref(&op.return_type);
2108 f.push(" ");
2109 f.format_block_multiline(&op.body);
2110 f.emit_trailing_comment_or_newline(op.trivia.trailing.as_deref());
2111 }
2112 });
2113 self.push("}");
2114 self.emit_trailing_comment_or_newline(p.trivia.trailing.as_deref());
2115 }
2116
2117 fn format_service(&mut self, s: &ServiceDecl) {
2118 self.emit_leading_comments(&s.trivia.leading);
2119 if let Some(doc) = &s.documentation {
2120 self.emit_doc(doc);
2121 }
2122 let from = match &s.protocol {
2123 ServiceProtocol::Call => String::new(),
2124 ServiceProtocol::Http => " from http".to_string(),
2125 ServiceProtocol::Cron => " from cron".to_string(),
2126 ServiceProtocol::Queue { name } => {
2127 format!(" from queue(\"{}\")", escape_string(name))
2128 }
2129 ServiceProtocol::Email { address } => {
2130 format!(" from email(\"{}\")", escape_string(address))
2131 }
2132 ServiceProtocol::WebSocket { in_type, out_type } => {
2133 format!(
2134 " from websocket(in: {}, out: {})",
2135 type_ref_to_string(in_type),
2136 type_ref_to_string(out_type)
2137 )
2138 }
2139 ServiceProtocol::Events {
2140 event_type,
2141 pattern,
2142 schema_dispatch,
2143 } => {
2144 let header = match pattern {
2145 Some(p) => format!(
2146 " from Events({} {})",
2147 type_ref_to_string(event_type),
2148 event_pattern_src(p)
2149 ),
2150 None => format!(" from Events({})", type_ref_to_string(event_type)),
2151 };
2152 match schema_dispatch {
2153 Some(d) => format!("{header} {}", schema_dispatch_src(d)),
2154 None => header,
2155 }
2156 }
2157 };
2158 let mut header = format!("service {}{}", s.name.name, from);
2162 if let Some(by) = &s.default_by {
2163 header.push_str(&format!(" {}", by_clause_src(by)));
2164 }
2165 if !s.default_given.is_empty() {
2166 let names: Vec<String> = s.default_given.iter().map(cap_ref_src).collect();
2167 header.push_str(&format!(" given {}", names.join(", ")));
2168 }
2169 self.push(&format!("{header} {{"));
2170 self.newline();
2171 self.indented(|f| {
2172 if let Some(cors) = &s.cors {
2177 f.format_cors_policy(cors);
2178 if s.security.is_some()
2179 || s.limits.is_some()
2180 || s.json.is_some()
2181 || !s.handlers.is_empty()
2182 {
2183 f.newline();
2184 }
2185 }
2186 if let Some(security) = &s.security {
2187 f.format_security_policy(security);
2188 if s.limits.is_some() || s.json.is_some() || !s.handlers.is_empty() {
2189 f.newline();
2190 }
2191 }
2192 if let Some(limits) = &s.limits {
2193 f.format_limits_policy(limits);
2194 if s.json.is_some() || !s.handlers.is_empty() {
2195 f.newline();
2196 }
2197 }
2198 if let Some(json) = &s.json {
2199 f.format_json_policy(json);
2200 if !s.handlers.is_empty() {
2201 f.newline();
2202 }
2203 }
2204 for (i, h) in s.handlers.iter().enumerate() {
2205 if i > 0 {
2206 f.newline();
2207 }
2208 f.format_handler(h);
2209 }
2210 if !s.trailing_comments.is_empty() {
2212 if !s.handlers.is_empty()
2213 || s.cors.is_some()
2214 || s.security.is_some()
2215 || s.limits.is_some()
2216 || s.json.is_some()
2217 {
2218 f.newline();
2219 }
2220 f.emit_trailing_comments(&s.trailing_comments);
2221 }
2222 });
2223 self.push("}");
2224 self.emit_trailing_comment_or_newline(s.trivia.trailing.as_deref());
2225 }
2226
2227 fn format_cors_policy(&mut self, cors: &CorsPolicy) {
2230 let fields: Vec<_> = cors
2231 .fields
2232 .iter()
2233 .map(|f| (&f.name, &f.value, &f.trivia))
2234 .collect();
2235 self.format_policy("cors", &cors.trivia, &fields, &cors.trailing_comments);
2236 }
2237
2238 fn format_security_policy(&mut self, security: &SecurityPolicy) {
2240 let fields: Vec<_> = security
2241 .fields
2242 .iter()
2243 .map(|f| (&f.name, &f.value, &f.trivia))
2244 .collect();
2245 self.format_policy(
2246 "security",
2247 &security.trivia,
2248 &fields,
2249 &security.trailing_comments,
2250 );
2251 }
2252
2253 fn format_limits_policy(&mut self, limits: &LimitsPolicy) {
2257 let fields: Vec<_> = limits
2258 .fields
2259 .iter()
2260 .map(|f| (&f.name, &f.value, &f.trivia))
2261 .collect();
2262 self.format_policy("limits", &limits.trivia, &fields, &limits.trailing_comments);
2263 }
2264
2265 fn format_json_policy(&mut self, json: &JsonPolicy) {
2267 let fields: Vec<_> = json
2268 .fields
2269 .iter()
2270 .map(|f| (&f.name, &f.value, &f.trivia))
2271 .collect();
2272 self.format_policy("json", &json.trivia, &fields, &json.trailing_comments);
2273 }
2274
2275 fn format_policy(
2279 &mut self,
2280 keyword: &str,
2281 trivia: &Trivia,
2282 fields: &[(&Ident, &Expr, &Trivia)],
2283 trailing_comments: &[Comment],
2284 ) {
2285 self.emit_leading_comments(&trivia.leading);
2286 self.push(&format!("{keyword} {{"));
2287 self.newline();
2288 self.indented(|f| {
2289 for (name, value, field_trivia) in fields {
2290 f.emit_leading_comments(&field_trivia.leading);
2291 f.push(&format!("{}: ", name.name));
2292 f.format_expr_at(value, 0, 1);
2293 f.push(",");
2294 f.emit_trailing_comment_or_newline(field_trivia.trailing.as_deref());
2295 }
2296 f.emit_trailing_comments(trailing_comments);
2297 });
2298 self.push("}");
2299 self.emit_trailing_comment_or_newline(trivia.trailing.as_deref());
2300 }
2301
2302 fn format_agent(&mut self, a: &AgentDecl) {
2303 self.emit_leading_comments(&a.trivia.leading);
2304 if let Some(doc) = &a.documentation {
2305 self.emit_doc(doc);
2306 }
2307 match &a.replaces {
2308 Some(old) => self.push(&format!("agent {} replaces {} {{", a.name.name, old.name)),
2309 None => self.push(&format!("agent {} {{", a.name.name)),
2310 }
2311 self.newline();
2312 self.indented(|f| {
2313 f.emit_leading_comments(&a.key_trivia.leading);
2315 f.push(&format!(
2316 "key {}: {}",
2317 a.key_name.name,
2318 type_ref_to_string(&a.key_type)
2319 ));
2320 f.emit_trailing_comment_or_newline(a.key_trivia.trailing.as_deref());
2321 f.newline();
2322 for sf in &a.store_fields {
2324 f.format_store_field(sf);
2325 }
2326 for inv in &a.invariants {
2329 f.newline();
2330 f.format_invariant(inv);
2331 }
2332 for tr in &a.transitions {
2335 f.newline();
2336 f.format_transition(tr);
2337 }
2338 for m in &a.migrations {
2340 f.newline();
2341 f.format_migrate(m);
2342 }
2343 for h in &a.handlers {
2345 f.newline();
2346 f.format_handler(h);
2347 }
2348 if !a.trailing_comments.is_empty() {
2350 f.newline();
2351 f.emit_trailing_comments(&a.trailing_comments);
2352 }
2353 });
2354 self.push("}");
2355 self.emit_trailing_comment_or_newline(a.trivia.trailing.as_deref());
2356 }
2357
2358 fn format_store_field(&mut self, sf: &StoreField) {
2362 self.emit_leading_comments(&sf.trivia.leading);
2363 if let Some(doc) = &sf.documentation {
2364 self.emit_doc(doc);
2365 }
2366 self.push(&format!(
2367 "store {}: {}",
2368 sf.name.name,
2369 store_kind_to_string(&sf.kind)
2370 ));
2371 for ann in &sf.annotations {
2373 self.push(&format!(" {}", annotation_to_string(ann)));
2374 }
2375 if let Some(init) = &sf.init {
2376 self.push(" = ");
2377 self.format_expr(init);
2378 }
2379 self.emit_trailing_comment_or_newline(sf.trivia.trailing.as_deref());
2380 }
2381
2382 fn format_invariant(&mut self, inv: &Invariant) {
2385 self.emit_leading_comments(&inv.trivia.leading);
2386 if let Some(doc) = &inv.documentation {
2387 self.emit_doc(doc);
2388 }
2389 self.push(&format!("invariant {}:", inv.name.name));
2390 self.newline();
2391 self.indented(|f| {
2392 f.format_expr(&inv.predicate);
2393 });
2394 self.emit_trailing_comment_or_newline(inv.trivia.trailing.as_deref());
2395 }
2396
2397 fn format_transition(&mut self, tr: &Transition) {
2400 self.emit_leading_comments(&tr.trivia.leading);
2401 if let Some(doc) = &tr.documentation {
2402 self.emit_doc(doc);
2403 }
2404 self.push(&format!("transition {}:", tr.name.name));
2405 self.newline();
2406 self.indented(|f| {
2407 f.format_expr(&tr.predicate);
2408 });
2409 self.emit_trailing_comment_or_newline(tr.trivia.trailing.as_deref());
2410 }
2411
2412 fn format_migrate(&mut self, m: &MigrateDecl) {
2415 self.emit_leading_comments(&m.trivia.leading);
2416 if let Some(doc) = &m.documentation {
2417 self.emit_doc(doc);
2418 }
2419 self.push(&format!("migrate from {}", m.from));
2420 if let Some(old) = &m.old {
2421 self.push(&format!(
2422 " ({}: {})",
2423 old.name.name,
2424 type_ref_to_string(&old.type_ref)
2425 ));
2426 }
2427 self.push(" {");
2428 self.newline();
2429 self.indented(|f| {
2430 for item in &m.items {
2431 let trivia = match item {
2432 MigrateItem::Let(l) => &l.trivia,
2433 MigrateItem::Assign(a) => &a.trivia,
2434 MigrateItem::Drop(d) => &d.trivia,
2435 };
2436 f.emit_leading_comments(&trivia.leading);
2437 match item {
2438 MigrateItem::Let(l) => {
2439 f.push("let ");
2440 f.push(&l.name.name);
2441 if let Some(t) = &l.type_annot {
2442 f.push(": ");
2443 f.format_type_ref(t);
2444 }
2445 f.push(" = ");
2446 f.format_expr(&l.value);
2447 }
2448 MigrateItem::Assign(a) => {
2449 f.push(&a.target.name);
2450 f.push(" := ");
2451 f.format_expr(&a.value);
2452 }
2453 MigrateItem::Drop(d) => f.push(&format!("drop {}", d.field.name)),
2454 }
2455 f.emit_trailing_comment_or_newline(trivia.trailing.as_deref());
2456 }
2457 if !m.trailing_comments.is_empty() {
2458 f.emit_trailing_comments(&m.trailing_comments);
2459 }
2460 });
2461 self.push("}");
2462 self.emit_trailing_comment_or_newline(m.trivia.trailing.as_deref());
2463 }
2464
2465 fn format_actor(&mut self, a: &ActorDecl) {
2466 self.emit_leading_comments(&a.trivia.leading);
2467 if let Some(doc) = &a.documentation {
2468 self.emit_doc(doc);
2469 }
2470 if let Some(r) = &a.refinement {
2471 self.push(&format!(
2473 "actor {} = {} where {}",
2474 a.name.name,
2475 r.base.name,
2476 expr_to_string(&r.predicate)
2477 ));
2478 } else {
2479 let auth = a.auth.as_ref().map(|i| i.name.as_str()).unwrap_or("None");
2481 let args: Vec<String> = a
2482 .auth_config
2483 .iter()
2484 .map(|arg| match &arg.value {
2485 bynk_syntax::ast::SchemeArgValue::Str(s) => {
2486 format!("{} = \"{}\"", arg.key.name, escape_string(s))
2487 }
2488 bynk_syntax::ast::SchemeArgValue::Int(n) => {
2489 format!("{} = {n}", arg.key.name)
2490 }
2491 bynk_syntax::ast::SchemeArgValue::Duration { value, unit, .. } => {
2492 format!("{} = {value}.{}", arg.key.name, unit.name_for(*value))
2493 }
2494 bynk_syntax::ast::SchemeArgValue::Ident(id) => {
2495 format!("{} = {id}", arg.key.name)
2496 }
2497 })
2498 .collect();
2499 let config = if args.is_empty() {
2500 String::new()
2501 } else {
2502 format!("({})", args.join(", "))
2503 };
2504 let identity = a.identity.as_ref().map(type_ref_to_string);
2505 let oneline = format!(
2506 "actor {} {{ auth = {auth}{config}{} }}",
2507 a.name.name,
2508 identity
2509 .as_ref()
2510 .map(|id| format!(", identity = {id}"))
2511 .unwrap_or_default()
2512 );
2513 let break_args = !args.is_empty() && !self.fits(&oneline, 0);
2518 let has_comments = !a.trailing_comments.is_empty()
2520 || [&a.auth_trivia, &a.identity_trivia]
2521 .iter()
2522 .any(|t| !t.leading.is_empty() || t.trailing.is_some());
2523 if !break_args && !has_comments {
2524 self.push(&oneline);
2525 } else {
2526 self.push(&format!("actor {} {{", a.name.name));
2527 self.newline();
2528 self.indented(|f| {
2529 f.emit_leading_comments(&a.auth_trivia.leading);
2530 if break_args {
2531 f.push(&format!("auth = {auth}("));
2532 f.newline();
2533 f.indented(|f2| {
2534 for (i, arg) in args.iter().enumerate() {
2535 f2.push(arg);
2536 if i + 1 < args.len() {
2537 f2.push(",");
2538 }
2539 f2.newline();
2540 }
2541 });
2542 f.push(")");
2543 } else {
2544 f.push(&format!("auth = {auth}{config}"));
2545 }
2546 if let Some(id) = &identity {
2547 f.push(",");
2550 f.emit_trailing_comment_or_newline(a.auth_trivia.trailing.as_deref());
2551 f.emit_leading_comments(&a.identity_trivia.leading);
2552 f.push(&format!("identity = {id}"));
2553 f.emit_trailing_comment_or_newline(a.identity_trivia.trailing.as_deref());
2554 } else {
2555 f.emit_trailing_comment_or_newline(a.auth_trivia.trailing.as_deref());
2556 }
2557 f.emit_trailing_comments(&a.trailing_comments);
2558 });
2559 self.push("}");
2560 }
2561 }
2562 self.emit_trailing_comment_or_newline(a.trivia.trailing.as_deref());
2563 }
2564
2565 fn format_handler(&mut self, h: &Handler) {
2566 self.emit_leading_comments(&h.trivia.leading);
2567 if let Some(doc) = &h.documentation {
2568 self.emit_doc(doc);
2569 }
2570 for ann in &h.annotations {
2574 self.push(&annotation_to_string(ann));
2575 self.newline();
2576 }
2577 match &h.kind {
2580 HandlerKind::Call => {
2581 self.push("on call");
2582 if let Some(m) = &h.method_name {
2583 self.push(&format!(" {}", m.name));
2584 }
2585 }
2586 HandlerKind::Http { method, path } => {
2587 self.push(&format!(
2590 "on {}(\"{}\") ",
2591 method.as_str(),
2592 escape_string(path)
2593 ));
2594 }
2595 HandlerKind::Cron { expr } => {
2596 self.push(&format!("on schedule(\"{}\") ", escape_string(expr)));
2597 }
2598 HandlerKind::Message => {
2599 self.push("on message");
2600 }
2601 HandlerKind::Open => {
2602 self.push("on open");
2603 }
2604 HandlerKind::Close => {
2605 self.push("on close");
2606 }
2607 HandlerKind::Event => {
2608 self.push("on event");
2609 }
2610 HandlerKind::Rejected => {
2611 self.push("on rejected");
2612 }
2613 }
2614 let mut tail = format!(" -> {}", type_ref_to_string(&h.return_type));
2623 if let Some(by) = &h.by_clause {
2624 tail.push_str(&format!(" {}", by_clause_src(by)));
2625 }
2626 if !h.given.is_empty() {
2627 let names: Vec<String> = h.given.iter().map(cap_ref_src).collect();
2628 tail.push_str(&format!(" given {}", names.join(", ")));
2629 }
2630 self.format_params(&h.params, false, tail.chars().count() + " {".len());
2631 self.push(&tail);
2632 self.push(" ");
2633 self.format_block_multiline(&h.body);
2634 self.emit_trailing_comment_or_newline(h.trivia.trailing.as_deref());
2635 }
2636
2637 fn format_block(&mut self, b: &Block) {
2640 self.format_block_with_reserve(b, 0);
2641 }
2642
2643 fn format_block_with_reserve(&mut self, b: &Block, reserve: usize) {
2647 let tail_oneline = expr_to_string(&b.tail);
2650 let any_stmt_trivia = b.statements.iter().any(|s| !statement_trivia(s).is_empty());
2651 if b.statements.is_empty()
2652 && b.tail_leading_comments.is_empty()
2653 && !any_stmt_trivia
2654 && !holds_comments(&b.tail)
2655 && self.fits(&format!("{{ {tail_oneline} }}"), reserve)
2656 {
2657 self.push("{ ");
2658 self.push(&tail_oneline);
2659 self.push(" }");
2660 return;
2661 }
2662 self.format_block_multiline(b);
2663 }
2664
2665 fn format_block_multiline(&mut self, b: &Block) {
2670 if b.statements.is_empty() && b.tail_leading_comments.is_empty() && omit_unit_tail(b) {
2673 self.push("{}");
2674 return;
2675 }
2676 self.push("{");
2677 self.newline();
2678 self.indented(|f| f.format_block_body(b));
2679 self.push("}");
2680 }
2681
2682 fn format_block_body(&mut self, b: &Block) {
2688 for stmt in &b.statements {
2689 let trivia = statement_trivia(stmt);
2690 self.emit_leading_comments(&trivia.leading);
2691 if let Some((l, effectful, le)) = let_else_binding(stmt)
2692 && let ExprKind::Match { arms, .. } = &b.tail.kind
2693 && let Some(MatchBody::Block(rest)) = arms.first().map(|a| &a.body)
2694 {
2695 self.format_let_else(l, effectful, le, arms);
2696 self.emit_trailing_comment_or_newline(trivia.trailing.as_deref());
2697 self.format_block_body(rest);
2698 return;
2699 }
2700 self.format_statement(stmt);
2701 self.emit_trailing_comment_or_newline(trivia.trailing.as_deref());
2702 }
2703 self.emit_leading_comments(&b.tail_leading_comments);
2704 if !omit_unit_tail(b) {
2705 self.format_expr(&b.tail);
2706 self.newline();
2707 }
2708 }
2709
2710 fn format_let_else(&mut self, l: &LetStmt, effectful: bool, le: &LetElse, arms: &[MatchArm]) {
2714 self.push("let ");
2715 self.push(&let_pattern_src(&arms[0].pattern));
2716 self.push(if effectful { " <- " } else { " = " });
2717 let principal = l
2718 .principal
2719 .as_ref()
2720 .map(|p| format!(" {}", call_site_actor_src(p)));
2721 let else_width = if le.form == LetElseForm::Plain {
2722 0
2723 } else {
2724 " else {".len()
2725 };
2726 let reserve = principal.as_deref().map_or(0, |p| p.chars().count()) + else_width;
2727 self.format_expr_at(&l.value, 0, reserve);
2728 if let Some(principal) = principal {
2729 self.push(&principal);
2730 }
2731 if le.form == LetElseForm::Plain {
2733 return;
2734 }
2735 self.push(" else ");
2736 match (le.form, arms.get(1).map(|a| &a.body)) {
2737 (LetElseForm::Block, Some(MatchBody::Block(otherwise))) => self.format_block(otherwise),
2738 _ => {
2739 self.push("match {");
2740 self.newline();
2741 self.indented(|f| f.format_arms(&arms[1..]));
2742 self.push("}");
2743 }
2744 }
2745 }
2746
2747 fn format_statement(&mut self, s: &Statement) {
2748 match s {
2749 Statement::Let(l) => {
2750 self.push("let ");
2751 self.push(&l.name.name);
2752 if let Some(t) = &l.type_annot {
2753 self.push(": ");
2754 self.format_type_ref(t);
2755 }
2756 self.push(" = ");
2757 self.format_expr(&l.value);
2758 }
2759 Statement::EffectLet(l) => {
2760 self.push("let ");
2761 self.push(&l.name.name);
2762 if let Some(t) = &l.type_annot {
2763 self.push(": ");
2764 self.format_type_ref(t);
2765 }
2766 self.push(" <- ");
2767 let principal = l
2769 .principal
2770 .as_ref()
2771 .map(|p| format!(" {}", call_site_actor_src(p)));
2772 let reserve = principal.as_deref().map_or(0, |p| p.chars().count());
2773 self.format_expr_at(&l.value, 0, reserve);
2774 if let Some(principal) = principal {
2775 self.push(&principal);
2776 }
2777 }
2778 Statement::Expect(a) => {
2779 self.push("expect ");
2780 self.format_expr(&a.value);
2781 if let Some(snapshot) = &a.snapshot {
2782 self.push(&format!(
2783 " matches snapshot \"{}\"",
2784 escape_string(&snapshot.name)
2785 ));
2786 }
2787 }
2788 Statement::Do(d) => {
2789 self.push("do ");
2790 self.format_expr(&d.value);
2791 }
2792 Statement::Assign(a) => {
2793 self.push(&a.target.name);
2794 self.push(" := ");
2795 self.format_expr(&a.value);
2796 }
2797 Statement::Advance(a) => {
2798 self.push(&format!("advance {} by ", a.cap.name));
2799 self.format_expr(&a.amount);
2800 }
2801 Statement::Par(p) => {
2802 self.push("par {");
2803 self.newline();
2804 self.indented(|f| {
2805 for stmt in &p.statements {
2806 let trivia = statement_trivia(stmt);
2807 f.emit_leading_comments(&trivia.leading);
2808 f.format_statement(stmt);
2809 f.emit_trailing_comment_or_newline(trivia.trailing.as_deref());
2810 }
2811 f.emit_leading_comments(&p.closing_comments);
2812 });
2813 self.push("}");
2814 }
2815 }
2816 }
2817
2818 fn format_expr(&mut self, e: &Expr) {
2819 self.format_expr_at(e, 0, 0);
2820 }
2821
2822 fn format_expr_at(&mut self, e: &Expr, parent_prec: u8, reserve: usize) {
2835 if let ExprKind::Match { discriminant, arms } = &e.kind {
2841 self.format_match(discriminant, arms);
2842 return;
2843 }
2844 let flat = expr_with_prec(e, parent_prec);
2845 let braced_record = match &e.kind {
2849 ExprKind::RecordConstruction { fields, .. } => fields.len() > 1,
2850 ExprKind::RecordSpread { overrides, .. } => !overrides.is_empty(),
2851 _ => false,
2852 };
2853 if !braced_record && !holds_comments(e) && self.fits(&flat, reserve) {
2855 self.push(&flat);
2856 return;
2857 }
2858 if needs_parens(e, parent_prec) {
2861 self.push("(");
2862 self.format_expr_broken(e, reserve + 1);
2863 self.push(")");
2864 } else {
2865 self.format_expr_broken(e, reserve);
2866 }
2867 }
2868
2869 fn format_expr_broken(&mut self, e: &Expr, reserve: usize) {
2874 match &e.kind {
2875 ExprKind::RecordConstruction {
2877 type_name,
2878 fields,
2879 trivia,
2880 } if !fields.is_empty() || trivia.is_some() => {
2881 self.push(&format!("{} {{", type_name.name));
2882 self.format_field_inits(fields.iter(), None, trivia.as_deref());
2883 }
2884 ExprKind::RecordSpread {
2887 type_name,
2888 base,
2889 overrides,
2890 trivia,
2891 } => {
2892 match type_name {
2893 Some(tn) => self.push(&format!("{} {{", tn.name)),
2894 None => self.push("{"),
2895 }
2896 let spread = format!("...{}", expr_with_prec(base, 0));
2897 self.format_field_inits(overrides.iter(), Some(&spread), trivia.as_deref());
2898 }
2899 ExprKind::Call {
2903 name,
2904 type_args,
2905 args,
2906 trivia,
2907 } if !args.is_empty() || trivia.is_some() => {
2908 self.push(&format!("{}{}(", name.name, type_args_src(type_args)));
2909 self.format_arg_list(args, trivia.as_deref(), reserve);
2910 }
2911 ExprKind::Val {
2912 type_ref,
2913 args,
2914 trivia,
2915 } if !args.is_empty() || trivia.is_some() => {
2916 self.push(&format!("Val[{}](", type_ref_to_string(type_ref)));
2917 self.format_arg_list(args, trivia.as_deref(), reserve);
2918 }
2919 ExprKind::MethodCall { .. } | ExprKind::FieldAccess { .. } => {
2923 self.format_chain(e, reserve);
2924 }
2925 ExprKind::ListLit(elems, trivia) if !elems.is_empty() || trivia.is_some() => {
2929 self.push("[");
2930 self.newline();
2931 self.indented(|f| {
2932 for (i, elem) in elems.iter().enumerate() {
2933 let last = i + 1 == elems.len();
2934 let item = trivia.as_ref().and_then(|t| t.items.get(i));
2935 if let Some(item) = item {
2936 f.emit_leading_comments(&item.leading);
2937 }
2938 f.format_expr_at(elem, 0, if last { 0 } else { 1 });
2941 if !last || f.opts.trailing_comma {
2942 f.push(",");
2943 }
2944 let eol = item.and_then(|t| t.trailing.as_deref());
2945 f.emit_trailing_comment_or_newline(eol);
2946 }
2947 if let Some(t) = trivia {
2948 f.emit_trailing_comments(&t.closing);
2949 }
2950 });
2951 self.push("]");
2952 }
2953 ExprKind::BinOp(op, ..) if is_logical(*op) => {
2958 let prec = binop_prec(*op);
2959 let mut operands = Vec::new();
2960 flatten_binop(e, *op, &mut operands);
2961 self.format_expr_at(operands[0], prec, 0);
2962 self.indented(|f| {
2963 for (i, operand) in operands.iter().enumerate().skip(1) {
2964 f.newline();
2965 f.push(&format!("{} ", op.name()));
2966 let last = i + 1 == operands.len();
2967 f.format_expr_at(operand, prec + 1, if last { reserve } else { 0 });
2968 }
2969 });
2970 }
2971 ExprKind::BinOp(op, lhs, rhs) => {
2974 let prec = binop_prec(*op);
2975 let tail = format!(" {} {}", op.name(), expr_with_prec(rhs, prec + 1));
2976 let lhs_reserve = if tail.contains('\n') || holds_comments(rhs) {
2979 0
2980 } else {
2981 tail.chars().count() + reserve
2982 };
2983 self.format_expr_at(lhs, prec, lhs_reserve);
2984 self.push(&format!(" {} ", op.name()));
2985 self.format_expr_at(rhs, prec + 1, reserve);
2986 }
2987 ExprKind::Is { value, pattern } => {
2988 let pat = format!(" is {}", is_pattern_src(pattern));
2989 self.format_expr_at(value, 4, pat.chars().count() + reserve);
2990 self.push(&pat);
2991 }
2992 ExprKind::If {
2996 cond,
2997 then_block,
2998 else_block,
2999 } => {
3000 self.push("if ");
3001 self.format_expr_at(cond, 0, 2);
3002 self.push(" ");
3003 self.format_block_multiline(then_block);
3004 if let Some(chained) = else_if_tail(else_block) {
3007 self.push(" else ");
3009 self.format_expr_at(chained, 0, 0);
3010 } else if !else_block.is_synth_unit() {
3011 self.push(" else ");
3012 self.format_block_multiline(else_block);
3013 }
3014 }
3015 ExprKind::Block(b) => self.format_block_multiline(b),
3016 ExprKind::Lambda(lambda) => {
3017 let params: Vec<String> = lambda.params.iter().map(lambda_param_src).collect();
3018 self.push(&format!("({}) => ", params.join(", ")));
3019 match lambda_body_src(lambda) {
3020 LambdaBodySrc::Expr(body) => self.format_expr_at(body, 0, reserve),
3021 LambdaBodySrc::Block(block) => self.format_block_multiline(block),
3022 }
3023 }
3024 ExprKind::Ok(v) => self.wrap_call("Ok(", v, reserve),
3027 ExprKind::Err(v) => self.wrap_call("Err(", v, reserve),
3028 ExprKind::Some(v) => self.wrap_call("Some(", v, reserve),
3029 ExprKind::EffectPure(v) => self.wrap_call("Effect.pure(", v, reserve),
3030 ExprKind::Wire(v) => self.wrap_call("Wire(", v, reserve),
3031 ExprKind::Paren(v) => self.wrap_call("(", v, reserve),
3032 ExprKind::Question(v) => {
3033 self.format_expr_at(v, 8, reserve + 1);
3034 self.push("?");
3035 }
3036 ExprKind::Expect(v) => {
3037 self.push("expect ");
3038 self.format_expr_at(v, 0, reserve);
3039 }
3040 _ => self.push(&expr_with_prec(e, 0)),
3043 }
3044 }
3045
3046 fn wrap_call(&mut self, head: &str, inner: &Expr, reserve: usize) {
3048 self.push(head);
3049 self.format_expr_at(inner, 0, reserve + 1);
3050 self.push(")");
3051 }
3052
3053 fn format_field_inits<'f, I>(
3058 &mut self,
3059 fields: I,
3060 spread: Option<&str>,
3061 trivia: Option<&ListTrivia>,
3062 ) where
3063 I: ExactSizeIterator<Item = &'f FieldInit>,
3064 {
3065 let total = fields.len() + usize::from(spread.is_some());
3066 self.newline();
3067 self.indented(|f| {
3068 let mut emitted = 0usize;
3069 let slot = |f: &mut Self, emitted: usize| {
3071 let item = trivia.and_then(|t| t.items.get(emitted));
3072 if let Some(item) = item {
3073 f.emit_leading_comments(&item.leading);
3074 }
3075 item.and_then(|t| t.trailing.clone())
3076 };
3077 if let Some(spread) = spread {
3078 let eol = slot(f, emitted);
3079 f.push(spread);
3080 emitted += 1;
3081 if emitted < total || f.opts.trailing_comma {
3082 f.push(",");
3083 }
3084 f.emit_trailing_comment_or_newline(eol.as_deref());
3085 }
3086 for field in fields {
3087 let eol = slot(f, emitted);
3088 f.push(&field.name.name);
3089 if let Some(v) = &field.value {
3090 f.push(": ");
3091 f.format_expr_at(v, 0, 1);
3092 }
3093 emitted += 1;
3094 if emitted < total || f.opts.trailing_comma {
3095 f.push(",");
3096 }
3097 f.emit_trailing_comment_or_newline(eol.as_deref());
3098 }
3099 if let Some(t) = trivia {
3100 f.emit_trailing_comments(&t.closing);
3101 }
3102 });
3103 self.push("}");
3104 }
3105
3106 fn format_arg_list(
3121 &mut self,
3122 args: &[Expr],
3123 trivia: Option<&ListTrivia>,
3124 reserve: usize,
3125 ) -> bool {
3126 if trivia.is_none()
3128 && let Some((last, leading)) = args.split_last()
3129 && (leading.is_empty() || is_block_like(last))
3130 && !leading.iter().any(holds_comments)
3131 && self.try_layout(reserve, |f| {
3132 for arg in leading {
3133 f.push(&expr_with_prec(arg, 0));
3134 f.push(", ");
3135 }
3136 f.format_expr_at(last, 0, 1);
3137 f.push(")");
3138 })
3139 {
3140 return false;
3141 }
3142 self.newline();
3143 self.indented(|f| {
3144 for (i, arg) in args.iter().enumerate() {
3145 let last = i + 1 == args.len();
3146 let item = trivia.and_then(|t| t.items.get(i));
3147 if let Some(item) = item {
3148 f.emit_leading_comments(&item.leading);
3149 }
3150 f.format_expr_at(arg, 0, if last { 0 } else { 1 });
3153 if !last {
3154 f.push(",");
3155 }
3156 f.emit_trailing_comment_or_newline(item.and_then(|t| t.trailing.as_deref()));
3157 }
3158 if let Some(t) = trivia {
3159 f.emit_trailing_comments(&t.closing);
3160 }
3161 });
3162 self.push(")");
3163 true
3164 }
3165
3166 fn format_chain(&mut self, e: &Expr, reserve: usize) {
3173 let (base, links) = flatten_chain(e);
3174 let calls = links
3175 .iter()
3176 .filter(|l| matches!(l, ChainLink::Method { .. }))
3177 .count();
3178 if calls < 2 {
3179 self.format_chain_inline(base, &links, reserve);
3180 return;
3181 }
3182 let exploded = std::cell::Cell::new(false);
3190 if self.try_layout_if(
3191 reserve,
3192 |f| exploded.set(f.format_chain_inline(base, &links, reserve)),
3193 || !exploded.get(),
3194 ) {
3195 return;
3196 }
3197 let first_call = links
3202 .iter()
3203 .position(|l| matches!(l, ChainLink::Method { .. }))
3204 .expect("a chain with two calls has one");
3205 self.format_expr_at(base, 8, 0);
3206 for link in &links[..first_call] {
3207 self.format_chain_link(link, 0);
3208 }
3209 self.indented(|f| {
3210 let mut i = first_call;
3211 while i < links.len() {
3212 let mut end = i;
3213 while end < links.len() && matches!(links[end], ChainLink::Field(_)) {
3214 end += 1;
3215 }
3216 if end < links.len() {
3218 end += 1;
3219 }
3220 f.newline();
3221 for (offset, link) in links[i..end].iter().enumerate() {
3222 let is_last = end == links.len() && i + offset + 1 == links.len();
3223 f.format_chain_link(link, if is_last { reserve } else { 0 });
3224 }
3225 i = end;
3226 }
3227 });
3228 }
3229
3230 fn format_chain_inline(
3236 &mut self,
3237 base: &Expr,
3238 links: &[ChainLink<'_>],
3239 reserve: usize,
3240 ) -> bool {
3241 self.format_expr_at(base, 8, 0);
3242 let mut exploded = false;
3243 for (i, link) in links.iter().enumerate() {
3244 exploded |=
3245 self.format_chain_link(link, if i + 1 == links.len() { reserve } else { 0 });
3246 }
3247 exploded
3248 }
3249
3250 fn format_chain_link(&mut self, link: &ChainLink<'_>, reserve: usize) -> bool {
3254 match link {
3255 ChainLink::Field(name) => {
3256 self.push(&format!(".{name}"));
3257 false
3258 }
3259 ChainLink::Method {
3260 method,
3261 type_args,
3262 args,
3263 trivia,
3264 } => {
3265 let head = format!(".{}{}", method, type_args_src(type_args));
3266 let flat = format!(
3267 "{head}({})",
3268 args.iter()
3269 .map(|a| expr_with_prec(a, 0))
3270 .collect::<Vec<_>>()
3271 .join(", ")
3272 );
3273 if (args.is_empty() && trivia.is_none())
3274 || (trivia.is_none()
3275 && !args.iter().any(holds_comments)
3276 && self.fits(&flat, reserve))
3277 {
3278 self.push(&flat);
3279 return false;
3280 }
3281 self.push(&head);
3282 self.push("(");
3283 self.format_arg_list(args, *trivia, reserve)
3284 }
3285 }
3286 }
3287
3288 fn format_match(&mut self, discriminant: &Expr, arms: &[MatchArm]) {
3292 self.push("match ");
3293 self.format_expr_at(discriminant, 0, " {".len());
3294 self.push(" {");
3295 self.newline();
3296 self.indented(|f| f.format_arms(arms));
3297 self.push("}");
3298 }
3299
3300 fn format_arms(&mut self, arms: &[MatchArm]) {
3302 for arm in arms {
3303 self.push(&pattern_to_string(&arm.pattern));
3304 if let Some(guard) = &arm.guard {
3306 self.push(" if ");
3307 self.format_expr_at(guard, 0, " => ".len());
3308 }
3309 self.push(" => ");
3310 match &arm.body {
3312 MatchBody::Expr(e) => self.format_expr_at(e, 0, 1),
3313 MatchBody::Block(b) => self.format_block_with_reserve(b, 1),
3314 }
3315 self.push(",");
3316 self.newline();
3317 }
3318 }
3319}
3320
3321enum ChainLink<'e> {
3323 Field(&'e str),
3324 Method {
3325 method: &'e str,
3326 type_args: &'e [TypeRef],
3327 args: &'e [Expr],
3328 trivia: Option<&'e ListTrivia>,
3329 },
3330}
3331
3332fn flatten_chain(e: &Expr) -> (&Expr, Vec<ChainLink<'_>>) {
3336 let mut links = Vec::new();
3337 let mut cur = e;
3338 loop {
3339 match &cur.kind {
3340 ExprKind::FieldAccess { receiver, field } => {
3341 links.push(ChainLink::Field(field.name.as_str()));
3342 cur = receiver;
3343 }
3344 ExprKind::MethodCall {
3345 receiver,
3346 method,
3347 type_args,
3348 args,
3349 trivia,
3350 } => {
3351 links.push(ChainLink::Method {
3352 method: method.name.as_str(),
3353 type_args,
3354 args,
3355 trivia: trivia.as_deref(),
3356 });
3357 cur = receiver;
3358 }
3359 _ => break,
3360 }
3361 }
3362 links.reverse();
3363 (cur, links)
3364}
3365
3366fn type_args_src(type_args: &[TypeRef]) -> String {
3368 if type_args.is_empty() {
3369 return String::new();
3370 }
3371 format!(
3372 "[{}]",
3373 type_args
3374 .iter()
3375 .map(type_ref_to_string)
3376 .collect::<Vec<_>>()
3377 .join(", ")
3378 )
3379}
3380
3381fn is_logical(op: BinOp) -> bool {
3385 matches!(op, BinOp::And | BinOp::Or | BinOp::Implies)
3386}
3387
3388fn flatten_binop<'e>(e: &'e Expr, op: BinOp, out: &mut Vec<&'e Expr>) {
3391 if let ExprKind::BinOp(inner_op, lhs, rhs) = &e.kind
3392 && *inner_op == op
3393 {
3394 flatten_binop(lhs, op, out);
3395 out.push(rhs);
3396 return;
3397 }
3398 out.push(e);
3399}
3400
3401fn is_block_like(e: &Expr) -> bool {
3407 matches!(
3408 e.kind,
3409 ExprKind::Lambda(_)
3410 | ExprKind::Block(_)
3411 | ExprKind::RecordConstruction { .. }
3412 | ExprKind::RecordSpread { .. }
3413 | ExprKind::Match { .. }
3414 | ExprKind::If { .. }
3415 )
3416}
3417
3418fn needs_parens(e: &Expr, parent_prec: u8) -> bool {
3422 match &e.kind {
3423 ExprKind::BinOp(op, ..) => binop_prec(*op) < parent_prec,
3424 ExprKind::UnaryOp(..) => parent_prec > 7,
3425 _ => false,
3426 }
3427}
3428
3429fn cap_ref_src(c: &CapRef) -> String {
3433 match &c.context {
3434 Some(prefix) => format!("{}.{}", prefix.joined(), c.name.name),
3435 None => c.name.name.clone(),
3436 }
3437}
3438
3439fn by_clause_src(by: &ByClause) -> String {
3443 let actors = by
3444 .actors
3445 .iter()
3446 .map(|a| a.name.as_str())
3447 .collect::<Vec<_>>()
3448 .join(" | ");
3449 match &by.binder {
3450 Some(b) => format!("by {}: {actors}", b.name),
3451 None => format!("by {actors}"),
3452 }
3453}
3454
3455fn event_pattern_src(p: &EventPattern) -> String {
3461 let fields: Vec<String> = p
3462 .fields
3463 .iter()
3464 .map(|f| format!("{}: {}", f.name.name, event_pattern_value_src(&f.value)))
3465 .collect();
3466 format!("{{ {}, .. }}", fields.join(", "))
3467}
3468
3469fn event_pattern_value_src(v: &EventPatternValue) -> String {
3470 match v {
3471 EventPatternValue::Literal { value, text, .. } => match value {
3472 LiteralValue::Int(n) => text.clone().unwrap_or_else(|| n.to_string()),
3473 LiteralValue::Str(s) => format!("\"{}\"", escape_string(s)),
3474 LiteralValue::Bool(b) => b.to_string(),
3475 },
3476 EventPatternValue::Variant {
3477 type_name, variant, ..
3478 } => match type_name {
3479 Some(t) => format!("{}.{}", t.name, variant.name),
3480 None => variant.name.clone(),
3481 },
3482 }
3483}
3484
3485fn schema_dispatch_src(d: &SchemaDispatch) -> String {
3488 match &d.pattern {
3489 SchemaVersionPattern::Literal(n) => format!("via schema({n})"),
3490 SchemaVersionPattern::Range(r) => format!("via schema({})", r.describe_source()),
3491 SchemaVersionPattern::Wildcard => "via schema(_)".to_string(),
3492 }
3493}
3494
3495fn store_kind_to_string(k: &StoreKind) -> String {
3497 if k.args.is_empty() {
3498 k.head.name.clone()
3499 } else {
3500 format!(
3501 "{}[{}]",
3502 k.head.name,
3503 k.args
3504 .iter()
3505 .map(type_ref_to_string)
3506 .collect::<Vec<_>>()
3507 .join(", ")
3508 )
3509 }
3510}
3511
3512pub fn annotation_to_string(ann: &Annotation) -> String {
3519 if ann.args.is_empty() {
3520 return format!("@{}", ann.name.name);
3521 }
3522 let args = ann
3523 .args
3524 .iter()
3525 .map(|a| match &a.label {
3526 Some(l) => format!("{}: {}", l.name, expr_with_prec(&a.value, 0)),
3527 None => expr_with_prec(&a.value, 0),
3528 })
3529 .collect::<Vec<_>>()
3530 .join(", ");
3531 format!("@{}({})", ann.name.name, args)
3532}
3533
3534fn stub_clause_to_string(pv: &StubClause) -> String {
3537 let args = pv
3538 .args
3539 .iter()
3540 .map(|a| match a {
3541 ArgPattern::Any(_) => "_".to_string(),
3542 ArgPattern::Value(e) => expr_to_string(e),
3543 })
3544 .collect::<Vec<_>>()
3545 .join(", ");
3546 let rhs = match &pv.rhs {
3547 StubRhs::Returns(e) => match &pv.after {
3548 Some(d) => format!("returns {} after {}", expr_to_string(e), expr_to_string(d)),
3549 None => format!("returns {}", expr_to_string(e)),
3550 },
3551 StubRhs::Fails(_) => "fails".to_string(),
3552 StubRhs::Never(_) => "never".to_string(),
3553 StubRhs::ReturnsEach(outcomes, _) => {
3554 let items = outcomes
3555 .iter()
3556 .map(|o| match o {
3557 SeqOutcome::Value(e) => expr_to_string(e),
3558 SeqOutcome::Fails(_) => "fails".to_string(),
3559 })
3560 .collect::<Vec<_>>()
3561 .join(", ");
3562 format!("returns each [{items}]")
3563 }
3564 };
3565 format!(
3566 "stub {}.{}({}) {}",
3567 pv.capability.name, pv.method.name, args, rhs
3568 )
3569}
3570
3571fn statement_trivia(s: &Statement) -> &Trivia {
3572 match s {
3573 Statement::Let(l) | Statement::EffectLet(l) => &l.trivia,
3574 Statement::Expect(a) => &a.trivia,
3575 Statement::Do(d) => &d.trivia,
3576 Statement::Assign(a) => &a.trivia,
3577 Statement::Advance(a) => &a.trivia,
3578 Statement::Par(p) => &p.trivia,
3579 }
3580}
3581
3582fn display_width(line: &str, tab: usize) -> usize {
3589 let mut col = 0usize;
3590 for ch in line.chars() {
3591 if ch == '\t' {
3592 col += tab - (col % tab);
3593 } else {
3594 col += 1;
3595 }
3596 }
3597 col
3598}
3599
3600fn type_param_text(tp: &TypeParam) -> String {
3602 if tp.bounds.is_empty() {
3603 tp.name.name.clone()
3604 } else {
3605 format!("{}: {}", tp.name.name, bounds_text(&tp.bounds))
3606 }
3607}
3608
3609fn bounds_text(bounds: &[Ident]) -> String {
3610 bounds
3611 .iter()
3612 .map(|b| b.name.as_str())
3613 .collect::<Vec<_>>()
3614 .join(" + ")
3615}
3616
3617fn holds_comments(e: &Expr) -> bool {
3621 matches!(
3622 &e.kind,
3623 ExprKind::ListLit(_, Some(_))
3624 | ExprKind::Call {
3625 trivia: Some(_),
3626 ..
3627 }
3628 | ExprKind::MethodCall {
3629 trivia: Some(_),
3630 ..
3631 }
3632 | ExprKind::Val {
3633 trivia: Some(_),
3634 ..
3635 }
3636 | ExprKind::RecordConstruction {
3637 trivia: Some(_),
3638 ..
3639 }
3640 | ExprKind::RecordSpread {
3641 trivia: Some(_),
3642 ..
3643 }
3644 ) || bynk_syntax::ast::expr_children(e)
3645 .into_iter()
3646 .any(holds_comments)
3647}
3648
3649#[cfg(test)]
3650mod tests {
3651 use super::*;
3652
3653 #[test]
3656 fn bounds_and_where_clauses_round_trip() {
3657 let src = "commons m\n\ntype Pair[T: Eq] = {\n\tleft: T,\n}\n\nfn same[T: Eq + Ord, U](a: T, b: T, u: U) -> Bool {\n\ta == b\n}\n\nfn Pair.has(self, x: T) -> Bool where T: Eq, T: Ord {\n\tself.left == x\n}\n\nfn Pair.has2(self, x: T) -> Bool where T: Eq\n\trequires p: true\n{\n\tself.left == x\n}\n";
3658 let out = format_source(src, &FormatOptions::default()).unwrap();
3659 assert_eq!(out, src);
3660 }
3661
3662 #[test]
3665 fn par_block_round_trips() {
3666 let src = "commons x\n\nfn f(id: Int) -> Effect[Int] {\n\t// load both\n\tpar {\n\t\t// the user\n\t\tlet user <- Users.get(id) // trailing\n\t\tlet orders: Int <- Orders.forUser(id)\n\t\tdo Audit.touch(id)\n\t\t// last word\n\t}\n\tEffect.pure(user + orders)\n}\n";
3667 let out = format_source(src, &FormatOptions::default()).unwrap();
3668 assert_eq!(out, src);
3669 assert_eq!(format_source(&out, &FormatOptions::default()).unwrap(), out);
3670 }
3671
3672 #[test]
3673 fn par_block_is_reindented_and_split_onto_lines() {
3674 let messy = "commons x\n\nfn f(id: Int) -> Effect[Int] {\n if id > 0 { par { let a <- A.get(id) let b <- B.get(id) }\n Effect.pure(a + b) } else { Effect.pure(0) }\n}\n";
3675 let out = format_source(messy, &FormatOptions::default()).unwrap();
3676 assert!(
3677 out.contains("\t\tpar {\n\t\t\tlet a <- A.get(id)\n\t\t\tlet b <- B.get(id)\n\t\t}\n"),
3678 "{out}"
3679 );
3680 assert_eq!(format_source(&out, &FormatOptions::default()).unwrap(), out);
3681 }
3682
3683 #[test]
3686 fn binding_includes_round_trips() {
3687 let src = "adapter x {\n\tbinding \"./x.ts\" includes [\"./a.wasm\", \"b.wasm\"] requires { \"p\": \"^1\" }\n}\n";
3688 let out = format_source(src, &FormatOptions::default()).unwrap();
3689 assert_eq!(out, src);
3690 }
3691
3692 #[test]
3696 fn doc_fence_outgrows_the_marker_lines_it_holds() {
3697 let held = "commons m\n\n-------\nAbove.\n---\nInner.\n-----\nBelow.\n-------\nfn f() -> Int { 1 }\n";
3698 let out = format_source(held, &FormatOptions::default()).unwrap();
3699 assert_eq!(
3700 out,
3701 "commons m\n\n------\nAbove.\n---\nInner.\n-----\nBelow.\n------\nfn f() -> Int {\n\t1\n}\n"
3702 );
3703 assert_eq!(format_source(&out, &FormatOptions::default()).unwrap(), out);
3704 let plain = "commons m\n\n-----\nJust prose.\n-----\nfn f() -> Int { 1 }\n";
3705 assert_eq!(
3706 format_source(plain, &FormatOptions::default()).unwrap(),
3707 "commons m\n\n---\nJust prose.\n---\nfn f() -> Int {\n\t1\n}\n"
3708 );
3709 assert_eq!(doc_fence_len("a\n --- \nb"), 4);
3710 assert_eq!(doc_fence_len("a\n--\n- - -"), 3);
3711 }
3712
3713 #[test]
3717 fn each_doc_form_round_trips_unchanged() {
3718 let src = "commons m\n\n--- A commit SHA.\ntype Commit = String\n\n---\nOne line, fenced.\n---\ntype Id = Int\n\ntype Point = {\n\t--- Across.\n\tx: Int,\n}\n\n--- One line.\ntype Run = {\n\t--- The repository.\n\trepo: String,\n\t---\n\tThe version.\n\t---\n\tversion: String,\n\t// a note\n\tsha: String, // trailing\n}\n\ntype Outcome = enum {\n\t--- Passed.\n\tPass,\n\t---\n\tFailed.\n\t---\n\tFail,\n}\n\ntype Shape =\n\t--- Round.\n\t| Circle(\n\t\t--- The radius.\n\t\tr: Int,\n\t\td: Int,\n\t)\n\t--- A dot.\n\t| Dot\n\nmessages \"en\" @reference {\n\t--- Greets.\n\t\"hi\" => \"Hello\"\n}\n";
3719 let out = format_source(src, &FormatOptions::default()).unwrap();
3720 assert_eq!(out, src);
3721 for (written, printed) in [
3725 ("--- bare", "--- bare"),
3726 ("-----\tspaced", "--- spaced"),
3727 ("--- Closed. ---", "--- Closed."),
3728 ("---- Ends in a rule ---", "---- Ends in a rule ---"),
3729 ] {
3730 let src = format!("commons m\n\n{written}\nfn f() -> Int {{ 1 }}\n");
3731 assert_eq!(
3732 format_source(&src, &FormatOptions::default()).unwrap(),
3733 format!("commons m\n\n{printed}\nfn f() -> Int {{\n\t1\n}}\n"),
3734 "{written:?}"
3735 );
3736 }
3737 }
3738
3739 #[test]
3743 fn legacy_spellings_format_to_the_new_ones() {
3744 let src = "-- A header.\ncommons m\n\n--| A run.\ntype Run = {\n\t--| The repo.\n\trepo: String,\n\tn: Int, -- trailing\n}\n\nfn d(a: Int, b: Int) -> Int { a--b }\n";
3745 let out = format_source(src, &FormatOptions::default()).unwrap();
3746 assert_eq!(
3747 out,
3748 "// A header.\ncommons m\n\n--- A run.\ntype Run = {\n\t--- The repo.\n\trepo: String,\n\tn: Int, // trailing\n}\n\nfn d(a: Int, b: Int) -> Int {\n\ta - -b\n}\n"
3749 );
3750 assert_eq!(format_source(&out, &FormatOptions::default()).unwrap(), out);
3751 let ruled = "commons m\n\n--| Ends in a rule ---\nfn f() -> Int { 1 }\n";
3753 assert_eq!(
3754 format_source(ruled, &FormatOptions::default()).unwrap(),
3755 "commons m\n\n---- Ends in a rule ---\nfn f() -> Int {\n\t1\n}\n"
3756 );
3757 }
3758
3759 #[test]
3764 fn a_half_migrated_file_is_refused_where_the_reads_differ() {
3765 let opts = FormatOptions::default();
3766 for (src, line) in [
3767 (
3768 "commons m\n\n-- note\n--- Adds two ints.\nfn add(a: Int, b: Int) -> Int { a + b }\n",
3769 "--- Adds two ints.",
3770 ),
3771 (
3772 "commons m\n\n-- note\nfn f(a: Int, b: Int) -> Int { a --b }\n",
3773 "fn f(a: Int, b: Int) -> Int { a --b }",
3774 ),
3775 ] {
3776 let err = format_source(src, &opts).unwrap_err();
3777 assert_eq!(
3778 err.errors[0].category, "bynk.fmt.mixed_comment_syntax",
3779 "{src}"
3780 );
3781 assert_eq!(&src[err.errors[0].span.range()], line, "{src}");
3782 }
3783 let divider = "-- A header.\ncommons m\n\n--- Helpers ---\n\nfn f() -> Int { 1 }\n";
3786 let err = format_source(divider, &opts).unwrap_err();
3787 assert_eq!(err.errors[0].category, "bynk.fmt.mixed_comment_syntax");
3788 let agreeing =
3789 "commons m\n\n-- note\n// new\nfn f(a: Int, b: Int) -> Int { a--b } --| old\n";
3790 assert_eq!(
3791 format_source(agreeing, &opts).unwrap(),
3792 "commons m\n\n// note\n// new\nfn f(a: Int, b: Int) -> Int {\n\ta - -b\n} // old\n"
3793 );
3794 }
3795
3796 #[test]
3800 fn a_blank_after_a_comment_under_a_doc_line_is_kept() {
3801 for (doc, printed) in [
3802 ("--- Doc.\n", "--- Doc.\n"),
3803 ("---\nDoc.\n---\n", "---\nDoc.\n---\n"),
3804 ] {
3805 let src = format!("commons m\n\n{doc}// note\n\ntype X = Int\n");
3806 assert_eq!(
3807 format_source(&src, &FormatOptions::default()).unwrap(),
3808 format!("commons m\n\n// note\n\n{printed}type X = Int\n"),
3809 "{doc:?}"
3810 );
3811 }
3812 }
3813
3814 #[test]
3817 fn an_orphaned_doc_line_run_keeps_its_form() {
3818 let src = "commons m\n\n--- Orphaned.\n\nfn f() -> Int { 1 }\n";
3819 assert_eq!(
3820 format_source(src, &FormatOptions::default()).unwrap(),
3821 "commons m\n\n--- Orphaned.\n\nfn f() -> Int {\n\t1\n}\n"
3822 );
3823 }
3824
3825 #[test]
3828 fn the_doc_loss_guard_sees_a_converted_form() {
3829 let src = "commons m\n\n--- Text.\nfn f() -> Int { 1 }\n";
3830 let tokens = tokenize(src).unwrap();
3831 let converted = "commons m\n\n---\nText.\n---\nfn f() -> Int { 1 }\n";
3832 assert!(doc_block_loss(src, &tokens, converted).is_some());
3833 assert!(doc_block_loss(src, &tokens, src).is_none());
3834 }
3835
3836 #[test]
3839 fn crlf_formats_to_the_lf_canonical_form() {
3840 let lf = "context greeting\n\n---\nA greeting for a name.\n---\nfn greet(name: String) -> String {\n\tname\n}\n";
3841 assert_eq!(format_source(lf, &FormatOptions::default()).unwrap(), lf);
3842 let crlf = lf.replace('\n', "\r\n");
3843 let formatted = format_source(&crlf, &FormatOptions::default()).unwrap();
3844 assert_eq!(formatted, lf);
3845 assert!(!formatted.contains('\r'));
3846 }
3847
3848 #[test]
3851 fn braced_declarations_always_break() {
3852 let src = "commons m\n\ntype P = { x: Int, y: Int }\n\nfn id(n: Int) -> Int { n }\n\nfn nop() -> () {}\n";
3853 let out = format_source(src, &FormatOptions::default()).unwrap();
3854 assert_eq!(
3855 out,
3856 "commons m\n\ntype P = {\n\tx: Int,\n\ty: Int,\n}\n\nfn id(n: Int) -> Int {\n\tn\n}\n\nfn nop() -> () {}\n"
3857 );
3858 assert_eq!(format_source(&out, &FormatOptions::default()).unwrap(), out);
3859 }
3860
3861 #[test]
3864 fn record_literals_break_but_match_arms_stay_compact() {
3865 let src = "commons m\n\nfn a(v: Int) -> P { P { x: v, y: v } }\n\nfn b(v: Int) -> P { P { x: v } }\n\nfn c(v: Int) -> Int { match v { 0 => 1, _ => 2 } }\n\nfn d(v: Int) -> Int { if v > 0 { 1 } else { 0 } }\n";
3866 let out = format_source(src, &FormatOptions::default()).unwrap();
3867 assert_eq!(
3868 out,
3869 "commons m\n\nfn a(v: Int) -> P {\n\tP {\n\t\tx: v,\n\t\ty: v,\n\t}\n}\n\nfn b(v: Int) -> P {\n\tP { x: v }\n}\n\nfn c(v: Int) -> Int {\n\tmatch v {\n\t\t0 => 1,\n\t\t_ => 2,\n\t}\n}\n\nfn d(v: Int) -> Int {\n\tif v > 0 { 1 } else { 0 }\n}\n"
3870 );
3871 assert_eq!(format_source(&out, &FormatOptions::default()).unwrap(), out);
3872 }
3873
3874 #[test]
3877 fn suite_header_is_spaced_and_members_keep_source_order() {
3878 let src = "suite shop\nuses money\nproperty \"p1\" {\n for all a: Int { expect a == a }\n}\ncase \"c1\" { expect true }\nproperty \"p2\" {\n for all a: Int { expect a == a }\n}\n";
3879 let out = format_source(src, &FormatOptions::default()).unwrap();
3880 assert_eq!(
3881 out,
3882 "suite shop\n\nuses money\n\nproperty \"p1\" {\n\tfor all a: Int {\n\t\texpect a == a\n\t}\n}\n\ncase \"c1\" {\n\texpect true\n}\n\nproperty \"p2\" {\n\tfor all a: Int {\n\t\texpect a == a\n\t}\n}\n"
3883 );
3884 assert_eq!(format_source(&out, &FormatOptions::default()).unwrap(), out);
3885 }
3886
3887 #[test]
3890 fn a_suite_keeps_its_consumes_clauses_together() {
3891 let src = "suite shop as unit\nconsumes bynk { Claim }\nconsumes bynk.cloudflare { D1 }\ncase \"c\" { expect true }\n";
3892 let out = format_source(src, &FormatOptions::default()).unwrap();
3893 assert_eq!(
3894 out,
3895 "suite shop as unit\n\nconsumes bynk { Claim }\nconsumes bynk.cloudflare { D1 }\n\ncase \"c\" {\n\texpect true\n}\n"
3896 );
3897 assert_eq!(format_source(&out, &FormatOptions::default()).unwrap(), out);
3898 }
3899
3900 #[test]
3903 fn spread_literals_break_only_with_overrides() {
3904 let src =
3905 "commons m\n\nfn a(b: P) -> P { P { ...b, x: 1 } }\n\nfn c(b: P) -> P { P { ...b } }\n";
3906 let out = format_source(src, &FormatOptions::default()).unwrap();
3907 assert_eq!(
3908 out,
3909 "commons m\n\nfn a(b: P) -> P {\n\tP {\n\t\t...b,\n\t\tx: 1,\n\t}\n}\n\nfn c(b: P) -> P {\n\tP { ...b }\n}\n"
3910 );
3911 assert_eq!(format_source(&out, &FormatOptions::default()).unwrap(), out);
3912 }
3913
3914 #[test]
3915 fn normalize_line_endings_borrows_when_there_is_nothing_to_do() {
3916 assert!(matches!(
3917 normalize_line_endings("a\nb"),
3918 std::borrow::Cow::Borrowed(_)
3919 ));
3920 assert_eq!(normalize_line_endings("a\r\nb\r\n"), "a\nb\n");
3921 }
3922
3923 #[test]
3926 fn normalize_line_endings_is_a_fixed_point() {
3927 for input in ["a\r\r\nb", "a\r\nb\rc\r\n", "\r\r\r\n", "x\r", "a\r\n\rb"] {
3928 let once = normalize_line_endings(input).into_owned();
3929 assert_eq!(normalize_line_endings(&once), once, "{input:?}");
3930 assert!(!once.contains("\r\n"), "{input:?} -> {once:?}");
3931 }
3932 assert_eq!(normalize_line_endings("a\r\r\nb"), "a\nb");
3933 assert_eq!(normalize_line_endings("a\r\nb\rc"), "a\nb\rc");
3934 }
3935
3936 #[test]
3940 fn doc_block_loss_leaves_an_untokenizable_output_to_the_roundtrip_guard() {
3941 let source = "commons d\n\n---\nattached\n---\nfn f() -> Int { 1 }\n";
3942 let tokens = tokenize(source).unwrap();
3943 assert!(tokenize("commons d\n\"unterminated").is_err());
3944 assert!(
3945 doc_block_loss(source, &tokens, "commons d\n\"unterminated").is_none(),
3946 "an untokenizable output was reported as doc-block loss"
3947 );
3948 }
3949
3950 #[test]
3955 fn a_file_with_a_lex_error_is_refused_not_formatted() {
3956 for src in [
3957 "commons d\n\n$\n\nfn f() -> Int { 1 }\n",
3958 "commons d\n\nfn f() -> Int { 1 }\n\nfn g() -> String { \"open }\n",
3959 "commons d\n\nfn f() -> Int { 99999999999999999999 }\n",
3960 ] {
3961 let errs = format_source(src, &FormatOptions::default())
3962 .expect_err("a file with a lex error must not format");
3963 assert!(
3964 errs.errors[0].category.starts_with("bynk.lex."),
3965 "{:?}",
3966 errs.errors
3967 );
3968 }
3969 }
3970
3971 fn fmt(src: &str) -> String {
3972 format_source(src, &FormatOptions::default()).expect("format failed")
3973 }
3974
3975 #[test]
3976 fn wildcard_lambda_params_round_trip() {
3977 let src = "commons x {\n\tfn f(r: Result[Int, String]) -> Result[Int, Int] {\n\t\tr.mapErr((_) => 0)\n\t}\n\n\tfn g(xs: List[Int]) -> Int {\n\t\txs.fold(0, (a, _) => a)\n\t}\n\n\tfn h(r: Result[Int, String]) -> Result[Int, Int] {\n\t\tr.mapErr((_: String) => 1)\n\t}\n\n\tfn k(f: (Int, Int) -> Int) -> Int {\n\t\tf(1, 2)\n\t}\n\n\tfn m() -> Int {\n\t\tk((_, _) => 1)\n\t}\n}\n";
3978 let out = fmt(src);
3979 assert_eq!(out, src);
3980 assert_eq!(fmt(&out), out);
3981 }
3982
3983 #[test]
3984 fn formats_minimal_commons() {
3985 let src = "commons fitness.units {}";
3986 let out = fmt(src);
3987 assert!(out.starts_with("commons fitness.units"));
3988 let out2 = fmt(&out);
3990 assert_eq!(out, out2);
3991 }
3992
3993 #[test]
3994 fn formats_refined_type() {
3995 let src = "commons x { type Metres = Int where NonNegative }";
3996 let out = fmt(src);
3997 assert!(out.contains("type Metres = Int where NonNegative"));
3998 let out2 = fmt(&out);
3999 assert_eq!(out, out2);
4000 }
4001
4002 #[test]
4003 fn formats_function_decl() {
4004 let src = "commons x { fn add(a: Int, b: Int) -> Int { a + b } }";
4005 let out = fmt(src);
4006 assert!(out.contains("fn add(a: Int, b: Int) -> Int"));
4007 let out2 = fmt(&out);
4008 assert_eq!(out, out2);
4009 }
4010
4011 #[test]
4012 fn formats_record() {
4013 let src = "commons x { type Pt = { x: Int, y: Int } }";
4014 let out = fmt(src);
4015 let out2 = fmt(&out);
4016 assert_eq!(out, out2, "formatter not idempotent: {out}");
4017 }
4018
4019 #[test]
4020 fn formats_a_fault_claim_with_a_call_site_principal() {
4021 let src = "suite s {\n case \"c\" {\n expect api.POST(\"/o\", x) by User( \"bob\" ) faults\n expect api.GET(\"/a\") by Visitor faults\n expect box.call() faults\n }\n}\n";
4024 let out = fmt(src);
4025 assert!(
4026 out.contains("expect api.POST(\"/o\", x) by User(\"bob\") faults"),
4027 "{out}"
4028 );
4029 assert!(
4030 out.contains("expect api.GET(\"/a\") by Visitor faults"),
4031 "{out}"
4032 );
4033 assert!(out.contains("expect box.call() faults"), "{out}");
4034 assert_eq!(out, fmt(&out), "formatter not idempotent: {out}");
4035 }
4036
4037 #[test]
4038 fn formats_doc_block() {
4039 let src = "commons x {\n---\nA descriptive doc.\n---\ntype T = Int where Positive\n}";
4040 let out = fmt(src);
4041 assert!(out.contains("A descriptive doc."));
4042 let out2 = fmt(&out);
4043 assert_eq!(out, out2);
4044 }
4045
4046 #[test]
4049 fn preserves_leading_line_comment_on_decl() {
4050 let src = "commons x {\n// explain T\ntype T = Int where NonNegative\n}";
4051 let out = fmt(src);
4052 assert!(out.contains("// explain T"), "comment dropped: {out}");
4053 assert_eq!(out, fmt(&out));
4055 }
4056
4057 #[test]
4058 fn preserves_trailing_line_comment_on_decl() {
4059 let src = "commons x {\ntype T = Int where NonNegative // short\n}";
4060 let out = fmt(src);
4061 assert!(out.contains("// short"));
4062 assert!(
4064 out.lines()
4065 .any(|l| l.contains("type T") && l.contains("// short")),
4066 "trailing comment not on same line: {out}"
4067 );
4068 assert_eq!(out, fmt(&out));
4069 }
4070
4071 #[test]
4072 fn preserves_grouped_leading_comments() {
4073 let src = "commons x {\n// one\n// two\ntype T = Int where Positive\n}";
4074 let out = fmt(src);
4075 assert!(out.contains("// one"));
4076 assert!(out.contains("// two"));
4077 let i1 = out.find("// one").unwrap();
4079 let i2 = out.find("// two").unwrap();
4080 let between = &out[i1..i2];
4081 assert_eq!(
4082 between.matches('\n').count(),
4083 1,
4084 "blank line inserted: {out}"
4085 );
4086 assert_eq!(out, fmt(&out));
4087 }
4088
4089 #[test]
4090 fn preserves_comment_before_block_tail() {
4091 let src = "commons x {\nfn f(n: Int) -> Int {\nlet y = n + 1\n// result\ny\n}\n}";
4092 let out = fmt(src);
4093 assert!(out.contains("// result"), "tail comment dropped: {out}");
4094 assert_eq!(out, fmt(&out));
4095 }
4096
4097 #[test]
4098 fn preserves_comment_with_doc_block_above_decl() {
4099 let src = "commons x {\n// TODO: rename\n---\nThe canonical T.\n---\ntype T = Int where Positive\n}";
4100 let out = fmt(src);
4101 assert!(out.contains("// TODO: rename"));
4102 assert!(out.contains("The canonical T."));
4103 let ic = out.find("// TODO: rename").unwrap();
4105 let id = out.find("The canonical T.").unwrap();
4106 let it = out.find("type T").unwrap();
4107 assert!(ic < id && id < it, "ordering wrong: {out}");
4108 assert_eq!(out, fmt(&out));
4109 }
4110
4111 #[test]
4112 fn preserves_trailing_file_comment() {
4113 let src = "commons x.y\n\ntype T = Int where Positive\n// TODO\n";
4114 let out = fmt(src);
4115 assert!(out.contains("// TODO"));
4116 assert_eq!(out, fmt(&out));
4117 }
4118
4119 #[test]
4128 fn expression_interior_comment_is_not_fully_drained_and_still_refused() {
4129 let src = "commons x {\n fn f() -> Int {\n 1 + // note\n 2\n }\n}\n";
4130 let tokens = tokenize(src).unwrap();
4131 let (_, _, fully_drained) = bynk_syntax::parser::parse_units_with_drain_check(&tokens, src)
4132 .expect("a comment inside an expression is still a valid parse");
4133 assert!(
4134 !fully_drained,
4135 "an expression-interior comment must leave the trivia table undrained"
4136 );
4137 let err = format_source(src, &FormatOptions::default())
4138 .expect_err("formatting must still refuse rather than lose the comment");
4139 assert_eq!(err.errors[0].category, "bynk.fmt.comment_loss");
4140 }
4141
4142 #[test]
4147 fn ordinary_comment_is_fully_drained_and_formats_normally() {
4148 let src = "commons x {\n// note\ntype T = Int where Positive\n}\n";
4149 let tokens = tokenize(src).unwrap();
4150 let (_, _, fully_drained) =
4151 bynk_syntax::parser::parse_units_with_drain_check(&tokens, src).expect("should parse");
4152 assert!(
4153 fully_drained,
4154 "a declaration-leading comment must be fully drained"
4155 );
4156 let out = fmt(src);
4157 assert!(out.contains("// note"));
4158 }
4159
4160 #[test]
4164 fn match_arm_block_tail_unit_after_assign_does_not_reattach_as_a_call() {
4165 let src = "commons x { fn f(status: T) -> T {\n match status {\n Draft => {\n status := Paid\n ()\n }\n Paid => (),\n }\n} }";
4171 let out = fmt(src);
4172 assert!(
4173 !out.contains("Paid()"),
4174 "the `()` tail must not re-attach to `Paid` as a call:\n{out}"
4175 );
4176 assert!(
4177 out.contains("status := Paid"),
4178 "the assignment must survive unmangled:\n{out}"
4179 );
4180 assert_eq!(out, fmt(&out), "must be idempotent");
4181 }
4182
4183 #[test]
4184 fn explicit_unit_tail_after_a_statement_is_omitted_like_an_implicit_one() {
4185 let src = "commons x { fn f() -> Effect[()] {\n let a = 1\n ()\n} }";
4189 let out = fmt(src);
4190 let expected = "commons x {\n\tfn f() -> Effect[()] {\n\t\tlet a = 1\n\t}\n}\n";
4191 assert_eq!(
4192 out, expected,
4193 "an explicit unit tail after a statement must be omitted"
4194 );
4195 assert_eq!(out, fmt(&out), "must be idempotent");
4196 }
4197
4198 #[test]
4201 fn code_only_canonical_ignores_comments() {
4202 let opts = FormatOptions::default();
4206 let bare = "commons x { type T = Int where Positive }";
4207 let commented = "commons x {\n// a note\ntype T = Int where Positive // trailing\n}";
4208 assert_eq!(
4209 code_only_canonical(bare, &opts).unwrap(),
4210 code_only_canonical(commented, &opts).unwrap(),
4211 );
4212 }
4213
4214 #[test]
4215 fn roundtrip_guard_accepts_faithful_output() {
4216 let opts = FormatOptions::default();
4218 let src = "commons x { fn add(a: Int, b: Int) -> Int { a + b } }";
4219 let out = format_source(src, &opts).unwrap();
4220 let tokens = tokenize(src).unwrap();
4221 assert!(roundtrip_divergence(&tokens, src, &out, &opts).is_none());
4222 }
4223
4224 #[test]
4225 fn roundtrip_guard_rejects_non_parsing_output() {
4226 let opts = FormatOptions::default();
4234 let src = "commons x { type T = Int where Positive }";
4235 let corrupt = "commons x { type T = Int where Positive } fn f(a: Int) -> Int { a +";
4236 assert!(
4237 corrupt.len() > src.len(),
4238 "output must be the longer buffer"
4239 );
4240 let tokens = tokenize(src).unwrap();
4241 let err = roundtrip_divergence(&tokens, src, corrupt, &opts)
4242 .expect("must reject non-parsing output");
4243 assert_eq!(err.category, "bynk.fmt.roundtrip");
4244 assert!(
4245 err.span.end <= src.len(),
4246 "roundtrip error span {:?} escapes the source it is rendered against (len {})",
4247 err.span,
4248 src.len(),
4249 );
4250 }
4251
4252 #[test]
4253 fn roundtrip_guard_rejects_structural_divergence() {
4254 let opts = FormatOptions::default();
4257 let src = "commons x { type T = Int where Positive }";
4258 let wrong = "commons x { type T = Bool }";
4259 let tokens = tokenize(src).unwrap();
4260 let err = roundtrip_divergence(&tokens, src, wrong, &opts)
4261 .expect("must reject structural divergence");
4262 assert_eq!(err.category, "bynk.fmt.roundtrip");
4263 assert!(err.span.end <= src.len(), "span escapes the source buffer");
4264 }
4265
4266 #[test]
4267 fn unchanged_files_without_comments_format_identically() {
4268 let src = "commons x { type T = Int where NonNegative }";
4269 let out = fmt(src);
4270 assert!(!out.contains("//"), "unexpected comment in output: {out}");
4273 }
4274
4275 #[test]
4278 fn formats_store_field_and_cell_write() {
4279 let src = "context shop {\nagent Counter {\nkey id: String\nstore count: Cell[Int] = 0\non call bump() -> Effect[()] {\ncount := count + 1\n()\n}\n}\n}";
4280 let out = fmt(src);
4281 assert!(
4282 out.contains("store count: Cell[Int] = 0"),
4283 "store field not formatted: {out}"
4284 );
4285 assert!(
4286 out.contains("count := count + 1"),
4287 "cell write not formatted: {out}"
4288 );
4289 assert_eq!(out, fmt(&out), "formatter not idempotent: {out}");
4290 }
4291
4292 #[test]
4293 fn formats_store_only_agent_without_state_block() {
4294 let src = "context shop {\nagent Counter {\nkey id: String\nstore count: Cell[Int] = 0\non call get() -> Effect[Int] {\ncount\n}\n}\n}";
4295 let out = fmt(src);
4296 assert!(!out.contains("state {"), "spurious state block: {out}");
4298 assert!(out.contains("store count: Cell[Int] = 0"), "{out}");
4299 assert_eq!(out, fmt(&out), "not idempotent: {out}");
4300 }
4301
4302 fn widths(out: &str) -> Vec<usize> {
4306 out.lines().map(|l| display_width(l, 4)).collect()
4307 }
4308
4309 fn assert_within_budget(out: &str) {
4310 let over: Vec<&str> = out.lines().filter(|l| display_width(l, 4) > 100).collect();
4311 assert!(over.is_empty(), "lines over 100 columns: {over:?}\n{out}");
4312 }
4313
4314 #[test]
4315 fn fit_test_counts_the_prefix_already_on_the_line() {
4316 let src = "commons x {\nfn authorise(amount: Int, ceiling: Int, floor: Int) -> Result[Int, Error] { if amount > ceiling { Err(Declined) } else { Ok(amount) } }\n}";
4319 let out = fmt(src);
4320 assert_within_budget(&out);
4321 assert!(
4322 out.contains("-> Result[Int, Error] {\n"),
4323 "body not broken out: {out}"
4324 );
4325 assert_eq!(out, fmt(&out), "not idempotent: {out}");
4326 }
4327
4328 #[test]
4329 fn wraps_a_long_record_construction_one_field_per_line() {
4330 let src = "commons x {\nfn make() -> R { R { alpha: \"first value here\", beta: \"second value here\", gamma: \"third value here\", delta: \"fourth value\" } }\n}";
4331 let out = fmt(src);
4332 assert_within_budget(&out);
4333 assert!(
4334 out.contains("\t\talpha: \"first value here\",\n"),
4335 "fields not one per line: {out}"
4336 );
4337 assert_eq!(out, fmt(&out), "not idempotent: {out}");
4338 }
4339
4340 #[test]
4341 fn wraps_a_long_argument_list_without_a_trailing_comma() {
4342 let src = "commons x {\nfn go() -> Int { combine(firstOperandValue, secondOperandValue, thirdOperandValue, fourthOperandValue) }\n}";
4346 let out = fmt(src);
4347 assert_within_budget(&out);
4348 assert!(
4349 !out.contains(",\n\t\t)"),
4350 "trailing comma in an argument list: {out}"
4351 );
4352 assert_eq!(out, fmt(&out), "not idempotent: {out}");
4353 }
4354
4355 #[test]
4356 fn wraps_long_parameter_lists_behind_the_return_type() {
4357 let src = "context x {\nservice api from http {\non POST(\"/reservations/confirm\") (identifier: String, body: Reservation) -> Effect[HttpResult[Reservation]] by Visitor { Ok(body) }\n}\n}";
4358 let out = fmt(src);
4359 assert_within_budget(&out);
4360 assert!(
4361 out.contains("\t\t\tidentifier: String,\n"),
4362 "params not wrapped: {out}"
4363 );
4364 assert_eq!(out, fmt(&out), "not idempotent: {out}");
4365 }
4366
4367 #[test]
4368 fn breaks_a_long_chain_at_its_dots() {
4369 let src = "commons x {\nfn go(rows: List[Row]) -> List[Int] { rows.filterOnlyTheInteresting((r) => r.nights > 0).mapEachOntoItsValue((r) => r.nights * r.rate).collect() }\n}";
4370 let out = fmt(src);
4371 assert_within_budget(&out);
4372 assert!(
4373 out.contains("\n\t\t\t.collect()"),
4374 "chain not broken at the dots: {out}"
4375 );
4376 assert_eq!(out, fmt(&out), "not idempotent: {out}");
4377 }
4378
4379 #[test]
4380 fn keeps_a_chain_intact_when_only_an_argument_needs_wrapping() {
4381 let src = "commons x {\nfn join(parts: List[String]) -> String {\nlet init: Option[String] = None\nparts.fold(init, (acc, p) => match acc {\nSome(s) => Some(s.concat(p)),\nNone => Some(p),\n}).getOrElse(\"\")\n}\n}";
4384 let out = fmt(src);
4385 assert_within_budget(&out);
4386 assert!(
4387 out.contains("parts.fold(init, (acc, p) => match acc {"),
4388 "chain broken needlessly: {out}"
4389 );
4390 assert_eq!(out, fmt(&out), "not idempotent: {out}");
4391 }
4392
4393 #[test]
4394 fn breaks_a_long_conjunction_before_each_operator() {
4395 let src = "commons x {\nfn ok(a: Int, b: Int, c: Int, d: Int) -> Bool { aSufficientlyLongPredicateName(a) && anotherRatherLongPredicate(b) && yetAnotherLongishPredicate(c) && theFinalPredicateHere(d) }\n}";
4396 let out = fmt(src);
4397 assert_within_budget(&out);
4398 assert!(
4399 out.lines().any(|l| l.trim_start().starts_with("&& ")),
4400 "conjunction not broken at the operators: {out}"
4401 );
4402 assert_eq!(out, fmt(&out), "not idempotent: {out}");
4403 }
4404
4405 #[test]
4406 fn never_breaks_before_an_arithmetic_operator() {
4407 let src = "commons x {\nfn total(a: Int, b: Int, c: Int, d: Int) -> Int { someLongFunctionName(a) + anotherLongFunction(b) + aThirdLongFunction(c) + lastOne(d) }\n}";
4410 let out = fmt(src);
4411 assert!(
4412 !out.lines().any(|l| l.trim_start().starts_with("+ ")),
4413 "broke before `+`, which does not re-parse: {out}"
4414 );
4415 assert_eq!(out, fmt(&out), "not idempotent: {out}");
4416 }
4417
4418 #[test]
4419 fn wraps_an_over_long_actor_auth_config() {
4420 let src = "context x {\nactor Partner { auth = Oidc(issuer = \"https://issuer.example.test\", audience = \"reservations-api\", jwks = \"https://issuer.example.test/jwks.json\"), identity = PartnerId }\n}";
4421 let out = fmt(src);
4422 assert_within_budget(&out);
4423 assert!(
4424 out.contains("\t\tissuer = "),
4425 "scheme args not wrapped: {out}"
4426 );
4427 assert!(out.contains("identity = PartnerId"), "identity lost: {out}");
4428 assert_eq!(out, fmt(&out), "not idempotent: {out}");
4429 }
4430
4431 #[test]
4432 fn a_lone_block_like_argument_hugs_its_call() {
4433 let src = "commons x {\nfn go(items: List[Item]) -> Effect[()] { items.forEachInTurnAndOrder((item: Item) => { let _ <- store.put(item.identifier, item) }) }\n}";
4434 let out = fmt(src);
4435 assert_within_budget(&out);
4436 assert!(
4437 out.contains("((item: Item) => {"),
4438 "sole lambda argument did not hug its call: {out}"
4439 );
4440 assert_eq!(out, fmt(&out), "not idempotent: {out}");
4441 }
4442
4443 #[test]
4444 fn an_unbreakable_line_is_left_long_rather_than_mangled() {
4445 let long = "x".repeat(140);
4448 let src = format!("commons x {{\nfn go() -> String {{ \"{long}\" }}\n}}");
4449 let out = fmt(&src);
4450 assert!(
4451 widths(&out).iter().any(|w| *w > 100),
4452 "expected an over-long line: {out}"
4453 );
4454 assert_eq!(out, fmt(&out), "not idempotent: {out}");
4455 }
4456
4457 #[test]
4458 fn wrapping_is_idempotent_and_structure_preserving_across_widths() {
4459 let src = "context x {\ntype R = { id: String, name: String, size: Int }\nfn build(id: String, name: String, size: Int) -> R { R { id: id, name: name, size: size } }\nfn pick(rows: List[R]) -> List[String] { rows.filter((r) => r.size > 0).map((r) => r.name).collect() }\n}";
4463 for width in [40u32, 60, 80, 100, 120] {
4464 let opts = FormatOptions {
4465 max_line_width: width,
4466 ..FormatOptions::default()
4467 };
4468 let out = format_source(src, &opts).unwrap_or_else(|e| {
4469 panic!("width {width}: format refused ({} errors)", e.errors.len())
4470 });
4471 let again = format_source(&out, &opts).unwrap_or_else(|e| {
4472 panic!(
4473 "width {width}: reformat refused ({} errors)",
4474 e.errors.len()
4475 )
4476 });
4477 assert_eq!(out, again, "width {width}: not idempotent:\n{out}");
4478 }
4479 }
4480
4481 #[test]
4484 fn event_schema_annotation_formats_and_is_idempotent() {
4485 let src = "context commerce.order {\nevent PaymentConfirmed @schema(2) = {\norderId: String,\n}\n}";
4486 let out = fmt(src);
4487 assert!(
4488 out.contains("event PaymentConfirmed @schema(2) = {"),
4489 "{out}"
4490 );
4491 assert_eq!(out, fmt(&out), "not idempotent: {out}");
4492 }
4493
4494 #[test]
4497 fn event_with_no_annotation_formats_unchanged() {
4498 let src = "context commerce.order {\nevent PaymentConfirmed = {\norderId: String,\n}\n}";
4499 let out = fmt(src);
4500 assert!(out.contains("event PaymentConfirmed = {"), "{out}");
4501 assert_eq!(out, fmt(&out), "not idempotent: {out}");
4502 }
4503
4504 #[test]
4507 fn via_schema_dispatch_formats_and_is_idempotent() {
4508 let src = "context commerce.order {\nservice OnPayment from Events(PaymentConfirmed) via schema(2) {\non event(e: PaymentConfirmed) -> Effect[()] {\nEffect.pure(())\n}\n}\n}";
4509 let out = fmt(src);
4510 assert!(
4511 out.contains("from Events(PaymentConfirmed) via schema(2)"),
4512 "{out}"
4513 );
4514 assert_eq!(out, fmt(&out), "not idempotent: {out}");
4515 }
4516
4517 #[test]
4521 fn via_schema_dispatch_combines_with_a_payload_pattern() {
4522 let src = "context commerce.order {\nservice OnPayment from Events(PaymentConfirmed { region: Domestic, .. }) via schema(2) {\non event(e: PaymentConfirmed) -> Effect[()] {\nEffect.pure(())\n}\n}\n}";
4523 let out = fmt(src);
4524 assert!(
4525 out.contains("from Events(PaymentConfirmed { region: Domestic, .. }) via schema(2)"),
4526 "{out}"
4527 );
4528 assert_eq!(out, fmt(&out), "not idempotent: {out}");
4529 }
4530
4531 #[test]
4534 fn via_schema_ranges_and_wildcard_format_and_are_idempotent() {
4535 for (written, printed) in [
4536 ("2 .. 4", "2..4"),
4537 ("2 ..", "2.."),
4538 (".. 4", "..4"),
4539 ("_", "_"),
4540 ] {
4541 let src = format!(
4542 "context commerce.order {{\nservice OnPayment from Events(PaymentConfirmed) via schema({written}) {{\non event(e: PaymentConfirmed) -> Effect[()] {{\nEffect.pure(())\n}}\n}}\n}}"
4543 );
4544 let out = fmt(&src);
4545 assert!(out.contains(&format!("via schema({printed})")), "{out}");
4546 assert_eq!(out, fmt(&out), "not idempotent: {out}");
4547 }
4548 }
4549
4550 #[test]
4553 fn range_patterns_format_without_spaces_and_are_idempotent() {
4554 let src = "commons c {\nfn f(n: Int, o: Option[Int], xs: List[Int]) -> Int {\nlet 0 .. 9 = n else { 0 }\nlet _ = match o {\nSome(0 .. 9 | 90 .. 99) => 1\nSome(.. -1) => 2\nSome(18 ..) => 3\nSome(_) => 4\nNone => 5\n}\nmatch xs {\n[0 .. 9, ..rest] => 1\n[.. -1] => 2\n_ => 3\n}\n}\n}";
4555 let out = fmt(src);
4556 for want in [
4557 "let 0..9 = n else",
4558 "Some(0..9 | 90..99) =>",
4559 "Some(..-1) =>",
4560 "Some(18..) =>",
4561 "[0..9, ..rest] =>",
4562 "[..-1] =>",
4563 ] {
4564 assert!(out.contains(want), "{want}: {out}");
4565 }
4566 assert_eq!(out, fmt(&out), "not idempotent: {out}");
4567 }
4568}
4569
4570#[cfg(test)]
4571mod snapshot_clause_tests {
4572 use super::*;
4573
4574 #[test]
4577 fn a_snapshot_clause_is_kept() {
4578 let src = "suite demo\n\ncase \"c\" {\n\texpect read(1) matches snapshot \"a \\\"q\\\" name\"\n\tlet matches = 1\n\texpect matches == 1\n}\n";
4579 let once = format_source(src, &FormatOptions::default()).expect("formats");
4580 assert!(
4581 once.contains("\texpect read(1) matches snapshot \"a \\\"q\\\" name\"\n"),
4582 "{once}"
4583 );
4584 assert!(once.contains("let matches = 1"), "{once}");
4585 let twice = format_source(&once, &FormatOptions::default()).expect("formats again");
4586 assert_eq!(once, twice);
4587 }
4588
4589 #[test]
4591 fn a_bare_matches_after_an_expect_is_the_next_statement() {
4592 let src = "suite demo\n\ncase \"c\" {\n\tlet matches = 1\n\texpect true\n\texpect matches == 1\n}\n";
4593 format_source(src, &FormatOptions::default()).expect("formats");
4594 }
4595}