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