Skip to content
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

rustpkg: Allow building executables, and normalize '-' to '_' #5896

Closed
wants to merge 1 commit 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
21 changes: 20 additions & 1 deletion src/librustpkg/path_util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
// rustpkg utilities having to do with paths and directories

use core::path::*;
use core::os;
use core::{os, str};
use core::option::*;
use util::PkgId;

/// Returns the output directory to use.
Expand Down Expand Up @@ -50,6 +51,24 @@ pub fn default_dest_dir(pkg_dir: &Path) -> Path {
}
}

/// Replace all occurrences of '-' in the stem part of path with '_'
/// This is because we treat rust-foo-bar-quux and rust_foo_bar_quux
/// as the same name
pub fn normalize(p: ~Path) -> ~Path {
match p.filestem() {
None => p,
Some(st) => {
let replaced = str::replace(st, "-", "_");
if replaced != st {
~p.with_filestem(replaced)
}
else {
p
}
}
}
}

#[cfg(test)]
mod test {
use core::{os, rand};
Expand Down
38 changes: 38 additions & 0 deletions src/librustpkg/predicates.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use rustc::driver::{driver, session};
use syntax::{ast, diagnostic};
use syntax::parse::token;
use core::path::Path;
use core::option::*;

/// True if the file at path `p` contains a `main` function
pub fn has_main_fn(p: &Path, binary: ~str) -> bool {
let input = driver::file_input(copy *p);
let options = @session::options {
binary: copy binary,
crate_type: session::bin_crate,
.. *session::basic_options()
};
// Should probably take a session as an argument
let sess = driver::build_session(options, diagnostic::emit);
let cfg = driver::build_configuration(sess, binary, input);
let (crate, _) = driver::compile_upto(sess, cfg, input, driver::cu_parse, None);
let mut has_main = false;
for crate.node.module.items.each() |it| {
match it.node {
ast::item_fn(*) if it.ident == token::special_idents::main =>
has_main = true,
_ => ()
}
}
has_main
}
45 changes: 29 additions & 16 deletions src/librustpkg/rustpkg.rc
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,16 @@ use rustc::metadata::filesearch;
use std::net::url;
use std::{getopts};
use syntax::{ast, diagnostic};
use util::{ExitCode, Pkg, PkgId};
use path_util::dest_dir;
use util::*;
use path_util::{dest_dir, normalize};
use predicates::has_main_fn;
use rustc::driver::session::{lib_crate, bin_crate, unknown_crate, crate_type};

mod conditions;
mod usage;
mod path_util;
mod util;
mod predicates;

/// A PkgScript represents user-supplied custom logic for
/// special build hooks. This only exists for packages with
Expand Down Expand Up @@ -117,9 +120,11 @@ impl PkgScript {
Ok(r) => {
let root = r.pop().pop().pop().pop(); // :-\
debug!("Root is %s, calling compile_rest", root.to_str());
util::compile_crate_from_input(self.input, Some(self.build_dir),
sess, Some(crate), os::args()[0]);
let exe = self.build_dir.push(~"pkg" + util::exe_suffix());
util::compile_crate_from_input(self.input, Some(self.build_dir),
sess, Some(crate),
exe, os::args()[0],
driver::cu_everything);
debug!("Running program: %s %s %s", exe.to_str(), root.to_str(), what);
let status = run::run_program(exe.to_str(), ~[root.to_str(), what]);
if status != 0 {
Expand Down Expand Up @@ -728,7 +733,6 @@ condition! {

impl PkgSrc {


fn new(src_dir: &Path, dst_dir: &Path,
id: &PkgId) -> PkgSrc {
PkgSrc {
Expand Down Expand Up @@ -786,14 +790,16 @@ impl PkgSrc {
/// True if the given path's stem is self's pkg ID's stem
/// or if the pkg ID's stem is <rust-foo> and the given path's
/// stem is foo
/// Requires that dashes in p have already been normalized to
/// underscores
fn stem_matches(&self, p: &Path) -> bool {
let self_id = self.id.path.filestem();
let self_id = normalize(~self.id.path).filestem();
if self_id == p.filestem() {
return true;
}
else {
for self_id.each |pth| {
if pth.starts_with("rust-")
if pth.starts_with("rust_") // because p is already normalized
&& match p.filestem() {
Some(s) => str::eq_slice(s, pth.slice(5, pth.len())),
None => false
Expand Down Expand Up @@ -841,18 +847,25 @@ impl PkgSrc {
// consider it to be a crate
let ext = pth.filetype();
let matches = |p: &Path| {
self.stem_matches(p) && (ext == Some(~".rc")
let normalized = normalize(~*p);
self.stem_matches(normalized) && (ext == Some(~".rc")
|| ext == Some(~".rs"))
};
debug!("Checking %? which %s and ext = %? %? %?", pth.filestem(),
if matches(pth) { "matches" } else { "does not match" },
ext, saw_rs, saw_rc);
if matches(pth) &&
// Avoid pushing foo.rc *and* foo.rs
// Avoid visiting foo.rc *and* foo.rs
!((ext == Some(~".rc") && saw_rs) ||
(ext == Some(~".rs") && saw_rc)) {
push_crate(&mut self.libs, // ????
if has_main_fn(pth, os::args()[0]) {
push_crate(&mut self.mains,
prefix, pth);
}
else {
push_crate(&mut self.libs,
prefix, pth);
}
if ext == Some(~".rc") {
saw_rc = true;
}
Expand All @@ -874,7 +887,7 @@ impl PkgSrc {
src_dir: &Path,
crates: &[Crate],
cfgs: ~[~str],
test: bool) {
test: bool, crate_type: crate_type) {

for crates.each |&crate| {
let path = &src_dir.push_rel(&crate.file).normalize();
Expand All @@ -885,7 +898,7 @@ impl PkgSrc {
dst_dir,
crate.flags,
crate.cfgs + cfgs,
false, test);
false, test, crate_type);
if !result {
build_err::cond.raise(fmt!("build failure on %s",
path.to_str()));
Expand All @@ -898,12 +911,12 @@ impl PkgSrc {
fn build(&self, dst_dir: &Path, cfgs: ~[~str]) {
let dir = self.check_dir();
debug!("Building libs");
PkgSrc::build_crates(dst_dir, &dir, self.libs, cfgs, false);
PkgSrc::build_crates(dst_dir, &dir, self.libs, cfgs, false, lib_crate);
debug!("Building mains");
PkgSrc::build_crates(dst_dir, &dir, self.mains, cfgs, false);
PkgSrc::build_crates(dst_dir, &dir, self.mains, cfgs, false, bin_crate);
debug!("Building tests");
PkgSrc::build_crates(dst_dir, &dir, self.tests, cfgs, true);
PkgSrc::build_crates(dst_dir, &dir, self.tests, cfgs, true, bin_crate);
debug!("Building benches");
PkgSrc::build_crates(dst_dir, &dir, self.benchs, cfgs, true);
PkgSrc::build_crates(dst_dir, &dir, self.benchs, cfgs, true, bin_crate);
}
}
56 changes: 34 additions & 22 deletions src/librustpkg/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ use core::*;
use core::cmp::Ord;
use core::hash::Streaming;
use rustc::driver::{driver, session};
use rustc::driver::session::{lib_crate, bin_crate, unknown_crate};
use rustc::metadata::filesearch;
use std::getopts::groups::getopts;
use std::semver;
Expand All @@ -22,6 +23,7 @@ use syntax::ext::base::{mk_ctxt, ext_ctxt};
use syntax::ext::build;
use syntax::{ast, attr, codemap, diagnostic, fold};
use rustc::back::link::output_type_exe;
use rustc::driver::session::{lib_crate, bin_crate, unknown_crate, crate_type};

pub type ExitCode = int; // For now

Expand Down Expand Up @@ -430,39 +432,45 @@ pub fn compile_input(sysroot: Option<Path>,
flags: ~[~str],
cfgs: ~[~str],
opt: bool,
test: bool) -> bool {
test: bool,
crate_type: session::crate_type) -> bool {

assert!(in_file.components.len() > 1);
let input = driver::file_input(copy *in_file);
debug!("compile_input: %s", in_file.to_str());
debug!("compile_input: %s / %?", in_file.to_str(), crate_type);
// tjc: by default, use the package ID name as the link name
// not sure if we should support anything else
let short_name = in_file.filestem().expect("Can't compile a directory!");
debug!("short_name = %s", short_name.to_str());

// Right now we're always assuming that we're building a library.
// What we should do is parse the crate and infer whether it's a library
// from the absence or presence of a main fn
let out_file = out_dir.push(os::dll_filename(short_name));
let building_library = true;
let binary = os::args()[0];
let building_library = match crate_type {
lib_crate | unknown_crate => true,
_ => false
};

let out_file = if building_library {
out_dir.push(os::dll_filename(short_name))
}
else {
out_dir.push(short_name + if test { ~"test" } else { ~"" }
+ os::EXE_SUFFIX)
};

debug!("compiling %s into %s",
in_file.to_str(),
out_file.to_str());

let binary = os::args()[0];

debug!("flags: %s", str::connect(flags, ~" "));
debug!("cfgs: %s", str::connect(cfgs, ~" "));
// Again, we assume we're building a library

let matches = getopts(~[~"-Z", ~"time-passes"]
+ if building_library { ~[~"--lib"] } else { ~[] }
+ if building_library { ~[~"--lib"] }
else { ~[~""] }
+ flags
+ cfgs.flat_map(|&c| { ~[~"--cfg", c] }),
driver::optgroups()).get();
let options = @session::options {
crate_type: if building_library { session::lib_crate }
else { session::bin_crate },
crate_type: crate_type,
optimize: if opt { session::Aggressive } else { session::No },
test: test,
maybe_sysroot: sysroot,
Expand All @@ -485,31 +493,35 @@ pub fn compile_input(sysroot: Option<Path>,

debug!("calling compile_crate_from_input, out_dir = %s,
building_library = %?", out_dir.to_str(), sess.building_library);
compile_crate_from_input(input, Some(*out_dir), sess, None, binary);
let _ = compile_crate_from_input(input, Some(*out_dir), sess, None,
out_file, binary,
driver::cu_everything);
true
}

// Should use workcache to avoid recompiling when not necessary
// Should also rename this to something better
// If crate_opt is present, then finish compilation. If it's None, then
// call compile_upto and return the crate
// also, too many arguments
pub fn compile_crate_from_input(input: driver::input, build_dir_opt: Option<Path>,
sess: session::Session, crate_opt: Option<@ast::crate>,
binary: ~str) -> @ast::crate {
sess: session::Session, crate_opt: Option<@ast::crate>, out_file: Path,
binary: ~str,
what: driver::compile_upto) -> @ast::crate {
debug!("Calling build_output_filenames with %?", build_dir_opt);
let outputs = driver::build_output_filenames(input, &build_dir_opt, &None, sess);
let outputs = driver::build_output_filenames(input, &build_dir_opt, &Some(out_file), sess);
debug!("Outputs are %? and output type = %?", outputs, sess.opts.output_type);
let cfg = driver::build_configuration(sess, binary, input);
match crate_opt {
Some(c) => {
debug!("Calling compile_rest, outputs = %?", outputs);
assert!(what == driver::cu_everything);
driver::compile_rest(sess, cfg, driver::cu_everything, Some(outputs), Some(c));
c
}
None => {
debug!("Calling compile_upto, outputs = %?", outputs);
let (crate, _) = driver::compile_upto(sess, cfg, input, driver::cu_parse,
Some(outputs));
let (crate, _) = driver::compile_upto(sess, cfg, input, what, Some(outputs));
crate
}
}
Expand All @@ -529,13 +541,13 @@ pub fn exe_suffix() -> ~str { ~"" }
// FIXME (#4432): Use workcache to only compile when needed
pub fn compile_crate(sysroot: Option<Path>, crate: &Path, dir: &Path,
flags: ~[~str], cfgs: ~[~str], opt: bool,
test: bool) -> bool {
test: bool, crate_type: crate_type) -> bool {
debug!("compile_crate: crate=%s, dir=%s", crate.to_str(), dir.to_str());
debug!("compile_crate: flags =...");
for flags.each |&fl| {
debug!("+++ %s", fl);
}
compile_input(sysroot, crate, dir, flags, cfgs, opt, test)
compile_input(sysroot, crate, dir, flags, cfgs, opt, test, crate_type)
}


Expand Down