2019-11-18 14:23:24 +03:00
|
|
|
//! Utilities to work with files, produced by macros.
|
|
|
|
use std::iter::successors;
|
|
|
|
|
|
|
|
use hir::Source;
|
|
|
|
use ra_db::FileId;
|
|
|
|
use ra_syntax::{ast, AstNode, SyntaxNode, SyntaxToken};
|
|
|
|
|
|
|
|
use crate::{db::RootDatabase, FileRange};
|
|
|
|
|
|
|
|
pub(crate) fn original_range(db: &RootDatabase, node: Source<&SyntaxNode>) -> FileRange {
|
2019-11-18 15:08:39 +03:00
|
|
|
let expansion = match node.file_id.expansion_info(db) {
|
|
|
|
None => {
|
|
|
|
return FileRange {
|
|
|
|
file_id: node.file_id.original_file(db),
|
2019-11-20 09:40:36 +03:00
|
|
|
range: node.value.text_range(),
|
2019-11-18 15:08:39 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
Some(it) => it,
|
|
|
|
};
|
|
|
|
// FIXME: the following completely wrong.
|
|
|
|
//
|
|
|
|
// *First*, we should try to map first and last tokens of node, and, if that
|
|
|
|
// fails, return the range of the overall macro expansions.
|
|
|
|
//
|
|
|
|
// *Second*, we should handle recurside macro expansions
|
|
|
|
|
|
|
|
let token = node
|
2019-11-20 09:40:36 +03:00
|
|
|
.value
|
2019-11-18 15:08:39 +03:00
|
|
|
.descendants_with_tokens()
|
|
|
|
.filter_map(|it| it.into_token())
|
2019-11-20 13:09:21 +03:00
|
|
|
.find_map(|it| expansion.map_token_up(node.with_value(&it)));
|
2019-11-18 14:23:24 +03:00
|
|
|
|
2019-11-18 15:08:39 +03:00
|
|
|
match token {
|
2019-11-20 09:40:36 +03:00
|
|
|
Some(it) => {
|
|
|
|
FileRange { file_id: it.file_id.original_file(db), range: it.value.text_range() }
|
|
|
|
}
|
|
|
|
None => {
|
|
|
|
FileRange { file_id: node.file_id.original_file(db), range: node.value.text_range() }
|
|
|
|
}
|
2019-11-18 15:08:39 +03:00
|
|
|
}
|
2019-11-18 14:23:24 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
pub(crate) fn descend_into_macros(
|
|
|
|
db: &RootDatabase,
|
|
|
|
file_id: FileId,
|
|
|
|
token: SyntaxToken,
|
|
|
|
) -> Source<SyntaxToken> {
|
|
|
|
let src = Source::new(file_id.into(), token);
|
|
|
|
|
|
|
|
successors(Some(src), |token| {
|
2019-11-20 09:40:36 +03:00
|
|
|
let macro_call = token.value.ancestors().find_map(ast::MacroCall::cast)?;
|
2019-11-18 14:23:24 +03:00
|
|
|
let tt = macro_call.token_tree()?;
|
2019-11-20 09:40:36 +03:00
|
|
|
if !token.value.text_range().is_subrange(&tt.syntax().text_range()) {
|
2019-11-18 14:23:24 +03:00
|
|
|
return None;
|
|
|
|
}
|
|
|
|
let source_analyzer =
|
2019-11-20 13:09:21 +03:00
|
|
|
hir::SourceAnalyzer::new(db, token.with_value(token.value.parent()).as_ref(), None);
|
2019-11-20 12:21:31 +08:00
|
|
|
let exp = source_analyzer.expand(db, token.with_value(¯o_call))?;
|
2019-11-18 14:23:24 +03:00
|
|
|
exp.map_token_down(db, token.as_ref())
|
|
|
|
})
|
|
|
|
.last()
|
|
|
|
.unwrap()
|
|
|
|
}
|