簡體   English   中英

如何獲得語法的絕對名稱:: ast :: Ident?

[英]How can I get the absolute name of a syntax::ast::Ident?

我正在嘗試從以下Rust代碼中提取函數名稱。

// example.rs

pub mod hello {
    pub mod world {
        pub fn greetings() {
            println!("Hello, world!")
        }
    }
}

這是試圖從example.rs提取函數名的代碼。

//runner.rs

/*
 * This program will only compile with nightly Rust
 *
 * To compile
 * rustc runner.rs
 *
 * To run
 * LD_LIBRARY_PATH=$(rustc --print sysroot)/lib ./runner
*/

#![feature(rustc_private)]
extern crate syntax;

use syntax::visit::{ self, Visitor, FnKind };
use syntax::ast::{ FnDecl, Block, NodeId, Mac };
use syntax::codemap::{ Span };
use syntax::{ parse, ast };
use std::path::Path;

struct MyVisitor;

impl<'x> Visitor<'x> for MyVisitor {
    fn visit_fn<'v>(&mut self, fk: FnKind<'v>, fd: &'v FnDecl, b: &'v Block, s: Span, _: NodeId) {
        let name;
        match fk {
            visit::FnKind::Method(_ident, ref _method_sig, _option) => {
                name = (*_ident.name.as_str()).to_string();
            }
            visit::FnKind::ItemFn(_ident, ref _generics, _unsafety, _constness, _abi, _visibility) => {
                name = (*_ident.name.as_str()).to_string();
            }
            visit::FnKind::Closure => {
                name = "".to_string();
            }
        };
        println!("{}", name);
        visit::walk_fn(self, fk, fd, b, s);
    }

    fn visit_mac<'v>(&mut self, _mac: &'v Mac) {
        // do nothing
        // just overriding here because parent panics as
        // panic!("visit_mac disabled by default");
    }
}

fn build_crate(path: &std::path::Path) -> ast::Crate {
    let sess = parse::ParseSess::new();
    let filemap = sess.codemap().load_file(path).unwrap();
    let cfg = ast::CrateConfig::new();
    let reader = parse::lexer::StringReader::new(&sess.span_diagnostic, filemap);
    let mut parser = parse::parser::Parser::new(&sess, cfg, Box::new(reader));
    return parser.parse_crate_mod().unwrap();
}

fn main() {
    let krate = build_crate(Path::new("./example.rs"));
    let mut visitor = MyVisitor {};
    visit::walk_crate(&mut visitor, &krate);
}

問題是它打印greetings作為輸出,但我想要完全限定的名稱,即hello::world::greetings 我怎么做?

你不能。 Ident只是一個名稱(+有關宏擴展的一些信息)。

你可以做的是使用你的訪問者來構建模塊路徑,同時實現visit_item方法並存儲當前路徑:

fn visit_item(&mut self, i: &'v Item) {
    self.modules.push(i.ident);
    walk_item(self, i);
    self.modules.pop();
}

然后你可以打印整個路徑:

for ident in &self.modules {
    print!("::{}", ident.name.as_str());
}
println!("");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM