Files
rust/crates/ra_analysis/src/syntax_ptr.rs

49 lines
1.4 KiB
Rust
Raw Normal View History

2018-11-07 18:32:33 +03:00
use ra_syntax::{SourceFileNode, SyntaxKind, SyntaxNode, SyntaxNodeRef, TextRange};
2018-10-30 21:23:23 +03:00
/// A pionter to a syntax node inside a file.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) struct LocalSyntaxPtr {
2018-10-30 21:23:23 +03:00
range: TextRange,
kind: SyntaxKind,
}
impl LocalSyntaxPtr {
pub(crate) fn new(node: SyntaxNodeRef) -> LocalSyntaxPtr {
2018-10-30 21:23:23 +03:00
LocalSyntaxPtr {
range: node.range(),
kind: node.kind(),
}
}
2018-11-07 18:32:33 +03:00
pub(crate) fn resolve(self, file: &SourceFileNode) -> SyntaxNode {
2018-10-30 21:23:23 +03:00
let mut curr = file.syntax();
loop {
if curr.range() == self.range && curr.kind() == self.kind {
return curr.owned();
}
2018-10-31 23:41:43 +03:00
curr = curr
.children()
2018-10-30 21:23:23 +03:00
.find(|it| self.range.is_subrange(&it.range()))
2018-10-31 09:39:31 -04:00
.unwrap_or_else(|| panic!("can't resolve local ptr to SyntaxNode: {:?}", self))
2018-10-30 21:23:23 +03:00
}
}
2018-10-31 15:13:49 +03:00
2018-11-28 01:11:29 +03:00
pub(crate) fn range(self) -> TextRange {
self.range
2018-10-31 15:13:49 +03:00
}
2018-10-30 21:23:23 +03:00
}
#[test]
fn test_local_syntax_ptr() {
2018-11-01 00:00:43 +03:00
use ra_syntax::{ast, AstNode};
2018-11-07 18:32:33 +03:00
let file = SourceFileNode::parse("struct Foo { f: u32, }");
2018-10-31 23:41:43 +03:00
let field = file
.syntax()
.descendants()
.find_map(ast::NamedFieldDef::cast)
.unwrap();
2018-10-30 21:23:23 +03:00
let ptr = LocalSyntaxPtr::new(field.syntax());
let field_syntax = ptr.resolve(&file);
assert_eq!(field.syntax(), field_syntax);
}