From 03684f4fe397a3903b3f716eb298412a21e7fe04 Mon Sep 17 00:00:00 2001 From: dalance Date: Fri, 29 Jan 2021 14:00:31 +0900 Subject: [PATCH] Add get_str_trim to SyntaxTree --- CHANGELOG.md | 2 ++ sv-parser/src/lib.rs | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 51f5bd6..5f6e849 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased](https://github.com/dalance/sv-parser/compare/v0.10.6...Unreleased) - ReleaseDate +* [Added] get_str_trim to SyntaxTree + ## [v0.10.6](https://github.com/dalance/sv-parser/compare/v0.10.5...v0.10.6) - 2021-01-28 * [Fixed] constant_expression_ternary priority [#30](https://github.com/dalance/sv-parser/issues/30) diff --git a/sv-parser/src/lib.rs b/sv-parser/src/lib.rs index db4811e..2373edb 100644 --- a/sv-parser/src/lib.rs +++ b/sv-parser/src/lib.rs @@ -20,6 +20,7 @@ pub struct SyntaxTree { } impl SyntaxTree { + /// Get `&str` from the specified node pub fn get_str<'a, T: Into>>(&self, nodes: T) -> Option<&str> { let mut beg = None; let mut end = 0; @@ -39,6 +40,37 @@ impl SyntaxTree { } } + /// Get `&str` without trailing `WhiteSpace` from the specified node + pub fn get_str_trim<'a, T: Into>>(&self, nodes: T) -> Option<&str> { + let mut beg = None; + let mut end = 0; + let mut skip = false; + for n in Iter::new(nodes.into()).event() { + match n { + NodeEvent::Enter(RefNode::WhiteSpace(_)) => { + skip = true; + } + NodeEvent::Leave(RefNode::WhiteSpace(_)) => { + skip = false; + } + NodeEvent::Enter(RefNode::Locate(x)) if !skip => { + 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 + } + } + + /// Get source code location of the specified `Locate` pub fn get_origin(&self, locate: &Locate) -> Option<(&PathBuf, usize)> { self.text.origin(locate.offset) }