rustc 可以加載編譯器插件,它是用戶提供的庫,這個庫使用新語法擴展編譯器的行為,lint 檢查等。
插件是一個有指定的 registrar 函數的動態(tài)庫,注冊 rustc 擴展。其它庫可以使用屬性 #![plugin(...)]
加載這些擴展。想了解更多關于定義機制和加載插件,查看 rustc::plugin 文檔。
如果存在,像 #![plugin(foo(... args ...))]
傳遞的參數不被 rustc 本身編譯。他們通過注冊表參數的方法提供給插件?! ?/p>
在絕大多數情況下,一個插件只能通過 #![plugin] 而不是通過一個 extern crate 項目來被使用。連接一個插件將會把所有 libsyntax 和 librustc 作為庫的依賴關系。這通常是不必要的,除非你正在創(chuàng)建另一個插件。plugin_as_library lint
檢查這些準則。
通常的做法是將編譯器插件放入自己的庫中,獨立于庫中被客戶端使用的任何 macro_rules ! 宏或普通 Rust 代碼。
插件可以用不同的方法擴展 Rust 的語法。一種語法擴展是程序宏。調用程序宏就像調用普通的宏一樣,但擴展是由任意在運行時操縱語法樹的 Rust 代碼執(zhí)行?! ?/p>
讓我們寫一個插件 roman_numerals.rs
實現羅馬數字整數常量。
#![crate_type="dylib"]
#![feature(plugin_registrar, rustc_private)]
extern crate syntax;
extern crate rustc;
use syntax::codemap::Span;
use syntax::parse::token;
use syntax::ast::{TokenTree, TtToken};
use syntax::ext::base::{ExtCtxt, MacResult, DummyResult, MacEager};
use syntax::ext::build::AstBuilder; // trait for expr_usize
use rustc::plugin::Registry;
fn expand_rn(cx: &mut ExtCtxt, sp: Span, args: &[TokenTree])
-> Box<MacResult + 'static> {
static NUMERALS: &'static [(&'static str, u32)] = &[
("M", 1000), ("CM", 900), ("D", 500), ("CD", 400),
("C", 100), ("XC", 90), ("L", 50), ("XL", 40),
("X", 10), ("IX", 9), ("V", 5), ("IV", 4),
("I",1)];
let text = match args {
[TtToken(_, token::Ident(s, _))] => token::get_ident(s).to_string(),
_ => {
cx.span_err(sp, "argument should be a single identifier");
return DummyResult::any(sp);
}
};
let mut text = &*text;
let mut total = 0;
while !text.is_empty() {
match NUMERALS.iter().find(|&&(rn, _)| text.starts_with(rn)) {
Some(&(rn, val)) => {
total += val;
text = &text[rn.len()..];
}
None => {
cx.span_err(sp, "invalid Roman numeral");
return DummyResult::any(sp);
}
}
}
MacEager::expr(cx.expr_u32(sp, total))
}
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_macro("rn", expand_rn);
}
然后我們可以像使用其他宏一樣使用 rn !():
#![feature(plugin)]
#![plugin(roman_numerals)]
fn main() {
assert_eq!(rn!(MMXV), 2015);
}
一個簡單的 fn(&str) -> u32
的優(yōu)勢是:
除了程序宏,你可以定義新的 derive-like 屬性和其他類型的擴展。請看Registry::register_syntax_extension 和 SyntaxExtension enum。更多調用宏的例子,請見 regex_macros。
有一些宏的調試技巧是適用的?! ?/p>
您可以使用 syntax::parse 將標記樹轉化為更高級的語法元素如表達式:
fn expand_foo(cx: &mut ExtCtxt, sp: Span, args: &[TokenTree])
-> Box<MacResult+'static> {
let mut parser = cx.new_parser_from_tts(args);
let expr: P<Expr> = parser.parse_expr();
通過這些 libsyntax 解析代碼我們可以知道解析基礎結構是如何工作的?! ?/p>
為得到更準確的錯誤報告,保持所有你解析的代碼的 span 。你可以將 spaned 封裝到自定義數據結構中?! ?/p>
調用 ExtCtxt:span_fatal 會立即中止編譯。最好不要調用 ExtCtxt:span_err 并返回 DummyResult,編譯器可以繼續(xù)并找到更多的錯誤?! ?/p>
為了打印語法片段進行調試,可以使用 span\_note
加上 syntax::print::pprust::*_to_string
。
上面的例子使用 AstBuilder::expr_usize 產生一個整數。除了 AstBuilder 特征,libsyntax 提供了一組 quasiquote 宏。他們沒有正式文件并且非常粗糙的。然而,它的實現可能是一個改進的一個普通的插件庫 quasiquote 的好的起點 。
插件可以通過對額外的代碼類型、安全等等的檢查來擴展 Rust 的 lint 基礎結構。在 src/test/auxiliary/lint_plugin\_test.rs
中你可以看到一個完整的例子。這個例子的核心如下:
declare_lint!(TEST_LINT, Warn,
"Warn about items named 'lintme'");
struct Pass;
impl LintPass for Pass {
fn get_lints(&self) -> LintArray {
lint_array!(TEST_LINT)
}
fn check_item(&mut self, cx: &Context, it: &ast::Item) {
let name = token::get_ident(it.ident);
if name.get() == "lintme" {
cx.span_lint(TEST_LINT, it.span, "item is named 'lintme'");
}
}
}
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_lint_pass(box Pass as LintPassObject);
}
然后代碼
#![plugin(lint_plugin_test)]
fn lintme() { }
將會產生一個編譯器警告:
foo.rs:4:1: 4:16 warning: item is named 'lintme', #[warn(test_lint)] on by default
foo.rs:4 fn lintme() { }
lint插件的組件如下:
Lint 通過遍歷語法,但他們在編譯的后期運行,在哪里可以獲得類型信息。rustc 內置的 lint 大多使用相同的基礎結構作為 lint 插件,并提供了一些說明如何訪問類型信息的例子。
插件定義的 lint 是由通常的屬性和編譯器標志所控制,例如 #[allow(test_lint)]
或 -A test-lint
。通過合適的案例和標點符號的轉換,這些標識符由第一個參數傳遞到 declare_lint !。
您可以運行 rustc -W help foo.rs 來看 rustc 知道的 lint 的列表,包括那些由foo.rs 加載的插件提供的列表。
更多建議: