@@ -448,6 +448,14 @@ class InsideTableVisitor : public AstVisitor {
448448 }
449449};
450450
451+ bool canOmitDoEnd (AstStatBlock* main_stat) {
452+ if (!main_stat->body .size )
453+ return false ;
454+
455+ auto & stat = main_stat->body .data [main_stat->body .size - 1 ];
456+ return !(stat->is <AstStatReturn>() || stat->is <AstStatContinue>() || stat->is <AstStatBreak>());
457+ }
458+
451459std::optional<std::string> AstFormatter::formatExpr (AstExpr* main_expr) {
452460 std::string result;
453461 auto & main_tag = getNodeTag (main_expr);
@@ -673,14 +681,16 @@ std::optional<std::string> AstFormatter::formatStat(AstStat* main_stat) {
673681 auto condition_is_truthy = simplifier.simplify (condition).isTruthy ();
674682 if (options.optimizations && condition_is_truthy != 2 ) {
675683 if (condition_is_truthy) {
676- // NOTE: intentional `do end` to avoid double returns
677- // skip_indent = true;
678- // tagOneTrue(thenbody, no_do_end)
684+ if (canOmitDoEnd (thenbody)) {
685+ skip_indent = true ;
686+ tagOneTrue (thenbody, no_do_end)
687+ }
679688 appendNode (thenbody, " optimized stat_if->thenbody" )
680689 } else if (elsebody) {
681- // NOTE: intentional `do end` to avoid double returns
682- // skip_indent = true;
683- // tagOneTrue(elsebody, no_do_end)
690+ if (auto elsebody_as_block = elsebody->as <AstStatBlock>(); elsebody_as_block && canOmitDoEnd (elsebody_as_block)) {
691+ skip_indent = true ;
692+ tagOneTrue (elsebody, no_do_end)
693+ }
684694 appendNode (elsebody, " optimized stat_if->elsebody" )
685695 } else
686696 appendComment (result, " optimized-out if statement" ); // TODO: this exists because there's an indent; find a better fix (nodesimplifier will check optimizations and from there we can tag dont_format)
@@ -756,9 +766,11 @@ std::optional<std::string> AstFormatter::formatStat(AstStat* main_stat) {
756766 auto repeat_condition_simplified = simplifier.simplify (repeat_condition);
757767 if (options.optimizations && canSimplifyRepeatBody (main_stat_as_repeat, repeat_condition_simplified)) {
758768 // NOTE: intentional `do end`; see above if optimization
759- // skip_indent = true; // below AstStatBlock pushes indent for first stat
760- // tagOneTrue(repeat_body, no_do_end)
761- // tagOneTrue(repeat_body, skip_last_stat_separator)
769+ if (canOmitDoEnd (repeat_body)) {
770+ skip_indent = true ; // below AstStatBlock pushes indent for first stat
771+ tagOneTrue (repeat_body, no_do_end)
772+ tagOneTrue (repeat_body, skip_last_stat_separator)
773+ }
762774 appendNode (repeat_body, " stat_repeat simplified body" );
763775 } else {
764776 appendStr (result, std::string (" repeat" ).append (separators.block ));
0 commit comments