1 use ide_db::{syntax_helpers::node_ext::vis_eq, FxHashSet};
3 ast::{self, AstNode, AstToken},
4 match_ast, Direction, NodeOrToken, SourceFile,
11 const REGION_START: &str = "// region:";
12 const REGION_END: &str = "// endregion";
14 #[derive(Debug, PartialEq, Eq)]
38 // Defines folding regions for curly braced blocks, runs of consecutive use, mod, const or static
39 // items, and `region` / `endregion` comment markers.
40 pub(crate) fn folding_ranges(file: &SourceFile) -> Vec<Fold> {
42 let mut visited_comments = FxHashSet::default();
43 let mut visited_imports = FxHashSet::default();
44 let mut visited_mods = FxHashSet::default();
45 let mut visited_consts = FxHashSet::default();
46 let mut visited_statics = FxHashSet::default();
48 // regions can be nested, here is a LIFO buffer
49 let mut region_starts: Vec<TextSize> = vec![];
51 for element in file.syntax().descendants_with_tokens() {
52 // Fold items that span multiple lines
53 if let Some(kind) = fold_kind(element.kind()) {
54 let is_multiline = match &element {
55 NodeOrToken::Node(node) => node.text().contains_char('\n'),
56 NodeOrToken::Token(token) => token.text().contains('\n'),
59 res.push(Fold { range: element.text_range(), kind });
65 NodeOrToken::Token(token) => {
66 // Fold groups of comments
67 if let Some(comment) = ast::Comment::cast(token) {
68 if visited_comments.contains(&comment) {
71 let text = comment.text().trim_start();
72 if text.starts_with(REGION_START) {
73 region_starts.push(comment.syntax().text_range().start());
74 } else if text.starts_with(REGION_END) {
75 if let Some(region) = region_starts.pop() {
77 range: TextRange::new(region, comment.syntax().text_range().end()),
78 kind: FoldKind::Region,
81 } else if let Some(range) =
82 contiguous_range_for_comment(comment, &mut visited_comments)
84 res.push(Fold { range, kind: FoldKind::Comment })
88 NodeOrToken::Node(node) => {
91 ast::Module(module) => {
92 if module.item_list().is_none() {
93 if let Some(range) = contiguous_range_for_item_group(
97 res.push(Fold { range, kind: FoldKind::Mods })
102 if let Some(range) = contiguous_range_for_item_group(use_, &mut visited_imports) {
103 res.push(Fold { range, kind: FoldKind::Imports })
106 ast::Const(konst) => {
107 if let Some(range) = contiguous_range_for_item_group(konst, &mut visited_consts) {
108 res.push(Fold { range, kind: FoldKind::Consts })
111 ast::Static(statik) => {
112 if let Some(range) = contiguous_range_for_item_group(statik, &mut visited_statics) {
113 res.push(Fold { range, kind: FoldKind::Statics })
116 ast::WhereClause(where_clause) => {
117 if let Some(range) = fold_range_for_where_clause(where_clause) {
118 res.push(Fold { range, kind: FoldKind::WhereClause })
121 ast::MatchArm(match_arm) => {
122 if let Some(range) = fold_range_for_multiline_match_arm(match_arm) {
123 res.push(Fold {range, kind: FoldKind::MatchArm})
136 fn fold_kind(kind: SyntaxKind) -> Option<FoldKind> {
138 COMMENT => Some(FoldKind::Comment),
139 ARG_LIST | PARAM_LIST => Some(FoldKind::ArgList),
140 ARRAY_EXPR => Some(FoldKind::Array),
141 RET_TYPE => Some(FoldKind::ReturnType),
144 | RECORD_PAT_FIELD_LIST
145 | RECORD_EXPR_FIELD_LIST
152 | TOKEN_TREE => Some(FoldKind::Block),
157 fn contiguous_range_for_item_group<N>(first: N, visited: &mut FxHashSet<N>) -> Option<TextRange>
159 N: ast::HasVisibility + Clone + Hash + Eq,
161 if !visited.insert(first.clone()) {
165 let (mut last, mut last_vis) = (first.clone(), first.visibility());
166 for element in first.syntax().siblings_with_tokens(Direction::Next) {
167 let node = match element {
168 NodeOrToken::Token(token) => {
169 if let Some(ws) = ast::Whitespace::cast(token) {
170 if !ws.spans_multiple_lines() {
171 // Ignore whitespace without blank lines
175 // There is a blank line or another token, which means that the
179 NodeOrToken::Node(node) => node,
182 if let Some(next) = N::cast(node) {
183 let next_vis = next.visibility();
184 if eq_visibility(next_vis.clone(), last_vis) {
185 visited.insert(next.clone());
191 // Stop if we find an item of a different kind or with a different visibility.
196 Some(TextRange::new(first.syntax().text_range().start(), last.syntax().text_range().end()))
198 // The group consists of only one element, therefore it cannot be folded
203 fn eq_visibility(vis0: Option<ast::Visibility>, vis1: Option<ast::Visibility>) -> bool {
205 (None, None) => true,
206 (Some(vis0), Some(vis1)) => vis_eq(&vis0, &vis1),
211 fn contiguous_range_for_comment(
213 visited: &mut FxHashSet<ast::Comment>,
214 ) -> Option<TextRange> {
215 visited.insert(first.clone());
217 // Only fold comments of the same flavor
218 let group_kind = first.kind();
219 if !group_kind.shape.is_line() {
223 let mut last = first.clone();
224 for element in first.syntax().siblings_with_tokens(Direction::Next) {
226 NodeOrToken::Token(token) => {
227 if let Some(ws) = ast::Whitespace::cast(token.clone()) {
228 if !ws.spans_multiple_lines() {
229 // Ignore whitespace without blank lines
233 if let Some(c) = ast::Comment::cast(token) {
234 if c.kind() == group_kind {
235 let text = c.text().trim_start();
236 // regions are not real comments
237 if !(text.starts_with(REGION_START) || text.starts_with(REGION_END)) {
238 visited.insert(c.clone());
244 // The comment group ends because either:
245 // * An element of a different kind was reached
246 // * A comment of a different flavor was reached
249 NodeOrToken::Node(_) => break,
254 Some(TextRange::new(first.syntax().text_range().start(), last.syntax().text_range().end()))
256 // The group consists of only one element, therefore it cannot be folded
261 fn fold_range_for_where_clause(where_clause: ast::WhereClause) -> Option<TextRange> {
262 let first_where_pred = where_clause.predicates().next();
263 let last_where_pred = where_clause.predicates().last();
265 if first_where_pred != last_where_pred {
266 let start = where_clause.where_token()?.text_range().end();
267 let end = where_clause.syntax().text_range().end();
268 return Some(TextRange::new(start, end));
273 fn fold_range_for_multiline_match_arm(match_arm: ast::MatchArm) -> Option<TextRange> {
274 if let Some(_) = fold_kind(match_arm.expr()?.syntax().kind()) {
277 if match_arm.expr()?.syntax().text().contains_char('\n') {
278 return Some(match_arm.expr()?.syntax().text_range());
285 use test_utils::extract_tags;
289 fn check(ra_fixture: &str) {
290 let (ranges, text) = extract_tags(ra_fixture, "fold");
292 let parse = SourceFile::parse(&text);
293 let mut folds = folding_ranges(&parse.tree());
294 folds.sort_by_key(|fold| (fold.range.start(), fold.range.end()));
299 "The amount of folds is different than the expected amount"
302 for (fold, (range, attr)) in folds.iter().zip(ranges.into_iter()) {
303 assert_eq!(fold.range.start(), range.start(), "mismatched start of folding ranges");
304 assert_eq!(fold.range.end(), range.end(), "mismatched end of folding ranges");
306 let kind = match fold.kind {
307 FoldKind::Comment => "comment",
308 FoldKind::Imports => "imports",
309 FoldKind::Mods => "mods",
310 FoldKind::Block => "block",
311 FoldKind::ArgList => "arglist",
312 FoldKind::Region => "region",
313 FoldKind::Consts => "consts",
314 FoldKind::Statics => "statics",
315 FoldKind::Array => "array",
316 FoldKind::WhereClause => "whereclause",
317 FoldKind::ReturnType => "returntype",
318 FoldKind::MatchArm => "matcharm",
320 assert_eq!(kind, &attr.unwrap());
325 fn test_fold_comments() {
328 <fold comment>// Hello
329 // this is a multiline
335 fn main() <fold block>{
336 <fold comment>// We should
340 <fold comment>//! But this one is different
341 //! because it has another flavor</fold>
342 <fold comment>/* As does this
343 multiline comment */</fold>
350 fn test_fold_imports() {
353 use std::<fold block>{
363 fn test_fold_mods() {
368 <fold mods>mod after_pub;
369 mod after_pub_next;</fold>
371 <fold mods>mod before_pub;
372 mod before_pub_next;</fold>
375 mod not_folding_single;
377 pub not_folding_single_next;
379 <fold mods>#[cfg(test)]
381 mod with_attribute_next;</fold>
386 mod inline2 <fold block>{
394 fn test_fold_import_groups() {
397 <fold imports>use std::str;
399 use std::io as iop;</fold>
401 <fold imports>use std::mem;
404 <fold imports>use std::collections::HashMap;
405 // Some random comment
406 use std::collections::VecDeque;</fold>
412 fn test_fold_import_and_groups() {
415 <fold imports>use std::str;
417 use std::io as iop;</fold>
419 <fold imports>use std::mem;
422 use std::collections::<fold block>{
426 // Some random comment
432 fn test_folds_structs() {
435 struct Foo <fold block>{
442 fn test_folds_traits() {
445 trait Foo <fold block>{
452 fn test_folds_macros() {
455 macro_rules! foo <fold block>{
456 ($($tt:tt)*) => { $($tt)* }
463 fn test_fold_match_arms() {
466 fn main() <fold block>{
467 match 0 <fold block>{
477 fn test_fold_multiline_non_block_match_arm() {
480 fn main() <fold block>{
481 match foo <fold block>{
482 block => <fold block>{
484 matcharm => <fold matcharm>some.
489 match_expr => <fold matcharm>match foo2 <fold block>{
492 array_list => <fold array>[
497 strustS => <fold matcharm>StructS <fold block>{
507 fn fold_big_calls() {
510 fn main() <fold block>{
511 frobnicate<fold arglist>(
522 fn fold_record_literals() {
525 const _: S = S <fold block>{
533 fn fold_multiline_params() {
536 fn foo<fold arglist>(
545 fn fold_multiline_array() {
548 const FOO: [usize; 4] = <fold array>[
562 // 1. some normal comment
563 <fold region>// region: test
564 // 2. some normal comment
565 <fold region>// region: inner
569 // endregion: test</fold>
575 fn fold_consecutive_const() {
578 <fold consts>const FIRST_CONST: &str = "first";
579 const SECOND_CONST: &str = "second";</fold>
585 fn fold_consecutive_static() {
588 <fold statics>static FIRST_STATIC: &str = "first";
589 static SECOND_STATIC: &str = "second";</fold>
595 fn fold_where_clause() {
596 // fold multi-line and don't fold single line.
600 where<fold whereclause>
614 fn fold_return_type() {
617 fn foo()<fold returntype>-> (
620 )</fold> { (true, true) }
622 fn bar() -> (bool, bool) { (true, true) }