Boxy
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    1
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Const Generics Big Pictures This is a rough outline of a variety of possible "big picture" designs for const generics. Not focusing too much on impl details or minutea but just generally how things can fit together in the long term. ## Minimal Present for Const Generics The current stable design ### Design The types `uN`, `iN`, `char` and `bool` can be used as the type of a Const Generic Parameter. Put another way, when writing `fn foo<const N: Ty>` the compiler will check that `Ty` is one of the above types. --- Const Generic Arguments are allowed to be a path to a Const Generic Parameter: ```rust fn path() -> [(); N] { ``` Const Generic Arguemnts are allowed to be an arbitrary non-generic expression: ```rust fn non_generic_expr<const N: usize>() -> [(); 1 + 1] { ... } // illegal as `N + 1` uses generic parameters and doesn't match any // of the other forms of accepted expressions fn generic_expr<const N: usize>() -> [(); N + 1] { ... } ``` Note: there is technically an extra rule to handle the length of array repeat expressions but that isn't intended to exist as an actual thing in the type system. It is FCW'd and will be removed eventually: https://github.com/rust-lang/rust/issues/76200 ### Unsolved Use Cases Most of them ## Slightly Sparkly Future for Const Generics A potential future state that doesn't solve all use cases but is cohesive, implementable, and a large step forwards. ### Design If a type implements the `ConstParamTy` trait it can be used as the type of a Const Generic Parameter. Put another way, when writing `fn foo<const N: Ty>` the compiler will check that `Ty: ConstParamTy` holds. It follows from this that generic parameters can be used as the type of a Const Generic Parameter if there is a `T: ConstParamTy` where clause: `fn foo<T: ConstParamTy, const N: T>`. The following builtin types implement the `ConstParamTy` trait: - `bool` - `char` - `iN` and `uN` - `[T; N] where T: ConstParamTy` - `(...T) where ...T: ConstParamTy` - all(?) function item types For an implementation of `ConstParamTy` to be accepted, the types of all fields must themselves implement `ConstParamTy`. For structs/enums all fields must be as public as the struct/enum itself, and the struct/variants must not be marked `non_exhaustive`. --- A new kind of item is introduced, `typeconst` which is an *alias* to a Const Generic Argument: `typeconst $ident: $ty = $constarg;`. `typeconst` items may have generic parameters and where clauses. ```rust typeconst FOO<const N: usize>: usize = N; // legal // illegal as `fn_call(N)` is not a valid Const Generic Argument typeconst BAR<const N: usize>: usize = fn_call(N); ``` The type of a `typeconst` item must implement `ConstParamTy`. If a trait definition has an associated `typeconst` then the trait impl must also implement the associated `typeconst`. Associated `typeconst`s don't make a trait dyn incompatible. A trait object whose trait has associated `typeconst`s must specify all the values of the `typeconst`s. --- Const Generic Arguments are allowed to be a path to a Const Generic Parameter[^1]: ```rust typeconst FOO<const N: usize>: usize = N; ``` Const Generic Arguments are allowed to be paths to `typeconst` items and these paths may involve generic parameters: ```rust typeconst BAZ<const N: usize>: usize = FOO::<N>; fn foo<const N: usize>() -> [(); BAZ::<N>] { ... } ``` Const Generic Arguments are allowed to be struct/variant expressions and struct/variant tuple constructor calls. All sub-expressions must be valid Const Generic Arguments (potentially involving generic parameters): ```rust #[derive(ConstParamTy, Eq, PartialEq)] struct Foo { field: usize } #[derive(ConstParamTy, Eq, PartialEq)] struct TupleFoo(usize); typeconst FOO<const N: usize>: Foo = Foo { field: N }; // illegal as `N + 1` is not a valid Const Generic Argument typeconst FOO_ILLEGAL<const N: usize>: Foo = Foo { field: N + 1 }; typeconst TUPLE_FOO<const N: usize>: TupleFoo = TupleFoo(N); // illegal as `N + 1` is not a valid Const Generic Argument typeconst TUPLE_FOO_ILLEGAL<const N: usize>: TupleFoo = TupleFoo(N + 1); ``` Const Generic Arguments are allowed to be tuple/array/repeat expressions. All sub-expressions must be valid Const Generic Arguments (potentially involving generic parameters): ```rust typeconst ARR<const N: u8, T: Trait>: [u8; 3] = [N, 1_u8, <T as Trait>::ASSOC]; // illegal as `N + 1` is not a valid Const Generic Argument typeconst ARR_ILLEGAL<const N: u8, T: Trait>: [u8; 3] = [N + 1, 1_u8, <T as Trait>::ASSOC]; typeconst ARR_REPEAT<const N: u8>: [u8; N] = [N; N]; // illegal as `N + 1` is not a valid Const Generic Argument typeconst ARR_REPEAT_ILLEGAL<const N: u8>: [u8; N] = [N + 1; N + 1]; typeconst TUPLE<const N: Foo, T: Trait>: (Foo, u8, bool) = (N, <T as Trait>::ASSOC, true); // illegal as `N + 1` is not a valid Const Generic Argument typeconst TUPLE_ILLEGAL<const N: Foo, T: Trait>: (Foo, u8, bool) = (N + 1, <T as Trait>::ASSOC, true); ``` Const Generic Arguemnts are allowed to be an arbitrary non-generic expression[^2]: ```rust typeconst NON_GENERIC_EXPR<const N: usize>: usize = 1 + 1; // illegal as `N + 1` uses generic parameters and doesn't match any // of the other forms of accepted expressions typeconst GENERIC_EXPR<const N: usize>: usize = N + 1; ``` ### Misc Design Thoughts This design has a few desirable properties: - No post mono errors - All types supported in const generics work "equally" well - Equality of type level expressions is "intuitive"/has one obvious behaviour - Equality of type level *values* is "intuitive"/has one obvious behaviour Because we special case "basic" constructor expressions we restrict the set of types allowed in const generics to only be those which can always be constructed via a "basic" constructor expression. This ensures that *all* types supported under this design work "equally" well. If we allowed, for example, structs with `non_exhaustive` then they would no longer be constructable via a struct expression in all scopes. Now it would not be possible to generically construct a value of such a type: ```rust pub mod foo { #[derive(ConstParamTy, Eq, PartialEq)] #[non_exhaustive] pub struct Foo<T> { field: T, } pub fn bar<T: ConstParamTy, const F: Foo<T>>() {} pub fn constructor<T>(field: T) -> Foo<T> { Foo { field, } } } use foo::*; fn example<T: ConstParamTy, const N: T>() { // illegal as function calls involving generic parameters // are not valid const generic arguments bar::<T, { constructor(N) }>(); // illegal as `Foo` is `non_exhaustive` but otherwise would // be legal bar::<T, { Foo { field: N }}>(); // there is no way for the user to make the above work } ``` ### Unsolved Use Cases - Arithmetic on user defined types, e.g. vector/matrix math - Types with private fields, e.g. `Layout` - Types with safety invariants, e.g. `str` or `NonZeroX` - floats/fnptrs/references/other builtin types. - `unsafe fn` ptrs can't use the `const F: impl FnOnce(...)` workaround - Closures cant be used, if we do implement `ConstParamTy` then we have classic "unused parameters" problems... It's unclear to me if the ability to "destructure" types via `match`/field projections/array indexing is a "necessity" for "reasonable" support for these types. Supporting field projections for structs/tuples is relativelt trivial. But supporting match expressions and array indexing is tricky... Match expressions have somewhat confusing type level equality because some users may expect match arms to be reorderable, it also involves introducing binders into const generics which is some impl work but doable. Array indexing is fallible and likely means post mono errors :< It's probably best to leave out destructuring types from the "slightly sparkly future". However, some limited form of destructuring *is* possible via impl matching: ```rust impl<const N: usize> Trait<{ Some(N) }> for () { ... } ``` allows to match a `const N: Option<usize>` against `Some(n)`... sort of... ## Post Mono Future for Const Generics Yeah this is very much a WIP and I need to finish this sectiona and is very outdated right now. No point reading from this point onwards ### Design :woman-shrugging: I need to think more about where we can get to past the "Slightly Sparkly" future - privacy/non_exhaustive/safety invariants are allowed on types implementing `ConstParamTy` - just assuming we can make safety invariants work somehow :thinking_face: worst case we can require constructing them to be behind a function/method call xd - typeconsts are gone in favour of normal const items - associated consts no longer make a trait dyn incompatible? - arbitrary expressions using generics are allowed but are treated "opaquely" to the type system. only equal to itself by definition-based equality rather than syntactic equality. only allowed as the rhs of a const item so that there is a name associated with the expression - introduces post mono errors - support function calls/method calls as Const Generic Arguments. - post mono errors - requires very involved const eval changes or *something* but we can figure something out maybe... - function calls are effectively now "opaque type consts" in that the type system doesnt look inside function bodies. actually kinda nice design wise? - this also probably isnt shiny enough - coercions work:tm: somehow - coercions (also from method lookup/autoref/deref) have weird interactions with type level expression equality which may be *weird*. potentially we'd want this to only ever be opaque - what even are the complete set of expressions we'd support without opaqueness? - should go through `hir::ExprKind` - drop half the adt_const_params ideals on the floor: - support `fn` in const generics - support floats with picking a singular NaN representation and having it be equal to itself and `-0`/``+0` being unequal - support raw pointers with Per-Value reject for pointers without a known address, and lossy conversion for its provenance ### Design Thoughts We now have post mono errors, makes it not *that* shiny future but there is a huge increase in expressiveness. Users **really** do not want post mono errors. We can support basically every type in const generics so long as it doesn't have safety invariants which conflict with the Lossy Conversions. We lose some nice hypothetical properties but the expressiveness is meaningful. Allowing post mono errors and having the "opaque" escape hatch means that most things are going to be possible with const generics at this point. The opaque escape hatch has the downside that it may cause ecossytem problems. E.g. if we don't support function calls as a first class type level expression, then different crates will have to define their own opaque `const FUNCTION_CALL<const F: impl Fn(...), const ARGS: (...)>` which won't iterop with eachother very nicely. By accepting post mono errors and treating function calls as a first class expr we *do* allow for ADTs with field privacy to be "just as well supported" as fully publicly constructable ADTs. ## Unsolved Use Cases ...ideally none :> [^1]: Note this rule exists on stable [^2]: Note this rule exists on stable

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully