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