ra_ap_syntax_bridge/
prettify_macro_expansion.rs

1//! Utilities for formatting macro expanded nodes until we get a proper formatter.
2use syntax::{
3    NodeOrToken,
4    SyntaxKind::{self, *},
5    SyntaxNode, SyntaxToken, T, WalkEvent,
6    ast::make,
7    ted::{self, Position},
8};
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum PrettifyWsKind {
12    Space,
13    Indent(usize),
14    Newline,
15}
16
17/// Renders a [`SyntaxNode`] with whitespace inserted between tokens that require them.
18///
19/// This is an internal API that is only exported because `mbe` needs it for tests and cannot depend
20/// on `hir-expand`. For any purpose other than tests, you are supposed to use the `prettify_macro_expansion`
21/// from `hir-expand` that handles `$crate` for you.
22#[deprecated = "use `hir_expand::prettify_macro_expansion()` instead"]
23pub fn prettify_macro_expansion(
24    syn: SyntaxNode,
25    dollar_crate_replacement: &mut dyn FnMut(&SyntaxToken) -> Option<SyntaxToken>,
26    inspect_mods: impl FnOnce(&[(Position, PrettifyWsKind)]),
27) -> SyntaxNode {
28    let mut indent = 0;
29    let mut last: Option<SyntaxKind> = None;
30    let mut mods = Vec::new();
31    let mut dollar_crate_replacements = Vec::new();
32    let syn = syn.clone_subtree().clone_for_update();
33
34    let before = Position::before;
35    let after = Position::after;
36
37    let do_indent = |pos: fn(_) -> Position, token: &SyntaxToken, indent| {
38        (pos(token.clone()), PrettifyWsKind::Indent(indent))
39    };
40    let do_ws =
41        |pos: fn(_) -> Position, token: &SyntaxToken| (pos(token.clone()), PrettifyWsKind::Space);
42    let do_nl =
43        |pos: fn(_) -> Position, token: &SyntaxToken| (pos(token.clone()), PrettifyWsKind::Newline);
44
45    for event in syn.preorder_with_tokens() {
46        let token = match event {
47            WalkEvent::Enter(NodeOrToken::Token(token)) => token,
48            WalkEvent::Leave(NodeOrToken::Node(node))
49                if matches!(
50                    node.kind(),
51                    ATTR | MATCH_ARM | STRUCT | ENUM | UNION | FN | IMPL | MACRO_RULES
52                ) =>
53            {
54                if indent > 0 {
55                    mods.push((Position::after(node.clone()), PrettifyWsKind::Indent(indent)));
56                }
57                if node.parent().is_some() {
58                    mods.push((Position::after(node), PrettifyWsKind::Newline));
59                }
60                continue;
61            }
62            _ => continue,
63        };
64        if token.kind() == SyntaxKind::IDENT && token.text() == "$crate" {
65            if let Some(replacement) = dollar_crate_replacement(&token) {
66                dollar_crate_replacements.push((token.clone(), replacement));
67            }
68        }
69        let tok = &token;
70
71        let is_next = |f: fn(SyntaxKind) -> bool, default| -> bool {
72            tok.next_token().map(|it| f(it.kind())).unwrap_or(default)
73        };
74        let is_last =
75            |f: fn(SyntaxKind) -> bool, default| -> bool { last.map(f).unwrap_or(default) };
76
77        match tok.kind() {
78            k if is_text(k)
79                && is_next(|it| !it.is_punct() || matches!(it, T![_] | T![#]), false) =>
80            {
81                mods.push(do_ws(after, tok));
82            }
83            L_CURLY if is_next(|it| it != R_CURLY, true) => {
84                indent += 1;
85                if is_last(is_text, false) {
86                    mods.push(do_ws(before, tok));
87                }
88
89                mods.push(do_indent(after, tok, indent));
90                mods.push(do_nl(after, tok));
91            }
92            R_CURLY if is_last(|it| it != L_CURLY, true) => {
93                indent = indent.saturating_sub(1);
94
95                if indent > 0 {
96                    mods.push(do_indent(before, tok, indent));
97                }
98                mods.push(do_nl(before, tok));
99            }
100            R_CURLY => {
101                if indent > 0 {
102                    mods.push(do_indent(after, tok, indent));
103                }
104                mods.push(do_nl(after, tok));
105            }
106            LIFETIME_IDENT if is_next(is_text, true) => {
107                mods.push(do_ws(after, tok));
108            }
109            AS_KW | DYN_KW | IMPL_KW | CONST_KW | MUT_KW => {
110                mods.push(do_ws(after, tok));
111            }
112            T![;] if is_next(|it| it != R_CURLY, true) => {
113                if indent > 0 {
114                    mods.push(do_indent(after, tok, indent));
115                }
116                mods.push(do_nl(after, tok));
117            }
118            T![=] if is_next(|it| it == T![>], false) => {
119                // FIXME: this branch is for `=>` in macro_rules!, which is currently parsed as
120                // two separate symbols.
121                mods.push(do_ws(before, tok));
122                mods.push(do_ws(after, &tok.next_token().unwrap()));
123            }
124            T![->] | T![=] | T![=>] => {
125                mods.push(do_ws(before, tok));
126                mods.push(do_ws(after, tok));
127            }
128            T![!] if is_last(|it| it == MACRO_RULES_KW, false) && is_next(is_text, false) => {
129                mods.push(do_ws(after, tok));
130            }
131            _ => (),
132        }
133
134        last = Some(tok.kind());
135    }
136
137    inspect_mods(&mods);
138    for (pos, insert) in mods {
139        ted::insert_raw(
140            pos,
141            match insert {
142                PrettifyWsKind::Space => make::tokens::single_space(),
143                PrettifyWsKind::Indent(indent) => make::tokens::whitespace(&" ".repeat(4 * indent)),
144                PrettifyWsKind::Newline => make::tokens::single_newline(),
145            },
146        );
147    }
148    for (old, new) in dollar_crate_replacements {
149        ted::replace(old, new);
150    }
151
152    if let Some(it) = syn.last_token().filter(|it| it.kind() == SyntaxKind::WHITESPACE) {
153        ted::remove(it);
154    }
155
156    syn
157}
158
159fn is_text(k: SyntaxKind) -> bool {
160    // Consider all keywords in all editions.
161    k.is_any_identifier() || k.is_literal() || k == UNDERSCORE
162}