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