1 use ide_db::helpers::node_ext::vis_eq;
2 use rustc_hash::FxHashSet;
5 ast::{self, AstNode, AstToken},
6 match_ast, Direction, NodeOrToken, SourceFile,
13 const REGION_START: &str = "// region:";
14 const REGION_END: &str = "// endregion";
16 #[derive(Debug, PartialEq, Eq)]
39 // Defines folding regions for curly braced blocks, runs of consecutive use, mod, const or static
40 // items, and `region` / `endregion` comment markers.
41 pub(crate) fn folding_ranges(file: &SourceFile) -> Vec<Fold> {
43 let mut visited_comments = FxHashSet::default();
44 let mut visited_imports = FxHashSet::default();
45 let mut visited_mods = FxHashSet::default();
46 let mut visited_consts = FxHashSet::default();
47 let mut visited_statics = FxHashSet::default();
49 // regions can be nested, here is a LIFO buffer
50 let mut region_starts: Vec<TextSize> = vec![];
52 for element in file.syntax().descendants_with_tokens() {
53 // Fold items that span multiple lines
54 if let Some(kind) = fold_kind(element.kind()) {
55 let is_multiline = match &element {
56 NodeOrToken::Node(node) => node.text().contains_char('\n'),
57 NodeOrToken::Token(token) => token.text().contains('\n'),
60 res.push(Fold { range: element.text_range(), kind });
66 NodeOrToken::Token(token) => {
67 // Fold groups of comments
68 if let Some(comment) = ast::Comment::cast(token) {
69 if visited_comments.contains(&comment) {
72 let text = comment.text().trim_start();
73 if text.starts_with(REGION_START) {
74 region_starts.push(comment.syntax().text_range().start());
75 } else if text.starts_with(REGION_END) {
76 if let Some(region) = region_starts.pop() {
78 range: TextRange::new(region, comment.syntax().text_range().end()),
79 kind: FoldKind::Region,
82 } else if let Some(range) =
83 contiguous_range_for_comment(comment, &mut visited_comments)
85 res.push(Fold { range, kind: FoldKind::Comment })
89 NodeOrToken::Node(node) => {
92 ast::Module(module) => {
93 if module.item_list().is_none() {
94 if let Some(range) = contiguous_range_for_item_group(
98 res.push(Fold { range, kind: FoldKind::Mods })
103 if let Some(range) = contiguous_range_for_item_group(use_, &mut visited_imports) {
104 res.push(Fold { range, kind: FoldKind::Imports })
107 ast::Const(konst) => {
108 if let Some(range) = contiguous_range_for_item_group(konst, &mut visited_consts) {
109 res.push(Fold { range, kind: FoldKind::Consts })
112 ast::Static(statik) => {
113 if let Some(range) = contiguous_range_for_item_group(statik, &mut visited_statics) {
114 res.push(Fold { range, kind: FoldKind::Statics })
117 ast::WhereClause(where_clause) => {
118 if let Some(range) = fold_range_for_where_clause(where_clause) {
119 res.push(Fold { range, kind: FoldKind::WhereClause })
132 fn fold_kind(kind: SyntaxKind) -> Option<FoldKind> {
134 COMMENT => Some(FoldKind::Comment),
135 ARG_LIST | PARAM_LIST => Some(FoldKind::ArgList),
136 ARRAY_EXPR => Some(FoldKind::Array),
137 RET_TYPE => Some(FoldKind::ReturnType),
140 | RECORD_PAT_FIELD_LIST
141 | RECORD_EXPR_FIELD_LIST
148 | TOKEN_TREE => Some(FoldKind::Block),
153 fn contiguous_range_for_item_group<N>(first: N, visited: &mut FxHashSet<N>) -> Option<TextRange>
155 N: ast::HasVisibility + Clone + Hash + Eq,
157 if !visited.insert(first.clone()) {
161 let (mut last, mut last_vis) = (first.clone(), first.visibility());
162 for element in first.syntax().siblings_with_tokens(Direction::Next) {
163 let node = match element {
164 NodeOrToken::Token(token) => {
165 if let Some(ws) = ast::Whitespace::cast(token) {
166 if !ws.spans_multiple_lines() {
167 // Ignore whitespace without blank lines
171 // There is a blank line or another token, which means that the
175 NodeOrToken::Node(node) => node,
178 if let Some(next) = N::cast(node) {
179 let next_vis = next.visibility();
180 if eq_visibility(next_vis.clone(), last_vis) {
181 visited.insert(next.clone());
187 // Stop if we find an item of a different kind or with a different visibility.
192 Some(TextRange::new(first.syntax().text_range().start(), last.syntax().text_range().end()))
194 // The group consists of only one element, therefore it cannot be folded
199 fn eq_visibility(vis0: Option<ast::Visibility>, vis1: Option<ast::Visibility>) -> bool {
201 (None, None) => true,
202 (Some(vis0), Some(vis1)) => vis_eq(&vis0, &vis1),
207 fn contiguous_range_for_comment(
209 visited: &mut FxHashSet<ast::Comment>,
210 ) -> Option<TextRange> {
211 visited.insert(first.clone());
213 // Only fold comments of the same flavor
214 let group_kind = first.kind();
215 if !group_kind.shape.is_line() {
219 let mut last = first.clone();
220 for element in first.syntax().siblings_with_tokens(Direction::Next) {
222 NodeOrToken::Token(token) => {
223 if let Some(ws) = ast::Whitespace::cast(token.clone()) {
224 if !ws.spans_multiple_lines() {
225 // Ignore whitespace without blank lines
229 if let Some(c) = ast::Comment::cast(token) {
230 if c.kind() == group_kind {
231 let text = c.text().trim_start();
232 // regions are not real comments
233 if !(text.starts_with(REGION_START) || text.starts_with(REGION_END)) {
234 visited.insert(c.clone());
240 // The comment group ends because either:
241 // * An element of a different kind was reached
242 // * A comment of a different flavor was reached
245 NodeOrToken::Node(_) => break,
250 Some(TextRange::new(first.syntax().text_range().start(), last.syntax().text_range().end()))
252 // The group consists of only one element, therefore it cannot be folded
257 fn fold_range_for_where_clause(where_clause: ast::WhereClause) -> Option<TextRange> {
258 let first_where_pred = where_clause.predicates().next();
259 let last_where_pred = where_clause.predicates().last();
261 if first_where_pred != last_where_pred {
262 let start = where_clause.where_token()?.text_range().end();
263 let end = where_clause.syntax().text_range().end();
264 return Some(TextRange::new(start, end));
271 use test_utils::extract_tags;
275 fn check(ra_fixture: &str) {
276 let (ranges, text) = extract_tags(ra_fixture, "fold");
278 let parse = SourceFile::parse(&text);
279 let mut folds = folding_ranges(&parse.tree());
280 folds.sort_by_key(|fold| (fold.range.start(), fold.range.end()));
285 "The amount of folds is different than the expected amount"
288 for (fold, (range, attr)) in folds.iter().zip(ranges.into_iter()) {
289 assert_eq!(fold.range.start(), range.start(), "mismatched start of folding ranges");
290 assert_eq!(fold.range.end(), range.end(), "mismatched end of folding ranges");
292 let kind = match fold.kind {
293 FoldKind::Comment => "comment",
294 FoldKind::Imports => "imports",
295 FoldKind::Mods => "mods",
296 FoldKind::Block => "block",
297 FoldKind::ArgList => "arglist",
298 FoldKind::Region => "region",
299 FoldKind::Consts => "consts",
300 FoldKind::Statics => "statics",
301 FoldKind::Array => "array",
302 FoldKind::WhereClause => "whereclause",
303 FoldKind::ReturnType => "returntype",
305 assert_eq!(kind, &attr.unwrap());
310 fn test_fold_comments() {
313 <fold comment>// Hello
314 // this is a multiline
320 fn main() <fold block>{
321 <fold comment>// We should
325 <fold comment>//! But this one is different
326 //! because it has another flavor</fold>
327 <fold comment>/* As does this
328 multiline comment */</fold>
335 fn test_fold_imports() {
338 use std::<fold block>{
348 fn test_fold_mods() {
353 <fold mods>mod after_pub;
354 mod after_pub_next;</fold>
356 <fold mods>mod before_pub;
357 mod before_pub_next;</fold>
360 mod not_folding_single;
362 pub not_folding_single_next;
364 <fold mods>#[cfg(test)]
366 mod with_attribute_next;</fold>
371 mod inline2 <fold block>{
379 fn test_fold_import_groups() {
382 <fold imports>use std::str;
384 use std::io as iop;</fold>
386 <fold imports>use std::mem;
389 <fold imports>use std::collections::HashMap;
390 // Some random comment
391 use std::collections::VecDeque;</fold>
397 fn test_fold_import_and_groups() {
400 <fold imports>use std::str;
402 use std::io as iop;</fold>
404 <fold imports>use std::mem;
407 use std::collections::<fold block>{
411 // Some random comment
417 fn test_folds_structs() {
420 struct Foo <fold block>{
427 fn test_folds_traits() {
430 trait Foo <fold block>{
437 fn test_folds_macros() {
440 macro_rules! foo <fold block>{
441 ($($tt:tt)*) => { $($tt)* }
448 fn test_fold_match_arms() {
451 fn main() <fold block>{
452 match 0 <fold block>{
462 fn fold_big_calls() {
465 fn main() <fold block>{
466 frobnicate<fold arglist>(
477 fn fold_record_literals() {
480 const _: S = S <fold block>{
488 fn fold_multiline_params() {
491 fn foo<fold arglist>(
500 fn fold_multiline_array() {
503 const FOO: [usize; 4] = <fold array>[
517 // 1. some normal comment
518 <fold region>// region: test
519 // 2. some normal comment
520 <fold region>// region: inner
524 // endregion: test</fold>
530 fn fold_consecutive_const() {
533 <fold consts>const FIRST_CONST: &str = "first";
534 const SECOND_CONST: &str = "second";</fold>
540 fn fold_consecutive_static() {
543 <fold statics>static FIRST_STATIC: &str = "first";
544 static SECOND_STATIC: &str = "second";</fold>
550 fn fold_where_clause() {
551 // fold multi-line and don't fold single line.
555 where<fold whereclause>
569 fn fold_return_type() {
572 fn foo()<fold returntype>-> (
575 )</fold> { (true, true) }
577 fn bar() -> (bool, bool) { (true, true) }