]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_ext/source_util.rs
Rollup merge of #66297 - vakaras:edit-queries, r=oli-obk
[rust.git] / src / libsyntax_ext / source_util.rs
1 use rustc_parse::{self, DirectoryOwnership, new_sub_parser_from_file, parser::Parser};
2 use syntax::ast;
3 use syntax::print::pprust;
4 use syntax::ptr::P;
5 use syntax::symbol::Symbol;
6 use syntax::token;
7 use syntax::tokenstream::TokenStream;
8 use syntax::early_buffered_lints::BufferedEarlyLintId;
9 use syntax_expand::panictry;
10 use syntax_expand::base::{self, *};
11
12 use smallvec::SmallVec;
13 use syntax_pos::{self, Pos, Span};
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(cx: &mut ExtCtxt<'_>, sp: Span, tts: TokenStream)
23                    -> Box<dyn base::MacResult+'static> {
24     base::check_zero_tts(cx, sp, tts, "line!");
25
26     let topmost = cx.expansion_cause().unwrap_or(sp);
27     let loc = cx.source_map().lookup_char_pos(topmost.lo());
28
29     base::MacEager::expr(cx.expr_u32(topmost, loc.line as u32))
30 }
31
32 /* column!(): expands to the current column number */
33 pub fn expand_column(cx: &mut ExtCtxt<'_>, sp: Span, tts: TokenStream)
34                   -> Box<dyn base::MacResult+'static> {
35     base::check_zero_tts(cx, sp, tts, "column!");
36
37     let topmost = cx.expansion_cause().unwrap_or(sp);
38     let loc = cx.source_map().lookup_char_pos(topmost.lo());
39
40     base::MacEager::expr(cx.expr_u32(topmost, loc.col.to_usize() as u32 + 1))
41 }
42
43 /// file!(): expands to the current filename */
44 /// The source_file (`loc.file`) contains a bunch more information we could spit
45 /// out if we wanted.
46 pub fn expand_file(cx: &mut ExtCtxt<'_>, sp: Span, tts: TokenStream)
47                    -> Box<dyn base::MacResult+'static> {
48     base::check_zero_tts(cx, sp, tts, "file!");
49
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())))
53 }
54
55 pub fn expand_stringify(cx: &mut ExtCtxt<'_>, sp: Span, tts: TokenStream)
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)))
59 }
60
61 pub fn expand_mod(cx: &mut ExtCtxt<'_>, sp: Span, tts: TokenStream)
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("::");
66
67     base::MacEager::expr(cx.expr_str(sp, Symbol::intern(&string)))
68 }
69
70 /// include! : parse the given file as an expr
71 /// This is generally a bad idea because it's going to behave
72 /// unhygienically.
73 pub fn expand_include<'cx>(cx: &'cx mut ExtCtxt<'_>, sp: Span, tts: TokenStream)
74                            -> Box<dyn base::MacResult+'cx> {
75     let file = match get_single_str_from_tts(cx, sp, tts, "include!") {
76         Some(f) => f,
77         None => return DummyResult::any(sp),
78     };
79     // The file will be added to the code map by the parser
80     let file = match cx.resolve_path(file, sp) {
81         Ok(f) => f,
82         Err(mut err) => {
83             err.emit();
84             return DummyResult::any(sp);
85         },
86     };
87     let directory_ownership = DirectoryOwnership::Owned { relative: None };
88     let p = new_sub_parser_from_file(cx.parse_sess(), &file, directory_ownership, None, sp);
89
90     struct ExpandResult<'a> {
91         p: Parser<'a>,
92     }
93     impl<'a> base::MacResult for ExpandResult<'a> {
94         fn make_expr(mut self: Box<ExpandResult<'a>>) -> Option<P<ast::Expr>> {
95             let r = panictry!(self.p.parse_expr());
96             if self.p.token != token::Eof {
97                 self.p.sess.buffer_lint(
98                     BufferedEarlyLintId::IncompleteInclude,
99                     self.p.token.span,
100                     ast::CRATE_NODE_ID,
101                     "include macro expected single expression in source",
102                 );
103             }
104             Some(r)
105         }
106
107         fn make_items(mut self: Box<ExpandResult<'a>>) -> Option<SmallVec<[P<ast::Item>; 1]>> {
108             let mut ret = SmallVec::new();
109             while self.p.token != token::Eof {
110                 match panictry!(self.p.parse_item()) {
111                     Some(item) => ret.push(item),
112                     None => self.p.sess.span_diagnostic.span_fatal(self.p.token.span,
113                                                            &format!("expected item, found `{}`",
114                                                                     self.p.this_token_to_string()))
115                                                .raise()
116                 }
117             }
118             Some(ret)
119         }
120     }
121
122     Box::new(ExpandResult { p })
123 }
124
125 // include_str! : read the given file, insert it as a literal string expr
126 pub fn expand_include_str(cx: &mut ExtCtxt<'_>, sp: Span, tts: TokenStream)
127                           -> Box<dyn base::MacResult+'static> {
128     let file = match get_single_str_from_tts(cx, sp, tts, "include_str!") {
129         Some(f) => f,
130         None => return DummyResult::any(sp)
131     };
132     let file = match cx.resolve_path(file, sp) {
133         Ok(f) => f,
134         Err(mut err) => {
135             err.emit();
136             return DummyResult::any(sp);
137         },
138     };
139     match cx.source_map().load_binary_file(&file) {
140         Ok(bytes) => match std::str::from_utf8(&bytes) {
141             Ok(src) => {
142                 let interned_src = Symbol::intern(&src);
143                 base::MacEager::expr(cx.expr_str(sp, interned_src))
144             }
145             Err(_) => {
146                 cx.span_err(sp, &format!("{} wasn't a utf-8 file", file.display()));
147                 DummyResult::any(sp)
148             }
149         },
150         Err(e) => {
151             cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e));
152             DummyResult::any(sp)
153         }
154     }
155 }
156
157 pub fn expand_include_bytes(cx: &mut ExtCtxt<'_>, sp: Span, tts: TokenStream)
158                             -> Box<dyn base::MacResult+'static> {
159     let file = match get_single_str_from_tts(cx, sp, tts, "include_bytes!") {
160         Some(f) => f,
161         None => return DummyResult::any(sp)
162     };
163     let file = match cx.resolve_path(file, sp) {
164         Ok(f) => f,
165         Err(mut err) => {
166             err.emit();
167             return DummyResult::any(sp);
168         },
169     };
170     match cx.source_map().load_binary_file(&file) {
171         Ok(bytes) => {
172             base::MacEager::expr(cx.expr_lit(sp, ast::LitKind::ByteStr(Lrc::new(bytes))))
173         },
174         Err(e) => {
175             cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e));
176             DummyResult::any(sp)
177         }
178     }
179 }