Skip to content

Commit

Permalink
also fix is_simple_ts_type
Browse files Browse the repository at this point in the history
  • Loading branch information
faultyserver committed Dec 12, 2023
1 parent 1ddce1f commit 1923357
Showing 1 changed file with 44 additions and 7 deletions.
51 changes: 44 additions & 7 deletions crates/biome_js_formatter/src/js/expressions/call_arguments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -874,11 +874,48 @@ fn should_group_last_argument(
/// HTMLElement => true
/// string | object => false
/// Foo<string> => false
///
/// Note that Prettier allows extracting the inner type from arrays and
/// single-argument generic types, but for now, this implementation does not.
fn is_simple_ts_type(ty: AnyTsType) -> bool {
match ty {
/// This function also introspects into array and generic types to extract the
/// core type, but only to a limited extent:
/// string[] => string
/// string[][] => string
/// string[][][] => string
/// Foo<string>[][] => string
/// Foo<string[]>[] => string[]
/// Foo<string[][]> => string[][]
fn is_simple_ts_type(ty: &AnyTsType) -> bool {
// Reach up to two-levels deep into array types:
// string[] => string
// string[][] => string
// string[][][] => string[]
let extracted_array_type = match ty {
AnyTsType::TsArrayType(array) => match array.element_type() {
Ok(AnyTsType::TsArrayType(inner_array)) => inner_array.element_type().ok(),
Ok(element_type) => Some(element_type),
_ => None,
},
_ => None,
};

// Then, extract the first type parameter of a Generic as long as it's the
// only parameter:
// Foo<number> => number
// Foo<number, string> => Foo<number, string>
let extracted_generic_type = match &extracted_array_type {
Some(AnyTsType::TsReferenceType(generic)) => {
generic.type_arguments().map_or(None, |type_arguments| {
let argument_list = type_arguments.ts_type_argument_list();
if argument_list.len() == 1 {
argument_list.first().map_or(None, |first| first.ok())
} else {
extracted_array_type
}
})
}
_ => extracted_array_type,
};

let resolved_type = extracted_generic_type.as_ref().unwrap_or(ty);
match resolved_type {
// Any keyword or literal types
AnyTsType::TsAnyType(_)
| AnyTsType::TsBigintLiteralType(_)
Expand Down Expand Up @@ -941,7 +978,7 @@ fn is_relatively_short_argument(argument: AnyJsExpression) -> bool {
ty: Ok(annotation),
} = as_expression.as_fields()
{
is_simple_ts_type(annotation) && SimpleArgument::from(expression).is_simple()
is_simple_ts_type(&annotation) && SimpleArgument::from(expression).is_simple()
} else {
false
}
Expand All @@ -953,7 +990,7 @@ fn is_relatively_short_argument(argument: AnyJsExpression) -> bool {
ty: Ok(annotation),
} = as_expression.as_fields()
{
is_simple_ts_type(annotation) && SimpleArgument::from(expression).is_simple()
is_simple_ts_type(&annotation) && SimpleArgument::from(expression).is_simple()
} else {
false
}
Expand Down

0 comments on commit 1923357

Please sign in to comment.