]> git.lizzy.rs Git - rust.git/blob - src/librustc_builtin_macros/source_util.rs
Rollup merge of #68313 - batrla:master, r=alexcrichton
[rust.git] / src / librustc_builtin_macros / source_util.rs
1 use rustc_expand::base::{self, *};
2 use rustc_expand::panictry;
3 use rustc_parse::{self, new_sub_parser_from_file, parser::Parser, DirectoryOwnership};
4 use rustc_session::lint::builtin::INCOMPLETE_INCLUDE;
5 use rustc_span::symbol::Symbol;
6 use rustc_span::{self, Pos, Span};
7 use syntax::ast;
8 use syntax::print::pprust;
9 use syntax::ptr::P;
10 use syntax::token;
11 use syntax::tokenstream::TokenStream;
12
13 use smallvec::SmallVec;
14
15 use rustc_data_structures::sync::Lrc;
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 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 directory_ownership = DirectoryOwnership::Owned { relative: None };
112     let p = new_sub_parser_from_file(cx.parse_sess(), &file, directory_ownership, None, sp);
113
114     struct ExpandResult<'a> {
115         p: Parser<'a>,
116     }
117     impl<'a> base::MacResult for ExpandResult<'a> {
118         fn make_expr(mut self: Box<ExpandResult<'a>>) -> Option<P<ast::Expr>> {
119             let r = panictry!(self.p.parse_expr());
120             if self.p.token != token::Eof {
121                 self.p.sess.buffer_lint(
122                     &INCOMPLETE_INCLUDE,
123                     self.p.token.span,
124                     ast::CRATE_NODE_ID,
125                     "include macro expected single expression in source",
126                 );
127             }
128             Some(r)
129         }
130
131         fn make_items(mut self: Box<ExpandResult<'a>>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
132             let mut ret = SmallVec::new();
133             while self.p.token != token::Eof {
134                 match panictry!(self.p.parse_item()) {
135                     Some(item) => ret.push(item),
136                     None => {
137                         let token = pprust::token_to_string(&self.p.token);
138                         self.p
139                             .sess
140                             .span_diagnostic
141                             .span_fatal(
142                                 self.p.token.span,
143                                 &format!("expected item, found `{}`", token),
144                             )
145                             .raise();
146                     }
147                 }
148             }
149             Some(ret)
150         }
151     }
152
153     Box::new(ExpandResult { p })
154 }
155
156 // include_str! : read the given file, insert it as a literal string expr
157 pub fn expand_include_str(
158     cx: &mut ExtCtxt<'_>,
159     sp: Span,
160     tts: TokenStream,
161 ) -> Box<dyn base::MacResult + 'static> {
162     let sp = cx.with_def_site_ctxt(sp);
163     let file = match get_single_str_from_tts(cx, sp, tts, "include_str!") {
164         Some(f) => f,
165         None => return DummyResult::any(sp),
166     };
167     let file = match cx.resolve_path(file, sp) {
168         Ok(f) => f,
169         Err(mut err) => {
170             err.emit();
171             return DummyResult::any(sp);
172         }
173     };
174     match cx.source_map().load_binary_file(&file) {
175         Ok(bytes) => match std::str::from_utf8(&bytes) {
176             Ok(src) => {
177                 let interned_src = Symbol::intern(&src);
178                 base::MacEager::expr(cx.expr_str(sp, interned_src))
179             }
180             Err(_) => {
181                 cx.span_err(sp, &format!("{} wasn't a utf-8 file", file.display()));
182                 DummyResult::any(sp)
183             }
184         },
185         Err(e) => {
186             cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e));
187             DummyResult::any(sp)
188         }
189     }
190 }
191
192 pub fn expand_include_bytes(
193     cx: &mut ExtCtxt<'_>,
194     sp: Span,
195     tts: TokenStream,
196 ) -> Box<dyn base::MacResult + 'static> {
197     let sp = cx.with_def_site_ctxt(sp);
198     let file = match get_single_str_from_tts(cx, sp, tts, "include_bytes!") {
199         Some(f) => f,
200         None => return DummyResult::any(sp),
201     };
202     let file = match cx.resolve_path(file, sp) {
203         Ok(f) => f,
204         Err(mut err) => {
205             err.emit();
206             return DummyResult::any(sp);
207         }
208     };
209     match cx.source_map().load_binary_file(&file) {
210         Ok(bytes) => base::MacEager::expr(cx.expr_lit(sp, ast::LitKind::ByteStr(Lrc::new(bytes)))),
211         Err(e) => {
212             cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e));
213             DummyResult::any(sp)
214         }
215     }
216 }