2 use crate::ext::base::{self, *};
3 use crate::ext::build::AstBuilder;
4 use crate::parse::{self, token, DirectoryOwnership};
5 use crate::print::pprust;
7 use crate::symbol::Symbol;
8 use crate::tokenstream;
10 use smallvec::SmallVec;
11 use syntax_pos::{self, Pos, Span};
14 use std::io::ErrorKind;
15 use rustc_data_structures::sync::Lrc;
17 // These macros all relate to the file system; they either return
18 // the column/row/filename of the expression, or they include
19 // a given file into the current one.
21 /// line!(): expands to the current line number
22 pub fn expand_line(cx: &mut ExtCtxt<'_>, sp: Span, tts: &[tokenstream::TokenTree])
23 -> Box<dyn base::MacResult+'static> {
24 base::check_zero_tts(cx, sp, tts, "line!");
26 let topmost = cx.expansion_cause().unwrap_or(sp);
27 let loc = cx.source_map().lookup_char_pos(topmost.lo());
29 base::MacEager::expr(cx.expr_u32(topmost, loc.line as u32))
32 /* column!(): expands to the current column number */
33 pub fn expand_column(cx: &mut ExtCtxt<'_>, sp: Span, tts: &[tokenstream::TokenTree])
34 -> Box<dyn base::MacResult+'static> {
35 base::check_zero_tts(cx, sp, tts, "column!");
37 let topmost = cx.expansion_cause().unwrap_or(sp);
38 let loc = cx.source_map().lookup_char_pos(topmost.lo());
40 base::MacEager::expr(cx.expr_u32(topmost, loc.col.to_usize() as u32 + 1))
43 /// file!(): expands to the current filename */
44 /// The source_file (`loc.file`) contains a bunch more information we could spit
46 pub fn expand_file(cx: &mut ExtCtxt<'_>, sp: Span, tts: &[tokenstream::TokenTree])
47 -> Box<dyn base::MacResult+'static> {
48 base::check_zero_tts(cx, sp, tts, "file!");
50 let topmost = cx.expansion_cause().unwrap_or(sp);
51 let loc = cx.source_map().lookup_char_pos(topmost.lo());
52 base::MacEager::expr(cx.expr_str(topmost, Symbol::intern(&loc.file.name.to_string())))
55 pub fn expand_stringify(cx: &mut ExtCtxt<'_>, sp: Span, tts: &[tokenstream::TokenTree])
56 -> Box<dyn base::MacResult+'static> {
57 let s = pprust::tts_to_string(tts);
58 base::MacEager::expr(cx.expr_str(sp, Symbol::intern(&s)))
61 pub fn expand_mod(cx: &mut ExtCtxt<'_>, sp: Span, tts: &[tokenstream::TokenTree])
62 -> Box<dyn base::MacResult+'static> {
63 base::check_zero_tts(cx, sp, tts, "module_path!");
64 let mod_path = &cx.current_expansion.module.mod_path;
65 let string = mod_path.iter().map(|x| x.to_string()).collect::<Vec<String>>().join("::");
67 base::MacEager::expr(cx.expr_str(sp, Symbol::intern(&string)))
70 /// include! : parse the given file as an expr
71 /// This is generally a bad idea because it's going to behave
73 pub fn expand_include<'cx>(cx: &'cx mut ExtCtxt<'_>, sp: Span, tts: &[tokenstream::TokenTree])
74 -> Box<dyn base::MacResult+'cx> {
75 let file = match get_single_str_from_tts(cx, sp, tts, "include!") {
77 None => return DummyResult::any(sp),
79 // The file will be added to the code map by the parser
80 let file = cx.resolve_path(file, sp);
81 let directory_ownership = DirectoryOwnership::Owned { relative: None };
82 let p = parse::new_sub_parser_from_file(cx.parse_sess(), &file, directory_ownership, None, sp);
84 struct ExpandResult<'a> {
85 p: parse::parser::Parser<'a>,
87 impl<'a> base::MacResult for ExpandResult<'a> {
88 fn make_expr(mut self: Box<ExpandResult<'a>>) -> Option<P<ast::Expr>> {
89 Some(panictry!(self.p.parse_expr()))
92 fn make_items(mut self: Box<ExpandResult<'a>>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
93 let mut ret = SmallVec::new();
94 while self.p.token != token::Eof {
95 match panictry!(self.p.parse_item()) {
96 Some(item) => ret.push(item),
97 None => self.p.diagnostic().span_fatal(self.p.token.span,
98 &format!("expected item, found `{}`",
99 self.p.this_token_to_string()))
107 Box::new(ExpandResult { p })
110 // include_str! : read the given file, insert it as a literal string expr
111 pub fn expand_include_str(cx: &mut ExtCtxt<'_>, sp: Span, tts: &[tokenstream::TokenTree])
112 -> Box<dyn base::MacResult+'static> {
113 let file = match get_single_str_from_tts(cx, sp, tts, "include_str!") {
115 None => return DummyResult::expr(sp)
117 let file = cx.resolve_path(file, sp);
118 match fs::read_to_string(&file) {
120 let interned_src = Symbol::intern(&src);
122 // Add this input file to the code map to make it available as
123 // dependency information
124 cx.source_map().new_source_file(file.into(), src);
126 base::MacEager::expr(cx.expr_str(sp, interned_src))
128 Err(ref e) if e.kind() == ErrorKind::InvalidData => {
129 cx.span_err(sp, &format!("{} wasn't a utf-8 file", file.display()));
130 DummyResult::expr(sp)
133 cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e));
134 DummyResult::expr(sp)
139 pub fn expand_include_bytes(cx: &mut ExtCtxt<'_>, sp: Span, tts: &[tokenstream::TokenTree])
140 -> Box<dyn base::MacResult+'static> {
141 let file = match get_single_str_from_tts(cx, sp, tts, "include_bytes!") {
143 None => return DummyResult::expr(sp)
145 let file = cx.resolve_path(file, sp);
146 match fs::read(&file) {
148 // Add the contents to the source map if it contains UTF-8.
149 let (contents, bytes) = match String::from_utf8(bytes) {
151 let bytes = s.as_bytes().to_owned();
154 Err(e) => (String::new(), e.into_bytes()),
156 cx.source_map().new_source_file(file.into(), contents);
158 base::MacEager::expr(cx.expr_lit(sp, ast::LitKind::ByteStr(Lrc::new(bytes))))
161 cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e));
162 DummyResult::expr(sp)