aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_editor/src/scope/fn_scope.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_editor/src/scope/fn_scope.rs')
-rw-r--r--crates/ra_editor/src/scope/fn_scope.rs435
1 files changed, 0 insertions, 435 deletions
diff --git a/crates/ra_editor/src/scope/fn_scope.rs b/crates/ra_editor/src/scope/fn_scope.rs
deleted file mode 100644
index f10bdf657..000000000
--- a/crates/ra_editor/src/scope/fn_scope.rs
+++ /dev/null
@@ -1,435 +0,0 @@
1use std::fmt;
2
3use rustc_hash::FxHashMap;
4
5use ra_syntax::{
6 algo::generate,
7 ast::{self, ArgListOwner, LoopBodyOwner, NameOwner},
8 AstNode, SmolStr, SyntaxNode, SyntaxNodeRef,
9};
10
11type ScopeId = usize;
12
13#[derive(Debug)]
14pub struct FnScopes {
15 pub self_param: Option<SyntaxNode>,
16 scopes: Vec<ScopeData>,
17 scope_for: FxHashMap<SyntaxNode, ScopeId>,
18}
19
20impl FnScopes {
21 pub fn new(fn_def: ast::FnDef) -> FnScopes {
22 let mut scopes = FnScopes {
23 self_param: fn_def
24 .param_list()
25 .and_then(|it| it.self_param())
26 .map(|it| it.syntax().owned()),
27 scopes: Vec::new(),
28 scope_for: FxHashMap::default(),
29 };
30 let root = scopes.root_scope();
31 scopes.add_params_bindings(root, fn_def.param_list());
32 if let Some(body) = fn_def.body() {
33 compute_block_scopes(body, &mut scopes, root)
34 }
35 scopes
36 }
37 pub fn entries(&self, scope: ScopeId) -> &[ScopeEntry] {
38 &self.scopes[scope].entries
39 }
40 pub fn scope_chain<'a>(&'a self, node: SyntaxNodeRef) -> impl Iterator<Item = ScopeId> + 'a {
41 generate(self.scope_for(node), move |&scope| {
42 self.scopes[scope].parent
43 })
44 }
45 fn root_scope(&mut self) -> ScopeId {
46 let res = self.scopes.len();
47 self.scopes.push(ScopeData {
48 parent: None,
49 entries: vec![],
50 });
51 res
52 }
53 fn new_scope(&mut self, parent: ScopeId) -> ScopeId {
54 let res = self.scopes.len();
55 self.scopes.push(ScopeData {
56 parent: Some(parent),
57 entries: vec![],
58 });
59 res
60 }
61 fn add_bindings(&mut self, scope: ScopeId, pat: ast::Pat) {
62 let entries = pat
63 .syntax()
64 .descendants()
65 .filter_map(ast::BindPat::cast)
66 .filter_map(ScopeEntry::new);
67 self.scopes[scope].entries.extend(entries);
68 }
69 fn add_params_bindings(&mut self, scope: ScopeId, params: Option<ast::ParamList>) {
70 params
71 .into_iter()
72 .flat_map(|it| it.params())
73 .filter_map(|it| it.pat())
74 .for_each(|it| self.add_bindings(scope, it));
75 }
76 fn set_scope(&mut self, node: SyntaxNodeRef, scope: ScopeId) {
77 self.scope_for.insert(node.owned(), scope);
78 }
79 fn scope_for(&self, node: SyntaxNodeRef) -> Option<ScopeId> {
80 node.ancestors()
81 .filter_map(|it| self.scope_for.get(&it.owned()).map(|&scope| scope))
82 .next()
83 }
84}
85
86pub struct ScopeEntry {
87 syntax: SyntaxNode,
88}
89
90impl ScopeEntry {
91 fn new(pat: ast::BindPat) -> Option<ScopeEntry> {
92 if pat.name().is_some() {
93 Some(ScopeEntry {
94 syntax: pat.syntax().owned(),
95 })
96 } else {
97 None
98 }
99 }
100 pub fn name(&self) -> SmolStr {
101 self.ast().name().unwrap().text()
102 }
103 pub fn ast(&self) -> ast::BindPat {
104 ast::BindPat::cast(self.syntax.borrowed()).unwrap()
105 }
106}
107
108impl fmt::Debug for ScopeEntry {
109 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
110 f.debug_struct("ScopeEntry")
111 .field("name", &self.name())
112 .field("syntax", &self.syntax)
113 .finish()
114 }
115}
116
117fn compute_block_scopes(block: ast::Block, scopes: &mut FnScopes, mut scope: ScopeId) {
118 for stmt in block.statements() {
119 match stmt {
120 ast::Stmt::LetStmt(stmt) => {
121 if let Some(expr) = stmt.initializer() {
122 scopes.set_scope(expr.syntax(), scope);
123 compute_expr_scopes(expr, scopes, scope);
124 }
125 scope = scopes.new_scope(scope);
126 if let Some(pat) = stmt.pat() {
127 scopes.add_bindings(scope, pat);
128 }
129 }
130 ast::Stmt::ExprStmt(expr_stmt) => {
131 if let Some(expr) = expr_stmt.expr() {
132 scopes.set_scope(expr.syntax(), scope);
133 compute_expr_scopes(expr, scopes, scope);
134 }
135 }
136 }
137 }
138 if let Some(expr) = block.expr() {
139 scopes.set_scope(expr.syntax(), scope);
140 compute_expr_scopes(expr, scopes, scope);
141 }
142}
143
144fn compute_expr_scopes(expr: ast::Expr, scopes: &mut FnScopes, scope: ScopeId) {
145 match expr {
146 ast::Expr::IfExpr(e) => {
147 let cond_scope = e
148 .condition()
149 .and_then(|cond| compute_cond_scopes(cond, scopes, scope));
150 if let Some(block) = e.then_branch() {
151 compute_block_scopes(block, scopes, cond_scope.unwrap_or(scope));
152 }
153 if let Some(block) = e.else_branch() {
154 compute_block_scopes(block, scopes, scope);
155 }
156 }
157 ast::Expr::BlockExpr(e) => {
158 if let Some(block) = e.block() {
159 compute_block_scopes(block, scopes, scope);
160 }
161 }
162 ast::Expr::LoopExpr(e) => {
163 if let Some(block) = e.loop_body() {
164 compute_block_scopes(block, scopes, scope);
165 }
166 }
167 ast::Expr::WhileExpr(e) => {
168 let cond_scope = e
169 .condition()
170 .and_then(|cond| compute_cond_scopes(cond, scopes, scope));
171 if let Some(block) = e.loop_body() {
172 compute_block_scopes(block, scopes, cond_scope.unwrap_or(scope));
173 }
174 }
175 ast::Expr::ForExpr(e) => {
176 if let Some(expr) = e.iterable() {
177 compute_expr_scopes(expr, scopes, scope);
178 }
179 let mut scope = scope;
180 if let Some(pat) = e.pat() {
181 scope = scopes.new_scope(scope);
182 scopes.add_bindings(scope, pat);
183 }
184 if let Some(block) = e.loop_body() {
185 compute_block_scopes(block, scopes, scope);
186 }
187 }
188 ast::Expr::LambdaExpr(e) => {
189 let scope = scopes.new_scope(scope);
190 scopes.add_params_bindings(scope, e.param_list());
191 if let Some(body) = e.body() {
192 scopes.set_scope(body.syntax(), scope);
193 compute_expr_scopes(body, scopes, scope);
194 }
195 }
196 ast::Expr::CallExpr(e) => {
197 compute_call_scopes(e.expr(), e.arg_list(), scopes, scope);
198 }
199 ast::Expr::MethodCallExpr(e) => {
200 compute_call_scopes(e.expr(), e.arg_list(), scopes, scope);
201 }
202 ast::Expr::MatchExpr(e) => {
203 if let Some(expr) = e.expr() {
204 compute_expr_scopes(expr, scopes, scope);
205 }
206 for arm in e.match_arm_list().into_iter().flat_map(|it| it.arms()) {
207 let scope = scopes.new_scope(scope);
208 for pat in arm.pats() {
209 scopes.add_bindings(scope, pat);
210 }
211 if let Some(expr) = arm.expr() {
212 compute_expr_scopes(expr, scopes, scope);
213 }
214 }
215 }
216 _ => expr
217 .syntax()
218 .children()
219 .filter_map(ast::Expr::cast)
220 .for_each(|expr| compute_expr_scopes(expr, scopes, scope)),
221 };
222
223 fn compute_call_scopes(
224 receiver: Option<ast::Expr>,
225 arg_list: Option<ast::ArgList>,
226 scopes: &mut FnScopes,
227 scope: ScopeId,
228 ) {
229 arg_list
230 .into_iter()
231 .flat_map(|it| it.args())
232 .chain(receiver)
233 .for_each(|expr| compute_expr_scopes(expr, scopes, scope));
234 }
235
236 fn compute_cond_scopes(
237 cond: ast::Condition,
238 scopes: &mut FnScopes,
239 scope: ScopeId,
240 ) -> Option<ScopeId> {
241 if let Some(expr) = cond.expr() {
242 compute_expr_scopes(expr, scopes, scope);
243 }
244 if let Some(pat) = cond.pat() {
245 let s = scopes.new_scope(scope);
246 scopes.add_bindings(s, pat);
247 Some(s)
248 } else {
249 None
250 }
251 }
252}
253
254#[derive(Debug)]
255struct ScopeData {
256 parent: Option<ScopeId>,
257 entries: Vec<ScopeEntry>,
258}
259
260pub fn resolve_local_name<'a>(
261 name_ref: ast::NameRef,
262 scopes: &'a FnScopes,
263) -> Option<&'a ScopeEntry> {
264 use rustc_hash::FxHashSet;
265
266 let mut shadowed = FxHashSet::default();
267 let ret = scopes
268 .scope_chain(name_ref.syntax())
269 .flat_map(|scope| scopes.entries(scope).iter())
270 .filter(|entry| shadowed.insert(entry.name()))
271 .filter(|entry| entry.name() == name_ref.text())
272 .nth(0);
273 ret
274}
275
276#[cfg(test)]
277mod tests {
278 use super::*;
279 use crate::{find_node_at_offset, test_utils::extract_offset};
280 use ra_syntax::File;
281
282 fn do_check(code: &str, expected: &[&str]) {
283 let (off, code) = extract_offset(code);
284 let code = {
285 let mut buf = String::new();
286 let off = u32::from(off) as usize;
287 buf.push_str(&code[..off]);
288 buf.push_str("marker");
289 buf.push_str(&code[off..]);
290 buf
291 };
292 let file = File::parse(&code);
293 let marker: ast::PathExpr = find_node_at_offset(file.syntax(), off).unwrap();
294 let fn_def: ast::FnDef = find_node_at_offset(file.syntax(), off).unwrap();
295 let scopes = FnScopes::new(fn_def);
296 let actual = scopes
297 .scope_chain(marker.syntax())
298 .flat_map(|scope| scopes.entries(scope))
299 .map(|it| it.name())
300 .collect::<Vec<_>>();
301 assert_eq!(actual.as_slice(), expected);
302 }
303
304 #[test]
305 fn test_lambda_scope() {
306 do_check(
307 r"
308 fn quux(foo: i32) {
309 let f = |bar, baz: i32| {
310 <|>
311 };
312 }",
313 &["bar", "baz", "foo"],
314 );
315 }
316
317 #[test]
318 fn test_call_scope() {
319 do_check(
320 r"
321 fn quux() {
322 f(|x| <|> );
323 }",
324 &["x"],
325 );
326 }
327
328 #[test]
329 fn test_metod_call_scope() {
330 do_check(
331 r"
332 fn quux() {
333 z.f(|x| <|> );
334 }",
335 &["x"],
336 );
337 }
338
339 #[test]
340 fn test_loop_scope() {
341 do_check(
342 r"
343 fn quux() {
344 loop {
345 let x = ();
346 <|>
347 };
348 }",
349 &["x"],
350 );
351 }
352
353 #[test]
354 fn test_match() {
355 do_check(
356 r"
357 fn quux() {
358 match () {
359 Some(x) => {
360 <|>
361 }
362 };
363 }",
364 &["x"],
365 );
366 }
367
368 #[test]
369 fn test_shadow_variable() {
370 do_check(
371 r"
372 fn foo(x: String) {
373 let x : &str = &x<|>;
374 }",
375 &["x"],
376 );
377 }
378
379 fn do_check_local_name(code: &str, expected_offset: u32) {
380 let (off, code) = extract_offset(code);
381 let file = File::parse(&code);
382 let fn_def: ast::FnDef = find_node_at_offset(file.syntax(), off).unwrap();
383 let name_ref: ast::NameRef = find_node_at_offset(file.syntax(), off).unwrap();
384
385 let scopes = FnScopes::new(fn_def);
386
387 let local_name = resolve_local_name(name_ref, &scopes)
388 .unwrap()
389 .ast()
390 .name()
391 .unwrap();
392 let expected_name =
393 find_node_at_offset::<ast::Name>(file.syntax(), expected_offset.into()).unwrap();
394 assert_eq!(local_name.syntax().range(), expected_name.syntax().range());
395 }
396
397 #[test]
398 fn test_resolve_local_name() {
399 do_check_local_name(
400 r#"
401 fn foo(x: i32, y: u32) {
402 {
403 let z = x * 2;
404 }
405 {
406 let t = x<|> * 3;
407 }
408 }"#,
409 21,
410 );
411 }
412
413 #[test]
414 fn test_resolve_local_name_declaration() {
415 do_check_local_name(
416 r#"
417 fn foo(x: String) {
418 let x : &str = &x<|>;
419 }"#,
420 21,
421 );
422 }
423
424 #[test]
425 fn test_resolve_local_name_shadow() {
426 do_check_local_name(
427 r"
428 fn foo(x: String) {
429 let x : &str = &x;
430 x<|>
431 }",
432 46,
433 );
434 }
435}