The Rust Reference

Overview

The Rust Language Reference

This document is the primary reference for the Rust programming language.

This document is not normative. It may include details that are specific to rustc itself, and should not be taken as a specification for the Rust language. We intend to produce such a document someday, but this is what we have for now.

Dependencies

  • rustc (the Rust compiler).
  • mdbook (use cargo install mdbook to install it).
  • rust nightly (you would be required to set your Rust version to the nightly version to make sure all tests pass)

Build steps

To build the project, follow the steps given below :

Clone the project by downloading the ZIP from the GitHub page or run the following command:

git clone https://github.com/rust-lang/reference

Change the directory to the downloaded repository:

cd reference

To run the tests, you would need to set the Rust version to the nightly release. You can do this by executing the following command:

rustup override set nightly

This will set the nightly version only for your the current project.

If you wish to set Rust nightly for all your projects, you can run the command:

rustup default nightly

Now, run the following command to test the code snippets to catch compilation errors:

mdbook test

To generate a local instance of the book, run:

mdbook build

The generated HTML will be in the book folder.

Comments
  • Document all features

    Document all features

    Overview

    Tracking issue for RFC #1636. Let's make the reference a reliable resource for all Rustaceans! :tada: This might seem intimidating, but the reality is that if we just chip away at it together, we'll be done in no time!

    I'm going to be updating this parent issue with a master list of items that need to be documented in the reference as I find them. Quoting the RFC text:

    Updating the reference should proceed stepwise:

    1. Begin by adding an appendix in the reference with links to all accepted RFCs which have been implemented but are not yet referenced in the documentation.
    2. As the reference material is written for each of those RFC features, remove it from that appendix.

    Note that step 1 should be fairly straightforward; the main issue will be assembling the list of accepted-and-implemented-but-undocumented RFCs. (Also, any RFCs accepted before RFC 1636 but not yet stabilized should presumably be documented under the rules it establishes, but if I'm wrong about that, someone should let me know and I'll include them as well.)

    Also, a pre-emptive apology for the scale of this issue description. We have let things get into a rough spot. (I plan to create documentation issues for each of the required items below once this list is completed, so this thread doesn't become completely unmanageable.)

    Status: Last updated May 13, 2017, now processing a copy of @Eh2406's wonderful gist based on @matthewjasper's fork here.

    "How Can I Help?"

    For right now, since you can't submit updates to the issue directly, there are two major ways you can help:

    1. Write documentation. For the RFCs already triaged and filed under the major section C. Documentation Needed and specifically the subsection 2. Write reference material for undocumented, implemented, stabilized RFC features below, you can open a pull request and reference this issue in its description. I'll keep an eye out for inbound links here and add those links to the relevant items, and once they're merged, we'll mark that item as done.

    2. Triage issues. Work the gist where I'm tracking the triaged-state, specifically looking at the Not Reviewed at All and Stabilized, Not Reviewed sections and evaluating whether they're documented or not. You can fork the gist and I will keep an eye out, checking roughly daily, for any changes to merge back into that document. (Do take a look at what others may have forked it so you don't duplicate work needlessly!) I'll then pull those over into this master issue.

      When working through those, if you determine that they're already documented, please leave a note (and link!) on your copy of the gist as to where so I can link it in this document. That dramatically decreases the time it takes me to confirm it—I double-check all of these.

    A. Tracking

    (This section will go away entirely once all of the RFCs have been flagged for documenting or marked documentation-not-needed here.)

    RFCs reviewed

    Currently: 115/301

    • 0001-private-fields.md
    • 0002-rfc-process.md
    • 0003-attribute-usage.md
    • 0008-new-intrinsics.md
    • 0016-more-attributes.md
    • 0019-opt-in-builtin-traits.md
    • 0026-remove-priv.md
    • 0034-bounded-type-parameters.md
    • 0040-libstd-facade.md
    • 0042-regexps.md
    • 0048-traits.md
    • 0049-match-arm-attributes.md
    • 0050-assert.md
    • 0059-remove-tilde.md
    • 0060-rename-strbuf.md
    • 0063-module-file-system-hierarchy.md
    • 0066-better-temporary-lifetimes.md
    • 0068-const-unsafe-pointers.md
    • 0069-ascii-literals.md
    • 0071-const-block-expr.md
    • 0079-undefined-struct-layout.md
    • 0086-plugin-registrar.md
    • 0092-struct-grammar.md
    • 0093-remove-format-intl.md
    • 0109-remove-crate-id.md
    • 0112-remove-cross-borrowing.md
    • 0115-rm-integer-fallback.md
    • 0123-share-to-threadsafe.md
    • 0131-target-specification.md
    • 0132-ufcs.md
    • 0135-where.md
    • 0139-remove-cross-borrowing-entirely.md
    • 0155-anonymous-impl-only-in-same-module.md
    • 0164-feature-gate-slice-pats.md
    • 0179-and-mut-patterns.md
    • 0184-tuple-accessors.md
    • 0199-ownership-variants.md
    • 0202-subslice-syntax-change.md
    • 0214-while-let.md
    • 0218-empty-struct-with-braces.md
    • 0230-remove-runtime.md
    • 0240-unsafe-api-location.md
    • 0235-collections-conventions.md
    • 0236-error-conventions.md
    • 0256-remove-refcounting-gc-of-t.md
    • 0341-remove-virtual-structs.md
    • 0342-keywords.md
    • 0344-conventions-galore.md
    • 0356-no-module-prefixes.md
    • 0379-remove-reflection.md
    • 0385-module-system-cleanup.md
    • 0390-enum-namespacing.md
    • 0403-cargo-build-command.md
    • 0430-finalizing-naming-conventions.md
    • 0445-extension-trait-conventions.md
    • 0446-es6-unicode-escapes.md
    • 0450-un-feature-gate-some-more-gates.md
    • 0495-array-pattern-changes.md
    • 0505-api-comment-conventions.md
    • 0507-release-channels.md
    • 0520-new-array-repeat-syntax.md
    • 0531-define-rfc-scope.md
    • 0533-no-array-elem-moves.md
    • 0544-rename-int-uint.md
    • 0556-raw-lifetime.md
    • 0558-require-parentheses-for-chained-comparisons.md
    • 0560-integer-overflow.md
    • 0563-remove-ndebug.md
    • 0565-show-string-guidelines.md
    • 0803-type-ascription.md
    • 1054-str-words.md
    • 1057-io-error-sync.md
    • 1058-slice-tail-redesign.md
    • 1066-safe-mem-forget.md
    • 1068-rust-governance.md
    • 1096-remove-static-assert.md
    • 1102-rename-connect-to-join.md
    • 1105-api-evolution.md
    • 1119-result-expect.md
    • 1122-language-semver.md
    • 1123-str-split-at.md
    • 1131-likely-intrinsic.md
    • 1199-simd-infrastructure.md
    • 1214-projections-lifetimes-and-wf.md
    • 1242-rust-lang-crates.md
    • 1317-ide.md
    • 1331-grammar-is-canonical.md
    • 1358-repr-align.md
    • 1398-kinds-of-allocators.md
    • 1432-replace-slice.md
    • 1566-proc-macros.md
    • 1567-long-error-codes-explanation-normalization.md
    • 1574-more-api-documentation-conventions.md
    • 1576-macros-literal-matcher.md
    • 1589-rustc-bug-fix-procedure.md
    • 1590-macro-lifetimes.md
    • 1607-style-rfcs.md
    • 1618-ergonomic-format-args.md
    • 1620-regex-1.0.md
    • 1624-loop-break-value.md
    • 1636-document_all_features.md
    • 1640-duration-checked-sub.md
    • 1643-memory-model-strike-team.md
    • 1644-default-and-expanded-rustc-errors.md
    • 1665-windows-subsystem.md
    • 1683-docs-team.md
    • 1721-crt-static.md
    • 1725-unaligned-access.md
    • 1728-north-star.md
    • 1774-roadmap-2017.md
    • 1828-rust-bookshelf.md
    • 1845-shared-from-slice.md
    • 1860-manually-drop.md
    • 1869-eprintln.md
    • 1884-unstable-sort.md

    RFCs unreviewed

    • 0085-pattern-macros.md
    • 0087-trait-bounds-with-plus.md
    • 0089-loadable-lints.md
    • 0090-lexical-syntax-simplification.md
    • 0100-partial-cmp.md
    • 0107-pattern-guards-with-bind-by-move.md
    • 0111-index-traits.md
    • 0114-closures.md
    • 0116-no-module-shadowing.md
    • 0130-box-not-special.md
    • 0136-no-privates-in-public.md
    • 0141-lifetime-elision.md
    • 0151-capture-by-value.md
    • 0160-if-let.md
    • 0168-mod.md
    • 0169-use-path-as-id.md
    • 0192-bounds-on-object-and-generic-types.md
    • 0194-cfg-syntax.md
    • 0195-associated-items.md
    • 0198-slice-notation.md
    • 0201-error-chaining.md
    • 0212-restore-int-fallback.md
    • 0213-defaulted-type-params.md
    • 0216-collection-views.md
    • 0221-panic.md
    • 0231-upvar-capture-inference.md
    • 0234-variants-namespace.md
    • 0241-deref-conversions.md
    • 0243-trait-based-exception-handling.md
    • 0246-const-vs-static.md
    • 0255-object-safety.md
    • 0320-nonzeroing-dynamic-drop.md
    • 0326-restrict-xXX-to-ascii.md
    • 0339-statically-sized-literals.md
    • 0369-num-reform.md
    • 0378-expr-macros.md
    • 0380-stabilize-std-fmt.md
    • 0387-higher-ranked-trait-bounds.md
    • 0401-coercions.md
    • 0404-change-prefer-dynamic.md
    • 0418-struct-variants.md
    • 0438-precedence-of-plus.md
    • 0439-cmp-ops-reform.md
    • 0447-no-unused-impl-parameters.md
    • 0453-macro-reform.md
    • 0458-send-improvements.md
    • 0459-disallow-shadowing.md
    • 0461-tls-overhaul.md
    • 0463-future-proof-literal-suffixes.md
    • 0469-feature-gate-box-patterns.md
    • 0474-path-reform.md
    • 0486-std-ascii-reform.md
    • 0490-dst-syntax.md
    • 0494-c_str-and-c_vec-stability.md
    • 0501-consistent_no_prelude_attributes.md
    • 0503-prelude-stabilization.md
    • 0504-show-stabilization.md
    • 0509-collections-reform-part-2.md
    • 0517-io-os-reform.md
    • 0522-self-impl.md
    • 0526-fmt-text-writer.md
    • 0528-string-patterns.md
    • 0529-conversion-traits.md
    • 0532-self-in-use.md
    • 0534-deriving2derive.md
    • 0546-Self-not-sized-by-default.md
    • 0550-macro-future-proofing.md
    • 0572-rustc-attribute.md
    • 0574-drain-range.md
    • 0580-rename-collections.md
    • 0587-fn-return-should-be-an-associated-type.md
    • 0592-c-str-deref.md
    • 0593-forbid-Self-definitions.md
    • 0599-default-object-bound.md
    • 0601-replace-be-with-become.md
    • 0639-discriminant-intrinsic.md
    • 0640-debug-improvements.md
    • 0702-rangefull-expression.md
    • 0735-allow-inherent-impls-anywhere.md
    • 0736-privacy-respecting-fru.md
    • 0738-variance.md
    • 0769-sound-generic-drop.md
    • 0771-std-iter-once.md
    • 0809-box-and-in-for-stdlib.md
    • 0823-hash-simplification.md
    • 0832-from-elem-with-love.md
    • 0839-embrace-extend-extinguish.md
    • 0840-no-panic-in-c-string.md Update 0840-no-panic-in-c-string.md
    • 0873-type-macros.md
    • 0879-small-base-lexing.md
    • 0888-compiler-fence-intrinsics.md
    • 0909-move-thread-local-to-std-thread.md
    • 0911-const-fn.md
    • 0921-entry_v3.md
    • 0940-hyphens-considered-harmful.md
    • 0953-op-assign.md
    • 0968-closure-return-type-syntax.md
    • 0979-align-splitn-with-other-languages.md
    • 0980-read-exact.md
    • 0982-dst-coercion.md
    • 1011-process.exit.md
    • 1014-stdout-existential-crisis.md
    • 1023-rebalancing-coherence.md
    • 1030-prelude-additions.md
    • 1040-duration-reform.md
    • 1044-io-fs-2.1.md
    • 1047-socket-timeouts.md
    • 1048-rename-soft-link-to-symlink.md
    • 1135-raw-pointer-comparisons.md
    • 1152-slice-string-symmetry.md
    • 1156-adjust-default-object-bounds.md
    • 1174-into-raw-fd-socket-handle-traits.md
    • 1183-swap-out-jemalloc.md
    • 1184-stabilize-no_std.md
    • 1191-hir.md
    • 1192-inclusive-ranges.md
    • 1193-cap-lints.md
    • 1194-set-recovery.md
    • 1200-cargo-install.md
    • 1201-naked-fns.md
    • 1210-impl-specialization.md
    • 1211-mir.md
    • 1212-line-endings.md
    • 1216-bang-type.md
    • 1219-use-group-as.md
    • 1228-placement-left-arrow.md
    • 1229-compile-time-asserts.md
    • 1236-stabilize-catch-panic.md
    • 1238-nonparametric-dropck.md
    • 1240-repr-packed-unsafe-ref.md
    • 1241-no-wildcard-deps.md
    • 1252-open-options.md
    • 1257-drain-range-2.md
    • 1260-main-reexport.md
    • 1268-allow-overlapping-impls-on-marker-traits.md
    • 1270-deprecation.md
    • 1288-time-improvements.md
    • 1291-promote-libc.md
    • 1298-incremental-compilation.md
    • 1300-intrinsic-semantics.md
    • 1307-osstring-methods.md
    • 1327-dropck-param-eyepatch.md
    • 1328-global-panic-handler.md
    • 1359-process-ext-unix.md
    • 1361-cargo-cfg-dependencies.md Add extension ".md
    • 1399-repr-pack.md
    • 1415-trim-std-os.md
    • 1419-slice-copy.md
    • 1422-pub-restricted.md
    • 1434-contains-method-for-ranges.md
    • 1440-drop-types-in-const.md
    • 1443-extended-compare-and-swap.md
    • 1444-union.md
    • 1445-restrict-constants-in-patterns.md Remove duplicate 0000-restrict-constants-in-patterns.md
    • 1461-net2-mutators.md
    • 1467-volatile.md
    • 1479-unix-socket.md
    • 1492-dotdot-in-patterns.md
    • 1498-ipv6addr-octets.md
    • 1504-int128.md
    • 1506-adt-kinds.md
    • 1510-cdylib.md Rename 1510-rdylib.md to 1510-cdylib.md
    • 1513-less-unwinding.md
    • 1521-copy-clone-semantics.md
    • 1522-conservative-impl-trait.md
    • 1525-cargo-workspace.md
    • 1535-stable-overflow-checks.md
    • 1542-try-from.md
    • 1543-integer_atomics.md
    • 1548-global-asm.md
    • 1552-contains-method-for-various-collections.md
    • 1559-attributes-with-literals.md
    • 1560-name-resolution.md
    • 1561-macro-naming.md
    • 1581-fused-iterator.md
    • 1623-static.md
    • 1649-atomic-access.md
    • 1653-assert_ne.md
    • 1660-try-borrow.md
    • 1679-panic-safe-slicing.md
    • 1681-macros-1.1.md
    • 1682-field-init-shorthand.md
    • 1696-discriminant.md
    • 1717-dllimport.md

    B. Status unclear

    Some of these are still in-flight; and some of them are just the kind of thing that I don't even fully grok yet well enough to see if they're documented. For these, unchecked means "status unknown"; checked means "status known and added to the latter bits appropriately."

    C. Documentation needed

    0. Accepted, not-yet-stabilized, undocumented RFCs

    0.1. Document implemented, unstable RFCs

    These should be considered the highest priority for documentation, as these are issues which fall under the rest of the rules of [RFC #1636], in that they need to be documented before stabilization. (That will presumably just happen before stabilizing as usual, but I'm including them here for completeness.)

    • [ ] #0086 plugin-registrar API
    • [ ] #0202: subslice syntax change -- implemented here, not stabilized; see discussion of [#0405] below under C.0.2.
    • [ ] #1131: Add an expect intrinsic
    • [ ] #1358: repr_align – implementation is in-progress, not yet landed on nightly
    • [x] #1624: loop_break_value
    • [x] #1665: Windows subsystem support

    0.2. Track accepted, not-yet-implemented or implementation-in-progress, undocumented RFCs

    These will eventually require documentation, but as they aren't even (fully) implemented yet, there is no urgency here.

    1. List accepted, implemented, already-stabilized, undocumented RFCs

    This list can be added directly to a newly(-to-be)-created appendix to the Reference.

    • [x] Create the appendix (once finished, this list should do just fine, perhaps with some massaging for descriptiveness)

      • [x] #0040: libstd-facade – there is one reference to the facade, in 6.3.13 Compiler Features under a discussion of #[no_std], but no explanation of its meaning. Nor, as far as I can tell, do the relevant sections of the standard library documentation explain this.
      • [x] #0048: Trait reform – some pieces of this are partially documented (the use of Self), but others aren't at all: coherence and orphan rules are covered nowhere. (Currently, the writeup here seems to be the best source on coherence?)
      • [x] #0049: Allow attributes on match arms. – the underlying idea is documented in 6.3 Attributes but the applicability to internal items is never specified.
      • [x] #0131: Some but not all of the flags are documented in 6.3.8 Conditional compilation
      • [x] #0132: Unambiguous function call syntax – not even mentioned
      • [x] #0558: require parentheses for chained comparisons
      • [x] #0560: Integer overflow not unsafe, documented with a reference to the RFC but requires further details
      • [x] #1717: dllimport, one element mentioned but not explained at 6.3.5 FFI attributes
      • [x] #1721: define crt_link
      • [x] #1725: define unaligned_access

    2. Write reference material for undocumented, implemented, stabilized RFC features

    Each of the features listed above in (1) needs to be documented more formally in the reference.

    • [ ] #0040: libstd-facade
    • [ ] #0048: (#5) Trait reform, requires documenting coherence and orphan rules (overlaps with Coherence and Orphan rules below in §3)
    • [ ] #0049: Allow attributes on match arms: specify applicability to internal items
    • [ ] [#0071]: (#13) Allow blocks in constants
    • [ ] #0131: Target specification – some but not all of these are in 6.3.8
    • [x] #0132: Unambiguous/universal function call syntax – not even mentioned
    • [ ] #0179: &mut patterns – symmetry of pattern syntax not documented
    • [x] #0558: (#41) require parentheses for chained comparisons – the requirement is not documented in the reference
    • [x] #0560: Integer overflow not unsafe, documented with a reference to the RFC but requires further details
    • [ ] #1717: dllimport
    • [ ] #1721: crt_link
    • [ ] #1725: unaligned_access

    3. Update out-of-date/incomplete sections of the reference

    • [ ] List of language items

      The set of language items is currently considered unstable. A complete list of the built-in language items will be added in the future.

    • [ ] Coherence

    • [ ] Orphan rules (#5)

    • [ ] Lifetime elision

    D. Documentation not needed

    0. Already documented

    1. Retired

    These items were accepted, but never implemented and not currently *planned* to be implemented and therefore not in need of documentation.
    • #0008: New intrinsics
    • #0112: Remove cross borrowing coercion. Replaced by the removal in #0139.
    • #0115: do not fall back to int if cannot infer integer; replaced with #0212.
    • #0155: only allow "anonymous impl" (impl Foo) in the same module as the data type is defined (struct Foo or mod Foo). Replaced by #0735.

    2. Removals

    Some items constitute not *additions to be documented* but *things removed* from the language. These do not require documentation (for obvious reasons!).
    • #0026: Remove the priv keyword
    • #0059: Remove ~ in favor of box and Box
    • #0063: Tighten restrictions on mod
    • #0093: Remove localization from format!
    • #0139: Remove cross borrowing entirely.
    • #0230: Remove runtime
    • #0256: Remove refcounting Gc<T> from stdlib
    • #0341: Remove "virtual struct"/struct inheritance feature
    • #0379: Remove reflection (libdebug, Poly trait, and an earlier version of :?, since repurposed)
    • #0385: Module system cleanup and simplification (current module rules are documented; these changes removed restrictions)
    • #0533: Remove support for moving individual elements into uninitialized arrays or out of fixed-sized arrays
    • #1096: Remove static_assert

    3. Parser-specific

    Some changes are specific to the parsing (though they affect the language). These should be documented not in the reference but in the language grammar.

    4. Process and conventions

    • #0199: Conventions for ownership variants (naming conventions, mostly internal interest)
    • #0235: Conventions for collections and iterables (and a few other things)
    • #0236: Conventions for error handling
    • #0240: Conventions for unsafe API locations
    • #0344: Conventions for naming conventions: types in method names, iterator type names, iterator method names, getter/setter APIs, associated types, traits, lints, suffix ordering, and prelude traits.
    • #0356: Conventions for exported items (Io:Error, not Io::IoError)
    • #0430: Conventions for capitalization, underscores, and unwrap
    • #0445: Conventions for naming extension traits
    • #0505: Conventions for API docs for Rust projects (including the language)
    • #0507: Release channels
    • #0531: RFC scope and Rust "distribution" definition
    • #0556: Conventions for unsafe functions constructing references out of raw pointers
    • #1068: Scaling Rust's governance
    • #1105: API evolution and versioning guidelines
    • #1122: Rust language SemVer definitions
    • #1242: Policy for rust-lang GitHub organization crates governance
    • #1331: grammar: make the formal grammer canonical and formal – Note: I think this should probably be linked in the reference (as well as other places) once it's finished, and it's already linked from the head of the reference.
    • #1567: Normalize long error codes with a baseline template
    • #1574: More API Documentation Conventions
    • #1589: Define the rustc bugfix best practices
    • #1607: RFC process for formatting style and Rustfmt defaults (results will be captured in a non-reference document)
    • #1636: Document All Features (process) (this PR!)
    • #1643: Dedicated strike team to resolve unsafe code guidelines (results should be captured in the Reference, but this issue itself not so much)
    • #1644: Default and expanded errors for rustc
    • #1683: Create a docs subteam
    • #1728: North Star (process)
    • #1774: Roadmap for 2017
    • #1828: Rust bookshelf

    5. Non-language features

    • #1317: Rust Language Server

    Note: I've just copied over the original issue as it was—wholesale. Note that some of the links here referencing things as "already documented" will degrade given the new structure of the book.

    Bug Enhancement Help Wanted Tracking Issue 
    opened by chriskrycho 44
  • Document execution order

    Document execution order

    Thank eddyb and Steve Klabnik for complaining on Twitter for this PR.

    Closes #248

    The order is now documented. I considered using an example over expression evaluation using println!, but the twitter thread is explicitly using iterators and this is probably the most common reason to care about evaluation order in tuple expressions anyways.

    I also cleaned up the page to bring it into style compliance. I did both at the same time, so there's only one noisy commit. Sorry to the reviewer.

    New Content A-expressions S-waiting-on-review 
    opened by Havvy 17
  • async-await initial reference material

    async-await initial reference material

    I'm not sure what the best reviewing process is here.

    cc @cramertj @withoutboats @centril @joshtriplett @pnkfelix @scottmcm @pnkfelix @eddyb (I think that's the lang team, did I miss anybody?)

    cc https://github.com/rust-lang-nursery/reference/issues/634 https://github.com/rust-lang/rust/issues/62566

    opened by nikomatsakis 17
  • Add

    Add "Logic errors" as behavior not considered unsafe

    In https://github.com/rust-lang/rust/issues/80657 and https://github.com/rust-lang/rust/pull/80681 it is discussed how to clarify/define what a "logic error" is and what are their consequences. The reference should mention them as well.

    We could use other term instead of "unspecified", e.g. "unpredictable"; in case we want to emphasize that the results may not the same between runs, builds, kinds of build, etc. For instance, from the description of integer overflow, it looks like the implementation needs to choose some reasonable behavior (e.g. a panic or wrap around), even if not documented (therefore, "unspecified", in terms of the C and C++ standards). However, logic errors seem to require more freedom: the implementation may not even be able (or want) to predict what may happen, so it cannot "reasonably choose" a particular behavior, even if such behavior is guaranteed to be safe (similar to deadlocks, although in that case the set of possible behavior is known, even if nondeterministic between runs).

    As I mentioned in one of the linked discussions, it might be a good idea to define a separate, clear term for this kind of behavior that is considered erroneous and unpredictable, yet safe. So not exactly "unspecified", at least as used in the C and C++ standards -- it is closer to "safe UB" than "unspecified". In other words, in the same spirit as C's "bounded UB" or Ada's "bounded error". Ideally, the term would not overload another common term in other language specs (like UB).

    opened by ojeda 16
  • Fix incorrect pseudocode for #[repr(C)] struct alignment

    Fix incorrect pseudocode for #[repr(C)] struct alignment

    Alternative to #559 incorporating some suggested changes to that PR.

    @RalfJung I felt like your pseudocode approached actual code too much, and sorta requires understanding what's going on with Layout in order to follow, so I just took the route of making the padding calculation into an implicit function per other suggestions.

    opened by kinseytamsin 16
  • Size fo empty structs in C is zero byte.

    Size fo empty structs in C is zero byte.

    #include<stdio.h>
    
    struct A {
    };
    
    int main() {
            struct A a;
            printf("%ld\n", sizeof(a));
    }
    
    $ gcc tmp.c
    $ ./a.out
    0
    $ g++ tmp.c
    $ ./a.out
    1
    
    opened by ldm0 13
  • update aliasing rules section of the reference

    update aliasing rules section of the reference

    This makes explicit some de-facto rules that existed at least since Rust 1.0:

    • Boxes also have aliasing requirements.
    • References must outlive functions they are passed to. (It is not entirely clear that this was intended when the dereferenceable attribute was added, given that the attribute was also added to Box which can definitely be deallocated by functions they are passed to. But when that got fixed in https://github.com/rust-lang/rust/issues/66600, nobody suggested to also remove the attribute from references.)

    Irrespective of whether we actually want these rules, they do reflect our current requirements and code not following them risks miscompilations. As such I think we should document them here and consider them the baseline for changes to the aliasing model. It's not great to have a baseline that was never carefully reviewed or designed, but for better or worse that's where we are at.

    Also incorporates https://github.com/rust-lang/rust/pull/98017.

    Rendered

    Cc @rust-lang/lang

    I-lang-nominated T-lang 
    opened by RalfJung 12
  • Add supported Directives list

    Add supported Directives list

    This seeks to limit the directives guaranteed to be supported by inline assembly to a subset of those supported by LLVM and GNU AS. The list is chosen as a compromise between utility and implementability, and may be increased in the future.

    See discussions here: https://rust-lang.zulipchat.com/#narrow/stream/213817-t-lang/topic/asm!.20and.20backends and https://rust-lang.zulipchat.com/#narrow/stream/216763-project-inline-asm/topic/Defect.20Report.3A.20GNU.20AS.20support

    CC: @joshtriplett

    I-lang-nominated T-lang final-comment-period 
    opened by chorman0773 12
  • Documented the `#[repr(align(x))]` attribute.

    Documented the `#[repr(align(x))]` attribute.

    Updated reference for stabilization of the #[repr(align(x))] attribute. See tracking issue comments https://github.com/rust-lang/rust/issues/33626#issuecomment-348467804 for discussion.

    opened by bitshifter 12
  • New Section - Type Layout

    New Section - Type Layout

    r? @scottmcm @Gankro @eddyb - Though if you don't want to, just say so and unsubscribe from the thread.

    There's no good term for what the compiler calls ADTs - structs, enums, and unions. I cannot think of one either. As such, there's a FIXME in there.

    I'm also choosing a very conservative definition of type layout. I'm not sure if it should be expanded or not, or if the valid values and calling convention changes should be a part or not. Although I don't think they should, I don't have any logical arguments either way. Part of the problem is that layout can probably mean multiple things at the same time. E.g. Layout for allocators is just size and alignment.

    New Content 
    opened by Havvy 12
  • Simplify rules for GenericArgs nonterminal and other small improvements and fixes

    Simplify rules for GenericArgs nonterminal and other small improvements and fixes

    I initially only wanted to create a version of the GenericArgs non-terminal that doesn’t need 8 cases. On my way there I stumbled across non-terminals that contain the empty word that could easily be changed (much nicer like this IMO), I noticed inconsistencies around parenthesis spacing and fixed some files, found a few typos and mistakes and finally created a bunch of internal links in the tokens.md file.

    If any of these changes is controversial I can split it into a different PR.

    S-waiting-on-author 
    opened by steffahn 10
  • Fix parsing of doc comments which are turned into raw strings

    Fix parsing of doc comments which are turned into raw strings

    PR prompted by https://github.com/dtolnay/syn/issues/771

    macro_rules! m {
        (#[doc = $tt:tt]) => { stringify!($tt) };
    }
    
    fn main() {
        println!(m! {
            ///test
        });
       // output: r"test"
    }
    

    Will also open a PR for rustdoc

    opened by kraktus 4
  • Clarify note stating that reading uninitialized padding is permitted

    Clarify note stating that reading uninitialized padding is permitted

    The reference says:

    • Producing an invalid value, even in private fields and locals. "Producing" a value happens any time a value is assigned to or read from a place, passed to a function/primitive operation or returned from a function/primitive operation. The following values are invalid (at their respective type):
      • [...]
      • An integer (i*/u*), floating point value (f*), or raw pointer obtained from uninitialized memory, or uninitialized memory in a str.

    and then later:

    Note: Uninitialized memory is also implicitly invalid for any type that has a restricted set of valid values. In other words, the only cases in which reading uninitialized memory is permitted are inside unions and in "padding" (the gaps between the fields/elements of a type).

    What would be an example of reading uninitialized padding memory? Does this mean that reading uninitialized padding memory is an exception to the above rule (I'm guessing not, but I don't know how to interpret this note otherwise)? Would ptr::read::<u8>(ptr_to_padding) be considered "permitted"? Or does it only mean that ptr::read::<MaybeUninit<u8>>(ptr_to_padding) is "permitted"?

    I think this note is unclear and should be reworded. The second sentence also starts with "In other words ...", but these two sentences seem like completely different ideas.

    opened by stevenengler 0
  • How method resolution ambiguties are/aren't resolved

    How method resolution ambiguties are/aren't resolved

    Spawned off of https://github.com/rust-lang/rust/issues/81211#issuecomment-767111563

    We need better documentation of the method resolution rules, in terms of how ambiguities are resolved (to either a single method or to a method ambiguity error).

    I wrote tests in PR #81294 that tried to enumerate the relevant combinations; see:

    • https://github.com/rust-lang/rust/blob/master/src/test/ui/derives/derive-Debug-use-ufcs-struct.rs
    • https://github.com/rust-lang/rust/blob/master/src/test/ui/derives/derive-Debug-use-ufcs-tuple.rs

    But we still need better docs in the reference

    opened by pnkfelix 0
  • Clearly specify the `instruction_set` inlining restrictions

    Clearly specify the `instruction_set` inlining restrictions

    This updates the instruction_set attribute entry to more clearly explain the additional restrictions that the attribute places on inlining. Since Rust performance heavily relies on inlining, it's actually a fairly big deal to document it.

    Pinging @pnkfelix as the liaison for the instruction_set attribute during its development.

    This explanation is actually slightly looser than the explanation given in the RFC: this explanation allows inlining between no-attribute code without inline asm and other code. So, T-lang should likely approve the update with an FCP or similar process. The intent is that once this is approved as the documentation for how the attribute works then https://github.com/rust-lang/rust/pull/104121 (which updates the MIR inliner to match these rules) will be easier to land.

    I-lang-nominated 
    opened by Lokathor 2
  • 'Type layout' and 'Dynamically Sized Types' pages disagree on whether the size of a pointer to a DST is defined

    'Type layout' and 'Dynamically Sized Types' pages disagree on whether the size of a pointer to a DST is defined

    The 'Dynamically Sized Types' page pretty clearly states that the size of a pointer to a DST is twice the size of a regular pointer:

    • Pointer types to DSTs are sized but have twice the size of pointers to sized types

    But, the 'Type layout' page gives this much less concrete answer:

    • Pointers to unsized types are sized. The size and alignment is guaranteed to be at least equal to the size and alignment of a pointer.

    And, in a note, it says the same thing as the DST page, but says that it shouldn't be relied upon:

    Note: Though you should not rely on this, all pointers to DSTs are currently twice the size of the size of usize and have the same alignment.

    The two pages should be consistent. Assuming that the DST page is correct, the type layout page should also concretely say that pointers to unsized types are twice the size of regular pointers, and the note should be removed.

    opened by Liamolucko 3
Owner
The Rust Programming Language
The Rust Programming Language
RcLite: small, fast, and memory-friendly reference counting for Rust

RcLite: small, fast, and memory-friendly reference counting RcLite is a lightweight reference-counting solution for Rust that serves as an alternative

Khashayar Fereidani 147 Apr 14, 2023
Leetcode Solutions in Rust, Advent of Code Solutions in Rust and more

RUST GYM Rust Solutions Leetcode Solutions in Rust AdventOfCode Solutions in Rust This project demostrates how to create Data Structures and to implem

Larry Fantasy 635 Jan 3, 2023
Simple autoclicker written in Rust, to learn the Rust language.

RClicker is an autoclicker written in Rust, written to learn more about the Rust programming language. RClicker was was written by me to learn more ab

null 7 Nov 15, 2022
Rust programs written entirely in Rust

mustang Programs written entirely in Rust Mustang is a system for building programs built entirely in Rust, meaning they do not depend on any part of

Dan Gohman 561 Dec 26, 2022
Rust 核心库和标准库的源码级中文翻译,可作为 IDE 工具的智能提示 (Rust core library and standard library translation. can be used as IntelliSense for IDE tools)

Rust 标准库中文版 这是翻译 Rust 库 的地方, 相关源代码来自于 https://github.com/rust-lang/rust。 如果您不会说英语,那么拥有使用中文的文档至关重要,即使您会说英语,使用母语也仍然能让您感到愉快。Rust 标准库是高质量的,不管是新手还是老手,都可以从中

wtklbm 493 Jan 4, 2023
A library for extracting #[no_mangle] pub extern "C" functions (https://docs.rust-embedded.org/book/interoperability/rust-with-c.html#no_mangle)

A library for extracting #[no_mangle] pub extern "C" functions In order to expose a function with C binary interface for interoperability with other p

Dmitrii - Demenev 0 Feb 17, 2022
clone of grep cli written in Rust. From Chapter 12 of the Rust Programming Language book

minigrep is a clone of the grep cli in rust Minigrep will find a query string in a file. To test it out, clone the project and run cargo run body poem

Raunak Singh 1 Dec 14, 2021
Rust-blog - Educational blog posts for Rust beginners

pretzelhammer's Rust blog ?? I write educational content for Rust beginners and Rust advanced beginners. My posts are listed below in reverse chronolo

kirill 5.2k Jan 1, 2023
The ray tracer challenge in rust - Repository to follow my development of "The Raytracer Challenge" book by Jamis Buck in the language Rust

The Ray Tracer Challenge This repository contains all the code written, while step by implementing Ray Tracer, based on the book "The Ray Tracer Chall

Jakob Westhoff 54 Dec 25, 2022
Learn-rust-the-hard-way - "Learn C The Hard Way" by Zed Shaw Converted to Rust

Learn Rust The Hard Way This is an implementation of Zed Shaw's Learn X The Hard Way for the Rust Programming Language. Installing Rust TODO: Instruct

Ryan Levick 309 Dec 8, 2022
Learn to write Rust procedural macros [Rust Latam conference, Montevideo Uruguay, March 2019]

Rust Latam: procedural macros workshop This repo contains a selection of projects designed to learn to write Rust procedural macros — Rust code that g

David Tolnay 2.5k Dec 29, 2022
The Rust Compiler Collection is a collection of compilers for various languages, written with The Rust Programming Language.

rcc The Rust Compiler Collection is a collection of compilers for various languages, written with The Rust Programming Language. Compilers Language Co

null 2 Jan 17, 2022
Integra8 rust integration test framework Rust with a focus on productivity, extensibility, and speed.

integra8 Integra8 rust integration test framework Rust with a focus on productivity, extensibility, and speed. | This repo is in a "work in progress"

exceptional 3 Sep 26, 2022
Neofetch but in Rust (rust-toml-fetch)

rtfetch Configuration Recompile each time you change the config file logo = "arch.logo" # in src/assets. info = [ "", "", "<yellow>{host_n

Paolo Bettelini 6 Jun 6, 2022
Rust Sandbox [code for 15 concepts of Rust language]

Rust-Programming-Tutorial Rust Sandbox [code for 15 concepts of Rust language]. The first time I've been introduced to Rust was on January 2022, you m

Bek Brace 4 Aug 30, 2022
TypeRust - simple Rust playground where you can build or run your Rust code and share it with others

Rust playground Welcome to TypeRust! This is a simple Rust playground where you can build or run your Rust code and share it with others. There are a

Kirill Vasiltsov 28 Dec 12, 2022
Rust Imaging Library: A high-level Rust imaging crate.

ril Rust Imaging Library: A performant and high-level Rust imaging crate. Documentation • Crates.io • Discord What's this? This is a Rust crate design

Jay3332 18 Jan 5, 2023
In this repository you can find modules with code and comments that explain rust syntax and all about Rust lang.

Learn Rust What is this? In this repository you can find modules with code and comments that explain rust syntax and all about Rust lang. This is usef

Domagoj Ratko 5 Nov 5, 2022
Game Boy Emulator written in Rust, as a way to fully grasp the Rust programming language

Flan's Game Boy Emulator Game Boy Emulator written in Rust, as a way to get hands-on with the Rust programming language, and creating a proper project

Flan 3 Dec 31, 2022