Skip to content

Add attribute to indicate entry point, #[main] #4483

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/librustc/driver/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ type Session_ = {targ_cfg: @config,
parse_sess: parse_sess,
codemap: @codemap::CodeMap,
// For a library crate, this is always none
mut main_fn: Option<(node_id, codemap::span)>,
mut main_fn: Option<(node_id, codemap::span, bool)>,
span_diagnostic: diagnostic::span_handler,
filesearch: filesearch::FileSearch,
mut building_library: bool,
Expand Down
32 changes: 18 additions & 14 deletions src/librustc/front/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,21 +85,25 @@ fn strip_test_functions(crate: @ast::crate) -> @ast::crate {

fn fold_mod(cx: test_ctxt, m: ast::_mod, fld: fold::ast_fold) -> ast::_mod {

// Remove any defined main function from the AST so it doesn't clash with
// Remove all #[main] attributes from the AST so it doesn't clash with
// the one we're going to add. Only if compiling an executable.

// FIXME (#2403): This is sloppy. Instead we should have some mechanism to
// indicate to the translation pass which function we want to be main.
fn nomain(cx: test_ctxt, item: @ast::item) -> Option<@ast::item> {
match item.node {
ast::item_fn(*) => {
if item.ident == cx.sess.ident_of(~"main")
&& !cx.sess.building_library {
option::None
} else { option::Some(item) }
}
_ => option::Some(item)
}

let it = @{
ident: item.ident,
attrs: vec::filter_map(item.attrs, |attr| {
if !cx.sess.building_library &&
attr::get_attr_name(*attr) == ~"main" {
None
} else { Some(copy *attr) }
}),
id: item.id,
node: copy item.node,
vis: item.vis,
span: item.span
};

Some(it)
}

let mod_nomain =
Expand Down Expand Up @@ -498,7 +502,7 @@ fn mk_main(cx: test_ctxt) -> @ast::item {
let item_ = ast::item_fn(decl, ast::impure_fn, ~[], body);
let item: ast::item =
{ident: cx.sess.ident_of(~"main"),
attrs: ~[],
attrs: ~[attr::mk_attr(attr::mk_word_item(~"main"))],
id: cx.sess.next_node_id(),
node: item_,
vis: ast::public,
Expand Down
76 changes: 68 additions & 8 deletions src/librustc/middle/resolve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ use syntax::ast_util::{def_id_of_def, dummy_sp, local_def};
use syntax::ast_util::{path_to_ident, walk_pat, trait_method_to_ty_method};
use syntax::ast_util::{Privacy, Public, Private, visibility_to_privacy};
use syntax::ast_util::has_legacy_export_attr;
use syntax::attr::{attr_metas, contains_name};
use syntax::attr::{attr_metas, contains_name, find_attrs_by_name};
use syntax::parse::token::ident_interner;
use syntax::parse::token::special_idents;
use syntax::print::pprust::{pat_to_str, path_to_str};
Expand Down Expand Up @@ -857,6 +857,8 @@ fn Resolver(session: Session, lang_items: LanguageItems,

namespaces: ~[ TypeNS, ValueNS ],

have_main_attr: false,

def_map: HashMap(),
export_map2: HashMap(),
trait_map: @HashMap(),
Expand Down Expand Up @@ -916,6 +918,9 @@ struct Resolver {
// The four namespaces.
namespaces: ~[Namespace],

// Whether there is any fn annotated with #[main]
mut have_main_attr: bool,

def_map: DefMap,
export_map2: ExportMap2,
trait_map: TraitMap,
Expand All @@ -934,6 +939,8 @@ impl Resolver {
self.record_exports();
self.session.abort_if_errors();

self.find_if_main_attr();

self.resolve_crate();
self.session.abort_if_errors();

Expand Down Expand Up @@ -3720,6 +3727,31 @@ impl Resolver {
return None;
}

// Find if there are any fn's with #[main]
fn find_if_main_attr(@self) {
visit_crate(*self.crate, (), mk_vt(@Visitor {
visit_item: |item, _context, _visitor| {

match /*bad*/copy item.node {

item_fn(*) => {

if !self.session.building_library {
if find_attrs_by_name(item.attrs, ~"main")
.is_not_empty() {
self.have_main_attr = true;
}
}

},
_ => {}
}

},
.. *default_visitor()
}));
}

fn resolve_crate(@self) {
debug!("(resolving crate) starting");

Expand Down Expand Up @@ -3923,15 +3955,43 @@ impl Resolver {
item_fn(ref fn_decl, _, ref ty_params, ref block) => {
// If this is the main function, we must record it in the
// session.
//
// For speed, we put the string comparison last in this chain
// of conditionals.

if !self.session.building_library &&
is_none(&self.session.main_fn) &&
item.ident == special_idents::main {
if !self.session.building_library {
let has_main_attr =
find_attrs_by_name(item.attrs, ~"main").is_not_empty();
let called_main = item.ident == special_idents::main;

if has_main_attr || called_main {
match self.session.main_fn {
Some((_, _, ident_main)) => {

if (!ident_main && has_main_attr) ||
(ident_main && !has_main_attr
&& !self.have_main_attr) {

// Already found a fn called `main`
// or multple functions marked
// with #[main]
self.session.span_fatal(item.span,
~"multiple 'main' functions");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

when functions are given in particular order like this: main - main - #[main]
I think it would print out "multiple 'main' functions" error.
https://gist.github.com/4530073

or this also would lead to similar result
https://gist.github.com/4530083


} else if ident_main && has_main_attr {

// Replace 'main' with fn explicitly
// marked #[main]
self.session.main_fn =
Some((item.id, item.span, !has_main_attr));

self.session.main_fn = Some((item.id, item.span));
}

},
None => {
self.session.main_fn =
Some((item.id, item.span, !has_main_attr))
}
}

}
}

self.resolve_function(OpaqueFunctionRibKind,
Expand Down
20 changes: 9 additions & 11 deletions src/librustc/middle/trans/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@ use middle::trans::shape::*;
use middle::trans::tvec;
use middle::trans::type_of::*;
use util::common::indenter;
use util::common::is_main_name;
use util::ppaux::{ty_to_str, ty_to_short_str};
use util::ppaux;

Expand Down Expand Up @@ -2130,7 +2129,7 @@ fn register_fn_full(ccx: @crate_ctxt,
}

fn register_fn_fuller(ccx: @crate_ctxt,
sp: span,
_sp: span,
+path: path,
node_id: ast::node_id,
attrs: &[ast::attribute],
Expand All @@ -2152,21 +2151,21 @@ fn register_fn_fuller(ccx: @crate_ctxt,
let llfn: ValueRef = decl_fn(ccx.llmod, copy ps, cc, llfty);
ccx.item_symbols.insert(node_id, ps);

let is_main = is_main_name(path) && !ccx.sess.building_library;
if is_main { create_main_wrapper(ccx, sp, llfn); }
let is_main = match ccx.sess.main_fn {
Some((id, _, _)) => node_id == id,
// Shouldn't get to this branch
// since typeck catches no main
None => false
};
if is_main { create_main_wrapper(ccx, llfn); }
llfn
}

// Create a _rust_main(args: ~[str]) function which will be called from the
// runtime rust_start function
fn create_main_wrapper(ccx: @crate_ctxt, sp: span, main_llfn: ValueRef) {

if ccx.main_fn != None::<ValueRef> {
ccx.sess.span_fatal(sp, ~"multiple 'main' functions");
}
fn create_main_wrapper(ccx: @crate_ctxt, main_llfn: ValueRef) {

let llfn = create_main(ccx, main_llfn);
ccx.main_fn = Some(llfn);
create_entry_fn(ccx, llfn);

fn create_main(ccx: @crate_ctxt, main_llfn: ValueRef) -> ValueRef {
Expand Down Expand Up @@ -2965,7 +2964,6 @@ fn trans_crate(sess: session::Session,
exp_map2: emap2,
reachable: reachable,
item_symbols: HashMap(),
mut main_fn: None::<ValueRef>,
link_meta: copy link_meta, // XXX: Bad copy.
enum_sizes: ty::new_ty_hash(),
discrims: HashMap(),
Expand Down
1 change: 0 additions & 1 deletion src/librustc/middle/trans/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,6 @@ struct crate_ctxt {
exp_map2: resolve::ExportMap2,
reachable: reachable::map,
item_symbols: HashMap<ast::node_id, ~str>,
mut main_fn: Option<ValueRef>,
link_meta: link_meta,
enum_sizes: HashMap<ty::t, uint>,
discrims: HashMap<ast::def_id, ValueRef>,
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/middle/typeck/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -391,7 +391,7 @@ fn check_for_main_fn(ccx: @crate_ctxt) {
let tcx = ccx.tcx;
if !tcx.sess.building_library {
match copy tcx.sess.main_fn {
Some((id, sp)) => check_main_fn_ty(ccx, id, sp),
Some((id, sp, _)) => check_main_fn_ty(ccx, id, sp),
None => tcx.sess.err(~"main function not found")
}
}
Expand Down