]> git.lizzy.rs Git - rust.git/blob - src/librustc_passes/entry.rs
Rollup merge of #68462 - matthiaskrgr:novec, r=varkor
[rust.git] / src / librustc_passes / entry.rs
1 use rustc::hir::map as hir_map;
2 use rustc::session::config::EntryFnType;
3 use rustc::session::{config, Session};
4 use rustc::ty::query::Providers;
5 use rustc::ty::TyCtxt;
6 use rustc_errors::struct_span_err;
7 use rustc_hir::def_id::{CrateNum, DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
8 use rustc_hir::itemlikevisit::ItemLikeVisitor;
9 use rustc_hir::{HirId, ImplItem, Item, ItemKind, TraitItem};
10 use rustc_span::symbol::sym;
11 use rustc_span::{Span, DUMMY_SP};
12 use syntax::attr;
13 use syntax::entry::EntryPointType;
14
15 struct EntryContext<'a, 'tcx> {
16     session: &'a Session,
17
18     map: &'a hir_map::Map<'tcx>,
19
20     /// The top-level function called `main`.
21     main_fn: Option<(HirId, Span)>,
22
23     /// The function that has attribute named `main`.
24     attr_main_fn: Option<(HirId, Span)>,
25
26     /// The function that has the attribute 'start' on it.
27     start_fn: Option<(HirId, Span)>,
28
29     /// The functions that one might think are `main` but aren't, e.g.
30     /// main functions not defined at the top level. For diagnostics.
31     non_main_fns: Vec<(HirId, Span)>,
32 }
33
34 impl<'a, 'tcx> ItemLikeVisitor<'tcx> for EntryContext<'a, 'tcx> {
35     fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
36         let def_id = self.map.local_def_id(item.hir_id);
37         let def_key = self.map.def_key(def_id);
38         let at_root = def_key.parent == Some(CRATE_DEF_INDEX);
39         find_item(item, self, at_root);
40     }
41
42     fn visit_trait_item(&mut self, _trait_item: &'tcx TraitItem<'tcx>) {
43         // Entry fn is never a trait item.
44     }
45
46     fn visit_impl_item(&mut self, _impl_item: &'tcx ImplItem<'tcx>) {
47         // Entry fn is never a trait item.
48     }
49 }
50
51 fn entry_fn(tcx: TyCtxt<'_>, cnum: CrateNum) -> Option<(DefId, EntryFnType)> {
52     assert_eq!(cnum, LOCAL_CRATE);
53
54     let any_exe =
55         tcx.sess.crate_types.borrow().iter().any(|ty| *ty == config::CrateType::Executable);
56     if !any_exe {
57         // No need to find a main function.
58         return None;
59     }
60
61     // If the user wants no main function at all, then stop here.
62     if attr::contains_name(&tcx.hir().krate().attrs, sym::no_main) {
63         return None;
64     }
65
66     let mut ctxt = EntryContext {
67         session: tcx.sess,
68         map: tcx.hir(),
69         main_fn: None,
70         attr_main_fn: None,
71         start_fn: None,
72         non_main_fns: Vec::new(),
73     };
74
75     tcx.hir().krate().visit_all_item_likes(&mut ctxt);
76
77     configure_main(tcx, &ctxt)
78 }
79
80 // Beware, this is duplicated in `libsyntax/entry.rs`, so make sure to keep
81 // them in sync.
82 fn entry_point_type(item: &Item<'_>, at_root: bool) -> EntryPointType {
83     match item.kind {
84         ItemKind::Fn(..) => {
85             if attr::contains_name(&item.attrs, sym::start) {
86                 EntryPointType::Start
87             } else if attr::contains_name(&item.attrs, sym::main) {
88                 EntryPointType::MainAttr
89             } else if item.ident.name == sym::main {
90                 if at_root {
91                     // This is a top-level function so can be `main`.
92                     EntryPointType::MainNamed
93                 } else {
94                     EntryPointType::OtherMain
95                 }
96             } else {
97                 EntryPointType::None
98             }
99         }
100         _ => EntryPointType::None,
101     }
102 }
103
104 fn find_item(item: &Item<'_>, ctxt: &mut EntryContext<'_, '_>, at_root: bool) {
105     match entry_point_type(item, at_root) {
106         EntryPointType::MainNamed => {
107             if ctxt.main_fn.is_none() {
108                 ctxt.main_fn = Some((item.hir_id, item.span));
109             } else {
110                 struct_span_err!(ctxt.session, item.span, E0136, "multiple `main` functions")
111                     .emit();
112             }
113         }
114         EntryPointType::OtherMain => {
115             ctxt.non_main_fns.push((item.hir_id, item.span));
116         }
117         EntryPointType::MainAttr => {
118             if ctxt.attr_main_fn.is_none() {
119                 ctxt.attr_main_fn = Some((item.hir_id, item.span));
120             } else {
121                 struct_span_err!(
122                     ctxt.session,
123                     item.span,
124                     E0137,
125                     "multiple functions with a `#[main]` attribute"
126                 )
127                 .span_label(item.span, "additional `#[main]` function")
128                 .span_label(ctxt.attr_main_fn.unwrap().1, "first `#[main]` function")
129                 .emit();
130             }
131         }
132         EntryPointType::Start => {
133             if ctxt.start_fn.is_none() {
134                 ctxt.start_fn = Some((item.hir_id, item.span));
135             } else {
136                 struct_span_err!(ctxt.session, item.span, E0138, "multiple `start` functions")
137                     .span_label(ctxt.start_fn.unwrap().1, "previous `#[start]` function here")
138                     .span_label(item.span, "multiple `start` functions")
139                     .emit();
140             }
141         }
142         EntryPointType::None => (),
143     }
144 }
145
146 fn configure_main(tcx: TyCtxt<'_>, visitor: &EntryContext<'_, '_>) -> Option<(DefId, EntryFnType)> {
147     if let Some((hir_id, _)) = visitor.start_fn {
148         Some((tcx.hir().local_def_id(hir_id), EntryFnType::Start))
149     } else if let Some((hir_id, _)) = visitor.attr_main_fn {
150         Some((tcx.hir().local_def_id(hir_id), EntryFnType::Main))
151     } else if let Some((hir_id, _)) = visitor.main_fn {
152         Some((tcx.hir().local_def_id(hir_id), EntryFnType::Main))
153     } else {
154         no_main_err(tcx, visitor);
155         None
156     }
157 }
158
159 fn no_main_err(tcx: TyCtxt<'_>, visitor: &EntryContext<'_, '_>) {
160     let sp = tcx.hir().krate().span;
161     if *tcx.sess.parse_sess.reached_eof.borrow() {
162         // There's an unclosed brace that made the parser reach `Eof`, we shouldn't complain about
163         // the missing `fn main()` then as it might have been hidden inside an unclosed block.
164         tcx.sess.delay_span_bug(sp, "`main` not found, but expected unclosed brace error");
165         return;
166     }
167
168     // There is no main function.
169     let mut err = struct_span_err!(
170         tcx.sess,
171         DUMMY_SP,
172         E0601,
173         "`main` function not found in crate `{}`",
174         tcx.crate_name(LOCAL_CRATE)
175     );
176     let filename = &tcx.sess.local_crate_source_file;
177     let note = if !visitor.non_main_fns.is_empty() {
178         for &(_, span) in &visitor.non_main_fns {
179             err.span_note(span, "here is a function named `main`");
180         }
181         err.note("you have one or more functions named `main` not defined at the crate level");
182         err.help(
183             "either move the `main` function definitions or attach the `#[main]` attribute \
184                   to one of them",
185         );
186         // There were some functions named `main` though. Try to give the user a hint.
187         format!(
188             "the main function must be defined at the crate level{}",
189             filename.as_ref().map(|f| format!(" (in `{}`)", f.display())).unwrap_or_default()
190         )
191     } else if let Some(filename) = filename {
192         format!("consider adding a `main` function to `{}`", filename.display())
193     } else {
194         String::from("consider adding a `main` function at the crate level")
195     };
196     // The file may be empty, which leads to the diagnostic machinery not emitting this
197     // note. This is a relatively simple way to detect that case and emit a span-less
198     // note instead.
199     if let Ok(_) = tcx.sess.source_map().lookup_line(sp.lo()) {
200         err.set_span(sp);
201         err.span_label(sp, &note);
202     } else {
203         err.note(&note);
204     }
205     if tcx.sess.teach(&err.get_code().unwrap()) {
206         err.note(
207             "If you don't know the basics of Rust, you can go look to the Rust Book \
208                   to get started: https://doc.rust-lang.org/book/",
209         );
210     }
211     err.emit();
212 }
213
214 pub fn find_entry_point(tcx: TyCtxt<'_>) -> Option<(DefId, EntryFnType)> {
215     tcx.entry_fn(LOCAL_CRATE)
216 }
217
218 pub fn provide(providers: &mut Providers<'_>) {
219     *providers = Providers { entry_fn, ..*providers };
220 }