Skip to content

Support compiling rustc without LLVM #42752

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 3 commits into from
Closed
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
4 changes: 4 additions & 0 deletions src/bootstrap/config.rs
Original file line number Diff line number Diff line change
@@ -53,6 +53,7 @@ pub struct Config {
pub profiler: bool,

// llvm codegen options
pub llvm_enabled: bool,
pub llvm_assertions: bool,
pub llvm_optimize: bool,
pub llvm_release_debuginfo: bool,
@@ -182,6 +183,7 @@ struct Install {
/// TOML representation of how the LLVM build is configured.
#[derive(RustcDecodable, Default)]
struct Llvm {
enabled: Option<bool>,
ccache: Option<StringOrBool>,
ninja: Option<bool>,
assertions: Option<bool>,
@@ -252,6 +254,7 @@ struct TomlTarget {
impl Config {
pub fn parse(build: &str, file: Option<PathBuf>) -> Config {
let mut config = Config::default();
config.llvm_enabled = true;
config.llvm_optimize = true;
config.use_jemalloc = true;
config.backtrace = true;
@@ -345,6 +348,7 @@ impl Config {
Some(StringOrBool::Bool(false)) | None => {}
}
set(&mut config.ninja, llvm.ninja);
set(&mut config.llvm_enabled, llvm.enabled);
set(&mut config.llvm_assertions, llvm.assertions);
set(&mut config.llvm_optimize, llvm.optimize);
set(&mut config.llvm_release_debuginfo, llvm.release_debuginfo);
3 changes: 3 additions & 0 deletions src/bootstrap/config.toml.example
Original file line number Diff line number Diff line change
@@ -14,6 +14,9 @@
# =============================================================================
[llvm]

# Indicates whether rustc will support compilation with LLVM (currently broken)
#enabled = true

# Indicates whether the LLVM build is a Release or Debug build
#optimize = true

3 changes: 3 additions & 0 deletions src/bootstrap/lib.rs
Original file line number Diff line number Diff line change
@@ -583,6 +583,9 @@ impl Build {
if self.config.use_jemalloc {
features.push_str(" jemalloc");
}
if self.config.llvm_enabled {
features.push_str(" llvm");
}
return features
}

5 changes: 5 additions & 0 deletions src/bootstrap/native.rs
Original file line number Diff line number Diff line change
@@ -35,6 +35,11 @@ use build_helper::up_to_date;

/// Compile LLVM for `target`.
pub fn llvm(build: &Build, target: &str) {
// If we're not compiling for LLVM bail out here.
if !build.config.llvm_enabled {
return;
}

// If we're using a custom LLVM bail out here, but we can only use a
// custom LLVM for the build triple.
if let Some(config) = build.config.target_config.get(target) {
5 changes: 4 additions & 1 deletion src/librustc_driver/Cargo.toml
Original file line number Diff line number Diff line change
@@ -29,9 +29,12 @@ rustc_plugin = { path = "../librustc_plugin" }
rustc_privacy = { path = "../librustc_privacy" }
rustc_resolve = { path = "../librustc_resolve" }
rustc_save_analysis = { path = "../librustc_save_analysis" }
rustc_trans = { path = "../librustc_trans" }
rustc_trans = { path = "../librustc_trans", optional=true }
rustc_typeck = { path = "../librustc_typeck" }
serialize = { path = "../libserialize" }
syntax = { path = "../libsyntax" }
syntax_ext = { path = "../libsyntax_ext" }
syntax_pos = { path = "../libsyntax_pos" }

[features]
llvm = ["rustc_trans"]
90 changes: 59 additions & 31 deletions src/librustc_driver/driver.rs
Original file line number Diff line number Diff line change
@@ -31,7 +31,11 @@ use rustc_incremental::{self, IncrementalHashesMap};
use rustc_resolve::{MakeGlobMap, Resolver};
use rustc_metadata::creader::CrateLoader;
use rustc_metadata::cstore::{self, CStore};
#[cfg(feature="llvm")]
use rustc_trans::back::{link, write};
#[cfg(not(feature="llvm"))]
use ::link;
#[cfg(feature="llvm")]
use rustc_trans as trans;
use rustc_typeck as typeck;
use rustc_privacy;
@@ -111,7 +115,7 @@ pub fn compile_input(sess: &Session,
};

let outputs = build_output_filenames(input, outdir, output, &krate.attrs, sess);
let crate_name = link::find_crate_name(Some(sess), &krate.attrs, input);
let crate_name: String = link::find_crate_name(Some(sess), &krate.attrs, input);
let ExpansionResult { expanded_crate, defs, analysis, resolutions, mut hir_forest } = {
phase_2_configure_and_expand(
sess, &cstore, krate, registry, &crate_name, addl_plugins, control.make_glob_map,
@@ -204,55 +208,71 @@ pub fn compile_input(sess: &Session,
println!("Pre-trans");
tcx.print_debug_stats();
}
let trans = phase_4_translate_to_llvm(tcx, analysis, &incremental_hashes_map,
&outputs);

if log_enabled!(::log::LogLevel::Info) {
println!("Post-trans");
tcx.print_debug_stats();
}
#[cfg(feature="llvm")]
{
let trans = phase_4_translate_to_llvm(tcx, analysis, &incremental_hashes_map,
&outputs);

if log_enabled!(::log::LogLevel::Info) {
println!("Post-trans");
tcx.print_debug_stats();
}

if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
if let Err(e) = mir::transform::dump_mir::emit_mir(tcx, &outputs) {
sess.err(&format!("could not emit MIR: {}", e));
sess.abort_if_errors();
if tcx.sess.opts.output_types.contains_key(&OutputType::Mir) {
if let Err(e) = mir::transform::dump_mir::emit_mir(tcx, &outputs) {
sess.err(&format!("could not emit MIR: {}", e));
sess.abort_if_errors();
}
}

return Ok((outputs, trans))
}

Ok((outputs, trans))
#[cfg(not(feature="llvm"))]
panic!("Unreachable")
})??
};

if sess.opts.debugging_opts.print_type_sizes {
sess.code_stats.borrow().print_type_sizes();
}

let phase5_result = phase_5_run_llvm_passes(sess, &trans, &outputs);
#[cfg(feature="llvm")]
{
let phase5_result = phase_5_run_llvm_passes(sess, &trans, &outputs);

controller_entry_point!(after_llvm,
sess,
CompileState::state_after_llvm(input, sess, outdir, output, &trans),
phase5_result);
phase5_result?;
controller_entry_point!(after_llvm,
sess,
CompileState::state_after_llvm(input, sess, outdir, output, &trans),
phase5_result);
phase5_result?;

write::cleanup_llvm(&trans);
write::cleanup_llvm(&trans);

phase_6_link_output(sess, &trans, &outputs);
phase_6_link_output(sess, &trans, &outputs);

// Now that we won't touch anything in the incremental compilation directory
// any more, we can finalize it (which involves renaming it)
rustc_incremental::finalize_session_directory(sess, trans.link.crate_hash);
// Now that we won't touch anything in the incremental compilation directory
// any more, we can finalize it (which involves renaming it)
rustc_incremental::finalize_session_directory(sess, trans.link.crate_hash);

if sess.opts.debugging_opts.perf_stats {
sess.print_perf_stats();
}
if sess.opts.debugging_opts.perf_stats {
sess.print_perf_stats();
}

controller_entry_point!(compilation_done,
sess,
CompileState::state_when_compilation_done(input,
sess,
outdir,
output),
Ok(()));

controller_entry_point!(compilation_done,
sess,
CompileState::state_when_compilation_done(input, sess, outdir, output),
Ok(()));
return Ok(())
}

Ok(())
#[cfg(not(feature="llvm"))]
panic!("Unreachable")
}

fn keep_hygiene_data(sess: &Session) -> bool {
@@ -355,6 +375,7 @@ pub struct CompileState<'a, 'tcx: 'a> {
pub resolutions: Option<&'a Resolutions>,
pub analysis: Option<&'a ty::CrateAnalysis>,
pub tcx: Option<TyCtxt<'a, 'tcx, 'tcx>>,
#[cfg(feature="llvm")]
pub trans: Option<&'a trans::CrateTranslation>,
}

@@ -381,6 +402,7 @@ impl<'a, 'tcx> CompileState<'a, 'tcx> {
resolutions: None,
analysis: None,
tcx: None,
#[cfg(feature="llvm")]
trans: None,
}
}
@@ -470,6 +492,7 @@ impl<'a, 'tcx> CompileState<'a, 'tcx> {
}


#[cfg(feature="llvm")]
fn state_after_llvm(input: &'a Input,
session: &'tcx Session,
out_dir: &'a Option<PathBuf>,
@@ -893,6 +916,7 @@ pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session,
mir::provide(&mut local_providers);
reachable::provide(&mut local_providers);
rustc_privacy::provide(&mut local_providers);
#[cfg(feature="llvm")]
trans::provide(&mut local_providers);
typeck::provide(&mut local_providers);
ty::provide(&mut local_providers);
@@ -904,6 +928,7 @@ pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session,

let mut extern_providers = ty::maps::Providers::default();
cstore::provide(&mut extern_providers);
#[cfg(feature="llvm")]
trans::provide(&mut extern_providers);
ty::provide_extern(&mut extern_providers);
traits::provide_extern(&mut extern_providers);
@@ -1045,6 +1070,7 @@ pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session,

/// Run the translation phase to LLVM, after which the AST and analysis can
/// be discarded.
#[cfg(feature="llvm")]
pub fn phase_4_translate_to_llvm<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
analysis: ty::CrateAnalysis,
incremental_hashes_map: &IncrementalHashesMap,
@@ -1076,6 +1102,7 @@ pub fn phase_4_translate_to_llvm<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,

/// Run LLVM itself, producing a bitcode file, assembly file or object file
/// as a side effect.
#[cfg(feature="llvm")]
pub fn phase_5_run_llvm_passes(sess: &Session,
trans: &trans::CrateTranslation,
outputs: &OutputFilenames) -> CompileResult {
@@ -1124,6 +1151,7 @@ pub fn phase_5_run_llvm_passes(sess: &Session,

/// Run the linker on any artifacts that resulted from the LLVM run.
/// This should produce either a finished executable or library.
#[cfg(feature="llvm")]
pub fn phase_6_link_output(sess: &Session,
trans: &trans::CrateTranslation,
outputs: &OutputFilenames) {
54 changes: 45 additions & 9 deletions src/librustc_driver/lib.rs
Original file line number Diff line number Diff line change
@@ -28,6 +28,8 @@
#![feature(rustc_diagnostic_macros)]
#![feature(set_stdio)]

#![cfg_attr(stage0, feature(struct_field_attributes))]

extern crate arena;
extern crate getopts;
extern crate graphviz;
@@ -48,6 +50,7 @@ extern crate rustc_metadata;
extern crate rustc_mir;
extern crate rustc_resolve;
extern crate rustc_save_analysis;
#[cfg(feature="llvm")]
extern crate rustc_trans;
extern crate rustc_typeck;
extern crate serialize;
@@ -63,7 +66,9 @@ use pretty::{PpMode, UserIdentifiedItem};
use rustc_resolve as resolve;
use rustc_save_analysis as save;
use rustc_save_analysis::DumpHandler;
#[cfg(feature="llvm")]
use rustc_trans::back::link;
#[cfg(feature="llvm")]
use rustc_trans::back::write::{RELOC_MODEL_ARGS, CODE_GEN_MODEL_ARGS};
use rustc::dep_graph::DepGraph;
use rustc::session::{self, config, Session, build_session, CompileResult};
@@ -175,6 +180,7 @@ pub fn run_compiler<'a>(args: &[String],
let (sopts, cfg) = config::build_session_options_and_crate_config(&matches);

if sopts.debugging_opts.debug_llvm {
#[cfg(feature="llvm")]
rustc_trans::enable_llvm_debug();
}

@@ -204,6 +210,7 @@ pub fn run_compiler<'a>(args: &[String],
let mut sess = session::build_session_with_codemap(
sopts, &dep_graph, input_file_path, descriptions, cstore.clone(), codemap, emitter_dest,
);
#[cfg(feature="llvm")]
rustc_trans::init(&sess);
rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));

@@ -409,6 +416,7 @@ impl<'a> CompilerCalls<'a> for RustcDefaultCalls {
None,
descriptions.clone(),
cstore.clone());
#[cfg(feature="llvm")]
rustc_trans::init(&sess);
rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
let mut cfg = config::build_configuration(&sess, cfg.clone());
@@ -607,7 +615,7 @@ impl RustcDefaultCalls {
};
let attrs = attrs.as_ref().unwrap();
let t_outputs = driver::build_output_filenames(input, odir, ofile, attrs, sess);
let id = link::find_crate_name(Some(sess), attrs, input);
let id: String = link::find_crate_name(Some(sess), attrs, input);
if *req == PrintRequest::CrateName {
println!("{}", id);
continue;
@@ -662,20 +670,36 @@ impl RustcDefaultCalls {
}
}
PrintRequest::RelocationModels => {
println!("Available relocation models:");
for &(name, _) in RELOC_MODEL_ARGS.iter() {
println!(" {}", name);
#[cfg(not(feature="llvm"))]
panic!("LLVM is not enabled for this rustc version");

#[cfg(feature="llvm")]
{
println!("Available relocation models:");
for &(name, _) in RELOC_MODEL_ARGS.iter() {
println!(" {}", name);
}
println!("");
}
println!("");
}
PrintRequest::CodeModels => {
println!("Available code models:");
for &(name, _) in CODE_GEN_MODEL_ARGS.iter(){
println!(" {}", name);
#[cfg(not(feature="llvm"))]
panic!("LLVM is not enabled for this rustc version");

#[cfg(feature="llvm")]
{
println!("Available code models:");
for &(name, _) in CODE_GEN_MODEL_ARGS.iter(){
println!(" {}", name);
}
println!("");
}
println!("");
}
PrintRequest::TargetCPUs | PrintRequest::TargetFeatures => {
#[cfg(not(feature="llvm"))]
panic!("LLVM is not enabled for this rustc version");

#[cfg(feature="llvm")]
rustc_trans::print(*req, sess);
}
}
@@ -715,6 +739,7 @@ pub fn version(binary: &str, matches: &getopts::Matches) {
println!("commit-date: {}", unw(commit_date_str()));
println!("host: {}", config::host_triple());
println!("release: {}", unw(release_str()));
#[cfg(feature="llvm")]
rustc_trans::print_version();
}
}
@@ -1008,6 +1033,10 @@ pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
}

if cg_flags.contains(&"passes=list".to_string()) {
#[cfg(not(feature="llvm"))]
panic!("LLVM is not enabled for this rustc version");

#[cfg(feature="llvm")]
rustc_trans::print_passes();
return None;
}
@@ -1135,6 +1164,7 @@ pub fn diagnostics_registry() -> errors::registry::Registry {
all_errors.extend_from_slice(&rustc_borrowck::DIAGNOSTICS);
all_errors.extend_from_slice(&rustc_resolve::DIAGNOSTICS);
all_errors.extend_from_slice(&rustc_privacy::DIAGNOSTICS);
#[cfg(feature="llvm")]
all_errors.extend_from_slice(&rustc_trans::DIAGNOSTICS);
all_errors.extend_from_slice(&rustc_const_eval::DIAGNOSTICS);
all_errors.extend_from_slice(&rustc_metadata::DIAGNOSTICS);
@@ -1159,3 +1189,9 @@ pub fn main() {
None));
process::exit(result as i32);
}


#[cfg(not(feature="llvm"))]
mod link {
include!("../librustc_trans/back/no_llvm_link.rs");
}
2 changes: 2 additions & 0 deletions src/librustc_driver/target_features.rs
Original file line number Diff line number Diff line change
@@ -11,6 +11,7 @@
use syntax::ast;
use rustc::session::Session;
use syntax::symbol::Symbol;
#[cfg(feature="llvm")]
use rustc_trans;

/// Add `target_feature = "..."` cfgs for a variety of platform
@@ -21,6 +22,7 @@ use rustc_trans;
pub fn add_configuration(cfg: &mut ast::CrateConfig, sess: &Session) {
let tf = Symbol::intern("target_feature");

#[cfg(feature="llvm")]
for feat in rustc_trans::target_features(sess) {
cfg.insert((tf, Some(feat)));
}
2 changes: 2 additions & 0 deletions src/librustc_driver/test.rs
Original file line number Diff line number Diff line change
@@ -14,6 +14,7 @@ use driver;
use rustc::dep_graph::DepGraph;
use rustc_lint;
use rustc_resolve::MakeGlobMap;
#[cfg(feature="llvm")]
use rustc_trans;
use rustc::middle::lang_items;
use rustc::middle::free_region::FreeRegionMap;
@@ -113,6 +114,7 @@ fn test_env<F>(source_string: &str,
diagnostic_handler,
Rc::new(CodeMap::new(FilePathMapping::empty())),
cstore.clone());
#[cfg(feature="llvm")]
rustc_trans::init(&sess);
rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess));
let input = config::Input::Str {
129 changes: 8 additions & 121 deletions src/librustc_trans/back/link.rs
Original file line number Diff line number Diff line change
@@ -13,11 +13,11 @@ use super::linker::Linker;
use super::rpath::RPathConfig;
use super::rpath;
use metadata::METADATA_FILENAME;
use rustc::session::config::{self, NoDebugInfo, OutputFilenames, Input, OutputType};
use rustc::session::config::{self, NoDebugInfo, OutputFilenames, OutputType};
use rustc::session::filesearch;
use rustc::session::search_paths::PathKind;
use rustc::session::Session;
use rustc::middle::cstore::{self, LinkMeta, NativeLibrary, LibSource, LinkagePreference,
use rustc::middle::cstore::{LinkMeta, NativeLibrary, LibSource, LinkagePreference,
NativeLibraryKind};
use rustc::middle::dependency_format::Linkage;
use CrateTranslation;
@@ -44,9 +44,13 @@ use std::process::Command;
use std::str;
use flate2::Compression;
use flate2::write::ZlibEncoder;
use syntax::ast;
use syntax::attr;
use syntax_pos::Span;

mod no_llvm_link {
include!("./no_llvm_link.rs");
}

pub use self::no_llvm_link::*;

/// The LLVM module name containing crate-metadata. This includes a `.` on
/// purpose, so it cannot clash with the name of a user-defined module.
@@ -84,56 +88,6 @@ pub const RLIB_BYTECODE_OBJECT_V1_DATASIZE_OFFSET: usize =
pub const RLIB_BYTECODE_OBJECT_V1_DATA_OFFSET: usize =
RLIB_BYTECODE_OBJECT_V1_DATASIZE_OFFSET + 8;


pub fn find_crate_name(sess: Option<&Session>,
attrs: &[ast::Attribute],
input: &Input) -> String {
let validate = |s: String, span: Option<Span>| {
cstore::validate_crate_name(sess, &s, span);
s
};

// Look in attributes 100% of the time to make sure the attribute is marked
// as used. After doing this, however, we still prioritize a crate name from
// the command line over one found in the #[crate_name] attribute. If we
// find both we ensure that they're the same later on as well.
let attr_crate_name = attrs.iter().find(|at| at.check_name("crate_name"))
.and_then(|at| at.value_str().map(|s| (at, s)));

if let Some(sess) = sess {
if let Some(ref s) = sess.opts.crate_name {
if let Some((attr, name)) = attr_crate_name {
if name != &**s {
let msg = format!("--crate-name and #[crate_name] are \
required to match, but `{}` != `{}`",
s, name);
sess.span_err(attr.span, &msg);
}
}
return validate(s.clone(), None);
}
}

if let Some((attr, s)) = attr_crate_name {
return validate(s.to_string(), Some(attr.span));
}
if let Input::File(ref path) = *input {
if let Some(s) = path.file_stem().and_then(|s| s.to_str()) {
if s.starts_with("-") {
let msg = format!("crate names cannot start with a `-`, but \
`{}` has a leading hyphen", s);
if let Some(sess) = sess {
sess.err(&msg);
}
} else {
return validate(s.replace("-", "_"), None);
}
}
}

"rust_out".to_string()
}

pub fn build_link_meta(incremental_hashes_map: &IncrementalHashesMap) -> LinkMeta {
let krate_dep_node = &DepNode::new_no_params(DepKind::Krate);
let r = LinkMeta {
@@ -245,37 +199,6 @@ pub fn link_binary(sess: &Session,
out_filenames
}


/// Returns default crate type for target
///
/// Default crate type is used when crate type isn't provided neither
/// through cmd line arguments nor through crate attributes
///
/// It is CrateTypeExecutable for all platforms but iOS as there is no
/// way to run iOS binaries anyway without jailbreaking and
/// interaction with Rust code through static library is the only
/// option for now
pub fn default_output_for_target(sess: &Session) -> config::CrateType {
if !sess.target.target.options.executables {
config::CrateTypeStaticlib
} else {
config::CrateTypeExecutable
}
}

/// Checks if target supports crate_type as output
pub fn invalid_output_for_target(sess: &Session,
crate_type: config::CrateType) -> bool {
match (sess.target.target.options.dynamic_linking,
sess.target.target.options.executables, crate_type) {
(false, _, config::CrateTypeCdylib) |
(false, _, config::CrateTypeProcMacro) |
(false, _, config::CrateTypeDylib) => true,
(_, false, config::CrateTypeExecutable) => true,
_ => false
}
}

fn is_writeable(p: &Path) -> bool {
match p.metadata() {
Err(..) => true,
@@ -292,42 +215,6 @@ fn filename_for_metadata(sess: &Session, crate_name: &str, outputs: &OutputFilen
out_filename
}

pub fn filename_for_input(sess: &Session,
crate_type: config::CrateType,
crate_name: &str,
outputs: &OutputFilenames) -> PathBuf {
let libname = format!("{}{}", crate_name, sess.opts.cg.extra_filename);

match crate_type {
config::CrateTypeRlib => {
outputs.out_directory.join(&format!("lib{}.rlib", libname))
}
config::CrateTypeCdylib |
config::CrateTypeProcMacro |
config::CrateTypeDylib => {
let (prefix, suffix) = (&sess.target.target.options.dll_prefix,
&sess.target.target.options.dll_suffix);
outputs.out_directory.join(&format!("{}{}{}", prefix, libname,
suffix))
}
config::CrateTypeStaticlib => {
let (prefix, suffix) = (&sess.target.target.options.staticlib_prefix,
&sess.target.target.options.staticlib_suffix);
outputs.out_directory.join(&format!("{}{}{}", prefix, libname,
suffix))
}
config::CrateTypeExecutable => {
let suffix = &sess.target.target.options.exe_suffix;
let out_filename = outputs.path(OutputType::Exe);
if suffix.is_empty() {
out_filename.to_path_buf()
} else {
out_filename.with_extension(&suffix[1..])
}
}
}
}

pub fn each_linked_rlib(sess: &Session,
f: &mut FnMut(CrateNum, &Path)) {
let crates = sess.cstore.used_crates(LinkagePreference::RequireStatic).into_iter();
133 changes: 133 additions & 0 deletions src/librustc_trans/back/no_llvm_link.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
// Copyright 2017 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 std::path::PathBuf;

use syntax::ast;
use syntax_pos::Span;

use rustc::session::Session;
use rustc::session::config::{self, OutputFilenames, Input, OutputType};
use rustc::middle::cstore;

pub fn filename_for_input(sess: &Session,
crate_type: config::CrateType,
crate_name: &str,
outputs: &OutputFilenames) -> PathBuf {
let libname = format!("{}{}", crate_name, sess.opts.cg.extra_filename);

match crate_type {
config::CrateTypeRlib => {
outputs.out_directory.join(&format!("lib{}.rlib", libname))
}
config::CrateTypeCdylib |
config::CrateTypeProcMacro |
config::CrateTypeDylib => {
let (prefix, suffix) = (&sess.target.target.options.dll_prefix,
&sess.target.target.options.dll_suffix);
outputs.out_directory.join(&format!("{}{}{}", prefix, libname,
suffix))
}
config::CrateTypeStaticlib => {
let (prefix, suffix) = (&sess.target.target.options.staticlib_prefix,
&sess.target.target.options.staticlib_suffix);
outputs.out_directory.join(&format!("{}{}{}", prefix, libname,
suffix))
}
config::CrateTypeExecutable => {
let suffix = &sess.target.target.options.exe_suffix;
let out_filename = outputs.path(OutputType::Exe);
if suffix.is_empty() {
out_filename.to_path_buf()
} else {
out_filename.with_extension(&suffix[1..])
}
}
}
}

pub fn find_crate_name(sess: Option<&Session>,
attrs: &[ast::Attribute],
input: &Input) -> String {
let validate = |s: String, span: Option<Span>| {
cstore::validate_crate_name(sess, &s, span);
s
};

// Look in attributes 100% of the time to make sure the attribute is marked
// as used. After doing this, however, we still prioritize a crate name from
// the command line over one found in the #[crate_name] attribute. If we
// find both we ensure that they're the same later on as well.
let attr_crate_name = attrs.iter().find(|at| at.check_name("crate_name"))
.and_then(|at| at.value_str().map(|s| (at, s)));

if let Some(sess) = sess {
if let Some(ref s) = sess.opts.crate_name {
if let Some((attr, name)) = attr_crate_name {
if name != &**s {
let msg = format!("--crate-name and #[crate_name] are \
required to match, but `{}` != `{}`",
s, name);
sess.span_err(attr.span, &msg);
}
}
return validate(s.clone(), None);
}
}

if let Some((attr, s)) = attr_crate_name {
return validate(s.to_string(), Some(attr.span));
}
if let Input::File(ref path) = *input {
if let Some(s) = path.file_stem().and_then(|s| s.to_str()) {
if s.starts_with("-") {
let msg = format!("crate names cannot start with a `-`, but \
`{}` has a leading hyphen", s);
if let Some(sess) = sess {
sess.err(&msg);
}
} else {
return validate(s.replace("-", "_"), None);
}
}
}

"rust_out".to_string()
}

/// Returns default crate type for target
///
/// Default crate type is used when crate type isn't provided neither
/// through cmd line arguments nor through crate attributes
///
/// It is CrateTypeExecutable for all platforms but iOS as there is no
/// way to run iOS binaries anyway without jailbreaking and
/// interaction with Rust code through static library is the only
/// option for now
pub fn default_output_for_target(sess: &Session) -> config::CrateType {
if !sess.target.target.options.executables {
config::CrateTypeStaticlib
} else {
config::CrateTypeExecutable
}
}

/// Checks if target supports crate_type as output
pub fn invalid_output_for_target(sess: &Session,
crate_type: config::CrateType) -> bool {
match (sess.target.target.options.dynamic_linking,
sess.target.target.options.executables, crate_type) {
(false, _, config::CrateTypeCdylib) |
(false, _, config::CrateTypeProcMacro) |
(false, _, config::CrateTypeDylib) => true,
(_, false, config::CrateTypeExecutable) => true,
_ => false
}
}
1 change: 1 addition & 0 deletions src/librustdoc/html/markdown.rs
Original file line number Diff line number Diff line change
@@ -42,6 +42,7 @@ use html::render::derive_id;
use html::toc::TocBuilder;
use html::highlight;
use html::escape::Escape;
#[cfg(feature="llvm")]
use test;

use pulldown_cmark::{html, Event, Tag, Parser};
1 change: 1 addition & 0 deletions src/librustdoc/lib.rs
Original file line number Diff line number Diff line change
@@ -87,6 +87,7 @@ pub mod passes;
pub mod plugins;
pub mod visit_ast;
pub mod visit_lib;
#[cfg(feature="llvm")]
pub mod test;

use clean::AttributesExt;
1 change: 1 addition & 0 deletions src/librustdoc/markdown.rs
Original file line number Diff line number Diff line change
@@ -27,6 +27,7 @@ use html::escape::Escape;
use html::markdown;
use html::markdown::{Markdown, MarkdownWithToc, find_testable_code, old_find_testable_code};
use html::markdown::RenderType;
#[cfg(feature="llvm")]
use test::{TestOptions, Collector};

/// Separate any lines at the start of the file that begin with `# ` or `%`.
1 change: 1 addition & 0 deletions src/rustc/Cargo.toml
Original file line number Diff line number Diff line change
@@ -20,3 +20,4 @@ rustdoc = { path = "../librustdoc" }

[features]
jemalloc = ["rustc_back/jemalloc"]
llvm = ["rustc_driver/llvm"]