-
Notifications
You must be signed in to change notification settings - Fork 12.7k
/
config.rs
2476 lines (2202 loc) · 102 KB
/
config.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 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.
//! Contains infrastructure for configuring the compiler, including parsing
//! command line options.
pub use self::EntryFnType::*;
pub use self::CrateType::*;
pub use self::Passes::*;
pub use self::DebugInfoLevel::*;
use session::{early_error, early_warn, Session};
use session::search_paths::SearchPaths;
use rustc_back::PanicStrategy;
use rustc_back::target::Target;
use lint;
use middle::cstore;
use syntax::ast::{self, IntTy, UintTy};
use syntax::parse;
use syntax::symbol::Symbol;
use syntax::feature_gate::UnstableFeatures;
use errors::{ColorConfig, FatalError, Handler};
use getopts;
use std::collections::{BTreeMap, BTreeSet};
use std::collections::btree_map::Iter as BTreeMapIter;
use std::collections::btree_map::Keys as BTreeMapKeysIter;
use std::collections::btree_map::Values as BTreeMapValuesIter;
use std::fmt;
use std::hash::Hasher;
use std::collections::hash_map::DefaultHasher;
use std::collections::HashSet;
use std::iter::FromIterator;
use std::path::PathBuf;
pub struct Config {
pub target: Target,
pub int_type: IntTy,
pub uint_type: UintTy,
}
#[derive(Clone, Copy, PartialEq, Hash)]
pub enum OptLevel {
No, // -O0
Less, // -O1
Default, // -O2
Aggressive, // -O3
Size, // -Os
SizeMin, // -Oz
}
#[derive(Clone, Copy, PartialEq, Hash)]
pub enum DebugInfoLevel {
NoDebugInfo,
LimitedDebugInfo,
FullDebugInfo,
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, PartialOrd, Ord,
RustcEncodable, RustcDecodable)]
pub enum OutputType {
Bitcode,
Assembly,
LlvmAssembly,
Object,
Exe,
DepInfo,
}
impl OutputType {
fn is_compatible_with_codegen_units_and_single_output_file(&self) -> bool {
match *self {
OutputType::Exe |
OutputType::DepInfo => true,
OutputType::Bitcode |
OutputType::Assembly |
OutputType::LlvmAssembly |
OutputType::Object => false,
}
}
fn shorthand(&self) -> &'static str {
match *self {
OutputType::Bitcode => "llvm-bc",
OutputType::Assembly => "asm",
OutputType::LlvmAssembly => "llvm-ir",
OutputType::Object => "obj",
OutputType::Exe => "link",
OutputType::DepInfo => "dep-info",
}
}
pub fn extension(&self) -> &'static str {
match *self {
OutputType::Bitcode => "bc",
OutputType::Assembly => "s",
OutputType::LlvmAssembly => "ll",
OutputType::Object => "o",
OutputType::DepInfo => "d",
OutputType::Exe => "",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ErrorOutputType {
HumanReadable(ColorConfig),
Json,
}
impl Default for ErrorOutputType {
fn default() -> ErrorOutputType {
ErrorOutputType::HumanReadable(ColorConfig::Auto)
}
}
// Use tree-based collections to cheaply get a deterministic Hash implementation.
// DO NOT switch BTreeMap out for an unsorted container type! That would break
// dependency tracking for commandline arguments.
#[derive(Clone, Hash)]
pub struct OutputTypes(BTreeMap<OutputType, Option<PathBuf>>);
impl OutputTypes {
pub fn new(entries: &[(OutputType, Option<PathBuf>)]) -> OutputTypes {
OutputTypes(BTreeMap::from_iter(entries.iter()
.map(|&(k, ref v)| (k, v.clone()))))
}
pub fn get(&self, key: &OutputType) -> Option<&Option<PathBuf>> {
self.0.get(key)
}
pub fn contains_key(&self, key: &OutputType) -> bool {
self.0.contains_key(key)
}
pub fn keys<'a>(&'a self) -> BTreeMapKeysIter<'a, OutputType, Option<PathBuf>> {
self.0.keys()
}
pub fn values<'a>(&'a self) -> BTreeMapValuesIter<'a, OutputType, Option<PathBuf>> {
self.0.values()
}
}
// Use tree-based collections to cheaply get a deterministic Hash implementation.
// DO NOT switch BTreeMap or BTreeSet out for an unsorted container type! That
// would break dependency tracking for commandline arguments.
#[derive(Clone, Hash)]
pub struct Externs(BTreeMap<String, BTreeSet<String>>);
impl Externs {
pub fn new(data: BTreeMap<String, BTreeSet<String>>) -> Externs {
Externs(data)
}
pub fn get(&self, key: &str) -> Option<&BTreeSet<String>> {
self.0.get(key)
}
pub fn iter<'a>(&'a self) -> BTreeMapIter<'a, String, BTreeSet<String>> {
self.0.iter()
}
}
macro_rules! hash_option {
($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, [UNTRACKED]) => ({});
($opt_name:ident, $opt_expr:expr, $sub_hashes:expr, [TRACKED]) => ({
if $sub_hashes.insert(stringify!($opt_name),
$opt_expr as &dep_tracking::DepTrackingHash).is_some() {
bug!("Duplicate key in CLI DepTrackingHash: {}", stringify!($opt_name))
}
});
($opt_name:ident,
$opt_expr:expr,
$sub_hashes:expr,
[UNTRACKED_WITH_WARNING $warn_val:expr, $warn_text:expr, $error_format:expr]) => ({
if *$opt_expr == $warn_val {
early_warn($error_format, $warn_text)
}
});
}
macro_rules! top_level_options {
(pub struct Options { $(
$opt:ident : $t:ty [$dep_tracking_marker:ident $($warn_val:expr, $warn_text:expr)*],
)* } ) => (
#[derive(Clone)]
pub struct Options {
$(pub $opt: $t),*
}
impl Options {
pub fn dep_tracking_hash(&self) -> u64 {
let mut sub_hashes = BTreeMap::new();
$({
hash_option!($opt,
&self.$opt,
&mut sub_hashes,
[$dep_tracking_marker $($warn_val,
$warn_text,
self.error_format)*]);
})*
let mut hasher = DefaultHasher::new();
dep_tracking::stable_hash(sub_hashes,
&mut hasher,
self.error_format);
hasher.finish()
}
}
);
}
// The top-level commandline options struct
//
// For each option, one has to specify how it behaves with regard to the
// dependency tracking system of incremental compilation. This is done via the
// square-bracketed directive after the field type. The options are:
//
// [TRACKED]
// A change in the given field will cause the compiler to completely clear the
// incremental compilation cache before proceeding.
//
// [UNTRACKED]
// Incremental compilation is not influenced by this option.
//
// [UNTRACKED_WITH_WARNING(val, warning)]
// The option is incompatible with incremental compilation in some way. If it
// has the value `val`, the string `warning` is emitted as a warning.
//
// If you add a new option to this struct or one of the sub-structs like
// CodegenOptions, think about how it influences incremental compilation. If in
// doubt, specify [TRACKED], which is always "correct" but might lead to
// unnecessary re-compilation.
top_level_options!(
pub struct Options {
// The crate config requested for the session, which may be combined
// with additional crate configurations during the compile process
crate_types: Vec<CrateType> [TRACKED],
optimize: OptLevel [TRACKED],
// Include the debug_assertions flag into dependency tracking, since it
// can influence whether overflow checks are done or not.
debug_assertions: bool [TRACKED],
debuginfo: DebugInfoLevel [TRACKED],
lint_opts: Vec<(String, lint::Level)> [TRACKED],
lint_cap: Option<lint::Level> [TRACKED],
describe_lints: bool [UNTRACKED],
output_types: OutputTypes [TRACKED],
// FIXME(mw): We track this for now but it actually doesn't make too
// much sense: The search path can stay the same while the
// things discovered there might have changed on disk.
search_paths: SearchPaths [TRACKED],
libs: Vec<(String, Option<String>, cstore::NativeLibraryKind)> [TRACKED],
maybe_sysroot: Option<PathBuf> [TRACKED],
target_triple: String [TRACKED],
test: bool [TRACKED],
error_format: ErrorOutputType [UNTRACKED],
// if Some, enable incremental compilation, using the given
// directory to store intermediate results
incremental: Option<PathBuf> [UNTRACKED],
debugging_opts: DebuggingOptions [TRACKED],
prints: Vec<PrintRequest> [UNTRACKED],
cg: CodegenOptions [TRACKED],
// FIXME(mw): We track this for now but it actually doesn't make too
// much sense: The value of this option can stay the same
// while the files they refer to might have changed on disk.
externs: Externs [TRACKED],
crate_name: Option<String> [TRACKED],
// An optional name to use as the crate for std during std injection,
// written `extern crate std = "name"`. Default to "std". Used by
// out-of-tree drivers.
alt_std_name: Option<String> [TRACKED],
// Indicates how the compiler should treat unstable features
unstable_features: UnstableFeatures [TRACKED],
// Indicates whether this run of the compiler is actually rustdoc. This
// is currently just a hack and will be removed eventually, so please
// try to not rely on this too much.
actually_rustdoc: bool [TRACKED],
}
);
#[derive(Clone, PartialEq, Eq)]
pub enum PrintRequest {
FileNames,
Sysroot,
CrateName,
Cfg,
TargetList,
TargetCPUs,
TargetFeatures,
RelocationModels,
CodeModels,
TargetSpec,
}
pub enum Input {
/// Load source from file
File(PathBuf),
Str {
/// String that is shown in place of a filename
name: String,
/// Anonymous source string
input: String,
},
}
impl Input {
pub fn filestem(&self) -> String {
match *self {
Input::File(ref ifile) => ifile.file_stem().unwrap()
.to_str().unwrap().to_string(),
Input::Str { .. } => "rust_out".to_string(),
}
}
}
#[derive(Clone)]
pub struct OutputFilenames {
pub out_directory: PathBuf,
pub out_filestem: String,
pub single_output_file: Option<PathBuf>,
pub extra: String,
pub outputs: OutputTypes,
}
/// Codegen unit names generated by the numbered naming scheme will contain this
/// marker right before the index of the codegen unit.
pub const NUMBERED_CODEGEN_UNIT_MARKER: &'static str = ".cgu-";
impl OutputFilenames {
pub fn path(&self, flavor: OutputType) -> PathBuf {
self.outputs.get(&flavor).and_then(|p| p.to_owned())
.or_else(|| self.single_output_file.clone())
.unwrap_or_else(|| self.temp_path(flavor, None))
}
/// Get the path where a compilation artifact of the given type for the
/// given codegen unit should be placed on disk. If codegen_unit_name is
/// None, a path distinct from those of any codegen unit will be generated.
pub fn temp_path(&self,
flavor: OutputType,
codegen_unit_name: Option<&str>)
-> PathBuf {
let extension = flavor.extension();
self.temp_path_ext(extension, codegen_unit_name)
}
/// Like temp_path, but also supports things where there is no corresponding
/// OutputType, like no-opt-bitcode or lto-bitcode.
pub fn temp_path_ext(&self,
ext: &str,
codegen_unit_name: Option<&str>)
-> PathBuf {
let base = self.out_directory.join(&self.filestem());
let mut extension = String::new();
if let Some(codegen_unit_name) = codegen_unit_name {
if codegen_unit_name.contains(NUMBERED_CODEGEN_UNIT_MARKER) {
// If we use the numbered naming scheme for modules, we don't want
// the files to look like <crate-name><extra>.<crate-name>.<index>.<ext>
// but simply <crate-name><extra>.<index>.<ext>
let marker_offset = codegen_unit_name.rfind(NUMBERED_CODEGEN_UNIT_MARKER)
.unwrap();
let index_offset = marker_offset + NUMBERED_CODEGEN_UNIT_MARKER.len();
extension.push_str(&codegen_unit_name[index_offset .. ]);
} else {
extension.push_str(codegen_unit_name);
};
}
if !ext.is_empty() {
if !extension.is_empty() {
extension.push_str(".");
}
extension.push_str(ext);
}
let path = base.with_extension(&extension[..]);
path
}
pub fn with_extension(&self, extension: &str) -> PathBuf {
self.out_directory.join(&self.filestem()).with_extension(extension)
}
pub fn filestem(&self) -> String {
format!("{}{}", self.out_filestem, self.extra)
}
}
pub fn host_triple() -> &'static str {
// Get the host triple out of the build environment. This ensures that our
// idea of the host triple is the same as for the set of libraries we've
// actually built. We can't just take LLVM's host triple because they
// normalize all ix86 architectures to i386.
//
// Instead of grabbing the host triple (for the current host), we grab (at
// compile time) the target triple that this rustc is built with and
// calling that (at runtime) the host triple.
(option_env!("CFG_COMPILER_HOST_TRIPLE")).
expect("CFG_COMPILER_HOST_TRIPLE")
}
/// Some reasonable defaults
pub fn basic_options() -> Options {
Options {
crate_types: Vec::new(),
optimize: OptLevel::No,
debuginfo: NoDebugInfo,
lint_opts: Vec::new(),
lint_cap: None,
describe_lints: false,
output_types: OutputTypes(BTreeMap::new()),
search_paths: SearchPaths::new(),
maybe_sysroot: None,
target_triple: host_triple().to_string(),
test: false,
incremental: None,
debugging_opts: basic_debugging_options(),
prints: Vec::new(),
cg: basic_codegen_options(),
error_format: ErrorOutputType::default(),
externs: Externs(BTreeMap::new()),
crate_name: None,
alt_std_name: None,
libs: Vec::new(),
unstable_features: UnstableFeatures::Disallow,
debug_assertions: true,
actually_rustdoc: false,
}
}
impl Options {
/// True if there is a reason to build the dep graph.
pub fn build_dep_graph(&self) -> bool {
self.incremental.is_some() ||
self.debugging_opts.dump_dep_graph ||
self.debugging_opts.query_dep_graph
}
pub fn single_codegen_unit(&self) -> bool {
self.incremental.is_none() ||
self.cg.codegen_units == 1
}
}
// The type of entry function, so
// users can have their own entry
// functions that don't start a
// scheduler
#[derive(Copy, Clone, PartialEq)]
pub enum EntryFnType {
EntryMain,
EntryStart,
EntryNone,
}
#[derive(Copy, PartialEq, PartialOrd, Clone, Ord, Eq, Hash, Debug)]
pub enum CrateType {
CrateTypeExecutable,
CrateTypeDylib,
CrateTypeRlib,
CrateTypeStaticlib,
CrateTypeCdylib,
CrateTypeProcMacro,
CrateTypeMetadata,
}
#[derive(Clone, Hash)]
pub enum Passes {
SomePasses(Vec<String>),
AllPasses,
}
impl Passes {
pub fn is_empty(&self) -> bool {
match *self {
SomePasses(ref v) => v.is_empty(),
AllPasses => false,
}
}
}
/// Declare a macro that will define all CodegenOptions/DebuggingOptions fields and parsers all
/// at once. The goal of this macro is to define an interface that can be
/// programmatically used by the option parser in order to initialize the struct
/// without hardcoding field names all over the place.
///
/// The goal is to invoke this macro once with the correct fields, and then this
/// macro generates all necessary code. The main gotcha of this macro is the
/// cgsetters module which is a bunch of generated code to parse an option into
/// its respective field in the struct. There are a few hand-written parsers for
/// parsing specific types of values in this module.
macro_rules! options {
($struct_name:ident, $setter_name:ident, $defaultfn:ident,
$buildfn:ident, $prefix:expr, $outputname:expr,
$stat:ident, $mod_desc:ident, $mod_set:ident,
$($opt:ident : $t:ty = (
$init:expr,
$parse:ident,
[$dep_tracking_marker:ident $(($dep_warn_val:expr, $dep_warn_text:expr))*],
$desc:expr)
),* ,) =>
(
#[derive(Clone)]
pub struct $struct_name { $(pub $opt: $t),* }
pub fn $defaultfn() -> $struct_name {
$struct_name { $($opt: $init),* }
}
pub fn $buildfn(matches: &getopts::Matches, error_format: ErrorOutputType) -> $struct_name
{
let mut op = $defaultfn();
for option in matches.opt_strs($prefix) {
let mut iter = option.splitn(2, '=');
let key = iter.next().unwrap();
let value = iter.next();
let option_to_lookup = key.replace("-", "_");
let mut found = false;
for &(candidate, setter, opt_type_desc, _) in $stat {
if option_to_lookup != candidate { continue }
if !setter(&mut op, value) {
match (value, opt_type_desc) {
(Some(..), None) => {
early_error(error_format, &format!("{} option `{}` takes no \
value", $outputname, key))
}
(None, Some(type_desc)) => {
early_error(error_format, &format!("{0} option `{1}` requires \
{2} ({3} {1}=<value>)",
$outputname, key,
type_desc, $prefix))
}
(Some(value), Some(type_desc)) => {
early_error(error_format, &format!("incorrect value `{}` for {} \
option `{}` - {} was expected",
value, $outputname,
key, type_desc))
}
(None, None) => bug!()
}
}
found = true;
break;
}
if !found {
early_error(error_format, &format!("unknown {} option: `{}`",
$outputname, key));
}
}
return op;
}
impl<'a> dep_tracking::DepTrackingHash for $struct_name {
fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) {
let mut sub_hashes = BTreeMap::new();
$({
hash_option!($opt,
&self.$opt,
&mut sub_hashes,
[$dep_tracking_marker $($dep_warn_val,
$dep_warn_text,
error_format)*]);
})*
dep_tracking::stable_hash(sub_hashes, hasher, error_format);
}
}
pub type $setter_name = fn(&mut $struct_name, v: Option<&str>) -> bool;
pub const $stat: &'static [(&'static str, $setter_name,
Option<&'static str>, &'static str)] =
&[ $( (stringify!($opt), $mod_set::$opt, $mod_desc::$parse, $desc) ),* ];
#[allow(non_upper_case_globals, dead_code)]
mod $mod_desc {
pub const parse_bool: Option<&'static str> = None;
pub const parse_opt_bool: Option<&'static str> =
Some("one of: `y`, `yes`, `on`, `n`, `no`, or `off`");
pub const parse_string: Option<&'static str> = Some("a string");
pub const parse_string_push: Option<&'static str> = Some("a string");
pub const parse_opt_string: Option<&'static str> = Some("a string");
pub const parse_list: Option<&'static str> = Some("a space-separated list of strings");
pub const parse_opt_list: Option<&'static str> = Some("a space-separated list of strings");
pub const parse_uint: Option<&'static str> = Some("a number");
pub const parse_passes: Option<&'static str> =
Some("a space-separated list of passes, or `all`");
pub const parse_opt_uint: Option<&'static str> =
Some("a number");
pub const parse_panic_strategy: Option<&'static str> =
Some("either `panic` or `abort`");
}
#[allow(dead_code)]
mod $mod_set {
use super::{$struct_name, Passes, SomePasses, AllPasses};
use rustc_back::PanicStrategy;
$(
pub fn $opt(cg: &mut $struct_name, v: Option<&str>) -> bool {
$parse(&mut cg.$opt, v)
}
)*
fn parse_bool(slot: &mut bool, v: Option<&str>) -> bool {
match v {
Some(..) => false,
None => { *slot = true; true }
}
}
fn parse_opt_bool(slot: &mut Option<bool>, v: Option<&str>) -> bool {
match v {
Some(s) => {
match s {
"n" | "no" | "off" => {
*slot = Some(false);
}
"y" | "yes" | "on" => {
*slot = Some(true);
}
_ => { return false; }
}
true
},
None => { *slot = Some(true); true }
}
}
fn parse_opt_string(slot: &mut Option<String>, v: Option<&str>) -> bool {
match v {
Some(s) => { *slot = Some(s.to_string()); true },
None => false,
}
}
fn parse_string(slot: &mut String, v: Option<&str>) -> bool {
match v {
Some(s) => { *slot = s.to_string(); true },
None => false,
}
}
fn parse_string_push(slot: &mut Vec<String>, v: Option<&str>) -> bool {
match v {
Some(s) => { slot.push(s.to_string()); true },
None => false,
}
}
fn parse_list(slot: &mut Vec<String>, v: Option<&str>)
-> bool {
match v {
Some(s) => {
for s in s.split_whitespace() {
slot.push(s.to_string());
}
true
},
None => false,
}
}
fn parse_opt_list(slot: &mut Option<Vec<String>>, v: Option<&str>)
-> bool {
match v {
Some(s) => {
let v = s.split_whitespace().map(|s| s.to_string()).collect();
*slot = Some(v);
true
},
None => false,
}
}
fn parse_uint(slot: &mut usize, v: Option<&str>) -> bool {
match v.and_then(|s| s.parse().ok()) {
Some(i) => { *slot = i; true },
None => false
}
}
fn parse_opt_uint(slot: &mut Option<usize>, v: Option<&str>) -> bool {
match v {
Some(s) => { *slot = s.parse().ok(); slot.is_some() }
None => { *slot = None; true }
}
}
fn parse_passes(slot: &mut Passes, v: Option<&str>) -> bool {
match v {
Some("all") => {
*slot = AllPasses;
true
}
v => {
let mut passes = vec![];
if parse_list(&mut passes, v) {
*slot = SomePasses(passes);
true
} else {
false
}
}
}
}
fn parse_panic_strategy(slot: &mut Option<PanicStrategy>, v: Option<&str>) -> bool {
match v {
Some("unwind") => *slot = Some(PanicStrategy::Unwind),
Some("abort") => *slot = Some(PanicStrategy::Abort),
_ => return false
}
true
}
}
) }
options! {CodegenOptions, CodegenSetter, basic_codegen_options,
build_codegen_options, "C", "codegen",
CG_OPTIONS, cg_type_desc, cgsetters,
ar: Option<String> = (None, parse_opt_string, [UNTRACKED],
"tool to assemble archives with"),
linker: Option<String> = (None, parse_opt_string, [UNTRACKED],
"system linker to link outputs with"),
link_arg: Vec<String> = (vec![], parse_string_push, [UNTRACKED],
"a single extra argument to pass to the linker (can be used several times)"),
link_args: Option<Vec<String>> = (None, parse_opt_list, [UNTRACKED],
"extra arguments to pass to the linker (space separated)"),
link_dead_code: bool = (false, parse_bool, [UNTRACKED],
"don't let linker strip dead code (turning it on can be used for code coverage)"),
lto: bool = (false, parse_bool, [TRACKED],
"perform LLVM link-time optimizations"),
target_cpu: Option<String> = (None, parse_opt_string, [TRACKED],
"select target processor (rustc --print target-cpus for details)"),
target_feature: String = ("".to_string(), parse_string, [TRACKED],
"target specific attributes (rustc --print target-features for details)"),
passes: Vec<String> = (Vec::new(), parse_list, [TRACKED],
"a list of extra LLVM passes to run (space separated)"),
llvm_args: Vec<String> = (Vec::new(), parse_list, [TRACKED],
"a list of arguments to pass to llvm (space separated)"),
save_temps: bool = (false, parse_bool, [UNTRACKED_WITH_WARNING(true,
"`-C save-temps` might not produce all requested temporary products \
when incremental compilation is enabled.")],
"save all temporary output files during compilation"),
rpath: bool = (false, parse_bool, [UNTRACKED],
"set rpath values in libs/exes"),
no_prepopulate_passes: bool = (false, parse_bool, [TRACKED],
"don't pre-populate the pass manager with a list of passes"),
no_vectorize_loops: bool = (false, parse_bool, [TRACKED],
"don't run the loop vectorization optimization passes"),
no_vectorize_slp: bool = (false, parse_bool, [TRACKED],
"don't run LLVM's SLP vectorization pass"),
soft_float: bool = (false, parse_bool, [TRACKED],
"use soft float ABI (*eabihf targets only)"),
prefer_dynamic: bool = (false, parse_bool, [TRACKED],
"prefer dynamic linking to static linking"),
no_integrated_as: bool = (false, parse_bool, [TRACKED],
"use an external assembler rather than LLVM's integrated one"),
no_redzone: Option<bool> = (None, parse_opt_bool, [TRACKED],
"disable the use of the redzone"),
relocation_model: Option<String> = (None, parse_opt_string, [TRACKED],
"choose the relocation model to use (rustc --print relocation-models for details)"),
code_model: Option<String> = (None, parse_opt_string, [TRACKED],
"choose the code model to use (rustc --print code-models for details)"),
metadata: Vec<String> = (Vec::new(), parse_list, [TRACKED],
"metadata to mangle symbol names with"),
extra_filename: String = ("".to_string(), parse_string, [UNTRACKED],
"extra data to put in each output filename"),
codegen_units: usize = (1, parse_uint, [UNTRACKED],
"divide crate into N units to optimize in parallel"),
remark: Passes = (SomePasses(Vec::new()), parse_passes, [UNTRACKED],
"print remarks for these optimization passes (space separated, or \"all\")"),
no_stack_check: bool = (false, parse_bool, [UNTRACKED],
"the --no-stack-check flag is deprecated and does nothing"),
debuginfo: Option<usize> = (None, parse_opt_uint, [TRACKED],
"debug info emission level, 0 = no debug info, 1 = line tables only, \
2 = full debug info with variable and type information"),
opt_level: Option<String> = (None, parse_opt_string, [TRACKED],
"optimize with possible levels 0-3, s, or z"),
debug_assertions: Option<bool> = (None, parse_opt_bool, [TRACKED],
"explicitly enable the cfg(debug_assertions) directive"),
inline_threshold: Option<usize> = (None, parse_opt_uint, [TRACKED],
"set the inlining threshold for"),
panic: Option<PanicStrategy> = (None, parse_panic_strategy,
[TRACKED], "panic strategy to compile crate with"),
}
options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
build_debugging_options, "Z", "debugging",
DB_OPTIONS, db_type_desc, dbsetters,
verbose: bool = (false, parse_bool, [UNTRACKED],
"in general, enable more debug printouts"),
time_passes: bool = (false, parse_bool, [UNTRACKED],
"measure time of each rustc pass"),
count_llvm_insns: bool = (false, parse_bool,
[UNTRACKED_WITH_WARNING(true,
"The output generated by `-Z count_llvm_insns` might not be reliable \
when used with incremental compilation")],
"count where LLVM instrs originate"),
time_llvm_passes: bool = (false, parse_bool, [UNTRACKED_WITH_WARNING(true,
"The output of `-Z time-llvm-passes` will only reflect timings of \
re-translated modules when used with incremental compilation" )],
"measure time of each LLVM pass"),
input_stats: bool = (false, parse_bool, [UNTRACKED],
"gather statistics about the input"),
trans_stats: bool = (false, parse_bool, [UNTRACKED_WITH_WARNING(true,
"The output of `-Z trans-stats` might not be accurate when incremental \
compilation is enabled")],
"gather trans statistics"),
asm_comments: bool = (false, parse_bool, [TRACKED],
"generate comments into the assembly (may change behavior)"),
no_verify: bool = (false, parse_bool, [TRACKED],
"skip LLVM verification"),
borrowck_stats: bool = (false, parse_bool, [UNTRACKED],
"gather borrowck statistics"),
no_landing_pads: bool = (false, parse_bool, [TRACKED],
"omit landing pads for unwinding"),
debug_llvm: bool = (false, parse_bool, [UNTRACKED],
"enable debug output from LLVM"),
meta_stats: bool = (false, parse_bool, [UNTRACKED],
"gather metadata statistics"),
print_link_args: bool = (false, parse_bool, [UNTRACKED],
"print the arguments passed to the linker"),
print_llvm_passes: bool = (false, parse_bool, [UNTRACKED],
"prints the llvm optimization passes being run"),
ast_json: bool = (false, parse_bool, [UNTRACKED],
"print the AST as JSON and halt"),
ast_json_noexpand: bool = (false, parse_bool, [UNTRACKED],
"print the pre-expansion AST as JSON and halt"),
ls: bool = (false, parse_bool, [UNTRACKED],
"list the symbols defined by a library crate"),
save_analysis: bool = (false, parse_bool, [UNTRACKED],
"write syntax and type analysis (in JSON format) information, in \
addition to normal output"),
save_analysis_csv: bool = (false, parse_bool, [UNTRACKED],
"write syntax and type analysis (in CSV format) information, in addition to normal output"),
save_analysis_api: bool = (false, parse_bool, [UNTRACKED],
"write syntax and type analysis information for opaque libraries (in JSON format), \
in addition to normal output"),
print_move_fragments: bool = (false, parse_bool, [UNTRACKED],
"print out move-fragment data for every fn"),
flowgraph_print_loans: bool = (false, parse_bool, [UNTRACKED],
"include loan analysis data in --unpretty flowgraph output"),
flowgraph_print_moves: bool = (false, parse_bool, [UNTRACKED],
"include move analysis data in --unpretty flowgraph output"),
flowgraph_print_assigns: bool = (false, parse_bool, [UNTRACKED],
"include assignment analysis data in --unpretty flowgraph output"),
flowgraph_print_all: bool = (false, parse_bool, [UNTRACKED],
"include all dataflow analysis data in --unpretty flowgraph output"),
print_region_graph: bool = (false, parse_bool, [UNTRACKED],
"prints region inference graph. \
Use with RUST_REGION_GRAPH=help for more info"),
parse_only: bool = (false, parse_bool, [UNTRACKED],
"parse only; do not compile, assemble, or link"),
no_trans: bool = (false, parse_bool, [TRACKED],
"run all passes except translation; no output"),
treat_err_as_bug: bool = (false, parse_bool, [TRACKED],
"treat all errors that occur as bugs"),
continue_parse_after_error: bool = (false, parse_bool, [TRACKED],
"attempt to recover from parse errors (experimental)"),
incremental: Option<String> = (None, parse_opt_string, [UNTRACKED],
"enable incremental compilation (experimental)"),
incremental_info: bool = (false, parse_bool, [UNTRACKED],
"print high-level information about incremental reuse (or the lack thereof)"),
incremental_dump_hash: bool = (false, parse_bool, [UNTRACKED],
"dump hash information in textual format to stdout"),
dump_dep_graph: bool = (false, parse_bool, [UNTRACKED],
"dump the dependency graph to $RUST_DEP_GRAPH (default: /tmp/dep_graph.gv)"),
query_dep_graph: bool = (false, parse_bool, [UNTRACKED],
"enable queries of the dependency graph for regression testing"),
no_analysis: bool = (false, parse_bool, [UNTRACKED],
"parse and expand the source, but run no analysis"),
extra_plugins: Vec<String> = (Vec::new(), parse_list, [TRACKED],
"load extra plugins"),
unstable_options: bool = (false, parse_bool, [UNTRACKED],
"adds unstable command line options to rustc interface"),
force_overflow_checks: Option<bool> = (None, parse_opt_bool, [TRACKED],
"force overflow checks on or off"),
trace_macros: bool = (false, parse_bool, [UNTRACKED],
"for every macro invocation, print its name and arguments"),
debug_macros: bool = (false, parse_bool, [TRACKED],
"emit line numbers debug info inside macros"),
enable_nonzeroing_move_hints: bool = (false, parse_bool, [TRACKED],
"force nonzeroing move optimization on"),
keep_hygiene_data: bool = (false, parse_bool, [UNTRACKED],
"don't clear the hygiene data after analysis"),
keep_ast: bool = (false, parse_bool, [UNTRACKED],
"keep the AST after lowering it to HIR"),
show_span: Option<String> = (None, parse_opt_string, [TRACKED],
"show spans for compiler debugging (expr|pat|ty)"),
print_type_sizes: bool = (false, parse_bool, [UNTRACKED],
"print layout information for each type encountered"),
print_trans_items: Option<String> = (None, parse_opt_string, [UNTRACKED],
"print the result of the translation item collection pass"),
mir_opt_level: usize = (1, parse_uint, [TRACKED],
"set the MIR optimization level (0-3, default: 1)"),
dump_mir: Option<String> = (None, parse_opt_string, [UNTRACKED],
"dump MIR state at various points in translation"),
dump_mir_dir: Option<String> = (None, parse_opt_string, [UNTRACKED],
"the directory the MIR is dumped into"),
perf_stats: bool = (false, parse_bool, [UNTRACKED],
"print some performance-related statistics"),
hir_stats: bool = (false, parse_bool, [UNTRACKED],
"print some statistics about AST and HIR"),
mir_stats: bool = (false, parse_bool, [UNTRACKED],
"print some statistics about MIR"),
always_encode_mir: bool = (false, parse_bool, [TRACKED],
"encode MIR of all functions into the crate metadata"),
}
pub fn default_lib_output() -> CrateType {
CrateTypeRlib
}
pub fn default_configuration(sess: &Session) -> ast::CrateConfig {
let end = &sess.target.target.target_endian;
let arch = &sess.target.target.arch;
let wordsz = &sess.target.target.target_pointer_width;
let os = &sess.target.target.target_os;
let env = &sess.target.target.target_env;
let vendor = &sess.target.target.target_vendor;
let max_atomic_width = sess.target.target.max_atomic_width();
let fam = if let Some(ref fam) = sess.target.target.options.target_family {
Symbol::intern(fam)
} else if sess.target.target.options.is_like_windows {
Symbol::intern("windows")
} else {
Symbol::intern("unix")
};
let mut ret = HashSet::new();
// Target bindings.
ret.insert((Symbol::intern("target_os"), Some(Symbol::intern(os))));
ret.insert((Symbol::intern("target_family"), Some(fam)));
ret.insert((Symbol::intern("target_arch"), Some(Symbol::intern(arch))));
ret.insert((Symbol::intern("target_endian"), Some(Symbol::intern(end))));
ret.insert((Symbol::intern("target_pointer_width"), Some(Symbol::intern(wordsz))));
ret.insert((Symbol::intern("target_env"), Some(Symbol::intern(env))));
ret.insert((Symbol::intern("target_vendor"), Some(Symbol::intern(vendor))));
if fam == "windows" || fam == "unix" {
ret.insert((fam, None));
}
if sess.target.target.options.has_elf_tls {
ret.insert((Symbol::intern("target_thread_local"), None));
}
for &i in &[8, 16, 32, 64, 128] {
if i <= max_atomic_width {
let s = i.to_string();
ret.insert((Symbol::intern("target_has_atomic"), Some(Symbol::intern(&s))));
if &s == wordsz {
ret.insert((Symbol::intern("target_has_atomic"), Some(Symbol::intern("ptr"))));
}
}
}
if sess.opts.debug_assertions {
ret.insert((Symbol::intern("debug_assertions"), None));
}
if sess.opts.crate_types.contains(&CrateTypeProcMacro) {
ret.insert((Symbol::intern("proc_macro"), None));
}
return ret;
}
pub fn build_configuration(sess: &Session,
mut user_cfg: ast::CrateConfig)
-> ast::CrateConfig {
// Combine the configuration requested by the session (command line) with
// some default and generated configuration items
let default_cfg = default_configuration(sess);
// If the user wants a test runner, then add the test cfg
if sess.opts.test {
user_cfg.insert((Symbol::intern("test"), None));
}
user_cfg.extend(default_cfg.iter().cloned());
user_cfg
}