This change removes the AbiSet from the AST, converting all usage to have just
one Abi value. The current scheme selects a relevant ABI given a list of ABIs
based on the target architecture and how relevant each ABI is to that
architecture.
Instead of this mildly complicated scheme, only one ABI will be allowed in abi
strings, and pseudo-abis will be created for special cases as necessary. For
example the "system" abi exists for stdcall on win32 and C on win64.
Closes#10049
This commit deals with the fallout of the previous change by making tuples
structs have public fields where necessary (now that the fields are private by
default).
This is a continuation of the work done in #13184 to make struct fields private
by default. This commit finishes RFC 4 by making all tuple structs have private
fields by default. Note that enum variants are not affected.
A tuple struct having a private field means that it cannot be matched on in a
pattern match (both refutable and irrefutable), and it also cannot have a value
specified to be constructed. Similarly to private fields, switching the type of
a private field in a tuple struct should be able to be done in a backwards
compatible way.
The one snag that I ran into which wasn't mentioned in the RFC is that this
commit also forbids taking the value of a tuple struct constructor. For example,
this code now fails to compile:
mod a {
pub struct A(int);
}
let a: fn(int) -> a::A = a::A; //~ ERROR: first field is private
Although no fields are bound in this example, it exposes implementation details
through the type itself. For this reason, taking the value of a struct
constructor with private fields is forbidden (outside the containing module).
RFC: 0004-private-fields
This removes the `attr` matcher and adds a `meta` matcher. The previous `attr`
matcher is now ambiguous because it doesn't disambiguate whether it means inner
attribute or outer attribute.
The new behavior can still be achieved by taking an argument of the form
`#[$foo:meta]` (the brackets are part of the macro pattern).
Closes#13067
Summary:
So far, we've used the term POD "Plain Old Data" to refer to types that
can be safely copied. However, this term is not consistent with the
other built-in bounds that use verbs instead. This patch renames the Pod
kind into Copy.
RFC: 0003-opt-in-builtin-traits
Test Plan: make check
Reviewers: cmr
Differential Revision: http://phabricator.octayn.net/D3
The previous syntax was `Foo:Bound<trait-parameters>`, but this is a little
ambiguous because it was being parsed as `Foo: (Bound<trait-parameters)` rather
than `Foo: (Bound) <trait-parameters>`
This commit changes the syntax to `Foo<trait-parameters>: Bound` in order to be
clear where the trait parameters are going.
Closes#9265
This change prepares `rustc` to accept private fields by default. These changes will have to go through a snapshot before the rest of the changes can happen.
The previous syntax was `Foo:Bound<trait-parameters>`, but this is a little
ambiguous because it was being parsed as `Foo: (Bound<trait-parameters)` rather
than `Foo: (Bound) <trait-parameters>`
This commit changes the syntax to `Foo<trait-parameters>: Bound` in order to be
clear where the trait parameters are going.
Closes#9265
Add some docs to ExpnInfo. Add a single overlooked `new_span` call to the folder (I'm pretty sure nothing reads this span, though, so it's probably pointless).
This change is in preparation for #8122. Nothing is currently done with these
visibility qualifiers, they are just parsed and accepted by the compiler.
RFC: 0004-private-fields
This was leaving Decls without the new spans; this is a minor change,
since literally nothing reads in the code base reads the span of a Decl
itself, always just its contents.
syntax: allow `trace_macros!` and `log_syntax!` in item position.
Previously
trace_macros!(true)
fn main() {}
would complain about `trace_macros` being an expression macro in item
position. This is a pointless limitation, because the macro is purely
compile-time, with no runtime effect. (And similarly for log_syntax.)
This also changes the behaviour of `trace_macros!` very slightly, it
used to be equivalent to
macro_rules! trace_macros {
(true $($_x: tt)*) => { true };
(false $($_x: tt)*) => { false }
}
I.e. you could invoke it with arbitrary trailing arguments, which were
ignored. It is changed to accept only exactly `true` or `false` (with no
trailing arguments) and expands to `()`.
std: remove the `equals` method from `TotalEq`.
`TotalEq` is now just an assertion about the `Eq` impl of a
type (i.e. `==` is a total equality if a type implements `TotalEq`) so
the extra method is just confusing.
Also, a new method magically appeared as a hack to allow deriving to
assert that the contents of a struct/enum are also TotalEq, because the
deriving infrastructure makes it very hard to do anything but create a
trait method. (You didn't hear about this horrible work-around from me
:(.)
`TotalEq` is now just an assertion about the `Eq` impl of a
type (i.e. `==` is a total equality if a type implements `TotalEq`) so
the extra method is just confusing.
Also, a new method magically appeared as a hack to allow deriving to
assert that the contents of a struct/enum are also TotalEq, because the
deriving infrastructure makes it very hard to do anything but create a
trait method. (You didn't hear about this horrible work-around from me
:(.)
Replace syntax::opt_vec with syntax::owned_slice
The `owned_slice::OwnedSlice` is `(*T, uint)` (i.e. a direct equivalent to DSTs `~[T]`).
This shaves two words off the old OptVec type; and also makes substituting in other implementations easy, by removing all the mutation methods. (And also everything that's very rarely/never used.)
This is a stand-in until we have a saner `~[T]` type (i.e. a proper
owned slice). It's a library version of what `~[T]` will be, i.e. an
owned pointer and a length.
Previously
trace_macros!(true)
fn main() {}
would complain about `trace_macros` being an expression macro in item
position. This is a pointless limitation, because the macro is purely
compile-time, with no runtime effect. (And similarly for log_syntax.)
This also changes the behaviour of `trace_macros!` very slightly, it
used to be equivalent to
macro_rules! trace_macros {
(true $($_x: tt)*) => { true };
(false $($_x: tt)*) => { false }
}
I.e. you could invoke it with arbitrary trailing arguments, which were
ignored. It is changed to accept only exactly `true` or `false` (with no
trailing arguments) and expands to `()`.
This is the first step to replacing OptVec with a new representation:
remove all mutability. Any mutations have to go via `Vec` and then make
to `OptVec`.
Many of the uses of OptVec are unnecessary now that Vec has no-alloc
emptiness (and have been converted to Vec): the only ones that really
need it are the AST and sty's (and so on) where there are a *lot* of
instances of them, and they're (mostly) immutable.
`Share` implies that all *reachable* content is *threadsafe*.
Threadsafe is defined as "exposing no operation that permits a data race if multiple threads have access to a &T pointer simultaneously". (NB: the type system should guarantee that if you have access to memory via a &T pointer, the only other way to gain access to that memory is through another &T pointer)...
Fixes#11781
cc #12577
What this PR will do
================
- [x] Add Share kind and
- [x] Replace usages of Freeze with Share in bounds.
- [x] Add Unsafe<T> #12577
- [x] Forbid taking the address of a immutable static item with `Unsafe<T>` interior
What's left to do in a separate PR (after the snapshot)?
===========================================
- Remove `Freeze` completely
The pretty printer constitues an enormous amount of code, there's no reason for
it to be generic. This just least to a huge amount of metadata which isn't
necessary. Instead, this change migrates the pretty printer to using a trait
object instead.
Closes#12985
This will enable rustdoc to treat them specially.
I also got rid of `std::cmp::cmp2`, which is isomorphic to the `TotalOrd` impl for 2-tuples and never used.
This commit removes all internal support for the previously used __log_level()
expression. The logging subsystem was previously modified to not rely on this
magical expression. This also removes the only other function to use the
module_data map in trans, decl_gc_metadata. It appears that this is an ancient
function from a GC only used long ago.
This does not remove the crate map entirely, as libgreen still uses it to hook
in to the event loop provided by libgreen.
This commit moves all logging out of the standard library into an external
crate. This crate is the new crate which is responsible for all logging macros
and logging implementation. A few reasons for this change are:
* The crate map has always been a bit of a code smell among rust programs. It
has difficulty being loaded on almost all platforms, and it's used almost
exclusively for logging and only logging. Removing the crate map is one of the
end goals of this movement.
* The compiler has a fair bit of special support for logging. It has the
__log_level() expression as well as generating a global word per module
specifying the log level. This is unfairly favoring the built-in logging
system, and is much better done purely in libraries instead of the compiler
itself.
* Initialization of logging is much easier to do if there is no reliance on a
magical crate map being available to set module log levels.
* If the logging library can be written outside of the standard library, there's
no reason that it shouldn't be. It's likely that we're not going to build the
highest quality logging library of all time, so third-party libraries should
be able to provide just as high-quality logging systems as the default one
provided in the rust distribution.
With a migration such as this, the change does not come for free. There are some
subtle changes in the behavior of liblog vs the previous logging macros:
* The core change of this migration is that there is no longer a physical
log-level per module. This concept is still emulated (it is quite useful), but
there is now only a global log level, not a local one. This global log level
is a reflection of the maximum of all log levels specified. The previously
generated logging code looked like:
if specified_level <= __module_log_level() {
println!(...)
}
The newly generated code looks like:
if specified_level <= ::log::LOG_LEVEL {
if ::log::module_enabled(module_path!()) {
println!(...)
}
}
Notably, the first layer of checking is still intended to be "super fast" in
that it's just a load of a global word and a compare. The second layer of
checking is executed to determine if the current module does indeed have
logging turned on.
This means that if any module has a debug log level turned on, all modules
with debug log levels get a little bit slower (they all do more expensive
dynamic checks to determine if they're turned on or not).
Semantically, this migration brings no change in this respect, but
runtime-wise, this will have a perf impact on some code.
* A `RUST_LOG=::help` directive will no longer print out a list of all modules
that can be logged. This is because the crate map will no longer specify the
log levels of all modules, so the list of modules is not known. Additionally,
warnings can no longer be provided if a malformed logging directive was
supplied.
The new "hello world" for logging looks like:
#[phase(syntax, link)]
extern crate log;
fn main() {
debug!("Hello, world!");
}
This commit shreds all remnants of libextra from the compiler and standard
distribution. Two modules, c_vec/tempfile, were moved into libstd after some
cleanup, and the other modules were moved to separate crates as seen fit.
Closes#8784Closes#12413Closes#12576
This commit shreds all remnants of libextra from the compiler and standard
distribution. Two modules, c_vec/tempfile, were moved into libstd after some
cleanup, and the other modules were moved to separate crates as seen fit.
Closes#8784Closes#12413Closes#12576
Previously, the cfg attribute `cfg(not(a, b))` was translated to `(!a && !b)`,
but this isn't very useful because that can already be expressed as
`cfg(not(a), not(b))`. This commit changes the translation to `!(a && b)` which
is more symmetrical of the rest of the `cfg` attribute.
Put another way, I would expect `cfg(clause)` to be the opposite of
`cfg(not(clause))`, but this is not currently the case with multiple element
clauses.
# Summary
This patch introduces the `_` token into the type grammar, with the meaning "infer this type".
With this change, the following two lines become equivalent:
```
let x = foo();
let x: _ = foo();
```
But due to its composability, it enables partial type hints like this:
```
let x: Bar<_> = baz();
```
Using it on the item level is explicitly forbidden, as the Rust language does not enable global type inference by design.
This implements the feature requested in https://github.com/mozilla/rust/issues/9508.
# Things requiring clarification
- The change to enable it is very small, but I have only limited understanding of the related code, so the approach here might be wrong.
- In particular, while this patch works, it does so in a way not originally intended according to the code comments.
- This probably needs more tests, or rather feedback for which tests are still missing.
- I'm unsure how this interacts with lifetime parameters, and whether it is correct in regard to them.
- Partial type hints on the right side of `as` like `&foo as *_` work in both a normal function contexts and in constexprs like `static foo: *int = &'static 123 as *_`. The question is whether this should be allowed in general.
# Todo for this PR
- The manual and tutorial still needs updating.
# Bugs I'm unsure how to fix
- Requesting inference for the top level of the right hand side of a `as` fails to infer correctly, even if all possible hints are given:
```
.../type_hole_1.rs:35:18: 35:22 error: the type of this value must be known in this context
.../type_hole_1.rs:35 let a: int = 1u32 as _;
^~~~
```
rustc: make stack traces print for .span_bug/.bug.
Previously a call to either of those to diagnostic printers would defer
to the `fatal` equivalents, which explicitly silence the stderr
printing, including a stack trace from `RUST_LOG=std::rt::backtrace`.
This splits the bug printers out to their own diagnostic type so that
things work properly.
Also, this removes the `Ok(...)` that was being printed around the
subtask's stderr output.
lint: add lint for use of a `~[T]`.
This is useless at the moment (since pretty much every crate uses
`~[]`), but should help avoid regressions once completely removed from a
crate.
## read+write modifier '+'
This small sugar was left out in the original implementation (#5359).
When an output operand with the '+' modifier is encountered, we store the index of that operand alongside the expression to create and append an input operand later. The following lines are equivalent:
```
asm!("" : "+m"(expr));
asm!("" : "=m"(expr) : "0"(expr));
```
## misplaced options and clobbers give a warning
It's really annoying when a small typo might change behavior without any warning.
```
asm!("mov $1, $0" : "=r"(x) : "r"(8u) : "cc" , "volatile");
//~^ WARNING expected a clobber, but found an option
```
## liveness
Fixed incorrect order of propagation.
Sometimes it caused spurious warnings in code: `warning: value assigned to `i` is never read, #[warn(dead_assignment)] on by default`
~~Note: Rebased on top of another PR. (uses other changes)~~
* [x] Implement read+write
* [x] Warn about misplaced options
* [x] Fix liveness (`dead_assignment` lint)
* [x] Add all tests
Previously a call to either of those to diagnostic printers would defer
to the `fatal` equivalents, which explicitly silence the stderr
printing, including a stack trace from `RUST_LOG=std::rt::backtrace`.
This splits the bug printers out to their own diagnostic type so that
things work properly.
Also, this removes the `Ok(...)` that was being printed around the
subtask's stderr output.
For the following code snippet:
```rust
struct Foo { bar: int }
fn foo1(x: &Foo) -> &int {
&x.bar
}
```
This PR generates the following error message:
```rust
test.rs:2:1: 4:2 note: consider using an explicit lifetime parameter as shown: fn foo1<'a>(x: &'a Foo) -> &'a int
test.rs:2 fn foo1(x: &Foo) -> &int {
test.rs:3 &x.bar
test.rs:4 }
test.rs:3:5: 3:11 error: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
test.rs:3 &x.bar
^~~~~~
```
Currently it does not support methods.
The `~str` type is not long for this world as it will be superseded by the
soon-to-come DST changes for the language. The new type will be
`~Str`, and matching over the allocation will no longer be supported.
Matching on `&str` will continue to work, in both a pre and post DST world.
Some types of error are caused by missing lifetime parameter on function
or method declaration. In such cases, this commit generates some
suggestion about what the function declaration could be. This does not
support method declaration yet.
There is a broader revision (that does this across the board) pending
in #12675, but that is awaiting the arrival of more data (to decide
whether to keep OptVec alive by using a non-Vec internally).
For this code, the representation of lifetime lists needs to be the
same in both ScopeChain and in the ast and ty structures. So it
seemed cleanest to just use `vec_ng::Vec`, now that it has a cheaper
empty representation than the current `vec` code.
This is needed to make progress on #10296 as the default bounds will no longer
include Send. I believe that this was the originally intended syntax for procs,
and it just hasn't been necessary up until now.
This is needed to make progress on #10296 as the default bounds will no longer
include Send. I believe that this was the originally intended syntax for procs,
and it just hasn't been necessary up until now.
This should be called far less than it is because it does expensive OS
interactions and seeding of the internal RNG, `task_rng` amortises this
cost. The main problem is the name is so short and suggestive.
The direct equivalent is `StdRng::new`, which does precisely the same
thing.
The deprecation will make migrating away from the function easier.
This functionality is not super-core and so doesn't need to be included
in std. It's possible that std may need rand (it does a little bit now,
for io::test) in which case the functionality required could be moved to
a secret hidden module and reexposed by librand.
Unfortunately, using #[deprecated] here is hard: there's too much to
mock to make it feasible, since we have to ensure that programs still
typecheck to reach the linting phase.
Where ItemDecorator creates new items given a single item, ItemModifier
alters the tagged item in place. The expansion rules for this are a bit
weird, but I think are the most reasonable option available.
When an item is expanded, all ItemModifier attributes are stripped from
it and the item is folded through all ItemModifiers. At that point, the
process repeats until there are no ItemModifiers in the new item.
CodeMap.span_to_* perform a lookup of a BytePos(sp.hi), which lands into the next filemap if the last byte of range denoted by Span is also the last byte of the filemap, which results in ICEs or incorrect error reports.
Example:
````
pub fn main() {
let mut num = 3;
let refe = &mut num;
*refe = 5;
println!("{}", num);
}````
(note the empty line in the beginning and the absence of newline at the end)
The above would have caused ICE when trying to report where "refe" borrow ends.
The above without an empty line in the beginning would have reported borrow end to be the first line.
Most probably, this is also responsible for (at least some occurrences of) issue #8256.
The issue is fixed by always adding a newline at the end of non-empty filemaps in case there isn't a new line there already.
* `Ord` inherits from `Eq`
* `TotalOrd` inherits from `TotalEq`
* `TotalOrd` inherits from `Ord`
* `TotalEq` inherits from `Eq`
This is a partial implementation of #12517.
If #[feature(default_type_parameters)] is enabled for a crate, then
deriving(Hash) will expand with Hash<W: Writer> instead of Hash<SipState> so
more hash algorithms can be used.
This leverages the new hashing framework and hashmap implementation to provide a
much speedier hashing algorithm for node ids and def ids. The hash algorithm
used is currentl FNV hashing, but it's quite easy to swap out.
I originally implemented hashing as the identity function, but this actually
ended up in slowing down rustc compiling libstd from 8s to 13s. I would suspect
that this is a result of a large number of collisions.
With FNV hashing, we get these timings (compiling with --no-trans, in seconds):
| | before | after |
|-----------|---------:|--------:|
| libstd | 8.324 | 6.703 |
| stdtest | 47.674 | 46.857 |
| libsyntax | 9.918 | 8.400 |
I added a new lint for variables whose names contain uppercase characters, since, by convention, variable names should be all lowercase. What motivated me to work on this was when I ran into something like the following:
```rust
use std::io::File;
use std::io::IoError;
fn main() {
let mut f = File::open(&Path::new("/something.txt"));
let mut buff = [0u8, ..16];
match f.read(buff) {
Ok(cnt) => println!("read this many bytes: {}", cnt),
Err(IoError{ kind: EndOfFile, .. }) => println!("Got end of file: {}", EndOfFile.to_str()),
}
}
```
I then got compile errors when I tried to add a wildcard match pattern at the end which I found very confusing since I believed that the 2nd match arm was only matching the EndOfFile condition. The problem is that I hadn't imported io::EndOfFile into the local scope. So, I thought that I was using EndOfFile as a sub-pattern, however, what I was actually doing was creating a new local variable named EndOfFile. This lint makes this error easier to spot by providing a warning that the variable name EndOfFile contains a uppercase characters which provides a nice hint as to why the code isn't doing what is intended.
The lint warns on local bindings as well:
```rust
let Hi = 0;
```
And also struct fields:
```rust
struct Something {
X: uint
}
```
Previously `ast::Arm` was always storing a single `ast::Expr` wrapped in an
`ast::Block` (for historical reasons, AIUI), so we might as just store
that expr directly.
Closes#3085.
A couple of syntax extensions manually expanded expressions, but it
wasn't done universally, most noticably inside of asm!().
There's also a bit of random cleanup.
Similarly to #12422 which made stdin buffered by default, this commit makes the
output streams also buffered by default. Now that buffered writers will flush
their contents when they are dropped, I don't believe that there's no reason why
the output shouldn't be buffered by default, which is what you want in 90% of
cases.
As with stdin, there are new stdout_raw() and stderr_raw() functions to get
unbuffered streams to stdout/stderr.
Formatting via reflection has been a little questionable for some time now, and
it's a little unfortunate that one of the standard macros will silently use
reflection when you weren't expecting it. This adds small bits of code bloat to
libraries, as well as not always being necessary. In light of this information,
this commit switches assert_eq!() to using {} in the error message instead of
{:?}.
In updating existing code, there were a few error cases that I encountered:
* It's impossible to define Show for [T, ..N]. I think DST will alleviate this
because we can define Show for [T].
* A few types here and there just needed a #[deriving(Show)]
* Type parameters needed a Show bound, I often moved this to `assert!(a == b)`
* `Path` doesn't implement `Show`, so assert_eq!() cannot be used on two paths.
I don't think this is much of a regression though because {:?} on paths looks
awful (it's a byte array).
Concretely speaking, this shaved 10K off a 656K binary. Not a lot, but sometime
significant for smaller binaries.
This helps prevent interleaving of error messages when running rustdoc tests.
This has an interesting bit of shuffling with I/O handles, but other than that
this is just using the APIs laid out in the previous commit.
Closes#12623
This commit alters the diagnostic emission machinery to be focused around a
Writer for emitting errors. This allows it to not hard-code emission of errors
to stderr (useful for other applications).
Previously, format!("{a}{b}", a=foo(), b=bar()) has foo() and bar() run in a
nondeterminisc order. This is clearly a non-desirable property, so this commit
uses iteration over a list instead of iteration over a hash map to provide
deterministic code generation of these format arguments.
The previous code passed around a {name,version} pair everywhere, but this is
better expressed as a CrateId. This patch changes these paths to store and pass
around crate ids instead of these pairs of name/version. This also prepares the
code to change the type of hash that is stored in crates.
There's a lot of these types in the compiler libraries, and a few of the
older or private stdlib ones. Some types are obviously meant to be
public, others not so much.
These are types that are in exported type signatures, but are not
exported themselves, e.g.
struct Foo { ... }
pub fn bar() -> Foo { ... }
will warn about the Foo.
Such types are not listed in documentation, and cannot be named outside
the crate in which they are declared, which is very user-unfriendly.
cc #10573
Make bytepos_to_charpos relative to the start of the filemap rather than its previous behaviour which was to be realtive to the start of the codemap, but ignoring multi-byte chars in earlier filemaps. Rename to bytepos_to_file_charpos. Add tests for multi-byte chars.
The most significant fix is for `syntax::ext::deriving::encodable`,
where one of the blocks of code, auspiciously containing `<S>` (recall
that Markdown allows arbitrary HTML to be contained inside it), was not
formatted as a code block, with a fun but messy effect.
The pretty printer was treating block comments with more than two
asterisks after the first slash (e.g. `/***`) as doc comments (which are
attributes), whereas in actual fact they are just regular comments.
This patch series does a couple things:
* replaces manual `Hash` implementations with `#[deriving(Hash)]`
* adds `Hash` back to `std::prelude`
* minor cleanup of whitespace and variable names.
They are still are not completely correct, since it does not handle
graphemes at all, just codepoints, but at least it handles the common
case correctly.
The calculation was previously very wrong (rather than just a little bit
wrong): it wasn't accounting for the fact that every character is 1
byte, and so multibyte characters were pretending to be zero width.
cc #8706
file.
Previously multibyte UTF-8 chars were being recorded as byte offsets
from the start of the file, and then later compared against global byte
positions, resulting in the compiler possibly thinking it had a byte
position pointing inside a multibyte character, if there were multibyte
characters in any non-crate files. (Although, sometimes the byte offsets
line up just right to not ICE, but that was a coincidence.)
Fixes#11136.
Fixes#11178.
This commit removes deriving(ToStr) in favor of deriving(Show), migrating all impls of ToStr to fmt::Show.
Most of the details can be found in the first commit message.
Closes#12477