]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/entry.rs
Rollup merge of #54488 - zackmdavis:and_the_case_of_the_unused_crate, r=estebank
[rust.git] / src / librustc / middle / entry.rs
1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11
12 use hir::map as hir_map;
13 use hir::def_id::{CRATE_DEF_INDEX};
14 use session::{config, Session};
15 use session::config::EntryFnType;
16 use syntax::ast::NodeId;
17 use syntax::attr;
18 use syntax::entry::EntryPointType;
19 use syntax_pos::Span;
20 use hir::{Item, ItemKind, ImplItem, TraitItem};
21 use hir::itemlikevisit::ItemLikeVisitor;
22
23 struct EntryContext<'a, 'tcx: 'a> {
24     session: &'a Session,
25
26     map: &'a hir_map::Map<'tcx>,
27
28     // The top-level function called 'main'
29     main_fn: Option<(NodeId, Span)>,
30
31     // The function that has attribute named 'main'
32     attr_main_fn: Option<(NodeId, Span)>,
33
34     // The function that has the attribute 'start' on it
35     start_fn: Option<(NodeId, Span)>,
36
37     // The functions that one might think are 'main' but aren't, e.g.
38     // main functions not defined at the top level. For diagnostics.
39     non_main_fns: Vec<(NodeId, Span)> ,
40 }
41
42 impl<'a, 'tcx> ItemLikeVisitor<'tcx> for EntryContext<'a, 'tcx> {
43     fn visit_item(&mut self, item: &'tcx Item) {
44         let def_id = self.map.local_def_id(item.id);
45         let def_key = self.map.def_key(def_id);
46         let at_root = def_key.parent == Some(CRATE_DEF_INDEX);
47         find_item(item, self, at_root);
48     }
49
50     fn visit_trait_item(&mut self, _trait_item: &'tcx TraitItem) {
51         // entry fn is never a trait item
52     }
53
54     fn visit_impl_item(&mut self, _impl_item: &'tcx ImplItem) {
55         // entry fn is never an impl item
56     }
57 }
58
59 pub fn find_entry_point(session: &Session,
60                         hir_map: &hir_map::Map<'_>,
61                         crate_name: &str) {
62     let any_exe = session.crate_types.borrow().iter().any(|ty| {
63         *ty == config::CrateType::Executable
64     });
65     if !any_exe {
66         // No need to find a main function
67         session.entry_fn.set(None);
68         return
69     }
70
71     // If the user wants no main function at all, then stop here.
72     if attr::contains_name(&hir_map.krate().attrs, "no_main") {
73         session.entry_fn.set(None);
74         return
75     }
76
77     let mut ctxt = EntryContext {
78         session,
79         map: hir_map,
80         main_fn: None,
81         attr_main_fn: None,
82         start_fn: None,
83         non_main_fns: Vec::new(),
84     };
85
86     hir_map.krate().visit_all_item_likes(&mut ctxt);
87
88     configure_main(&mut ctxt, crate_name);
89 }
90
91 // Beware, this is duplicated in libsyntax/entry.rs, make sure to keep
92 // them in sync.
93 fn entry_point_type(item: &Item, at_root: bool) -> EntryPointType {
94     match item.node {
95         ItemKind::Fn(..) => {
96             if attr::contains_name(&item.attrs, "start") {
97                 EntryPointType::Start
98             } else if attr::contains_name(&item.attrs, "main") {
99                 EntryPointType::MainAttr
100             } else if item.name == "main" {
101                 if at_root {
102                     // This is a top-level function so can be 'main'
103                     EntryPointType::MainNamed
104                 } else {
105                     EntryPointType::OtherMain
106                 }
107             } else {
108                 EntryPointType::None
109             }
110         }
111         _ => EntryPointType::None,
112     }
113 }
114
115
116 fn find_item(item: &Item, ctxt: &mut EntryContext<'_, '_>, at_root: bool) {
117     match entry_point_type(item, at_root) {
118         EntryPointType::MainNamed => {
119             if ctxt.main_fn.is_none() {
120                 ctxt.main_fn = Some((item.id, item.span));
121             } else {
122                 span_err!(ctxt.session, item.span, E0136,
123                           "multiple 'main' functions");
124             }
125         },
126         EntryPointType::OtherMain => {
127             ctxt.non_main_fns.push((item.id, item.span));
128         },
129         EntryPointType::MainAttr => {
130             if ctxt.attr_main_fn.is_none() {
131                 ctxt.attr_main_fn = Some((item.id, item.span));
132             } else {
133                 struct_span_err!(ctxt.session, item.span, E0137,
134                           "multiple functions with a #[main] attribute")
135                 .span_label(item.span, "additional #[main] function")
136                 .span_label(ctxt.attr_main_fn.unwrap().1, "first #[main] function")
137                 .emit();
138             }
139         },
140         EntryPointType::Start => {
141             if ctxt.start_fn.is_none() {
142                 ctxt.start_fn = Some((item.id, item.span));
143             } else {
144                 struct_span_err!(
145                     ctxt.session, item.span, E0138,
146                     "multiple 'start' functions")
147                     .span_label(ctxt.start_fn.unwrap().1,
148                                 "previous `start` function here")
149                     .span_label(item.span, "multiple `start` functions")
150                     .emit();
151             }
152         },
153         EntryPointType::None => ()
154     }
155 }
156
157 fn configure_main(this: &mut EntryContext<'_, '_>, crate_name: &str) {
158     if let Some((node_id, span)) = this.start_fn {
159         this.session.entry_fn.set(Some((node_id, span, EntryFnType::Start)));
160     } else if let Some((node_id, span)) = this.attr_main_fn {
161         this.session.entry_fn.set(Some((node_id, span, EntryFnType::Main)));
162     } else if let Some((node_id, span)) = this.main_fn {
163         this.session.entry_fn.set(Some((node_id, span, EntryFnType::Main)));
164     } else {
165         // No main function
166         this.session.entry_fn.set(None);
167         let mut err = struct_err!(this.session, E0601,
168             "`main` function not found in crate `{}`", crate_name);
169         if !this.non_main_fns.is_empty() {
170             // There were some functions named 'main' though. Try to give the user a hint.
171             err.note("the main function must be defined at the crate level \
172                       but you have one or more functions named 'main' that are not \
173                       defined at the crate level. Either move the definition or \
174                       attach the `#[main]` attribute to override this behavior.");
175             for &(_, span) in &this.non_main_fns {
176                 err.span_note(span, "here is a function named 'main'");
177             }
178             err.emit();
179             this.session.abort_if_errors();
180         } else {
181             if let Some(ref filename) = this.session.local_crate_source_file {
182                 err.note(&format!("consider adding a `main` function to `{}`", filename.display()));
183             }
184             if this.session.teach(&err.get_code().unwrap()) {
185                 err.note("If you don't know the basics of Rust, you can go look to the Rust Book \
186                           to get started: https://doc.rust-lang.org/book/");
187             }
188             err.emit();
189         }
190     }
191 }