Add unwrap_node macro

This commit is contained in:
dalance 2019-09-19 15:43:41 +09:00
parent 85a15ebc47
commit e08ced524a
3 changed files with 62 additions and 53 deletions

View File

@ -12,14 +12,24 @@ Parser library for SystemVerilog ([IEEE 1800-2017](https://standards.ieee.org/st
sv-parser = "0.1.0" sv-parser = "0.1.0"
``` ```
sv-parser provides `parse_sv` function which returns `SyntexTree`.
`SyntaxTree` shows Concrete Syntax Tree. It has the preprocessed string and the parsed tree.
`RefNode` shows a reference to any node of `SyntaxTree`.
You can get `RefNode` through an iterator of `SyntaxTree`.
`Locate` shows a position of token. All leaf node of `SyntaxTree` is `Locate`.
You can get string from `Locate` by `SyntaxTree::get_str(self, locate: &Locate)`.
## Example ## Example
The following example parses a SystemVerilog source file and shows module names.
```rust ```rust
use std::collections::HashMap; use std::collections::HashMap;
use std::convert::TryInto;
use std::env; use std::env;
use std::path::PathBuf; use std::path::PathBuf;
use sv_parser::{parse_sv, Locate, RefNode}; use sv_parser::{parse_sv, unwrap_node, Locate, RefNode};
fn main() { fn main() {
let args: Vec<String> = env::args().collect(); let args: Vec<String> = env::args().collect();
@ -31,31 +41,27 @@ fn main() {
// The list of include paths // The list of include paths
let includes: Vec<PathBuf> = Vec::new(); let includes: Vec<PathBuf> = Vec::new();
// Do parse // Parse
let result = parse_sv(&path, &defines, &includes); let result = parse_sv(&path, &defines, &includes);
if let Ok((syntax_tree, _)) = result { if let Ok((syntax_tree, _)) = result {
// SyntexTree is iterable // &SyntaxTree is iterable
for node in &syntax_tree { for node in &syntax_tree {
// The type of Each node is RefNode // The type of each node is RefNode
match node { match node {
RefNode::ModuleDeclarationNonansi(x) => { RefNode::ModuleDeclarationNonansi(x) => {
// The type of header is ModuleNonansiHeader // unwrap_node! gets the nearest ModuleIdentifier from x
let (ref header, _, _, _, _) = x.nodes; let id = unwrap_node!(x, ModuleIdentifier).unwrap();
// The type of name is ModuleIdentifier
let (_, _, _, ref name, _, _, _, _) = header.nodes;
// Any type included in SyntaxTree can be convert RefNode by into() let id = get_identifier(id).unwrap();
let id = get_identifier(name.into()).unwrap();
// Original string can be got by SyntexTree::get_str(self, locate: &Locate) // Original string can be got by SyntaxTree::get_str(self, locate: &Locate)
let id = syntax_tree.get_str(&id); let id = syntax_tree.get_str(&id);
println!("module: {}", id); println!("module: {}", id);
} }
RefNode::ModuleDeclarationAnsi(x) => { RefNode::ModuleDeclarationAnsi(x) => {
let (ref header, _, _, _, _) = x.nodes; let id = unwrap_node!(x, ModuleIdentifier).unwrap();
let (_, _, _, ref name, _, _, _, _) = header.nodes; let id = get_identifier(id).unwrap();
let id = get_identifier(name.into()).unwrap();
let id = syntax_tree.get_str(&id); let id = syntax_tree.get_str(&id);
println!("module: {}", id); println!("module: {}", id);
} }
@ -68,19 +74,15 @@ fn main() {
} }
fn get_identifier(node: RefNode) -> Option<Locate> { fn get_identifier(node: RefNode) -> Option<Locate> {
for n in node { // unwrap_node! can take multiple types
match n { match unwrap_node!(node, SimpleIdentifier, EscapedIdentifier) {
RefNode::SimpleIdentifier(x) => { Some(RefNode::SimpleIdentifier(x)) => {
let x: Locate = x.nodes.0.try_into().unwrap(); return Some(x.nodes.0);
return Some(x);
} }
RefNode::EscapedIdentifier(x) => { Some(RefNode::EscapedIdentifier(x)) => {
let x: Locate = x.nodes.0.try_into().unwrap(); return Some(x.nodes.0);
return Some(x);
} }
_ => (), _ => None,
} }
}
None
} }
``` ```

View File

@ -1,8 +1,7 @@
use std::collections::HashMap; use std::collections::HashMap;
use std::convert::TryInto;
use std::env; use std::env;
use std::path::PathBuf; use std::path::PathBuf;
use sv_parser::{parse_sv, Locate, RefNode}; use sv_parser::{parse_sv, unwrap_node, Locate, RefNode};
fn main() { fn main() {
let args: Vec<String> = env::args().collect(); let args: Vec<String> = env::args().collect();
@ -14,31 +13,27 @@ fn main() {
// The list of include paths // The list of include paths
let includes: Vec<PathBuf> = Vec::new(); let includes: Vec<PathBuf> = Vec::new();
// Do parse // Parse
let result = parse_sv(&path, &defines, &includes); let result = parse_sv(&path, &defines, &includes);
if let Ok((syntax_tree, _)) = result { if let Ok((syntax_tree, _)) = result {
// SyntexTree is iterable // &SyntexTree is iterable
for node in &syntax_tree { for node in &syntax_tree {
// The type of Each node is RefNode // The type of each node is RefNode
match node { match node {
RefNode::ModuleDeclarationNonansi(x) => { RefNode::ModuleDeclarationNonansi(x) => {
// The type of header is ModuleNonansiHeader // unwrap_node! gets the nearest ModuleIdentifier from x
let (ref header, _, _, _, _) = x.nodes; let id = unwrap_node!(x, ModuleIdentifier).unwrap();
// The type of name is ModuleIdentifier
let (_, _, _, ref name, _, _, _, _) = header.nodes;
// Any type included in SyntaxTree can be convert RefNode by into() let id = get_identifier(id).unwrap();
let id = get_identifier(name.into()).unwrap();
// Original string can be got by SyntexTree::get_str(self, locate: &Locate) // Original string can be got by SyntexTree::get_str(self, locate: &Locate)
let id = syntax_tree.get_str(&id); let id = syntax_tree.get_str(&id);
println!("module: {}", id); println!("module: {}", id);
} }
RefNode::ModuleDeclarationAnsi(x) => { RefNode::ModuleDeclarationAnsi(x) => {
let (ref header, _, _, _, _) = x.nodes; let id = unwrap_node!(x, ModuleIdentifier).unwrap();
let (_, _, _, ref name, _, _, _, _) = header.nodes; let id = get_identifier(id).unwrap();
let id = get_identifier(name.into()).unwrap();
let id = syntax_tree.get_str(&id); let id = syntax_tree.get_str(&id);
println!("module: {}", id); println!("module: {}", id);
} }
@ -51,18 +46,14 @@ fn main() {
} }
fn get_identifier(node: RefNode) -> Option<Locate> { fn get_identifier(node: RefNode) -> Option<Locate> {
for n in node { // unwrap_node! can take multiple types
match n { match unwrap_node!(node, SimpleIdentifier, EscapedIdentifier) {
RefNode::SimpleIdentifier(x) => { Some(RefNode::SimpleIdentifier(x)) => {
let x: Locate = x.nodes.0.try_into().unwrap(); return Some(x.nodes.0);
return Some(x);
} }
RefNode::EscapedIdentifier(x) => { Some(RefNode::EscapedIdentifier(x)) => {
let x: Locate = x.nodes.0.try_into().unwrap(); return Some(x.nodes.0);
return Some(x);
} }
_ => (), _ => None,
} }
}
None
} }

View File

@ -102,3 +102,19 @@ pub fn parse_lib<T: AsRef<Path>, U: AsRef<Path>>(
Err(_) => Err(ErrorKind::Parse.into()), Err(_) => Err(ErrorKind::Parse.into()),
} }
} }
#[macro_export]
macro_rules! unwrap_node {
($n:expr, $( $ty:tt ),+) => {{
let unwrap = || {
for x in $n {
match x {
$(RefNode::$ty(x) => return Some(RefNode::$ty(x)),)*
_ => (),
}
}
None
};
unwrap()
}};
}