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