1 use rustc_ast as ast;
2 use rustc_ast::ptr::P;
3 use rustc_ast::token;
4 use rustc_ast::tokenstream::TokenStream;
5 use rustc_ast_pretty::pprust;
6 use rustc_expand::base::{self, *};
7 use rustc_expand::module::DirOwnership;
8 use rustc_parse::parser::{ForceCollect, Parser};
9 use rustc_parse::{self, new_parser_from_file};
10 use rustc_session::lint::builtin::INCOMPLETE_INCLUDE;
11 use rustc_span::symbol::Symbol;
12 use rustc_span::{self, Pos, Span};
13 
14 use smallvec::SmallVec;
15 use std::rc::Rc;
16 
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.
20 
21 /// line!(): expands to the current line number
expand_line( cx: &mut ExtCtxt<'_>, sp: Span, tts: TokenStream, ) -> Box<dyn base::MacResult + 'static>22 pub fn expand_line(
23     cx: &mut ExtCtxt<'_>,
24     sp: Span,
25     tts: TokenStream,
26 ) -> Box<dyn base::MacResult + 'static> {
27     let sp = cx.with_def_site_ctxt(sp);
28     base::check_zero_tts(cx, sp, tts, "line!");
29 
30     let topmost = cx.expansion_cause().unwrap_or(sp);
31     let loc = cx.source_map().lookup_char_pos(topmost.lo());
32 
33     base::MacEager::expr(cx.expr_u32(topmost, loc.line as u32))
34 }
35 
36 /* column!(): expands to the current column number */
expand_column( cx: &mut ExtCtxt<'_>, sp: Span, tts: TokenStream, ) -> Box<dyn base::MacResult + 'static>37 pub fn expand_column(
38     cx: &mut ExtCtxt<'_>,
39     sp: Span,
40     tts: TokenStream,
41 ) -> Box<dyn base::MacResult + 'static> {
42     let sp = cx.with_def_site_ctxt(sp);
43     base::check_zero_tts(cx, sp, tts, "column!");
44 
45     let topmost = cx.expansion_cause().unwrap_or(sp);
46     let loc = cx.source_map().lookup_char_pos(topmost.lo());
47 
48     base::MacEager::expr(cx.expr_u32(topmost, loc.col.to_usize() as u32 + 1))
49 }
50 
51 /// file!(): expands to the current filename */
52 /// The source_file (`loc.file`) contains a bunch more information we could spit
53 /// out if we wanted.
expand_file( cx: &mut ExtCtxt<'_>, sp: Span, tts: TokenStream, ) -> Box<dyn base::MacResult + 'static>54 pub fn expand_file(
55     cx: &mut ExtCtxt<'_>,
56     sp: Span,
57     tts: TokenStream,
58 ) -> Box<dyn base::MacResult + 'static> {
59     let sp = cx.with_def_site_ctxt(sp);
60     base::check_zero_tts(cx, sp, tts, "file!");
61 
62     let topmost = cx.expansion_cause().unwrap_or(sp);
63     let loc = cx.source_map().lookup_char_pos(topmost.lo());
64     base::MacEager::expr(
65         cx.expr_str(topmost, Symbol::intern(&loc.file.name.prefer_remapped().to_string_lossy())),
66     )
67 }
68 
expand_stringify( cx: &mut ExtCtxt<'_>, sp: Span, tts: TokenStream, ) -> Box<dyn base::MacResult + 'static>69 pub fn expand_stringify(
70     cx: &mut ExtCtxt<'_>,
71     sp: Span,
72     tts: TokenStream,
73 ) -> Box<dyn base::MacResult + 'static> {
74     let sp = cx.with_def_site_ctxt(sp);
75     let s = pprust::tts_to_string(&tts);
76     base::MacEager::expr(cx.expr_str(sp, Symbol::intern(&s)))
77 }
78 
expand_mod( cx: &mut ExtCtxt<'_>, sp: Span, tts: TokenStream, ) -> Box<dyn base::MacResult + 'static>79 pub fn expand_mod(
80     cx: &mut ExtCtxt<'_>,
81     sp: Span,
82     tts: TokenStream,
83 ) -> Box<dyn base::MacResult + 'static> {
84     let sp = cx.with_def_site_ctxt(sp);
85     base::check_zero_tts(cx, sp, tts, "module_path!");
86     let mod_path = &cx.current_expansion.module.mod_path;
87     let string = mod_path.iter().map(|x| x.to_string()).collect::<Vec<String>>().join("::");
88 
89     base::MacEager::expr(cx.expr_str(sp, Symbol::intern(&string)))
90 }
91 
92 /// include! : parse the given file as an expr
93 /// This is generally a bad idea because it's going to behave
94 /// unhygienically.
expand_include<'cx>( cx: &'cx mut ExtCtxt<'_>, sp: Span, tts: TokenStream, ) -> Box<dyn base::MacResult + 'cx>95 pub fn expand_include<'cx>(
96     cx: &'cx mut ExtCtxt<'_>,
97     sp: Span,
98     tts: TokenStream,
99 ) -> Box<dyn base::MacResult + 'cx> {
100     let sp = cx.with_def_site_ctxt(sp);
101     let file = match get_single_str_from_tts(cx, sp, tts, "include!") {
102         Some(f) => f,
103         None => return DummyResult::any(sp),
104     };
105     // The file will be added to the code map by the parser
106     let file = match cx.resolve_path(file, sp) {
107         Ok(f) => f,
108         Err(mut err) => {
109             err.emit();
110             return DummyResult::any(sp);
111         }
112     };
113     let p = new_parser_from_file(cx.parse_sess(), &file, Some(sp));
114 
115     // If in the included file we have e.g., `mod bar;`,
116     // then the path of `bar.rs` should be relative to the directory of `file`.
117     // See https://github.com/rust-lang/rust/pull/69838/files#r395217057 for a discussion.
118     // `MacroExpander::fully_expand_fragment` later restores, so "stack discipline" is maintained.
119     let dir_path = file.parent().unwrap_or(&file).to_owned();
120     cx.current_expansion.module = Rc::new(cx.current_expansion.module.with_dir_path(dir_path));
121     cx.current_expansion.dir_ownership = DirOwnership::Owned { relative: None };
122 
123     struct ExpandResult<'a> {
124         p: Parser<'a>,
125         node_id: ast::NodeId,
126     }
127     impl<'a> base::MacResult for ExpandResult<'a> {
128         fn make_expr(mut self: Box<ExpandResult<'a>>) -> Option<P<ast::Expr>> {
129             let r = base::parse_expr(&mut self.p)?;
130             if self.p.token != token::Eof {
131                 self.p.sess.buffer_lint(
132                     &INCOMPLETE_INCLUDE,
133                     self.p.token.span,
134                     self.node_id,
135                     "include macro expected single expression in source",
136                 );
137             }
138             Some(r)
139         }
140 
141         fn make_items(mut self: Box<ExpandResult<'a>>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
142             let mut ret = SmallVec::new();
143             while self.p.token != token::Eof {
144                 match self.p.parse_item(ForceCollect::No) {
145                     Err(mut err) => {
146                         err.emit();
147                         break;
148                     }
149                     Ok(Some(item)) => ret.push(item),
150                     Ok(None) => {
151                         let token = pprust::token_to_string(&self.p.token);
152                         let msg = format!("expected item, found `{}`", token);
153                         self.p.struct_span_err(self.p.token.span, &msg).emit();
154                         break;
155                     }
156                 }
157             }
158             Some(ret)
159         }
160     }
161 
162     Box::new(ExpandResult { p, node_id: cx.current_expansion.lint_node_id })
163 }
164 
165 // include_str! : read the given file, insert it as a literal string expr
expand_include_str( cx: &mut ExtCtxt<'_>, sp: Span, tts: TokenStream, ) -> Box<dyn base::MacResult + 'static>166 pub fn expand_include_str(
167     cx: &mut ExtCtxt<'_>,
168     sp: Span,
169     tts: TokenStream,
170 ) -> Box<dyn base::MacResult + 'static> {
171     let sp = cx.with_def_site_ctxt(sp);
172     let file = match get_single_str_from_tts(cx, sp, tts, "include_str!") {
173         Some(f) => f,
174         None => return DummyResult::any(sp),
175     };
176     let file = match cx.resolve_path(file, sp) {
177         Ok(f) => f,
178         Err(mut err) => {
179             err.emit();
180             return DummyResult::any(sp);
181         }
182     };
183     match cx.source_map().load_binary_file(&file) {
184         Ok(bytes) => match std::str::from_utf8(&bytes) {
185             Ok(src) => {
186                 let interned_src = Symbol::intern(&src);
187                 base::MacEager::expr(cx.expr_str(sp, interned_src))
188             }
189             Err(_) => {
190                 cx.span_err(sp, &format!("{} wasn't a utf-8 file", file.display()));
191                 DummyResult::any(sp)
192             }
193         },
194         Err(e) => {
195             cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e));
196             DummyResult::any(sp)
197         }
198     }
199 }
200 
expand_include_bytes( cx: &mut ExtCtxt<'_>, sp: Span, tts: TokenStream, ) -> Box<dyn base::MacResult + 'static>201 pub fn expand_include_bytes(
202     cx: &mut ExtCtxt<'_>,
203     sp: Span,
204     tts: TokenStream,
205 ) -> Box<dyn base::MacResult + 'static> {
206     let sp = cx.with_def_site_ctxt(sp);
207     let file = match get_single_str_from_tts(cx, sp, tts, "include_bytes!") {
208         Some(f) => f,
209         None => return DummyResult::any(sp),
210     };
211     let file = match cx.resolve_path(file, sp) {
212         Ok(f) => f,
213         Err(mut err) => {
214             err.emit();
215             return DummyResult::any(sp);
216         }
217     };
218     match cx.source_map().load_binary_file(&file) {
219         Ok(bytes) => base::MacEager::expr(cx.expr_lit(sp, ast::LitKind::ByteStr(bytes.into()))),
220         Err(e) => {
221             cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e));
222             DummyResult::any(sp)
223         }
224     }
225 }
226