Skip to content

Commit

Permalink
Merge branch 'rust-lang:master' into spec-type-layout-improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
chorman0773 authored Oct 17, 2024
2 parents cd8bf7b + bff8721 commit 0060118
Show file tree
Hide file tree
Showing 49 changed files with 984 additions and 77 deletions.
29 changes: 29 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,34 @@ jobs:
working-directory: ./mdbook-spec
run: cargo fmt --check

preview:
if: github.event_name == 'pull_request'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
- name: Update rustup
run: rustup self update
- name: Install Rust
run: |
rustup set profile minimal
rustup toolchain install nightly
rustup default nightly
- name: Install mdbook
run: |
mkdir bin
curl -sSL https://github.com/rust-lang/mdBook/releases/download/v${MDBOOK_VERSION}/mdbook-v${MDBOOK_VERSION}-x86_64-unknown-linux-gnu.tar.gz | tar -xz --directory=bin
echo "$(pwd)/bin" >> $GITHUB_PATH
- name: Build the book
env:
SPEC_RELATIVE: 0
run: mdbook build --dest-dir dist/preview-${{ github.event.pull_request.number }}
- name: Upload artifact
uses: actions/upload-artifact@v4
with:
name: preview-${{ github.event.pull_request.number }}
overwrite: true
path: dist

# The success job is here to consolidate the total success/failure state of
# all other jobs. This job is then included in the GitHub branch protection
# rule which prevents merges unless all other jobs are passing. This makes
Expand All @@ -110,6 +138,7 @@ jobs:
- code-tests
- style-tests
- mdbook-spec
# preview is explicitly excluded here since it doesn't run on merge
runs-on: ubuntu-latest
steps:
- run: jq --exit-status 'all(.result == "success")' <<< '${{ toJson(needs) }}'
Expand Down
26 changes: 25 additions & 1 deletion docs/authoring.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ This document serves as a guide for editors and reviewers. Some conventions and
* Code blocks should have an explicit language tag.
* Do not wrap long lines. This helps with reviewing diffs of the source.
* Use [smart punctuation] instead of Unicode characters. For example, use `---` for em-dash instead of the Unicode character. Characters like em-dash can be difficult to see in a fixed-width editor, and some editors may not have easy methods to enter such characters.
* Links should be relative with the `.md` extension. Links to other rust-lang books that are published with the reference or the standard library API should also be relative so that the linkchecker can validate them.
* Links should be relative with the `.md` extension. Links to other rust-lang books that are published with the reference should also be relative so that the linkchecker can validate them.
* Links to the standard library should use rustdoc-style links described in [Standard library links](#standard-library-links).
* The use of reference links is preferred, with shortcuts if appropriate. Place the sorted link reference definitions at the bottom of the file, or at the bottom of a section if there are an unusually large number of links that are specific to the section.

```markdown
Expand Down Expand Up @@ -75,6 +76,29 @@ Rules can be linked to by their ID using markdown such as `[foo.bar]`. There are

In the HTML, the rules are clickable just like headers.

When assigning rules to new paragraphs, or when modifying rule names, use the following guidelines:

1. A rule applies to one core idea, which should be easily determined when reading the paragraph it is applied to.
2. Other than the "intro" paragraph, purely explanatory, expository, or exemplary content does not need a rule. If the expository paragraph isn't directly related to the previous, separate it with a hard (rendered) line break.
* This content will be moved to `[!NOTE]` or more specific admonitions in the future.
3. Rust code examples and tests do not need their own rules.
4. Use the following guidelines for admonitions:
* Notes: Do not include a rule.
* Warning: Omit the rule if the warning follows from the previous paragraph or if the warning is explanatory and doesn't introduce any new rules.
* Target specific behavior: Always include the rule.
* Edition differences: Always include the rule.
5. The following keywords should be used to identify paragraphs when unambiguous:
* `intro`: The beginning paragraph of each section - should explain the construct being defined overall.
* `syntax`: Syntax definitions or explanations when BNF syntax definitions are not used.
* `namespace`: For items only, specifies the namespace(s) the item introduces a name in. May also be used elsewhere when defining a namespace (e.g. `r[attribute.diagnostic.namespace]`).
6. When a rule doesn't fall under the above keywords, or for section rule ids, name the subrule as follows:
* If the rule is naming a specific Rust language construct (e.g. an attribute, standard library type/function, or keyword-introduced concept), use the construct as named in the language, appropriately case-adjusted (but do not replace `_`s with `-`s).
* Other than Rust language concepts with `_`s in the name, use `-` characters to separate words within a "subrule".
* Whenever possible, do not repeat previous components of the rule.
* Edition differences admonitions should typically be named by the edition referenced directly by the rule. If multiple editions are named, use the one for which the behavior is defined by the admonition, and not by a previous paragraph.
* Target specific admonitions should typically be named by the least specific target property to which they apply (e.g. if a rule affects all x86 CPUs, the rule name should include `x86` rather than separately listing `i586`, `i686` and `x86_64`, and if a rule applies to all ELF platforms, it should be named `elf` rather than listing every ELF OS).
* Use an appropriately descriptive, but short, name if the language does not provide one.

### Standard library links

You should link to the standard library without specifying a URL in a fashion similar to [rustdoc intra-doc links][intra]. Some examples:
Expand Down
33 changes: 28 additions & 5 deletions src/attributes/type_system.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,12 +163,35 @@ match message {
}
```

It's also not allowed to cast non-exhaustive types from foreign crates.
```rust, ignore
use othercrate::NonExhaustiveEnum;
It's also not allowed to use numeric casts (`as`) on enums that contain any non-exhaustive variants.

For example, the following enum can be cast because it doesn't contain any non-exhaustive variants:

```rust
#[non_exhaustive]
pub enum Example {
First,
Second
}
```

However, if the enum contains even a single non-exhaustive variant, casting will result in an error. Consider this modified version of the same enum:

```rust
#[non_exhaustive]
pub enum EnumWithNonExhaustiveVariants {
First,
#[non_exhaustive]
Second
}
```

<!-- ignore: needs multiple crates -->
```rust,ignore
use othercrate::EnumWithNonExhaustiveVariants;
// Cannot cast a non-exhaustive enum outside of its defining crate.
let _ = NonExhaustiveEnum::default() as u8;
// Error: cannot cast an enum with a non-exhaustive variant when it's defined in another crate
let _ = EnumWithNonExhaustiveVariants::First as u8;
```

Non-exhaustive types are always considered inhabited in downstream crates.
Expand Down
6 changes: 4 additions & 2 deletions src/behavior-considered-undefined.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ undefined behavior, it is *unsound*.
All this also applies when values of these
types are passed in a (nested) field of a compound type, but not behind
pointer indirections.
* Mutating immutable bytes. All bytes inside a [`const`] item or within an implicitly [const-promoted] expression are immutable.
* Mutating immutable bytes.
All bytes reachable through a [const-promoted] expression are immutable, as well as bytes reachable through borrows in `static` and `const` initializers that have been [lifetime-extended] to `'static`.
The bytes owned by an immutable binding or immutable `static` are immutable, unless those bytes are part of an [`UnsafeCell<U>`].

Moreover, the bytes [pointed to] by a shared reference, including transitively through other references (both shared and mutable) and `Box`es, are immutable; transitivity includes those references stored in fields of compound types.
Expand Down Expand Up @@ -78,7 +79,7 @@ The span of bytes a pointer or reference "points to" is determined by the pointe
A place is said to be "based on a misaligned pointer" if the last `*` projection
during place computation was performed on a pointer that was not aligned for its
type. (If there is no `*` projection in the place expression, then this is
accessing the field of a local and rustc will guarantee proper alignment. If
accessing the field of a local or `static` and rustc will guarantee proper alignment. If
there are multiple `*` projection, then each of them incurs a load of the
pointer-to-be-dereferenced itself from memory, and each of these loads is
subject to the alignment constraint. Note that some `*` projections can be
Expand Down Expand Up @@ -179,3 +180,4 @@ reading uninitialized memory is permitted are inside `union`s and in "padding"
[project-tuple]: expressions/tuple-expr.md#tuple-indexing-expressions
[project-slice]: expressions/array-expr.md#array-and-slice-indexing-expressions
[const-promoted]: destructors.md#constant-promotion
[lifetime-extended]: destructors.md#temporary-lifetime-extension
29 changes: 26 additions & 3 deletions src/comments.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# Comments

r[comments.syntax]

> **<sup>Lexer</sup>**\
> LINE_COMMENT :\
> &nbsp;&nbsp; &nbsp;&nbsp; `//` (~\[`/` `!` `\n`] | `//`) ~`\n`<sup>\*</sup>\
Expand Down Expand Up @@ -34,27 +36,48 @@
## Non-doc comments

r[comments.normal]

Comments follow the general C++ style of line (`//`) and
block (`/* ... */`) comment forms. Nested block comments are supported.

r[comments.normal.tokenization]
Non-doc comments are interpreted as a form of whitespace.

## Doc comments

r[comments.doc]

r[comments.doc.syntax]
Line doc comments beginning with exactly _three_ slashes (`///`), and block
doc comments (`/** ... */`), both outer doc comments, are interpreted as a
special syntax for [`doc` attributes]. That is, they are equivalent to writing
special syntax for [`doc` attributes].

r[comments.doc.attributes]
That is, they are equivalent to writing
`#[doc="..."]` around the body of the comment, i.e., `/// Foo` turns into
`#[doc="Foo"]` and `/** Bar */` turns into `#[doc="Bar"]`.
`#[doc="Foo"]` and `/** Bar */` turns into `#[doc="Bar"]`. They must therefore
appear before something that accepts an outer attribute.

r[comments.doc.inner-syntax]
Line comments beginning with `//!` and block comments `/*! ... */` are
doc comments that apply to the parent of the comment, rather than the item
that follows. That is, they are equivalent to writing `#![doc="..."]` around
that follows.

r[comments.doc.inner-attributes]
That is, they are equivalent to writing `#![doc="..."]` around
the body of the comment. `//!` comments are usually used to document
modules that occupy a source file.

r[comments.doc.bare-crs]
The character `U+000D` (CR) is not allowed in doc comments.

> **Note**: It is conventional for doc comments to contain Markdown, as expected by
> `rustdoc`. However, the comment syntax does not respect any internal Markdown.
> ``/** `glob = "*/*.rs";` */`` terminates the comment at the first `*/`, and the
> remaining code would cause a syntax error. This slightly limits the content of
> block doc comments compared to line doc comments.
> **Note**: The sequence `U+000D` (CR) immediately followed by `U+000A` (LF) would have been previously transformed into a single `U+000A` (LF).
## Examples
Expand Down
8 changes: 6 additions & 2 deletions src/const_eval.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,11 @@ to be run.
* [Closure expressions] which don't capture variables from the environment.
* Built-in [negation], [arithmetic], [logical], [comparison] or [lazy boolean]
operators used on integer and floating point types, `bool`, and `char`.
* Shared [borrow]s, except if applied to a type with [interior mutability].
* The [dereference operator] except for raw pointers.
* All forms of [borrow]s, including raw borrows, with one limitation:
mutable borrows and shared borrows to values with interior mutability
are only allowed to refer to *transient* places. A place is *transient*
if its lifetime is strictly contained inside the current [const context].
* The [dereference operator].
* [Grouped] expressions.
* [Cast] expressions, except
* pointer to address casts and
Expand All @@ -49,6 +52,7 @@ to be run.
* [if], [`if let`] and [match] expressions.

## Const context
[const context]: #const-context

A _const context_ is one of the following:

Expand Down
12 changes: 12 additions & 0 deletions src/destructors.md
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,18 @@ let x = &mut 0;
println!("{}", x);
```

r[destructors.scope.lifetime-extension.static]
Lifetime extension also applies to `static` and `const` items, where it
makes temporaries live until the end of the program. For example:

```rust
const C: &Vec<i32> = &Vec::new();
// Usually this would be a dangling reference as the `Vec` would only
// exist inside the initializer expression of `C`, but instead the
// borrow gets lifetime-extended so it effectively has `'static` lifetime.
println!("{:?}", C);
```

r[destructors.scope.lifetime-extension.sub-expressions]
If a [borrow][borrow expression], [dereference][dereference expression],
[field][field expression], or [tuple indexing expression] has an extended
Expand Down
2 changes: 1 addition & 1 deletion src/inline-assembly.md
Original file line number Diff line number Diff line change
Expand Up @@ -484,7 +484,7 @@ The following ABIs can be used with `clobber_abi`:
| AArch64 | `"C"`, `"system"`, `"efiapi"` | `x[0-17]`, `x18`\*, `x30`, `v[0-31]`, `p[0-15]`, `ffr` |
| ARM | `"C"`, `"system"`, `"efiapi"`, `"aapcs"` | `r[0-3]`, `r12`, `r14`, `s[0-15]`, `d[0-7]`, `d[16-31]` |
| RISC-V | `"C"`, `"system"`, `"efiapi"` | `x1`, `x[5-7]`, `x[10-17]`, `x[28-31]`, `f[0-7]`, `f[10-17]`, `f[28-31]`, `v[0-31]` |
| LoongArch | `"C"`, `"system"`, `"efiapi"` | `$r1`, `$r[4-20]`, `$f[0-23]` |
| LoongArch | `"C"`, `"system"` | `$r1`, `$r[4-20]`, `$f[0-23]` |

> Notes:
> - On AArch64 `x18` only included in the clobber list if it is not considered as a reserved register on the target.
Expand Down
19 changes: 18 additions & 1 deletion src/input-format.md
Original file line number Diff line number Diff line change
@@ -1,26 +1,41 @@
# Input format

r[input]

r[input.intro]
This chapter describes how a source file is interpreted as a sequence of tokens.

See [Crates and source files] for a description of how programs are organised into files.

## Source encoding

r[input.encoding]

r[input.encoding.utf8]
Each source file is interpreted as a sequence of Unicode characters encoded in UTF-8.

r[input.encoding.invalid]
It is an error if the file is not valid UTF-8.

## Byte order mark removal

r[input.byte-order-mark]

If the first character in the sequence is `U+FEFF` ([BYTE ORDER MARK]), it is removed.

## CRLF normalization

r[input.crlf]

Each pair of characters `U+000D` (CR) immediately followed by `U+000A` (LF) is replaced by a single `U+000A` (LF).

Other occurrences of the character `U+000D` (CR) are left in place (they are treated as [whitespace]).

## Shebang removal

r[input.shebang]

r[input.shebang.intro]
If the remaining sequence begins with the characters `#!`, the characters up to and including the first `U+000A` (LF) are removed from the sequence.

For example, the first line of the following file would be ignored:
Expand All @@ -34,15 +49,17 @@ fn main() {
}
```

r[input.shebang.inner-attribute]
As an exception, if the `#!` characters are followed (ignoring intervening [comments] or [whitespace]) by a `[` token, nothing is removed.
This prevents an [inner attribute] at the start of a source file being removed.

> **Note**: The standard library [`include!`] macro applies byte order mark removal, CRLF normalization, and shebang removal to the file it reads. The [`include_str!`] and [`include_bytes!`] macros do not.
## Tokenization

The resulting sequence of characters is then converted into tokens as described in the remainder of this chapter.
r[input.tokenization]

The resulting sequence of characters is then converted into tokens as described in the remainder of this chapter.

[inner attribute]: attributes.md
[BYTE ORDER MARK]: https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8
Expand Down
32 changes: 24 additions & 8 deletions src/interior-mutability.md
Original file line number Diff line number Diff line change
@@ -1,22 +1,38 @@
# Interior Mutability

r[interior-mut]

r[interior-mut.intro]
Sometimes a type needs to be mutated while having multiple aliases. In Rust this
is achieved using a pattern called _interior mutability_. A type has interior
mutability if its internal state can be changed through a [shared reference] to
it. This goes against the usual [requirement][ub] that the value pointed to by a
is achieved using a pattern called _interior mutability_.

r[interior-mut.shared-ref]
A type has interior mutability if its internal state can be changed through a [shared reference] to
it.

r[interior-mut.no-constraint]
This goes against the usual [requirement][ub] that the value pointed to by a
shared reference is not mutated.

r[interior-mut.unsafe-cell]
[`std::cell::UnsafeCell<T>`] type is the only allowed way to disable
this requirement. When `UnsafeCell<T>` is immutably aliased, it is still safe to
mutate, or obtain a mutable reference to, the `T` it contains. As with all
other types, it is undefined behavior to have multiple `&mut UnsafeCell<T>`
mutate, or obtain a mutable reference to, the `T` it contains.

r[interior-mut.mut-unsafe-cell]
As with all other types, it is undefined behavior to have multiple `&mut UnsafeCell<T>`
aliases.

r[interior-mut.abstraction]
Other types with interior mutability can be created by using `UnsafeCell<T>` as
a field. The standard library provides a variety of types that provide safe
interior mutability APIs. For example, [`std::cell::RefCell<T>`] uses run-time
borrow checks to ensure the usual rules around multiple references. The
[`std::sync::atomic`] module contains types that wrap a value that is only
interior mutability APIs.

r[interior-mut.ref-cell]
For example, [`std::cell::RefCell<T>`] uses run-time borrow checks to ensure the usual rules around multiple references.

r[interior-mut.atomic]
The [`std::sync::atomic`] module contains types that wrap a value that is only
accessed with atomic operations, allowing the value to be shared and mutated
across threads.

Expand Down
12 changes: 6 additions & 6 deletions src/items/constant-items.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,12 @@ guaranteed to refer to the same memory address.
The constant declaration defines the constant value in the [value namespace] of the module or block where it is located.

Constants must be explicitly typed. The type must have a `'static` lifetime: any
references in the initializer must have `'static` lifetimes.
references in the initializer must have `'static` lifetimes. References
in the type of a constant default to `'static` lifetime; see [static lifetime
elision].

Constants may refer to the address of other constants, in which case the
address will have elided lifetimes where applicable, otherwise -- in most cases
-- defaulting to the `static` lifetime. (See [static lifetime
elision].) The compiler is, however, still at liberty to translate the constant
many times, so the address referred to may not be stable.
A reference to a constant will have `'static` lifetime if the constant value is eligible for
[promotion]; otherwise, a temporary will be created.

```rust
const BIT1: u32 = 1 << 0;
Expand Down Expand Up @@ -118,3 +117,4 @@ fn unused_generic_function<T>() {
[_Expression_]: ../expressions.md
[`Copy`]: ../special-types-and-traits.md#copy
[value namespace]: ../names/namespaces.md
[promotion]: ../destructors.md#constant-promotion
2 changes: 1 addition & 1 deletion src/items/functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ Functions qualified with the `const` keyword are [const functions], as are
[tuple struct] and [tuple variant] constructors. _Const functions_ can be
called from within [const contexts].

Const functions may use the [`extern`] function qualifier, but only with the `"Rust"` and `"C"` ABIs.
Const functions may use the [`extern`] function qualifier.

Const functions are not allowed to be [async](#async-functions).

Expand Down
Loading

0 comments on commit 0060118

Please sign in to comment.