rust/src/libsyntax_ext/source_util.rs

215 lines
6.8 KiB
Rust
Raw Normal View History

2019-12-22 22:42:04 +00:00
use rustc_parse::{self, new_sub_parser_from_file, parser::Parser, DirectoryOwnership};
use syntax::ast;
2019-12-22 22:42:04 +00:00
use syntax::early_buffered_lints::INCOMPLETE_INCLUDE;
use syntax::print::pprust;
use syntax::ptr::P;
use syntax::symbol::Symbol;
2019-10-11 10:46:32 +00:00
use syntax::token;
use syntax::tokenstream::TokenStream;
use syntax_expand::base::{self, *};
2019-12-22 22:42:04 +00:00
use syntax_expand::panictry;
2019-02-06 17:33:01 +00:00
2018-08-30 09:42:16 +00:00
use smallvec::SmallVec;
use syntax_pos::{self, Pos, Span};
2018-02-27 16:11:14 +00:00
use rustc_data_structures::sync::Lrc;
// These macros all relate to the file system; they either return
// the column/row/filename of the expression, or they include
// a given file into the current one.
2014-06-09 20:12:30 +00:00
/// line!(): expands to the current line number
2019-12-22 22:42:04 +00:00
pub fn expand_line(
cx: &mut ExtCtxt<'_>,
sp: Span,
tts: TokenStream,
) -> Box<dyn base::MacResult + 'static> {
let sp = cx.with_def_site_ctxt(sp);
base::check_zero_tts(cx, sp, tts, "line!");
2017-05-15 09:41:05 +00:00
let topmost = cx.expansion_cause().unwrap_or(sp);
2018-08-18 10:14:09 +00:00
let loc = cx.source_map().lookup_char_pos(topmost.lo());
base::MacEager::expr(cx.expr_u32(topmost, loc.line as u32))
}
/* column!(): expands to the current column number */
2019-12-22 22:42:04 +00:00
pub fn expand_column(
cx: &mut ExtCtxt<'_>,
sp: Span,
tts: TokenStream,
) -> Box<dyn base::MacResult + 'static> {
let sp = cx.with_def_site_ctxt(sp);
base::check_zero_tts(cx, sp, tts, "column!");
2017-05-15 09:41:05 +00:00
let topmost = cx.expansion_cause().unwrap_or(sp);
2018-08-18 10:14:09 +00:00
let loc = cx.source_map().lookup_char_pos(topmost.lo());
2015-02-21 11:56:46 +00:00
base::MacEager::expr(cx.expr_u32(topmost, loc.col.to_usize() as u32 + 1))
}
2014-06-09 20:12:30 +00:00
/// file!(): expands to the current filename */
2018-08-18 10:13:56 +00:00
/// The source_file (`loc.file`) contains a bunch more information we could spit
2014-06-09 20:12:30 +00:00
/// out if we wanted.
2019-12-22 22:42:04 +00:00
pub fn expand_file(
cx: &mut ExtCtxt<'_>,
sp: Span,
tts: TokenStream,
) -> Box<dyn base::MacResult + 'static> {
let sp = cx.with_def_site_ctxt(sp);
base::check_zero_tts(cx, sp, tts, "file!");
2017-05-15 09:41:05 +00:00
let topmost = cx.expansion_cause().unwrap_or(sp);
2018-08-18 10:14:09 +00:00
let loc = cx.source_map().lookup_char_pos(topmost.lo());
base::MacEager::expr(cx.expr_str(topmost, Symbol::intern(&loc.file.name.to_string())))
}
2019-12-22 22:42:04 +00:00
pub fn expand_stringify(
cx: &mut ExtCtxt<'_>,
sp: Span,
tts: TokenStream,
) -> Box<dyn base::MacResult + 'static> {
let sp = cx.with_def_site_ctxt(sp);
let s = pprust::tts_to_string(tts);
base::MacEager::expr(cx.expr_str(sp, Symbol::intern(&s)))
}
2019-12-22 22:42:04 +00:00
pub fn expand_mod(
cx: &mut ExtCtxt<'_>,
sp: Span,
tts: TokenStream,
) -> Box<dyn base::MacResult + 'static> {
let sp = cx.with_def_site_ctxt(sp);
base::check_zero_tts(cx, sp, tts, "module_path!");
let mod_path = &cx.current_expansion.module.mod_path;
let string = mod_path.iter().map(|x| x.to_string()).collect::<Vec<String>>().join("::");
2016-09-01 06:44:54 +00:00
base::MacEager::expr(cx.expr_str(sp, Symbol::intern(&string)))
}
2014-06-09 20:12:30 +00:00
/// include! : parse the given file as an expr
/// This is generally a bad idea because it's going to behave
/// unhygienically.
2019-12-22 22:42:04 +00:00
pub fn expand_include<'cx>(
cx: &'cx mut ExtCtxt<'_>,
sp: Span,
tts: TokenStream,
) -> Box<dyn base::MacResult + 'cx> {
let sp = cx.with_def_site_ctxt(sp);
let file = match get_single_str_from_tts(cx, sp, tts, "include!") {
Some(f) => f,
None => return DummyResult::any(sp),
};
// The file will be added to the code map by the parser
let file = match cx.resolve_path(file, sp) {
Ok(f) => f,
Err(mut err) => {
err.emit();
return DummyResult::any(sp);
2019-12-22 22:42:04 +00:00
}
};
2017-11-28 02:14:24 +00:00
let directory_ownership = DirectoryOwnership::Owned { relative: None };
let p = new_sub_parser_from_file(cx.parse_sess(), &file, directory_ownership, None, sp);
struct ExpandResult<'a> {
p: Parser<'a>,
}
impl<'a> base::MacResult for ExpandResult<'a> {
fn make_expr(mut self: Box<ExpandResult<'a>>) -> Option<P<ast::Expr>> {
let r = panictry!(self.p.parse_expr());
if self.p.token != token::Eof {
self.p.sess.buffer_lint(
&INCOMPLETE_INCLUDE,
self.p.token.span,
ast::CRATE_NODE_ID,
"include macro expected single expression in source",
);
}
Some(r)
}
2018-08-30 09:42:16 +00:00
fn make_items(mut self: Box<ExpandResult<'a>>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
let mut ret = SmallVec::new();
while self.p.token != token::Eof {
match panictry!(self.p.parse_item()) {
Some(item) => ret.push(item),
2019-12-22 22:42:04 +00:00
None => self
.p
.sess
.span_diagnostic
.span_fatal(
self.p.token.span,
&format!("expected item, found `{}`", self.p.this_token_to_string()),
)
.raise(),
}
}
Some(ret)
}
}
2018-11-06 20:05:44 +00:00
Box::new(ExpandResult { p })
}
// include_str! : read the given file, insert it as a literal string expr
2019-12-22 22:42:04 +00:00
pub fn expand_include_str(
cx: &mut ExtCtxt<'_>,
sp: Span,
tts: TokenStream,
) -> Box<dyn base::MacResult + 'static> {
let sp = cx.with_def_site_ctxt(sp);
let file = match get_single_str_from_tts(cx, sp, tts, "include_str!") {
Some(f) => f,
2019-12-22 22:42:04 +00:00
None => return DummyResult::any(sp),
};
let file = match cx.resolve_path(file, sp) {
Ok(f) => f,
Err(mut err) => {
err.emit();
return DummyResult::any(sp);
2019-12-22 22:42:04 +00:00
}
};
match cx.source_map().load_binary_file(&file) {
Ok(bytes) => match std::str::from_utf8(&bytes) {
Ok(src) => {
let interned_src = Symbol::intern(&src);
base::MacEager::expr(cx.expr_str(sp, interned_src))
}
Err(_) => {
cx.span_err(sp, &format!("{} wasn't a utf-8 file", file.display()));
DummyResult::any(sp)
}
},
Err(e) => {
cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e));
DummyResult::any(sp)
}
}
}
2019-12-22 22:42:04 +00:00
pub fn expand_include_bytes(
cx: &mut ExtCtxt<'_>,
sp: Span,
tts: TokenStream,
) -> Box<dyn base::MacResult + 'static> {
let sp = cx.with_def_site_ctxt(sp);
let file = match get_single_str_from_tts(cx, sp, tts, "include_bytes!") {
Some(f) => f,
2019-12-22 22:42:04 +00:00
None => return DummyResult::any(sp),
};
let file = match cx.resolve_path(file, sp) {
Ok(f) => f,
Err(mut err) => {
err.emit();
return DummyResult::any(sp);
2019-12-22 22:42:04 +00:00
}
};
match cx.source_map().load_binary_file(&file) {
2019-12-22 22:42:04 +00:00
Ok(bytes) => base::MacEager::expr(cx.expr_lit(sp, ast::LitKind::ByteStr(Lrc::new(bytes)))),
Err(e) => {
cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e));
DummyResult::any(sp)
}
2012-05-18 17:03:27 +00:00
}
}