Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ harness = false

[dependencies]
capacity_builder = "0.5.0"
dprint-core = { version = "0.75.2", features = ["formatting"] }
dprint-core = { version = "0.77.0", features = ["formatting"] }
dprint-core-macros = "0.1.0"
dprint-swc-ext = { version = "0.28.1", features = ["view"] }
globset = "0.4"
Expand Down
24 changes: 24 additions & 0 deletions deployment/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
"preferHanging",
"preferSingleLine",
"operatorPosition",
"arrayExpression.linePerElement",
"binaryExpression.linePerExpression",
"memberExpression.linePerExpression",
"conditionalExpression.linePerExpression",
Expand Down Expand Up @@ -674,6 +675,18 @@
"description": "Prefers not using parentheses when possible."
}]
},
"arrayExpression.linePerElement": {
"description": "Whether to force a line per element when an array expression spans multiple lines.",
"type": "boolean",
"default": true,
"oneOf": [{
"const": true,
"description": "Formats with each element on a new line."
}, {
"const": false,
"description": "Maintains the line breaks between the elements as written by the programmer. A line that exceeds the line width is still split up."
}]
},
"binaryExpression.linePerExpression": {
"description": "Whether to force a line per expression when spanning multiple lines.",
"type": "boolean",
Expand Down Expand Up @@ -1489,6 +1502,17 @@
]
}
},
"arrayExpression.linePerElement": {
"$ref": "#/definitions/arrayExpression.linePerElement",
"x-example": {
"input": [
"const bytes = [",
" 0x00, 0x01, 0x02, 0x03,",
" 0x10, 0x11, 0x12, 0x13,",
"];"
]
}
},
"binaryExpression.linePerExpression": {
"$ref": "#/definitions/binaryExpression.linePerExpression",
"x-example": {
Expand Down
12 changes: 11 additions & 1 deletion src/configuration/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -616,6 +616,15 @@ impl ConfigurationBuilder {

/* situational */

/// Whether to force a line per element when an array expression spans multiple lines.
///
/// * `true` (default) - Formats with each element on a new line.
/// * `false` - Maintains the line breaks between the elements as written by the programmer.
/// A line that exceeds the line width is still split up.
pub fn array_expression_line_per_element(&mut self, value: bool) -> &mut Self {
self.insert("arrayExpression.linePerElement", value.into())
}

/// Whether to use parentheses for arrow functions.
///
/// Default: `UseParentheses::Maintain`
Expand Down Expand Up @@ -1531,6 +1540,7 @@ mod tests {
.quote_props(QuoteProps::AsNeeded)
.prefer_hanging(false)
/* situational */
.array_expression_line_per_element(false)
.arrow_function_use_parentheses(UseParentheses::Maintain)
.binary_expression_line_per_expression(false)
.conditional_expression_line_per_expression(true)
Expand Down Expand Up @@ -1758,7 +1768,7 @@ mod tests {
.with_statement_space_around(true);

let inner_config = config.get_inner_config();
assert_eq!(inner_config.len(), 236);
assert_eq!(inner_config.len(), 237);
let diagnostics = resolve_config(inner_config, &Default::default()).diagnostics;
assert_eq!(diagnostics.len(), 0);
}
Expand Down
22 changes: 22 additions & 0 deletions src/configuration/resolve_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ pub fn resolve_config(config: ConfigKeyMap, global_config: &GlobalConfiguration)
file_indent_level: get_value(&mut config, "fileIndentLevel", 0, &mut diagnostics),
max_blank_lines: get_value(&mut config, "maxBlankLines", 1, &mut diagnostics),
/* situational */
array_expression_line_per_element: get_value(&mut config, "arrayExpression.linePerElement", true, &mut diagnostics),
arrow_function_use_parentheses: get_value(&mut config, "arrowFunction.useParentheses", UseParentheses::Maintain, &mut diagnostics),
binary_expression_line_per_expression: get_value(&mut config, "binaryExpression.linePerExpression", false, &mut diagnostics),
conditional_expression_line_per_expression: get_value(&mut config, "conditionalExpression.linePerExpression", true, &mut diagnostics),
Expand Down Expand Up @@ -1093,6 +1094,27 @@ mod tests {
);
}

#[test]
fn handle_array_expression_line_per_element() {
let property_name = "arrayExpression.linePerElement";
for value in [None, Some(true), Some(false)] {
let mut config = ConfigKeyMap::new();
if let Some(value) = value {
config.insert(property_name.to_string(), value.into());
}
let result = resolve_config(config, &GlobalConfiguration::default());
assert_eq!(result.diagnostics.len(), 0);
assert_eq!(result.config.array_expression_line_per_element, value.unwrap_or(true));
assert_eq!(serde_json::to_value(&result.config).unwrap()[property_name], value.unwrap_or(true));
}

let mut config = ConfigKeyMap::new();
config.insert(property_name.to_string(), ConfigKeyValue::from_str("invalid"));
let result = resolve_config(config, &GlobalConfiguration::default());
assert!(result.config.array_expression_line_per_element);
assert_eq!(get_diagnostic_property_names(&result.diagnostics), [property_name]);
}

#[test]
fn handle_space_between_object_closing_braces() {
let property_name = "spaceBetweenObjectClosingBraces";
Expand Down
2 changes: 2 additions & 0 deletions src/configuration/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -535,6 +535,8 @@ pub struct Configuration {
pub file_indent_level: u32,
pub max_blank_lines: u32,
/* situational */
#[serde(rename = "arrayExpression.linePerElement")]
pub array_expression_line_per_element: bool,
#[serde(rename = "arrowFunction.useParentheses")]
pub arrow_function_use_parentheses: UseParentheses,
#[serde(rename = "binaryExpression.linePerExpression")]
Expand Down
62 changes: 56 additions & 6 deletions src/generation/generate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1819,6 +1819,7 @@ fn gen_array_expr<'a>(node: &ArrayLit<'a>, context: &mut Context<'a>) -> PrintIt
range: node.range(),
nodes: node.elems.iter().map(|&x| x.map(|elem| elem.into())).collect(),
prefer_hanging: get_array_expr_prefer_hanging(node, context.config),
line_per_element: context.config.array_expression_line_per_element,
prefer_single_line: context.config.array_expression_prefer_single_line,
trailing_commas: context.config.array_expression_trailing_commas,
space_around: context.config.array_expression_space_around,
Expand Down Expand Up @@ -5643,6 +5644,7 @@ fn gen_array_pat<'a>(node: &ArrayPat<'a>, context: &mut Context<'a>) -> PrintIte
range: get_brackets_range(node, context),
nodes: node.elems.iter().map(|x| x.as_ref().map(|elem| elem.into())).collect(),
prefer_hanging: context.config.array_pattern_prefer_hanging,
line_per_element: true,
prefer_single_line: context.config.array_pattern_prefer_single_line,
trailing_commas: context.config.array_pattern_trailing_commas,
space_around: context.config.array_pattern_space_around,
Expand Down Expand Up @@ -7853,6 +7855,7 @@ fn gen_tuple_type<'a>(node: &TsTupleType<'a>, context: &mut Context<'a>) -> Prin
range: node.range(),
nodes: node.elem_types.iter().map(|&x| Some(x.into())).collect(),
prefer_hanging,
line_per_element: true,
prefer_single_line: context.config.tuple_type_prefer_single_line,
trailing_commas: context.config.tuple_type_trailing_commas,
space_around: context.config.tuple_type_space_around,
Expand Down Expand Up @@ -8983,6 +8986,9 @@ struct GenArrayLikeNodesOptions<'a> {
range: SourceRange,
nodes: Vec<Option<Node<'a>>>,
prefer_hanging: bool,
/// Whether each element goes on its own line when multi-line instead of
/// maintaining the line breaks between the elements.
line_per_element: bool,
prefer_single_line: bool,
space_around: bool,
trailing_commas: TrailingCommas,
Expand All @@ -9001,6 +9007,8 @@ fn gen_array_like_nodes<'a>(opts: GenArrayLikeNodesOptions<'a>, context: &mut Co
TrailingCommas::Never
};
let prefer_hanging = opts.prefer_hanging;
// a hanging array that prefers being on a single line fills the lines instead
let maintain_line_breaks = !opts.line_per_element && !(prefer_hanging && prefer_single_line);
let space_around = opts.space_around;
let range = opts.range;
let force_use_new_lines = get_array_like_force_use_new_lines(range, &nodes, prefer_single_line, context);
Expand All @@ -9026,7 +9034,11 @@ fn gen_array_like_nodes<'a>(opts: GenArrayLikeNodesOptions<'a>, context: &mut Co
space_at_end: space_around,
separator: Signal::SpaceOrNewLine.into_print_items(context.arena),
},
multi_line_options: ir_helpers::MultiLineOptions::surround_newlines_indented(),
multi_line_options: ir_helpers::MultiLineOptions {
maintain_line_breaks,
newline_after_value_made_multi_line: maintain_line_breaks,
..ir_helpers::MultiLineOptions::surround_newlines_indented()
},
force_possible_newline_at_start: false,
node_sorter: None,
disallow_inline_multi_line_new_line_groups,
Expand Down Expand Up @@ -10372,6 +10384,7 @@ fn gen_separated_values_with_result<'a>(opts: GenSeparatedValuesParams<'a>, cont
ListBlankLines::Force => 1,
};
let node_sorter = opts.node_sorter;
let maintain_line_breaks = opts.multi_line_options.maintain_line_breaks;
let disallow_inline_multi_line_new_line_groups = opts.disallow_inline_multi_line_new_line_groups;
let is_hanging = opts.prefer_hanging && !opts.force_use_new_lines;

Expand Down Expand Up @@ -10409,10 +10422,24 @@ fn gen_separated_values_with_result<'a>(opts: GenSeparatedValuesParams<'a>, cont
};
let lines_span = match blank_lines {
ListBlankLines::Remove => None,
ListBlankLines::Maintain => value.as_node().map(|x| ir_helpers::LinesSpan {
start_line: x.start_line_with_comments(context),
end_line: x.end_line_with_comments(context),
}),
ListBlankLines::Maintain => match &value {
NodeOrSeparator::Node(node) => Some(ir_helpers::LinesSpan {
start_line: node.start_line_with_comments(context),
end_line: if maintain_line_breaks && is_comma_on_later_line(*node, context) {
// maintain the line break before a comma at the start of a line
node.end_line_fast(context.program)
} else {
node.end_line_with_comments(context)
},
}),
// a separator in place of a value (ex. the hole in `[a, , b]`) only has a
// span when it's necessary for maintaining the line breaks beside it
NodeOrSeparator::Separator(token) if maintain_line_breaks => Some(ir_helpers::LinesSpan {
start_line: token.range().start_line_with_comments(context),
end_line: get_end_line_with_trailing_comments(token.end(), context.program),
}),
NodeOrSeparator::Separator(_) => None,
},
// a span that's one blank line after the previous value's, unless the blank line
// was already added before the comments after the previous value's comma
ListBlankLines::Force => value.as_node().map(|node| {
Expand Down Expand Up @@ -10479,7 +10506,22 @@ fn gen_separated_values_with_result<'a>(opts: GenSeparatedValuesParams<'a>, cont
_ => true,
};

let items = if use_new_line_group { ir_helpers::new_line_group(items) } else { items };
let items = if use_new_line_group {
ir_helpers::new_line_group(items)
} else if maintain_line_breaks {
// when multi-line, the value goes on the next line when it doesn't fit on
// the rest of the line instead of breaking within (ex. `[1, 2], [3, 4]`)
let items = items.into_rc_path();
if_true_or(
"newLineGroupIfMultiLine",
is_multi_line_or_hanging,
ir_helpers::new_line_group(items.into_print_items(context.arena)),
items.into_print_items(context.arena),
)
.into_print_items(context.arena)
} else {
items
};
// a value that's allowed to be inline multi-line is still pulled up beside the previous value (ex. a function)
let items = if is_hanging && i > 0 && use_new_line_group && !allow_inline_multi_line && is_value_on_new_line(&value, context) {
gen_multi_line_hanging_value_on_new_line(items, context)
Expand Down Expand Up @@ -10512,6 +10554,14 @@ fn gen_separated_values_with_result<'a>(opts: GenSeparatedValuesParams<'a>, cont
},
);

/// Gets if the comma after the node starts on a later line than the node ends on.
fn is_comma_on_later_line<'a>(node: Node<'a>, context: &mut Context<'a>) -> bool {
context
.token_finder
.get_next_token_if_comma(&node)
.is_some_and(|comma| comma.start_line_fast(context.program) > node.end_line_fast(context.program))
}

/// Gets if each value isn't allowed to be inline multi-line because it has a value beside it of
/// the same kind, so the container breaks instead (ex. `[{ a }, { b }]` instead of expanding the
/// last object). When every value with a same-kind neighbor is already multi-line because of how
Expand Down
39 changes: 22 additions & 17 deletions src/generation/generate_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,27 +58,32 @@ where
.get_next_token_if_comma(self)
.map(|x| x.end())
.unwrap_or_else(|| self.end());
let trailing_comments = search_end.trailing_comments_fast(context.program);
let previous_end_line = search_end.end_line_fast(context.program);
for comment in trailing_comments {
// optimization
if comment.kind == CommentKind::Line {
break;
}
get_end_line_with_trailing_comments(search_end, context.program)
}
}

let comment_start_line = comment.start_line_fast(context.program);
if comment_start_line <= previous_end_line {
let comment_end_line = comment.end_line_fast(context.program);
if comment_end_line > previous_end_line {
return comment_end_line; // should only include the first multi-line comment block
}
} else {
break;
}
/// Gets the end line of the position with a possible trailing multi-line block comment end.
pub fn get_end_line_with_trailing_comments(search_end: SourcePos, program: Program) -> usize {
let trailing_comments = search_end.trailing_comments_fast(program);
let previous_end_line = search_end.end_line_fast(program);
for comment in trailing_comments {
// optimization
if comment.kind == CommentKind::Line {
break;
}

previous_end_line
let comment_start_line = comment.start_line_fast(program);
if comment_start_line <= previous_end_line {
let comment_end_line = comment.end_line_fast(program);
if comment_end_line > previous_end_line {
return comment_end_line; // should only include the first multi-line comment block
}
} else {
break;
}
}

previous_end_line
}

/* custom enums */
Expand Down
2 changes: 1 addition & 1 deletion src/wasm_plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ impl SyncPluginHandler<Configuration> for TypeScriptPluginHandler {
help_url: "https://dprint.dev/plugins/typescript".to_string(),
config_schema_url: format!("https://plugins.dprint.dev/dprint/dprint-plugin-typescript/{}/schema.json", version),
update_url: Some("https://plugins.dprint.dev/dprint/dprint-plugin-typescript/latest.json".to_string()),
supports_range_formatting: Some(true),
supports_range_formatting: true,
}
}

Expand Down
Loading