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