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