]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_builtin_macros/src/source_util.rs
Rollup merge of #80573 - jyn514:tool-lints, r=GuillaumeGomez
[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::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
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 */
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.
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(cx.expr_str(topmost, Symbol::intern(&loc.file.name.to_string())))
65 }
66
67 pub fn expand_stringify(
68     cx: &mut ExtCtxt<'_>,
69     sp: Span,
70     tts: TokenStream,
71 ) -> Box<dyn base::MacResult + 'static> {
72     let sp = cx.with_def_site_ctxt(sp);
73     let s = pprust::tts_to_string(&tts);
74     base::MacEager::expr(cx.expr_str(sp, Symbol::intern(&s)))
75 }
76
77 pub fn expand_mod(
78     cx: &mut ExtCtxt<'_>,
79     sp: Span,
80     tts: TokenStream,
81 ) -> Box<dyn base::MacResult + 'static> {
82     let sp = cx.with_def_site_ctxt(sp);
83     base::check_zero_tts(cx, sp, tts, "module_path!");
84     let mod_path = &cx.current_expansion.module.mod_path;
85     let string = mod_path.iter().map(|x| x.to_string()).collect::<Vec<String>>().join("::");
86
87     base::MacEager::expr(cx.expr_str(sp, Symbol::intern(&string)))
88 }
89
90 /// include! : parse the given file as an expr
91 /// This is generally a bad idea because it's going to behave
92 /// unhygienically.
93 pub fn expand_include<'cx>(
94     cx: &'cx mut ExtCtxt<'_>,
95     sp: Span,
96     tts: TokenStream,
97 ) -> Box<dyn base::MacResult + 'cx> {
98     let sp = cx.with_def_site_ctxt(sp);
99     let file = match get_single_str_from_tts(cx, sp, tts, "include!") {
100         Some(f) => f,
101         None => return DummyResult::any(sp),
102     };
103     // The file will be added to the code map by the parser
104     let mut file = match cx.resolve_path(file, sp) {
105         Ok(f) => f,
106         Err(mut err) => {
107             err.emit();
108             return DummyResult::any(sp);
109         }
110     };
111     let p = new_parser_from_file(cx.parse_sess(), &file, Some(sp));
112
113     // If in the included file we have e.g., `mod bar;`,
114     // then the path of `bar.rs` should be relative to the directory of `file`.
115     // See https://github.com/rust-lang/rust/pull/69838/files#r395217057 for a discussion.
116     // `MacroExpander::fully_expand_fragment` later restores, so "stack discipline" is maintained.
117     file.pop();
118     cx.current_expansion.directory_ownership = DirectoryOwnership::Owned { relative: None };
119     let mod_path = cx.current_expansion.module.mod_path.clone();
120     cx.current_expansion.module = Rc::new(ModuleData { mod_path, directory: file });
121
122     struct ExpandResult<'a> {
123         p: Parser<'a>,
124         node_id: ast::NodeId,
125     }
126     impl<'a> base::MacResult for ExpandResult<'a> {
127         fn make_expr(mut self: Box<ExpandResult<'a>>) -> Option<P<ast::Expr>> {
128             let r = base::parse_expr(&mut self.p)?;
129             if self.p.token != token::Eof {
130                 self.p.sess.buffer_lint(
131                     &INCOMPLETE_INCLUDE,
132                     self.p.token.span,
133                     self.node_id,
134                     "include macro expected single expression in source",
135                 );
136             }
137             Some(r)
138         }
139
140         fn make_items(mut self: Box<ExpandResult<'a>>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
141             let mut ret = SmallVec::new();
142             while self.p.token != token::Eof {
143                 match self.p.parse_item(ForceCollect::No) {
144                     Err(mut err) => {
145                         err.emit();
146                         break;
147                     }
148                     Ok(Some(item)) => ret.push(item),
149                     Ok(None) => {
150                         let token = pprust::token_to_string(&self.p.token);
151                         let msg = format!("expected item, found `{}`", token);
152                         self.p.struct_span_err(self.p.token.span, &msg).emit();
153                         break;
154                     }
155                 }
156             }
157             Some(ret)
158         }
159     }
160
161     Box::new(ExpandResult { p, node_id: cx.resolver.lint_node_id(cx.current_expansion.id) })
162 }
163
164 // include_str! : read the given file, insert it as a literal string expr
165 pub fn expand_include_str(
166     cx: &mut ExtCtxt<'_>,
167     sp: Span,
168     tts: TokenStream,
169 ) -> Box<dyn base::MacResult + 'static> {
170     let sp = cx.with_def_site_ctxt(sp);
171     let file = match get_single_str_from_tts(cx, sp, tts, "include_str!") {
172         Some(f) => f,
173         None => return DummyResult::any(sp),
174     };
175     let file = match cx.resolve_path(file, sp) {
176         Ok(f) => f,
177         Err(mut err) => {
178             err.emit();
179             return DummyResult::any(sp);
180         }
181     };
182     match cx.source_map().load_binary_file(&file) {
183         Ok(bytes) => match std::str::from_utf8(&bytes) {
184             Ok(src) => {
185                 let interned_src = Symbol::intern(&src);
186                 base::MacEager::expr(cx.expr_str(sp, interned_src))
187             }
188             Err(_) => {
189                 cx.span_err(sp, &format!("{} wasn't a utf-8 file", file.display()));
190                 DummyResult::any(sp)
191             }
192         },
193         Err(e) => {
194             cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e));
195             DummyResult::any(sp)
196         }
197     }
198 }
199
200 pub fn expand_include_bytes(
201     cx: &mut ExtCtxt<'_>,
202     sp: Span,
203     tts: TokenStream,
204 ) -> Box<dyn base::MacResult + 'static> {
205     let sp = cx.with_def_site_ctxt(sp);
206     let file = match get_single_str_from_tts(cx, sp, tts, "include_bytes!") {
207         Some(f) => f,
208         None => return DummyResult::any(sp),
209     };
210     let file = match cx.resolve_path(file, sp) {
211         Ok(f) => f,
212         Err(mut err) => {
213             err.emit();
214             return DummyResult::any(sp);
215         }
216     };
217     match cx.source_map().load_binary_file(&file) {
218         Ok(bytes) => base::MacEager::expr(cx.expr_lit(sp, ast::LitKind::ByteStr(bytes.into()))),
219         Err(e) => {
220             cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e));
221             DummyResult::any(sp)
222         }
223     }
224 }