1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
#[cfg(feature = "luau")]
use full_moon::ast::types::{ElseIfExpression, IfExpression};
use full_moon::{
    ast::{
        span::ContainedSpan, BinOp, Call, Expression, Index, Prefix, Suffix, UnOp, Value, Var,
        VarExpression,
    },
    node::Node,
    tokenizer::{StringLiteralQuoteType, Symbol, Token, TokenReference, TokenType},
};
use std::boxed::Box;

#[cfg(feature = "luau")]
use crate::formatters::{luau::format_type_assertion, stmt::remove_condition_parentheses};
use crate::{
    context::{create_indent_trivia, create_newline_trivia, Context},
    fmt_symbol,
    formatters::{
        functions::{
            format_anonymous_function, format_call, format_function_call, FunctionCallNextNode,
        },
        general::{format_contained_span, format_end_token, format_token_reference, EndTokenType},
        table::format_table_constructor,
        trivia::{
            strip_leading_trivia, strip_trivia, FormatTriviaType, UpdateLeadingTrivia,
            UpdateTrailingTrivia, UpdateTrivia,
        },
        trivia_util::{
            self, contains_comments, expression_leading_comments, get_expression_trailing_trivia,
            token_contains_leading_comments, token_contains_trailing_comments, trivia_is_newline,
        },
    },
    shape::Shape,
};

#[macro_export]
macro_rules! fmt_op {
    ($ctx:expr, $enum:ident, $value:ident, $shape:expr, { $($operator:ident = $output:expr,)+ }) => {
        match $value {
            $(
                $enum::$operator(token) => $enum::$operator(fmt_symbol!($ctx, token, $output, $shape)),
            )+
            other => panic!("unknown node {:?}", other),
        }
    };
}

enum ExpressionContext {
    /// Standard expression, with no special context
    Standard,
    /// The expression originates from a [`Prefix`] node. The special context here is that the expression will
    /// always be wrapped in parentheses.
    Prefix,
}

pub fn format_binop(ctx: &Context, binop: &BinOp, shape: Shape) -> BinOp {
    fmt_op!(ctx, BinOp, binop, shape, {
        And = " and ",
        Caret = " ^ ",
        GreaterThan = " > ",
        GreaterThanEqual = " >= ",
        LessThan = " < ",
        LessThanEqual = " <= ",
        Minus = " - ",
        Or = " or ",
        Percent = " % ",
        Plus = " + ",
        Slash = " / ",
        Star = " * ",
        TildeEqual = " ~= ",
        TwoDots = " .. ",
        TwoEqual = " == ",
    })
}

/// Check to determine whether expression parentheses are required, depending on the provided
/// internal expression contained within the parentheses
fn check_excess_parentheses(internal_expression: &Expression) -> bool {
    match internal_expression {
        // Parentheses inside parentheses, not necessary
        Expression::Parentheses { .. } => true,
        // Check whether the expression relating to the UnOp is safe
        Expression::UnaryOperator { expression, .. } => check_excess_parentheses(expression),
        // Don't bother removing them if there is a binop, as they may be needed. TODO: can we be more intelligent here?
        Expression::BinaryOperator { .. } => false,
        Expression::Value {
            value,
            #[cfg(feature = "luau")]
            type_assertion,
        } => {
            // If we have a type assertion, we should always keep parentheses
            #[cfg(feature = "luau")]
            if type_assertion.is_some() {
                return false;
            }

            match &**value {
                // Internal expression is a function call
                // We could potentially be culling values, so we should not remove parentheses
                Value::FunctionCall(_) => false,
                Value::Symbol(token_ref) => {
                    match token_ref.token_type() {
                        // If we have an ellipse inside of parentheses, we may also be culling values
                        // Therefore, we don't remove parentheses
                        TokenType::Symbol { symbol } => !matches!(symbol, Symbol::Ellipse),
                        _ => true,
                    }
                }
                // If the internal expression is an if expression, we need to keep the parentheses
                // as modifying it can lead to issues [e.g. (if <x> then <expr> else <expr>) + 1 is different without parens]
                #[cfg(feature = "luau")]
                Value::IfExpression(_) => false,
                _ => true,
            }
        }
        other => panic!("unknown node {:?}", other),
    }
}

/// Formats an Expression node
pub fn format_expression(ctx: &Context, expression: &Expression, shape: Shape) -> Expression {
    format_expression_internal(ctx, expression, ExpressionContext::Standard, shape)
}

/// Internal expression formatter, with access to expression context
fn format_expression_internal(
    ctx: &Context,
    expression: &Expression,
    context: ExpressionContext,
    shape: Shape,
) -> Expression {
    match expression {
        Expression::Value {
            value,
            #[cfg(feature = "luau")]
            type_assertion,
        } => Expression::Value {
            value: Box::new(format_value(ctx, value, shape)),
            #[cfg(feature = "luau")]
            type_assertion: type_assertion
                .as_ref()
                .map(|assertion| format_type_assertion(ctx, assertion, shape)),
        },
        Expression::Parentheses {
            contained,
            expression,
        } => {
            // Examine whether the internal expression requires parentheses
            // If not, just format and return the internal expression. Otherwise, format the parentheses
            let use_internal_expression = check_excess_parentheses(expression);

            // If the context is for a prefix, we should always keep the parentheses, as they are always required
            if use_internal_expression && !matches!(context, ExpressionContext::Prefix) {
                // Get the trailing comments from contained span and append them onto the expression
                let trailing_comments = contained
                    .tokens()
                    .1
                    .trailing_trivia()
                    .filter(|token| trivia_util::trivia_is_comment(token))
                    .flat_map(|x| {
                        // Prepend a single space beforehand
                        vec![Token::new(TokenType::spaces(1)), x.to_owned()]
                    })
                    .collect();
                format_expression(ctx, expression, shape)
                    .update_trailing_trivia(FormatTriviaType::Append(trailing_comments))
            } else {
                Expression::Parentheses {
                    contained: format_contained_span(ctx, contained, shape),
                    expression: Box::new(format_expression(ctx, expression, shape + 1)), // 1 = opening parentheses
                }
            }
        }
        Expression::UnaryOperator { unop, expression } => {
            let unop = format_unop(ctx, unop, shape);
            let shape = shape + strip_leading_trivia(&unop).to_string().len();
            let mut expression = format_expression(ctx, expression, shape);

            // Special case: if we have `- -foo`, or `-(-foo)` where we have already removed the parentheses, then
            // it will lead to `--foo`, which is invalid syntax. We must explicitly add/keep the parentheses `-(-foo)`.
            if let UnOp::Minus(_) = unop {
                let require_parentheses = match expression {
                    Expression::UnaryOperator {
                        unop: UnOp::Minus(_),
                        ..
                    } => true,

                    Expression::Value { ref value, .. } => matches!(
                        **value,
                        Value::ParenthesesExpression(Expression::UnaryOperator {
                            unop: UnOp::Minus(_),
                            ..
                        })
                    ),

                    _ => false,
                };

                if require_parentheses {
                    let (new_expression, trailing_comments) =
                        trivia_util::take_expression_trailing_comments(&expression);
                    expression = Expression::Parentheses {
                        contained: ContainedSpan::new(
                            TokenReference::symbol("(").unwrap(),
                            TokenReference::symbol(")").unwrap(),
                        )
                        .update_trailing_trivia(FormatTriviaType::Append(trailing_comments)),
                        expression: Box::new(new_expression),
                    }
                }
            }

            Expression::UnaryOperator {
                unop,
                expression: Box::new(expression),
            }
        }
        Expression::BinaryOperator { lhs, binop, rhs } => {
            let lhs = format_expression(ctx, lhs, shape);
            let binop = format_binop(ctx, binop, shape);
            let shape = shape.take_last_line(&lhs) + binop.to_string().len();
            Expression::BinaryOperator {
                lhs: Box::new(lhs),
                binop,
                rhs: Box::new(format_expression(ctx, rhs, shape)),
            }
        }
        other => panic!("unknown node {:?}", other),
    }
}

/// Determines whether the provided [`Expression`] is a brackets string, i.e. `[[string]]`
pub fn is_brackets_string(expression: &Expression) -> bool {
    if let Expression::Value { value, .. } = expression {
        if let Value::String(token_reference) = &**value {
            return matches!(
                token_reference.token_type(),
                TokenType::StringLiteral {
                    quote_type: StringLiteralQuoteType::Brackets,
                    ..
                }
            );
        }
    }
    false
}

/// Formats an Index Node
pub fn format_index(ctx: &Context, index: &Index, shape: Shape) -> Index {
    match index {
        Index::Brackets {
            brackets,
            expression,
        } => {
            if token_contains_trailing_comments(brackets.tokens().0)
                || contains_comments(expression)
                || token_contains_leading_comments(brackets.tokens().1)
            {
                let (start_bracket, end_bracket) = brackets.tokens();

                let indent_shape = shape.reset().increment_additional_indent();

                // Format the brackets multiline
                let brackets = ContainedSpan::new(
                    fmt_symbol!(ctx, start_bracket, "[", shape).update_trailing_trivia(
                        FormatTriviaType::Append(vec![
                            create_newline_trivia(ctx),
                            create_indent_trivia(ctx, indent_shape),
                        ]),
                    ),
                    format_end_token(ctx, end_bracket, EndTokenType::ClosingBrace, shape)
                        .update_leading_trivia(FormatTriviaType::Append(vec![
                            create_indent_trivia(ctx, shape),
                        ])),
                );

                let expression = format_expression(ctx, expression, indent_shape)
                    .update_trailing_trivia(FormatTriviaType::Append(vec![create_newline_trivia(
                        ctx,
                    )]));

                Index::Brackets {
                    brackets,
                    expression,
                }
            } else if is_brackets_string(expression) {
                Index::Brackets {
                    brackets: format_contained_span(ctx, brackets, shape),
                    expression: format_expression(ctx, expression, shape + 2) // 2 = "[ "
                        .update_leading_trivia(FormatTriviaType::Append(vec![Token::new(
                            TokenType::spaces(1),
                        )]))
                        .update_trailing_trivia(FormatTriviaType::Append(vec![Token::new(
                            TokenType::spaces(1),
                        )])),
                }
            } else {
                Index::Brackets {
                    brackets: format_contained_span(ctx, brackets, shape),
                    expression: format_expression(ctx, expression, shape + 1), // 1 = opening bracket
                }
            }
        }

        Index::Dot { dot, name } => Index::Dot {
            dot: format_token_reference(ctx, dot, shape),
            name: format_token_reference(ctx, name, shape),
        },
        other => panic!("unknown node {:?}", other),
    }
}

/// Formats a Prefix Node
pub fn format_prefix(ctx: &Context, prefix: &Prefix, shape: Shape) -> Prefix {
    match prefix {
        Prefix::Expression(expression) => {
            let singleline_format =
                format_expression_internal(ctx, expression, ExpressionContext::Prefix, shape);
            let singeline_shape = shape.take_first_line(&strip_trivia(&singleline_format));

            if singeline_shape.over_budget() {
                Prefix::Expression(format_hanging_expression_(
                    ctx,
                    expression,
                    shape,
                    ExpressionContext::Prefix,
                    None,
                ))
            } else {
                Prefix::Expression(singleline_format)
            }
        }
        Prefix::Name(token_reference) => {
            Prefix::Name(format_token_reference(ctx, token_reference, shape))
        }
        other => panic!("unknown node {:?}", other),
    }
}

/// Formats a Suffix Node
pub fn format_suffix(
    ctx: &Context,
    suffix: &Suffix,
    shape: Shape,
    call_next_node: FunctionCallNextNode,
) -> Suffix {
    match suffix {
        Suffix::Call(call) => Suffix::Call(format_call(ctx, call, shape, call_next_node)),
        Suffix::Index(index) => Suffix::Index(format_index(ctx, index, shape)),
        other => panic!("unknown node {:?}", other),
    }
}

/// Formats and else if expression onto a single line.
/// This function does not take into account for comments
#[cfg(feature = "luau")]
fn format_else_if_expression_singleline(
    ctx: &Context,
    else_if_expression: &ElseIfExpression,
    shape: Shape,
) -> ElseIfExpression {
    let else_if_token = fmt_symbol!(ctx, else_if_expression.else_if_token(), "elseif ", shape);
    let else_if_condition = remove_condition_parentheses(else_if_expression.condition().to_owned());
    let else_if_condition = format_expression(ctx, &else_if_condition, shape + 7); // 7 = "elseif "
    let (then_token, expression) = format_token_expression_sequence(
        ctx,
        else_if_expression.then_token(),
        else_if_expression.expression(),
        shape.take_first_line(&else_if_condition) + 13, // 13 = "elseif " + " then ",
    );

    // Add a space before the then token
    let then_token = then_token.update_leading_trivia(FormatTriviaType::Append(vec![Token::new(
        TokenType::spaces(1),
    )]));

    ElseIfExpression::new(else_if_condition, expression)
        .with_else_if_token(else_if_token)
        .with_then_token(then_token)
}

/// Formats a `<token> <expr>` sequence, such as `then <expr>` or `else <expr>`.
/// In particular, this handles when the <expr> has to be formatted onto multiple lines (either due to comments, or going over width)
#[cfg(feature = "luau")]
fn format_token_expression_sequence(
    ctx: &Context,
    token: &TokenReference,
    expression: &Expression,
    shape: Shape,
) -> (TokenReference, Expression) {
    let formatted_expression = format_expression(ctx, expression, shape);

    let requires_multiline_expression = shape.take_first_line(&formatted_expression).over_budget()
        || trivia_util::token_contains_trailing_comments(token)
        || trivia_util::contains_comments(expression);

    let token = match requires_multiline_expression {
        // `<token>\n`
        true => format_token_reference(ctx, token, shape)
            .update_trailing_trivia(FormatTriviaType::Append(vec![create_newline_trivia(ctx)])),
        // `<token> `
        false => format_token_reference(ctx, token, shape).update_trailing_trivia(
            FormatTriviaType::Append(vec![Token::new(TokenType::spaces(1))]),
        ),
    };

    let expression = match requires_multiline_expression {
        true => {
            let shape = shape.reset().increment_additional_indent();
            hang_expression(ctx, expression, shape, None).update_leading_trivia(
                FormatTriviaType::Append(vec![create_indent_trivia(ctx, shape)]),
            )
        }
        false => formatted_expression,
    };

    (token, expression)
}

/// Formats an [`IfExpression`] node
#[cfg(feature = "luau")]
fn format_if_expression(ctx: &Context, if_expression: &IfExpression, shape: Shape) -> IfExpression {
    // Remove parentheses around the condition
    let condition = remove_condition_parentheses(if_expression.condition().to_owned());
    let if_token = fmt_symbol!(ctx, if_expression.if_token(), "if ", shape);

    // Initially format the remainder on a single line
    let singleline_condition = format_expression(ctx, &condition, shape.with_infinite_width());
    let then_token = fmt_symbol!(ctx, if_expression.then_token(), " then ", shape);
    let singleline_expression = format_expression(
        ctx,
        if_expression.if_expression(),
        shape.with_infinite_width(),
    );
    let else_ifs = if_expression
        .else_if_expressions()
        .map(|else_if_expressions| {
            else_if_expressions
                .iter()
                .map(|else_if_expression| {
                    format_else_if_expression_singleline(
                        ctx,
                        else_if_expression,
                        shape.with_infinite_width(),
                    )
                })
                .collect::<Vec<_>>()
        });
    let else_token = fmt_symbol!(ctx, if_expression.else_token(), " else ", shape);
    let singleline_else_expression = format_expression(
        ctx,
        if_expression.else_expression(),
        shape.with_infinite_width(),
    );

    const IF_LENGTH: usize = 3; // "if "
    const THEN_LENGTH: usize = 6; // " then "
    const ELSE_LENGTH: usize = 6; // " else "

    // Determine if we need to hang the expression
    let singleline_shape = (shape + IF_LENGTH + THEN_LENGTH + ELSE_LENGTH)
        .take_first_line(&strip_trivia(&singleline_condition))
        .take_first_line(&strip_trivia(&singleline_expression))
        .take_first_line(&else_ifs.as_ref().map_or(String::new(), |x| {
            x.iter().map(|x| x.to_string()).collect::<String>()
        }))
        .take_first_line(&strip_trivia(&singleline_else_expression));

    let require_multiline_expression = singleline_shape.over_budget()
        || trivia_util::token_contains_trailing_comments(if_expression.if_token())
        || trivia_util::contains_comments(if_expression.condition())
        || trivia_util::contains_comments(if_expression.then_token())
        || trivia_util::contains_comments(if_expression.if_expression())
        || trivia_util::contains_comments(if_expression.else_token())
        || if_expression
            .else_if_expressions()
            .map_or(false, |else_ifs| {
                else_ifs.iter().any(trivia_util::contains_comments)
            })
        || trivia_util::expression_contains_inline_comments(if_expression.else_expression())
        || trivia_util::spans_multiple_lines(&singleline_condition)
        || trivia_util::spans_multiple_lines(&singleline_expression)
        || else_ifs.as_ref().map_or(false, |else_ifs| {
            else_ifs.iter().any(trivia_util::spans_multiple_lines)
        })
        || trivia_util::spans_multiple_lines(&singleline_else_expression);

    if require_multiline_expression {
        let condition = hang_expression_trailing_newline(
            ctx,
            if_expression.condition(),
            shape.increment_additional_indent(),
            Some(1),
        );
        let hanging_shape = shape.reset().increment_additional_indent();

        // then <expr>
        let (then_token, expression) = format_token_expression_sequence(
            ctx,
            if_expression.then_token(),
            if_expression.if_expression(),
            hanging_shape,
        );

        // Indent the then token
        let then_token =
            then_token.update_leading_trivia(FormatTriviaType::Append(vec![create_indent_trivia(
                ctx,
                hanging_shape,
            )]));

        // elseif <condition> then <expr>
        let else_ifs = if_expression
            .else_if_expressions()
            .map(|else_if_expressions| {
                else_if_expressions
                    .iter()
                    .map(|else_if_expression| {
                        let singleline_else_if = format_else_if_expression_singleline(
                            ctx,
                            else_if_expression,
                            hanging_shape,
                        );
                        let singleline_shape = hanging_shape.take_first_line(&singleline_else_if);

                        if singleline_shape.over_budget()
                            || trivia_util::token_contains_trailing_comments(
                                else_if_expression.else_if_token(),
                            )
                            || trivia_util::contains_comments(else_if_expression.condition())
                            || trivia_util::contains_comments(else_if_expression.then_token())
                        {
                            let else_if_token = fmt_symbol!(
                                ctx,
                                else_if_expression.else_if_token(),
                                "elseif",
                                shape
                            )
                            .update_leading_trivia(FormatTriviaType::Append(vec![
                                create_newline_trivia(ctx),
                                create_indent_trivia(ctx, hanging_shape),
                            ]));

                            let condiiton_shape =
                                hanging_shape.reset().increment_additional_indent();
                            let else_if_condition = hang_expression(
                                ctx,
                                &remove_condition_parentheses(
                                    else_if_expression.condition().to_owned(),
                                ),
                                condiiton_shape,
                                None,
                            )
                            .update_leading_trivia(FormatTriviaType::Append(vec![
                                create_newline_trivia(ctx),
                                create_indent_trivia(ctx, condiiton_shape),
                            ]));

                            let hanging_shape =
                                hanging_shape.take_first_line(&else_if_condition) + 13; // 13 = "elseif " + " then "

                            let (then_token, expression) = format_token_expression_sequence(
                                ctx,
                                else_if_expression.then_token(),
                                else_if_expression.expression(),
                                hanging_shape,
                            );

                            let then_token =
                                then_token.update_leading_trivia(FormatTriviaType::Append(vec![
                                    create_newline_trivia(ctx),
                                    create_indent_trivia(ctx, hanging_shape),
                                ]));

                            ElseIfExpression::new(else_if_condition, expression)
                                .with_else_if_token(else_if_token)
                                .with_then_token(then_token)
                        } else {
                            singleline_else_if.update_leading_trivia(FormatTriviaType::Append(
                                vec![
                                    create_newline_trivia(ctx),
                                    create_indent_trivia(ctx, hanging_shape),
                                ],
                            ))
                        }
                    })
                    .collect::<Vec<_>>()
            });

        // else <expr>
        let (else_token, else_expression) = format_token_expression_sequence(
            ctx,
            if_expression.else_token(),
            if_expression.else_expression(),
            hanging_shape + 5, // 5 = "else "
        );

        // Put the else on a new line
        let else_token = else_token.update_leading_trivia(FormatTriviaType::Append(vec![
            create_newline_trivia(ctx),
            create_indent_trivia(ctx, hanging_shape),
        ]));

        IfExpression::new(condition, expression, else_expression)
            .with_if_token(if_token)
            .with_then_token(then_token)
            .with_else_if(else_ifs)
            .with_else_token(else_token)
    } else {
        // Prepend a space before each else if
        let else_ifs = else_ifs.map(|x| {
            x.iter()
                .map(|x| {
                    x.update_leading_trivia(FormatTriviaType::Append(vec![Token::new(
                        TokenType::spaces(1),
                    )]))
                })
                .collect()
        });

        IfExpression::new(
            singleline_condition,
            singleline_expression,
            singleline_else_expression,
        )
        .with_if_token(if_token)
        .with_then_token(then_token)
        .with_else_if(else_ifs)
        .with_else_token(else_token)
    }
}

/// Formats a Value Node
pub fn format_value(ctx: &Context, value: &Value, shape: Shape) -> Value {
    match value {
        Value::Function((token_reference, function_body)) => Value::Function(
            format_anonymous_function(ctx, token_reference, function_body, shape),
        ),
        Value::FunctionCall(function_call) => {
            Value::FunctionCall(format_function_call(ctx, function_call, shape))
        }
        #[cfg(feature = "luau")]
        Value::IfExpression(if_expression) => {
            Value::IfExpression(format_if_expression(ctx, if_expression, shape))
        }
        Value::Number(token_reference) => {
            Value::Number(format_token_reference(ctx, token_reference, shape))
        }
        Value::ParenthesesExpression(expression) => {
            Value::ParenthesesExpression(format_expression(ctx, expression, shape))
        }
        Value::String(token_reference) => {
            Value::String(format_token_reference(ctx, token_reference, shape))
        }
        Value::Symbol(token_reference) => {
            Value::Symbol(format_token_reference(ctx, token_reference, shape))
        }
        Value::TableConstructor(table_constructor) => {
            Value::TableConstructor(format_table_constructor(ctx, table_constructor, shape))
        }
        Value::Var(var) => Value::Var(format_var(ctx, var, shape)),
        other => panic!("unknown node {:?}", other),
    }
}

/// Formats a Var Node
pub fn format_var(ctx: &Context, var: &Var, shape: Shape) -> Var {
    match var {
        Var::Name(token_reference) => {
            Var::Name(format_token_reference(ctx, token_reference, shape))
        }
        Var::Expression(var_expression) => {
            Var::Expression(format_var_expression(ctx, var_expression, shape))
        }
        other => panic!("unknown node {:?}", other),
    }
}

pub fn format_var_expression(
    ctx: &Context,
    var_expression: &VarExpression,
    shape: Shape,
) -> VarExpression {
    let formatted_prefix = format_prefix(ctx, var_expression.prefix(), shape);
    let mut shape = shape + strip_leading_trivia(&formatted_prefix).to_string().len();

    let mut formatted_suffixes = Vec::new();
    let mut suffixes = var_expression.suffixes().peekable();

    while let Some(suffix) = suffixes.next() {
        // If the suffix after this one is something like `.foo` or `:foo` - this affects removing parentheses
        let ambiguous_next_suffix = if matches!(
            suffixes.peek(),
            Some(Suffix::Index(_)) | Some(Suffix::Call(Call::MethodCall(_)))
        ) {
            FunctionCallNextNode::ObscureWithoutParens
        } else {
            FunctionCallNextNode::None
        };

        let suffix = format_suffix(ctx, suffix, shape, ambiguous_next_suffix);
        shape = shape.take_last_line(&suffix);
        formatted_suffixes.push(suffix);
    }

    VarExpression::new(formatted_prefix).with_suffixes(formatted_suffixes)
}

/// Formats an UnOp Node
pub fn format_unop(ctx: &Context, unop: &UnOp, shape: Shape) -> UnOp {
    fmt_op!(ctx, UnOp, unop, shape, {
        Minus = "-",
        Not = "not ",
        Hash = "#",
    })
}

/// Pushes a [`BinOp`] onto a newline, and indent its depending on indent_level.
/// Preserves any leading comments, and moves trailing comments to before the BinOp.
/// Also takes in the [`Expression`] present on the RHS of the BinOp - this is needed so that we can take any
/// leading comments from the expression, and place them before the BinOp.
fn hang_binop(ctx: &Context, binop: BinOp, shape: Shape, rhs: &Expression) -> BinOp {
    // Get the leading comments of a binop, as we need to preserve them
    // Intersperse a newline and indent trivia between them
    // iter_intersperse is currently not available, so we need to do something different. Tracking issue: https://github.com/rust-lang/rust/issues/79524
    let mut leading_comments = trivia_util::binop_leading_comments(&binop)
        .iter()
        .flat_map(|x| {
            vec![
                create_newline_trivia(ctx),
                create_indent_trivia(ctx, shape),
                x.to_owned(),
            ]
        })
        .collect::<Vec<_>>();

    // If there are any comments trailing the BinOp, we need to move them to before the BinOp
    let mut trailing_comments = trivia_util::binop_trailing_comments(&binop);
    leading_comments.append(&mut trailing_comments);

    // If there are any leading comments to the RHS expression, we need to move them to before the BinOp
    let mut expression_leading_comments = trivia_util::expression_leading_comments(rhs)
        .iter()
        .flat_map(|x| {
            vec![
                create_newline_trivia(ctx),
                create_indent_trivia(ctx, shape),
                x.to_owned(),
            ]
        })
        .collect::<Vec<_>>();
    leading_comments.append(&mut expression_leading_comments);

    // Create a newline just before the BinOp, and preserve the indentation
    leading_comments.push(create_newline_trivia(ctx));
    leading_comments.push(create_indent_trivia(ctx, shape));

    binop.update_trivia(
        FormatTriviaType::Replace(leading_comments),
        FormatTriviaType::Replace(vec![Token::new(TokenType::spaces(1))]),
    )
}

/// Finds the length of the expression which matches the precedence level of the provided binop
fn binop_expression_length(expression: &Expression, top_binop: &BinOp) -> usize {
    match expression {
        Expression::BinaryOperator { lhs, binop, rhs } => {
            if binop.precedence() >= top_binop.precedence()
                && binop.is_right_associative() == top_binop.is_right_associative()
            {
                if binop.is_right_associative() {
                    binop_expression_length(rhs, top_binop)
                        + strip_trivia(binop).to_string().len() + 2 // 2 = space before and after binop
                        + strip_trivia(&**lhs).to_string().len()
                } else {
                    binop_expression_length(lhs, top_binop)
                        + strip_trivia(binop).to_string().len() + 2 // 2 = space before and after binop
                        + strip_trivia(&**rhs).to_string().len()
                }
            } else {
                0
            }
        }
        _ => strip_trivia(expression).to_string().len(),
    }
}

fn binop_expression_contains_comments(expression: &Expression, top_binop: &BinOp) -> bool {
    match expression {
        Expression::BinaryOperator { lhs, binop, rhs } => {
            if binop.precedence() == top_binop.precedence() {
                contains_comments(binop)
                    || !expression_leading_comments(rhs).is_empty()
                    || get_expression_trailing_trivia(lhs)
                        .iter()
                        .any(trivia_util::trivia_is_comment)
                    || binop_expression_contains_comments(lhs, top_binop)
                    || binop_expression_contains_comments(rhs, top_binop)
            } else {
                false
            }
        }
        _ => false,
    }
}

/// Converts an item to a range
trait ToRange {
    fn to_range(&self) -> (usize, usize);
}

impl ToRange for (usize, usize) {
    fn to_range(&self) -> (usize, usize) {
        *self
    }
}

impl ToRange for Expression {
    fn to_range(&self) -> (usize, usize) {
        let (start, end) = self.range().unwrap();
        (start.bytes(), end.bytes())
    }
}

/// This struct encompasses information about the leftmost-expression in a BinaryExpression tree.
/// It holds the range of the leftmost binary expression, and the original additional indent level of this range.
/// This struct is only used when the hanging binary expression involves a hang level, for example:
/// ```lua
/// foooo
///    + bar
///    + baz
/// ```
/// or in a larger context:
/// ```lua
/// local someVariable = foooo
///    + bar
///    + baz
/// ```
/// As seen, the first item (`foooo`) is inlined, and has an indent level one lower than the rest of the binary
/// expressions. We want to ensure that whenever we have `foooo` in our expression, we use the original indentation level
/// because the expression is (at this current point in time) inlined - otherwise, it will be over-indented.
/// We hold the original indentation level incase we are deep down in the recursivecalls:
/// ```lua
/// local ratio = (minAxis - minAxisSize) / delta * (self.props.maxScaleRatio - self.props.minScaleRatio)
///     + self.props.minScaleRatio
/// ```
/// Since the first line contains binary operators at a different precedence level to the `+`, then the indentation
/// level has been increased even further. But we want to use the original indentation level, because as it stands,
/// the expression is currently inlined on the original line.
#[derive(Clone, Copy, Debug)]
struct LeftmostRangeHang {
    range: (usize, usize),
    original_additional_indent_level: usize,
}

impl LeftmostRangeHang {
    /// Finds the leftmost expression from the given (full) expression, and then creates a [`LeftmostRangeHang`]
    /// to represent it
    fn find(expression: &Expression, original_additional_indent_level: usize) -> Self {
        match expression {
            Expression::BinaryOperator { lhs, .. } => {
                Self::find(lhs, original_additional_indent_level)
            }
            _ => Self {
                range: expression.to_range(),
                original_additional_indent_level,
            },
        }
    }

    /// Given an [`Expression`], returns the [`Shape`] to use for this expression.
    /// This function checks the provided expression to see if the LeftmostRange falls inside of it.
    /// If so, then we need to use the original indentation level shape, as (so far) the expression is inlined.
    fn required_shape<T: ToRange>(&self, shape: Shape, item: &T) -> Shape {
        let (expression_start, expression_end) = item.to_range();
        let (lhs_start, lhs_end) = self.range;

        if lhs_start >= expression_start && lhs_end <= expression_end {
            shape.with_indent(
                shape
                    .indent()
                    .with_additional_indent(self.original_additional_indent_level),
            )
        } else {
            shape
        }
    }
}

fn is_hang_binop_over_width(
    shape: Shape,
    expression: &Expression,
    top_binop: &BinOp,
    lhs_range: Option<LeftmostRangeHang>,
) -> bool {
    let shape = if let Some(lhs_hang) = lhs_range {
        lhs_hang.required_shape(shape, expression)
    } else {
        shape
    };

    shape
        .add_width(binop_expression_length(expression, top_binop))
        .over_budget()
}

/// If present, finds the precedence level of the provided binop in the BinOp expression. Otherwise, returns 0
fn binop_precedence_level(expression: &Expression) -> u8 {
    match expression {
        Expression::BinaryOperator { binop, .. } => binop.precedence(),
        _ => 0,
    }
}

fn did_hang_expression(expression: &Expression) -> bool {
    if let Expression::BinaryOperator { binop, .. } = expression {
        // Examine the binop's leading trivia for a newline
        // TODO: this works..., but is it the right solution?
        binop
            .surrounding_trivia()
            .0
            .iter()
            .any(|x| trivia_is_newline(x))
    } else {
        false
    }
}

#[derive(Debug)]
enum ExpressionSide {
    Left,
    Right,
}

fn hang_binop_expression(
    ctx: &Context,
    expression: Expression,
    top_binop: BinOp,
    shape: Shape,
    lhs_range: Option<LeftmostRangeHang>,
) -> Expression {
    let full_expression = expression.to_owned();

    match expression {
        Expression::BinaryOperator { lhs, binop, rhs } => {
            // Keep grouping together all operators with the same precedence level as the main BinOp
            // They should also have the same associativity
            let same_op_level = binop.precedence() == top_binop.precedence()
                && binop.is_right_associative() == top_binop.is_right_associative();
            let is_right_associative = binop.is_right_associative();

            let test_shape = if same_op_level {
                shape
            } else {
                shape.increment_additional_indent()
            };

            let side_to_hang = if is_right_associative {
                ExpressionSide::Right
            } else {
                ExpressionSide::Left
            };

            // TODO/FIXME: using test_shape here leads to too high of an indent level, causing the expression to hang unnecessarily
            let over_column_width =
                is_hang_binop_over_width(test_shape, &full_expression, &binop, lhs_range);
            let should_hang = same_op_level
                || over_column_width
                || binop_expression_contains_comments(&full_expression, &binop);

            // Only use the indented shape if we are planning to hang
            let shape = if should_hang { test_shape } else { shape };

            let mut new_binop = format_binop(ctx, &binop, shape);
            if should_hang {
                new_binop = hang_binop(ctx, binop.to_owned(), shape, &rhs);
            }

            let (lhs, rhs) = match should_hang {
                true => {
                    let lhs_shape = shape;
                    let rhs_shape = shape + strip_trivia(&new_binop).to_string().len() + 1;

                    let (lhs, rhs) = match side_to_hang {
                        ExpressionSide::Left => (
                            hang_binop_expression(
                                ctx,
                                *lhs,
                                if same_op_level { top_binop } else { binop },
                                lhs_shape,
                                lhs_range,
                            ),
                            format_expression(ctx, &*rhs, rhs_shape),
                        ),
                        ExpressionSide::Right => (
                            format_expression(ctx, &*lhs, lhs_shape),
                            hang_binop_expression(
                                ctx,
                                *rhs,
                                if same_op_level { top_binop } else { binop },
                                rhs_shape,
                                lhs_range,
                            ),
                        ),
                    };
                    (
                        lhs,
                        rhs.update_leading_trivia(FormatTriviaType::Replace(Vec::new())),
                    )
                }
                false => {
                    // Check if the chain still has comments deeper inside of it.
                    // If it does, we need to hang that part of the chain still, otherwise the comments will mess it up
                    let lhs = if contains_comments(&*lhs) {
                        hang_binop_expression(ctx, *lhs, binop.to_owned(), shape, lhs_range)
                    } else {
                        format_expression(ctx, &*lhs, shape)
                    };

                    let rhs = if contains_comments(&*rhs) {
                        hang_binop_expression(ctx, *rhs, binop, shape, lhs_range)
                    } else {
                        format_expression(ctx, &*rhs, shape)
                    };

                    (lhs, rhs)
                }
            };

            Expression::BinaryOperator {
                lhs: Box::new(lhs),
                binop: new_binop,
                rhs: Box::new(rhs),
            }
        }
        // Base case: no more binary operators - just return to normal splitting
        _ => format_hanging_expression_(
            ctx,
            &expression,
            shape,
            ExpressionContext::Standard,
            lhs_range,
        ),
    }
}

/// Internal expression formatter, where the binop is also hung
fn format_hanging_expression_(
    ctx: &Context,
    expression: &Expression,
    shape: Shape,
    expression_context: ExpressionContext,
    lhs_range: Option<LeftmostRangeHang>,
) -> Expression {
    let expression_range = expression.to_range();

    match expression {
        Expression::Value {
            value,
            #[cfg(feature = "luau")]
            type_assertion,
        } => {
            let value = Box::new(match &**value {
                Value::ParenthesesExpression(expression) => {
                    Value::ParenthesesExpression(format_hanging_expression_(
                        ctx,
                        expression,
                        shape,
                        expression_context,
                        lhs_range,
                    ))
                }
                _ => {
                    let shape = if let Some(lhs_hang) = lhs_range {
                        lhs_hang.required_shape(shape, &expression_range)
                    } else {
                        shape
                    };
                    format_value(ctx, value, shape)
                }
            });
            Expression::Value {
                value,
                #[cfg(feature = "luau")]
                type_assertion: type_assertion
                    .as_ref()
                    .map(|assertion| format_type_assertion(ctx, assertion, shape)),
            }
        }
        Expression::Parentheses {
            contained,
            expression,
        } => {
            let lhs_shape = if let Some(lhs_hang) = lhs_range {
                lhs_hang.required_shape(shape, &expression_range)
            } else {
                shape
            };

            // Examine whether the internal expression requires parentheses
            // If not, just format and return the internal expression. Otherwise, format the parentheses
            let use_internal_expression = check_excess_parentheses(expression);

            // If the context is for a prefix, we should always keep the parentheses, as they are always required
            if use_internal_expression && !matches!(expression_context, ExpressionContext::Prefix) {
                format_hanging_expression_(
                    ctx,
                    expression,
                    lhs_shape,
                    expression_context,
                    lhs_range,
                )
            } else {
                let contained = format_contained_span(ctx, contained, lhs_shape);

                // Provide a sample formatting to see how large it is
                // Examine the expression itself to see if needs to be split onto multiple lines
                let formatted_expression = format_expression(ctx, expression, lhs_shape + 1); // 1 = opening parentheses

                let expression_str = formatted_expression.to_string();
                if !lhs_shape.add_width(2 + expression_str.len()).over_budget() {
                    // The expression inside the parentheses is small, we do not need to break it down further
                    return Expression::Parentheses {
                        contained,
                        expression: Box::new(formatted_expression),
                    };
                }

                // Update the expression shape to be used inside the parentheses, applying the indent increase
                // Use the original `shape` rather than the LeftmostRangeHang-determined shape, because we are now
                // indenting the internal expression, which is not part of the hang
                let expression_shape = shape.reset().increment_additional_indent();

                // Modify the parentheses to hang the expression
                let (start_token, end_token) = contained.tokens();

                // Create a newline after the start brace and before the end brace
                // Also, indent enough for the first expression in the start brace
                let contained = ContainedSpan::new(
                    start_token.update_trailing_trivia(FormatTriviaType::Append(vec![
                        create_newline_trivia(ctx),
                        create_indent_trivia(ctx, expression_shape),
                    ])),
                    end_token.update_leading_trivia(FormatTriviaType::Append(vec![
                        create_newline_trivia(ctx),
                        create_indent_trivia(ctx, shape),
                    ])),
                );

                Expression::Parentheses {
                    contained,
                    expression: Box::new(format_hanging_expression_(
                        ctx,
                        expression,
                        expression_shape,
                        ExpressionContext::Standard,
                        None,
                    )),
                }
            }
        }
        Expression::UnaryOperator { unop, expression } => {
            let unop = format_unop(ctx, unop, shape);
            let shape = shape + strip_leading_trivia(&unop).to_string().len();
            let expression =
                format_hanging_expression_(ctx, expression, shape, expression_context, lhs_range);

            Expression::UnaryOperator {
                unop,
                expression: Box::new(expression),
            }
        }
        Expression::BinaryOperator { lhs, binop, rhs } => {
            // Don't format the lhs and rhs here, because it will be handled later when hang_binop_expression calls back for a Value
            let lhs =
                hang_binop_expression(ctx, *lhs.to_owned(), binop.to_owned(), shape, lhs_range);

            let current_shape = shape.take_last_line(&lhs) + 1; // 1 = space before binop
            let mut new_binop = format_binop(ctx, binop, current_shape);

            let singleline_shape = current_shape + strip_trivia(binop).to_string().len() + 1; // 1 = space after binop

            let mut new_rhs = hang_binop_expression(
                ctx,
                *rhs.to_owned(),
                binop.to_owned(),
                singleline_shape,
                None,
            );

            // Examine the last line to see if we need to hang this binop, or if the precedence levels match
            if (did_hang_expression(&lhs) && binop_precedence_level(&lhs) >= binop.precedence())
                || (did_hang_expression(&new_rhs)
                    && binop_precedence_level(&new_rhs) >= binop.precedence())
                || contains_comments(binop)
                || get_expression_trailing_trivia(&lhs)
                    .iter()
                    .any(trivia_util::trivia_is_comment)
                || (shape.take_last_line(&lhs) + format!("{}{}", binop, rhs).len()).over_budget()
            {
                let hanging_shape = shape.reset() + strip_trivia(binop).to_string().len() + 1;
                new_binop = hang_binop(ctx, binop.to_owned(), shape, rhs);
                new_rhs = hang_binop_expression(
                    ctx,
                    *rhs.to_owned(),
                    binop.to_owned(),
                    hanging_shape,
                    None,
                )
                .update_leading_trivia(FormatTriviaType::Replace(Vec::new()));
            }

            Expression::BinaryOperator {
                lhs: Box::new(lhs),
                binop: new_binop,
                rhs: Box::new(new_rhs),
            }
        }
        other => panic!("unknown node {:?}", other),
    }
}

pub fn hang_expression(
    ctx: &Context,
    expression: &Expression,
    shape: Shape,
    hang_level: Option<usize>,
) -> Expression {
    let original_additional_indent_level = shape.indent().additional_indent();
    let shape = match hang_level {
        Some(hang_level) => shape.with_indent(shape.indent().add_indent_level(hang_level)),
        None => shape,
    };

    let lhs_range =
        hang_level.map(|_| LeftmostRangeHang::find(expression, original_additional_indent_level));

    format_hanging_expression_(
        ctx,
        expression,
        shape,
        ExpressionContext::Standard,
        lhs_range,
    )
}

pub fn hang_expression_trailing_newline(
    ctx: &Context,
    expression: &Expression,
    shape: Shape,
    hang_level: Option<usize>,
) -> Expression {
    hang_expression(ctx, expression, shape, hang_level)
        .update_trailing_trivia(FormatTriviaType::Append(vec![create_newline_trivia(ctx)]))
}