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