difftreelog
fix(formatter) diagnostic on offset 0
in: master
1 file changed
crates/jrsonnet-formatter/src/lib.rsdiffbeforeafterboth1use std::{any::type_name, rc::Rc};23use children::{children_between, trivia_before};4use dprint_core::formatting::{5 ConditionResolver, ConditionResolverContext, LineNumber, PrintItems, PrintOptions,6 condition_helpers::is_multiple_lines,7 condition_resolvers::true_resolver,8 ir_helpers::{new_line_group, with_indent},9};10use hi_doc::{Formatting, SnippetBuilder};11use jrsonnet_lexer::collect_lexed_str_block;12use jrsonnet_rowan_parser::{13 AstNode, AstToken as _, SyntaxToken,14 nodes::{15 Arg, ArgsDesc, Assertion, BinaryOperator, Bind, CompSpec, Destruct, DestructArrayPart,16 DestructRest, Expr, ExprArray, ExprBase, FieldName, ForObjSpec, ForSpec, IfSpec,17 ImportKind, Literal, Member, Name, Number, ObjBody, ObjLocal, ParamsDesc, SliceDesc,18 SourceFile, Stmt, Suffix, Text, TextKind, UnaryOperator, Visibility,19 },20};2122use crate::{23 children::{Child, EndingComments, trivia_after},24 comments::{CommentLocation, format_comments},25};2627mod children;28mod comments;29mod tests;3031fn with_indent_eoi(cond: ConditionResolver, o: PrintItems, e: EndingComments) -> PrintItems {32 let end_comments_items = {33 let mut items = PrintItems::new();34 if e.should_start_with_newline {35 p!(&mut items, nl);36 }37 format_comments(&e.trivia, CommentLocation::EndOfItems, &mut items);38 items.into_rc_path()39 };40 let items = new_line_group(pi!(@i; items(o) items(end_comments_items.into()))).into_rc_path();4142 let indented = with_indent(pi!(@i; nl items(items.into())));4344 pi!(@i; if_else("indented body", cond, items(indented))(str(" ") items(items.into())))45}4647pub trait Printable {48 fn print(&self, out: &mut PrintItems);49}5051macro_rules! pi {52 (@i; $($t:tt)*) => {{53 #[allow(unused_mut)]54 let mut o = dprint_core::formatting::PrintItems::new();55 pi!(@s; o: $($t)*);56 o57 }};58 (@s; $o:ident: str($e:expr $(,)?) $($t:tt)*) => {{59 $o.push_string($e.to_owned());60 pi!(@s; $o: $($t)*);61 }};62 (@s; $o:ident: string($e:expr $(,)?) $($t:tt)*) => {{63 $o.push_string($e);64 pi!(@s; $o: $($t)*);65 }};66 (@s; $o:ident: nl $($t:tt)*) => {{67 $o.push_signal(dprint_core::formatting::Signal::NewLine);68 pi!(@s; $o: $($t)*);69 }};70 (@s; $o:ident: sonl $($t:tt)*) => {{71 $o.push_signal(dprint_core::formatting::Signal::SpaceOrNewLine);72 pi!(@s; $o: $($t)*);73 }};74 (@s; $o:ident: tab $($t:tt)*) => {{75 $o.push_signal(dprint_core::formatting::Signal::Tab);76 pi!(@s; $o: $($t)*);77 }};78 (@s; $o:ident: >i $($t:tt)*) => {{79 $o.push_signal(dprint_core::formatting::Signal::StartIndent);80 pi!(@s; $o: $($t)*);81 }};82 (@s; $o:ident: <i $($t:tt)*) => {{83 $o.push_signal(dprint_core::formatting::Signal::FinishIndent);84 pi!(@s; $o: $($t)*);85 }};86 (@s; $o:ident: >ii $($t:tt)*) => {{87 $o.push_signal(dprint_core::formatting::Signal::StartIgnoringIndent);88 pi!(@s; $o: $($t)*);89 }};90 (@s; $o:ident: <ii $($t:tt)*) => {{91 $o.push_signal(dprint_core::formatting::Signal::FinishIgnoringIndent);92 pi!(@s; $o: $($t)*);93 }};94 (@s; $o:ident: info($v:expr) $($t:tt)*) => {{95 $o.push_info($v);96 pi!(@s; $o: $($t)*);97 }};98 (@s; $o:ident: ln_anchor($v:expr) $($t:tt)*) => {{99 $o.push_anchor(LineNumberAnchor::new($v));100 pi!(@s; $o: $($t)*);101 }};102 (@s; $o:ident: if($s:literal, $cond:expr, $($i:tt)*) $($t:tt)*) => {{103 $o.push_condition(dprint_core::formatting::conditions::if_true(104 $s,105 $cond.clone(),106 {107 let mut o = PrintItems::new();108 p!(o, $($i)*);109 o110 },111 ));112 pi!(@s; $o: $($t)*);113 }};114 (@s; $o:ident: if_else($s:literal, $cond:expr, $($i:tt)*)($($e:tt)+) $($t:tt)*) => {{115 $o.push_condition(dprint_core::formatting::conditions::if_true_or(116 $s,117 $cond.clone(),118 {119 let mut o = PrintItems::new();120 p!(o, $($i)*);121 o122 },123 {124 let mut o = PrintItems::new();125 p!(o, $($e)*);126 o127 },128 ));129 pi!(@s; $o: $($t)*);130 }};131 (@s; $o:ident: if_not($s:literal, $cond:expr, $($e:tt)*) $($t:tt)*) => {{132 $o.push_condition(dprint_core::formatting::conditions::if_true_or(133 $s,134 $cond.clone(),135 {136 let o = PrintItems::new();137 o138 },139 {140 let mut o = PrintItems::new();141 p!(o, $($e)*);142 o143 },144 ));145 pi!(@s; $o: $($t)*);146 }};147 (@s; $o:ident: {$expr:expr} $($t:tt)*) => {{148 $expr.print($o);149 pi!(@s; $o: $($t)*);150 }};151 (@s; $o:ident: items($expr:expr) $($t:tt)*) => {{152 $o.extend($expr);153 pi!(@s; $o: $($t)*);154 }};155 (@s; $o:ident: if ($e:expr)($($then:tt)*) $($t:tt)*) => {{156 if $e {157 pi!(@s; $o: $($then)*);158 }159 pi!(@s; $o: $($t)*);160 }};161 (@s; $o:ident: ifelse ($e:expr)($($then:tt)*)($($else:tt)*) $($t:tt)*) => {{162 if $e {163 pi!(@s; $o: $($then)*);164 } else {165 pi!(@s; $o: $($else)*);166 }167 pi!(@s; $o: $($t)*);168 }};169 (@s; $i:ident:) => {}170}171macro_rules! p {172 ($o:ident, $($t:tt)*) => {173 pi!(@s; $o: $($t)*)174 };175 (&mut $o:ident, $($t:tt)*) => {176 let om = &mut $o;177 pi!(@s; om: $($t)*)178 };179}180pub(crate) use p;181pub(crate) use pi;182183impl<P> Printable for Option<P>184where185 P: Printable,186{187 fn print(&self, out: &mut PrintItems) {188 if let Some(v) = self {189 v.print(out);190 } else {191 p!(192 out,193 string(format!(194 "/*missing {}*/",195 type_name::<P>().replace("jrsonnet_rowan_parser::generated::nodes::", "")196 ),)197 );198 }199 }200}201202impl Printable for SyntaxToken {203 fn print(&self, out: &mut PrintItems) {204 p!(out, string(self.to_string()));205 }206}207208impl Printable for Text {209 fn print(&self, out: &mut PrintItems) {210 if matches!(self.kind(), TextKind::StringBlock) {211 let text = self.text();212 let mut text = collect_lexed_str_block(&text[3..])213 .expect("formatting is not performed on code with parsing errors");214215 if text.truncate && text.lines.ends_with(&[""]) {216 text.truncate = false;217 text.lines.pop();218 }219220 p!(out, str("|||"));221 if text.truncate {222 p!(out, str("-"));223 }224 p!(out, nl > i);225 for ele in text.lines {226 if ele.is_empty() {227 p!(out, >ii nl <ii);228 } else {229 p!(out, string(ele.to_string()) nl);230 }231 }232 p!(out, <i str("|||"));233234 return;235 }236 p!(out, string(format!("{}", self)));237 }238}239impl Printable for Number {240 fn print(&self, out: &mut PrintItems) {241 p!(out, string(format!("{}", self)));242 }243}244245impl Printable for Name {246 fn print(&self, out: &mut PrintItems) {247 p!(out, { self.ident_lit() });248 }249}250251impl Printable for DestructRest {252 fn print(&self, out: &mut PrintItems) {253 p!(out, str("..."));254 if let Some(name) = self.into() {255 p!(out, { name });256 }257 }258}259260impl Printable for Destruct {261 fn print(&self, out: &mut PrintItems) {262 match self {263 Self::DestructFull(f) => {264 p!(out, { f.name() });265 }266 Self::DestructSkip(_) => p!(out, str("?")),267 Self::DestructArray(a) => {268 p!(out, str("[") >i nl);269 for el in a.destruct_array_parts() {270 match el {271 DestructArrayPart::DestructArrayElement(e) => {272 p!(out, {e.destruct()} str(",") nl);273 }274 DestructArrayPart::DestructRest(d) => {275 p!(out, {d} str(",") nl);276 }277 }278 }279 p!(out, <i str("]"));280 }281 Self::DestructObject(o) => {282 p!(out, str("{") >i nl);283 for item in o.destruct_object_fields() {284 p!(out, { item.field() });285 if let Some(des) = item.destruct() {286 p!(out, str(": ") {des});287 }288 if let Some(def) = item.expr() {289 p!(out, str(" = ") {def});290 }291 p!(out, str(",") nl);292 }293 if let Some(rest) = o.destruct_rest() {294 p!(out, {rest} nl);295 }296 p!(out, <i str("}"));297 }298 }299 }300}301302impl Printable for FieldName {303 fn print(&self, out: &mut PrintItems) {304 match self {305 Self::FieldNameFixed(f) => {306 if let Some(id) = f.id() {307 p!(out, { id });308 } else if let Some(str) = f.text() {309 p!(out, { str });310 } else {311 p!(out, str("/*missing FieldName*/"));312 }313 }314 Self::FieldNameDynamic(d) => {315 p!(out, str("[") {d.expr()} str("]"));316 }317 }318 }319}320321impl Printable for Visibility {322 fn print(&self, out: &mut PrintItems) {323 p!(out, string(self.to_string()));324 }325}326327impl Printable for ObjLocal {328 fn print(&self, out: &mut PrintItems) {329 p!(out, str("local ") {self.bind()});330 }331}332333impl Printable for Assertion {334 fn print(&self, out: &mut PrintItems) {335 p!(out, str("assert ") {self.condition()});336 if self.colon_token().is_some() || self.message().is_some() {337 p!(out, str(": ") {self.message()});338 }339 }340}341342impl Printable for ParamsDesc {343 fn print(&self, out: &mut PrintItems) {344 p!(out, str("(") >i nl);345 for param in self.params() {346 p!(out, { param.destruct() });347 if param.assign_token().is_some() || param.expr().is_some() {348 p!(out, str(" = ") {param.expr()});349 }350 p!(out, str(",") nl);351 }352 p!(out, <i str(")"));353 }354}355impl Printable for ArgsDesc {356 fn print(&self, out: &mut PrintItems) {357 fn gen_args(children: Vec<Child<Arg>>, multi_line: ConditionResolver) -> PrintItems {358 let mut out = PrintItems::new();359360 let mut args = children.into_iter().peekable();361 while let Some(ele) = args.next() {362 if ele.should_start_with_newline {363 p!(out, nl);364 }365 format_comments(&ele.before_trivia, CommentLocation::AboveItem, &mut out);366 let arg = ele.value;367 if arg.name().is_some() || arg.assign_token().is_some() {368 p!(&mut out, {arg.name()} str(" = "));369 }370 p!(&mut out, { arg.expr() });371 let has_more = args.peek().is_some();372 if has_more {373 p!(out, str(","));374 } else {375 p!(out, if("trailing comma", multi_line, str(",")));376 }377 format_comments(&ele.inline_trivia, CommentLocation::ItemInline, &mut out);378 if has_more {379 p!(out, if_else("arg separator", multi_line, nl)(sonl));380 }381 }382383 out384 }385386 let start = LineNumber::new("args start line");387 let end = LineNumber::new("args end line");388 let multi_line = Rc::new(move |condition_context: &mut ConditionResolverContext| {389 is_multiple_lines(condition_context, start, end)390 });391392 let (children, end_comments) = children_between::<Arg>(393 self.syntax().clone(),394 self.l_paren_token().map(Into::into).as_ref(),395 self.r_paren_token().map(Into::into).as_ref(),396 None,397 );398399 let args_items = new_line_group(gen_args(children, multi_line.clone())).into_rc_path();400 let args_indented = with_indent(pi!(@i; nl items(args_items.into())));401402 p!(out, str("(") info(start));403 p!(out, if_else("args body", multi_line, items(args_indented) nl)(items(args_items.into())));404 if end_comments.should_start_with_newline {405 p!(out, nl);406 }407 format_comments(&end_comments.trivia, CommentLocation::EndOfItems, out);408 p!(out, str(")") info(end));409 }410}411impl Printable for SliceDesc {412 fn print(&self, out: &mut PrintItems) {413 p!(out, str("["));414 if self.from().is_some() {415 p!(out, { self.from() });416 }417 p!(out, str(":"));418 if self.end().is_some() {419 p!(out, { self.end().map(|e| e.expr()) });420 }421 // Keep only one : in case if we don't need step422 if self.step().is_some() {423 p!(out, str(":") {self.step().map(|e|e.expr())});424 }425 p!(out, str("]"));426 }427}428429impl Printable for Member {430 fn print(&self, out: &mut PrintItems) {431 match self {432 Self::MemberBindStmt(b) => {433 p!(out, { b.obj_local() });434 }435 Self::MemberAssertStmt(ass) => {436 p!(out, { ass.assertion() });437 }438 Self::MemberFieldNormal(n) => {439 p!(out, {n.field_name()} if(n.plus_token().is_some())({n.plus_token()}) {n.visibility()} str(" ") {n.expr()});440 }441 Self::MemberFieldMethod(m) => {442 p!(out, {m.field_name()} {m.params_desc()} {m.visibility()} str(" ") {m.expr()});443 }444 }445 }446}447448impl Printable for ObjBody {449 #[allow(clippy::too_many_lines)]450 fn print(&self, out: &mut PrintItems) {451 match self {452 Self::ObjBodyComp(l) => {453 fn gen_obj_comp(454 members: Vec<Child<Member>>,455 member_end_comments: EndingComments,456 compspecs: Vec<Child<CompSpec>>,457 multi_line: ConditionResolver,458 ) -> PrintItems {459 let mut out = PrintItems::new();460 for mem in members {461 if mem.should_start_with_newline {462 p!(out, nl);463 }464 format_comments(&mem.before_trivia, CommentLocation::AboveItem, &mut out);465 p!(&mut out, { mem.value });466 p!(out, if("trailing comma", multi_line, str(",")));467 format_comments(&mem.inline_trivia, CommentLocation::ItemInline, &mut out);468 p!(out, if_else("member-comp sep", multi_line, nl)(sonl));469 }470471 if member_end_comments.should_start_with_newline {472 p!(out, nl);473 }474 format_comments(475 &member_end_comments.trivia,476 CommentLocation::EndOfItems,477 &mut out,478 );479480 for mem in compspecs {481 if mem.should_start_with_newline {482 p!(out, nl);483 }484 format_comments(&mem.before_trivia, CommentLocation::AboveItem, &mut out);485 p!(&mut out, { mem.value });486 format_comments(&mem.inline_trivia, CommentLocation::ItemInline, &mut out);487 p!(out, if_else("comp spec sep", multi_line, nl)(sonl));488 }489490 out491 }492493 let (children, mut end_comments) = children_between::<Member>(494 l.syntax().clone(),495 l.l_brace_token().map(Into::into).as_ref(),496 Some(497 &(l.comp_specs()498 .next()499 .expect("at least one spec is defined")500 .syntax()501 .clone())502 .into(),503 ),504 None,505 );506 let trailing_for_comp = end_comments.extract_trailing();507508 let (compspecs, comp_end_comments) = children_between::<CompSpec>(509 l.syntax().clone(),510 l.member_comps()511 .last()512 .map(|m| m.syntax().clone())513 .map(Into::into)514 .or_else(|| l.l_brace_token().map(Into::into))515 .as_ref(),516 l.r_brace_token().map(Into::into).as_ref(),517 Some(trailing_for_comp),518 );519520 let source_is_multiline = children.iter().any(|c| c.triggers_multiline)521 || compspecs.iter().any(|c| c.triggers_multiline)522 || end_comments.should_start_with_newline523 || comp_end_comments.should_start_with_newline;524525 let start = LineNumber::new("obj comp start line");526 let end = LineNumber::new("obj comp end line");527 let multi_line: ConditionResolver = if source_is_multiline {528 true_resolver()529 } else {530 Rc::new(move |ctx: &mut ConditionResolverContext| {531 is_multiple_lines(ctx, start, end)532 })533 };534535 let body = new_line_group(gen_obj_comp(536 children,537 end_comments,538 compspecs,539 multi_line.clone(),540 ))541 .into_rc_path();542543 let body = with_indent_eoi(multi_line, body.into(), comp_end_comments);544545 p!(out, str("{") info(start));546 p!(out, items(body));547 p!(out, str("}") info(end));548 }549 Self::ObjBodyMemberList(l) => {550 fn gen_members(551 children: Vec<Child<Member>>,552 multi_line: ConditionResolver,553 ) -> PrintItems {554 let mut out = PrintItems::new();555 let mut members = children.into_iter().peekable();556 while let Some(mem) = members.next() {557 if mem.should_start_with_newline {558 p!(out, nl);559 }560 format_comments(&mem.before_trivia, CommentLocation::AboveItem, &mut out);561 p!(&mut out, { mem.value });562 let has_more = members.peek().is_some();563 if has_more {564 p!(out, str(","));565 } else {566 p!(out, if("trailing comma", multi_line, str(",")));567 }568 format_comments(&mem.inline_trivia, CommentLocation::ItemInline, &mut out);569 p!(out, if_else("member separator", multi_line, nl)(sonl));570 }571 out572 }573574 let (children, end_comments) = children_between::<Member>(575 l.syntax().clone(),576 l.l_brace_token().map(Into::into).as_ref(),577 l.r_brace_token().map(Into::into).as_ref(),578 None,579 );580 if children.is_empty() && end_comments.is_empty() {581 p!(out, str("{ }"));582 return;583 }584585 let source_is_multiline = children.iter().any(|c| c.triggers_multiline)586 || end_comments.should_start_with_newline;587588 let start = LineNumber::new("obj start line");589 let end = LineNumber::new("obj end line");590 let multi_line: ConditionResolver = if source_is_multiline {591 true_resolver()592 } else {593 Rc::new(move |ctx: &mut ConditionResolverContext| {594 is_multiple_lines(ctx, start, end)595 })596 };597598 let members_items =599 new_line_group(gen_members(children, multi_line.clone())).into_rc_path();600601 let members = with_indent_eoi(multi_line, members_items.into(), end_comments);602603 p!(out, str("{") info(start));604 p!(out, items(members));605 p!(out, str("}") info(end));606 }607 }608 }609}610impl Printable for UnaryOperator {611 fn print(&self, out: &mut PrintItems) {612 p!(out, string(self.text().to_string()));613 }614}615impl Printable for BinaryOperator {616 fn print(&self, out: &mut PrintItems) {617 p!(out, string(self.text().to_string()));618 }619}620impl Printable for Bind {621 fn print(&self, out: &mut PrintItems) {622 match self {623 Self::BindDestruct(d) => {624 p!(out, {d.into()} str(" = ") {d.value()});625 }626 Self::BindFunction(f) => {627 p!(out, {f.name()} {f.params()} str(" = ") {f.value()});628 }629 }630 }631}632impl Printable for Literal {633 fn print(&self, out: &mut PrintItems) {634 p!(out, string(self.syntax().to_string()));635 }636}637impl Printable for ImportKind {638 fn print(&self, out: &mut PrintItems) {639 p!(out, string(self.syntax().to_string()));640 }641}642impl Printable for ForSpec {643 fn print(&self, out: &mut PrintItems) {644 p!(out, str("for ") {self.bind()} str(" in ") {self.expr()});645 }646}647impl Printable for ForObjSpec {648 fn print(&self, out: &mut PrintItems) {649 p!(out, str("for [") {self.key()} str("]") {self.visibility()} str(" ") {self.value()} str(" in ") {self.expr()});650 }651}652impl Printable for IfSpec {653 fn print(&self, out: &mut PrintItems) {654 p!(out, str("if ") {self.expr()});655 }656}657impl Printable for CompSpec {658 fn print(&self, out: &mut PrintItems) {659 match self {660 Self::ForSpec(f) => f.print(out),661 Self::ForObjSpec(f) => f.print(out),662 Self::IfSpec(i) => i.print(out),663 }664 }665}666impl Printable for Expr {667 fn print(&self, out: &mut PrintItems) {668 let (stmts, _ending) = children_between::<Stmt>(669 self.syntax().clone(),670 None,671 self.expr_base()672 .as_ref()673 .map(ExprBase::syntax)674 .cloned()675 .map(Into::into)676 .as_ref(),677 None,678 );679 for stmt in stmts {680 p!(out, { stmt.value });681 }682 p!(out, { self.expr_base() });683 let (suffixes, _ending) = children_between::<Suffix>(684 self.syntax().clone(),685 self.expr_base()686 .as_ref()687 .map(ExprBase::syntax)688 .cloned()689 .map(Into::into)690 .as_ref(),691 None,692 None,693 );694 for suffix in suffixes {695 p!(out, { suffix.value });696 }697 }698}699impl Printable for Suffix {700 fn print(&self, out: &mut PrintItems) {701 match self {702 Self::SuffixIndex(i) => {703 if i.question_mark_token().is_some() {704 p!(out, str("?"));705 }706 p!(out, str(".") {i.index()});707 }708 Self::SuffixIndexExpr(e) => {709 if e.question_mark_token().is_some() {710 p!(out, str(".?"));711 }712 p!(out, str("[") {e.index()} str("]"));713 }714 Self::SuffixSlice(d) => {715 p!(out, { d.slice_desc() });716 }717 Self::SuffixApply(a) => {718 p!(out, { a.args_desc() });719 }720 }721 }722}723impl Printable for Stmt {724 fn print(&self, out: &mut PrintItems) {725 match self {726 Self::StmtLocal(l) => {727 let (binds, end_comments) = children_between::<Bind>(728 l.syntax().clone(),729 l.local_kw_token().map(Into::into).as_ref(),730 l.semi_token().map(Into::into).as_ref(),731 None,732 );733 if binds.len() == 1 {734 let bind = &binds[0];735 format_comments(&bind.before_trivia, CommentLocation::AboveItem, out);736 p!(out, str("local ") {bind.value});737 // TODO: keep end_comments, child.inline_trivia somehow, force multiple locals formatting in case of presence?738 } else {739 p!(out,str("local") >i nl);740 for bind in binds {741 if bind.should_start_with_newline {742 p!(out, nl);743 }744 format_comments(&bind.before_trivia, CommentLocation::AboveItem, out);745 p!(out, {bind.value} str(","));746 format_comments(&bind.inline_trivia, CommentLocation::ItemInline, out);747 p!(out, nl);748 }749 if end_comments.should_start_with_newline {750 p!(out, nl);751 }752 format_comments(&end_comments.trivia, CommentLocation::EndOfItems, out);753 p!(out,<i);754 }755 p!(out,str(";") nl);756 }757 Self::StmtAssert(a) => {758 p!(out, {a.assertion()} str(";") nl);759 }760 }761 }762}763764impl Printable for ExprArray {765 fn print(&self, out: &mut PrintItems) {766 fn gen_elements(children: Vec<Child<Expr>>, multi_line: ConditionResolver) -> PrintItems {767 let mut out = PrintItems::new();768 let mut els = children.into_iter().peekable();769 while let Some(el) = els.next() {770 if el.should_start_with_newline {771 p!(out, nl);772 }773 format_comments(&el.before_trivia, CommentLocation::AboveItem, &mut out);774 p!(&mut out, { el.value });775 let has_more = els.peek().is_some();776 if has_more {777 p!(out, str(","));778 } else {779 p!(out, if("trailing comma", multi_line, str(",")));780 }781 format_comments(&el.inline_trivia, CommentLocation::ItemInline, &mut out);782 p!(out, if_else("element separator", multi_line, nl)(sonl));783 }784 out785 }786787 let (children, end_comments) = children_between::<Expr>(788 self.syntax().clone(),789 self.l_brack_token().map(Into::into).as_ref(),790 self.r_brack_token().map(Into::into).as_ref(),791 None,792 );793 if children.is_empty() && end_comments.is_empty() {794 p!(out, str("[ ]"));795 return;796 }797798 let source_is_multiline =799 children.iter().any(|c| c.triggers_multiline) || end_comments.should_start_with_newline;800801 let start = LineNumber::new("arr start line");802 let end = LineNumber::new("arr end line");803 let multi_line: ConditionResolver = if source_is_multiline {804 true_resolver()805 } else {806 Rc::new(move |ctx: &mut ConditionResolverContext| is_multiple_lines(ctx, start, end))807 };808809 let els_items = new_line_group(gen_elements(children, multi_line.clone())).into_rc_path();810811 let els = with_indent_eoi(multi_line, els_items.into(), end_comments);812813 p!(out, str("[") info(start) items(els) str("]") info(end));814 }815}816817impl Printable for ExprBase {818 fn print(&self, out: &mut PrintItems) {819 match self {820 Self::ExprBinary(b) => {821 p!(out, {b.lhs()} str(" ") {b.binary_operator()} str(" ") {b.rhs()});822 }823 Self::ExprUnary(u) => p!(out, {u.unary_operator()} {u.rhs()}),824 // Self::ExprSlice(s) => {825 // p!(new: {s.expr()} {s.slice_desc()})826 // }827 // Self::ExprIndex(i) => {828 // p!(new: {i.expr()} str(".") {i.index()})829 // }830 // Self::ExprIndexExpr(i) => p!(new: {i.base()} str("[") {i.index()} str("]")),831 // Self::ExprApply(a) => {832 // let mut pi = p!(new: {a.expr()} {a.args_desc()});833 // if a.tailstrict_kw_token().is_some() {834 // p!(out,str(" tailstrict"));835 // }836 // pi837 // }838 Self::ExprObjExtend(ex) => {839 p!(out, {ex.lhs()} str(" ") {ex.rhs()});840 }841 Self::ExprParened(p) => {842 p!(out, str("(") {p.expr()} str(")"));843 }844 Self::ExprString(s) => p!(out, { s.text() }),845 Self::ExprNumber(n) => p!(out, { n.number() }),846 Self::ExprArray(a) => {847 p!(out, { a });848 }849 Self::ExprObject(obj) => {850 p!(out, { obj.obj_body() });851 }852 Self::ExprArrayComp(arr) => {853 p!(out, str("[") {arr.expr()});854 for spec in arr.comp_specs() {855 p!(out, str(" ") {spec});856 }857 p!(out, str("]"));858 }859 Self::ExprImport(v) => {860 p!(out, {v.import_kind()} str(" ") {v.text()});861 }862 Self::ExprVar(n) => p!(out, { n.name() }),863 // Self::ExprLocal(l) => {864 // }865 Self::ExprIfThenElse(ite) => {866 p!(out, str("if ") {ite.cond()} str(" then ") {ite.then().map(|t| t.expr())});867 if ite.else_kw_token().is_some() || ite.else_().is_some() {868 p!(out, str(" else ") {ite.else_().map(|t| t.expr())});869 }870 }871 Self::ExprFunction(f) => p!(out, str("function") {f.params_desc()} nl {f.expr()}),872 // Self::ExprAssert(a) => p!(new: {a.assertion()} str("; ") {a.expr()}),873 Self::ExprError(e) => p!(out, str("error ") {e.expr()}),874 Self::ExprLiteral(l) => {875 p!(out, { l.literal() });876 }877 }878 }879}880881impl Printable for SourceFile {882 fn print(&self, out: &mut PrintItems) {883 let before = trivia_before(884 self.syntax().clone(),885 self.expr()886 .map(|e| e.syntax().clone())887 .map(Into::into)888 .as_ref(),889 );890 let after = trivia_after(891 self.syntax().clone(),892 self.expr()893 .map(|e| e.syntax().clone())894 .map(Into::into)895 .as_ref(),896 );897 format_comments(&before, CommentLocation::AboveItem, out);898 p!(out, {self.expr()} nl);899 format_comments(&after, CommentLocation::EndOfItems, out);900 }901}902903pub struct FormatOptions {904 pub indent: u8,905 pub use_tabs: bool,906 pub max_width: u32,907}908909impl FormatOptions {910 pub fn new() -> Self {911 Self {912 indent: 4,913 use_tabs: true,914 max_width: 100,915 }916 }917}918919impl Default for FormatOptions {920 fn default() -> Self {921 Self::new()922 }923}924925#[allow(926 clippy::result_large_err,927 reason = "TODO: there should be an intermediate representation for such reports"928)]929pub fn format(input: &str, opts: &FormatOptions) -> Result<String, SnippetBuilder> {930 let (parsed, errors) = jrsonnet_rowan_parser::parse(input);931 if !errors.is_empty() {932 // Reserve one char for EOF display933 let input = format!("{input} ");934 let mut builder = hi_doc::SnippetBuilder::new(input);935 for error in errors {936 builder937 .error(hi_doc::Text::fragment(938 format!("{:?}", error.error),939 Formatting::default(),940 ))941 .range(942 error.range.start().into()943 ..=(usize::from(error.range.end()) - 1).max(error.range.start().into()),944 )945 .build();946 }947 // let snippet = builder.build();948 return Err(builder);949 // It is possible to recover from this failure, but the output may be broken, as formatter is free to skip950 // ERROR rowan nodes.951 // Recovery needs to be enabled for LSP, though.952 }953 Ok(dprint_core::formatting::format(954 || {955 let mut out = PrintItems::new();956 parsed.print(&mut out);957 out958 },959 PrintOptions {960 indent_width: opts.indent,961 max_width: opts.max_width,962 use_tabs: opts.use_tabs,963 new_line_text: "\n",964 },965 ))966}1use std::{any::type_name, rc::Rc};23use children::{children_between, trivia_before};4use dprint_core::formatting::{5 ConditionResolver, ConditionResolverContext, LineNumber, PrintItems, PrintOptions,6 condition_helpers::is_multiple_lines,7 condition_resolvers::true_resolver,8 ir_helpers::{new_line_group, with_indent},9};10use hi_doc::{Formatting, SnippetBuilder};11use jrsonnet_lexer::collect_lexed_str_block;12use jrsonnet_rowan_parser::{13 AstNode, AstToken as _, SyntaxToken,14 nodes::{15 Arg, ArgsDesc, Assertion, BinaryOperator, Bind, CompSpec, Destruct, DestructArrayPart,16 DestructRest, Expr, ExprArray, ExprBase, FieldName, ForObjSpec, ForSpec, IfSpec,17 ImportKind, Literal, Member, Name, Number, ObjBody, ObjLocal, ParamsDesc, SliceDesc,18 SourceFile, Stmt, Suffix, Text, TextKind, UnaryOperator, Visibility,19 },20};2122use crate::{23 children::{Child, EndingComments, trivia_after},24 comments::{CommentLocation, format_comments},25};2627mod children;28mod comments;29mod tests;3031fn with_indent_eoi(cond: ConditionResolver, o: PrintItems, e: EndingComments) -> PrintItems {32 let end_comments_items = {33 let mut items = PrintItems::new();34 if e.should_start_with_newline {35 p!(&mut items, nl);36 }37 format_comments(&e.trivia, CommentLocation::EndOfItems, &mut items);38 items.into_rc_path()39 };40 let items = new_line_group(pi!(@i; items(o) items(end_comments_items.into()))).into_rc_path();4142 let indented = with_indent(pi!(@i; nl items(items.into())));4344 pi!(@i; if_else("indented body", cond, items(indented))(str(" ") items(items.into())))45}4647pub trait Printable {48 fn print(&self, out: &mut PrintItems);49}5051macro_rules! pi {52 (@i; $($t:tt)*) => {{53 #[allow(unused_mut)]54 let mut o = dprint_core::formatting::PrintItems::new();55 pi!(@s; o: $($t)*);56 o57 }};58 (@s; $o:ident: str($e:expr $(,)?) $($t:tt)*) => {{59 $o.push_string($e.to_owned());60 pi!(@s; $o: $($t)*);61 }};62 (@s; $o:ident: string($e:expr $(,)?) $($t:tt)*) => {{63 $o.push_string($e);64 pi!(@s; $o: $($t)*);65 }};66 (@s; $o:ident: nl $($t:tt)*) => {{67 $o.push_signal(dprint_core::formatting::Signal::NewLine);68 pi!(@s; $o: $($t)*);69 }};70 (@s; $o:ident: sonl $($t:tt)*) => {{71 $o.push_signal(dprint_core::formatting::Signal::SpaceOrNewLine);72 pi!(@s; $o: $($t)*);73 }};74 (@s; $o:ident: tab $($t:tt)*) => {{75 $o.push_signal(dprint_core::formatting::Signal::Tab);76 pi!(@s; $o: $($t)*);77 }};78 (@s; $o:ident: >i $($t:tt)*) => {{79 $o.push_signal(dprint_core::formatting::Signal::StartIndent);80 pi!(@s; $o: $($t)*);81 }};82 (@s; $o:ident: <i $($t:tt)*) => {{83 $o.push_signal(dprint_core::formatting::Signal::FinishIndent);84 pi!(@s; $o: $($t)*);85 }};86 (@s; $o:ident: >ii $($t:tt)*) => {{87 $o.push_signal(dprint_core::formatting::Signal::StartIgnoringIndent);88 pi!(@s; $o: $($t)*);89 }};90 (@s; $o:ident: <ii $($t:tt)*) => {{91 $o.push_signal(dprint_core::formatting::Signal::FinishIgnoringIndent);92 pi!(@s; $o: $($t)*);93 }};94 (@s; $o:ident: info($v:expr) $($t:tt)*) => {{95 $o.push_info($v);96 pi!(@s; $o: $($t)*);97 }};98 (@s; $o:ident: ln_anchor($v:expr) $($t:tt)*) => {{99 $o.push_anchor(LineNumberAnchor::new($v));100 pi!(@s; $o: $($t)*);101 }};102 (@s; $o:ident: if($s:literal, $cond:expr, $($i:tt)*) $($t:tt)*) => {{103 $o.push_condition(dprint_core::formatting::conditions::if_true(104 $s,105 $cond.clone(),106 {107 let mut o = PrintItems::new();108 p!(o, $($i)*);109 o110 },111 ));112 pi!(@s; $o: $($t)*);113 }};114 (@s; $o:ident: if_else($s:literal, $cond:expr, $($i:tt)*)($($e:tt)+) $($t:tt)*) => {{115 $o.push_condition(dprint_core::formatting::conditions::if_true_or(116 $s,117 $cond.clone(),118 {119 let mut o = PrintItems::new();120 p!(o, $($i)*);121 o122 },123 {124 let mut o = PrintItems::new();125 p!(o, $($e)*);126 o127 },128 ));129 pi!(@s; $o: $($t)*);130 }};131 (@s; $o:ident: if_not($s:literal, $cond:expr, $($e:tt)*) $($t:tt)*) => {{132 $o.push_condition(dprint_core::formatting::conditions::if_true_or(133 $s,134 $cond.clone(),135 {136 let o = PrintItems::new();137 o138 },139 {140 let mut o = PrintItems::new();141 p!(o, $($e)*);142 o143 },144 ));145 pi!(@s; $o: $($t)*);146 }};147 (@s; $o:ident: {$expr:expr} $($t:tt)*) => {{148 $expr.print($o);149 pi!(@s; $o: $($t)*);150 }};151 (@s; $o:ident: items($expr:expr) $($t:tt)*) => {{152 $o.extend($expr);153 pi!(@s; $o: $($t)*);154 }};155 (@s; $o:ident: if ($e:expr)($($then:tt)*) $($t:tt)*) => {{156 if $e {157 pi!(@s; $o: $($then)*);158 }159 pi!(@s; $o: $($t)*);160 }};161 (@s; $o:ident: ifelse ($e:expr)($($then:tt)*)($($else:tt)*) $($t:tt)*) => {{162 if $e {163 pi!(@s; $o: $($then)*);164 } else {165 pi!(@s; $o: $($else)*);166 }167 pi!(@s; $o: $($t)*);168 }};169 (@s; $i:ident:) => {}170}171macro_rules! p {172 ($o:ident, $($t:tt)*) => {173 pi!(@s; $o: $($t)*)174 };175 (&mut $o:ident, $($t:tt)*) => {176 let om = &mut $o;177 pi!(@s; om: $($t)*)178 };179}180pub(crate) use p;181pub(crate) use pi;182183impl<P> Printable for Option<P>184where185 P: Printable,186{187 fn print(&self, out: &mut PrintItems) {188 if let Some(v) = self {189 v.print(out);190 } else {191 p!(192 out,193 string(format!(194 "/*missing {}*/",195 type_name::<P>().replace("jrsonnet_rowan_parser::generated::nodes::", "")196 ),)197 );198 }199 }200}201202impl Printable for SyntaxToken {203 fn print(&self, out: &mut PrintItems) {204 p!(out, string(self.to_string()));205 }206}207208impl Printable for Text {209 fn print(&self, out: &mut PrintItems) {210 if matches!(self.kind(), TextKind::StringBlock) {211 let text = self.text();212 let mut text = collect_lexed_str_block(&text[3..])213 .expect("formatting is not performed on code with parsing errors");214215 if text.truncate && text.lines.ends_with(&[""]) {216 text.truncate = false;217 text.lines.pop();218 }219220 p!(out, str("|||"));221 if text.truncate {222 p!(out, str("-"));223 }224 p!(out, nl > i);225 for ele in text.lines {226 if ele.is_empty() {227 p!(out, >ii nl <ii);228 } else {229 p!(out, string(ele.to_string()) nl);230 }231 }232 p!(out, <i str("|||"));233234 return;235 }236 p!(out, string(format!("{}", self)));237 }238}239impl Printable for Number {240 fn print(&self, out: &mut PrintItems) {241 p!(out, string(format!("{}", self)));242 }243}244245impl Printable for Name {246 fn print(&self, out: &mut PrintItems) {247 p!(out, { self.ident_lit() });248 }249}250251impl Printable for DestructRest {252 fn print(&self, out: &mut PrintItems) {253 p!(out, str("..."));254 if let Some(name) = self.into() {255 p!(out, { name });256 }257 }258}259260impl Printable for Destruct {261 fn print(&self, out: &mut PrintItems) {262 match self {263 Self::DestructFull(f) => {264 p!(out, { f.name() });265 }266 Self::DestructSkip(_) => p!(out, str("?")),267 Self::DestructArray(a) => {268 p!(out, str("[") >i nl);269 for el in a.destruct_array_parts() {270 match el {271 DestructArrayPart::DestructArrayElement(e) => {272 p!(out, {e.destruct()} str(",") nl);273 }274 DestructArrayPart::DestructRest(d) => {275 p!(out, {d} str(",") nl);276 }277 }278 }279 p!(out, <i str("]"));280 }281 Self::DestructObject(o) => {282 p!(out, str("{") >i nl);283 for item in o.destruct_object_fields() {284 p!(out, { item.field() });285 if let Some(des) = item.destruct() {286 p!(out, str(": ") {des});287 }288 if let Some(def) = item.expr() {289 p!(out, str(" = ") {def});290 }291 p!(out, str(",") nl);292 }293 if let Some(rest) = o.destruct_rest() {294 p!(out, {rest} nl);295 }296 p!(out, <i str("}"));297 }298 }299 }300}301302impl Printable for FieldName {303 fn print(&self, out: &mut PrintItems) {304 match self {305 Self::FieldNameFixed(f) => {306 if let Some(id) = f.id() {307 p!(out, { id });308 } else if let Some(str) = f.text() {309 p!(out, { str });310 } else {311 p!(out, str("/*missing FieldName*/"));312 }313 }314 Self::FieldNameDynamic(d) => {315 p!(out, str("[") {d.expr()} str("]"));316 }317 }318 }319}320321impl Printable for Visibility {322 fn print(&self, out: &mut PrintItems) {323 p!(out, string(self.to_string()));324 }325}326327impl Printable for ObjLocal {328 fn print(&self, out: &mut PrintItems) {329 p!(out, str("local ") {self.bind()});330 }331}332333impl Printable for Assertion {334 fn print(&self, out: &mut PrintItems) {335 p!(out, str("assert ") {self.condition()});336 if self.colon_token().is_some() || self.message().is_some() {337 p!(out, str(": ") {self.message()});338 }339 }340}341342impl Printable for ParamsDesc {343 fn print(&self, out: &mut PrintItems) {344 p!(out, str("(") >i nl);345 for param in self.params() {346 p!(out, { param.destruct() });347 if param.assign_token().is_some() || param.expr().is_some() {348 p!(out, str(" = ") {param.expr()});349 }350 p!(out, str(",") nl);351 }352 p!(out, <i str(")"));353 }354}355impl Printable for ArgsDesc {356 fn print(&self, out: &mut PrintItems) {357 fn gen_args(children: Vec<Child<Arg>>, multi_line: ConditionResolver) -> PrintItems {358 let mut out = PrintItems::new();359360 let mut args = children.into_iter().peekable();361 while let Some(ele) = args.next() {362 if ele.should_start_with_newline {363 p!(out, nl);364 }365 format_comments(&ele.before_trivia, CommentLocation::AboveItem, &mut out);366 let arg = ele.value;367 if arg.name().is_some() || arg.assign_token().is_some() {368 p!(&mut out, {arg.name()} str(" = "));369 }370 p!(&mut out, { arg.expr() });371 let has_more = args.peek().is_some();372 if has_more {373 p!(out, str(","));374 } else {375 p!(out, if("trailing comma", multi_line, str(",")));376 }377 format_comments(&ele.inline_trivia, CommentLocation::ItemInline, &mut out);378 if has_more {379 p!(out, if_else("arg separator", multi_line, nl)(sonl));380 }381 }382383 out384 }385386 let start = LineNumber::new("args start line");387 let end = LineNumber::new("args end line");388 let multi_line = Rc::new(move |condition_context: &mut ConditionResolverContext| {389 is_multiple_lines(condition_context, start, end)390 });391392 let (children, end_comments) = children_between::<Arg>(393 self.syntax().clone(),394 self.l_paren_token().map(Into::into).as_ref(),395 self.r_paren_token().map(Into::into).as_ref(),396 None,397 );398399 let args_items = new_line_group(gen_args(children, multi_line.clone())).into_rc_path();400 let args_indented = with_indent(pi!(@i; nl items(args_items.into())));401402 p!(out, str("(") info(start));403 p!(out, if_else("args body", multi_line, items(args_indented) nl)(items(args_items.into())));404 if end_comments.should_start_with_newline {405 p!(out, nl);406 }407 format_comments(&end_comments.trivia, CommentLocation::EndOfItems, out);408 p!(out, str(")") info(end));409 }410}411impl Printable for SliceDesc {412 fn print(&self, out: &mut PrintItems) {413 p!(out, str("["));414 if self.from().is_some() {415 p!(out, { self.from() });416 }417 p!(out, str(":"));418 if self.end().is_some() {419 p!(out, { self.end().map(|e| e.expr()) });420 }421 // Keep only one : in case if we don't need step422 if self.step().is_some() {423 p!(out, str(":") {self.step().map(|e|e.expr())});424 }425 p!(out, str("]"));426 }427}428429impl Printable for Member {430 fn print(&self, out: &mut PrintItems) {431 match self {432 Self::MemberBindStmt(b) => {433 p!(out, { b.obj_local() });434 }435 Self::MemberAssertStmt(ass) => {436 p!(out, { ass.assertion() });437 }438 Self::MemberFieldNormal(n) => {439 p!(out, {n.field_name()} if(n.plus_token().is_some())({n.plus_token()}) {n.visibility()} str(" ") {n.expr()});440 }441 Self::MemberFieldMethod(m) => {442 p!(out, {m.field_name()} {m.params_desc()} {m.visibility()} str(" ") {m.expr()});443 }444 }445 }446}447448impl Printable for ObjBody {449 #[allow(clippy::too_many_lines)]450 fn print(&self, out: &mut PrintItems) {451 match self {452 Self::ObjBodyComp(l) => {453 fn gen_obj_comp(454 members: Vec<Child<Member>>,455 member_end_comments: EndingComments,456 compspecs: Vec<Child<CompSpec>>,457 multi_line: ConditionResolver,458 ) -> PrintItems {459 let mut out = PrintItems::new();460 for mem in members {461 if mem.should_start_with_newline {462 p!(out, nl);463 }464 format_comments(&mem.before_trivia, CommentLocation::AboveItem, &mut out);465 p!(&mut out, { mem.value });466 p!(out, if("trailing comma", multi_line, str(",")));467 format_comments(&mem.inline_trivia, CommentLocation::ItemInline, &mut out);468 p!(out, if_else("member-comp sep", multi_line, nl)(sonl));469 }470471 if member_end_comments.should_start_with_newline {472 p!(out, nl);473 }474 format_comments(475 &member_end_comments.trivia,476 CommentLocation::EndOfItems,477 &mut out,478 );479480 for mem in compspecs {481 if mem.should_start_with_newline {482 p!(out, nl);483 }484 format_comments(&mem.before_trivia, CommentLocation::AboveItem, &mut out);485 p!(&mut out, { mem.value });486 format_comments(&mem.inline_trivia, CommentLocation::ItemInline, &mut out);487 p!(out, if_else("comp spec sep", multi_line, nl)(sonl));488 }489490 out491 }492493 let (children, mut end_comments) = children_between::<Member>(494 l.syntax().clone(),495 l.l_brace_token().map(Into::into).as_ref(),496 Some(497 &(l.comp_specs()498 .next()499 .expect("at least one spec is defined")500 .syntax()501 .clone())502 .into(),503 ),504 None,505 );506 let trailing_for_comp = end_comments.extract_trailing();507508 let (compspecs, comp_end_comments) = children_between::<CompSpec>(509 l.syntax().clone(),510 l.member_comps()511 .last()512 .map(|m| m.syntax().clone())513 .map(Into::into)514 .or_else(|| l.l_brace_token().map(Into::into))515 .as_ref(),516 l.r_brace_token().map(Into::into).as_ref(),517 Some(trailing_for_comp),518 );519520 let source_is_multiline = children.iter().any(|c| c.triggers_multiline)521 || compspecs.iter().any(|c| c.triggers_multiline)522 || end_comments.should_start_with_newline523 || comp_end_comments.should_start_with_newline;524525 let start = LineNumber::new("obj comp start line");526 let end = LineNumber::new("obj comp end line");527 let multi_line: ConditionResolver = if source_is_multiline {528 true_resolver()529 } else {530 Rc::new(move |ctx: &mut ConditionResolverContext| {531 is_multiple_lines(ctx, start, end)532 })533 };534535 let body = new_line_group(gen_obj_comp(536 children,537 end_comments,538 compspecs,539 multi_line.clone(),540 ))541 .into_rc_path();542543 let body = with_indent_eoi(multi_line, body.into(), comp_end_comments);544545 p!(out, str("{") info(start));546 p!(out, items(body));547 p!(out, str("}") info(end));548 }549 Self::ObjBodyMemberList(l) => {550 fn gen_members(551 children: Vec<Child<Member>>,552 multi_line: ConditionResolver,553 ) -> PrintItems {554 let mut out = PrintItems::new();555 let mut members = children.into_iter().peekable();556 while let Some(mem) = members.next() {557 if mem.should_start_with_newline {558 p!(out, nl);559 }560 format_comments(&mem.before_trivia, CommentLocation::AboveItem, &mut out);561 p!(&mut out, { mem.value });562 let has_more = members.peek().is_some();563 if has_more {564 p!(out, str(","));565 } else {566 p!(out, if("trailing comma", multi_line, str(",")));567 }568 format_comments(&mem.inline_trivia, CommentLocation::ItemInline, &mut out);569 p!(out, if_else("member separator", multi_line, nl)(sonl));570 }571 out572 }573574 let (children, end_comments) = children_between::<Member>(575 l.syntax().clone(),576 l.l_brace_token().map(Into::into).as_ref(),577 l.r_brace_token().map(Into::into).as_ref(),578 None,579 );580 if children.is_empty() && end_comments.is_empty() {581 p!(out, str("{ }"));582 return;583 }584585 let source_is_multiline = children.iter().any(|c| c.triggers_multiline)586 || end_comments.should_start_with_newline;587588 let start = LineNumber::new("obj start line");589 let end = LineNumber::new("obj end line");590 let multi_line: ConditionResolver = if source_is_multiline {591 true_resolver()592 } else {593 Rc::new(move |ctx: &mut ConditionResolverContext| {594 is_multiple_lines(ctx, start, end)595 })596 };597598 let members_items =599 new_line_group(gen_members(children, multi_line.clone())).into_rc_path();600601 let members = with_indent_eoi(multi_line, members_items.into(), end_comments);602603 p!(out, str("{") info(start));604 p!(out, items(members));605 p!(out, str("}") info(end));606 }607 }608 }609}610impl Printable for UnaryOperator {611 fn print(&self, out: &mut PrintItems) {612 p!(out, string(self.text().to_string()));613 }614}615impl Printable for BinaryOperator {616 fn print(&self, out: &mut PrintItems) {617 p!(out, string(self.text().to_string()));618 }619}620impl Printable for Bind {621 fn print(&self, out: &mut PrintItems) {622 match self {623 Self::BindDestruct(d) => {624 p!(out, {d.into()} str(" = ") {d.value()});625 }626 Self::BindFunction(f) => {627 p!(out, {f.name()} {f.params()} str(" = ") {f.value()});628 }629 }630 }631}632impl Printable for Literal {633 fn print(&self, out: &mut PrintItems) {634 p!(out, string(self.syntax().to_string()));635 }636}637impl Printable for ImportKind {638 fn print(&self, out: &mut PrintItems) {639 p!(out, string(self.syntax().to_string()));640 }641}642impl Printable for ForSpec {643 fn print(&self, out: &mut PrintItems) {644 p!(out, str("for ") {self.bind()} str(" in ") {self.expr()});645 }646}647impl Printable for ForObjSpec {648 fn print(&self, out: &mut PrintItems) {649 p!(out, str("for [") {self.key()} str("]") {self.visibility()} str(" ") {self.value()} str(" in ") {self.expr()});650 }651}652impl Printable for IfSpec {653 fn print(&self, out: &mut PrintItems) {654 p!(out, str("if ") {self.expr()});655 }656}657impl Printable for CompSpec {658 fn print(&self, out: &mut PrintItems) {659 match self {660 Self::ForSpec(f) => f.print(out),661 Self::ForObjSpec(f) => f.print(out),662 Self::IfSpec(i) => i.print(out),663 }664 }665}666impl Printable for Expr {667 fn print(&self, out: &mut PrintItems) {668 let (stmts, _ending) = children_between::<Stmt>(669 self.syntax().clone(),670 None,671 self.expr_base()672 .as_ref()673 .map(ExprBase::syntax)674 .cloned()675 .map(Into::into)676 .as_ref(),677 None,678 );679 for stmt in stmts {680 p!(out, { stmt.value });681 }682 p!(out, { self.expr_base() });683 let (suffixes, _ending) = children_between::<Suffix>(684 self.syntax().clone(),685 self.expr_base()686 .as_ref()687 .map(ExprBase::syntax)688 .cloned()689 .map(Into::into)690 .as_ref(),691 None,692 None,693 );694 for suffix in suffixes {695 p!(out, { suffix.value });696 }697 }698}699impl Printable for Suffix {700 fn print(&self, out: &mut PrintItems) {701 match self {702 Self::SuffixIndex(i) => {703 if i.question_mark_token().is_some() {704 p!(out, str("?"));705 }706 p!(out, str(".") {i.index()});707 }708 Self::SuffixIndexExpr(e) => {709 if e.question_mark_token().is_some() {710 p!(out, str(".?"));711 }712 p!(out, str("[") {e.index()} str("]"));713 }714 Self::SuffixSlice(d) => {715 p!(out, { d.slice_desc() });716 }717 Self::SuffixApply(a) => {718 p!(out, { a.args_desc() });719 }720 }721 }722}723impl Printable for Stmt {724 fn print(&self, out: &mut PrintItems) {725 match self {726 Self::StmtLocal(l) => {727 let (binds, end_comments) = children_between::<Bind>(728 l.syntax().clone(),729 l.local_kw_token().map(Into::into).as_ref(),730 l.semi_token().map(Into::into).as_ref(),731 None,732 );733 if binds.len() == 1 {734 let bind = &binds[0];735 format_comments(&bind.before_trivia, CommentLocation::AboveItem, out);736 p!(out, str("local ") {bind.value});737 // TODO: keep end_comments, child.inline_trivia somehow, force multiple locals formatting in case of presence?738 } else {739 p!(out,str("local") >i nl);740 for bind in binds {741 if bind.should_start_with_newline {742 p!(out, nl);743 }744 format_comments(&bind.before_trivia, CommentLocation::AboveItem, out);745 p!(out, {bind.value} str(","));746 format_comments(&bind.inline_trivia, CommentLocation::ItemInline, out);747 p!(out, nl);748 }749 if end_comments.should_start_with_newline {750 p!(out, nl);751 }752 format_comments(&end_comments.trivia, CommentLocation::EndOfItems, out);753 p!(out,<i);754 }755 p!(out,str(";") nl);756 }757 Self::StmtAssert(a) => {758 p!(out, {a.assertion()} str(";") nl);759 }760 }761 }762}763764impl Printable for ExprArray {765 fn print(&self, out: &mut PrintItems) {766 fn gen_elements(children: Vec<Child<Expr>>, multi_line: ConditionResolver) -> PrintItems {767 let mut out = PrintItems::new();768 let mut els = children.into_iter().peekable();769 while let Some(el) = els.next() {770 if el.should_start_with_newline {771 p!(out, nl);772 }773 format_comments(&el.before_trivia, CommentLocation::AboveItem, &mut out);774 p!(&mut out, { el.value });775 let has_more = els.peek().is_some();776 if has_more {777 p!(out, str(","));778 } else {779 p!(out, if("trailing comma", multi_line, str(",")));780 }781 format_comments(&el.inline_trivia, CommentLocation::ItemInline, &mut out);782 p!(out, if_else("element separator", multi_line, nl)(sonl));783 }784 out785 }786787 let (children, end_comments) = children_between::<Expr>(788 self.syntax().clone(),789 self.l_brack_token().map(Into::into).as_ref(),790 self.r_brack_token().map(Into::into).as_ref(),791 None,792 );793 if children.is_empty() && end_comments.is_empty() {794 p!(out, str("[ ]"));795 return;796 }797798 let source_is_multiline =799 children.iter().any(|c| c.triggers_multiline) || end_comments.should_start_with_newline;800801 let start = LineNumber::new("arr start line");802 let end = LineNumber::new("arr end line");803 let multi_line: ConditionResolver = if source_is_multiline {804 true_resolver()805 } else {806 Rc::new(move |ctx: &mut ConditionResolverContext| is_multiple_lines(ctx, start, end))807 };808809 let els_items = new_line_group(gen_elements(children, multi_line.clone())).into_rc_path();810811 let els = with_indent_eoi(multi_line, els_items.into(), end_comments);812813 p!(out, str("[") info(start) items(els) str("]") info(end));814 }815}816817impl Printable for ExprBase {818 fn print(&self, out: &mut PrintItems) {819 match self {820 Self::ExprBinary(b) => {821 p!(out, {b.lhs()} str(" ") {b.binary_operator()} str(" ") {b.rhs()});822 }823 Self::ExprUnary(u) => p!(out, {u.unary_operator()} {u.rhs()}),824 // Self::ExprSlice(s) => {825 // p!(new: {s.expr()} {s.slice_desc()})826 // }827 // Self::ExprIndex(i) => {828 // p!(new: {i.expr()} str(".") {i.index()})829 // }830 // Self::ExprIndexExpr(i) => p!(new: {i.base()} str("[") {i.index()} str("]")),831 // Self::ExprApply(a) => {832 // let mut pi = p!(new: {a.expr()} {a.args_desc()});833 // if a.tailstrict_kw_token().is_some() {834 // p!(out,str(" tailstrict"));835 // }836 // pi837 // }838 Self::ExprObjExtend(ex) => {839 p!(out, {ex.lhs()} str(" ") {ex.rhs()});840 }841 Self::ExprParened(p) => {842 p!(out, str("(") {p.expr()} str(")"));843 }844 Self::ExprString(s) => p!(out, { s.text() }),845 Self::ExprNumber(n) => p!(out, { n.number() }),846 Self::ExprArray(a) => {847 p!(out, { a });848 }849 Self::ExprObject(obj) => {850 p!(out, { obj.obj_body() });851 }852 Self::ExprArrayComp(arr) => {853 p!(out, str("[") {arr.expr()});854 for spec in arr.comp_specs() {855 p!(out, str(" ") {spec});856 }857 p!(out, str("]"));858 }859 Self::ExprImport(v) => {860 p!(out, {v.import_kind()} str(" ") {v.text()});861 }862 Self::ExprVar(n) => p!(out, { n.name() }),863 // Self::ExprLocal(l) => {864 // }865 Self::ExprIfThenElse(ite) => {866 p!(out, str("if ") {ite.cond()} str(" then ") {ite.then().map(|t| t.expr())});867 if ite.else_kw_token().is_some() || ite.else_().is_some() {868 p!(out, str(" else ") {ite.else_().map(|t| t.expr())});869 }870 }871 Self::ExprFunction(f) => p!(out, str("function") {f.params_desc()} nl {f.expr()}),872 // Self::ExprAssert(a) => p!(new: {a.assertion()} str("; ") {a.expr()}),873 Self::ExprError(e) => p!(out, str("error ") {e.expr()}),874 Self::ExprLiteral(l) => {875 p!(out, { l.literal() });876 }877 }878 }879}880881impl Printable for SourceFile {882 fn print(&self, out: &mut PrintItems) {883 let before = trivia_before(884 self.syntax().clone(),885 self.expr()886 .map(|e| e.syntax().clone())887 .map(Into::into)888 .as_ref(),889 );890 let after = trivia_after(891 self.syntax().clone(),892 self.expr()893 .map(|e| e.syntax().clone())894 .map(Into::into)895 .as_ref(),896 );897 format_comments(&before, CommentLocation::AboveItem, out);898 p!(out, {self.expr()} nl);899 format_comments(&after, CommentLocation::EndOfItems, out);900 }901}902903pub struct FormatOptions {904 pub indent: u8,905 pub use_tabs: bool,906 pub max_width: u32,907}908909impl FormatOptions {910 pub fn new() -> Self {911 Self {912 indent: 4,913 use_tabs: true,914 max_width: 100,915 }916 }917}918919impl Default for FormatOptions {920 fn default() -> Self {921 Self::new()922 }923}924925#[allow(926 clippy::result_large_err,927 reason = "TODO: there should be an intermediate representation for such reports"928)]929pub fn format(input: &str, opts: &FormatOptions) -> Result<String, SnippetBuilder> {930 let (parsed, errors) = jrsonnet_rowan_parser::parse(input);931 if !errors.is_empty() {932 // Reserve one char for EOF display933 let input = format!("{input} ");934 let mut builder = hi_doc::SnippetBuilder::new(input);935 for error in errors {936 builder937 .error(hi_doc::Text::fragment(938 format!("{:?}", error.error),939 Formatting::default(),940 ))941 .range(942 error.range.start().into()943 ..=(usize::from(error.range.end()).saturating_sub(1))944 .max(error.range.start().into()),945 )946 .build();947 }948 // let snippet = builder.build();949 return Err(builder);950 // It is possible to recover from this failure, but the output may be broken, as formatter is free to skip951 // ERROR rowan nodes.952 // Recovery needs to be enabled for LSP, though.953 }954 Ok(dprint_core::formatting::format(955 || {956 let mut out = PrintItems::new();957 parsed.print(&mut out);958 out959 },960 PrintOptions {961 indent_width: opts.indent,962 max_width: opts.max_width,963 use_tabs: opts.use_tabs,964 new_line_text: "\n",965 },966 ))967}