Aleksey Kladov
    • 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
      • Invitee
    • Publish Note

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

      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.
      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
    • Engagement control
    • 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 Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync Engagement control 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
Invitee
Publish Note

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

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.
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
Subscribed
  • Any changes
    Be notified of any changes
  • Mention me
    Be notified of mention me
  • Unsubscribe
Subscribe
# HIR 2.0 for rust-analyzer This document is a collaboratively edited _RFC_ to design the end-game API for writing IDE analysis of the Rust programming language. The immediate goal is to use the API in rust-analyzer. The lodestar is to make this API stable and publicly available, to let others build on top of it. Zulip discusion thread: https://rust-lang.zulipchat.com/#narrow/stream/185405-t-compiler.2Frust-analyzer/topic/Tree.20Based.20HIR ## Domain We want to build an API for programs written in the Rust programming language. The primary use of the API is getting semantic information about Rust programms. Crucially, this is an API for *consumers* of the analysis. Intrernally, compiler will use a different set of data structures to perform type inference and such. ## Semantic Constraints - The API describes Rust code as written, and not some intermediate representation. - Full-fidelity -- there is precise correspondence between HIR node and the original source code (precise doesn't mean one-to-one though) - Full error tolerance -- no constraints are imposed on the source code, beyond "valid utf8". Combined with full fidelity, this means that arbitrary text can be round-tripped through the API. - Fully analyzed view of the code. In particular: - The code is fully macro expanded (but fidelity requires that original, non-expanded code is also available) - The code is fully resolved. Getting from the `impl` block to the corresponding `trait` is one-step (but fidelity requires that original path, designating the trait, is also available, and that each component of that path can be resolved). - The API presents static view of the code. The API to change the input or to apply refactors is specified elsewhere. - API allows for speculative analysis: "what would be the result if the text was like this?" Reasons for speculation: - Completion: want to insert an `fake` ident to repair the syntax tree and ask about the type of `fake` to better sort suggestions - Doc comments: want to resolve and highlight code snippets from comment as if they were written. - Some refactors -- in ["remove semicolon"](https://github.com/rust-analyzer/rust-analyzer/pull/6769#discussion_r540148545) we want to speculatively remove `;` to check if the result type-checks. - Traversability -- it should be easy to navigate through heterogeneous entities comprising the rust progam - Whole World -- API should not be constrained to a single crate, and should represent an arbitrary set of crates with cross-references between them. - rmeta-transparent -- source code might not be available for some crates, the API should support pre-compiled rmeta files as inputs. - single-file-mode ready? Do we need special support for files which are not part of the crate graph? ## Implementation Constraints - Laziness -- although the API presents static view of the code, the implementation should be able to lazily compute only the minimally required bits on info. As a litmus test, when using the API to compute syntax hightlighting for a single file, bodies of functions in other files should remain unprocessed. - Cancellability -- analysis can take a long time to complete and, given that the user constantly types into the editor, we need an ability to cancel in-progress work. - In general, analyzing Rust source code can take unbounded amount of time, Rust is full of compilation bombs. None the less, the API should guarate reasonable response times (<16ms ideally, <100ms OK, >100ms needs improvement). So, every compiler functionality that can get stuck should be limited by some kind of fuel. - The API doesn't need to be thread-safe -- it's a light-weight view into data. It's ok to use cells & rc in the API. Internally, it's ok to transparently multithread to improve performance - VFS: do we require to know the super-set of all source files up-front? Can we dynamically discover additional files? ## Guide-level explanation EDIT: the below is probably won't work, it seems that we want to separate layers: * expanded syntax layer * symbols (whith substitution) The code is generally tree shaped, so the idea is to make the tree shaped API work. That means that each entity in the API will have (conteptually) `.parent()` and `.children` methods. The root of of the tree is a crate, all crates form a DAG. The single child of a crate is it's root module. Module contains all the items defined within the module. Items like function or const contain bodies, which are a tree of expresisons, etc. The leaves of the tree are tokens. So, it is possible to get a reference to a particular ident token, and then get the type, resolve, lifetimes out of it, etc. Macro calls will will have both the original argument and an expansion as children. Let's see a small example ```rust macro_rules! m { ($i:expr) => { $i.abs() } } fn main() { let x = m!(-92); } ``` Here, we'll have a `MacroCall` node for the `m!(-92);` fragment. It will have `.arg()` property, returning `(-92)` token tree, as well as `.expansion()` property, returning `(-92).abs()`. Correlating `-92` from the call-site with the `-92` from the expansion is a surprisingly hard problem, with no precise solution. Rust macro expansion model has no notion of token identity -- we can't say that a source token get turned into an expanded token. Rather, some source and expanded tokens happen to share identical source spans (but potentailly different hygiene info). For this reason, only `TextRange` based API is available. Expansion can map an `.arg` text range to a set of ranges in `.expansion()`. Each token has a `source_span` method, returning the orignal source location. For attributes, the annotated item will have an `.expansion()` attribute: ```rust #[tokio::main] async fn main() { } ``` Here, the `async main` `hir::Fn` will have `.expansion()` pointing to the, well, expansion. ## API Sketch Note the "Context Passing" unresovled question below! ```rust= //* Elemets *// /// All there is! struct Universe; /// Source file as written by user. struct SourceFile; /// `SourceFile`, which is a part of a specific `Crate` /// via `mod ;` or `include!()`. Aliased `SourceFile`s /// create distinct `CrateFile`s. struct PhysicalFile; // NQ: MountedFile? /// Either a physical `PhysicalFile` or a macro expansion. /// Contains tokens rather than strings? struct LogicalFile; // NQ: TokenFile? struct Crate; struct Module; enum ModuleKind { Root { file: ModuleFile } File { decl: ModuleDecl, file: ModuleFile, } Inline { body: ModuleBody, } } struct ModuleFile { file: PhysicalFile, } struct Token; //* Utility Types *// struct CrateDep { krate: Crate, name: String } /// Strongly-typed (u32, u32). type TextRange = text_size::TextRange ; /// Location in the source code written by the user. /// Corresponds to `lo, hi` bit of `SpanData` from `rustc`. struct SourceLocation { file: SourceFile, text_range: TextRange } struct PhysicalLocation { file: PhysicalFile, text_range: TextRange } struct LogicalLocation { file: LogicalFile, text_range: TextRange } //* API *// impl Universe { fn crates(self) -> Vec<Crate> /// For a given source location, the list of /// `PhysycalLocation`s it can be viewed as. /// /// For `#[test]` and other conditional compilation situations, /// this will return PLs for both versions of the crate /// (with and without `--cfg test`). It's up to the caller to /// figure out that one of them is not interesting (expands to void). /// /// Invariant: /// /// result.all(|pl| { /// pl.file.source_file() == sl.file /// && pl.text_range = sl.text_range /// }) /// /// Q?: should this group by crate? HashMap<Crate, Vec<PhysicalLocation>> /// alternatively, just sort by crate? fn source_to_physical_loc(self, sl: SourceLocation) -> Vec<PhysicalLocation> } impl Crate { fn deps(self) -> Vec<CrateDep> fn rev_deps(self) -> Vec<CrateDep> fn root_module(self) -> Module; /// For a given source locatin anchored to a crate, /// the list of logical locations it expands to. /// /// Q: If PL corresponds to cfg-ed out code, should /// this return an empty Vec? /// /// Precondition: /// pl.file.crate() == self /// /// Invariant: /// Q: logical location doesn't neccessary correspond /// to a physical location: physical locations are /// properties of the whole tokens. How do we express /// the neccessary constraint here? fn physical_to_logical_loc(self, pl: PhysicalLocation) -> Vec<LogicalLocation> /// Finds the token for the corresponding logical location /// /// Invariant: logical location belongs to this crate fn find_token(self, ll: LogicalLocation) -> Option<Token> fn find_element<E: Element>(self, ll: LogicalLocation) -> Option<E> } impl Module { fn physical_file(self) -> PhysicalFile } impl PhysicalFile { fn crate(self) -> Crate; /// `SourceFile` corresponding to this `CrateFile`. /// Q: should this return an Option<>? /// Can we manufacture a file out of thin air? fn source_file(self) -> SourceFile; } impl Token { /// Source-location bits of rustc's `.span()`. fn physical_location(self) -> PhysicalLocation; /// Position of the token in a specific macro expansion. fn logical_location(self) -> LogicalLocation; } ``` ## Unresolved Qustions **Naming** `hir` is a decidedly bad name here. Better versions: * `sem` for semantics * `fir` for front-end IR, homage to Kotlin * `rst` for rs tree **Contex Passing** Should nodes contain an Rc/& to global ctx? Should we thread arguments? **Symbols** Consider the following field declaration: `field: module::Thing<String>,`. If this is `let f: hir::Field`, then `f.ty()` can reasonably mean three things: * the `module::Thing<String>` path * the `hir::Struct` corresponding which `module::Thing` resolves to * the `Ty { ctor: hir::Struct, subst: [String] }` type All APIs are useful, should they be split into syntax/symbols/ty layers or kept in one? **Deep/shallow expansion** Should intermediate macro expansion steps be visible in the API? If yes, should `.expansion()` be deep or shallow by default? **Eager macro expansion?** Find usages can't be implemented precisely without eagarly expanding all macros. So perhaps that our model should be that all macros are expanded eagerly, even those inside function calls? This is more of an implementation qustion. We also typically don't look for usages in libs, so being lazy&correct might be possible?

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

By clicking below, you agree to our terms of service.

Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
Wallet ( )
Connect another wallet

New to HackMD? Sign up

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