Change get_str

This commit is contained in:
dalance 2019-10-29 15:37:16 +09:00
parent 6abcdae565
commit 4d996a5edd
3 changed files with 28 additions and 9 deletions

View File

@ -2,6 +2,7 @@
## [Unreleased](https://github.com/dalance/sv-parser/compare/v0.2.1...Unreleased) - ReleaseDate ## [Unreleased](https://github.com/dalance/sv-parser/compare/v0.2.1...Unreleased) - ReleaseDate
* [Changed] SyntaxTree::get_str can take &RefNode
* [Added] unwrap_locate macro * [Added] unwrap_locate macro
## [v0.2.1](https://github.com/dalance/sv-parser/compare/v0.2.0...v0.2.1) - 2019-10-28 ## [v0.2.1](https://github.com/dalance/sv-parser/compare/v0.2.0...v0.2.1) - 2019-10-28

View File

@ -27,14 +27,14 @@ fn main() {
let id = get_identifier(id).unwrap(); let id = get_identifier(id).unwrap();
// Original string can be got by SyntexTree::get_str(self, locate: &Locate) // Original string can be got by SyntexTree::get_str(self, node: &RefNode)
let id = syntax_tree.get_str(&id); let id = syntax_tree.get_str(&id).unwrap();
println!("module: {}", id); println!("module: {}", id);
} }
RefNode::ModuleDeclarationAnsi(x) => { RefNode::ModuleDeclarationAnsi(x) => {
let id = unwrap_node!(x, ModuleIdentifier).unwrap(); let id = unwrap_node!(x, ModuleIdentifier).unwrap();
let id = get_identifier(id).unwrap(); let id = get_identifier(id).unwrap();
let id = syntax_tree.get_str(&id); let id = syntax_tree.get_str(&id).unwrap();
println!("module: {}", id); println!("module: {}", id);
} }
_ => (), _ => (),

View File

@ -16,11 +16,25 @@ pub struct SyntaxTree {
} }
impl SyntaxTree { impl SyntaxTree {
pub fn get_str(&self, locate: &Locate) -> &str { pub fn get_str<'a, T: Into<RefNodes<'a>>>(&self, nodes: T) -> Option<&str> {
unsafe { let mut beg = None;
self.text let mut end = 0;
.text() for n in Iter::new(nodes.into()) {
.get_unchecked(locate.offset..locate.offset + locate.len) match n {
RefNode::Locate(x) => {
if beg.is_none() {
beg = Some(x.offset);
}
end = x.offset + x.len;
}
_ => (),
}
}
if let Some(beg) = beg {
let ret = unsafe { self.text.text().get_unchecked(beg..end) };
Some(ret)
} else {
None
} }
} }
@ -37,7 +51,11 @@ impl fmt::Display for SyntaxTree {
for node in self.into_iter().event() { for node in self.into_iter().event() {
match node { match node {
NodeEvent::Enter(RefNode::Locate(locate)) if !skip => { NodeEvent::Enter(RefNode::Locate(locate)) if !skip => {
ret.push_str(&format!("{}{}\n", " ".repeat(depth), self.get_str(locate))); ret.push_str(&format!(
"{}{}\n",
" ".repeat(depth),
self.get_str(locate).unwrap()
));
depth += 1; depth += 1;
} }
NodeEvent::Enter(RefNode::WhiteSpace(_)) => { NodeEvent::Enter(RefNode::WhiteSpace(_)) => {