aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_ide_api/src/syntax_tree.rs
blob: 3d7373d02bce1879d392b6a105b3785b6343efdf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
use crate::db::RootDatabase;
use ra_db::SourceDatabase;
use ra_syntax::{
    algo, AstNode, SourceFile, SyntaxElement,
    SyntaxKind::{RAW_STRING, STRING},
    SyntaxToken, TextRange,
};

pub use ra_db::FileId;

pub(crate) fn syntax_tree(
    db: &RootDatabase,
    file_id: FileId,
    text_range: Option<TextRange>,
) -> String {
    let parse = db.parse(file_id);
    if let Some(text_range) = text_range {
        let node = match algo::find_covering_element(parse.tree().syntax(), text_range) {
            SyntaxElement::Node(node) => node,
            SyntaxElement::Token(token) => {
                if let Some(tree) = syntax_tree_for_string(&token, text_range) {
                    return tree;
                }
                token.parent()
            }
        };

        node.debug_dump()
    } else {
        parse.tree().syntax().debug_dump()
    }
}

/// Attempts parsing the selected contents of a string literal
/// as rust syntax and returns its syntax tree
fn syntax_tree_for_string(token: &SyntaxToken, text_range: TextRange) -> Option<String> {
    // When the range is inside a string
    // we'll attempt parsing it as rust syntax
    // to provide the syntax tree of the contents of the string
    match token.kind() {
        STRING | RAW_STRING => syntax_tree_for_token(token, text_range),
        _ => None,
    }
}

fn syntax_tree_for_token(node: &SyntaxToken, text_range: TextRange) -> Option<String> {
    // Range of the full node
    let node_range = node.range();
    let text = node.text().to_string();

    // We start at some point inside the node
    // Either we have selected the whole string
    // or our selection is inside it
    let start = text_range.start() - node_range.start();

    // how many characters we have selected
    let len = text_range.len().to_usize();

    let node_len = node_range.len().to_usize();

    let start = start.to_usize();

    // We want to cap our length
    let len = len.min(node_len);

    // Ensure our slice is inside the actual string
    let end = if start + len < text.len() { start + len } else { text.len() - start };

    let text = &text[start..end];

    // Remove possible extra string quotes from the start
    // and the end of the string
    let text = text
        .trim_start_matches('r')
        .trim_start_matches('#')
        .trim_start_matches('"')
        .trim_end_matches('#')
        .trim_end_matches('"')
        .trim()
        // Remove custom markers
        .replace("<|>", "");

    let parsed = SourceFile::parse(&text);

    // If the "file" parsed without errors,
    // return its syntax
    if parsed.errors().is_empty() {
        return Some(parsed.tree().syntax().debug_dump());
    }

    None
}

#[cfg(test)]
mod tests {
    use test_utils::assert_eq_text;

    use crate::mock_analysis::{single_file, single_file_with_range};

    #[test]
    fn test_syntax_tree_without_range() {
        // Basic syntax
        let (analysis, file_id) = single_file(r#"fn foo() {}"#);
        let syn = analysis.syntax_tree(file_id, None);

        assert_eq_text!(
            syn.trim(),
            r#"
SOURCE_FILE@[0; 11)
  FN_DEF@[0; 11)
    FN_KW@[0; 2) "fn"
    WHITESPACE@[2; 3) " "
    NAME@[3; 6)
      IDENT@[3; 6) "foo"
    PARAM_LIST@[6; 8)
      L_PAREN@[6; 7) "("
      R_PAREN@[7; 8) ")"
    WHITESPACE@[8; 9) " "
    BLOCK@[9; 11)
      L_CURLY@[9; 10) "{"
      R_CURLY@[10; 11) "}"
"#
            .trim()
        );

        let (analysis, file_id) = single_file(
            r#"
fn test() {
    assert!("
    fn foo() {
    }
    ", "");
}"#
            .trim(),
        );
        let syn = analysis.syntax_tree(file_id, None);

        assert_eq_text!(
            syn.trim(),
            r#"
SOURCE_FILE@[0; 60)
  FN_DEF@[0; 60)
    FN_KW@[0; 2) "fn"
    WHITESPACE@[2; 3) " "
    NAME@[3; 7)
      IDENT@[3; 7) "test"
    PARAM_LIST@[7; 9)
      L_PAREN@[7; 8) "("
      R_PAREN@[8; 9) ")"
    WHITESPACE@[9; 10) " "
    BLOCK@[10; 60)
      L_CURLY@[10; 11) "{"
      WHITESPACE@[11; 16) "\n    "
      EXPR_STMT@[16; 58)
        MACRO_CALL@[16; 57)
          PATH@[16; 22)
            PATH_SEGMENT@[16; 22)
              NAME_REF@[16; 22)
                IDENT@[16; 22) "assert"
          EXCL@[22; 23) "!"
          TOKEN_TREE@[23; 57)
            L_PAREN@[23; 24) "("
            STRING@[24; 52) "\"\n    fn foo() {\n     ..."
            COMMA@[52; 53) ","
            WHITESPACE@[53; 54) " "
            STRING@[54; 56) "\"\""
            R_PAREN@[56; 57) ")"
        SEMI@[57; 58) ";"
      WHITESPACE@[58; 59) "\n"
      R_CURLY@[59; 60) "}"
"#
            .trim()
        );
    }

    #[test]
    fn test_syntax_tree_with_range() {
        let (analysis, range) = single_file_with_range(r#"<|>fn foo() {}<|>"#.trim());
        let syn = analysis.syntax_tree(range.file_id, Some(range.range));

        assert_eq_text!(
            syn.trim(),
            r#"
FN_DEF@[0; 11)
  FN_KW@[0; 2) "fn"
  WHITESPACE@[2; 3) " "
  NAME@[3; 6)
    IDENT@[3; 6) "foo"
  PARAM_LIST@[6; 8)
    L_PAREN@[6; 7) "("
    R_PAREN@[7; 8) ")"
  WHITESPACE@[8; 9) " "
  BLOCK@[9; 11)
    L_CURLY@[9; 10) "{"
    R_CURLY@[10; 11) "}"
"#
            .trim()
        );

        let (analysis, range) = single_file_with_range(
            r#"fn test() {
    <|>assert!("
    fn foo() {
    }
    ", "");<|>
}"#
            .trim(),
        );
        let syn = analysis.syntax_tree(range.file_id, Some(range.range));

        assert_eq_text!(
            syn.trim(),
            r#"
EXPR_STMT@[16; 58)
  MACRO_CALL@[16; 57)
    PATH@[16; 22)
      PATH_SEGMENT@[16; 22)
        NAME_REF@[16; 22)
          IDENT@[16; 22) "assert"
    EXCL@[22; 23) "!"
    TOKEN_TREE@[23; 57)
      L_PAREN@[23; 24) "("
      STRING@[24; 52) "\"\n    fn foo() {\n     ..."
      COMMA@[52; 53) ","
      WHITESPACE@[53; 54) " "
      STRING@[54; 56) "\"\""
      R_PAREN@[56; 57) ")"
  SEMI@[57; 58) ";"
"#
            .trim()
        );
    }

    #[test]
    fn test_syntax_tree_inside_string() {
        let (analysis, range) = single_file_with_range(
            r#"fn test() {
    assert!("
<|>fn foo() {
}<|>
fn bar() {
}
    ", "");
}"#
            .trim(),
        );
        let syn = analysis.syntax_tree(range.file_id, Some(range.range));
        assert_eq_text!(
            syn.trim(),
            r#"
SOURCE_FILE@[0; 12)
  FN_DEF@[0; 12)
    FN_KW@[0; 2) "fn"
    WHITESPACE@[2; 3) " "
    NAME@[3; 6)
      IDENT@[3; 6) "foo"
    PARAM_LIST@[6; 8)
      L_PAREN@[6; 7) "("
      R_PAREN@[7; 8) ")"
    WHITESPACE@[8; 9) " "
    BLOCK@[9; 12)
      L_CURLY@[9; 10) "{"
      WHITESPACE@[10; 11) "\n"
      R_CURLY@[11; 12) "}"
"#
            .trim()
        );

        // With a raw string
        let (analysis, range) = single_file_with_range(
            r###"fn test() {
    assert!(r#"
<|>fn foo() {
}<|>
fn bar() {
}
    "#, "");
}"###
                .trim(),
        );
        let syn = analysis.syntax_tree(range.file_id, Some(range.range));
        assert_eq_text!(
            syn.trim(),
            r#"
SOURCE_FILE@[0; 12)
  FN_DEF@[0; 12)
    FN_KW@[0; 2) "fn"
    WHITESPACE@[2; 3) " "
    NAME@[3; 6)
      IDENT@[3; 6) "foo"
    PARAM_LIST@[6; 8)
      L_PAREN@[6; 7) "("
      R_PAREN@[7; 8) ")"
    WHITESPACE@[8; 9) " "
    BLOCK@[9; 12)
      L_CURLY@[9; 10) "{"
      WHITESPACE@[10; 11) "\n"
      R_CURLY@[11; 12) "}"
"#
            .trim()
        );

        // With a raw string
        let (analysis, range) = single_file_with_range(
            r###"fn test() {
    assert!(r<|>#"
fn foo() {
}
fn bar() {
}"<|>#, "");
}"###
                .trim(),
        );
        let syn = analysis.syntax_tree(range.file_id, Some(range.range));
        assert_eq_text!(
            syn.trim(),
            r#"
SOURCE_FILE@[0; 25)
  FN_DEF@[0; 12)
    FN_KW@[0; 2) "fn"
    WHITESPACE@[2; 3) " "
    NAME@[3; 6)
      IDENT@[3; 6) "foo"
    PARAM_LIST@[6; 8)
      L_PAREN@[6; 7) "("
      R_PAREN@[7; 8) ")"
    WHITESPACE@[8; 9) " "
    BLOCK@[9; 12)
      L_CURLY@[9; 10) "{"
      WHITESPACE@[10; 11) "\n"
      R_CURLY@[11; 12) "}"
  WHITESPACE@[12; 13) "\n"
  FN_DEF@[13; 25)
    FN_KW@[13; 15) "fn"
    WHITESPACE@[15; 16) " "
    NAME@[16; 19)
      IDENT@[16; 19) "bar"
    PARAM_LIST@[19; 21)
      L_PAREN@[19; 20) "("
      R_PAREN@[20; 21) ")"
    WHITESPACE@[21; 22) " "
    BLOCK@[22; 25)
      L_CURLY@[22; 23) "{"
      WHITESPACE@[23; 24) "\n"
      R_CURLY@[24; 25) "}"
"#
            .trim()
        );
    }
}