Repository: jinxdash/prettier-plugin-rust Branch: master Commit: 61dc16d002ba Files: 202 Total size: 764.2 KB Directory structure: gitextract_sexpc5gs/ ├── .github/ │ └── ISSUE_TEMPLATE/ │ ├── Bug_report.yml │ └── config.yml ├── .gitignore ├── .gitmodules ├── .npmrc ├── .vscode/ │ ├── launch.json │ └── settings.json ├── CHANGELOG.md ├── LICENSE ├── README.md ├── crate/ │ ├── Cargo.toml │ ├── README.md │ └── src/ │ └── main.rs ├── extension/ │ ├── LICENSE │ ├── README.md │ ├── package.json │ ├── src/ │ │ └── index.ts │ └── tsconfig.json ├── package.json ├── pnpm-workspace.yaml ├── scripts/ │ ├── build.ts │ ├── dev.format.ts │ ├── dev.repl.ts │ └── tsconfig.json ├── src/ │ ├── format/ │ │ ├── comments.ts │ │ ├── complexity.ts │ │ ├── core.ts │ │ ├── external.ts │ │ ├── plugin.ts │ │ ├── printer.ts │ │ └── styling.ts │ ├── index.ts │ ├── transform/ │ │ ├── custom/ │ │ │ ├── attribute.ts │ │ │ ├── cfg_if.ts │ │ │ └── utils.ts │ │ └── index.ts │ └── utils/ │ ├── common.ts │ └── debug.ts ├── tests/ │ ├── output/ │ │ ├── comments/ │ │ │ ├── assignment.f.rs │ │ │ ├── binaryish.f.rs │ │ │ ├── blocks.f.rs │ │ │ ├── chain.f.rs │ │ │ ├── closure.f.rs │ │ │ ├── dangling.f.rs │ │ │ ├── file.f.rs │ │ │ ├── flow.f.rs │ │ │ ├── functions.f.rs │ │ │ ├── ignore.attr.f.rs │ │ │ ├── ignore.f.rs │ │ │ ├── ignore.file.f.rs │ │ │ ├── imports.f.rs │ │ │ ├── macro.f.rs │ │ │ ├── multiple.f.rs │ │ │ ├── parens.f.rs │ │ │ └── whitespace.f.rs │ │ ├── common/ │ │ │ ├── arrays.f.rs │ │ │ ├── assignments.f.rs │ │ │ ├── binaryish.f.rs │ │ │ ├── chains.f.rs │ │ │ ├── chains.first-argument-expansion.f.rs │ │ │ ├── chains.last-argument-expansion.f.rs │ │ │ ├── closures.f.rs │ │ │ ├── destructuring.f.rs │ │ │ ├── members.f.rs │ │ │ └── types.f.rs │ │ ├── issues/ │ │ │ ├── 0.f.rs │ │ │ ├── 14.f.rs │ │ │ ├── 21/ │ │ │ │ ├── fn_comment.f.rs │ │ │ │ ├── fn_fn.f.rs │ │ │ │ ├── fn_ln.f.rs │ │ │ │ ├── ln_fn_ln.f.rs │ │ │ │ └── mod.f.rs │ │ │ ├── 22.f.rs │ │ │ ├── 25.f.rs │ │ │ ├── nth-pass.f.1.rs │ │ │ └── nth-pass.f.rs │ │ ├── macros/ │ │ │ ├── cfg_if.f.rs │ │ │ ├── if_chain.f.rs │ │ │ └── matches.f.rs │ │ └── styling/ │ │ ├── blockify.f.rs │ │ ├── canInlineBlockBody.f.rs │ │ ├── needsParens.f.rs │ │ └── needsSemi.f.rs │ ├── output-ext/ │ │ ├── errors/ │ │ │ └── foo.rs │ │ ├── expressions/ │ │ │ ├── block.f.rs │ │ │ ├── closure.f.rs │ │ │ ├── expr.f.rs │ │ │ ├── flow_expr.f.rs │ │ │ ├── ident.f.rs │ │ │ ├── literal.f.rs │ │ │ ├── match.f.rs │ │ │ ├── parens.f.rs │ │ │ ├── precedence.f.rs │ │ │ └── range.f.rs │ │ ├── features/ │ │ │ ├── arbitrary_enum_discriminant.f.rs │ │ │ ├── associated_type_bounds.f.rs │ │ │ ├── async_closure.f.rs │ │ │ ├── auto_traits.f.rs │ │ │ ├── const_generics_defaults.f.rs │ │ │ ├── const_trait_impl.f.rs │ │ │ ├── decl_macro.f.rs │ │ │ ├── destructuring_assignment.f.rs │ │ │ ├── generators.f.rs │ │ │ ├── if_let_guard.f.rs │ │ │ ├── inline_const.f.rs │ │ │ ├── inline_const_pat.f.rs │ │ │ ├── let_chains.f.rs │ │ │ ├── let_else.f.rs │ │ │ ├── negative_impls.f.rs │ │ │ └── trait_alias.f.rs │ │ ├── macro/ │ │ │ ├── attributes.f.rs │ │ │ ├── macro.invocation.f.rs │ │ │ ├── macro.item.f.rs │ │ │ ├── macro.match.f.rs │ │ │ ├── macro.tokens.f.rs │ │ │ └── macro.transform.f.rs │ │ ├── miscellaneous/ │ │ │ ├── ast-program-locs-attr-dangling.f.rs │ │ │ ├── ast-program-locs-attr.f.rs │ │ │ ├── ast-program-locs.f.rs │ │ │ ├── empty-attr-dangling-x.f.rs │ │ │ ├── empty-attr-dangling.f.rs │ │ │ ├── empty-attr-x.f.rs │ │ │ ├── empty-attr.f.rs │ │ │ ├── empty-comment-block-x.f.rs │ │ │ ├── empty-comment-block.f.rs │ │ │ ├── empty-comment-x.f.rs │ │ │ ├── empty-comment.f.rs │ │ │ ├── empty-doc-block-x.f.rs │ │ │ ├── empty-doc-block.f.rs │ │ │ ├── empty-doc-x.f.rs │ │ │ ├── empty-doc.f.rs │ │ │ ├── empty.f.rs │ │ │ ├── shebang-b.f.rs │ │ │ └── shebang.f.rs │ │ ├── patterns/ │ │ │ ├── pattern.f.rs │ │ │ ├── rest.f.rs │ │ │ └── union.f.rs │ │ ├── specifiers/ │ │ │ ├── extern.f.rs │ │ │ └── pub.f.rs │ │ ├── statements/ │ │ │ ├── const.f.rs │ │ │ ├── enum.f.rs │ │ │ ├── impl.f.rs │ │ │ ├── self.f.rs │ │ │ ├── spread.f.rs │ │ │ ├── statements.f.rs │ │ │ ├── static.f.rs │ │ │ ├── struct.f.rs │ │ │ ├── trait.f.rs │ │ │ ├── union.f.rs │ │ │ └── use.f.rs │ │ └── types/ │ │ ├── cast.f.rs │ │ ├── never.f.rs │ │ └── types.f.rs │ ├── print.ts │ ├── samples/ │ │ ├── comments/ │ │ │ ├── assignment.rs │ │ │ ├── binaryish.rs │ │ │ ├── blocks.rs │ │ │ ├── chain.rs │ │ │ ├── closure.rs │ │ │ ├── dangling.rs │ │ │ ├── file.rs │ │ │ ├── flow.rs │ │ │ ├── functions.rs │ │ │ ├── ignore.attr.rs │ │ │ ├── ignore.file.rs │ │ │ ├── ignore.rs │ │ │ ├── imports.rs │ │ │ ├── macro.rs │ │ │ ├── multiple.rs │ │ │ ├── parens.rs │ │ │ └── whitespace.rs │ │ ├── common/ │ │ │ ├── arrays.rs │ │ │ ├── assignments.rs │ │ │ ├── binaryish.rs │ │ │ ├── chains.first-argument-expansion.rs │ │ │ ├── chains.last-argument-expansion.rs │ │ │ ├── chains.rs │ │ │ ├── closures.rs │ │ │ ├── destructuring.rs │ │ │ ├── members.rs │ │ │ └── types.rs │ │ ├── issues/ │ │ │ ├── 0.rs │ │ │ ├── 14.rs │ │ │ ├── 21/ │ │ │ │ ├── fn_comment.rs │ │ │ │ ├── fn_fn.rs │ │ │ │ ├── fn_ln.rs │ │ │ │ ├── ln_fn_ln.rs │ │ │ │ └── mod.rs │ │ │ ├── 22.rs │ │ │ ├── 25.rs │ │ │ └── nth-pass.rs │ │ ├── macros/ │ │ │ ├── cfg_if.rs │ │ │ ├── if_chain.rs │ │ │ └── matches.rs │ │ └── styling/ │ │ ├── blockify.rs │ │ ├── canInlineBlockBody.rs │ │ ├── needsParens.rs │ │ └── needsSemi.rs │ └── test.build.ts ├── tsconfig.base.json ├── tsconfig.build.json └── tsconfig.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/ISSUE_TEMPLATE/Bug_report.yml ================================================ name: ✨ Formatting description: Issues for incorrect or unreadable code body: - type: textarea id: code attributes: label: Input code placeholder: Paste the input code here. render: rust validations: required: true - type: textarea id: output attributes: label: Output code placeholder: Paste the formatted code here. render: rust validations: required: true - type: textarea id: extra attributes: label: Additional context placeholder: Add other relevant context about the problem here. ================================================ FILE: .github/ISSUE_TEMPLATE/config.yml ================================================ contact_links: - name: Github discussion board url: https://github.com/jinxdash/prettier-plugin-rust/discussions about: Questions and answers blank_issues_enabled: true ================================================ FILE: .gitignore ================================================ # npm node_modules # cache /.rollup.cache/ *.tsbuildinfo # debug *.temp.* *.temp/ # repl /repl/ # build /index.* /extension/index.* *.vsix /crate/target ================================================ FILE: .gitmodules ================================================ [submodule "ext/jinx-rust"] path = ext/jinx-rust url = https://github.com/jinxdash/jinx-rust.git ================================================ FILE: .npmrc ================================================ link-workspace-packages = false ================================================ FILE: .vscode/launch.json ================================================ // A launch configuration that compiles the extension and then opens it inside a new window // Use IntelliSense to learn about possible attributes. // Hover to view descriptions of existing attributes. // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 { "version": "0.2.0", "configurations": [ { "args": ["--extensionDevelopmentPath=${workspaceFolder}/extension"], "name": "Launch Extension", "outFiles": ["${workspaceFolder}/extension/index.js"], "request": "launch", "type": "extensionHost" } ] } ================================================ FILE: .vscode/settings.json ================================================ { "npm.exclude": [ "**/ext/jinx-rust" ], "files.exclude": { "ext": true } } ================================================ FILE: CHANGELOG.md ================================================ # Prettier Rust Changelog ## Unreleased - fix: clear some issues related to formatting `#[attr]` like full-on expressions ([#25](jinxdash/prettier-plugin-rust/issues/25)) ## 0.1.9 - feat: format `cfg_if!` macros - feat: format `@` character in `macro_rules` - fix: format `.` and `e0` to float instead of int ([#14](https://github.com/jinxdash/prettier-plugin-rust/issues/14), [#16](https://github.com/jinxdash/prettier-plugin-rust/issues/16)) - fix: always end files with a newline ([#21](https://github.com/jinxdash/prettier-plugin-rust/issues/21)) - fix: avoid removing optional semi in rare [rust compiler bug](https://github.com/rust-lang/rust/issues/70844) ([#22](https://github.com/jinxdash/prettier-plugin-rust/issues/22)) ## 0.1.8 - feat(extension): display message when formatting fails due to non-parser errors. - feat: move `..spread`, `..` to the end of patterns and reassignments ([#7](https://github.com/jinxdash/prettier-plugin-rust/pull/7)) - fix: remove comma after `..` in patterns and reassignments ([#7](https://github.com/jinxdash/prettier-plugin-rust/pull/7)) - fix: support malformed `macro_rules!` ([jinx-rust@0.1.6](/jinxdash/jinx-rust/pull/2)) - fix: unprinted comment errors in failed macros ([#8](https://github.com/jinxdash/prettier-plugin-rust/pull/8)) ## 0.1.7 - feat: move `..spread` to the end of struct literals ([#6](https://github.com/jinxdash/prettier-plugin-rust/pull/6)) - fix: remove comma after `..spread` in struct literals ([#6](https://github.com/jinxdash/prettier-plugin-rust/pull/6)) ## 0.1.6 - fix: parenthesize >1 length `dyn`/`impl` types nested in unary types. ([#4](https://github.com/jinxdash/prettier-plugin-rust/pull/4)) - fix: remove comma after `match` cases with block-like macro expressions. ([#4](https://github.com/jinxdash/prettier-plugin-rust/pull/4)) ## 0.1.5 - feat: wrap non-block closure expressions with a block when a `->` ReturnType is defined - fix: add extension to filepath in ESM imports ([#2](https://github.com/jinxdash/prettier-plugin-rust/issues/2)) - fix: add missing whitespace in `let_else` feature - fix(extension): disable config caching ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2022-present jinxdash (https://github.com/jinxdash) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================
Prettier Rust

Prettier Rust

![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg) [![npm version](https://img.shields.io/npm/v/prettier-plugin-rust.svg?style=flat)](https://www.npmjs.com/package/prettier-plugin-rust) [![extension installs](https://img.shields.io/visual-studio-marketplace/i/jinxdash.prettier-rust?logo=visualstudiocode&style=social)](https://marketplace.visualstudio.com/items?itemName=jinxdash.prettier-rust) ![GitHub Repo stars](https://img.shields.io/github/stars/jinxdash/prettier-plugin-rust?style=social) [![Twitter Follow](https://img.shields.io/twitter/follow/jinxdash?style=social)](https://twitter.com/jinxdash) _The massively popular [Prettier](https://prettier.io/) code formatter, now with [Rust](https://www.rust-lang.org/) support!_ **Get Started:** Install [VSCode Extension](https://marketplace.visualstudio.com/items?itemName=jinxdash.prettier-rust) `Prettier - Code formatter (Rust)`
## Why Prettier? > What usually happens once people start using Prettier is that they realize how much time and mental energy they actually spend formatting their code. No matter how incomplete or broken the code you're working on is, with the Prettier Editor Extension you can always just press the `Format Document` key binding and \*poof\*, the code snaps right into place.
- **Beautiful, uniform and consistent** — Prettier is strongly opinionated, with no style options. - **There when you need it the most** — Prettier can format code that won't compile _(e.g. missing annotations)_ - **Speed up the day-to-day** — Prettier auto-fixes common syntax errors _(e.g. missing semicolons, blocks, parentheses)_
> input > formatted
```rs const LEET = 1337 /// My WIP code draft #![feature(crate_visibility_modifier)] async crate fn foo(arg) { arg.0 *= 3.14 + LEET & 1337 arg.1(|b, c| -> T &c).await } ``` ```rs const LEET = 1337; #![feature(crate_visibility_modifier)] /// My WIP code draft crate async fn foo(arg) { arg.0 *= (3.14 + LEET) & 1337; (arg.1)(|b, c| -> T { &c }).await } ```
_Formatting succeeds and fixes 7 syntax errors._

## Configuration https://prettier.io/docs/en/configuration ```json5 // .prettierrc.json { "useTabs": false, "tabWidth": 4, "printWidth": 100, "endOfLine": "lf", // -- Not supported yet -- // "trailingComma": "es5", // "embeddedLanguageFormatting": "auto", // Example override "overrides": { "files": ["tests/*.rs"], "options": { "printWidth": 80 } } } ```
See alternative configuration using a TOML file ```toml # .prettierrc.toml useTabs = false tabWidth = 4 printWidth = 100 endOfLine = "lf" # -- Not supported yet -- # trailingComma = "es5" # embeddedLanguageFormatting = "auto" # Example override overrides = [ { files = ["tests/*.rs"], options = { printWidth = 80 } } ] ```
### How to ignore things - Add `// prettier-ignore` or `#[rustfmt::skip]` above it - Add `#![rustfmt::skip]` inside blocks or files - Create a `.prettierignore` file to glob-match files, like `.gitignore` ### How are macros formatted? - Curlies `!{}` format like blocks, `![]` and `!()` like comma-separated expressions - Formatting inside macro invocations is more conservative, since macros can be token-sensitive - Popular/built-in macros with original syntax rules get custom formatting (e.g. `matches!`, `if_chains!`...) _[Not implemented yet]_ - Macro Declarations are only partially formatted (the transformed part isn't yet, but could be in the future) - Macros that can't be formatted are silently ignored ### Are nightly features supported? Yes! Prettier Rust formats most nightly features. Support depends on [`jinx-rust`](https://github.com/jinxdash/jinx-rust).
## Editor integration - ### `Recommended` Extension Standalone _Easy install + auto-updates_ - VSCode | Search and install `Prettier - Code formatter (Rust)` [[direct link]](https://marketplace.visualstudio.com/items?itemName=jinxdash.prettier-rust) - _Request your favorite editor:_ [[file an issue]](https://github.com/jinxdash/prettier-plugin-rust/issues/new) - ### `Alternative` Core Extension Plugin _Requires [NodeJS](https://nodejs.dev/download/) + [Prettier Extension](https://prettier.io/docs/en/editors.html)_ (built-in Jetbrains IDEs) ```sh npm install --global prettier-plugin-rust prettier ``` _Restart IDE after installing._ _To update (manual only!!):_ `npm upgrade --global prettier-plugin-rust prettier` _To check installed version:_ `npm ls -g --depth=0 prettier-plugin-rust prettier` _To check latest version:_ `npm info prettier-plugin-rust version`
## Project integration - ### Command line _Requires [NodeJS](https://nodejs.dev/download/)_ - Install `prettier` and `prettier-plugin-rust` globally ```sh npm install --global prettier-plugin-rust prettier ``` - Use the [prettier CLI](https://prettier.io/docs/en/cli.html) to format rust files. E.g. run: ```sh prettier --write **/*.rs ``` - ### NodeJS package _Requires [NodeJS](https://nodejs.dev/download/)_ - Install `prettier` and `prettier-plugin-rust` in the project ```sh npm install --save-dev prettier-plugin-rust prettier ``` - Link to the plugin's location in your prettier config: ```json "plugins": ["./node_modules/prettier-plugin-rust"] ``` - Use the [prettier CLI](https://prettier.io/docs/en/cli.html) to format rust files. E.g. run: ```sh npx prettier --write **/*.rs ``` - You can also use the plugin programmatically: ```ts import prettier from "prettier"; import * as rustPlugin from "prettier-plugin-rust"; prettier.format(code, { plugins: [rustPlugin] }); ``` - ### Rust crate _No crate yet. Above options are available in the meantime._
## Q&A - ### _Why would I use this and not the established `cargo fmt` ?_ _It's all about the Editor Integration_ — Having the ability to format your code while you work on it really makes for a great developer experience, and autocompletion for Rust's strict syntax is such a massive time save. Once you've tried the extension there really is no coming back. All-in-all the difference in code style is minimal, so adopting Prettier Rust won't drastically change your codebase. The real downside is the harsher integration with the Rust ecosystem, but it'll get better eventually. Point by point: - the extension streamlines your work in the editor - it can format code that won't compile _(e.g. code with missing type annotations)_ - it autocorrects syntax errors _(e.g. missing semicolons, blocks, parentheses...)_ - it is strongly opinionated with no style options, so code is uniform across projects. - it produces more readable code in some cases (e.g. condition chains, compound expressions, patterns) - it supports everything out-of-the-box (e.g. nightly features, macros) - it consistently prints code in the same way, whereas Rustfmt preserves arbitrary style at places - it can be used for other languages (e.g. markdown, html, typescript, java, python, ruby) - it formats language embeds. So rust code blocks in non-rust files (e.g. markdown), and supported languages in rust doc comments. _[NOTE: the latter is not yet implemented]_ - ### _Why not just add those features to rustfmt instead?_ Unfortunately Rustfmt cannot implement those features by design. Rustfmt parses code with rustc. Rustc is strict and unforgiving as it always assumes code is at its "final version", thus every slight deviation from the accepted syntax crashes the parser. There's also that rustc has many lint-like checks within the parser. The intention is to save work for the compiler down the line, unfortunately it also means that rustc sometimes fails to parse syntactically correct code. Prettier Rust however is based on [jinx-rust](https://github.com/jinxdash/jinx-rust). Jinx-rust is built specifically for Rust tooling. Hence it's designed to tolerate a wide range of syntax errors, supports missing nodes and sometimes even infers user intent (e.g. Javascript's `!==`) Jinx-rust has a little _plaidoyer_ in its readme arguing for Rust Tooling _not_ to use the official rustc parser [here](https://github.com/jinxdash/jinx-rust#why-jinx-rust-and-why-in-typescript). - ### _When exactly does Prettier Rust change code syntax?_ The Prettier Rust syntax autocorrection feature is intended to be an adaptation of how Prettier Typescript autocorrects javascript code with missing semicolons. You can effectively think of Prettier Rust syntax autocorrection as auto-applying the Rust compiler's suggested syntax fixes automatically (e.g. "semicolon missing here", "parenthesize this" or "add a block around that") Otherwise if your codebase compiles, then Prettier Rust is just a formatter like any other. It won't change the syntax of valid rust code. Moreover, it doesn't reorganize imports, split comments or combine attributes. - ### _This is an "opinionated formatter". But it's brand new! How reliable are those opinions?_ Rest assured, Prettier Rust actually does not take style decisions on its own. Prettier Rust is essentially a 1:1 adaptation of Prettier Typescript, hence the opinions it implements have been battle tested and agreed-upon by [millions and millions of users](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) already. ================================================ FILE: crate/Cargo.toml ================================================ [package] name = "prettier" version = "0.1.5" edition = "2021" readme = "README.md" license = "MIT" description = "Opinionated code formatter - `cargo fmt` alternative (Community) (WIP)" repository = "https://github.com/jinxdash/prettier-plugin-rust" keywords = ["format", "rustfmt", "tool", "development", "editor"] categories = ["development-tools", "text-editors", "web-programming"] # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] ================================================ FILE: crate/README.md ================================================ # Prettier crate _Reserved_ (August 2022) https://github.com/jinxdash/prettier-plugin-rust - _(todo) Crate provides Prettier CLI_ - _(todo) Rust binding for `prettier.format`_ - _(todo) Configuration and version-control of prettier and its plugins from `Cargo.toml`_ ================================================ FILE: crate/src/main.rs ================================================ fn main() { println!("Hello, world!"); } ================================================ FILE: extension/LICENSE ================================================ MIT License Copyright (c) 2022-present jinxdash (https://github.com/jinxdash) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: extension/README.md ================================================
Prettier Rust

Prettier Rust

![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg) [![npm version](https://img.shields.io/npm/v/prettier-plugin-rust.svg?style=flat)](https://www.npmjs.com/package/prettier-plugin-rust) ![GitHub Repo stars](https://img.shields.io/github/stars/jinxdash/prettier-plugin-rust?style=social) [![Twitter Follow](https://img.shields.io/twitter/follow/jinxdash?style=social)](https://twitter.com/jinxdash) _The massively popular [Prettier](https://prettier.io/) code formatter, now with [Rust](https://www.rust-lang.org/) support!_ _This extension is a standalone bundle of Prettier + Prettier Plugin Rust._
## Why Prettier? > What usually happens once people start using Prettier is that they realize how much time and mental energy they actually spend formatting their code. No matter how incomplete or broken the code you're working on is, with the Prettier Editor Extension you can always just press the `Format Document` key binding and \*poof\*, the code snaps right into place.
- **Beautiful, uniform and consistent** — Prettier is strongly opinionated, with no style options. - **There when you need it the most** — Prettier can format code that won't compile _(e.g. missing annotations)_ - **Speed up the day-to-day** — Prettier auto-fixes common syntax errors _(e.g. missing semicolons, blocks, parentheses)_
> input > formatted
```rs const LEET = 1337 /// My WIP code draft #![feature(crate_visibility_modifier)] async crate fn foo(arg) { arg.0 *= 3.14 + LEET & 1337 arg.1(|b, c| -> T &c).await } ``` ```rs const LEET = 1337; #![feature(crate_visibility_modifier)] /// My WIP code draft crate async fn foo(arg) { arg.0 *= (3.14 + LEET) & 1337; (arg.1)(|b, c| -> T { &c }).await } ```
_Formatting succeeds and fixes 7 syntax errors._

## Configuration https://prettier.io/docs/en/configuration ```json5 // .prettierrc.json { "useTabs": false, "tabWidth": 4, "printWidth": 100, "endOfLine": "lf", // -- Not supported yet -- // "trailingComma": "es5", // "embeddedLanguageFormatting": "auto", // Example override "overrides": { "files": ["tests/*.rs"], "options": { "printWidth": 80 } } } ```
Alternative config using TOML ```toml # .prettierrc.toml useTabs = false tabWidth = 4 printWidth = 100 endOfLine = "lf" # -- Not supported yet -- # trailingComma = "es5" # embeddedLanguageFormatting = "auto" # Example override overrides = [ { files = ["tests/*.rs"], options = { printWidth = 80 } } ] ```
### How to ignore things - Add `// prettier-ignore` or `#[rustfmt::skip]` above it - Add `#![rustfmt::skip]` inside blocks or files - Create a `.prettierignore` file to glob-match files, like `.gitignore` ### How are macros formatted? - Curlies `!{}` format like blocks, `![]` and `!()` like comma-separated expressions - Formatting inside macro invocations is more conservative, since macros can be token-sensitive - Popular/built-in macros with original syntax rules get custom formatting (e.g. `matches!`, `if_chains!`...) _[Not implemented yet]_ - Macro Declarations are only partially formatted (the transformed part isn't yet, but could be in the future) - Macros that can't be formatted are silently ignored ### Are nightly features supported? Yes! Prettier Rust formats most nightly features. Support depends on [`jinx-rust`](https://github.com/jinxdash/jinx-rust).
## Project integration - ### Command line _Requires [NodeJS](https://nodejs.dev/download/)_ - Install `prettier` and `prettier-plugin-rust` globally ```sh npm install --global prettier-plugin-rust prettier ``` - Use the [prettier CLI](https://prettier.io/docs/en/cli.html) to format rust files. E.g. run: ```sh prettier --write **/*.rs ``` - ### NodeJS package _Requires [NodeJS](https://nodejs.dev/download/)_ - Install `prettier` and `prettier-plugin-rust` in the project ```sh npm install --save-dev prettier-plugin-rust prettier ``` - Link to the plugin's location in your prettier config: ```json "plugins": ["./node_modules/prettier-plugin-rust"] ``` - Use the [prettier CLI](https://prettier.io/docs/en/cli.html) to format rust files. E.g. run: ```sh npx prettier --write **/*.rs ``` - ### Rust crate _No crate yet. Above options are available in the meantime._
## Q&A - ### _Why would I use this and not the established `cargo fmt` ?_ _It's all about the Editor Integration_ — Having the ability to format your code while you work on it really makes for a great developer experience, and autocompletion for Rust's strict syntax is such a massive time save. Once you've tried the extension there really is no coming back. All-in-all the difference in code style is minimal, so adopting Prettier Rust won't drastically change your codebase. The real downside is the harsher integration with the Rust ecosystem, but it'll get better eventually. Point by point: - the extension streamlines your work in the editor - it can format code that won't compile _(e.g. code with missing type annotations)_ - it autocorrects syntax errors _(e.g. missing semicolons, blocks, parentheses...)_ - it is strongly opinionated with no style options, so code is uniform across projects. - it produces more readable code in some cases (e.g. condition chains, compound expressions, patterns) - it supports everything out-of-the-box (e.g. nightly features, macros) - it consistently prints code in the same way, whereas Rustfmt preserves arbitrary style at places - it can be used for other languages (e.g. markdown, html, typescript, java, python, ruby) - it formats language embeds. So rust code blocks in non-rust files (e.g. markdown), and supported languages in rust doc comments. _[NOTE: the latter is not yet implemented]_ - ### _Why not just add those features to rustfmt instead?_ Unfortunately Rustfmt cannot implement those features by design. Rustfmt parses code with rustc. Rustc is strict and unforgiving as it always assumes code is at its "final version", thus every slight deviation from the accepted syntax crashes the parser. There's also that rustc has many lint-like checks within the parser. The intention is to save work for the compiler down the line, unfortunately it also means that rustc sometimes fails to parse syntactically correct code. Prettier Rust however is based on [jinx-rust](https://github.com/jinxdash/jinx-rust). Jinx-rust is built specifically for Rust tooling. Hence it's designed to tolerate a wide range of syntax errors, supports missing nodes and sometimes even infers user intent (e.g. Javascript's `!==`) Jinx-rust has a little *plaidoyer* in its readme arguing for Rust Tooling *not* to use the official rustc parser [here](https://github.com/jinxdash/jinx-rust#why-jinx-rust-and-why-in-typescript). - ### _When exactly does Prettier Rust change code syntax?_ The Prettier Rust syntax autocorrection feature is intended to be an adaptation of how Prettier Typescript autocorrects javascript code with missing semicolons. You can effectively think of Prettier Rust syntax autocorrection as auto-applying the Rust compiler's suggested syntax fixes automatically (e.g. "semicolon missing here", "parenthesize this" or "add a block around that") Otherwise if your codebase compiles, then Prettier Rust is just a formatter like any other. It won't change the syntax of valid rust code. Moreover, it doesn't reorganize imports, split comments or combine attributes. - ### _This is an "opinionated formatter". But it's brand new! How reliable are those opinions?_ Rest assured, Prettier Rust actually does not take style decisions on its own. Prettier Rust is essentially a 1:1 adaptation of Prettier Typescript, hence the opinions it implements have been battle tested and agreed-upon by [millions and millions of users](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) already. ================================================ FILE: extension/package.json ================================================ { "icon": "icon.png", "name": "prettier-rust", "publisher": "jinxdash", "displayName": "Prettier - Code formatter (Rust)", "description": "Prettier Rust is a code formatter that autocorrects bad syntax", "repository": { "type": "git", "url": "https://github.com/jinxdash/prettier-plugin-rust.git", "directory": "extension" }, "author": "jinxdash (https://github.com/jinxdash)", "version": "0.1.9", "engines": { "vscode": "^1.69.0" }, "categories": [ "Formatters" ], "keywords": [ "rust", "formatter", "prettier" ], "scripts": { "bundle": "esbuild src/index.ts --bundle --outfile=index.js --format=cjs --platform=node --external:vscode", "watch": "pnpm run bundle --watch", "package": "pnpm run bundle && pnpm vsce package --no-dependencies", "publish": "pnpm vsce publish --no-dependencies" }, "contributes": { "languages": [ { "id": "rust", "aliases": [ "rs" ], "extensions": [ "rs" ] } ] }, "devDependencies": { "@types/node": "^18.0.6", "@types/vscode": "^1.69.0", "esbuild": "^0.14.49", "typescript": "^4.7.4" }, "dependencies": { "prettier": "^2.7.1", "jinx-rust": "0.1.6", "prettier-plugin-rust": "workspace:prettier-plugin-rust" }, "main": "index.js", "activationEvents": [ "onStartupFinished" ] } ================================================ FILE: extension/src/index.ts ================================================ import { rs } from "jinx-rust"; import path from "node:path"; import prettier, { Config, resolveConfig } from "prettier"; import plugin from "prettier-plugin-rust"; import { ExtensionContext, languages, Position, Range, TextDocument, TextEdit, window } from "vscode"; const console = createOutputChannel("Prettier (Rust)"); console.log(`VSCode Extension: ${process.env.EXTENSION_NAME || "jinxdash.prettier-rust"}@${process.env.EXTENSION_VERSION || "dev"}`); export async function activate(context: ExtensionContext) { context.subscriptions.push( languages.registerDocumentFormattingEditProvider("rust", { async provideDocumentFormattingEdits(document) { const config: Config = { filepath: cmd(document.fileName), ...((await resolveConfig(document.fileName, { editorconfig: true, useCache: false })) ?? {}), }; console.log("", `# Formatting using prettier@${prettier.version}`, { ...config, plugins: config.plugins?.flatMap((p) => (typeof p === "string" ? p : p.printers && Object.keys(p.printers))), }); if ( !config.plugins?.some((plugin) => typeof plugin === "object" && plugin.languages?.some((lang) => lang.name === "Rust")) ) { config.parser = "jinx-rust"; config.plugins ??= [plugin]; } return format(document, config); }, }) ); } function format(document: TextDocument, config: Config) { // length of common prefix const next = tryFormat(document, config); const prev = document.getText(); if (prev === next) { // console.log("No changes"); return []; } const end = Math.min(prev.length, next.length); var i = 0; var j = 0; for (var i = 0; i < end && compare(i, i); ++i); for (var j = 0; i + j < end && compare(prev.length - j - 1, next.length - j - 1); ++j); // console.log([i, j]); return [TextEdit.replace(new Range(document.positionAt(i), document.positionAt(prev.length - j)), next.substring(i, next.length - j))]; function compare(i: number, j: number) { return prev.charCodeAt(i) === next.charCodeAt(j); } } function tryFormat(doc: TextDocument, config: prettier.Config) { try { return prettier.format(doc.getText(), config); } catch (e) { if ((e as any).loc) { try { rs.parseFile(doc.getText(), { filepath: config.filepath }); } catch (_e) { const e2 = _e as rs.ParserError; const pos = new Position(e2.loc.start.line - 1, e2.loc.start.column - 1); window.showTextDocument(doc, { selection: new Range(pos, pos) }); window.showErrorMessage(e2.message); } } else { console.log(e); window.showErrorMessage((e as any).message); } return doc.getText(); } } function createOutputChannel(name: string) { const out = window.createOutputChannel(name); return { log(...arr: any[]) { for (var item of arr) { if (typeof item === "string") { out.appendLine(unstyle(item)); } else if (item instanceof Error) { if (item?.message) out.appendLine(unstyle(item.message)); if (item?.stack) out.appendLine(unstyle(item.stack)); } else { out.appendLine(JSON.stringify(item, null, 2)); } } }, }; } function unstyle(str: string) { return str.replace(/\x1B\[[0-9][0-9]?m/g, ""); } function cmd(filepath: string | undefined, frompath = "") { return normPath(path.relative(frompath, normPath(filepath ?? ""))) || "."; } function normPath(filepath: string) { return filepath.replace(/^file:\/\/\//, "").replace(/\\\\?/g, "/"); } ================================================ FILE: extension/tsconfig.json ================================================ { "extends": "../tsconfig.base.json", "compilerOptions": { "rootDir": "src" }, "include": ["src"] } ================================================ FILE: package.json ================================================ { "name": "prettier-plugin-rust", "version": "0.1.9", "description": "Prettier plugin for Rust", "repository": { "type": "git", "url": "https://github.com/jinxdash/prettier-plugin-rust.git" }, "author": "jinxdash (https://github.com/jinxdash)", "keywords": [ "prettier", "formatter", "rust" ], "license": "MIT", "type": "module", "main": "index.cjs", "module": "index.js", "types": "index.d.ts", "exports": { "./package.json": "./package.json", ".": { "require": "./index.cjs", "import": "./index.js" } }, "files": [ "index.js", "index.cjs", "index.d.ts", "package.json", "LICENSE" ], "scripts": { "build": "ts-node ./scripts/build.ts && ts-node ./tests/test.build.ts", "test-build": "ts-node ./tests/test.build.ts", "test-print-samples": "ts-node ./tests/print.ts", "dev-repl": "ts-node ./scripts/dev.repl.ts", "dev-format-local": "ts-node ./scripts/dev.format.ts" }, "devDependencies": { "@swc/core": "^1.2.248", "@types/node": "^18.0.6", "@types/prettier": "^2.7.0", "ts-node": "^10.9.1", "tsup": "^6.2.3", "typescript": "^4.8.2" }, "dependencies": { "jinx-rust": "0.1.6", "prettier": "^2.7.1" }, "prettier": { "printWidth": 140, "semi": true, "tabWidth": 4, "useTabs": true, "endOfLine": "lf", "overrides": [ { "files": [ "**/*.md" ], "options": { "printWidth": 80, "useTabs": false, "tabWidth": 2 } } ] } } ================================================ FILE: pnpm-workspace.yaml ================================================ packages: - 'ext/*' - 'extension' ================================================ FILE: scripts/build.ts ================================================ import { build } from "tsup"; import { createStripPlugin } from "../ext/jinx-rust/scripts/utils/build"; await build({ dts: true, tsconfig: "tsconfig.build.json", entry: ["src/index.ts"], external: ["jinx-rust"], outDir: ".", format: ["cjs", "esm"], plugins: [createStripPlugin({ labels: ["__DEV__"], functionCalls: ["devonly"] })], treeshake: { preset: "smallest", moduleSideEffects: false, propertyReadSideEffects: false, tryCatchDeoptimization: false, unknownGlobalSideEffects: false, }, }); ================================================ FILE: scripts/dev.format.ts ================================================ import prettier from "prettier"; import { for_each_rs_file } from "../ext/jinx-rust/scripts/utils/common"; import { update_file } from "../ext/jinx-rust/scripts/utils/fs"; import { plugin } from "../src/format/plugin"; function format(code: string, filepath: string) { const next = prettier.format(code, { parser: "jinx-rust", plugins: [plugin], printWidth: 100, tabWidth: 4, filepath, }); if (code !== next && code.trim() !== next.trim()) { update_file(filepath, next, { external: true }); } } globalThis.TESTS_FORMAT_DEV = true; for_each_rs_file( [`E:/dev/github/rust/rust-lang/`], (file) => { format(file.content, file.cmd); }, ["test", "tests"] ).then(() => { globalThis.TESTS_FORMAT_DEV = false; }); ================================================ FILE: scripts/dev.repl.ts ================================================ import { createASTtoJSONPrinter, createPrettierPrinter, rs_createREPL } from "../ext/jinx-rust/scripts/utils"; import { plugin } from "../src/format/plugin"; rs_createREPL([ createPrettierPrinter( { parser: "jinx-rust", plugins: [plugin], }, true ), createASTtoJSONPrinter(), ]); ================================================ FILE: scripts/tsconfig.json ================================================ { "extends": "../tsconfig.base.json", "include": ["../tests", "../scripts"], "references": [{ "path": "../tsconfig.json" }, { "path": "../ext/jinx-rust/scripts/tsconfig.json" }], "compilerOptions": { "rootDir": ".." } } ================================================ FILE: src/format/comments.ts ================================================ import { CommentOrDocComment, LocArray, Node, NodeType, NodeWithBodyOrCases } from "jinx-rust"; import { end, getBodyOrCases, getLastParameter, hasOuterAttributes, isInner, is_Attribute, is_AttributeOrDocComment, is_BlockCommentKind, is_BlockCommentNode, is_Comment, is_CommentOrDocComment, is_ExpressionWithBodyOrCases, is_ExternSpecifier, is_FlowControlExpression, is_FunctionDeclaration, is_FunctionNode, is_IfBlockExpression, is_LineCommentKind, is_LineCommentNode, is_LocArray, is_MacroRule, is_NodeWithBodyOrCases, is_ReassignmentNode, is_StatementNode, is_StructLiteralProperty, is_StructLiteralPropertySpread, nisAnyOf, ownStart, start, } from "jinx-rust/utils"; import { is_CallExpression_or_CallLikeMacroInvocation } from "../transform"; import { Narrow, assert, exit, iLast, last_of, maybe_last_of } from "../utils/common"; import { is_MemberAccessLike, is_xVariableEqualishLike } from "./core"; import { AnyComment, CustomOptions, DCM, Doc, MutatedAttribute, NodeWithComments, PrettierCommentInfo, breakParent, cursor, hardline, indent, join, line, lineSuffix, literalline, } from "./external"; import { assertPathAtNode, canAttachComment, getAllComments, getContext, getNode, getOptions, pathCallEach } from "./plugin"; import { shouldPrintOuterAttributesAbove } from "./styling"; function addCommentHelper(node: Node, comment: AnyComment, leading = false, trailing = false) { __DEV__: assert(!handled(comment)); ((node as NodeWithComments).comments ??= []).push(comment); (comment.leading = leading), (comment.trailing = trailing), (comment.printed = false); } function addLeadingComment(node: Node, comment: AnyComment) { addCommentHelper(node, comment, true); } function addDanglingComment(node: Node, comment: AnyComment, marker: DCM) { addCommentHelper(node, comment); comment.marker = marker; } function addTrailingComment(node: Node, comment: AnyComment) { addCommentHelper(node, comment, false, true); } export function setPrettierIgnoreTarget(node: Node, comment: AnyComment) { __DEV__: Narrow(node), assert(isPrettierIgnoreComment(comment) || isPrettierIgnoreAttribute(comment)); comment.unignore = true; node.prettierIgnore = true; } function hasComments(node: T): node is NodeWithComments { return "comments" in node && node.comments.length > 0; } export function printDanglingComments(enclosingNode: Node, sameIndent: boolean, marker?: DCM) { if (hasComments(enclosingNode)) { const printed: Doc[] = []; pathCallEach(enclosingNode, "comments", (comment) => { if (isDangling(comment) && (!marker || comment.marker === marker)) { printed.push(printComment(comment)); } }); if (printed.length > 0) { return sameIndent // ? join(hardline, printed) : indent([hardline, join(hardline, printed)]); } } return ""; } export function needsHardlineAfterDanglingComment(node: Node) { if (!hasComment(node)) return false; const lastDanglingComment = maybe_last_of(getComments(node, CF.Dangling)); return lastDanglingComment && is_LineCommentNode(lastDanglingComment); } export function setDidPrintComment(comment: AnyComment) { comment.printed = true; } function printComment(comment: AnyComment) { __DEV__: assertPathAtNode("printComment", comment); __DEV__: assert(handled(comment), `Assertion failed: Comment was not printed at ${comment.loc.url()}`, comment); setDidPrintComment(comment); return getContext().options.printer.printComment!(getContext().path as any, getOptions()); } export function isPreviousLineEmpty(node: Node) { let index = start(node) - 1; index = skipSpaces(index, true) as number; index = skipNewline(index, true) as number; index = skipSpaces(index, true) as number; return index !== skipNewline(index, true); } export function hasBreaklineBefore(node: Node) { return hasNewline(start(node) - 1, true); } export function hasBreaklineAfter(node: Node) { return hasNewline(end(node)); } export function printCommentsSeparately(ignored?: Set) { const node = getNode(); __DEV__: Narrow(node); const leading: Doc[] = []; const trailing: Doc[] = []; let hasTrailingLineComment = false; let hadLeadingBlockComment = false; if ("comments" in node) { pathCallEach(node, "comments", (comment) => { if (ignored?.has(comment)) { return; } else if (isLeading(comment)) { leading.push(printLeadingComment(comment)); } else if (isTrailing(comment)) { trailing.push(printTrailingComment(comment)); } }); } if (node === getOptions().cursorNode) { leading.unshift(cursor); trailing.push(cursor); } return (leading.length | trailing.length) > 0 ? { leading, trailing } : ({ leading: "", trailing: "" } as const); function printLeadingComment(comment: AnyComment) { if (is_Attribute(comment) && !comment.inner) { const printed = printComment(comment); return [printed, " "]; } hadLeadingBlockComment ||= is_BlockCommentKind(comment) && hasBreaklineBefore(comment); return [ printComment(comment), is_BlockCommentKind(comment) ? hasBreaklineAfter(comment) // ? hadLeadingBlockComment ? hardline : line : " " : hardline, hasNewline(skipNewline(skipSpaces(end(comment)))) ? hardline : "", ]; } function printTrailingComment(comment: AnyComment) { const printed = printComment(comment); return hasBreaklineBefore(comment) ? lineSuffix([hardline, isPreviousLineEmpty(comment) ? hardline : "", printed]) : is_BlockCommentNode(comment) ? [" ", printed] : lineSuffix([" ", printed, hasTrailingLineComment === (hasTrailingLineComment = true) ? hardline : breakParent]); } } export function getPostLeadingComment(comment: AnyComment) { // console.log(comment.loc.url()); // is_BlockCommentKind(comment) // ? hasBreaklineAfter(comment) // // ? hasBreaklineBefore(comment) // ? hardline // : line // : " " // : hardline, return hasNewline(skipNewline(skipSpaces(end(comment)))) ? hardline : ""; } export function withComments(node: Node, printed: D, ignored?: Set): D | Doc[] { __DEV__: assertPathAtNode("withComments", node); const { leading, trailing } = printCommentsSeparately(ignored); return leading || trailing ? [...leading!, printed, ...trailing!] : printed; // return needsOuterParens(node) ? group(["(", indent([softline, parts]), softline, ")"]) : parts; // return parts; } export function getComments(node: Node, ...args: Parameters): AnyComment[] { __DEV__: Narrow(node); // if (!node || !node.comments) return []; // if (args.length === 0) return node.comments; // return args.length > 0 ? node.comments.filter(getCommentTestFunction(...args)) : node.comments; return node && node.comments // ? args.length > 0 ? node.comments.filter(getCommentTestFunction(...args)) : node.comments : []; } export function getFirstComment(node: Node, flags: CF, fn?: (comment: AnyComment) => boolean): AnyComment | undefined { const r = getComments(node, flags | CF.First, fn); return r.length === 0 ? undefined : r[0]; } export function escapeComments(flags: number, fn?: (comment: AnyComment) => boolean) { const comments = getAllComments().filter(getCommentTestFunction(flags, fn)) as AnyComment[]; comments.forEach(setDidPrintComment); return new Set(comments); } export const enum CF { Leading = 1 << 1, Trailing = 1 << 2, Dangling = 1 << 3, Block = 1 << 4, Line = 1 << 5, PrettierIgnore = 1 << 6, First = 1 << 7, Last = 1 << 8, } export function isPrettierIgnoreComment(comment: AnyComment) { return is_Comment(comment) && /^\s*prettier-ignore\s*/.test(comment.value) && !comment.unignore; } export function isPrettierIgnoreAttribute(node: Node): node is MutatedAttribute { return is_Attribute(node) && /^\s*rustfmt::skip\s*$/.test(node.value); } function getCommentTestFunction(flags: CF, fn?: (comment: AnyComment) => boolean) { return function (comment: AnyComment, index: number, comments: AnyComment[]) { __DEV__: Narrow(flags), assert(handled(comment)); return !( (flags & CF.Leading && !isLeading(comment)) || (flags & CF.Trailing && !isTrailing(comment)) || (flags & CF.Dangling && !isDangling(comment)) || (flags & CF.Block && !is_BlockCommentKind(comment)) || (flags & CF.Line && !is_LineCommentKind(comment)) || (flags & CF.First && index !== 0) || (flags & CF.Last && !iLast(index, comments)) || (flags & CF.PrettierIgnore && !(isPrettierIgnoreComment(comment) || isPrettierIgnoreAttribute(comment))) || (fn && !fn(comment)) ); }; } export function hasComment(node: Node, flags: number = 0, fn?: (comment: AnyComment) => boolean) { if ("comments" in node && node.comments!.length > 0) { return flags || fn ? (node.comments as AnyComment[]).some(getCommentTestFunction(flags, fn)) : true; } return false; } export function hasNewlineInRange(leftIndex: number, rightIndex: number) { __DEV__: assert(leftIndex <= rightIndex); const text = getContext().options.originalText; for (var i = leftIndex; i < rightIndex; ++i) if (text.charCodeAt(i) === 10) return true; return false; } export function isNextLineEmpty(node: Node) { return isNextLineEmptyAfterIndex(end(node)); } export function isNextLineEmptyAfterIndex(index: number | false) { let oldIdx: number | false = -1; let idx: number | false = index; while (idx !== oldIdx) { oldIdx = idx; idx = skipToLineEnd(idx); idx = skipBlockComment(idx); idx = skipSpaces(idx); idx = skipParens(idx); } idx = skipLineComment(idx); idx = skipParens(idx); idx = skipNewline(idx); idx = skipParens(idx); return idx !== false && hasNewline(idx); } export function hasNewline(index: number | false, backwards = false) { if (index === false) return false; const i = skipSpaces(index, backwards); return i !== false && i !== skipNewline(i, backwards); } function skipLineComment(index: number | false) { if (index === false) return false; const { commentSpans, originalText } = getContext().options; if (commentSpans.has(index) && originalText.charCodeAt(index + 1) === 47 /** "/" */) return skipEverythingButNewLine(commentSpans.get(index)!); return index; } function skipBlockComment(index: number | false) { if (index === false) return false; const { commentSpans, originalText } = getContext().options; if (commentSpans.has(index) && originalText.charCodeAt(index + 1) === 42 /** "*" */) return commentSpans.get(index)!; return index; } const [skipSpaces, skipToLineEnd, skipEverythingButNewLine] = [/[ \t]/, /[,; \t]/, /[^\r\n]/].map(function (re) { return function (index: number | false, backwards = false) { if (index === false) return false; const { originalText: text } = getContext().options; let cursor = index; while (cursor >= 0 && cursor < text.length) { if (re.test(text.charAt(cursor))) backwards ? cursor-- : cursor++; else return cursor; } return cursor === -1 || cursor === text.length ? cursor : false; }; }); function skipNewline(index: number | false, backwards = false) { if (index === false) return false; const { originalText } = getContext().options; const atIndex = originalText.charCodeAt(index); if (backwards) { if (originalText.charCodeAt(index - 1) === 13 && atIndex === 10) return index - 2; if (atIndex === 10) return index - 1; } else { if (atIndex === 13 && originalText.charCodeAt(index + 1) === 10) return index + 2; if (atIndex === 10) return index + 1; } return index; } function skipParens(index: number | false, backwards = false) { return index; // if (index === false) return false; // const { parensPositions } = getContext().options; // while (parensPositions.has(index)) backwards ? index-- : index++; // return index; } export function getNextNonSpaceNonCommentCharacterIndex(node: Node) { return getNextNonSpaceNonCommentCharacterIndexWithStartIndex(end(node)); } function getNextNonSpaceNonCommentCharacterIndexWithStartIndex(i: number) { let oldIdx = -1; let nextIdx = i; while (nextIdx !== oldIdx) { oldIdx = nextIdx; nextIdx = skipSpaces(nextIdx) as number; nextIdx = skipBlockComment(nextIdx) as number; nextIdx = skipLineComment(nextIdx) as number; nextIdx = skipNewline(nextIdx) as number; nextIdx = skipParens(nextIdx) as number; } return nextIdx; } export function getNextNonSpaceNonCommentCharacter(node: Node) { return getContext().options.originalText.charAt(getNextNonSpaceNonCommentCharacterIndex(node)); } interface CommentContext { comment: AnyComment; precedingNode: Node | undefined; enclosingNode: Node | undefined; followingNode: Node | undefined; text: string; options: CustomOptions; ast: Node; isLastComment: boolean; } function handled(comment: AnyComment) { return "printed" in comment; } function handleCommon(ctx: CommentContext): boolean { { const { comment, precedingNode, enclosingNode, followingNode } = ctx; if (!enclosingNode) { ctx.enclosingNode = ctx.comment.loc.src.program; } else if (enclosingNode && is_NodeWithBodyOrCases(enclosingNode)) { const body = getBodyOrCases(enclosingNode); if (body) { if (is_ExpressionWithBodyOrCases(enclosingNode) && enclosingNode.label) { if (ctx.precedingNode === enclosingNode.label) { ctx.precedingNode = undefined; } if (followingNode === enclosingNode.label) { ctx.followingNode = undefined; } } if (comment.loc.isBefore(body)) { if (followingNode && body.loc.contains(followingNode)) { ctx.followingNode = undefined; } if (!ctx.precedingNode && !ctx.followingNode) { addLeadingComment(enclosingNode, comment); return true; } } else if (comment.loc.isAfter(body)) { if (precedingNode && body.loc.contains(precedingNode)) { ctx.precedingNode = undefined; } if (!ctx.precedingNode && !ctx.followingNode) { addTrailingComment(enclosingNode, comment); return true; } } else if (body.loc.contains(comment)) { if (precedingNode && !body.loc.contains(precedingNode)) { ctx.precedingNode = undefined; } if (followingNode && !body.loc.contains(followingNode)) { ctx.followingNode = undefined; } } } } } for (const fn of [ handleMixedInOuterAttributeComments, handleAttributeComments, handleDanglingComments, handleFunctionComments, handleMacroRuleComments, handleStructLiteralComments, handleVariableDeclaratorComments, handleIfBlockExpressionComments, handleMemberExpressionComments, handleStatementComments, handleFlowControlComments, handleBadComments, ]) { fn(ctx); if (handled(ctx.comment)) { // console.log(ctx.comment.loc.url(), fn.name); return true; } } const { precedingNode, followingNode, comment } = ctx; if (isStartOfLine(comment)) { if (followingNode) { addLeadingComment(followingNode, comment); } else if (precedingNode) { addTrailingComment(precedingNode, comment); } else { exit.never(ctx); } } else if (isEndOfLine(comment)) { if (precedingNode) { addTrailingComment(precedingNode, comment); } else if (followingNode) { addLeadingComment(followingNode, comment); } else { exit.never(ctx); } } else { if (precedingNode && followingNode) { return false; } else if (precedingNode) { addTrailingComment(precedingNode, comment); } else if (followingNode) { addLeadingComment(followingNode, comment); } else { exit.never(ctx); } } return handled(ctx.comment); } export function handleOwnLineComment(ctx: CommentContext) { return handleCommon(ctx); } export function handleEndOfLineComment(ctx: CommentContext) { const { precedingNode, enclosingNode, comment } = ctx; if ( // handleCallExpressionComments precedingNode && enclosingNode && is_CallExpression_or_CallLikeMacroInvocation(enclosingNode) && enclosingNode.arguments.length > 0 && precedingNode === (enclosingNode.typeArguments ? last_of(enclosingNode.typeArguments) : enclosingNode.callee) ) { addLeadingComment(enclosingNode.arguments[0], comment); return true; } else if ( // handlePropertyComments enclosingNode && is_StructLiteralProperty(enclosingNode) ) { addLeadingComment(enclosingNode, comment); return true; } else { return handleCommon(ctx); } } export function handleRemainingComment(ctx: CommentContext) { return handleCommon(ctx); } function handleStructLiteralComments({ enclosingNode, followingNode, comment }: CommentContext) { if (enclosingNode && is_StructLiteralPropertySpread(enclosingNode) && followingNode === enclosingNode.expression) { addLeadingComment(enclosingNode, comment); } } function handleVariableDeclaratorComments({ enclosingNode, followingNode, comment }: CommentContext) { if ( enclosingNode && (is_xVariableEqualishLike(enclosingNode) || is_ReassignmentNode(enclosingNode)) && followingNode && (is_BlockCommentKind(comment) || nisAnyOf(followingNode, [ NodeType.StructLiteral, NodeType.StructPattern, NodeType.TupleLiteral, NodeType.TypeTuple, NodeType.TuplePattern, NodeType.ArrayLiteral, NodeType.ArrayPattern, NodeType.SizedArrayLiteral, NodeType.TypeSizedArray, ])) ) { addLeadingComment(followingNode, comment); } } function handleMixedInOuterAttributeComments({ precedingNode, enclosingNode, followingNode, comment }: CommentContext) { if (enclosingNode && hasOuterAttributes(enclosingNode) && end(comment) <= ownStart(enclosingNode)) { if (isPrettierIgnoreComment(comment) || isPrettierIgnoreAttribute(comment)) { setPrettierIgnoreTarget(enclosingNode, comment); } if (isEndOfLine(comment)) { __DEV__: assert(!!precedingNode && is_Attribute(precedingNode), "", precedingNode); if (shouldPrintOuterAttributesAbove(enclosingNode)) { // #[attr] // comment // node addTrailingComment(precedingNode, comment); } else { // #[attr] /* comment */ node addLeadingComment(followingNode || enclosingNode, comment); } } else { // __DEV__: assert(isStartOfLine(comment)); if (followingNode && end(followingNode) <= ownStart(enclosingNode)) { addLeadingComment(followingNode, comment); } else if (precedingNode && enclosingNode.loc.contains(precedingNode)) { addTrailingComment(precedingNode, comment); } else { addLeadingComment(enclosingNode, comment); } } } } function handleAttributeComments({ precedingNode, enclosingNode, followingNode, comment, ast }: CommentContext) { if (is_AttributeOrDocComment(comment)) { if ( comment.inner && enclosingNode && is_FunctionDeclaration(enclosingNode) && (!followingNode || !is_StatementNode(followingNode)) && (!precedingNode || !is_StatementNode(precedingNode)) ) { if (enclosingNode.body) { if (canAttachCommentInLocArray(enclosingNode.body)) { addDanglingComment(enclosingNode, comment, DCM["body"]); } else { addLeadingComment(enclosingNode.body[0], comment); } } else { addLeadingComment(enclosingNode, comment); } } else { // if (comment.loc.url().startsWith("tests/samples/macro/attr.rs") && getContext().options.danglingAttributes.includes(comment)) { // // debugger; // console.log({ // comment: comment.loc.url(), // precedingNode: precedingNode?.loc.url(), // enclosingNode: enclosingNode?.loc.url(), // followingNode: followingNode?.loc.url(), // }); // } if (followingNode) { addLeadingComment(followingNode, comment); } else if (enclosingNode) { for (var key in DCM) if (key in enclosingNode) { addDanglingComment(enclosingNode, comment, key as DCM); return; } } else { addDanglingComment(ast, comment, DCM["body"]); } } } } function handleBadComments({ precedingNode, enclosingNode, followingNode, ast, comment }: CommentContext) { if (!enclosingNode) { // console.log(comment.loc.url()); if (followingNode) { addLeadingComment(followingNode, comment); } else if (precedingNode) { addTrailingComment(precedingNode, comment); } else { addDanglingComment(enclosingNode || ast, comment, DCM["body"]); } } else if (!precedingNode && !followingNode) { if (enclosingNode && enclosingNode !== ast) { addLeadingComment(enclosingNode, comment); } else { addDanglingComment(ast, comment, DCM["body"]); } } } function is_ABI_Comment({ precedingNode, enclosingNode, comment }: CommentContext) { return ( is_CommentOrDocComment(comment) && ((precedingNode && is_ExternSpecifier(precedingNode)) || (enclosingNode && is_ExternSpecifier(enclosingNode))) ); } function handleFlowControlComments({ precedingNode, enclosingNode, followingNode, comment }: CommentContext) { if (enclosingNode && is_FlowControlExpression(enclosingNode)) { if (!precedingNode && (isOwnLine(comment) || isEndOfLine(comment)) && !followingNode) { addLeadingComment(enclosingNode, comment); } } } function handleFunctionComments(ctx: CommentContext) { const { precedingNode, enclosingNode, followingNode, comment } = ctx; if (enclosingNode && is_FunctionNode(enclosingNode)) { if ( is_FunctionDeclaration(enclosingNode) && ((!is_ABI_Comment(ctx) && comment.loc.isBefore(enclosingNode.generics || enclosingNode.id)) || (enclosingNode.generics && comment.loc.isBetween(enclosingNode.generics, enclosingNode.parameters))) ) { addLeadingComment(enclosingNode, comment); } else if ( !enclosingNode.returnType && comment.loc.isBetween( enclosingNode.parameters, is_FunctionDeclaration(enclosingNode) ? enclosingNode.body! : enclosingNode.expression ) ) { if (is_FunctionDeclaration(enclosingNode)) { addCommentToBlock(enclosingNode, comment); } else { addLeadingComment(enclosingNode.expression, comment); } } else if ( precedingNode && // enclosingNode.parameters.loc.contains(comment) ) { if (precedingNode === getLastParameter(enclosingNode)) { addTrailingComment(precedingNode, comment); } } else if ( followingNode && isStartOfLine(comment) && comment.loc.isAfter(enclosingNode.parameters) && (!is_FunctionDeclaration(enclosingNode) || !enclosingNode.whereBounds || comment.loc.isAfter(enclosingNode.whereBounds!)) && (!enclosingNode.returnType || comment.loc.isAfter(enclosingNode.returnType)) && followingNode === (is_FunctionDeclaration(enclosingNode) ? enclosingNode.body?.[0] : enclosingNode.expression) ) { addLeadingComment(followingNode, comment); } } } function handleMacroRuleComments(ctx: CommentContext) { const { precedingNode, enclosingNode, followingNode, comment } = ctx; if (enclosingNode && is_MacroRule(enclosingNode)) { if (enclosingNode.transform.loc.contains(comment)) { __DEV__: assert(enclosingNode.transform.length > 0); if (!precedingNode || !enclosingNode.transform.loc.contains(precedingNode)) { __DEV__: assert(!!followingNode && enclosingNode.transform.loc.contains(followingNode)); addLeadingComment(followingNode, comment); } } else if (enclosingNode.match.loc.contains(comment)) { __DEV__: assert(enclosingNode.match.length > 0); if (!followingNode || !enclosingNode.match.loc.contains(followingNode)) { __DEV__: assert(!!precedingNode && enclosingNode.match.loc.contains(precedingNode)); addTrailingComment(precedingNode!, comment); } } } } function handleStatementComments(ctx: CommentContext) { const { precedingNode, comment } = ctx; if (isEndOfLine(comment) && precedingNode && (is_StatementNode(precedingNode) || precedingNode.loc.sliceText().endsWith(";"))) { addTrailingComment(precedingNode, comment); } } function addCommentToBlock(block: NodeWithBodyOrCases, comment: AnyComment) { const body = getBodyOrCases(block); __DEV__: assert(!!body); if (body.length > 0) { addLeadingComment(body![0], comment); } else { addDanglingComment(block, comment, DCM["body"]); } } function handleIfBlockExpressionComments(ctx: CommentContext) { const { comment, enclosingNode } = ctx; if (enclosingNode && is_IfBlockExpression(enclosingNode)) { const { condition, body, else: else_ } = enclosingNode; if (comment.loc.isBefore(condition)) { addLeadingComment(condition, comment); } else if (comment.loc.isBetween(condition, body)) { addTrailingComment(condition, comment); } else if (else_ && comment.loc.isBetween(body, else_)) { if (is_IfBlockExpression(else_)) { addLeadingComment(else_.condition, comment); } else { addCommentToBlock(else_, comment); } } } } function handleMemberExpressionComments({ comment, precedingNode, enclosingNode }: CommentContext) { if (enclosingNode && is_MemberAccessLike(enclosingNode)) { if (isStartOfLine(comment) || !precedingNode) addLeadingComment(enclosingNode, comment); else addTrailingComment(precedingNode, comment); return true; } return false; } function handleDanglingComments({ comment, enclosingNode }: CommentContext) { if (enclosingNode) { for (var key in DCM) { if (key in enclosingNode) { var arr: LocArray = enclosingNode[key]; if (is_LocArray(arr) && canAttachCommentInLocArray(arr) && arr.loc.contains(comment)) { addDanglingComment(enclosingNode, comment, key as DCM); return; } } } } } function canAttachCommentInLocArray(arr: LocArray) { return arr.length === 0 || arr.every((node) => !canAttachComment(node)); } function isOwnLine(comment: AnyComment) { return isStartOfLine(comment) && hasBreaklineAfter(comment); } function isStartOfLine(comment: AnyComment) { return comment.placement === "ownLine"; } function isEndOfLine(comment: AnyComment) { return comment.placement === "endOfLine"; } export function isDangling(comment: AnyComment) { __DEV__: assert(handled(comment)); return !comment.leading && !comment.trailing; } export function isLeading(comment: AnyComment) { __DEV__: assert(handled(comment)); return comment.leading && !comment.trailing; } export function isTrailing(comment: AnyComment) { __DEV__: assert(handled(comment)); return !comment.leading && comment.trailing; } export function print_comment(comment: CommentOrDocComment) { __DEV__: Narrow(comment); const doc = is_BlockCommentNode(comment) ? isIndentableBlockComment(comment.value) ? [ (!handled(comment) || isTrailing(comment)) && !hasBreaklineBefore(comment) ? hardline : "", getCommentStart(comment), ...comment.value.split(/\n/g).map((line, i, a) => i === 0 // ? [line.trimEnd(), hardline] : !iLast(i, a) ? [" " + line.trim(), hardline] : " " + line.trimStart() ), "*/", ] : [ getCommentStart(comment), // join(literalline, comment.value.split(/\n/g)), "*/", ] : [getCommentStart(comment), comment.value.trimEnd()]; return handled(comment) && isDangling(comment) // ? [doc, getPostLeadingComment(comment)] : doc; function getCommentStart(comment: CommentOrDocComment) { return is_Comment(comment) ? is_BlockCommentKind(comment) ? "/*" : "//" : is_BlockCommentKind(comment) ? isInner(comment) ? "/*!" : "/**" : isInner(comment) ? "//!" : "///"; } function isIndentableBlockComment(value: string) { const lines = `*${value}*`.split(/\n/g); return lines.length > 1 && lines.every((line) => /^\s*\*/.test(line)); } } ================================================ FILE: src/format/complexity.ts ================================================ import { ForLtParametersBody, FunctionSpread, GenericParameterDeclaration, MaybeGenericArgsTarget, MissingNode, Node, NodeType, TypeBound, TypeBoundsConstaint, TypeCallArgument, TypeNamespaceTargetNoSelector, TypeNode, } from "jinx-rust"; import { getAstPath, getOwnChildAstPath, is_BareTypeTraitBound, is_FunctionSpread, is_LetScrutinee, is_Literal, is_MissingNode, is_TypeBoundsStandaloneNode, is_TypeFunctionNode, is_TypeNode, is_VariableDeclarationNode, } from "jinx-rust/utils"; import { exit, has_key_defined, last_of, spliceAll } from "../utils/common"; import { canBreak } from "./external"; import { getContext, getNode, getOptions, getPrintFn } from "./plugin"; let DEPTH = 0; const ANCESTRY: Node[] = []; const LONE_SHORT_ARGUMENT_THRESHOLD_RATE = 0.25; export function withCheckContext(fn: () => R): R { if (0 === DEPTH) { return fn(); } else { DEPTH = 0; const prev = spliceAll(ANCESTRY); try { return fn(); } finally { DEPTH = ANCESTRY.push(...prev); } } } export function is_short(str: string) { return str.length <= LONE_SHORT_ARGUMENT_THRESHOLD_RATE * getOptions().printWidth; } function print(target: Node) { const current = getNode(); const keys: (string | number)[] = [...getAstPath(ANCESTRY[0], getNode())]; for (let i = 1; i < ANCESTRY.length; i++) keys.push(...getOwnChildAstPath(ANCESTRY[i - 1], ANCESTRY[i])); keys.push(...getOwnChildAstPath(last_of(ANCESTRY), target)); try { return getContext().path.call(() => getPrintFn(target)(), ...keys); } catch (e) { console.log({ current, target, keys, ANCESTRY }); throw e; } } function IsSimpleFunction(fn: (node: T) => boolean): (node: T) => boolean { return function (node: T) { if (0 !== DEPTH && node === ANCESTRY[DEPTH - 1]) { return fn(node); } if (DEPTH >= 2) { return isShortBasic(node); } try { return fn((ANCESTRY[DEPTH++] = node) as any); } finally { ANCESTRY.length = --DEPTH; } } as any; } function HasComplexFunction(fn: (node: T) => boolean): (node: T) => boolean { return function (node: T) { if (0 !== DEPTH && node === ANCESTRY[DEPTH - 1]) { return fn(node); } if (DEPTH >= 2) { return !isShortBasic(node); } try { return fn((ANCESTRY[DEPTH++] = node) as any); } finally { ANCESTRY.length = --DEPTH; } } as any; } const isShortBasic = (node: Node) => { switch (node.nodeType) { case NodeType.MissingNode: return true; case NodeType.Identifier: case NodeType.Index: case NodeType.LtIdentifier: case NodeType.LbIdentifier: case NodeType.McIdentifier: return is_short(node.name); case NodeType.Literal: return is_short(node.value) && !/\n/.test(node.value); } return false; }; export const isSimpleType = IsSimpleFunction((node): boolean => { switch (node.nodeType) { case NodeType.MissingNode: case NodeType.FunctionSpread: return true; case NodeType.MacroInvocation: return false; case NodeType.Identifier: case NodeType.TypeNever: case NodeType.TypeInferred: return true; case NodeType.TypePath: return isShortBasic(node.segment) && (!node.namespace || isSimpleType(node.namespace)); case NodeType.TypeCall: return isSimpleType(node.typeCallee) && !hasComplexTypeArguments(node); case NodeType.ExpressionTypeSelector: return isSimpleType(node.typeTarget) && (!node.typeExpression || isSimpleType(node.typeExpression)); case NodeType.TypeDynBounds: return !hasComplexTypeBounds(node); case NodeType.TypeImplBounds: return !hasComplexTypeBounds(node); case NodeType.TypeFnPointer: { const param = node.parameters[0]; return ( (!node.extern || !node.extern.abi || isShortBasic(node.extern.abi)) && !hasComplexLtParameters(node) && (node.parameters.length === 0 || (node.parameters.length === 1 && (is_FunctionSpread(param) || (!is_TypeFunctionNode(param.typeAnnotation) && isSimpleType(param.typeAnnotation))))) && (!node.returnType || isSimpleType(node.returnType)) ); } case NodeType.TypeFunction: return isSimpleType(node.callee) && node.parameters.every(isSimpleType) && (!node.returnType || isSimpleType(node.returnType)); case NodeType.TypeSizedArray: return isSimpleType(node.typeExpression) && isShortBasic(node.sizeExpression); case NodeType.TypeSlice: return isSimpleType(node.typeExpression); case NodeType.TypeTuple: return node.items.length === 0 || (node.items.length === 1 && isSimpleType(node.items[0])); case NodeType.TypeReference: case NodeType.TypeDereferenceMut: case NodeType.TypeDereferenceConst: case NodeType.TypeParenthesized: return isSimpleType(node.typeExpression); default: __DEV__: exit.never(node); return false; } }); export const hasComplexTypeBounds = HasComplexFunction>((node) => { return !!node.typeBounds && node.typeBounds.length > 1 && !node.typeBounds.every(isSimpleTypeBound); }); export const isSimpleTypeBound = (node: TypeBound): boolean => { switch (node.nodeType) { case NodeType.TypeParenthesized: return isSimpleTypeBound(node.typeExpression); // #Lifetime case NodeType.LtIdentifier: case NodeType.LtElided: case NodeType.LtStatic: return true; case NodeType.TypeTraitBound: return is_BareTypeTraitBound(node) && isSimpleTypeNamespaceTargetNoSelector(node.typeExpression); default: __DEV__: exit.never(node); return false; } function isSimpleTypeNamespaceTargetNoSelector(node: TypeNamespaceTargetNoSelector): boolean { switch (node.nodeType) { case NodeType.Identifier: return true; case NodeType.TypePath: return undefined === node.namespace || isSimpleTypeNamespaceTargetNoSelector(node.namespace); case NodeType.TypeCall: return false; case NodeType.TypeFunction: return isSimpleTypeNamespaceTargetNoSelector(node.callee) && node.parameters.length === 0 && !node.returnType; default: __DEV__: exit.never(node); return false; } } }; const isSimpleTypeArgument = IsSimpleFunction((node) => { if (is_TypeNode(node)) { return isSimpleType(node); } switch (node.nodeType) { // #Lifetime case NodeType.LtIdentifier: case NodeType.LtElided: case NodeType.LtStatic: case NodeType.Literal: return true; case NodeType.MinusExpression: return is_Literal(node.expression); case NodeType.BlockExpression: return false; //willBreak(getPrintFn(node)("body")); case NodeType.TypeCallNamedArgument: return isSimpleType(node.typeExpression); case NodeType.TypeCallNamedBound: return isSimpleType(node.typeTarget) && !hasComplexTypeBounds(node); default: __DEV__: exit.never(node); return false; } }); export const hasComplexTypeArguments = HasComplexFunction>((node) => !node.typeArguments || node.typeArguments.length === 0 ? false : node.typeArguments.length === 1 ? (() => { const arg = node.typeArguments[0]; return is_TypeBoundsStandaloneNode(arg) || canBreak(print(arg)); })() : true ); export const hasComplexLtParameters = HasComplexFunction>((node) => { const ltParameters = node.ltParameters; if (!ltParameters || ltParameters.length === 0) { return false; } if (ltParameters.length === 1) { const arg = ltParameters[0]; if (arg.ltBounds && arg.ltBounds.length > 1) { return true; } return false; } return true; }); export const isShortGenericParameterDeclaration = IsSimpleFunction((node) => { switch (node.nodeType) { case NodeType.GenericTypeParameterDeclaration: return !node.typeBounds && !node.typeDefault; case NodeType.ConstTypeParameterDeclaration: return (!node.typeAnnotation || is_MissingNode(node)) && !node.typeDefault; case NodeType.GenericLtParameterDeclaration: return !node.ltBounds; default: exit.never(); } }); export const hasComplexGenerics = HasComplexFunction((node) => { return has_key_defined(node, "generics") && node.generics.length > 0 && !node.generics.every(isShortGenericParameterDeclaration); }); export const hasComplexTypeAnnotation = HasComplexFunction((node) => { if (is_VariableDeclarationNode(node) && !is_LetScrutinee(node)) { const { typeAnnotation } = node; return !!typeAnnotation && !is_MissingNode(typeAnnotation) && !isSimpleType(typeAnnotation); } else { return false; } }); ================================================ FILE: src/format/core.ts ================================================ import { AndExpression, AttributeOrDocComment, BreakExpression, CallExpression, ClosureFunctionExpression, ComparisonExpression, DeclarationNode, DelimKind, EnumDeclaration, ExpressionBody, ExpressionNode, ExpressionPath, ExpressionWithBody, ForLtParametersBody, FunctionDeclaration, FunctionLike, FunctionNode, IfBlockExpression, ImplDeclaration, LeftRightExpression, LocArray, MacroDeclaration, MacroGroup, MacroInlineRuleDeclaration, MacroMatchSegment, MacroRuleDeclaration, MacroRulesDeclaration, MatchExpression, MatchExpressionCase, MaybeBlockBody, MaybeGenericArgsTarget, MaybeHasLtBounds, MaybeReturnTypeConstraint, MaybeTypeAnnotationTarget, MemberExpression, NegativeImplDeclaration, Node, NodeType, NodeWithBodyOrCases, NodeWithCondition, ObjectNode, OperationExpression, OrExpression, PathNode, PatternBody, PatternNode, PunctuationToken, RangeNode, RestPattern, ReturnExpression, StructDeclaration, StructLiteral, StructLiteralPropertySpread, StructLiteralRestUnassigned, TK, TraitAliasDeclaration, TraitDeclaration, TupleStructDeclaration, TypeAliasDeclaration, TypeBoundsConstaint, TypeFunctionNode, UnaryExpression, UnionDeclaration, UnionPattern, WhileBlockExpression, YieldExpression, } from "jinx-rust"; import { DelimChars, end, getBodyOrCases, getDelimChars, getParameters, hasAttributes, hasCondition, hasItems, hasLetScrutineeCondition, hasParameters, hasProperties, hasSelfParameter, hasSemiNoBody, hasSemiNoProperties, hasTypeBounds, is_ArrayOrTupleLiteral, is_Attribute, is_ClosureBlock, is_ClosureFunctionExpression, is_DelimGroup, is_ElseBlock, is_EnumMemberStructDeclaration, is_ExpressionAsTypeCast, is_ExpressionNode, is_ExpressionPath, is_ExpressionStatement, is_ExpressionTypeCast, is_ExpressionWithBodyOrCases, is_FlowControlExpression, is_FunctionDeclaration, is_FunctionParameterDeclaration, is_GenericParameterDeclaration, is_Identifier, is_IdentifierOrIndex, is_IfBlockExpression, is_ImplDeclarationNode, is_LetScrutinee, is_LineCommentNode, is_Literal, is_LiteralBooleanLike, is_LiteralNumberLike, is_LiteralStringLike, is_LogicalExpression, is_MacroGroup, is_MacroInlineRuleDeclaration, is_MacroInvocation, is_MacroParameterDeclaration, is_MatchExpression, is_MatchExpressionCase, is_MemberExpression, is_MinusExpression, is_MissingNode, is_NodeWithBodyOrCases, is_OrExpression, is_PostfixExpression, is_Program, is_PunctuationToken, is_RangeLiteral, is_RangePattern, is_ReassignmentExpression, is_ReassignmentNode, is_RestPattern, is_SourceFile, is_StructDeclaration, is_StructLiteral, is_StructLiteralProperty, is_StructLiteralPropertySpread, is_StructPattern, is_StructPatternPropertyDestructured, is_StructProperty, is_TupleLiteral, is_TupleNode, is_TuplePattern, is_TupleStructDeclaration, is_TypeCallNamedArgument, is_TypeTuple, is_UnaryExpression, is_UnionDeclaration, is_UnwrapExpression, is_VariableDeclarationNode, ownStart, start, } from "jinx-rust/utils"; import { BlockLikeMacroInvocation, CallLikeMacroInvocation, is_CallExpression_or_CallLikeMacroInvocation } from "../transform"; import { AssertTypesEq, Identity, Map_get, Narrow, assert, exit, find_last, flat, iLast, last_of, spread } from "../utils/common"; import { CF, getFirstComment, getNextNonSpaceNonCommentCharacterIndex, hasBreaklineBefore, hasComment, hasNewline, hasNewlineInRange, isNextLineEmpty, isNextLineEmptyAfterIndex, isPreviousLineEmpty, printCommentsSeparately, printDanglingComments, withComments, } from "./comments"; import { hasComplexGenerics, hasComplexLtParameters, hasComplexTypeAnnotation, hasComplexTypeArguments, hasComplexTypeBounds, isShortGenericParameterDeclaration, is_short, } from "./complexity"; import { AstPath, DCM, Doc, align, breakParent, canBreak, cleanDoc, conditionalGroup, dedentToRoot, fill, getDocParts, group, hardline, ifBreak, indent, indentIfBreak, isConcat, join, label, line, lineSuffixBoundary, removeLines, softline, willBreak, } from "./external"; import { f, getContext, getGrandParentNode, getNode, getOptions, getParentNode, getPrintFn, is_printing_macro, pathCall, pathCallEach, print, } from "./plugin"; import { canInlineBlockBody, emptyContent, needsParens, shouldFlatten } from "./styling"; export function isNoopExpressionStatement(node: Node) { return is_ExpressionStatement(node) && undefined === node.expression && !hasAttributes(node) && !hasComment(node); } export function getLastNotNoopExpressionStatement(parent: MaybeBlockBody) { return parent.body && find_last(parent.body, (stmt) => !isNoopExpressionStatement(stmt)); } export function is_xVariableEqualishLike(node: Node) { switch (node.nodeType) { case NodeType.LetScrutinee: case NodeType.LetVariableDeclaration: case NodeType.ConstVariableDeclaration: case NodeType.StaticVariableDeclaration: case NodeType.TypeAliasDeclaration: case NodeType.TraitAliasDeclaration: return true; default: return false; } } export function is_BinaryishExpression(node: Node): node is OrExpression | AndExpression | OperationExpression | ComparisonExpression { switch (node.nodeType) { case NodeType.OrExpression: case NodeType.AndExpression: case NodeType.OperationExpression: case NodeType.ComparisonExpression: return true; default: return false; } } export type StructSpread = StructLiteralPropertySpread | StructLiteralRestUnassigned | RestPattern; export function is_StructSpread(node: Node): node is StructSpread { switch (node.nodeType) { case NodeType.StructLiteralPropertySpread: case NodeType.StructLiteralRestUnassigned: case NodeType.RestPattern: return true; default: return false; } } type ArrayLikeNode = Exclude, UnionPattern>; function isConciselyPrintedArray(node: ArrayLikeNode) { return ( node.items.length > 1 && (node.items as Node[]).every( (element) => (is_LiteralNumberLike(element) || (is_MinusExpression(element) && is_LiteralNumberLike(element.expression) && !hasComment(element.expression))) && !hasComment(element, CF.Trailing | CF.Line, (comment) => !hasBreaklineBefore(comment)) ) ); } export function printCommentsInsideEmptyArray(path: AstPath) { const node = path.getValue(); if (hasComment(node, CF.Dangling)) { return [printDanglingComments(node, false, DCM["items"]), softline]; } else { return ""; } } export function printNumber(rawNumber: string) { return rawNumber .toLowerCase() .replace(/^([\d.]+e)(?:\+|(-))?0*(\d)/, "$1$2$3") .replace(/^(\d+)e[+-]?0+$/, "$1.0") .replace(/^([\d.]+)e[+-]?0+$/, "$1") .replace(/\.(\d+?)0+(?=e|$)/, ".$1") .replace(/\.(?=e|$)/, ".0"); } export function printOnOwnLine(node: Node, printed: Doc) { return [printed, maybeEmptyLine(node)]; } export function maybeEmptyLine(node: Node) { return isNextLineEmpty(node) ? [hardline, hardline] : hardline; } export function printBodyOrCases(print: print, node: T) { // Note: Inner Attributes are inserted into body/cases (see "./transform.ts") // Example: { #[OUTER] #![INNER] 0 }; body: ["#[OUTER] 0", "#![INNER]"] const p: { node: Node; doc: Doc }[] = []; if (is_MatchExpression(node)) { __DEV__: Narrow>(print); pathCallEach(node as Extract, "cases", (mCase) => { p.push({ node: mCase, doc: is_MatchExpressionCase(mCase) && !is_ExpressionWithBodyOrCases(mCase.expression) ? [print(), ","] : print(), }); }); } else { __DEV__: Narrow>(node); pathCallEach(node as Extract, "body", (stmt) => { if (!isNoopExpressionStatement(stmt)) { p.push({ node: stmt, doc: print() }); } }); } const printed: Doc[] = bumpInnerAttributes(p).map(({ doc, node }, i, a) => iLast(i, a) ? group(doc) : printOnOwnLine(node, group(doc)) ); const comments = printDanglingCommentsForInline(node, DCM["body"]); if (comments) printed.push(comments); const ccomments = printDanglingCommentsForInline(node, DCM["cases"]); if (ccomments) printed.push(ccomments); if (is_Program(node) && is_SourceFile(getParentNode(node)!) && printed.length > 0 && !comments) { printed.push(hardline); } return printed; function bumpInnerAttributes(arr: { node: Node; doc: Doc }[]) { return arr.sort((a, b) => ownStart(a.node) - ownStart(b.node)); } } export function printMacroRules(print: print, node: T) { return !Array.isArray(node.rules) ? print("rules") : node.rules.length > 0 ? [" {", indent([hardline, ...print.join("rules", (rule) => maybeEmptyLine(rule))]), hardline, "}"] : [" {", printDanglingCommentsForInline(node, DCM["rules"]) || emptyContent(node), "}"]; } function is_unary_token(item: MacroMatchSegment | undefined) { switch (item && is_PunctuationToken(item) ? item.tk : TK.None) { case TK["-"]: case TK["*"]: case TK["&"]: case TK["#"]: case TK["!"]: case TK["~"]: return true; case TK["?"]: return !/\s/.test(getOptions().originalText.charAt(end(item!))); default: return false; } } function can_unary(node: MacroMatchSegment) { return (!is_PunctuationToken(node) || is_unary_token(node)) && (!is_MacroGroup(node) || is_optional_unary(node)); } function is_optional_token(item: MacroMatchSegment | undefined): item is MacroGroup & { segments: [PunctuationToken] } { return !!item && is_MacroGroup(item) && item.kind === "?" && item.segments.length === 1 && is_PunctuationToken(item.segments[0]); } function is_optional_unary(item: MacroMatchSegment | undefined) { return is_optional_token(item) && is_unary_token(item.segments[0]); } function is_optional_segment(item: Node): item is MacroGroup { return is_MacroGroup(item) && item.kind === "?"; } export function printRuleMatch(print: print, rule: T) { // "", ".", "&&", "||", "=", "+", "-", "*", "/", "%", "&", "|", "^", "<<", ">>", "==", "!=", ">", ">=", "<", "<=", "+=", "-=", "*=", "/=", // "%=", "&=", "|=", "^=", "<<=", ">>=", "$", "@", "_", "..", "...", "..=", ",", ";", ":", "::", "#", "?", "!", "=>", "->", "~" return print_map(rule, "match"); type ArrProps = { [K in keyof T]: NonNullable extends readonly any[] ? T[K] & unknown[] : never }; function print_map & keyof typeof DCM>(node: T, property: K) { __DEV__: assert(property in DCM); const arr = node[property as any] as LocArray; const shouldHug = should_hug(arr); const dline = arr.dk === DelimKind["{}"] ? line : shouldHug ? "" /* : is_MacroGroup(node) && node.kind !== "?" ? hardline */ : softline; const isParamsLike = is_params_like(arr); const shouldBreak = should_break(arr); const d = getDelimChars(arr); if (arr.length === 0) return [d.left, printDanglingCommentsForInline(node, DCM[property]), d.right]; const printed = flat(print.map_join(property as any, print_item, join_item)); // const printed = flat(print.map_join(property as any, print_item, join_item)) // .reduce( // (arr, doc, i, a) => { // last_of(arr).push(doc); // if (doc === line && (a[i - 1] === "," || a[i - 1] === ";")) arr.push([]); // return arr; // }, // [[]] as Doc[][] // ) // .map((grp) => group(grp)); return group([d.left, !dline ? printed : [indent([dline, printed]), dline], d.right], { shouldBreak, id: getMacroGroupId(node), }); function should_hug(arr: LocArray) { if (node === (rule as any)) return false; let has_nonToken = false; return arr.every((item) => !is_MacroGroup(item) && (is_PunctuationToken(item) || has_nonToken !== (has_nonToken = true))); } function should_break(arr: LocArray) { let has_decl = false; return arr.some( (item, i, a) => (is_match_any(item) && arr.length !== 1) || (!iLast(i, a) && isDeclStart(item, a[i + 1]) && has_decl === (has_decl = true)) ); } function print_item(item: MacroMatchSegment, index: number, arr: MacroMatchSegment[]) { switch (item.nodeType) { case NodeType.Identifier: case NodeType.LtIdentifier: case NodeType.Literal: case NodeType.PunctuationToken: case NodeType.MacroParameterDeclaration: return print(); case NodeType.MacroGroup: Narrow>(print); return printComments(["$", print_map(item, "segments"), print("sep"), item.kind]); case NodeType.DelimGroup: return printComments(print_map(item, "segments")); } __DEV__: exit.never(); function printComments(doc: Doc) { const printed = withComments(item, doc); const comment = getFirstComment(item, CF.Leading | CF.Line); return comment && index !== 0 ? isPreviousLineEmpty(comment) && typeof join_item(arr[index - 1], item, index === 1 ? undefined : arr[index - 2]) === "string" ? [hardline, hardline, printed] : [hardline, printed] : printed; } } function is_params_like(arr: MacroMatchSegment[]) { return arr.some(function isComma(item) { switch (item.nodeType) { case NodeType.PunctuationToken: return TK[","] === item.tk; case NodeType.MacroGroup: return (!!item.sep && isComma(item.sep)) || is_params_like(item.segments); } }); } function join_item(item: MacroMatchSegment, next: MacroMatchSegment, prev: MacroMatchSegment | undefined) { if (is_PunctuationToken(item)) { switch (item.tk) { case TK[","]: case TK[";"]: return line; case TK["::"]: case TK[".."]: case TK["..."]: case TK["."]: case TK["#"]: return ""; case TK["!"]: if (prev && is_ident(prev) && is_DelimGroup(next)) { return next.segments.dk === DelimKind["{}"] ? " " : ""; } break; case TK["@"]: return is_ident(next) && (!prev || is_MacroGroup(prev) || is_DelimGroup(prev)) ? "" : " "; } return is_unary_token(item) && // (!prev || !is_ident(prev)) && can_unary(next) ? "" : " "; } switch (is_PunctuationToken(next) ? next.tk : TK.None) { case TK[","]: case TK[";"]: case TK[":"]: case TK["::"]: case TK[".."]: case TK["..."]: case TK["."]: return ""; case TK["!"]: if (is_ident(item)) { return ""; } } if (is_match_any(item)) { return line; } { const sep_tk = is_MacroGroup(item) && item.sep && is_PunctuationToken(item.sep) ? item.sep.tk : TK.None; switch (sep_tk) { case TK["::"]: case TK["."]: return ""; // $(...)::* | $(...).* case TK[","]: case TK[";"]: return sep_tk === maybe_tk(next) ? ifBreak(line, " ", { groupId: getMacroGroupId(item) }) : line; } } if (is_optional_token(item)) { switch (item.segments[0].tk) { case TK["+"]: case TK["|"]: return " "; case TK["::"]: return ""; } if (is_unary_token(item.segments[0])) { return ""; } } if (is_DelimGroup(item) || is_MacroGroup(item)) { if (item.segments.dk === DelimKind["{}"]) { return line; } if (is_MacroGroup(item) && item.segments.length === 2) { const { 0: left, 1: right } = item.segments; if (is_PunctuationToken(left) && is_DelimGroup(right) && left.tk === TK["#"] && right.segments.dk === DelimKind["[]"]) { return hardline; } } return isParamsLike || is_tk(next) ? " " : line; } const next_1 = next !== last_of(arr) && arr[arr.indexOf(next) + 1]; if (is_ident(item) && is_DelimGroup(next) && next.segments.dk === DelimKind["()"]) { if (!next_1 || !is_match_any(next_1)) { return ""; } } if (is_match_any(next) && (!is_DelimGroup(next) || (next_1 && is_match_any(next_1)))) { return line; } // if (is_ident(item) && !is_ident(next) && !(is_DelimGroup(next) && next.segments.dk === DelimKind["{}"])) { // const next_1 = arr[arr.indexOf(next) + 1]; // if (next_1 && typeof join_item(next, next_1, item) === "object") { // return line; // } // } return " "; } } function is_ident(item: MacroMatchSegment) { switch (item.nodeType) { case NodeType.Identifier: return true; case NodeType.MacroParameterDeclaration: return item.ty.name === "ident"; default: return false; } } function is_tk(item: MacroMatchSegment) { return is_PunctuationToken(item) || is_optional_token(item); } function maybe_tk(item: MacroMatchSegment) { switch (item.nodeType) { case NodeType.PunctuationToken: return item.tk; case NodeType.MacroGroup: return is_optional_token(item) ? item.segments[0].tk : TK.None; default: return TK.None; } } function isDeclStart(item: MacroMatchSegment, next: MacroMatchSegment) { if (is_Identifier(item)) { switch (item.name) { case "fn": case "mod": case "use": case "struct": case "trait": case "union": case "enum": case "impl": case "type": case "let": case "static": case "const": if (is_ident(next)) { return true; } } } return false; } function is_match_any(item: MacroMatchSegment) { return ( !!item && ((is_MacroGroup(item) && !item.sep && (item.kind === "*" || item.kind === "+") && item.segments.length === 1 && is_MacroParameterDeclaration(item.segments[0]) && item.segments[0].ty.name === "tt") || (is_DelimGroup(item) && item.segments.length === 1 && is_match_any(item.segments[0]))) ); } } export function printRuleTransform( print: print, node: T, t: DelimChars = getDelimChars(node.transform) ) { const text = node.transform.loc.sliceText(); const fline = is_MacroInlineRuleDeclaration(node) ? hardline : line; if (/^. *\n/.test(text)) { return [ dedentToRoot([ t.left, fline, text .slice(1, -1) // .replace(/^ *\n|\n\s*$/g, ""), ]), fline, t.right, ]; } else if (/\n/.test(text) && node.transform.length === 1) { const segment = node.transform[0]; if (is_DelimGroup(segment) || is_MacroGroup(segment)) { const inner = is_DelimGroup(segment) ? getDelimChars(segment.segments) : { left: "$(", right: `)${segment.sep?.loc.getOwnText() ?? ""}${segment.kind}` }; return [ dedentToRoot([ t.left, [ indent(indent([fline, inner.left])), line, segment.segments.loc.sliceText(1, -1).replace(/^ *\n|\n\s*$/g, ""), indent(indent([line, inner.right])), ], ]), fline, t.right, ]; } } return text; return node.transform.length > 0 ? group([t.left, indent([line, print("transform")]), line, t.right]) : [t.left, printDanglingCommentsForInline(node, DCM["transform"]), t.right]; } function is_AssignmentOrVariableDeclarator(node: Node): boolean { return is_ReassignmentNode(node) || is_VariableDeclarationNode(node); } function hasLeadingOwnLineComment(node: Node): boolean { if (is_NodeWithBodyOrCases(node) && hasComment(node, CF.Leading, is_Attribute)) { return true; } return hasComment( node, CF.Leading, (comment) => hasNewline(end(comment)) && !getContext().options.danglingAttributes.includes(comment as any) ); } function isComplexDestructuring(node: Node): boolean { if (is_ReassignmentExpression(node)) { const leftNode = node.left; return ( is_StructLiteral(leftNode) && // leftNode.properties.length > 2 && leftNode.properties.some((property) => is_StructLiteralProperty(property) || is_StructLiteralPropertySpread(property)) ); } if (is_VariableDeclarationNode(node) || is_MatchExpressionCase(node) || is_LetScrutinee(node)) { const leftNode = node.pattern; return ( is_StructPattern(leftNode) && // leftNode.properties.length > 2 && leftNode.properties.some((property) => is_StructPatternPropertyDestructured(property)) ); } return false; } // export function isShortWhereBoundDeclaration(node: WhereBoundDeclaration) { // switch (node.nodeType) { // case NodeType.WhereTypeBoundDeclaration: // __DEV__: Narrow(node); // return !node.ltParameters && is_Identifier(node.typeTarget); // case NodeType.WhereLtBoundDeclaration: // __DEV__: Narrow(node); // // return !node.typeAnnotation && !node.typeDefault; // default: // exit.never(); // } // } function isArrowFunctionVariableDeclarator(node: Node) { return is_VariableDeclarationNode(node) && node.expression && is_ClosureFunctionExpression(node.expression); } function isObjectPropertyWithShortKey(node: Node, keyDoc: Doc) { if (!is_StructProperty(node)) return false; keyDoc = cleanDoc(keyDoc); const MIN_OVERLAP_FOR_BREAK = 3; return typeof keyDoc === "string" && keyDoc.length < getContext().options.tabWidth + MIN_OVERLAP_FOR_BREAK; } function print_CallExpression_end(print: print, node: CallExpression) { return [f`::${printTypeArguments(print, node)}`, printCallArguments(print, node)]; } export function printCallExpression(print: print, node: CallExpression) { if (shouldPrint_CallExpression_chain(node) && !pathCall(node, "callee", (node) => needsParens(node))) { return printMemberChain(print, node); } const contents = [print("callee"), ...print_CallExpression_end(print, node)]; if (is_CallExpression_or_CallLikeMacroInvocation(node.callee)) { return group(contents); } return contents; } export function printTypeAnnotation>>(print: print, node: T) { return node.typeAnnotation && !is_MissingNode(node.typeAnnotation) ? [": ", print("typeAnnotation")] : ""; } export function printAnnotatedPattern & PatternBody>>(print: print, node: T) { return [print("pattern"), printTypeAnnotation(print, node)]; } function isLoneShortArgument(node: Node) { if (hasComment(node)) { return false; } if ((is_Identifier(node) && is_short(node.name)) || (is_LiteralNumberLike(node) && !hasComment(node))) { return true; } if (is_LiteralStringLike(node)) { return is_short(node.value) && !node.value.includes("\n"); } return is_LiteralBooleanLike(node); } // prettier-ignore const toLayout = ["break-after-operator", "never-break-after-operator", "fluid", "break-lhs", "chain", "chain-tail", "chain-tail-arrow-chain", "only-left"]; const enum Layout { "break-after-operator", "never-break-after-operator", "fluid", "break-lhs", "chain", "chain-tail", "chain-tail-arrow-chain", "only-left", } export function printMemberExpression(print: print, node: MemberExpression) { const objectDoc = print("expression"); const lookupDoc = printMemberLookup(print, node); const shouldInline = shouldInlineMemberExpression(node, objectDoc); return label((objectDoc as any).label === "member-chain" ? "member-chain" : "member", [ objectDoc, shouldInline ? lookupDoc : group(indent([softline, lookupDoc])), ]); } function shouldInlineMemberExpression(node: MemberExpression, objectDoc: Doc) { const { path } = getContext(); const parent = getParentNode()!; let i = 0; let nmparent: Node | null = parent; while (nmparent && (is_MemberExpression(nmparent) || is_PostfixExpression(nmparent))) { nmparent = path.getParentNode(i++); } const shouldInline = (nmparent && (is_ExpressionPath(nmparent) || (is_ReassignmentNode(nmparent) && !is_Identifier(nmparent.left)))) || !node.computed || (is_Identifier(node.expression) && is_Identifier(node.property) && !is_MemberExpression(parent)) || (is_AssignmentOrVariableDeclarator(parent) && ((is_CallExpression_or_CallLikeMacroInvocation(node.expression) && node.expression.arguments.length > 0) || (is_PostfixExpression(node.expression) && is_CallExpression_or_CallLikeMacroInvocation(node.expression.expression) && node.expression.expression.arguments.length > 0) || (objectDoc as any).label === "member-chain")); return shouldInline; } export function printAssignment(leftDoc: Doc, operator: string, rightPropertyName: string) { const assignmentNode = getNode(); const rightNode = assignmentNode[rightPropertyName]; if (!rightNode) return group(leftDoc); const layout = chooseLayout(); const rightDoc = getPrintFn(assignmentNode)(rightPropertyName as any, { assignmentLayout: layout }); const res = (function () { switch (layout) { case Layout["break-after-operator"]: return group([group(leftDoc), operator, group(indent([line, rightDoc]))]); case Layout["never-break-after-operator"]: return group([group(leftDoc), operator, " ", rightDoc]); case Layout["fluid"]: { const groupId = Symbol("assignment"); return group([ group(leftDoc), operator, // group(indent(line), { id: groupId }), lineSuffixBoundary, indentIfBreak(rightDoc, { groupId }), ]); } case Layout["break-lhs"]: return group([leftDoc, operator, " ", group(rightDoc)]); case Layout["chain"]: return [group(leftDoc), operator, line, rightDoc]; case Layout["chain-tail"]: return [group(leftDoc), operator, indent([line, rightDoc])]; case Layout["chain-tail-arrow-chain"]: return [group(leftDoc), operator, rightDoc]; default: exit.never(); } })(); return label(toLayout[layout], res); return res; function chooseLayout() { if ( (is_ReassignmentExpression(assignmentNode) && is_printing_macro()) || is_GenericParameterDeclaration(assignmentNode) || is_TypeCallNamedArgument(assignmentNode) ) { return Layout["never-break-after-operator"]; } const isTail = !is_ReassignmentNode(rightNode); const shouldUseChainFormatting = getContext().path.match( is_ReassignmentNode, is_AssignmentOrVariableDeclarator, (node: Node) => !isTail || (!is_ExpressionStatement(node) && !is_VariableDeclarationNode(node)) ); if (shouldUseChainFormatting) { return !isTail ? Layout["chain"] : is_ClosureFunctionExpression(rightNode) && is_ClosureFunctionExpression(rightNode.expression) ? Layout["chain-tail-arrow-chain"] : Layout["chain-tail"]; } const isHeadOfLongChain = !isTail && is_ReassignmentNode(rightNode.right); if (isHeadOfLongChain || hasLeadingOwnLineComment(rightNode)) { return Layout["break-after-operator"]; } if ( isComplexDestructuring(assignmentNode) || hasComplexGenerics(assignmentNode) || hasComplexTypeAnnotation(assignmentNode) || (isArrowFunctionVariableDeclarator(assignmentNode) && canBreak(leftDoc)) ) { return Layout["break-lhs"]; } const hasShortKey = isObjectPropertyWithShortKey(assignmentNode, leftDoc); if (pathCall(assignmentNode, rightPropertyName as never, (rightNode) => shouldBreakAfterOperator(rightNode, hasShortKey))) { return Layout["break-after-operator"]; } if (hasShortKey || is_Literal(rightNode)) { return Layout["never-break-after-operator"]; } return Layout["fluid"]; } function shouldBreakAfterOperator(rightNode: Node, hasShortKey: boolean) { if (is_MemberExpression(rightNode) && shouldInlineMemberExpression(rightNode, getPrintFn(rightNode)("expression"))) { return false; } if (is_BinaryishExpression(rightNode) && !shouldInlineLogicalExpression(rightNode)) { return true; } if (is_IfBlockExpression(rightNode)) { return false; } if (hasShortKey) { return false; } return (function unwrap(node: Node) { if (is_UnaryExpression(node) || is_PostfixExpression(node)) { return pathCall(node, "expression", unwrap); } if (is_LiteralStringLike(node)) { return true; } return isPoorlyBreakableMemberOrCallChain(node); })(rightNode); function isPoorlyBreakableMemberOrCallChain(topNode: Node) { return (function unwrap(node: Node): boolean { if (is_MemberExpression(node) || is_PostfixExpression(node) || is_UnaryExpression(node)) { return pathCall(node, "expression", unwrap); } if (is_ExpressionPath(node)) { return pathCall(node, "namespace", (namespace) => !namespace || unwrap(namespace)); } if (is_CallExpression_or_CallLikeMacroInvocation(node)) { const doc = printCallExpression(getPrintFn(), node); if ((doc as any).label === "member-chain") { return false; } const args = node.arguments; const isPoorlyBreakableCall = args.length === 0 || (args.length === 1 && isLoneShortArgument(args[0])); if (!isPoorlyBreakableCall) { return false; } if (hasComplexTypeArguments(node)) { return false; } return pathCall(node, "callee", unwrap); } return topNode === node ? false : is_Identifier(node); })(topNode); } } } function is_MemberExpression_with_RangeOrLiteral_Property(node: Node | undefined) { return ( !!node && is_MemberExpression(node) && (node.computed ? is_Literal_or_SimpleRangeLiteral(node.property) : is_Literal(node.property)) ); } function is_Literal_or_SimpleRangeLiteral(node: Node) { return is_Literal(node) ? true : is_RangeLiteral(node) ? (!node.lower || is_Literal(node.lower)) && (!node.upper || is_Literal(node.upper)) : false; } function printMemberLookup(print: print, node: MemberExpression) { return !node.computed ? [".", print("property")] : is_Literal_or_SimpleRangeLiteral(node.property) ? ["[", print("property"), "]"] : group(["[", indent([softline, print("property")]), softline, "]"]); } function shouldPrint_CallExpression_chain(node: CallExpression) { return is_MemberAccessLike(node.callee) || is_CallExpression_or_CallLikeMacroInvocation(node.callee); } export function is_MemberAccessLike(node: Node): node is ExpressionPath | MemberExpression { switch (node.nodeType) { case NodeType.ExpressionPath: case NodeType.MemberExpression: return true; default: return false; } } type ChainItem = { node: Node; printed: Doc; needsParens: boolean }; function printMemberChain(print: print, node: CallExpression) { const parent = getParentNode(); const isExpressionStatement = !parent || is_ExpressionStatement(parent); const { printedNodes, groups } = splitCallChains(node); const shouldMerge = groups.length >= 2 && !hasComment(groups[1][0].node) && shouldNotWrap(groups); const printedGroups = groups.map(printGroup); const oneLine = printedGroups; const cutoff = shouldMerge ? 3 : 2; const nodeHasComment = printedNodes.slice(1, -1).some(({ node }) => hasComment(node, CF.Leading)) || printedNodes.slice(0, -1).some(({ node }) => hasComment(node, CF.Trailing)) || (groups[cutoff] && hasComment(groups[cutoff][0].node, CF.Leading)); if (groups.length <= cutoff && !nodeHasComment) { return isLongCurriedCallExpression(node) ? oneLine : group(oneLine); } const lastNodeBeforeIndent = last_of(groups[shouldMerge ? 1 : 0]).node; const shouldHaveEmptyLineBeforeIndent = !is_CallExpression_or_CallLikeMacroInvocation(lastNodeBeforeIndent) && shouldInsertEmptyLineAfter(lastNodeBeforeIndent); const expanded = [ printGroup(groups[0]), shouldMerge ? groups.slice(1, 2).map(printGroup) : "", shouldHaveEmptyLineBeforeIndent ? hardline : "", printIndentedGroup(groups.slice(shouldMerge ? 2 : 1)), ]; const callExpressions = printedNodes.map(({ node }) => node).filter(is_CallExpression_or_CallLikeMacroInvocation); const result: Doc = nodeHasComment || (callExpressions.length > 2 && callExpressions.some((expr) => expr.arguments.some((arg) => !isSimpleCallArgument(arg, 0)))) || printedGroups.slice(0, -1).some(willBreak) || lastGroupWillBreakAndOtherCallsHaveFunctionArguments() ? group(expanded) : [shouldHaveEmptyLineBeforeIndent || willBreak(oneLine) ? breakParent : "", conditionalGroup([oneLine, expanded])]; return label("member-chain", result); function shouldInsertEmptyLineAfter(node: Node) { let start = end(node); const last = getNextNonSpaceNonCommentCharacterIndex(node); const { originalText } = getContext().options; while (start < last) { if (originalText.charAt(start) === ")") { return isNextLineEmptyAfterIndex(start + 1); } start++; } return isNextLineEmpty(node); } function isFactory(name: string) { return /^[A-Z]|^[$_]+$/.test(name); } function isShort(name: string) { return name.length <= getContext().options.tabWidth; } function shouldNotWrap(groups: ChainItem[][]) { const hasComputed = groups[1].length > 0 && is_MemberExpression(groups[1][0].node) && groups[1][0].node.computed; if (groups[0].length === 1) { const firstNode = groups[0][0].node; return ( is_Identifier(firstNode) && (isFactory(firstNode.name) || (isExpressionStatement && isShort(firstNode.name)) || hasComputed) ); } const lastNode = last_of(groups[0]).node; const lastNodeLeft = is_ExpressionPath(lastNode) ? lastNode.namespace : is_MemberExpression(lastNode) ? lastNode.expression : undefined; return lastNodeLeft && is_Identifier(lastNodeLeft) && (isFactory(lastNodeLeft.name) || hasComputed); } function printGroup(g: ChainItem[]) { const printed: Doc[] = []; if (printedNodes[0] === g[0]) { for (const item of printedNodes) { if (item.needsParens) printed.unshift("("); } } for (const item of g) { printed.push(item.printed); if (item.needsParens) printed.push(")"); } return printed; } function printIndentedGroup(groups: ChainItem[][]) { if (groups.length === 0) return ""; return indent(group([hardline, join(hardline, groups.map(printGroup))])); } function lastGroupWillBreakAndOtherCallsHaveFunctionArguments() { const lastGroupNode = last_of(last_of(groups)).node; const lastGroupDoc = last_of(printedGroups); return ( is_CallExpression_or_CallLikeMacroInvocation(lastGroupNode) && willBreak(lastGroupDoc) && callExpressions.slice(0, -1).some((node) => node.arguments.some(is_ClosureFunctionExpression)) ); } function splitCallChains(topNode: CallExpression | CallLikeMacroInvocation) { const printedNodes: ChainItem[] = [ { node: topNode, needsParens: false, printed: print_CallExpression_end(print, node), }, ]; pathCall(topNode, "callee", function READ_LEFT(node: Node) { if (is_CallExpression_or_CallLikeMacroInvocation(node) && shouldPrint_CallExpression_chain(node)) { __DEV__: Narrow>(print); unshift(print_CallExpression_end(print, node), shouldInsertEmptyLineAfter(node)); pathCall(node, "callee", READ_LEFT); } else if (is_MemberExpression(node)) { __DEV__: Narrow>(print); unshift(printMemberLookup(print, node)); pathCall(node, "expression", READ_LEFT); } else if (is_ExpressionPath(node)) { __DEV__: Narrow>(print); unshift(["::", print("segment")]); if (node.namespace) { pathCall(node, "namespace", READ_LEFT as any); } } else if (is_PostfixExpression(node)) { unshift(is_UnwrapExpression(node) ? "?" : ".await"); pathCall(node, "expression", READ_LEFT); } else { printedNodes.unshift({ node, needsParens: false, printed: print() }); } function unshift(printed: Doc, needsHardlineAfter = false) { printedNodes.unshift({ node, needsParens: is_MemberAccessLike(node) && needsParens(node), printed: [withComments(node, printed), needsHardlineAfter ? hardline : ""], }); } }); const groups = spread(function* () { let i = 0; let currentItem = printedNodes[i]; function testNextItem(fn: (item: ChainItem) => boolean) { return i + 1 < printedNodes.length && fn(printedNodes[i + 1]); } function readGroup(fn: () => Iterable) { __DEV__: assert(i < printedNodes.length); return spread(function* () { for (var _item of fn()) { yield currentItem; if (++i < printedNodes.length) currentItem = printedNodes[i]; else break; } }); } function* loop(condition: (item: ChainItem) => boolean) { while (condition(currentItem)) yield currentItem; } function* until(condition: (item: ChainItem) => boolean) { while (!condition(currentItem)) yield currentItem; } yield readGroup(function* () { const isCallExpression = is_CallExpression_or_CallLikeMacroInvocation(currentItem.node); yield currentItem; yield* loop( ({ node, needsParens }) => is_PostfixExpression(node) || is_CallExpression_or_CallLikeMacroInvocation(node) || is_MemberExpression_with_RangeOrLiteral_Property(node) || needsParens ); if (!isCallExpression) { yield* loop( ({ node, needsParens }) => is_MemberAccessLike(node) && // testNextItem(({ node }) => is_MemberAccessLike(node)) ); } }); while (i < printedNodes.length) { yield readGroup(function* () { let isCallExpression = false; yield* until( ({ node }) => (isCallExpression = is_CallExpression_or_CallLikeMacroInvocation(node)) || // hasComment(node, CF.Trailing) ); yield currentItem; if (isCallExpression) { yield* loop(({ node }) => is_MemberExpression_with_RangeOrLiteral_Property(node)); yield* until( ({ node }) => is_MemberAccessLike(node) || // hasComment(node, CF.Trailing) ); } }); } }); return { printedNodes, groups }; } } function isSimpleCallArgument(node: Node, depth: number) { if (depth >= 2) return false; if (is_IdentifierOrIndex(node)) { return true; } if (is_Literal(node)) { return !is_LiteralStringLike(node) || !node.value.includes("\n"); } if (is_ArrayOrTupleLiteral(node)) { return node.items.every(isChildSimple); } if (is_StructLiteral(node)) { return ( isSimpleCallArgument(node.struct, depth) && node.properties.every((prop) => is_StructLiteralPropertySpread(prop) ? isChildSimple(prop.expression) : is_StructLiteralProperty(prop) ? isChildSimple(prop.value) : true ) ); } if (is_CallExpression_or_CallLikeMacroInvocation(node)) { return ( isSimpleCallArgument(node.callee, depth) && (node.typeArguments ?? []).every(isChildSimple) && node.arguments.every(isChildSimple) ); } if (is_MemberExpression(node)) { return isSimpleCallArgument(node.expression, depth) && isSimpleCallArgument(node.property, depth); } if (is_ExpressionTypeCast(node)) { return isSimpleCallArgument(node.typeCallee, depth) && node.typeArguments.every(isChildSimple); } if (is_ExpressionPath(node)) { const namespace = node.namespace; return !namespace || isSimpleCallArgument(namespace, depth); } if (is_UnaryExpression(node) || is_PostfixExpression(node)) { return isSimpleCallArgument(node.expression, depth); } return false; function isChildSimple(child: Node) { return isSimpleCallArgument(child, depth + 1); } } function isLongCurriedCallExpression(node: Node) { const parent = getParentNode(node)!; return ( is_CallExpression_or_CallLikeMacroInvocation(node) && is_CallExpression_or_CallLikeMacroInvocation(parent) && parent.callee === node && node.arguments.length > parent.arguments.length && parent.arguments.length > 0 ); } export function printTypeArguments>(print: print, node: T) { return !node.typeArguments ? "" : node.typeArguments.length === 0 ? ["<", printDanglingCommentsForInline(node, DCM["typeArguments"]), ">"] : hasComplexTypeArguments(node) ? group( [ "<", // indent([softline, print.join("typeArguments", [",", line])]), softline, ">", ], { id: getTypeParametersGroupId(node) } ) : ["<", print.join("typeArguments", ", "), ">"]; } export function printLtParameters>(print: print, node: T) { return !node.ltParameters ? "" : node.ltParameters.length === 0 ? ["for<", printDanglingCommentsForInline(node, DCM["ltParameters"]), "> "] : hasComplexLtParameters(node) ? group( [ "for<", // indent([softline, print.join("ltParameters", [",", line])]), softline, "> ", ], { id: getTypeParametersGroupId(node) } ) : ["for<", print.join("ltParameters", ", "), "> "]; } export function printGenerics(print: print, node: T) { return group( !node.generics ? "" : hasComplexGenerics(node) ? [ "<", indent([softline, print.join("generics", [",", line])]), // hasMultipleHeritage(node) ? indent([softline, ">"]) : [softline, ">"], ] : [ "<", print.join("generics", ", "), // printDanglingCommentsForInline(node, DCM["generics"]), ">", ] ); } function getPrintedTypeBounds>(print: print, node: T) { if (!hasTypeBounds(node) || node.typeBounds.length === 0) return ""; if (node.typeBounds.length === 1) return print.map("typeBounds"); // let shouldIndent = false; // const printed = print.map("typeBounds", (bound, i, arr) => // 0 === i // ? print() // : true //isSimpleTypeBound(arr[i - 1]) && isSimpleTypeBound(bound) // ? indent([" +", line, print()]) // : [" + ", (shouldIndent ||= isSimpleTypeBound(arr[i - 1]) || isSimpleTypeBound(bound)) ? indent(print()) : print()] // ); const printed = print.join("typeBounds", (_, __, prev) => (!prev ? " +" : [" +", line])); return [printed.shift()!, indent([line, printed])]; } export function printTypeBounds>(operator: "dyn" | "impl" | ":", print: print, node: T) { if (!hasTypeBounds(node)) return ""; const printed = getPrintedTypeBounds(print, node); return printed ? group([operator, " ", printed]) : operator; return !node.typeBounds ? "" : hasComplexTypeBounds(node) ? group(indent([ifBreak(line), operator, " ", join([line, "+ "], print.map("typeBounds"))])) : [operator, " ", join(" + ", print.map("typeBounds"))]; } export function printLtBounds>(left: Doc, print: print, node: T) { return group( !node.ltBounds ? "" : node.ltBounds.length === 0 ? [left, " "] : [left, " ", print.map("ltBounds", (typeBound, i) => (i === 0 ? print() : indent([line, "+ ", print()])))] ); } function printWhereBounds(print: print, node: T) { if (!node.whereBounds || node.whereBounds.length === 0) return ""; return adjustDeclarationClause( node, // "where", print.join("whereBounds", [",", line]) ); } export function printDeclarationTypeBounds>( print: print, node: T, operator: ":" | " =" ) { return hasTypeBounds(node) ? adjustDeclarationClause(node, operator, getPrintedTypeBounds(print, node)) : ""; } export function printImplTraitForType( print: print, node: ImplDeclaration | NegativeImplDeclaration ) { return node.trait ? [print("trait"), adjustDeclarationClause(node, "for", print("typeTarget"))] // : print("typeTarget"); } function adjustDeclarationClause(node: DeclarationNode, clause: ":" | " =" | "for" | "->" | "where", content: Doc) { const isTypeBoundsClause = clause === ":" || clause === " ="; return (clause === "where" || hasMultipleHeritage(node) ? indent : Identity)([ clause === "->" ? hasMultipleHeritage(node) && node.whereBounds!.length > 1 ? line : " " : clause === "where" // ? line : isTypeBoundsClause ? hasMultipleHeritage(node) ? softline : "" : line, clause, content && group( clause === "where" ? indent([line, content]) // : clause === "->" || isTypeBoundsClause ? [" ", content] : [line, content] ), ]); } function hasNonWhereHeritageClause(node: DeclarationNode) { AssertTypesEq< DeclarationNode, | FunctionDeclaration | StructDeclaration | TupleStructDeclaration | UnionDeclaration | TypeAliasDeclaration | TraitDeclaration | TraitAliasDeclaration | NegativeImplDeclaration | ImplDeclaration | EnumDeclaration >(); switch (node.nodeType) { case NodeType.FunctionDeclaration: return !!node.returnType; case NodeType.StructDeclaration: case NodeType.TupleStructDeclaration: case NodeType.UnionDeclaration: case NodeType.EnumDeclaration: return false; case NodeType.TypeAliasDeclaration: case NodeType.TraitDeclaration: case NodeType.TraitAliasDeclaration: // case NodeType.AutoTraitDeclaration: return hasTypeBounds(node); case NodeType.ImplDeclaration: case NodeType.NegativeImplDeclaration: return !!node.trait; default: __DEV__: exit.never(node); } } function hasAnyHeritageClause(node: DeclarationNode) { return !!node.whereBounds || hasNonWhereHeritageClause(node); } function hasMultipleHeritage(node: DeclarationNode) { return !!node.whereBounds && hasNonWhereHeritageClause(node); } const getMacroGroupId = createGroupIdMapper("MacroGroup"); const getHeritageGroupId = createGroupIdMapper("heritageGroup"); const getWhereBoundsGroupId = createGroupIdMapper("where"); const getTypeParametersGroupId = createGroupIdMapper("typeParameters"); function createGroupIdMapper(description: string) { const groupIds = new WeakMap(); return (node: Node) => Map_get(groupIds, node, () => Symbol(description)); } export function printDanglingCommentsForInline(node: Node, marker?: DCM) { const hasOnlyBlockComments = !hasComment(node, CF.Line | CF.Dangling, (comment) => !marker || comment.marker === marker) || is_Program(node); const printed = printDanglingComments(node, hasOnlyBlockComments, marker); return ( printed && (hasOnlyBlockComments && !is_Program(node) ? willBreak(printed) ? [indent([hardline, printed]), hardline] : [printed] : [printed, hardline]) ); } function isFormatLikeCall(node: CallExpression | CallLikeMacroInvocation) { if (is_Identifier(node.callee) && !node.typeArguments) { const [first, ...rest] = node.arguments; if (is_Literal(first) && is_LiteralStringLike(first) && first.value.includes("{}") && rest.every(is_Identifier)) { return true; } } return false; } class ArgExpansionBailout extends Error {} export function printCallArguments(print: print, node: T) { const args = node.arguments; const { left: LEFT, right: RIGHT } = getDelimChars(args); __DEV__: { // assert(args.length === 0 || !hasComment(node, CF.Dangling), "", node); if (is_MacroInvocation(node)) assert(args.every(is_ExpressionNode), "", node); } if (args.length === 0) return [LEFT, printDanglingCommentsForInline(node, DCM["arguments"]), RIGHT]; // force inline format!(" {} ", ident) if (args.length === 2 && isFormatLikeCall(node)) { return [LEFT, print(["arguments", 0]), ", ", print(["arguments", 1]), RIGHT]; } let anyArgEmptyLine = false; let hasEmptyLineFollowingFirstArg = false; const lastArgIndex = args.length - 1; const trailingComma = false ? "," : ""; const printedArguments = print.map("arguments", (arg, index, arr) => { if (index === lastArgIndex) { return [print()]; } else if (isNextLineEmpty(arg)) { if (index === 0) hasEmptyLineFollowingFirstArg = true; anyArgEmptyLine = true; return [print(), ",", hardline, hardline]; } else { return [print(), ",", line]; } }); if (anyArgEmptyLine || isFunctionCompositionArgs(args)) { return allArgsBrokenOut(); } const shouldGroupFirst = shouldGroupFirstArg(args); const shouldGroupLast = shouldGroupLastArg(args); if (shouldGroupFirst || shouldGroupLast) { if (shouldGroupFirst ? printedArguments.slice(1).some(willBreak) : printedArguments.slice(0, -1).some(willBreak)) { return allArgsBrokenOut(); } let printedExpanded: Doc[] = []; const { path } = getContext(); const stackBackup = [...path.stack]; try { path_try(() => { getContext().path.each((p, i) => { if (shouldGroupFirst && i === 0) { printedExpanded = [ [ print([], { expandFirstArg: true }), printedArguments.length > 1 ? "," : "", hasEmptyLineFollowingFirstArg ? hardline : line, hasEmptyLineFollowingFirstArg ? hardline : "", ], ...printedArguments.slice(1), ]; } if (shouldGroupLast && i === lastArgIndex) { printedExpanded = [...printedArguments.slice(0, -1), print([], { expandLastArg: true })]; } }, "arguments"); }); } catch (caught) { path.stack.length = 0; path.stack.push(...stackBackup); if (caught instanceof ArgExpansionBailout) return allArgsBrokenOut(); throw caught; } return [ printedArguments.some(willBreak) ? breakParent : "", conditionalGroup([ [LEFT, ...printedExpanded, RIGHT], shouldGroupFirst ? [LEFT, group(printedExpanded[0], { shouldBreak: true }), ...printedExpanded.slice(1), RIGHT] : [LEFT, ...printedArguments.slice(0, -1), group(printedExpanded[lastArgIndex], { shouldBreak: true }), RIGHT], allArgsBrokenOut(), ]), ]; } const contents = [LEFT, indent([softline, ...printedArguments]), ifBreak(trailingComma), softline, RIGHT]; return isLongCurriedCallExpression(node) ? contents : group(contents, { shouldBreak: anyArgEmptyLine || printedArguments.some(willBreak) }); function allArgsBrokenOut() { return group([LEFT, indent([line, ...printedArguments]), trailingComma, line, RIGHT], { shouldBreak: true }); } } function shouldHugFunctionParameters(node: Extract) { if (!node) return false; const parameters = getParameters(node); if (parameters.length !== 1) return false; const param = parameters[0]; if (hasComment(param)) return false; switch (param.nodeType) { case NodeType.FunctionSelfParameterDeclaration: case NodeType.FunctionSpread: case NodeType.TypeFnPointerParameter: default: return false; case NodeType.FunctionParameterDeclaration: case NodeType.ClosureFunctionParameterDeclaration: return "items" in param.pattern || "properties" in param.pattern; } } function shouldGroupFunctionParameters(functionNode: FunctionDeclaration, returnTypeDoc: Doc) { const returnType = functionNode.returnType; const generics = functionNode.generics; const whereBounds = functionNode.whereBounds; if (!returnType) return false; if (generics) { if (generics.length > 1) return false; if (generics.length === 1 && !isShortGenericParameterDeclaration(generics[0])) return false; } if (whereBounds) { if (whereBounds.length > 1) return false; } return ( getParameters(functionNode).length === 1 && (willBreak(returnTypeDoc) || willBreak(printWhereBounds(getPrintFn(functionNode), functionNode))) ); } export function printBlockBody(print: print, node: T): Doc { const body = printBodyOrCases(print, node); return [ "{", body.length > 0 ? getBodyOrCases(node)?.length ? canInlineBlockBody(node) ? [indent([line, body]), line] : group([indent([line, body]), line], { shouldBreak: true }) : body : emptyContent(node), "}", ]; } export function printMaybeBlockBody( print: print, node: T ): Doc { return hasSemiNoBody(node) ? ";" : adjustClause(node, printBlockBody(print, node)); } export function printArrowFunction(print: print, node: T) { const signatures: Doc[] = []; const body: Doc[] = []; const { args, path } = getContext(); let chainShouldBreak = false; let tailNode: ClosureFunctionExpression = node; (function rec(node: ClosureFunctionExpression) { tailNode = node; const doc = printArrowFunctionSignature(print, node); if (signatures.length === 0) { signatures.push(doc); } else { const { leading, trailing } = printCommentsSeparately(); signatures.push([leading!, doc]); body.unshift(trailing!); } chainShouldBreak ||= !!node.returnType || !node.parameters.every((param) => isSimplePattern(param.pattern)); if (!is_ClosureFunctionExpression(node.expression) || (args && args.expandLastArg)) { body.unshift(print("expression", args)); } else { pathCall(node, "expression", rec); } })(node); if (signatures.length > 1) { return printArrowChain(signatures, chainShouldBreak, body, tailNode); } else { const printed = signatures[0]; if ( !hasLeadingOwnLineComment(node.expression) && (is_ArrayOrTupleLiteral(node.expression) || is_StructLiteral(node.expression) || is_ExpressionWithBodyOrCases(node.expression) || is_ClosureFunctionExpression(node.expression)) ) { return group([printed, " ", body]); } const shouldAddSoftLine = args && args.expandLastArg && !hasComment(node); const printTrailingComma = args && args.expandLastArg && false; const shouldAddParens = is_OrExpression(node.expression); return group([ printed, group([ indent(shouldAddParens ? [line, ifBreak("", "("), body, ifBreak("", ")")] : [line, body]), shouldAddSoftLine ? [ifBreak(printTrailingComma ? "," : ""), softline] : "", ]), ]); } } function printArrowChain(signatures: Doc[], shouldBreak: boolean, bodyDoc: Doc, tailNode: ClosureFunctionExpression) { const { args } = getContext(); const parent = getParentNode()!; const isCallee = is_CallExpression_or_CallLikeMacroInvocation(parent) && parent.callee === getNode(); const isAssignmentRhs = !!(args && args.assignmentLayout); const shouldPutBodyOnSeparateLine = !is_ExpressionWithBodyOrCases(tailNode.expression) && !is_StructLiteral(tailNode.expression); const shouldBreakBeforeChain = (isCallee && shouldPutBodyOnSeparateLine) || (args && args.assignmentLayout === Layout["chain-tail-arrow-chain"]); const groupId = Symbol("arrow-chain"); return group([ group( indent([isCallee || isAssignmentRhs ? softline : "", group(join(line, signatures), { shouldBreak })]), // { id: groupId, shouldBreak: shouldBreakBeforeChain } ), indentIfBreak(shouldPutBodyOnSeparateLine ? indent([line, bodyDoc]) : [" ", bodyDoc], { groupId }), isCallee ? ifBreak(softline, "", { groupId }) : "", ]); } function printArrowFunctionSignature(print: print, node: T) { const { args } = getContext(); const expandArg = args && (args.expandLastArg || args.expandFirstArg); let returnTypeDoc: Doc = printReturnType(print, node); if (expandArg) { if (willBreak(returnTypeDoc)) throw new ArgExpansionBailout(); else returnTypeDoc = group(removeLines(returnTypeDoc)); } // const dangling = printDanglingComments(node, true, (comment) => node.parameters.loc.contains(comment)); // if (dangling) { // parts.push(" ", dangling); // } return [ print.b("static"), print.b("async"), print.b("move"), // group([printFunctionParameters(print, node, expandArg), returnTypeDoc]), ]; } export function printGenerics_x_whereBounds(print: print, node: T, xDoc: Doc) { const generics: Doc = is_ImplDeclarationNode(node) ? [printGenerics(print, node), " "] : [" ", print("id" as any), printGenerics(print, node)]; const whereBoundsDoc = printWhereBounds(print, node); return is_TupleStructDeclaration(node) ? [...generics, xDoc, group(whereBoundsDoc, { id: getHeritageGroupId(node) })] : [...generics, group([xDoc, whereBoundsDoc], { id: getHeritageGroupId(node) })]; } export function adjustClause( node: DeclarationNode | ((NodeWithBodyOrCases | BlockLikeMacroInvocation) & { body: undefined | {} }), doc: Doc ) { return [ "whereBounds" in node && (!!node.whereBounds || (hasTypeBounds(node) && node.typeBounds.length > 1)) && willBreak(doc) ? ifBreak(hardline, " ", { groupId: getHeritageGroupId(node) }) : " ", doc, ]; } export function printParametersAndReturnType(node: FunctionNode | TypeFunctionNode) { const parametersDoc = printFunctionParameters(getPrintFn(node), node); const returnTypeDoc = printReturnType(getPrintFn(node), node); return is_FunctionDeclaration(node) && shouldGroupFunctionParameters(node, returnTypeDoc) ? group([group(parametersDoc), returnTypeDoc]) : group([parametersDoc, returnTypeDoc]); } export function printFlowControlExpression(print: print, node: T) { return !node.expression ? "" : // : hasLeadingComment(node.expression) // ? [" (", indent([hardline, print("expression")]), hardline, ")"] is_BinaryishExpression(node.expression) && !flowControlExpressionNeedsOuterParens(node) ? group([" ", ifBreak("("), indent([softline, print("expression")]), softline, ifBreak(")")]) : [" ", print("expression")]; function hasLeadingComment(node: Node) { if (hasLeadingOwnLineComment(node)) return true; if (hasNakedLeftSide(node)) { let leftMost = node; while ((leftMost = getLeftSide(leftMost))) { if (hasLeadingOwnLineComment(leftMost)) return true; } } return false; } } export function flowControlExpressionNeedsOuterParens(flow: ReturnExpression | BreakExpression | YieldExpression) { return ( flow.expression && (function hasLeadingComment(node: Node) { if (hasLeadingOwnLineComment(node)) return true; if (hasNakedLeftSide(node)) { let leftMost = node; while ((leftMost = getLeftSide(leftMost))) { if (hasLeadingOwnLineComment(leftMost)) return true; } } return false; })(flow.expression) ); } function getLeftSide(node, includeAttributes = false) { let target: Node = (node as LeftRightExpression).left ?? (node as CallExpression).callee ?? (node as PathNode).namespace ?? (node as ExpressionWithBody).label ?? (node as RangeNode).lower ?? (node as StructLiteral).struct ?? (node as NodeWithCondition).condition ?? (node as ExpressionBody).expression; if (target && includeAttributes && hasAttributes(node)) { (node.attributes as AttributeOrDocComment[]).forEach((attr) => { if (start(attr) < start(target)) target = attr; }); } return target; } function hasNakedLeftSide(node: Node) { return ( is_BinaryishExpression(node) || is_ReassignmentNode(node) || is_CallExpression_or_CallLikeMacroInvocation(node) || is_MemberAccessLike(node) || is_PostfixExpression(node) || is_ExpressionAsTypeCast(node) ); } export function printReturnType>(print: print, node: T) { return node.returnType ? is_FunctionDeclaration(node) ? adjustDeclarationClause(node, "->", print("returnType")) : [" -> ", print("returnType")] : ""; } function printFunctionParameters( print: print, node: T, expandArg = false, printTypeParams = false ) { const { left: leftDelim, right: rightDelim } = getDelimChars(node.parameters); const generics = printTypeParams && is_FunctionDeclaration(node) ? printGenerics(print as any, node) : ""; if (!hasParameters(node)) { return [ generics, // leftDelim, printDanglingCommentsForInline(node, DCM["parameters"]), rightDelim, ]; } const isParametersInTestCall = false; const shouldHugParameters = shouldHugFunctionParameters(node); const printed = print.join("parameters", sepFn); if (hasSelfParameter(node)) { printed.unshift(getContext().path.call(() => [print(), printed.length ? sepFn(node.parameters.self) : ""], "parameters", "self")); } if (expandArg) { if (willBreak(generics) || willBreak(printed)) throw new ArgExpansionBailout(); return group([removeLines(generics), leftDelim, removeLines(printed), rightDelim]); } else if (shouldHugParameters || isParametersInTestCall) { return [generics, leftDelim, ...printed, rightDelim]; } else { return [generics, leftDelim, indent([softline, ...printed]), softline, rightDelim]; } function sepFn(param: Node) { return shouldHugParameters || isParametersInTestCall // ? ", " : isNextLineEmpty(param) ? [",", hardline, hardline] : [",", line]; } } function path_try(callback: () => T): T { const { stack } = getContext().path; const stackBackup = [...stack]; try { return callback(); } finally { stack.length = 0; stack.push(...stackBackup); } } function shouldGroupFirstArg(args: LocArray): boolean { if (args.length !== 2) return false; const [firstArg, secondArg] = args; return ( !hasComment(firstArg) && is_ClosureFunctionExpression(firstArg) && is_ExpressionWithBodyOrCases(firstArg.expression) && !is_ClosureFunctionExpression(secondArg) && !couldGroupArg(secondArg) ); } function shouldGroupLastArg(args: LocArray): boolean { const lastArg = last_of(args); const preLastArg = args[args.length - 2]; return ( !hasComment(lastArg, CF.Leading) && !hasComment(lastArg, CF.Trailing) && couldGroupArg(lastArg) && (!preLastArg || preLastArg.nodeType !== lastArg.nodeType) && (args.length !== 2 || !is_ClosureFunctionExpression(preLastArg) || !is_ArrayOrTupleLiteral(lastArg)) && !(args.length > 1 && is_ArrayOrTupleLiteral(lastArg) && isConciselyPrintedArray(lastArg)) && (args.length !== 1 || !is_IfBlockExpression(lastArg)) ); } function couldGroupArg(arg: Node, arrowChainRecursion = false): boolean { return ( (is_StructLiteral(arg) && (arg.properties.length > 0 || hasComment(arg))) || (is_ArrayOrTupleLiteral(arg) && (arg.items.length > 0 || hasComment(arg))) || (is_ExpressionAsTypeCast(arg) && couldGroupArg(arg.expression)) || (is_ClosureFunctionExpression(arg) && (!arg.returnType || is_Identifier(arg.returnType) || !isNonEmptyBlockStatement(arg.expression)) && (isNonEmptyBlockStatement(arg.expression) || (is_ClosureFunctionExpression(arg.expression) && couldGroupArg(arg.expression, true)) || is_StructLiteral(arg.expression) || is_ArrayOrTupleLiteral(arg.expression) || (!arrowChainRecursion && is_CallExpression_or_CallLikeMacroInvocation(arg.expression)))) || is_ExpressionWithBodyOrCases(arg) //&& isNonEmptyBlockStatement(arg) ); } function isNonEmptyBlockStatement(node: Node) { if (is_MatchExpression(node)) return node.cases.length > 0; return is_ExpressionWithBodyOrCases(node) && node.body.length > 0; } function isFunctionCompositionArgs(args) { if (args.length <= 1) { return false; } let count = 0; for (const arg of args) { if (is_ClosureFunctionExpression(arg)) { if (++count > 1) return true; } else if (is_CallExpression_or_CallLikeMacroInvocation(arg)) { for (const childArg of arg.arguments) { if (is_ClosureFunctionExpression(childArg)) { return true; } } } } return false; } export function printBinaryishExpression( print: print, node: T ) { const parent = getParentNode()!; const grandParent = getGrandParentNode(); const isInsideParenthesis = ("condition" in parent && parent.condition === node) || is_MatchExpression(parent); const parts = printBinaryishExpressions(false, isInsideParenthesis); if (isInsideParenthesis) return parts; if ( (is_CallExpression_or_CallLikeMacroInvocation(parent) && parent.callee === node) || // is_UnaryExpression(parent) || is_MemberExpression(parent) ) { return group([indent([softline, ...parts]), softline]); } const shouldNotIndent = is_FlowControlExpression(parent) || (is_ClosureFunctionExpression(parent) && parent.expression === node) || is_ExpressionWithBodyOrCases(parent); const shouldIndentIfInlining = is_ReassignmentNode(parent) || is_VariableDeclarationNode(parent) || is_StructLiteral(parent) || is_StructLiteral(grandParent); const samePrecedenceSubExpression = is_BinaryishExpression(node.left) && shouldFlatten(node, node.left); if ( shouldNotIndent || (shouldInlineLogicalExpression(node) && !samePrecedenceSubExpression) || (!shouldInlineLogicalExpression(node) && shouldIndentIfInlining) ) { return group(parts); } if (parts.length === 0) return ""; const firstGroupIndex = parts.findIndex((part) => typeof part !== "string" && !Array.isArray(part) && part.type === "group"); const leading = parts.slice(0, firstGroupIndex === -1 ? 1 : firstGroupIndex + 1); return group([...leading, indent(parts.slice(leading.length))], { id: Symbol("logicalChain") }); function printBinaryishExpressions(isNested: boolean, isInsideParenthesis: boolean): Doc[] { const { path, print, options } = getContext(); const node = path.getValue(); if (!is_BinaryishExpression(node)) { return [group(print())]; } const parts: Doc[] = []; if (shouldFlatten(node, node.left)) { parts.push(...pathCall(node, "left", () => printBinaryishExpressions(true, isInsideParenthesis))); } else { parts.push(group(print("left"))); } const shouldInline = shouldInlineLogicalExpression(node); const operator = node.kind; const right = [ operator, shouldInline ? " " : line, // this is a hack (should always be 'print("right")') !shouldInline && is_LogicalExpression(node.right) && shouldFlatten(node.right, node) ? pathCall(node, "right", () => printBinaryishExpressions(true, isInsideParenthesis)) : print("right"), ]; const shouldBreak = hasComment(node.left, CF.Trailing | CF.Line); const shouldGroup = shouldBreak || (!(isInsideParenthesis && is_LogicalExpression(node)) && path.getParentNode()!.nodeType !== node.nodeType && node.left.nodeType !== node.nodeType && node.right.nodeType !== node.nodeType); parts.push(" ", shouldGroup ? group(right, { shouldBreak }) : right); if (isNested && hasComment(node)) { const printed = cleanDoc(withComments(node, parts)); if (isConcat(printed) || (printed as any).type === "fill") { return getDocParts(printed) as Doc[]; } return [printed]; } return parts; } } // export function printLogicalExpression(print: print, node: T) { // if (!is_insideScrutinee(node)) return printBinaryishExpression(print, node); // } function shouldInlineLogicalExpression(node: Node) { if (is_LogicalExpression(node)) { if (is_StructLiteral(node.right)) return node.right.properties.length > 0; if (is_ArrayOrTupleLiteral(node.right)) return node.right.items.length > 0; } return false; } export function printUnaryExpression(leftDoc: Doc, node: T) { __DEV__: assert(is_UnaryExpression(node)); // if (unaryNeedsOuterParens(node)) { // return [leftDoc, group(["(", indent([softline, getPrintFn()("expression")]), softline, ")"])]; // } else { const printed = getPrintFn(node)("expression"); return group([leftDoc, printed]); // } } export function printIfBlock(print: print, node: T) { let printed: Doc = [ printIfBlockCondition(print, node), // printBlockBody(print, node), f` else ${print("else")}`, ]; const parent = getParentNode()!; if (is_ClosureBlock(node, parent)) { printed = parenthesize_if_break([indent([softline, printed]), softline]); } else if (!is_ElseBlock(node, parent)) { // if (needsParens(node)) { // printed = group(printed); // } // if (needsParens(node)) { // printed = group([indent([softline, printed]), softline]); // } else { // printed = group(printed); // } } return printed; } export function printIfBlockCondition(print: print, node: T) { if (!hasCondition(node)) return ""; // const id = Symbol("if"); // return ["if ", group(printCondition(print, node), { id }), ifBreak("", " ", { groupId: id })]; return f`if ${printCondition(print, node)}`; } // export function printMatchExpressionExpression(print: print, node: T) { // return ["match ", maybe_parenthesize_condition(print, node), " "]; // } export function printCondition(print: print, node: T) { return pathCall(node, "condition", (condition) => { if (!condition) return ""; if (needsParens(condition)) return [print(), " "]; const id = Symbol("condition"); const softlineStart = true; //!is_LetScrutinee(condition); //!is_LetScrutinee(getLeftMostCondition(condition)); const printed = [indent([softlineStart ? softline : "", print()]), softline]; return [group(printed, { id }), ifBreak("", " ", { groupId: id })]; return hasLetScrutineeCondition(node) ? printed // parenthesizing nested "let" throws 'unused_parens' : parenthesize_if_break(printed); }); } export function parenthesize_if_break(doc: Doc) { return conditionalGroup([doc, ["(", doc, ")"]], { shouldBreak: willBreak(doc) }); } function unwrapParenthesized(doc: Doc) { __DEV__: { const check = (doc: Doc) => Array.isArray(doc) && doc.length === 3 && doc[0] === "(" && doc[2] === ")"; assert(Array.isArray(doc) && check(doc.length === 1 ? doc[0] : doc), "Expected ['(', Doc, ')']", doc); } return doc.length === 1 ? doc[0][1] : doc[1]; } export function withParensIdentOnBreak(node: Node, printed: Doc) { return printed; const parens = needsParens(node); const grouped = group([indent([softline, parens ? unwrapParenthesized(printed) : printed]), softline]); return conditionalGroup([printed, parens ? ["(", grouped, ")"] : grouped], { shouldBreak: willBreak(printed) }); } function isSimplePattern(node: PatternNode | undefined) { if (!node) return false; switch (node.nodeType) { case NodeType.MacroInvocation: return false; case NodeType.ExpressionTypeCast: return isSimplePattern(node.typeCallee) && !hasComplexTypeArguments(node); case NodeType.ExpressionTypeSelector: return is_Identifier(node.typeTarget) && (!node.typeExpression || is_Identifier(node.typeExpression)); case NodeType.ExpressionPath: return !node.namespace || isSimplePattern(node.namespace); case NodeType.RangePattern: return (!node.lower || isSimplePattern(node.lower)) && (!node.upper || isSimplePattern(node.upper)); case NodeType.PatternVariableDeclaration: case NodeType.ReferencePattern: case NodeType.BoxPattern: case NodeType.MinusPattern: return isSimplePattern(node.pattern); case NodeType.Identifier: case NodeType.Literal: case NodeType.RestPattern: case NodeType.WildcardPattern: return true; default: return false; } } export function printUnionPattern(print: print, node: T) { if (node.patterns.length === 1) return print.map("patterns"); const parent = getParentNode(); const prebreak = parent && (is_VariableDeclarationNode(parent) || is_LetScrutinee(parent)) && !needsParens(node); return group([ prebreak ? softline : "", print.map("patterns", (node, i, arr) => [ withComments(node, [ i === 0 // ? ifBreak("| ") : "| ", align(2, print()), ]), i === arr.length - 1 ? "" : line, ]), ]); } export function printArrayLike(print: print, node: T) { const delims = getDelimChars(node.items); if (node.items.length === 0) { const comments = printDanglingCommentsForInline(node, DCM["items"]); return comments ? group([delims.left, comments, delims.right]) : delims.left + delims.right; } const groupId = Symbol("array"); const shouldBreak = // is_TupleStructDeclaration(node) || !is_TupleNode(node) && node.items.length > 1 && (node.items as (ExpressionNode | PatternNode)[]).every((item, i) => { const next = node.items[i + 1]; return ( ((hasProperties(item) && item.properties.length > 1) || (hasItems(item) && item.items.length > 1)) && (!next || item.nodeType === next.nodeType) ); }); const shouldUseConciseFormatting = isConciselyPrintedArray(node); const parent = getParentNode(node)!; const needsForcedTrailingComma = node.items.length === 1 ? is_TupleLiteral(node) ? is_RangeLiteral(node.items[0]) ? !(is_ReassignmentExpression(parent) && parent.left === node) : true : is_TuplePattern(node) ? !node.struct && !is_RangePattern(node.items[0]) && !is_RestPattern(node.items[0]) : is_TypeTuple(node) ? true : false : false; const trailingComma: Doc = needsForcedTrailingComma ? "," // : shouldUseConciseFormatting ? ifBreak(",", "", { groupId }) : ifBreak(","); const printed = shouldUseConciseFormatting // ? fill( print.join( "items", (item, next) => isNextLineEmpty(item) ? [",", hardline, hardline] : hasComment(next, CF.Leading, (comment) => is_LineCommentNode(comment) || comment.placement === "ownLine") ? [",", hardline] : [",", line], trailingComma ) ) : print.map_join( "items", () => group(print()), (item) => (isNextLineEmpty(item) ? [",", line, softline] : [",", line]), trailingComma ); return group([delims.left, indent([softline, printed]), printDanglingComments(node, true, DCM["items"]), softline, delims.right], { shouldBreak, id: groupId, }); } export function printObject(print: print, node: T): Doc { if (hasSemiNoProperties(node)) { return ";"; } if (!hasProperties(node)) { return [" {", printDanglingCommentsForInline(node, DCM["properties"]) || emptyContent(node), "}"]; } const firstProperty = node.properties[0]; const parent = getParentNode()!; const shouldBreak = is_StructPattern(node) ? false : is_UnionDeclaration(node) || is_StructDeclaration(node) || is_EnumMemberStructDeclaration(node) || hasNewlineInRange(start(node), start(firstProperty)); const content = [ " {", indent([ line, ...print.join( "properties", // (node) => (isNextLineEmpty(node) ? [",", hardline, hardline] : [",", line]), (node) => (is_StructSpread(node) ? "" : ifBreak(",")) ), ]), line, "}", ]; const grandparent = getGrandParentNode(); if ( grandparent && (is_FunctionDeclaration(grandparent) || is_ClosureFunctionExpression(grandparent)) && getParameters(grandparent)[0] === parent ) { return content; } if ( (is_StructLiteral(node) && is_ReassignmentNode(parent) && parent.left === node) || (is_StructPattern(node) && (is_VariableDeclarationNode(parent) || is_MatchExpressionCase(parent) || is_FunctionParameterDeclaration(parent)) && parent.pattern === node) ) { return content; } return group(content, { shouldBreak }); } export function printEnumBody(print: print, node: T): Doc { const printed = print.join("members", (member) => [",", maybeEmptyLine(member)], ","); return [ " {", printed.length === 0 ? printDanglingCommentsForInline(node, DCM["members"]) || emptyContent(node) : [indent([hardline, ...printed]), hardline], "}", ]; } ================================================ FILE: src/format/external.ts ================================================ import { Attribute, AttributeOrDocComment, Comment, DocCommentAttribute, LocArray, MemberExpression, Node, SourceFile } from "jinx-rust"; import { PickProps } from "jinx-rust/utils"; import type { Doc, ParserOptions, Printer } from "prettier"; import doc from "prettier/doc.js"; import { AssertTypesEq } from "../utils/common"; export type { Doc, ParserOptions, Plugin, Printer } from "prettier"; declare module "prettier/doc.js" { namespace utils { function canBreak(doc: Doc): boolean; } } export const { join, line, softline, hardline, literalline, group, conditionalGroup, fill, lineSuffix, lineSuffixBoundary, cursor, breakParent, ifBreak, trim, indent, indentIfBreak, align, addAlignmentToDoc, markAsRoot, dedentToRoot, dedent, hardlineWithoutBreakParent, literallineWithoutBreakParent, label, } = doc.builders; export const { isConcat, getDocParts, willBreak, traverseDoc, findInDoc, mapDoc, propagateBreaks, removeLines, stripTrailingHardline, normalizeParts, normalizeDoc, cleanDoc, canBreak, } = doc.utils; export const Symbol_comments = Symbol.for("comments"); export interface CustomOptions extends ParserOptions { [Symbol_comments]: AnyComment[]; rsParsedFile: SourceFile; commentSpans: Map; printer: Printer; cursorNode: any; comments: Comment[]; danglingAttributes: AttributeOrDocComment[]; actuallyMethodNodes: WeakSet; } export type NodeWithComments = T & { comments: AnyComment[] }; export interface MutatedComment extends Comment, PrettierCommentInfo {} export interface MutatedAttribute extends Attribute, PrettierCommentInfo {} export interface MutatedDocComment extends DocCommentAttribute, PrettierCommentInfo {} export type AnyComment = MutatedComment | MutatedAttribute | MutatedDocComment; type keyofDelimitedArrayProps = T extends never ? never : keyof PickProps">>; __DEV__: AssertTypesEq>(); export enum DCM { "arguments" = "arguments", "parameters" = "parameters", "items" = "items", "properties" = "properties", "members" = "members", "body" = "body", "cases" = "cases", "typeArguments" = "typeArguments", "ltParameters" = "ltParameters", "generics" = "generics", "specifiers" = "specifiers", "rules" = "rules", "match" = "match", "transform" = "transform", "segments" = "segments", } export interface PrettierCommentInfo { trailing: boolean; leading: boolean; unignore: boolean; printed: boolean; placement: "ownLine" | "endOfLine" | "remaining"; // nodeDescription?: any; marker?: DCM; } export interface AstPath { stack: (Node | string | number)[]; callParent(callback: (path: this) => R, count?: number): R; getName(): PropertyKey | null; getValue(): T; getNode(count?: number): T | null; getParentNode(count?: number): T | null; match(...predicates: ((node: Node, name: string | null, number: number | null) => boolean)[]): boolean; call(callback: (path: AstPath, index: number, value: any) => R, ...props: (string | number)[]): R; each(callback: (path: AstPath, index: number, value: any) => void, ...props: (string | number)[]): void; map(callback: (path: AstPath, index: number, value: any) => R, ...props: (string | number)[]): R[]; } ================================================ FILE: src/format/plugin.ts ================================================ import { AttributeOrComment, IfBlockExpression, Node, Program, rs } from "jinx-rust"; import { ArrayProps, BoolProps, NodeProps, end, hasAttributes, insertNodes, is_Attribute, is_BlockCommentKind, is_BlockCommentNode, is_Comment, is_DocCommentAttribute, is_ElseBlock, is_LineCommentNode, is_MacroInvocation, is_MacroRule, is_MissingNode, is_Node, is_PunctuationToken, is_UnionPattern, start, } from "jinx-rust/utils"; import { getCommentChildNodes, isTransformed, transform_ast } from "../transform"; import { Narrow, assert, color, each, exit, iLast, is_array, map_tagged_template, print_string } from "../utils/common"; import { CF, escapeComments, getComments, handleEndOfLineComment, handleOwnLineComment, handleRemainingComment, hasBreaklineAfter, hasComment, isDangling, isPrettierIgnoreAttribute, setDidPrintComment, withComments, } from "./comments"; import { withCheckContext } from "./complexity"; import { isNoopExpressionStatement, maybeEmptyLine } from "./core"; import { AstPath, CustomOptions, Doc, Plugin, Symbol_comments, group, hardline, indent, line, softline } from "./external"; import { printer } from "./printer"; import { needsInnerParens, needsOuterSoftbreakParens, shouldPrintOuterAttributesAbove } from "./styling"; export function is_printing_macro() { return getContext().path.stack.some((node) => is_Node(node) && (is_MacroInvocation(node) || is_Attribute(node))); } export function assertPathAtNode(name: string, node: Node, ...ctx: any[]) { __DEV__: if (getNode() !== node) exit(`Attempted to call ${name}() in wrong prettier path context`, { asserted: node, actual: getNode() }, ...ctx); } export function f(...args: [strings: TemplateStringsArray, ...values: Doc[]]) { let cancel = false; const res = map_tagged_template(args, (doc) => { cancel ||= !doc || (is_array(doc) && doc.length === 0); return doc; }); return cancel ? "" : res; } export function sg_single(s: TemplateStringsArray, v_0: Doc) { return group([s[0], indent([softline, v_0]), softline, s[1]]); } export function sg_duo(s: TemplateStringsArray, v_0: Doc, v_1: Doc) { return group([s[0], indent([softline, v_0, s[1], line, v_1]), softline, s[2]]); } let ctx: { path: AstPath; options: CustomOptions; print: (path?: AstPath | string | [], args?: any) => Doc; args: any; }; export const getNode = () => ctx.path.stack[ctx.path.stack.length - 1] as Node; export const stackIncludes = (x: Node | string | number) => ctx.path.stack.includes(x); export const getContext = () => ctx; export const getOptions = () => ctx.options; export const getProgram = () => ctx.options.rsParsedFile.program; export const getAllComments = () => ctx.options[Symbol_comments]; export const getParentNode = (child?: Node) => { __DEV__: if (child) assertPathAtNode("getParentNode", child); return ctx.path.getParentNode(); }; export const getGrandParentNode = () => ctx.path.getParentNode(1) as Node; export const getPrintFn = (forNode?: T | undefined): print => { __DEV__: if (forNode) assertPathAtNode("getPrintFn", forNode); return print as print; }; const get = (property: keyof any) => getNode()[property]; const has = (property: keyof any) => !!get(property); export function pathCall & keyof T, R>(node: T, key: K, fn: (child: T[K]) => R): R { return ctx.path.call(() => fn(getNode() as any), key as any); } export function pathCallEach>( node: T, key: K, // @ts-expect-error fn: (child: NonNullable[number], index: number) => void ) { __DEV__: assertPathAtNode("", node); // @ts-expect-error ctx.path.each((_, i) => fn(getNode() as any, i), key); } export function pathCallAtParent(parent: T, fn: (parent: T) => R): R { return ctx.path.callParent(() => { __DEV__: assertPathAtNode("pathCallParent", parent); return fn(parent); }); } export function pathCallParentOf(child: Node, fn: (parent: T) => R): R { __DEV__: assertPathAtNode("pathCallParentOf", child); return ctx.path.callParent((p) => fn(getNode() as any)); } export function pathCallTopMostIfBlockExpression(node: IfBlockExpression, fn: (node: IfBlockExpression) => R): R { const parent = getParentNode(node)!; return is_ElseBlock(node, parent) ? pathCallAtParent(parent, (parent) => pathCallTopMostIfBlockExpression(parent, fn)) : fn(node); } function print(property?: any, args?: any): Doc | Doc[] { if (!property) return ctx.print(undefined!, args); if (Array.isArray(property)) return ctx.print(property as any, args); const value = get(property); return !!value ? (Array.isArray(value) ? ctx.path.map(ctx.print, property) : ctx.print(property, args)) : ""; } namespace print { export function b(property: string, res = `${property} `): Doc { return has(property) ? res : ""; } export function map(property: string, mapItem?: MapFn): Doc[] { return !has(property) ? [] : ctx.path.map(mapItem ? (p, i, a) => mapItem(a[i], i, a) : () => ctx.print(), property); } export function join(property: string, sep: SepFn | Doc, trailingSep: TrailingSepFn | Doc = ""): Doc[] { return map_join(property, () => ctx.print(), sep, trailingSep); } export function map_join( property: string, mapFn: MapFn, sep: SepFn | Doc, sepTrailing: TrailingSepFn | Doc = "" ) { const sepFn = typeof sep === "function" ? sep : () => sep; return map(property, (v, i, a) => [ mapFn(v, i, a), iLast(i, a as any) ? typeof sepTrailing === "function" ? sepTrailing(v) : sepTrailing : sepFn(v, a[i + 1], i === 0 ? undefined : a[i - 1]), ]); } } // prettier-ignore type SepFn = AK> = >(item: A[number], next_item: A[number], prev_item: A[number] | undefined) => Doc; type MapFn = AK> = >(item: A[number], index: number, arr: A) => Doc; type TrailingSepFn = AK> = >(item: A[number]) => Doc; type AV = Extract, ReadonlyArray>; type AK = keyof ArrayProps & keyof T; // type AK = keyof PickProps & keyof T; export interface print { (property?: [], args?: any): Doc; (property?: [AK, number], args?: any): Doc; (property?: AK, args?: any): Doc[]; // (property?: T extends {rules:{nodeType:number}|{nodeType:number}[]} ? "rules" : never, args?: any): Doc[]; (property?: keyof NodeProps & keyof T, args?: any): Doc; b(property: keyof BoolProps, res?: string): Doc; map>(property: K & keyof ArrayProps, mapFn?: MapFn): Doc[]; join>(property: K, sep: SepFn | Doc, trailingSep?: TrailingSepFn | Doc): Doc[]; map_join>(property: K, mapFn: MapFn, sep: SepFn | Doc, trailingSep?: TrailingSepFn | Doc): Doc[]; } function genericPrint() { return withCheckContext(() => { const node = getNode(); __DEV__: assert(node.nodeType in printer); let printed: Doc = hasPrettierIgnore(node) // ? node.loc.getOwnText() : printer[node.nodeType]!(print as any, node as never); const inner_parens = needsInnerParens(node); if (inner_parens) { printed = group(["(", printed, ")"]); } if (hasAttributes(node)) { const print_above = shouldPrintOuterAttributesAbove(node); /* || node.attributes.length > 1 */ printed = [ ...print.join( "attributes", (attr) => print_above ? maybeEmptyLine(attr) : is_LineCommentNode(attr) || (is_BlockCommentNode(attr) && hasBreaklineAfter(attr)) ? hardline : " ", (attr) => print_above && is_DocCommentAttribute(attr) ? maybeEmptyLine(attr) : print_above || is_LineCommentNode(attr) || (is_BlockCommentNode(attr) && hasBreaklineAfter(attr)) ? hardline : " " ), printed, ]; } printed = withComments( node, printed, hasPrettierIgnore(node) || ((is_Attribute(node) || is_MacroInvocation(node)) && !isTransformed(node)) ? escapeComments(0, (comment) => node.loc.ownContains(comment)) : is_MacroRule(node) ? escapeComments(0, (comment) => node.transform.loc.contains(comment)) : is_UnionPattern(getParentNode() ?? ({ nodeType: 0 } as any)) ? new Set(getComments(node, 0, (comment) => !isDangling(comment))) : undefined ); if (!inner_parens && needsOuterSoftbreakParens(node)) { printed = [group(["(", indent([softline, printed]), softline, ")"])]; } return printed; }); function hasPrettierIgnore(node: Node) { return ( (node as any).prettierIgnore || hasComment(node, CF.PrettierIgnore) || (hasAttributes(node) && node.attributes.some(isPrettierIgnoreAttribute)) ); } } export function canAttachComment(n: Node) { return !is_Comment(n) && !isNoopExpressionStatement(n) && !is_MissingNode(n) && !is_PunctuationToken(n); } export const plugin: Plugin = { languages: [ { name: "Rust", aliases: ["rs"], parsers: ["jinx-rust"], extensions: [".rs", ".rs.in"], linguistLanguageId: 327, vscodeLanguageIds: ["rust"], tmScope: "source.rust", aceMode: "rust", codemirrorMode: "rust", codemirrorMimeType: "text/x-rustsrc", }, ], parsers: { "jinx-rust": { astFormat: "jinx-rust", locStart: start, locEnd: end, parse(code, parsers, options: CustomOptions) { ctx = { options } as any; options.rsParsedFile = rs.parseFile((options.originalText = code), { filepath: options.filepath }); options.actuallyMethodNodes = new WeakSet(); options.danglingAttributes = []; options.comments = []; transform_ast(options); const comments: AttributeOrComment[] = []; insertNodes(comments, options.comments); insertNodes(comments, options.danglingAttributes); // @ts-expect-error options.rsParsedFile.program.comments = comments; options.commentSpans = new Map(comments.map((n) => [start(n), end(n)])); return options.rsParsedFile.program; }, }, }, printers: { "jinx-rust": { preprocess: (node: Program) => node.loc.src, print(path, options, print, args) { if (path.stack.length === 1) { __DEV__: Narrow(options); ctx = { path, options, print, args }; try { const printed = genericPrint(); __DEV__: devEndCheck(printed); return printed; } finally { ctx = undefined!; } } else if (args || ctx.args) { const prev_args = ctx.args; try { ctx.args = args; return genericPrint(); } finally { ctx.args = prev_args; } } else { return genericPrint(); } }, hasPrettierIgnore: () => false, willPrintOwnComments: () => true, isBlockComment: is_BlockCommentKind, canAttachComment: canAttachComment, getCommentChildNodes: getCommentChildNodes, printComment: genericPrint, handleComments: { // @ts-expect-error avoidAstMutation: true, ownLine: handleOwnLineComment, endOfLine: handleEndOfLineComment, remaining: handleRemainingComment, }, }, }, options: {}, defaultOptions: { // default prettier (2) -> rustfmt (4) tabWidth: 4, // default prettier (80) -> rustfmt (100) printWidth: 100, }, }; function devEndCheck(printed: Doc) { let first = false; const comments = getAllComments(); each(comments, (comment, index) => { if (!comment.printed) { if (!first) (first = true), console.log(color.red(`Unprinted comments:`)); const len = 40; const msg = color.magenta( (comment.marker ? `Dangling "${comment.marker}" ` : "") + (is_Attribute(comment) ? "Attribute " : is_DocCommentAttribute(comment) ? "DocCommentAttribute" : "Comment") + ` ${index}/${comments.length}` + color.yellow(` ${print_string(comment.loc.sliceText(0, len))}${comment.loc.len() > len ? " ..." : ""}`) ) + color.grey(`\n at ${comment.loc.url()}`); if (globalThis.TESTS_FORMAT_DEV) exit(msg); else console.log(msg); setDidPrintComment(comment); } }); } ================================================ FILE: src/format/printer.ts ================================================ import { DelimKind, Node, NodeType, NTMap } from "jinx-rust"; import { getDelimChars, hasSuffix, is_ArrayOrTupleLiteral, is_BlockExpression, is_ClosureFunctionExpression, is_Identifier, is_IfBlockExpression, is_LiteralNumberLike, is_StructLiteral, start, } from "jinx-rust/utils"; import { BlockLikeMacroInvocation, CallLikeMacroInvocation, is_BlockLikeMacroInvocation, is_CallLikeMacroInvocation, isTransformed, } from "../transform"; import { exit } from "../utils/common"; import { hasComment, print_comment } from "./comments"; import { isSimpleType } from "./complexity"; import { adjustClause, parenthesize_if_break, printAnnotatedPattern, printArrayLike, printArrowFunction, printAssignment, printBinaryishExpression, printBlockBody, printBodyOrCases, printCallArguments, printCallExpression, printCondition, printDanglingCommentsForInline, printDeclarationTypeBounds, printEnumBody, printFlowControlExpression, printGenerics_x_whereBounds, printIfBlock, printIfBlockCondition, printImplTraitForType, printLtBounds, printLtParameters, printMacroRules, printMaybeBlockBody, printMemberExpression, printNumber, printObject, printParametersAndReturnType, printRuleMatch, printRuleTransform, printTypeAnnotation, printTypeArguments, printTypeBounds, printUnaryExpression, printUnionPattern, } from "./core"; import { DCM, Doc, group, hardline, ifBreak, indent, join, line, softline, willBreak } from "./external"; import { f, getOptions, getParentNode, pathCall, sg_duo, sg_single, type print } from "./plugin"; import { needsParens, stmtNeedsSemi } from "./styling"; type nPrint = (print: print, node: T) => Doc | never; export const printer: { [K in NodeType]: nPrint> } = { [NodeType.MissingNode](print, node) { return ""; }, [NodeType.SourceFile](print, node) { return [ print.b("UTF8BOM", "\uFEFF"), // print("shebang"), print("program"), ]; }, [NodeType.Shebang](print, node) { return [`#!${node.value}`, hardline]; }, [NodeType.Program](print, node) { return printBodyOrCases(print, node); }, [NodeType.Snippet](print, node) { exit.never(); }, [NodeType.Identifier](print, node) { return node.name; }, [NodeType.Index](print, node) { return node.name; }, [NodeType.LbIdentifier](print, node) { return node.name; }, [NodeType.McIdentifier](print, node) { return node.name; }, [NodeType.LtIdentifier](print, node) { return node.name; }, [NodeType.PunctuationToken](print, node) { return node.token; }, [NodeType.DelimGroup](print, node) { return node.loc.getOwnText(); }, [NodeType.Literal](print, node) { let { value } = node; if (is_LiteralNumberLike(node)) value = printNumber(value); return hasSuffix(node) ? [value, print("suffix")] : value; }, [NodeType.ItemPath](print, node) { return [print("namespace"), "::", print("segment")]; }, [NodeType.ExpressionPath](print, node) { return [print("namespace"), "::", print("segment")]; }, [NodeType.TypePath](print, node) { return [print("namespace"), "::", print("segment")]; }, [NodeType.Comment](print, node) { return print_comment(node); }, [NodeType.DocCommentAttribute](print, node) { return print_comment(node); }, [NodeType.Attribute](print, node) { return [ node.inner ? "#![" : "#[", isTransformed(node) ? [print("segments"), printDanglingCommentsForInline(node)] // : node.segments.loc.sliceText(1, -1).trim(), "]", ]; }, [NodeType.MacroInvocation](print, node) { const hasCurlyBrackets = node.segments.dk === DelimKind["{}"]; const delim = getDelimChars(node.segments); if (node.segments.length === 0) { return [print("callee"), "!", hasCurlyBrackets ? " " : "", delim.left, printDanglingCommentsForInline(node), delim.right]; } if (isTransformed(node)) { if (is_CallLikeMacroInvocation(node)) { return [print("callee"), "!", printCallArguments(print as print, node)]; } if (is_BlockLikeMacroInvocation(node)) { return [print("callee"), "!", " ", printBlockBody(print as print, node)]; } } let content = node.segments.loc.sliceText(1, -1); if (content.trim().length === 0) { content = ""; } else if (!content.includes("\n")) { content = content.trim(); if (hasCurlyBrackets) content = " " + content + " "; } return [print("callee"), "!", hasCurlyBrackets ? " " : "", delim.left, content, delim.right]; }, [NodeType.MacroRulesDeclaration](print, node) { return ["macro_rules! ", print("id"), printMacroRules(print, node)]; }, [NodeType.MacroRuleDeclaration](print, node) { return [printRuleMatch(print, node), " => ", printRuleTransform(print, node), ";"]; }, [NodeType.MacroDeclaration](print, node) { return [print("pub"), "macro ", print("id"), printMacroRules(print, node)]; }, [NodeType.MacroInlineRuleDeclaration](print, node) { return [printRuleMatch(print, node), " ", printRuleTransform(print, node)]; }, [NodeType.MacroGroup](print, node) { return node.loc.getOwnText(); }, [NodeType.MacroParameterDeclaration](print, node) { return [print("id"), ":", print("ty")]; }, [NodeType.PubSpecifier](print, node) { if (!node.location) return "pub "; if (is_Identifier(node.location)) { switch (node.location.name) { case "crate": if (start(node) === start(node.location)) { return "crate "; } else { return ["pub(", print("location"), ") "]; } case "self": case "super": return ["pub(", print("location"), ") "]; } } return ["pub(in ", print("location"), ") "]; }, [NodeType.ExternSpecifier](print, node) { return ["extern ", f`${print("abi")} `]; }, [NodeType.ExpressionStatement](print, node) { return [print("expression"), stmtNeedsSemi(node) ? ";" : ""]; }, [NodeType.UseStatement](print, node) { return [print("pub"), "use ", print("import"), ";"]; }, [NodeType.DestructuredImport](print, node) { if (node.specifiers.length === 0) return [print("source"), "::{", printDanglingCommentsForInline(node, DCM["specifiers"]), "}"]; let space = true; __DEV__: if (globalThis.TESTS_FORMAT_DEV) space = false; return [ print("source"), group([ "::{", indent([space ? line : softline, join([",", line], print("specifiers")), ifBreak(",")]), space ? line : softline, "}", ]), ]; }, [NodeType.AmbientImport](print, node) { return f`${print("source")}::*` || "*"; }, [NodeType.AnonymousImport](print, node) { return [print("source"), " as ", "_"]; }, [NodeType.NamedImport](print, node) { return [print("source"), f` as ${print("local")}`]; }, [NodeType.ExternCrateStatement](print, node) { return [print("pub"), "extern crate ", print("import"), ";"]; }, [NodeType.TypeAliasDeclaration](print, node) { return [ print("pub"), "type", printAssignment( printGenerics_x_whereBounds(print, node, printDeclarationTypeBounds(print, node, ":")), // " =", "typeExpression" ), ";", ]; }, [NodeType.LetVariableDeclaration](print, node) { return [ "let ", printAssignment( printAnnotatedPattern(print, node), // " =", "expression" ), f` else ${print("else")}`, ";", ]; }, [NodeType.ConstVariableDeclaration](print, node) { return [ print("pub"), "const ", printAssignment( printAnnotatedPattern(print, node), // " =", "expression" ), ";", ]; }, [NodeType.StaticVariableDeclaration](print, node) { return [ print("pub"), "static ", printAssignment( printAnnotatedPattern(print, node), // " =", "expression" ), ";", ]; }, [NodeType.ModuleDeclaration](print, node) { return [ print("pub"), // print.b("unsafe"), "mod ", print("id"), printMaybeBlockBody(print, node), ]; }, [NodeType.ExternBlockDeclaration](print, node) { return [ print("pub"), // print.b("unsafe"), "extern ", f`${print("abi")} `, printBlockBody(print, node), ]; }, [NodeType.FunctionDeclaration](print, node) { return [ print("pub"), print.b("const"), print.b("async"), print.b("unsafe"), print("extern"), "fn", printGenerics_x_whereBounds(print, node, printParametersAndReturnType(node)), printMaybeBlockBody(print, node), ]; }, [NodeType.FunctionSelfParameterDeclaration](print, node) { return group([print.b("ref", "&"), f`${print("lt")} `, print.b("mut"), "self", printTypeAnnotation(print, node)]); }, [NodeType.FunctionParameterDeclaration](print, node) { return group(printAnnotatedPattern(print, node)); }, [NodeType.FunctionSpread](print, node) { return "..."; }, [NodeType.StructDeclaration](print, node) { return [print("pub"), "struct", printGenerics_x_whereBounds(print, node, ""), printObject(print, node)]; }, [NodeType.StructPropertyDeclaration](print, node) { return [print("pub"), print("id"), printTypeAnnotation(print, node)]; }, [NodeType.TupleStructDeclaration](print, node) { return [print("pub"), "struct", printGenerics_x_whereBounds(print, node, printArrayLike(print, node)), ";"]; }, [NodeType.TupleStructItemDeclaration](print, node) { return [print("pub"), print("typeAnnotation")]; }, [NodeType.UnionDeclaration](print, node) { return [print("pub"), "union", printGenerics_x_whereBounds(print, node, ""), printObject(print, node)]; }, [NodeType.EnumDeclaration](print, node) { return [print("pub"), "enum", printGenerics_x_whereBounds(print, node, ""), printEnumBody(print, node)]; }, [NodeType.EnumMemberDeclaration](print, node) { return [ print("pub"), printAssignment( print("id"), // " =", "value" ), ]; }, [NodeType.EnumMemberTupleDeclaration](print, node) { return [ print("pub"), printAssignment( [print("id"), printArrayLike(print, node)], // " =", "value" ), ]; }, [NodeType.EnumMemberStructDeclaration](print, node) { return [ print("pub"), printAssignment( [print("id"), printObject(print, node)], // " =", "value" ), ]; }, [NodeType.TraitDeclaration](print, node) { return [ print("pub"), print.b("unsafe"), "trait", printGenerics_x_whereBounds(print, node, printDeclarationTypeBounds(print, node, ":")), adjustClause(node, printBlockBody(print, node)), ]; }, [NodeType.AutoTraitDeclaration](print, node) { return [ print("pub"), print.b("unsafe"), "auto trait ", print("id"), " ", printBlockBody(print, node as any), // see "transform.ts" ]; }, [NodeType.TraitAliasDeclaration](print, node) { return [ print("pub"), print.b("unsafe"), "trait", printGenerics_x_whereBounds(print, node, printDeclarationTypeBounds(print, node, " =")), ";", ]; }, [NodeType.ImplDeclaration](print, node) { return [ print("pub"), print.b("unsafe"), "impl", printGenerics_x_whereBounds(print, node, [print.b("const"), printImplTraitForType(print, node)]), adjustClause(node, printBlockBody(print, node)), ]; }, [NodeType.NegativeImplDeclaration](print, node) { return [ print("pub"), "impl", printGenerics_x_whereBounds(print, node, ["!", printImplTraitForType(print, node)]), " ", printBlockBody(print, node as any), // see "transform.ts" ]; }, [NodeType.ExpressionTypeSelector](print, node) { return group(["<", print("typeTarget"), f` as ${print("typeExpression")}`, ">"]); }, [NodeType.ExpressionTypeCast](print, node) { return [print("typeCallee"), f`::${printTypeArguments(print, node)}`]; }, [NodeType.ExpressionAsTypeCast](print, node) { return [print("expression"), " as ", print("typeExpression")]; }, [NodeType.ReturnExpression](print, node) { return ["return", printFlowControlExpression(print, node)]; }, [NodeType.BreakExpression](print, node) { return ["break", f` ${print("label")}`, printFlowControlExpression(print, node)]; }, [NodeType.ContinueExpression](print, node) { return ["continue", f` ${print("label")}`]; }, [NodeType.YieldExpression](print, node) { return ["yield", printFlowControlExpression(print, node)]; }, [NodeType.RangeLiteral](print, node) { return [print("lower"), "..", print.b("last", "="), print("upper")]; }, [NodeType.CallExpression](print, node) { return printCallExpression(print, node); }, [NodeType.MemberExpression](print, node) { return printMemberExpression(print, node); }, [NodeType.AwaitExpression](print, node) { return [print("expression"), ".await"]; }, [NodeType.UnwrapExpression](print, node) { return [print("expression"), "?"]; }, [NodeType.ParenthesizedExpression](print, node) { exit.never(); const shouldHug = !hasComment(node.expression) && (is_ArrayOrTupleLiteral(node.expression) || is_StructLiteral(node.expression)); if (shouldHug) return ["(", print("expression"), ")"]; return group(["(", indent([softline, print("expression")]), softline, ")"]); }, [NodeType.MinusExpression](print, node) { return printUnaryExpression("-", node); }, [NodeType.NotExpression](print, node) { return printUnaryExpression("!", node); }, [NodeType.OrExpression](print, node) { return printBinaryishExpression(print, node); }, [NodeType.AndExpression](print, node) { return printBinaryishExpression(print, node); }, [NodeType.ReassignmentExpression](print, node) { return printAssignment(print("left"), " =", "right"); }, [NodeType.UnassignedExpression](print, node) { return "_"; }, [NodeType.OperationExpression](print, node) { return printBinaryishExpression(print, node); }, [NodeType.ReassignmentOperationExpression](print, node) { return printAssignment(print("left"), " " + node.kind, "right"); }, [NodeType.ComparisonExpression](print, node) { return printBinaryishExpression(print, node); }, [NodeType.LetScrutinee](print, node) { return ["let ", printAssignment(print("pattern"), " =", "expression")]; }, [NodeType.ClosureFunctionExpression](print, node) { return printArrowFunction(print, node); }, [NodeType.ClosureFunctionParameterDeclaration](print, node) { return group(printAnnotatedPattern(print, node)); }, [NodeType.BlockExpression](print, node) { return [ f`${print("label")}: `, print.b("const"), print.b("async"), print.b("move"), print.b("unsafe"), printBlockBody(print, node), ]; }, [NodeType.LoopBlockExpression](print, node) { return [f`${print("label")}: `, "loop ", printBlockBody(print, node)]; }, [NodeType.WhileBlockExpression](print, node) { return [f`${print("label")}: `, "while ", printCondition(print, node), printBlockBody(print, node)]; }, [NodeType.ForInBlockExpression](print, node) { return [f`${print("label")}: `, "for ", print("pattern"), " in ", print("expression"), " ", printBlockBody(print, node)]; }, [NodeType.IfBlockExpression](print, node) { return [f`${print("label")}: `, printIfBlock(print, node)]; }, [NodeType.TryBlockExpression](print, node) { return [f`${print("label")}: `, "try ", printBlockBody(print, node)]; }, [NodeType.MatchExpression](print, node) { const id = Symbol("match"); const expr = print("expression"); const needs_parens = pathCall(node, "expression", needsParens); let printed: Doc = [ f`${print("label")}: `, "match ", needs_parens ? expr : group([indent([softline, expr]), softline], { id }), needs_parens ? " " : !willBreak(expr) ? ifBreak("", " ", { groupId: id }) : "" /* ifBreak("", " ", { groupId: id }) */, printBlockBody(print, node), ]; const parent = getParentNode()!; if (is_ClosureFunctionExpression(parent) && parent.expression === node) { printed = parenthesize_if_break([indent([softline, printed]), softline]); } return printed; }, [NodeType.MatchExpressionCase](print, node) { return group([ group(print("pattern")), " ", printIfBlockCondition(print, node), "=>", // (is_BlockExpression(node.expression) || is_IfBlockExpression(node.expression)) && !hasComment(node.expression, 0, (comment) => getOptions().danglingAttributes.includes(comment as any)) ? [" ", print("expression")] : group(indent([line, print("expression")])), ]); return printAssignment( [print("pattern"), " ", printIfBlockCondition(print, node)], // "=>", "expression" ); return [print("pattern"), " ", printIfBlockCondition(print, node)]; }, [NodeType.StructLiteral](print, node) { return [print("struct"), printObject(print, node)]; }, [NodeType.StructLiteralPropertyShorthand](print, node) { return print("value"); }, [NodeType.StructLiteralProperty](print, node) { return [print("key"), ": ", print("value")]; }, [NodeType.StructLiteralPropertySpread](print, node) { return ["..", print("expression")]; }, [NodeType.StructLiteralRestUnassigned](print, node) { return ".."; }, [NodeType.ArrayLiteral](print, node) { return printArrayLike(print, node); }, [NodeType.SizedArrayLiteral](print, node) { return sg_duo`[${print("initExpression")};${print("sizeExpression")}]`; }, [NodeType.TupleLiteral](print, node) { return printArrayLike(print, node); }, [NodeType.ReferenceExpression](print, node) { return printUnaryExpression(["&", print.b("mut")], node); }, [NodeType.RawReferenceExpression](print, node) { return printUnaryExpression(`&raw ${node.kind} `, node); }, [NodeType.DereferenceExpression](print, node) { return printUnaryExpression("*", node); }, [NodeType.BoxExpression](print, node) { return printUnaryExpression("box ", node); }, [NodeType.UnionPattern](print, node) { return printUnionPattern(print, node); }, [NodeType.ParenthesizedPattern](print, node) { exit.never(); return sg_single`(${print("pattern")})`; }, [NodeType.RestPattern](print, node) { return ".."; }, [NodeType.WildcardPattern](print, node) { return "_"; }, [NodeType.PatternVariableDeclaration](print, node) { return [print.b("ref"), print.b("mut"), printAssignment(print("id"), " @", "pattern")]; }, [NodeType.StructPattern](print, node) { return [print("struct"), printObject(print, node)]; }, [NodeType.StructPatternPropertyDestructured](print, node) { return [print("key"), ": ", print("pattern")]; }, [NodeType.StructPatternPropertyShorthand](print, node) { return [print.b("box"), print.b("ref"), print.b("mut"), print("id")]; }, [NodeType.TuplePattern](print, node) { return [print("struct"), printArrayLike(print, node)]; }, [NodeType.ArrayPattern](print, node) { return printArrayLike(print, node); }, [NodeType.ReferencePattern](print, node) { return ["&", print.b("mut"), print("pattern")]; }, [NodeType.BoxPattern](print, node) { return ["box ", print("pattern")]; }, [NodeType.MinusPattern](print, node) { return ["-", print("pattern")]; }, [NodeType.RangePattern](print, node) { return [print("lower"), "..", print.b("last", "="), print("upper")]; }, [NodeType.TypeCall](print, node) { return [print("typeCallee"), printTypeArguments(print, node)]; }, [NodeType.TypeCallNamedArgument](print, node) { return printAssignment(print("target"), " =", "typeExpression"); }, [NodeType.TypeCallNamedBound](print, node) { return [print("typeTarget"), printTypeBounds(":", print, node)]; }, [NodeType.LtElided](print, node) { return "'_"; }, [NodeType.LtStatic](print, node) { return "'static"; }, [NodeType.TypeNever](print, node) { return "!"; }, [NodeType.TypeInferred](print, node) { return "_"; }, [NodeType.GenericTypeParameterDeclaration](print, node) { return printAssignment( [print("id"), printTypeBounds(":", print, node)], // " =", "typeDefault" ); }, [NodeType.ConstTypeParameterDeclaration](print, node) { return [ "const ", printAssignment( [print("id"), printTypeAnnotation(print, node)], // " =", "typeDefault" ), ]; }, [NodeType.GenericLtParameterDeclaration](print, node) { return [print("id"), printLtBounds(":", print, node)]; }, [NodeType.WhereTypeBoundDeclaration](print, node) { return [printLtParameters(print, node), print("typeTarget"), printTypeBounds(":", print, node)]; }, [NodeType.WhereLtBoundDeclaration](print, node) { return [print("ltTarget"), printLtBounds(":", print, node)]; }, [NodeType.TypeTraitBound](print, node) { return [print.b("maybeConst", "~const "), print.b("optional", "?"), printLtParameters(print, node), print("typeExpression")]; }, [NodeType.TypeDynBounds](print, node) { return printTypeBounds("dyn", print, node); }, [NodeType.TypeImplBounds](print, node) { return printTypeBounds("impl", print, node); }, [NodeType.TypeFnPointer](print, node) { return [printLtParameters(print, node), print.b("unsafe"), print("extern"), "fn", printParametersAndReturnType(node)]; }, [NodeType.TypeFnPointerParameter](print, node) { return [f`${print("id")}: `, print("typeAnnotation")]; }, [NodeType.TypeFunction](print, node) { return [print("callee"), printParametersAndReturnType(node)]; }, [NodeType.TypeTuple](print, node) { return printArrayLike(print, node); }, [NodeType.TypeSizedArray](print, node) { return sg_duo`[${print("typeExpression")};${print("sizeExpression")}]`; if (isSimpleType(node)) return ["[", print("typeExpression"), "; ", print("sizeExpression"), "]"]; }, [NodeType.TypeSlice](print, node) { if (isSimpleType(node)) return ["[", print("typeExpression"), "]"]; return sg_single`[${print("typeExpression")}]`; }, [NodeType.TypeReference](print, node) { return ["&", f`${print("lt")} `, print.b("mut"), print("typeExpression")]; }, [NodeType.TypeDereferenceConst](print, node) { return ["*const ", print("typeExpression")]; }, [NodeType.TypeDereferenceMut](print, node) { return ["*mut ", print("typeExpression")]; }, [NodeType.TypeParenthesized](print, node) { exit.never(); return sg_single`(${print("typeExpression")})`; }, }; ================================================ FILE: src/format/styling.ts ================================================ import { ClosureFunctionExpression, ComparisonExpression, ConditionExpression, EnumDeclaration, EnumMemberStructDeclaration, ExpressionAsTypeCast, ExpressionNode, ExpressionStatement, ExpressionWithBody, LeftRightExpression, LogicalExpression, MacroDeclaration, MacroRulesDeclaration, MissingNode, Node, NodeType, NodeWithBody, NodeWithBodyOrCases, OperationExpression, PRCD, StructDeclaration, StructLiteral, StructPattern, TK, UnionDeclaration, } from "jinx-rust"; import { can_have_OuterAttributes, getAstPath, getPrecedence, hasAttributes, hasBody, hasCondition, hasItems, hasLetScrutineeCondition, hasOuterAttributes, hasProperties, is_Attribute, is_AttributeOrDocComment, is_AwaitExpression, is_BitwiseOperator, is_CallExpression, is_ClosureFunctionExpression, is_ComparisonExpression, is_DocCommentAttribute, is_ElseBlock, is_EnumMemberDeclaration, is_EqualityOperator, is_ExpressionAsTypeCast, is_ExpressionStatement, is_ExpressionWithBody, is_ExpressionWithBodyOrCases, is_ExpressionWithBodyOrCases_or_BlockLikeMacroInvocation, is_FlowControlExpression, is_FlowControlMaybeValueExpression, is_ForInBlockExpression, is_Identifier, is_IfBlockExpression, is_ImplicitReturnAbleNode, is_LeftRightExpression, is_LetScrutinee, is_Literal, is_LiteralNumberLike, is_LogicalExpression, is_LoopBlockExpression, is_MatchExpression, is_MatchExpressionCase, is_MemberExpression, is_NodeWithBodyNoBody, is_NodeWithMaybePatternNoUnionBody, is_OperationExpression, is_ParenthesizedNode, is_PatternVariableDeclaration, is_PostfixExpression, is_RangeLiteral, is_ReassignmentNode, is_ReturnExpression, is_StatementNode, is_StructLiteral, is_StructLiteralProperty, is_StructPatternProperty, is_StructPropertyDeclaration, is_TypeBoundsStandaloneNode, is_TypeFunctionNode, is_TypeTraitBound, is_UnaryExpression, is_UnaryType, is_UnionPattern, is_WhileBlockExpression, is_YieldExpression, is_bitshiftOperator, is_multiplicativeOperator, } from "jinx-rust/utils"; import { BlockLikeMacroInvocation, is_BlockLikeMacroInvocation, is_CallExpression_or_CallLikeMacroInvocation } from "../transform"; import { exit, last_of } from "../utils/common"; import { CF, hasBreaklineAfter, hasComment } from "./comments"; import { flowControlExpressionNeedsOuterParens } from "./core"; import { Doc, hardline, softline, willBreak } from "./external"; import { assertPathAtNode, getContext, getGrandParentNode, getNode, getOptions, getParentNode, getPrintFn, is_printing_macro, pathCallAtParent, pathCallParentOf, stackIncludes, } from "./plugin"; export function needsOuterSoftbreakParens(node: Node) { const parent = getParentNode(node); if (!parent) return false; if (is_ExpressionAsTypeCast(node)) { return precedenceNeedsParens(node, parent); } if ( is_FlowControlMaybeValueExpression(parent) && // parent.expression === node && flowControlExpressionNeedsOuterParens(parent) ) { return true; } if ( is_ExpressionWithBodyOrCases_or_BlockLikeMacroInvocation(node) && (false || (is_MemberExpression(parent) && parent.expression === node) || (is_ExpressionWithBodyOrCases_or_BlockLikeMacroInvocation(parent) && !is_ElseBlock(node, parent))) ) { return true; } if (is_UnionPattern(node) && is_NodeWithMaybePatternNoUnionBody(parent)) { return true; } if (hasComment(node)) { if (is_UnaryExpression(parent)) { return true; } if (hasComment(node, CF.Line)) { if (is_ReturnExpression(parent) || (is_YieldExpression(parent) && parent.expression === node)) { return true; } } if ( hasComment(node, CF.Leading, (comment) => is_Attribute(comment) && !comment.inner) && !can_have_OuterAttributes(node, parent, true) ) { return true; } } return false; } export function needsInnerParens(node: Node) { if (needsOuterSoftbreakParens(node)) { return false; } const parent = getParentNode(node); if (!parent) { return false; } if (is_Identifier(node)) { return false; } if (is_Literal(node)) { return is_LiteralNumberLike(node) && is_MemberExpression(parent) && node === parent.expression; } if (is_CallExpression(parent) && parent.callee === node && is_MemberExpression(node)) { return !getOptions().actuallyMethodNodes.has(node); } if (is_ReassignmentNode(node)) { if (is_printing_macro()) { return false; } if (is_ClosureFunctionExpression(parent) && node === parent.expression) { return true; } if (is_ExpressionStatement(parent)) { return is_StructLiteral(node.left); } if (is_ReassignmentNode(parent)) { return false; } return true; } if (is_ParenthesizedNode(parent)) { return false; } if (is_ExpressionStatement(parent)) { return false; } if (is_RangeLiteral(node)) { return ( is_ExpressionAsTypeCast(parent) || is_LogicalExpression(parent) || is_UnaryExpression(parent) || is_PostfixExpression(parent) || (is_MemberExpression(parent) && node === parent.expression) || (is_CallExpression(parent) && node === parent.callee) || is_OperationExpression(parent) || is_ComparisonExpression(parent) ); } if (is_LetScrutinee(parent) && is_LogicalExpression(node) && parent.expression === (node as any)) { return true; } if (is_UnaryExpression(node)) { switch (parent.nodeType) { case NodeType.MemberExpression: case NodeType.AwaitExpression: return node === parent.expression; case NodeType.CallExpression: return node === parent.callee; default: return false; } } if (is_ExpressionWithBodyOrCases_or_BlockLikeMacroInvocation(node)) { if (is_ExpressionWithBodyOrCases(parent)) { return !is_ElseBlock(node, parent); } if (is_LetScrutinee(parent) && parent.expression === node && is_ExpressionWithBodyOrCases(getGrandParentNode())) { return true; } return ( is_ExpressionAsTypeCast(parent) || is_LogicalExpression(parent) || is_UnaryExpression(parent) || is_PostfixExpression(parent) || (is_MemberExpression(parent) && node === parent.expression) || (is_CallExpression(parent) && node === parent.callee) || is_OperationExpression(parent) || is_ComparisonExpression(parent) || is_RangeLiteral(parent) ); } if (is_StructLiteral(node)) { if (is_ExpressionWithBodyOrCases(parent)) { return true; } if (is_LetScrutinee(parent) && parent.expression === node && is_ExpressionWithBodyOrCases(getGrandParentNode())) { return true; } if (is_UnaryExpression(parent) || is_PostfixExpression(parent) || is_MemberExpression(parent)) { return parent.expression === node; } if (is_CallExpression(parent)) { return parent.callee === node; } } if (is_LogicalExpression(node) || is_OperationExpression(node) || is_ComparisonExpression(node) || is_ClosureFunctionExpression(node)) { return precedenceNeedsParens(node, parent); } if (is_TypeFunctionNode(node)) { const gp = getGrandParentNode(); if (node.returnType && is_TypeTraitBound(parent) && is_TypeBoundsStandaloneNode(gp) && last_of(gp.typeBounds) !== parent) { return true; } } if (is_TypeBoundsStandaloneNode(node)) { return ( (is_UnaryType(parent) && node.typeBounds.length > 1) || is_TypeBoundsStandaloneNode(parent) || is_TypeTraitBound(parent) || (is_TypeFunctionNode(parent) && parent.returnType === node) ); } if (is_PatternVariableDeclaration(parent)) { return is_UnionPattern(node); } return false; } function precedenceNeedsParens(node: LeftRightExpression | ClosureFunctionExpression | ExpressionAsTypeCast, parent: Node) { if (is_UnaryExpression(parent) || is_PostfixExpression(parent)) return true; if (is_ReassignmentNode(parent)) return parent.left === node; if (is_MemberExpression(parent)) return parent.expression === node; if (is_CallExpression(parent)) return parent.callee === node; if (is_ExpressionAsTypeCast(parent)) return !is_ExpressionAsTypeCast(node); if (is_LogicalExpression(parent)) return is_LogicalExpression(node) ? parent.nodeType !== node.nodeType : evalPrecedence(node, parent); if (is_OperationExpression(parent) || is_ComparisonExpression(parent)) return evalPrecedence(node, parent); return false; function evalPrecedence( child: LeftRightExpression | ClosureFunctionExpression | ExpressionAsTypeCast, parent: ComparisonExpression | OperationExpression | LogicalExpression ) { if (is_ExpressionAsTypeCast(child) || is_ClosureFunctionExpression(child)) { return true; } function getPrec(node, bool) { // if (is_EqualityOperator(node.tk)) { // return 11.3; // } // if (is_LargerLesserOperator(node.tk)) { // return 11.6; // } return getPrecedence(node, bool); } const childPRCD = getPrec(child, is_insideScrutinee(child)); const parentPRCD = getPrec(parent, is_insideScrutinee(parent)); if (parentPRCD > childPRCD) { return true; } if (parentPRCD === childPRCD && parent.right === child) { return true; } if (parentPRCD === childPRCD && !shouldFlatten(parent, child)) { return true; } if (parentPRCD < childPRCD && child.tk === TK["%"]) { return parentPRCD === PRCD["+-"]; } if (is_BitwiseOperator(parent.tk) || (is_BitwiseOperator(child.tk) && is_EqualityOperator(parent.tk))) { return true; } return false; } } export function shouldFlatten(parent: ExpressionNode | ConditionExpression, node: ExpressionNode | ConditionExpression) { if (getPrecedence(node, is_insideScrutinee(node)) !== getPrecedence(parent, is_insideScrutinee(parent))) return false; if (is_ComparisonExpression(parent) && is_ComparisonExpression(node)) return false; if (is_OperationExpression(parent) && is_OperationExpression(node)) { if ( (node.tk === TK["%"] && is_multiplicativeOperator(parent.tk)) || (parent.tk === TK["%"] && is_multiplicativeOperator(node.tk)) || (node.tk !== parent.tk && is_multiplicativeOperator(node.tk) && is_multiplicativeOperator(parent.tk)) || (is_bitshiftOperator(node.tk) && is_bitshiftOperator(parent.tk)) ) return false; } return true; } export function needsParens(node: Node) { return needsOuterSoftbreakParens(node) || needsInnerParens(node); } export function stmtNeedsSemi(stmt: ExpressionStatement, disregardExprType = false) { return pathCallParentOf(stmt, (parent) => needsSemi(parent as any, stmt, disregardExprType)); } const NoNode = { nodeType: 0 } as MissingNode; export function needsSemi(parent: NodeWithBody, stmt: ExpressionStatement, disregardExprType = false) { const expr = disregardExprType ? NoNode : stmt.expression!; const hadSemi = !disregardExprType && stmt.semi; return ( !!expr && (forcePreserveSemi() ? true : shouldNeverSemi() ? false : shouldPreserveSemi() ? hadSemi || shouldAlwaysSemi() || canAutoCompleteSemi() : true) ); function forcePreserveSemi() { /** Rust Compiler bug (preserve optional semicolon) */ // rust-lang/rust#70844 https://github.com/rust-lang/rust/issues/70844 // issue#22 https://github.com/jinxdash/prettier-plugin-rust/issues/22 return ( hadSemi && stmt === last_of(parent.body!) && ((is_IfBlockExpression(expr) && hasLetScrutineeCondition(expr) && !(is_LetScrutinee(expr.condition) && is_Identifier(expr.condition.expression))) || (is_MatchExpression(expr) && !is_Identifier(expr.expression))) ); } function shouldNeverSemi() { return is_ExpressionWithBodyOrCases_or_BlockLikeMacroInvocation(expr); } function shouldPreserveSemi() { return stmt === last_of(parent.body!) && (is_ImplicitReturnAbleNode(parent) || is_BlockLikeMacroInvocation(parent)); } function shouldAlwaysSemi() { return is_FlowControlExpression(expr) || is_ReassignmentNode(expr); } function canAutoCompleteSemi() { return withPathAt(parent, function checkParent(child: NodeWithBodyOrCases): boolean { return pathCallParentOf(child, (parent) => { if (is_IfBlockExpression(parent) && parent.else === child) { // if ... { ... } else if { ... } ... // ^ ------------------------------- parent // ^ ----------- child return checkParent(parent); } if (is_ExpressionStatement(parent)) { // { .... { ... } ... } // ^ -----------------^ grandparent // ^ --- ^ ExpressionStatement if (hasOuterAttributes(parent)) return false; return stmtNeedsSemi(parent, true); } if (is_MatchExpressionCase(parent) && parent.expression === child) { return pathCallParentOf(parent, checkParent); } return false; }); }); } } export function canInlineBlockBody(node: NodeWithBodyOrCases | BlockLikeMacroInvocation): boolean { if (!is_ExpressionWithBody(node)) { return false; } const body = node.body; if (body.length === 0) { return canInlineInlineable(node); } if (body.length === 1) { const stmt = body[0]; if (is_AttributeOrDocComment(stmt)) { return true; } if (is_ExpressionStatement(stmt) && !needsSemi(node, stmt)) { /** * parent ( ExpressionStatement | StructLiteralProperty | LetVariableDeclaration | ... ) * ... * node { * expr * } * ... * * * Q: Can you inline "node { expr }" ? */ const expr = stmt.expression!; if ( is_FlowControlExpression(expr) || // is_ClosureFunctionExpression(expr) || is_ExpressionWithBodyOrCases_or_BlockLikeMacroInvocation(expr) ) { return false; } return canInlineInlineable(node); } } return false; } // function q(node: ExpressionWithBody) { // pathCallTopMostIfBlockExpression(node, (node) => {}); // } function canInlineInlineable(node: ExpressionWithBody) { if (is_ForInBlockExpression(node) || is_LoopBlockExpression(node)) { return false; } if (is_WhileBlockExpression(node)) { return true; } const parent = getParentNode(node)!; if ( is_ExpressionStatement(parent) && (!is_ImplicitReturnAbleNode(node) || pathCallAtParent(parent, (parent) => stmtNeedsSemi(parent, true))) ) { return false; } if (is_ElseBlock(node, parent)) { return pathCallAtParent(parent, canInlineBlockBody); } // if (is_CaseBlock(node, parent)) { // return false; // } if (is_IfBlockExpression(node)) { if ( !node.else || // hasLetScrutineeCondition(node) || is_ExpressionWithBodyOrCases_or_BlockLikeMacroInvocation(node.condition) || willBreak(getPrintFn(node)("condition")) ) { return false; } const grandparent = getGrandParentNode(); if (is_ExpressionStatement(parent) && hasBody(grandparent) && grandparent.body.length > 1) { return false; } } return true; return ( is_CallExpression_or_CallLikeMacroInvocation(parent) || hasItems(parent) || hasProperties(parent) || is_ClosureFunctionExpression(parent) || is_MemberExpression(parent) || is_AwaitExpression(parent) || is_LeftRightExpression(parent) ); } type NodeWithBracketContent = | NodeWithBodyOrCases | BlockLikeMacroInvocation | EnumDeclaration | StructDeclaration | StructLiteral | StructPattern | EnumMemberStructDeclaration | UnionDeclaration | MacroRulesDeclaration | MacroDeclaration; export function emptyContent(node: NodeWithBracketContent): Doc { switch (node.nodeType) { case NodeType.Program: case NodeType.MacroRulesDeclaration: case NodeType.MacroDeclaration: case NodeType.ExternBlockDeclaration: case NodeType.ModuleDeclaration: case NodeType.TraitDeclaration: case NodeType.StructDeclaration: case NodeType.MacroInvocation: case NodeType.FunctionDeclaration: case NodeType.ImplDeclaration: case NodeType.UnionDeclaration: case NodeType.EnumDeclaration: case NodeType.EnumMemberStructDeclaration: case NodeType.StructLiteral: case NodeType.StructPattern: // case NodeType.MatchExpression: return ""; case NodeType.BlockExpression: case NodeType.WhileBlockExpression: case NodeType.ForInBlockExpression: case NodeType.TryBlockExpression: case NodeType.IfBlockExpression: return canInlineInlineable(node) ? is_IfBlockExpression(node) || is_ElseBlock(node, getParentNode()!) ? softline : "" : hardline; case NodeType.LoopBlockExpression: case NodeType.MatchExpression: return hardline; default: if (is_NodeWithBodyNoBody(node)) { return ""; } __DEV__: exit.never(node); return ""; } } export function is_insideScrutinee(target: Node) { return withPathAt(target, (n) => stackIncludes("condition") && r(n)); function r(CHILD: Node) { switch (CHILD.nodeType) { case NodeType.OrExpression: case NodeType.AndExpression: return pathCallParentOf(CHILD, (PARENT) => hasCondition(PARENT) && PARENT.condition === CHILD // ? hasLetScrutineeCondition(PARENT) : r(PARENT) ); case NodeType.LetScrutinee: return true; default: return false; } } } function withPathAt(target: T, callback: (target: T) => R): R { if (target === getNode()) return callback(target); if (target === getParentNode()) return pathCallAtParent(target, () => callback(target)); if (stackIncludes(target)) return pathCallAtParent(getParentNode()!, () => withPathAt(target, callback)); return getContext().path.call(() => { __DEV__: assertPathAtNode("withPathAt", target); return callback(target); // @ts-ignore }, ...getAstPath(getNode(), target)); } export function shouldPrintOuterAttributesAbove(node: Node) { return ( is_StatementNode(node) || is_MatchExpressionCase(node) || (hasAttributes(node) && node.attributes.some( canInlineOuterAttribute(node) ? (attr) => is_DocCommentAttribute(attr) || hasBreaklineAfter(attr) // : is_DocCommentAttribute )) ); function canInlineOuterAttribute(node: Node) { return ( is_EnumMemberDeclaration(node) || is_StructPropertyDeclaration(node) || is_StructLiteralProperty(node) || is_StructPatternProperty(node) ); } } ================================================ FILE: src/index.ts ================================================ import { plugin } from "./format/plugin"; export default plugin; export const languages = plugin.languages; export const parsers = plugin.parsers; export const printers = plugin.printers; export const options = plugin.options; export const defaultOptions = plugin.defaultOptions; ================================================ FILE: src/transform/custom/attribute.ts ================================================ import { AttrSegment, CallExpression, DelimKind, ExpressionPath, Identifier, Literal, LocArray, MacroInvocation, NodeType, PunctuationToken, ReassignmentExpression, TK, rs, } from "jinx-rust"; import { isTK, start } from "jinx-rust/utils"; import { assert, exit } from "../../utils/common"; import { isIdent } from "./utils"; type SimpleAttrItem = | Identifier // | Literal | ExpressionPath | CallExpression | ReassignmentExpression | MacroInvocation; export function transform_simpleAttrSyntax(segments: MacroInvocation["segments"]) { assert(segments.length !== 0, segments.loc.url()); return transform_segments(segments, false); function transform_segments( seq: LocArray, nestedCall: N ): N extends true ? LocArray : SimpleAttrItem { let i = 0; if (nestedCall) { const args = rs.createLocArray(DelimKind["()"], seq.loc.clone()); while (i !== seq.length) { args.push(read(true)); if (i === seq.length) break; assert(isTK(seq[i++], TK[","])); } return args as any; } else { const res = read(true); assert(i === seq.length, res.loc.url()); return res as any; } function read(allowEq: boolean): SimpleAttrItem { let lhs: Identifier | ExpressionPath; switch (seq[i].nodeType) { case NodeType.Literal: return seq[i++] as Literal; case NodeType.Identifier: lhs = seq[i++] as Identifier; break; case NodeType.PunctuationToken: assert((seq[i] as PunctuationToken).tk === TK["::"], seq[i].loc.url()); lhs = eatPathSegment(undefined); break; default: exit.never(); } while (true) { if (i === seq.length) return lhs; const seg = seq[i]; switch (seg.nodeType) { case NodeType.PunctuationToken: switch (seg.tk) { case TK[","]: assert(nestedCall); return lhs; case TK["="]: { assert(allowEq); const right = (i++, read(false)); return rs.mockNode(NodeType.ReassignmentExpression, right.loc.cloneFrom(start(lhs)), { tk: TK["="], kind: DelimKind["="], left: lhs, right, }); } case TK["::"]: lhs = eatPathSegment(lhs); continue; default: exit.never(); } case NodeType.DelimGroup: assert(seg.segments.dk === DelimKind["()"]); return rs.mockNode(NodeType.CallExpression, seq[i++].loc.cloneFrom(start(lhs)), { callee: lhs, typeArguments: undefined, method: undefined, arguments: transform_segments(seg.segments, true), }); default: exit.never(); } } } function eatPathSegment(left: undefined | Identifier | ExpressionPath) { const segment = seq[i + 1]; assert(isIdent(segment)); const res = rs.mockNode(NodeType.ExpressionPath, segment.loc.cloneFrom(start(left ?? seq[i])), { namespace: left, segment }); i += 2; return res; } } } ================================================ FILE: src/transform/custom/cfg_if.ts ================================================ import { DelimGroup, DelimKind, IfBlockExpression, LocArray, MacroInvocation, NodeType, NodeWithBody, rs, Segment, Snippet, StatementNode, TK, } from "jinx-rust"; import { insertNodes, start, transferAttributes } from "jinx-rust/utils"; import { assert, iLast } from "../../utils/common"; import { isGroup, isIdent, isToken } from "./utils"; export function transform_macro_cfg_if(segments: MacroInvocation["segments"]) { const danglingAttributes: Snippet["danglingAttributes"] = []; const comments: Snippet["comments"] = []; const block = (function create_if_block(i: number): IfBlockExpression | undefined { if (i >= segments.length) return undefined; const _if = segments[i]; const pound = segments[i + 1]; const grp = segments[i + 2]; const block = segments[i + 3]; const _else = segments[i + 4]; assert( isIdent(_if, "if") && isToken(pound, TK["#"]) && isGroup(grp, DelimKind["[]"]) && isGroup(block, DelimKind["{}"]) && (!_else || isIdent(_else, "else")) ); return create_block(block, (body) => rs.mockNode(NodeType.IfBlockExpression, block.loc.cloneFrom(start(_if)), { label: undefined, condition: rs.mockNode(NodeType.Attribute, grp.loc.cloneFrom(start(pound)), { segments: grp.segments, value: grp.segments.loc.sliceText(), line: false, inner: false, }) as any, body: body, else: (_else && iLast(i + 5, segments) ? function create_else_block(i: number) { const block = segments[i]; assert(isGroup(block, DelimKind["{}"])); return create_block(block, (body) => rs.mockNode(NodeType.BlockExpression, body.loc.clone(), { label: undefined, body, }) ); } : create_if_block)(i + 5), }) ); })(0); const ast = rs.createLocArray( segments.dk, segments.loc, block && [ rs.mockNode(NodeType.ExpressionStatement, block.loc.clone(), { expression: block, semi: false, }), ] ); return rs.mockNode(NodeType.Snippet, segments.loc.clone(), { ast, danglingAttributes, comments }); function create_block( group: DelimGroup & { segments: { dk: 3 } }, fn: (statements: LocArray) => R ): R { const snippet = rs.toBlockBody(group.segments); insertNodes(danglingAttributes, snippet.danglingAttributes); insertNodes(comments, snippet.comments); const block = fn(snippet.ast); transferAttributes(snippet, block); return block; } } ================================================ FILE: src/transform/custom/utils.ts ================================================ import { DelimGroup, DelimKind, Identifier, LocArray, PunctuationToken, Segment, TK } from "jinx-rust"; import { isTK, is_DelimGroup, is_Identifier, is_PunctuationToken } from "jinx-rust/utils"; export function isIdent(node: Segment | undefined, name?: string): node is Identifier { return !!node && is_Identifier(node) && (null == name || node.name === name); } export function isToken(node: Segment | undefined, tk?: TK): node is PunctuationToken { return !!node && (null == tk ? is_PunctuationToken(node) : isTK(node, tk)); } export function isGroup(node: Segment | undefined, dk?: D): node is DelimGroup & { segments: LocArray } { return !!node && is_DelimGroup(node) && (null == dk || node.segments.dk === dk); } export function isCallLike(tk_1: Segment | undefined, tk_2: Segment | undefined): boolean { return !!tk_1 && !!tk_2 && is_Identifier(tk_1) && is_DelimGroup(tk_2) && tk_2.segments.dk === DelimKind["()"]; } ================================================ FILE: src/transform/index.ts ================================================ import { Attribute, AttributeOrDocComment, CallExpression, DelimKind, ExpressionNode, LocArray, MacroInvocation, MemberExpression, Node, NodeType, NodeWithBodyNoBody, NodeWithTypeBounds, NTMap, ProgramLike, rs, Snippet, StatementNode, StructLiteral, StructPattern, TK, TypeBound, TypeBoundsStandaloneNode, TypeDynBounds, TypeTraitBound, } from "jinx-rust"; import { countActualNodeChildren, deleteAttributes, each_childNode, end, getActualNodeChildren, getBodyOrCases, getMacroName, getNodeChildren, hasAttributes, hasMethod, hasTypeBounds, includesTK, insertNode, insertNodes, is_AttributeOrDocComment, is_BareTypeTraitBound, is_BlockExpression, is_CallExpression, is_ClosureFunctionExpression, is_DocCommentAttribute, is_ExpressionStatement, is_ExpressionWithBodyOrCases, is_FlowControlExpression, is_IfBlockExpression, is_MacroInvocation, is_Node, is_NodeWithBodyNoBody, is_NodeWithBodyOrCases, is_Program, is_PunctuationToken, is_ReassignmentNode, is_Snippet, is_TypeBoundsStandaloneNode, is_TypeDynBounds, is_TypeImplBounds, is_TypeTraitBound, ownStart, reassignNodeProperty, start, transferAttributes, unsafe_set_nodeType, } from "jinx-rust/utils"; import { isPrettierIgnoreAttribute, setPrettierIgnoreTarget } from "../format/comments"; import { is_StructSpread } from "../format/core"; import { CustomOptions } from "../format/external"; import { getOptions } from "../format/plugin"; import { Array_replace, Array_splice, assert, binarySearchIn, each, exit, iLast, last_of, Map_get, spliceAll, try_eval, } from "../utils/common"; import { transform_simpleAttrSyntax } from "./custom/attribute"; import { transform_macro_cfg_if } from "./custom/cfg_if"; export interface ExpressionLikeAttribute extends Attribute { segments: LocArray; } export interface CallLikeMacroInvocation extends MacroInvocation { segments: LocArray; callee: MacroInvocation["callee"]; method: undefined; typeArguments: undefined; arguments: LocArray; } export interface BlockLikeMacroInvocation extends MacroInvocation { segments: LocArray; body: LocArray; attributes?: AttributeOrDocComment[]; } export function is_CallLikeMacroInvocation(node: Node): node is CallLikeMacroInvocation { return is_MacroInvocation(node) && "arguments" in node; } export function is_BlockLikeMacroInvocation(node: Node): node is BlockLikeMacroInvocation { return is_MacroInvocation(node) && "body" in node; } export function is_CallExpression_or_CallLikeMacroInvocation(node: any): node is CallExpression | CallLikeMacroInvocation { return is_CallExpression(node) || is_CallLikeMacroInvocation(node); } const IGNORED_MACROS = new Set([ // std // crates "quote", ]); const HARDCODED_MACRO_DELIMS = new Map(); each( { [DelimKind["{}"]]: [ // std "thread_local", // crates "cfg_if", ], [DelimKind["()"]]: [ // std "assert_eq", "assert_ne", "assert", "cfg", "concat_bytes", "concat_idents", "concat", "debug_assert_eq", "debug_assert_ne", "debug_assert", "eprint", "eprintln", "format_args_nl", "format_args", "format", "matches", "panic", "print", "println", "try", "unimplemented", "unreachable", "write", "writeln", // crates ], [DelimKind["[]"]]: [ // std "vec", // crates ], }, (names, tk) => each(names, (name) => { HARDCODED_MACRO_DELIMS.set(name, +tk as MacroInvocation["segments"]["dk"]); }) ); let _COMMENTS: CustomOptions["comments"] = undefined!; let _DANGLING_ATTRIBUTES: CustomOptions["danglingAttributes"] = undefined!; export function transform_ast(options: CustomOptions) { try { _COMMENTS = options.comments; _DANGLING_ATTRIBUTES = options.danglingAttributes; transformNode(options.rsParsedFile); } finally { _depth = 0; _COMMENTS = undefined!; _DANGLING_ATTRIBUTES = undefined!; } } let _depth = 0; const isReadingSnippet = () => 0 !== _depth; function maybe_transform_node( node: T, read_snippet: () => S, fn: (node: T, snippet: S) => void ): T | undefined { const snippet = try_eval(read_snippet); if (snippet) { ++_depth; transformNode(snippet); --_depth; fn(node, snippet); transformed.add(node); return node; } } const transformed = new WeakSet(); export function isTransformed(node: Node) { return transformed.has(node); } const transform: { [K in NodeType]?: (node: NTMap[K]) => void } = { [NodeType.Attribute](node) { try_eval(() => { node.segments = rs.createLocArray(node.segments.dk, node.segments.loc.clone(), [ transform_simpleAttrSyntax(node.segments), ]) as any; transformed.add(node); }); }, [NodeType.MacroInlineRuleDeclaration](node) { node.match.dk = DelimKind["()"]; node.transform.dk = DelimKind["{}"]; }, [NodeType.MacroInvocation](node) { const name = getMacroName(node); if ( IGNORED_MACROS.has(name) || node.segments.length === 0 || (node.segments.length === 1 && is_PunctuationToken(node.segments[0])) ) { return; } const tk = transformMacroDelim(name, node); if (name === "matches") { // } if (name === "if_chain") { // } if (name === "cfg_if") { transformBlockLike(() => transform_macro_cfg_if(node.segments) as any); } else if (tk === DelimKind["{}"]) { transformBlockLike(); /* || (includesTK(node, TK[","]) && transformCallLike()); */ } else { transformCallLike(); /* || (includesTK(node, TK[";"]) && transformBlockLike()); */ } function transformBlockLike(transform = () => rs.toBlockBody(node.segments)) { return maybe_transform_node(node as BlockLikeMacroInvocation, transform, (node, snippet) => { const _body = snippet.ast; _body.dk = tk; node.body = _body; node.segments = _body; transferAttributes(snippet, node); }); } function transformCallLike() { return maybe_transform_node( node as CallLikeMacroInvocation, () => rs.toCallExpressionArguments(node.segments), (node, snippet) => { const _arguments = snippet.ast; _arguments.dk = tk; node.method = undefined; node.typeArguments = undefined; node.arguments = _arguments; node.segments = _arguments; } ); } }, [NodeType.CallExpression](node) { if (hasMethod(node)) { node.callee = rs.mockNode(NodeType.MemberExpression, node.method.loc.cloneFrom(start(node.callee)), { expression: node.callee, property: node.method, computed: false, }); node.method = undefined!; getOptions().actuallyMethodNodes.add(node.callee as MemberExpression); } }, [NodeType.AutoTraitDeclaration](node) { mockBodyNoBody(node); }, [NodeType.NegativeImplDeclaration](node) { mockBodyNoBody(node); }, [NodeType.StructLiteral](node) { moveSpreadsToEnd(node); }, [NodeType.StructPattern](node) { moveSpreadsToEnd(node); }, }; function moveSpreadsToEnd(node: StructLiteral | StructPattern) { const props = node.properties; if (props.some((p, i, a) => is_StructSpread(p) && !iLast(i, a))) { const spreads: any[] = []; for (let i = 0; i < props.length; i++) { const prop = props[i]; if (is_StructSpread(prop)) { Array_splice(props, prop, i--); spreads.push(prop); } } props.push(...spreads); } } function mockBodyNoBody(node: NodeWithBodyNoBody) { // @ts-expect-error node.body = rs.createLocArray(last_of(rs.toTokens(node).ast).loc.clone(), DelimKind["{}"]); } function transformMacroDelim(name: string, node: MacroInvocation): 1 | 2 | 3 { if (HARDCODED_MACRO_DELIMS.has(name)) { return HARDCODED_MACRO_DELIMS.get(name)!; } if (node.segments.dk === DelimKind["{}"] && includesTK(node, TK[","])) { return DelimKind["()"]; } if (node.segments.dk === DelimKind["()"] && includesTK(node, TK[";"])) { return DelimKind["{}"]; } return node.segments.dk; } // export function createTransformed(create: () => S): S { // return transformNode(create()); // } const seen = new WeakSet(); function transformNode(node: T, parent?: Node, key?: string, index?: any): T { if (!seen.has(node)) { seen.add(node); if (is_Snippet(node) || is_Program(node)) { registerPogramLike(node); } each_childNode(node, transformNode); insert_blocks(node, parent, key, index); transform[node.nodeType]?.(node as any); flatten_typeBounds(node); transform_nodeAttributes(node); } return node; } function insert_blocks(node: Node, parent?: Node, key?: string, index?: any) { if (parent && key) { if ( !is_ExpressionStatement(parent) && (false || // "1 + break" -> "1 + { break; }" is_FlowControlExpression(node) || // "1 + a = b" -> "1 + { a = b; }" (!isReadingSnippet() && is_ReassignmentNode(node) && !(is_ReassignmentNode(parent) && parent.left === node))) ) { reassignNodeProperty(blockify(node), parent, key, index); } else if ( is_ClosureFunctionExpression(node) && (false || // "|| -> T x" -> "|| -> T { x }" (!!node.returnType && !is_BlockExpression(node.expression)) || // "|| match x {}" -> "|| { match x {} }" (is_ExpressionWithBodyOrCases(node.expression) && !is_BlockExpression(node.expression) && !is_IfBlockExpression(node.expression))) ) { node.expression = blockify(node.expression); } } function blockify(node: ExpressionNode) { const block = rs.mockNode(NodeType.BlockExpression, node.loc.clone(), { label: undefined, body: rs.createLocArray(DelimKind["{}"], node.loc.clone(), [ rs.mockNode(NodeType.ExpressionStatement, node.loc.clone(), { semi: false, expression: node }), ]), }); transferAttributes(node, block); return block; } } function flatten_typeBounds(topNode: Node) { if (hasTypeBounds(topNode)) { const nestedBounds: TypeTraitBound[] = topNode.typeBounds.filter(isBoundWithNestedBounds); const [first, ...subsequent] = nestedBounds; const flatten = (bound: TypeTraitBound) => Array_replace(topNode.typeBounds, bound, ...(bound.typeExpression as unknown as TypeDynBounds).typeBounds); if (nestedBounds.every(isBareBoundWithNestedBoundsNoPrefix)) { // A + (B + C) // -> A + B + C each(nestedBounds, flatten); } else if ( !hasDefinedPrefix(topNode) && first === topNode.typeBounds[0] && !isBareBoundWithNestedBoundsNoPrefix(first) && subsequent.every(isBareBoundWithNestedBoundsNoPrefix) ) { if (is_TypeDynBounds(topNode)) { if (is_TypeImplBounds(first.typeExpression)) { // (impl A) + B // -> impl A + B unsafe_set_nodeType(topNode, NodeType.TypeImplBounds); } else { // (dyn A) + B // -> dyn A + B topNode.dyn = true; } each(nestedBounds, flatten); } else { each(subsequent, flatten); (first.typeExpression as unknown as TypeDynBounds).typeBounds.push(...topNode.typeBounds.slice(1)); topNode.typeBounds.length = 1; } } } function isBoundWithNestedBounds(bound: TypeBound): bound is TypeTraitBound & { typeExpression: TypeBoundsStandaloneNode } { return is_TypeTraitBound(bound) && is_TypeBoundsStandaloneNode(bound.typeExpression); } function isBareBoundWithNestedBounds(bound: TypeBound): bound is TypeTraitBound & { typeExpression: TypeBoundsStandaloneNode } { return isBoundWithNestedBounds(bound) && is_BareTypeTraitBound(bound); } function isBareBoundWithNestedBoundsNoPrefix(bound: TypeBound): bound is TypeTraitBound & { typeExpression: TypeDynBounds } { return isBareBoundWithNestedBounds(bound) && !hasDefinedPrefix(bound.typeExpression); } function hasDefinedPrefix(node: NodeWithTypeBounds) { return (is_TypeDynBounds(node) && node.dyn) || is_TypeImplBounds(node); } } function transform_nodeAttributes(node: Node) { /** * # Inside Token trees: * * 1. DocCommentAttribute --is parsed as--> Comment * 2. Attribute --is parsed as--> Token<'#'>, DelimGroup<'[]'> * * # Transforming tokens into a Snippet: * * 1. DocCommentAttribute <--replace from-- Comment * a) Remove node with same loc from comments * b) Merge Snippet.danglingAttributes with Program.danglingAttributes * * 2. Attribute (no action needed) * */ if (hasAttributes(node)) { const attrs = node.attributes; for (let i = 0; i < attrs.length; i++) { const attr = attrs[i]; if (isReadingSnippet() && is_DocCommentAttribute(attr)) { const index = binarySearchIn(_COMMENTS, start(attr), start); __DEV__: assert(index !== -1), assert(end(_COMMENTS[index]) === end(attr)); _COMMENTS.splice(index, 1); } if (attr.inner) { if (isPrettierIgnoreAttribute(attr)) { setPrettierIgnoreTarget(is_Program(node) ? node.loc.src : node, attr); } // @ts-expect-error Inserting Attribute into StatementNode[] insertNode(is_Snippet(node) ? node.ast : getBodyOrCases(node)!, attr); Array_splice(attrs, attr, i--); } } if (attrs.length === 0) { deleteAttributes(node); } } } function registerPogramLike(program: Extract) { const comments = spliceAll(program.comments); const danglingAttributes = spliceAll(program.danglingAttributes); for (let i = 0; i < danglingAttributes.length; i++) { const attr = danglingAttributes[i]; // if (isReadingSnippet() && is_DocCommentAttribute(attr)) { // } if (is_DocCommentAttribute(attr)) { if (isReadingSnippet()) { const index = binarySearchIn(_COMMENTS, start(attr), start); __DEV__: assert(index !== -1), assert(end(_COMMENTS[index]) === end(attr)); _COMMENTS.splice(index, 1); } } else { transformNode(danglingAttributes[i], program, "danglingAttributes", i); } } if (!isReadingSnippet()) insertNodes(_COMMENTS, comments); insertNodes(_DANGLING_ATTRIBUTES, danglingAttributes); } const CommentChildNodes = new WeakMap(); export function getCommentChildNodes(n: any): Node[] { const children = Map_get(CommentChildNodes, n, getTransformedNodeChildren); /** * parent { * #[attr] * #![attr] <-------- list misplaced inner attrs as part of "#[attr] child {}" * child {} * } */ if (is_NodeWithBodyOrCases(n) || is_BlockLikeMacroInvocation(n)) { for (let i = 0; i < children.length; i++) { const attr = children[i]; if (is_AttributeOrDocComment(attr)) { const target = children.find((n) => start(n) <= start(attr) && ownStart(n) >= end(attr)); if (target) { children.splice(i--, 1); insertNode(Map_get(CommentChildNodes, target, getTransformedNodeChildren), attr); } } } } return children; function getTransformedNodeChildren(node: Node) { if (is_Program(node)) node.comments ??= []; // prettier core deletes this property const children = getNodeChildren(node); if (is_NodeWithBodyNoBody(node)) { insertNodes(children, (node as any).body); } __DEV__: { const actual_count = countActualNodeChildren(node); if ( children.length !== actual_count && !(is_MacroInvocation(node) && actual_count - node.segments.length === children.length) ) { const actual = getActualNodeChildren(node); const missing = actual.filter((n) => !children.includes(n)); const unknown = children.filter((n) => !actual.includes(n)); const duplicates_in_object = actual.filter((n, i, a) => i !== 0 && n === a[i - 1]); const duplicates_in_childNodes = children.filter((n, i, a) => i !== 0 && n === a[i - 1]); const ctx = { missing, unknown, duplicates_in_object, duplicates_in_childNodes }; for (let key in ctx) if (ctx[key].length === 0) delete ctx[key]; exit(`${node.type} was transformed but did not patch its childNodes list`, ctx, node.loc.url(), node); } for (const child of children) if (!is_Node(child)) exit(`${node.type}'s childNodes includes unexpected entries`, { node, child }); } return children; } } ================================================ FILE: src/utils/common.ts ================================================ import { createCustomError } from "./debug"; declare global { var console: { log(...args: any[]): void; error(...args: any[]): void }; interface ErrorConstructor { captureStackTrace(targetObject: object, constructorOpt?: Function): void; prepareStackTrace?: ((err: Error, stackTraces: any[]) => any) | undefined; stackTraceLimit: number; } interface ImportMeta { url: string; } } export function Narrow(value: R): asserts value is T {} export function AssertTypesEq(...args: [B] extends [A] ? [] : [RIGHT_TYPES_NOT_ASSIGNABLE_TO_LEFT: Exclude]) {} // prettier-ignore type indexof = A extends readonly any[] ? A extends 0 ? any : keyof A & number : A extends Set ? never : A extends Map ? U : A extends Iterable ? never : A extends object ? keyof A & (number | string) : never; // prettier-ignore type valueof = A extends ReadonlyArray ? A extends 0 ? any : U : A extends Set ? U : A extends Map ? U : A extends Iterable ? U : A extends object ? A[keyof A & (number | string)] : never; // prettier-ignore type vObject = | object | readonly V[] | { [key: string]: V } | anySet | anyMap; export type itfn = (value: valueof, key: indexof) => R; type anySet = Set; type anyMap = Map; type anyfunction = (...args: A) => R; type objlike = object | anyfunction; type anymap = K extends objlike ? Map | WeakMap : Map; export function exit(message: string, ...ctx: any[]): never { if (ctx.length > 0) console.log("Error context:", { ...ctx }); throw createCustomError({ message }); } exit.never = function never(...ctx: any[]): never { exit("Reached unreachable code", ...ctx); }; export function assert(predicate: boolean, err?: string, ...ctx: any[]): asserts predicate { __DEV__: if (typeof predicate !== "boolean") exit("Expected boolean", predicate); if (false === predicate) exit(err ?? "Assertion failed", ...ctx); } export function Identity(v: T): T { return v; } export function last_of>(arr: T): T extends readonly [...infer A, infer U] ? U : T[number] { __DEV__: isArrayLike(arr) || exit("Expected Array"), arr.length > 0 || exit("Attempted to retrieve last item of an empty array", arr); return arr[arr.length - 1]; } export function maybe_last_of( arr: T ): T extends any[] ? (T extends readonly [...infer A, infer U] ? U : T[number]) : undefined { return undefined === arr || 0 === arr.length ? undefined : last_of(arr as any[]); } export function normPath(filepath: string) { return filepath.replace(/^file:\/\/\//, "").replace(/\\\\?/g, "/"); } export function print_string(str: string) { return /[\u0000-\u0020]/.test(str) ? str .replace(/ /g, "•") .replace(/\n/g, "↲") .replace(/\t/g, "╚") .replace(/[\u0000-\u0020]/g, "□") : str; } function isArrayLike(value: any): value is ArrayLike { return is_object(value) && oisArrayLike(value); } function oisArrayLike(value: {}): value is ArrayLike { return "length" in value && (0 === (value as any).length || "0" in value); } export function binarySearchIn(array: ArrayLike, target: number, toValue: (item: T) => number) { if (isEmpty(array)) return -1; let i = 0; let low = 0; let high = array.length - 1; let value = toValue(array[high]); if (target >= value) return high; else high--; while (low <= high) { i = low + ((high - low) >> 1); value = toValue(array[i]); if (target === value) return i; if (target > value) low = i + 1; else high = i - 1; } return low - 1; } export function getTerminalWidth(fallbackWidth = 200) { return globalThis?.process?.stdout?.columns ?? fallbackWidth; } // @ts-ignore const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined"; export const color = ((cfn, mfn) => ({ black: cfn(30), red: cfn(31), green: cfn(32), yellow: cfn(33), blue: cfn(34), magenta: cfn(35), cyan: cfn(36), white: cfn(37), grey: cfn(90), bold: mfn(1, 22), italic: mfn(3, 23), underline: mfn(4, 24), hidden: mfn(8, 28), hiddenCursor: (str: string) => `\x1B[?25l${str}\x1B[?25h`, unstyle: (str: string) => str.replace(/\x1B\[[0-9][0-9]?m/g, ""), unstyledLength: (str: string) => str.replace(/\x1B\[[0-9][0-9]?m/g, "").length, link: (str: string) => color.underline(color.blue(str)), }))( (c1: number) => (isBrowser ? Identity : (str: string) => `\x1B[${c1}m${str.replace(/\x1B\[39m/g, `\x1B[${c1}m`)}\x1B[39m`), (c1: number, c2: number) => (isBrowser ? Identity : (str: string) => `\x1B[${c1}m${str}\x1B[${c2}m`) ); export function Map_get(map: WeakMap, key: K, init: (key: K) => V): V; export function Map_get(map: Map, key: K, init: (key: K) => V): V; export function Map_get(map: anymap, key: K, init: (key: K) => V): V { if (!map.has(key)) map.set(key, init(key)); return map.get(key)!; } export function isEmpty(array: ArrayLike): boolean { __DEV__: assert(isArrayLike(array)); return 0 === array.length; } export function Array_splice(array: T, target: T[number], index: number = array.indexOf(target)) { __DEV__: { const i = arguments.length === 2 ? array.indexOf(target) : index; assert(i === index && i !== -1 && i === array.lastIndexOf(target), "", { array, target, index, i }); } array.splice(index, 1); } export function Array_replace(array: T, target: T[number], ...replacements: T[number][]) { const i = array.indexOf(target); __DEV__: if (i === -1 || i !== array.lastIndexOf(target)) exit("Array_replace", { index: i, lastIndex: array.lastIndexOf(target), array, target, replacements }); array.splice(array.indexOf(target), 1, ...replacements); } export function has_key_defined( o: T, k: K ): o is K extends never ? never : T extends { [k in K]: any } ? T & { [k in K]: {} } : T extends { [k in K]?: any } ? T & { [k in K]: {} } : never { return k in o && undefined !== o[k]; } export function is_object(data: unknown): data is object | ({ [key: string]: unknown } | unknown[]) { return "object" === typeof data && null !== data; } export function is_array(data: unknown): data is any[] { return Array.isArray(data); } function ois_vobject(data: any) { __DEV__: assert(is_object(data)); switch (data.constructor) { case Array: case Object: case Set: case Map: return true; default: return false; } } export function each(data: A, callback: itfn): void; export function each(data: any, callback: (value: any, index: any) => void): void { __DEV__: assert(ois_vobject(data)); // prettier-ignore switch (data.constructor) { case Array: { let i = 0; for (; i < data.length; i++) callback(data[i], i); return; } case Object: { let k; for (k in data) callback(data[k], k); return; } case Set: { let d; for (d of data) callback(d, undefined!); return; } case Map: { let e; for (e of data) callback(e[1], e[0]); return; } default: { let x; for (x of data) callback(x, undefined!); return; } } } export function iLast(index: number, array: any[]) { return 1 + index === array.length; } export function find_last(arr: T[], test: itfn): T | undefined { for (var i = arr.length; --i !== -1; ) if (test(arr[i], i)) return arr[i]; } export function try_eval(fn: () => T): T | undefined { try { return fn(); } catch (e) { return undefined; } } export function clamp(min: number, max: number, value: number) { return value > min ? (value < max ? value : max) : min; } export type MaybeFlatten = T extends ReadonlyArray ? MaybeFlatten> : T; export type FlatArray = MaybeFlatten[]; export function flat(arr: T): FlatArray { return (arr as any as [any]).flat(Infinity); } export function flatMap(arr: T, mapFn: (item: T[number], index: number, array: T) => R): FlatArray { return flat(arr.map(mapFn)); } export function joinln(...arr: string[]): string { return arr.join("\n"); } export function join_lines(fn: () => Generator): string { return [...fn()].join("\n"); } export function reduce_tagged_template(args: [strings: TemplateStringsArray, ...values: T[]], map: (value: T) => string) { for (var str = "" + args[0][0], i = 1; i < args.length; i++) str += map(args[i] as T) + args[0][i]; return str; } export function map_tagged_template(args: [strings: TemplateStringsArray, ...values: T[]], map: (value: T) => R) { const arr: (R | string)[] = [args[0][0]]; for (var i = 1; i < args.length; i++) arr.push(map(args[i] as T), args[0][i]); return arr; } export function spliceAll(array: T): [...T] { const r: [...T] = [...array]; array.length = 0; return r; } export function spread(fn: () => Iterable): R[] { return [...fn()]; } ================================================ FILE: src/utils/debug.ts ================================================ import { clamp, color, getTerminalWidth, normPath } from "./common"; const cwd = // @ts-expect-error typeof process === "object" && typeof process?.cwd === "function" ? /* @__PURE__ */ normPath(/* @__PURE__ */ process.cwd() ?? "") : ""; function normPath_strip_cwd(filepath: string) { let normFilePath = normPath(filepath); return normFilePath.startsWith(cwd) ? normFilePath.slice(cwd.length + 1) : normFilePath; } type StackStyleFn = (callee: string, item: StackItem) => (str: string) => string; interface Stack extends Array { message: string; style?: { callee?: StackStyleFn; url?: StackStyleFn } | undefined; } class StackLine { declare readonly raw: string; declare readonly callee: string; declare readonly filepath: string; declare readonly line: string; declare readonly col: string; declare readonly other: string; declare readonly url: string; constructor(raw: string) { ({ 1: this.callee = "", 2: this.filepath = "", 3: this.line = "", 4: this.col = "", 5: this.other = "", } = (this.raw = raw).match(/at (?:(.+?)\s+\()?(?:(.+?):([0-9]+)(?::([0-9]+))?|([^)]+))\)?/) ?? ["", "", "", "", "", ""]); this.url = this.filepath // ? normPath_strip_cwd(this.filepath) + (this.line && this.col && `:${this.line}:${this.col}`) : this.other === "native" ? "" : ""; } } function getPrintWidth() { return clamp(0, getTerminalWidth(128), 200) - 4; } class StackItem extends StackLine { constructor(private readonly stack: Stack, readonly i: number, raw: string) { super(raw); } hidden = false; hide() { this.hidden = true; return this; } hideNext(n: number) { for (let i = 0; i < n; i++) this.at(i)?.hide(); } hideWhileTrue(test: (line: StackItem) => boolean) { let line: StackItem | undefined = this; while (line && test(line)) line = line.hide().next(); } at(relIndex: number) { return this.i + relIndex >= this.stack.length || this.i + relIndex < 0 ? undefined : this.stack[this.i + relIndex]; } next() { return this.at(+1); } toString() { const url = this.url; const calleeColor = this.stack.style?.callee?.(this.callee, this) ?? color.cyan; const urlColor = this.stack.style?.url?.(url, this) ?? color.grey; return compose2Cols(" at " + calleeColor(this.callee), urlColor(url), getPrintWidth()); } } // prettier-ignore function createStack(message: string, Error_stack: string, style: Stack["style"]): Stack { for (var STACK: Stack = [] as any, i = 0, stack = Error_stack.split("\n").slice(2); i < stack.length; i++) STACK[i] = new StackItem(STACK, i, stack[i]); return (STACK.message = message), (STACK.style = style), STACK; } function composeStack(stack: Stack) { var hidden = 0; var str = stack.message; for (var item of stack) item.hidden ? ++hidden : (str += "\n" + item.toString()); return str + (hidden > 0 ? "\n" + color.grey(compose2Cols("", `...filtered ${hidden} lines`, getPrintWidth())) : ""); } export function get_caller_cmd(offset = 0) { const obj: { stack: string } = {} as any; Error.captureStackTrace(obj, get_caller_cmd); const lines = obj.stack.split("\n"); return new StackLine(lines[1 + clamp(0, lines.length - 2, offset)]).url; } var Error_prepareStackTrace; let replaced_default_prepareStackTrace = false; function custom_prepareStackTrace(err, calls) { return (Error_prepareStackTrace?.(err, calls) ?? calls.join("\n"))?.replace(/file:\/\/\//g, "").replace(/\\\\?/g, "/") ?? calls; } export function overrideDefaultError(silent = false) { if (replaced_default_prepareStackTrace === (replaced_default_prepareStackTrace = true)) return; Error_prepareStackTrace = Error.prepareStackTrace ?? ((_, calls) => calls.join("\n")); Error.prepareStackTrace = custom_prepareStackTrace; if (!silent) console.log(color.grey(`[devtools] Replaced Error.prepareStackTrace at ${get_caller_cmd(1)}`)); } export function createCustomError({ message = "Unknown Error", editStack = (stack: StackItem[]) => {}, style = undefined as Stack["style"], stackTraceLimit = 20, }): Error { const _stackTraceLimit = Error.stackTraceLimit; const _prepareStackTrace = Error.prepareStackTrace; if (replaced_default_prepareStackTrace && _prepareStackTrace === custom_prepareStackTrace) Error.prepareStackTrace = Error_prepareStackTrace; Error.stackTraceLimit = stackTraceLimit; const _ctx: { stack: string } = {} as any; Error.captureStackTrace(_ctx, createCustomError); const stack = createStack(message, _ctx.stack, style); Error.prepareStackTrace = function (err, calls) { editStack(stack); return composeStack(stack); }; const err = new Error(message); // @ts-expect-error (get) to trigger prepareStackTrace, (set) to prevent treeshaking err.stack = err.stack; Error.stackTraceLimit = _stackTraceLimit; Error.prepareStackTrace = _prepareStackTrace; return err; } function compose2Cols(left: string, right: string, len = 64, min = 1) { return left + " ".repeat(clamp(min, len, len - (color.unstyledLength(left) + color.unstyledLength(right)))) + right; } ================================================ FILE: tests/output/comments/assignment.f.rs ================================================ f1 = | //comment a | {}; f2 = | a //comment | {}; f3 = | a //comment | {}; f4 = // Comment || {}; f5 = // Comment || {}; f6 = /* comment */ // Comment || {}; let f4 = // Comment || {}; let f5 = // Comment || {}; let f6 = /* comment */ // Comment || {}; const kochabCooieGameOnOboleUnweave = // ??? annularCooeedSplicesWalksWayWay; const bifornCringerMoshedPerplexSawder = // !!! glimseGlyphsHazardNoopsTieTie + averredBathersBoxroomBuggyNurl - anodyneCondosMalateOverateRetinol; fnNumber = // Comment 3; fnNumber = // Comment 3; fnNumber = // Comment0 // Comment1 3; fnNumber = /* comment */ 3; fnNumber = /* comments0 */ /* comments1 */ 3; fnNumber = // Comment 3; let fnNumber = // Comment 3; let fnNumber = // Comment0 // Comment1 3; let fnNumber = /* comment */ 3; let fnNumber = /* comments0 */ /* comments1 */ 3; fnString = // Comment "some" + "long" + "string"; fnString = // Comment "some" + "long" + "string"; fnString = // Comment "some" + "long" + "string"; fnString = /* comment */ "some" + "long" + "string"; fnString = /** * multi-line */ "some" + "long" + "string"; fnString = /* inline */ "some" + "long" + "string" + "some" + "long" + "string" + "some" + "long" + "string" + "some" + "long" + "string"; fnString = // Comment0 // Comment1 "some" + "long" + "string"; fnString = "some" + "long" + "string"; // Comment fnString = // Comment "some" + "long" + "string"; let fnString = // Comment "some" + "long" + "string"; let fnString = // Comment "some" + "long" + "string"; let fnString = /* comment */ "some" + "long" + "string"; let fnString = /** * multi-line */ "some" + "long" + "string"; let fnString = /* inline */ "some" + "long" + "string" + "some" + "long" + "string" + "some" + "long" + "string" + "some" + "long" + "string"; let fnString = // Comment0 // Comment1 "some" + "long" + "string"; let fnString = "some" + "long" + "string"; // Comment let obj1 = // 36_______ A { key: "val", }; let obj2 = // 37_______ A { key: "val", }; let obj3 = A { // 38_______ key: "val", }; let obj4 = A { // 39_______ key: "val", }; let obj5 = // 40_______ ["val"]; let obj6 = // 41_______ ["val"]; let obj7 = [ // 42_______ "val", ]; let obj8 = [ // 43_______ "val", ]; const A { a /* 0_______ */: 1 } = b; const A { c: 1 /* 1_______ */ } = d; let A { d: b, //2_______ } = c; const foo = A { a: "a" /* 3_______________ */, /* 4_________ */ b: "b", }; let // 44_______ foo1 = "val"; const foo3 = 123; // 45_______ ["2", "3"].forEach(|x| console.log(x)); let a = b || /** 46_______ */ c; let a = A { a /* 47_______ */: || 1, }; let a = /* 48 */ 0; let b = /* * 4 * 9 */ 0; let c = /* * 5 * 0 */ 0; let d = /* * 5 * 1 */ 0; fn foo() { let x = foo.bar???.baz; // comment let x = // comment foo.bar???.baz; let x = // comment foo.bar???.baz; // comment let x = foo.bar???????????????.baz; // comment // comment // comment // comment // comment let x = /* Invisible comment */ try { foo()? }; let loooooooooooooooooooooooooooooooooooooooooong = does_this?.look?.good?.should_we_break?.after_the_first_question_mark?; let x = y.z; // comment self.rev_dep_graph .iter() // Remove nodes that are not dirty .filter(|&(unit, _)| dirties.contains(&unit)) // Retain only dirty dependencies of the ones that are dirty .map(|(k, deps)| { ( k.clone(), deps .iter() .cloned() .filter(|d| dirties.contains(&d)) .collect(), ) }); let y = expr /* comment */ .kaas()?; (Foo { // comment ..a } = a); } // source: "../../samples/comments/assignment.rs" ================================================ FILE: tests/output/comments/binaryish.f.rs ================================================ a = b || /** 5_______ */ c; a = b || /** 6_______ */ c; a = b || /** 7_____________________________________________________________________________ */ c; a = b || /** 8_____________________________________________________________________________ */ c; a = b || /** 9_____________________________________________________________________________ */ c; a = b && /** 10_______ */ c; a = b && /** 11_______ */ c; a = b && /** 12_____________________________________________________________________________ */ c; a = b && /** 13_____________________________________________________________________________ */ c; a = b && /** 14_____________________________________________________________________________ */ c; a = b + /** 15_______ */ c; a = b + /** 16_______ */ c; a = b + /** 17_____________________________________________________________________________ */ c; a = b + /** 18_____________________________________________________________________________ */ c; a = b + /** 19_____________________________________________________________________________ */ c; a = b || // 20_______ c; a = b || // 21_____________________________________________________________________________ c; a = b && // 22_______ c; a = b && // 23_____________________________________________________________________________ c; a = b + // 24_______ c; a = b + // 25_____________________________________________________________________________ c; 0 + // 26_______ x; 0 * // 27_______ x; 0 / // 28_______ x; 0 - // 29_______ x; 0 % // 30_______ x; 0 << // 31_______ x; 0 >> // 32_______ x; 0 & // 33_______ x; 0 | // 34_______ x; 0 ^ // 35_______ x; // source: "../../samples/comments/binaryish.rs" ================================================ FILE: tests/output/comments/blocks.f.rs ================================================ if 0 { 0; // } else if 0 { } if 1 { /* * _______ */ } if 1 { // _______ } if 1 { } else { // _______ } if 1 // if 1 (ln trailing) { 1; } else if // else if 2 (leading) 2 { 2; } else if // else if 3 (leading) // else if 3 (leading) // else if 3 (leading) 3 // if 3 (ln trailing) { 3; } else if // else if 4 (leading) 4 { // 4 body } else { // else (leading) } if 5 // if 5 (trailing) { 1; } if 6 // if 6 (trailing) { 6; } else if 7 // else if 7 (trailing) { 7; } else { // else (trailing) 0; } if 8 // if 8 (trailing) // ^ if 8 (ln trailing) { 1; } else if 9 // else if 9 // else if 9 (ln trailing) { 1; } else { // else (trailing) // else (ln trailing) 1; } if 10 /* _______ */ // _______ { 10; } else if 11 /* _______ */ { 11; } else if 12 // _______ /* _______ */ // _______ { 12; } else if 13 /* _______ */ /* _______ */ // _______ { 13; } else { /* _______ */ 0; } if 14 // _______ /* _______ */ // _______ { 14; } else if 15 // _______ /* _______ */ /* _______ */ // _______ { 15; } for // _______ a in b { } for /* _______ */ a in b { } let a = {/* _______ */}; let b = { // _______ }; for e in q { r = *e; // c } while true // _______ {} while true // _______ {} while true {} // _______ while true /*_______*/ {} while true /* _______ */ {} while true && // _______ true // _______ {} while true {} // _______ if cond { stuff; } else if /* _______ */ cond { stuff; } else { // _______ stuff; } if cond { stuff; } else { // _______ stuff; } ret = if __DEV__ // _______ { vm.runInContext(source, ctx) } else { a }; if a == 0 { doSomething(); // _______ } else if a == 1 { doSomethingElse(); // _______ } else if a == 2 { doSomethingElse(); // _______ } if a == 0 { doSomething(); /* _______ */ } else if a == 1 { doSomethingElse(); /* _______ */ } else if a == 2 { doSomethingElse(); /* _______ */ } if a == 0 { expr; // _______ } else if a == 1 { expr; // _______ } else if a == 2 { expr; // _______ } if a == 0 { expr; /* _______ */ } else if a == 1 { expr; /* _______ */ } else if a == 2 { expr; /* _______ */ } if a == 0 { looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong; // _______ } else if a == 1 { looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong; // _______ } else if a == 2 { looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong; // _______ } if code == 92 /* _______ */ { } if code == 92 /* _______ */ /* _______ */ { } if code == 92 /* _______ */ { } if code == 92 {/* _______ */} if 1 // _______ { a; } { // _______ 'a: loop { } } { // _______ 'a: loop { } } fn f() { a /* _______ */ } fn f() { a /* _______ */ } fn d() {/* _______ */} fn f() { // _______ f(); // _______ f() // _______ // _______ } fn f() { // _______ return 1; } fn f() { // _______ return 1; } fn f() { // _______ return 1; } fn f() { // _______ return 1; } // So this is a very long comment. // Multi-line, too. // Will it still format correctly? unsafe { a; } {/* a block with a comment */} { } { // A block with a comment. } fn foo() { (async { // Do // some // work }).await; (async { // Do // some // work }).await; } // source: "../../samples/comments/blocks.rs" ================================================ FILE: tests/output/comments/chain.f.rs ================================================ _ .a(a) /* _____________________________________________________________________________ */ .a(); _ .a( a ) /* _____________________________________________________________________________ */ .a(); _ .a( a ) /* _____________________________________________________________________________ */ .a(); Something // _______ .getInstance(this.props.dao) .getters(); // _______ measure().then(|| { SomethingLong(); }); measure() // _______ .then(|| { SomethingLong(); }); const configModel = this.baseConfigurationService .getCache() .consolidated // _______ .merge(this.cachedWorkspaceConfig); this .doWriteConfiguration(target, value, options) // _______ .then( || null, || { return if options.donotNotifyError { TPromise.wrapError(error) } else { this.onError(error, target, value) }; } ); angular .module("AngularAppModule") // _______ .constant("API_URL", "http://localhost:8080/api"); // _______ Observable.of(process) // _______ .merge(Observable.never()) // _______ .takeUntil( if throwOnError { errors.flatMap(Observable.throw) } else { errors } ) .takeUntil(exit); // source: "../../samples/comments/chain.rs" ================================================ FILE: tests/output/comments/closure.f.rs ================================================ call(|/*_______*/ row| {}); KEYPAD_NUMBERS.map( |num| // _______ 1 ); const obj = A { f1: /* _______ */ || {}, f2: |/* _______ */| {}, f3: || /* _______ */ {}, f4: /* _______ */ |/* _______ */| /* _______ */ {}, }; /* _______ */ (|| {})(); (|/* _______ */| {})(); (|| /* _______ */ {})(); /* _______ */ (|/* _______ */| /* _______ */ {})(); let commented = | /* first */ a /*argument*/, /* second*/ b: WithType /* argument*/, /* ignored */ _ | ( aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb, ); const fn1 = |/*_______, _______*/| doSomething(); const fn2 = |/*_______, _______*/| doSomething(anything); foo( | // _______ | {} ); const rootEpic = |actions, store| combineEpics(epics)(actions, store) // _______ .catch(|err, stream| { getLogger().error(err); return stream; }); // source: "../../samples/comments/closure.rs" ================================================ FILE: tests/output/comments/dangling.f.rs ================================================ use std::{/* comment */}; macro_rules! m {/* comment */} macro_rules! m { /* comment */ /* comment */ (/* comment */) => {/* comment */}; } macro m/* comment */ (/* comment */) {/* comment */} {/* comment */} f(/* comment */); f /* comment */!(/* comment */); f /* comment */! {/* comment */} f /* comment */![/* comment */]; f!([/* comment */]); f!({/* comment */}); f!((/* comment */)); f!(~[/* comment */]); f!(~{/* comment */}); f!(~(/* comment */)); [/* comment */]; (/* comment */); A /* comment */ {/* comment */}; if let A {/* comment */} | a(/* comment */) | [/* comment */] = (/* comment */) { } if 0 {/* comment */} if 0 {/* comment */} else { /* comment */ /* comment */ /* comment */ } if 0 {/* comment */} else if /* comment */ /* comment */ 0 {/* comment */} if 0 {/* comment */} else if /* comment */ /* comment */ /* comment */ let _ = 0 {/* comment */} match (/* comment */) {/* comment */} fn a(/* comment */) { /* comment */ /* comment */ } |/* comment */| 0; impl A {/* comment */} trait A {/* comment */} enum A {/* comment */} struct A(/* comment */); struct A {/* comment */} mod A {/* comment */} use A::{/* comment */}; union A {/* comment */} A::; A::(/* comment */); type A : fn(/* comment */) where for A: for Fn(/* comment */) -> (/* comment */); #![/* comment */] #[/* comment */] struct A; #![/* comment */] #[/* comment */] struct A; #![/* comment */] #[/* comment */] #[/* comment */] struct A; #![/* comment */] #![/* comment */] #[/* comment */] struct A; #![/* comment */] #![/* comment */] #[/* comment */] #[/* comment */] struct A; #![/* comment */] #![/* comment */] #[/* comment */] #[/* comment */] struct A; // source: "../../samples/comments/dangling.rs" ================================================ FILE: tests/output/comments/file.f.rs ================================================ // This file only // has comments. This comment // should still exist // // when printed. /** * @typedef {DataDrivenMapping|ConstantMapping} Mapping */ /** * @typedef {Object.} ConfigurationMapping */ /** * @typedef {Function} D3Scale - a D3 scale * @property {Function} ticks * @property {Function} tickFormat */ // comment // comment // source: "../../samples/comments/file.rs" ================================================ FILE: tests/output/comments/flow.f.rs ================================================ loop { break /* _______ */; continue /* _______ */; } 'loop: loop { break /* _______ */ 'loop; break 'loop /* _______ */; continue /* _______ */ 'loop; continue 'loop /* _______ */; } return ( // _______ !!x ); return 1337; // _______ return ( // _______ 42 && 84 ); return ( // _______ 42 * 84 ); return if // _______ 42 { 1 } else { 2 }; return if // _______ 42 * 3 { 1 } else { 2 }; return ( // _______ a() ); return ( // _______ a.b.c ); return ( // _______ a.b.c ); return ( afn .b() // _______ .c.d() ); return ( // _______ if a.b() * 3 + 4 + (if ("a`hi`", 1) { 1 } else { 1 }) { } else { 1 } ); return ( // _______ a, b, ); return ( // _______ a ); return /* _______ */ 42 || 42; return ( observableFromSubscribeFunction() // _______ // _______ .debounceTime(debounceInterval) ); return A { // _______ bar: baz() + 1, }; // source: "../../samples/comments/flow.rs" ================================================ FILE: tests/output/comments/functions.f.rs ================================================ fn a(/* _______ */) {} // _______ fn b() {} // _______ fn c(/* _______ */ argA, argB, argC) {} // _______ fn a(a /*_______*/) {} fn b(a /*_______*/) {} fn d(a /*_______*/, b /*_______*/, c /*_______*/, d /*_______*/) {} fn d(a /*_______*/, b /*_______*/, c /*_______*/, d /*_______*/) {/*_______*/} // prettier-ignore fn c(a /*_______*/ ) {} // prettier-ignore fn d( a /*_______*/, b /*_______*/, c /*_______*/, d /*_______*/ ) {} // prettier-ignore fn e( a /*_______*/, b /*_______*/, c /*_______*/, d /*_______*/ ) {} /* _______*/ fn f1 /* _______ */() {} fn f2(/* _______ */) {} fn f3() {/* _______ */} fn f4 /* _______ */(/* _______ */) {/* _______ */} fn f5(/* _______ */ /* _______ */ a) {} fn f6(/* _______ */ a /* _______ */) {} fn f7(/* _______ */ /* _______ */ a) {/* _______ */} // source: "../../samples/comments/functions.rs" ================================================ FILE: tests/output/comments/ignore.attr.f.rs ================================================ const baseline = 1 + 1; fn no() { a( a ); #![rustfmt::skip] // _______ } #[rustfmt::skip] const a = A { b: "_______", }; fn f() { 1 + 1; #[no ] #![rustfmt::skip] fn f() { 1 + 1; } } // source: "../../samples/comments/ignore.attr.rs" ================================================ FILE: tests/output/comments/ignore.f.rs ================================================ const baseline = 1 + 1; // prettier-ignore let x = "" + this.USE + " " + this.STRICT + ";\n" + this.filterPrefix() + "var fn=" + this.generateFunction("fn", "s,l,a,i") + extra + this.watchFns() + "return fn;"; // prettier-ignore const x = Matrix.create( 1, 0, 0, 0, 1, 0, 0, 0, 0 ); // prettier-ignore const x = A { b: "_______", }; fn f() { a( a ); // prettier-ignore // _______ } // prettier-ignore console.error( "_______" + prompt + "_______" + "_______ _______" ); const response = A { // prettier-ignore a: "Turn on the lights", intent: "lights", }; verylongidentifierthatwillwrap123123123123123( a.b // prettier-ignore // _______ .c ); call( // _______ a. // prettier-ignore b ); call(a( /* _______ */ 1, 2.0000, 3 ) // prettier-ignore .c); #[attr] // prettier-ignore const foo = 1 + 1; const A { // prettier-ignore bar : a, } = foo; const A { a, // prettier-ignore bar2 : a, } = foo; /* _______ */ const A { // prettier-ignore bar3 : a, // _______ } = foo; const A { // prettier-ignore bar4 : a /* _______ */, } = foo; const A { // prettier-ignore bar5 : /* _______ */ a, } = foo; const A { // prettier-ignore .. } = foo; const A { baz: A { // prettier-ignore foo2: [a, b, c], }, // prettier-ignore bar7 : a, } = foo; // source: "../../samples/comments/ignore.rs" ================================================ FILE: tests/output/comments/ignore.file.f.rs ================================================ const unformatted= 1; #![rustfmt::skip] // a fn unformatted () { struct a { // b c } } // source: "../../samples/comments/ignore.file.rs" ================================================ FILE: tests/output/comments/imports.f.rs ================================================ use list::{ // Some item SomeItem /* Comment */, /* Another item */ AnotherItem /* Another Comment */, // Last Item LastItem, }; use test::{ Other /* C */, /* A */ self /* B */ }; use ::{ /* Pre-comment! */ Foo, Bar /* comment */ }; // source: "../../samples/comments/imports.rs" ================================================ FILE: tests/output/comments/macro.f.rs ================================================ a!(~ " { } "); a!(~ // 1 ); a!(~ { // 2 }); cfg_if::cfg_if! { if #[attr] { if 0 { } else { // ERROR! } } } a! { if #[attr] { // ERROR! } } x! {~ { // ERROR! } } // source: "../../samples/comments/macro.rs" ================================================ FILE: tests/output/comments/multiple.f.rs ================================================ /* _______ */ /* _______ */ /* _______ */ a; a; /* _______ */ /* _______ */ /* _______ */ a; // _______ a; /*1*/ /*2*/ /*3*/ b; a; /*1*/ /*2*/ /*3*/ b; a; /*1*/ /*2*/ /*3*/ b; a; /* 1*/ /*2*/ /*3 */ b; a; /* 1*/ /*2*/ /*3 */ b; a; /* 1*/ /*2*/ /*3 */ b; a; /*1*/ /*2*/ /*3*/ b; a; /*1*/ /*2*/ /*3*/ b; a; /*1*/ /*2*/ /*3*/ b; a; /* 1*/ /*2*/ /*3 */ b; a; /* 1*/ /*2*/ /*3 */ b; a; /* 1*/ /*2*/ /*3 */ b; a; /*1*/ /*2*/ /*3*/ b; a; /*1*/ /*2*/ /*3*/ b; a; /*1*/ /*2*/ /*3*/ b; a; /* 1*/ /*2*/ /*3 */ b; a; /* 1*/ /*2*/ /*3 */ b; a; /* 1*/ /*2*/ /*3 */ b; use foo; /* 14 */ /* 1 10 */ /*/ 13 */ /* 9 ****/ use bar; x; /* 1 */ /* 2 */ y; x; /*1*/ /*2*/ y; /** 1 - OUTER DOC */ /* 2 - COMMENT */ /*! 3 - INNER DOC */ /*! 4 - INNER DOC *//** /* 5A - COMMENT */ * 5B - OUTER DOC */ /** * 5C - OUTER DOC */ // format: lost 1 comments // source: "../../samples/comments/multiple.rs" ================================================ FILE: tests/output/comments/parens.f.rs ================================================ !x; !(x /* 0 */); !(/* 1 */ x); !( /* 2 */ x ); !( x /* 3 */ ); !( x // 4 ); !(x + y); !(x + y /* 5 */); !(/* 6 */ x + y); a!(!(/* 6 */ x + y)); !( /* 7 */ x + y ); !( x + y /* 8 */ ); !( x + y // 9 ); !(x || y); !(/* 10 */ x || y); !(x || y /* 11 */); !( /* 12 */ x || y ); !( x || y /* 13 */ ); !( x || y // 14 ); ![1, 2, 3]; !([1, 2, 3] /* 15 */); !(/* 16 */ [1, 2, 3]); !( /* 17 */ [1, 2, 3] ); !( [1, 2, 3] /* 18 */ ); !( [1, 2, 3] // 19 ); !(A { a: 1, b: 2 }); !(A { a: 1, b: 2 } /* 20 */); !(/* 21 */ A { a: 1, b: 2 }); !( /* 22 */ A { a: 1, b: 2 } ); !( A { a: 1, b: 2 } /* 23 */ ); !( A { a: 1, b: 2 } // 24 ); !(|| { return x; }); !( || { return x; } /* 25 */ ); !( /* 26 */ || { return x; } ); !( /* 27 */ || { return x; } ); !( || { return x; } /* 28 */ ); !( || { return x; } // 29 ); !({ x = y; }); !( { x = y; } /* 30 */ ); !( /* 31 */ { x = y; } ); !( /* 32 */ { x = y; } ); !( { x = y; } /* 33 */ ); !( { x = y; } // 34 ); !x.y; !(x.y /* 35 */); !(/* 36 */ x.y); !( /* 37 */ x.y ); !( x.y /* 38 */ ); !( x.y // 39 ); !x(); !(x() /* 40 */); !(/* 41 */ x()); !( /* 42 */ x() ); !( x() /* 43 */ ); !( x() // 44 ); !(x, y); !(x, y /* 45 */); !(/* 46 */ x, y); !( /* 47 */ x, y, ); !( x, y, /* 48 */ ); !( x.y // 49 ); !(|| 3); !(|| 3 /* 50 */); !(/* 51 */ || 3); !( /* 52 */ || 3 ); !( || 3 /* 53 */ ); !( || 3 // 54 ); loop { !({ yield x; }); !( { yield x; } /* 55 */ ); !( /* 56 */ { yield x; } ); !( /* 57 */ { yield x; } ); !( { yield x; } /* 58 */ ); !( { yield x; } // 59 ); } async || { !x.await; !(x.await /* 60 */); !(/* 61 */ x.await); !( /* 62 */ x.await ); !( x.await /* 63 */ ); !( x.await // 64 ); }; Math.min( /* ______________________________________________________________ * _______________________________________________________________ * _______ */ document.body.scrollHeight - (window.scrollY + window.innerHeight) - devsite_footer_height, 0 ); // source: "../../samples/comments/parens.rs" ================================================ FILE: tests/output/comments/whitespace.f.rs ================================================ /* 1 */ /* 2 */ /* 3 */ /* 4 */ /* 5a 5b */ /* 6 */ /* 7a 7b */ /* 8a 8b */ /* VT4+2: 9 */ /* FF4+2: 10 */ /* CR4+2: 11 */ /* ………… NEL4+2: 12 */ /*      13a 13b */ /*      14 */ /*      15a 15b */ /*   16   16    16   16     16    16     16   16     16     16      16    16      16     16      16 */ /* */ /* 17a 17b 17c        17d */ /* */ /* 18a 18b 18c        18d */ // source: "../../samples/comments/whitespace.rs" ================================================ FILE: tests/output/common/arrays.f.rs ================================================ { for srcPath in [src, "${src}.js", "${src}/index", "${src}/index.js"] { } } { for srcPath in [123, 123_123_123, 123_123_123_1, 13_123_3123_31_43] { } } { for srcPath in [123, 123_123_123, 123_123_123_1, 13_123_3123_31_432] { } } { for srcPath in [123, 123_123_123, 123_123_123_1, 13_123_3123_31_4321] { } } [[]]; [[], []]; [[], [], []]; [[], [0], []]; [[], [0], [0]]; [[], [0, 1], [0]]; [[], [0, 1], [0, 1]]; [[0]]; [[0], []]; [[0], [], []]; [[0], [0], []]; [[0], [0], [0]]; [[0], [0, 1], [0]]; [[0], [0, 1], [0, 1]]; [[0, 1]]; [[0, 1], []]; [[0, 1], [], []]; [[0, 1], [0], []]; [[0, 1], [0], [0]]; [[0, 1], [0, 1], [0]]; [ [0, 1], [0, 1], [0, 1], ]; [[], [1, 2, 3]]; [[1], [1]]; [ [1, 2], [1, 2, 3], ]; [ [1, 0], [1, 0], ]; [A {}]; [A {}, A {}]; [A {}, A {}, A {}]; [A {}, A { a }]; [A {}, A { a, b }]; [A {}, A { a, b, c }]; [A { a }]; [A { a }, A { a }]; [A { a }, A { a }, A { a }]; [A { a }, A { a, b }]; [A { a }, A { a, b, c }]; [A { a, b }]; [A { a, b }, A { a }]; [A { a, b }, A { a }, A { a }]; [ A { a, b }, A { a, b }, ]; [ A { a, b }, A { a, b, c }, ]; expect(|| {}).toTriggerReadyStateChanges([ // _______ ]); expect(bifornCringerMoshedPerplexSawder.getArrayOfNumbers()).toEqual([ 1, 2, 3, 4, 5, ]); expect(bifornCringerMoshedPerplexSawder.getLongArrayOfNumbers()).toEqual([ 66, 57, 45, 47, 33, 53, 82, 81, 76, 78, 10, 78, 15, 98, 24, 29, 32, 27, 28, 76, 41, 65, 84, 35, 97, 90, 75, 24, 88, 45, 23, 75, 63, 86, 24, 39, 9, 51, 33, 40, 58, 17, 49, 86, 63, 59, 97, 91, 98, 99, 5, 69, 51, 44, 34, 69, 17, 91, 27, 83, 26, 34, 93, 29, 66, 88, 49, 33, 49, 73, 9, 81, 4, 36, 5, 14, 43, 31, 86, 27, 39, 75, 98, 99, 55, 19, 39, 21, 85, 86, 46, 82, 11, 44, 48, 77, 35, 48, 78, 97, ]); bifornCringerMoshedPerplex.bifornCringerMoshedPerplexSawder.arrayOfNumbers = [ 1, 2, 3, 4, 5, ]; bifornCringerMoshedPerplex.bifornCringerMoshedPerplexSawder.arrayOfNumbers2 = [ 66, 57, 45, 47, 33, 53, 82, 81, 76, 78, 10, 78, 15, 98, 24, 29, 32, 27, 28, 76, 41, 65, 84, 35, 97, 90, 75, 24, 88, 45, 23, 75, 63, 86, 24, 39, 9, 51, 33, 40, 58, 17, 49, 86, 63, 59, 97, 91, 98, 99, 5, 69, 51, 44, 34, 69, 17, 91, 27, 83, 26, 34, 93, 29, 66, 88, 49, 33, 49, 73, 9, 81, 4, 36, 5, 14, 43, 31, 86, 27, 39, 75, 98, 99, 55, 19, 39, 21, 85, 86, 46, 82, 11, 44, 48, 77, 35, 48, 78, 97, ]; const numbers = [ -2017, -506252, -744011292, -7224, -70.4, -83353.6, -708.4, -174023963.52, -40385, -( // comment1 380014 ), -253951682, -728, -15.84, -2058467564.56, -43, -33, -85134845, -67092, -1, -78820379, -2371.6, -16, 7, // comment2 -62454, -4282239912, -10816495.36, 0.88, -100622682, 8.8, -67087.68000000001, -3758276, -25.5211, -54, -1184265243, -46073628, -280423.44, -41833463, -27961.12, -305.36, -199875.28, ]; c = [ -(/**/ 66), 66, 57, 45, 47, 33, 53, 82, 81, 76, 66, 57, 45, 47, 33, 53, 82, 81, 223323, ]; const numbers1 = [ -2017, -506252, -744011292, -7224, -70.4, -83353.6, -708.4, -174023963.52, -40385, // comment1 -380014, -253951682, -728, -15.84, -2058467564.56, -43, -33, -85134845, -67092, -1, -78820379, -2371.6, -16, 7, // comment2 -62454, -4282239912, -10816495.36, 0.88, -100622682, 8.8, -67087.68000000001, -3758276, -25.5211, -54, -1184265243, -46073628, -280423.44, -41833463, -27961.12, -305.36, -199875.28, ]; const numbers2 = [ -234, -342, // comment3 -223, -333333.33, 12345, ]; let _v1 = [ // a 0, // b 1, // c 2, ]; let _v2 = [ 0, // a 1, // b 2, ]; // c let _v3 = [ /* a */ 0, /* b */ 1, /* c */ 2, ]; let _v4 = [0 /* a */, 1 /* b */, 2]; /* c */ [ &(|x /*: r*/| { x.e(); }), ]; // --------------- print-width ------------------------------------------------- const result = asyncExecute("non_existing_command", /* _______ */ []); let b = [/* _______ */]; c = [ 66, 66, 57, 45, 47, 33, 53, 82, 81, 76, 66, 57, 45, 47, 33, 53, 82, 81, 223323, ]; [1 /* _______ _______ */, 2 /* _______ _______ */, 3]; fn isUnusedDiagnostic(code) { return [ 6133, // '{0}' is declared but never used. 6138, // Property '{0}' is declared but its value is never read. 6192, // All imports in import declaration are unused. 6196, // '{0}' is declared but its value is never read. 6198, 6199, 6205, // All type parameters are unused. ].includes(code); } const lazyCatererNumbers = [ 1, 2, 4, 7, 11, 16, 22, 29, 37, 46, 56, 67, 79, 92, 106, 121, 137, 154, 172, 191, 211, 232, 254, 277, 301, 326, 352, 379, 407, 436, 466 /*block*/, // line 497, 529, 562, 596, 631, 667, 704, 742, 781, 821, 862, 904, 947, 991, 1036, 1082, 1129, 1177, 1226, // line 2 1276, 1327, 1379, ]; const numbers1 = [ 7234932941, 7234932722, 7234932312, 7234932933, 7234932841, 7234932166, 7234932843, 7234932978, 7234932436, 7234932687, 7234932269, 7234932573, 7234932913, 7234932873, 7234932748, 7234932354, 7234932153, 7234932181, 7234932947, 7234932563, 7234932324, 7234932952, 7234932885, 7234932911, 7234932698, 7234932248, 7234932764, 7234932431, 7234932811, 7234932344, 7234932855, 7234932430, 7234932396, 7234932981, 7234932594, 7234932131, 7234932489, 7234932552, 7234932116, 7234932833, 7234932521, 7234932252, 7234932503, 7234932540, 7234932893, 7234932736, 7234932969, 7234932145, 7234932925, 7234932417, 7234932344, 7234932108, 7234932161, 7234932777, 7234932971, 7234932159, 7234932158, 7234932908, 7234932511, 7234932876, 7234932768, 7234932284, 7234932640, 7234932309, 7234932651, 7234932292, 7234932898, 7234932284, 7234932201, 7234932506, 7234932654, 7234932840, 7234932334, 7234932246, 7234932376, 7234932398, 7234932714, 7234932134, 7234932435, 7234932181, 7234932980, 7234932594, 7234932396, 7234932100, 7234932743, 7234932812, 7234932583, 7234932622, 7234932800, 7234932310, 7234932111, 7234932537, 7234932751, 7234932920, 7234932872, 7234932700, 7234932702, 7234932655, 7234932515, 7234932298, ]; const userIds1 = [7234932941, 7234932722, 7234932312, 7234932933]; const userIds2 = [ 7234932941, 7234932722, 7234932312, 7234932933, 7234932841, 7234932166, 7234932843, 7234932978, 7234932436, ]; const userIds3 = [ 7234932941, 7234932722, 7234932312, 7234932933, 7234932841, 7234932166, 7234932843, 7234932978, 7234932436, ]; const userIds4 = [ 7234932941, 7234932722, 7234932312, 7234932933, 7234932841, 7234932166, // comment 1 7234932843, 7234932978, // comment 2 7234932436, // comment 3 ]; let test_case = [ [ 66, 57, 45, 47, 33, 53, 82, 81, 76, 78, 10, 78, 15, 98, 24, 29, 32, 27, 28, 76, 41, 65, 84, 35, 97, 90, 75, 24, 88, 45, 23, 75, 63, 86, 24, 39, 9, 51, 33, 40, 58, 17, 49, 86, 63, 59, 97, 91, 98, 99, 5, 69, 51, 44, 34, 69, 17, 91, 27, 83, 26, 34, 93, 29, 66, 88, 49, 33, 49, 73, 9, 81, 4, 36, 5, 14, 43, 31, 86, 27, 39, 75, 98, 99, 55, 19, 39, 21, 85, 86, 46, 82, 11, 44, 48, 77, 35, 48, 78, 97, ], [ 41, 83, 31, 62, 15, 70, 10, 90, /*21,*/ 48, 39, 76, 14, 48, 63, 62, 16, 17, 61, 97, 86, 80, 34, 27, 39, 53, 90, 80, 56, 71, 31, 22, 29, 7, 71, 90, 65, 17, 48, 85, 14, 94, 16, 32, 4, 96, 49, 97, 53, 87, 54, 2, 78, 37, 21, 3, 97, 62, 93, 62, 11, 27, 14, 29, 64, 44, 11, 5, 39, 43, 94, 52, 0, 4, 86, 58, 63, 42, 97, 54, 2, 1, 53, 17, 92, 79, 52, 47, 81, 93, 34, 17, 93, 20, 61, 68, 58, 49, 27, 45, ], ]; // source: "../../samples/common/arrays.rs" ================================================ FILE: tests/output/common/assignments.f.rs ================================================ const computedDescriptionLines = (showConfirm && descriptionLinesConfirming) || (focused && !loading && descriptionLinesFocused) || descriptionLines; computedDescriptionLines = (focused && !loading && descriptionLinesFocused) || descriptionLines; const result = template(r#" if (SOME_VAR == "") {} "#)(A { SOME_VAR: value, }); const output = template("function f() %%A%%")(A { A: t.blockStatement([]), }); tt.parenR.updateContext = { tt.braceR.updateContext = || { if this.state.context.length == 1 { return; } }; }; let bifornCringerMoshedPerplexSawder = { askTrovenaBeenaDependsRowans = { glimseGlyphsHazardNoopsTieTie = { averredBathersBoxroomBuggyNurl = { anodyneCondosMalateOverateRetinol = { annularCooeedSplicesWalksWayWay = kochabCooieGameOnOboleUnweave; }; }; }; }; }; bifornCringerMoshedPerplexSawder = { askTrovenaBeenaDependsRowans = { glimseGlyphsHazardNoopsTieTie = { x = { averredBathersBoxroomBuggyNurl = { anodyneCondosMal( sdsadsa, dasdas, asd(|| sdf) ).ateOverateRetinol = { annularCooeedSplicesWalksWayWay = kochabCooieGameOnOboleUnweave; }; }; }; }; }; }; bifornCringerMoshedPerplexSawder = { askTrovenaBeenaDependsRowans = { glimseGlyphsHazardNoopsTieTie = { x = { averredBathersBoxroomBuggyNurl = { anodyneCondosMal( sdsadsa, dasdas, asd(|| sdf) ).ateOverateRetinol = { annularCooeedSplicesWalksWayWay = kochabCooieGameOnOboleUnweave + kochabCooieGameOnOboleUnweave; }; }; }; }; }; }; a = { b = c; }; const [width, height, baseline] = measureText(nextText, getFontString(element)); { { const A { id, statlc: isStatic, method: isMethod, methodId, getId, setId, } = privateNamesMap.get(name); const A { id1, method: isMethod1, methodId1 } = privateNamesMap.get(name); const A { id2, method: isMethod2, methodId2, } = privateNamesMap.get(bifornCringerMoshedPerplexSawder); const A { id3, method: isMethod3, methodId3, } = anodyneCondosMalateOverateRetinol.get(bifornCringerMoshedPerplexSawder); } } let A { bottom: offsetBottom, left: offsetLeft, right: offsetRight, top: offsetTop, } = if getPressRectOffset == null { DEFAULT_PRESS_RECT } else { getPressRectOffset() }; const A { accessibilityModule: FooAccessibilityModule, accessibilityModule: FooAccessibilityModule2, accessibilityModule: FooAccessibilityModule3, accessibilityModule: FooAccessibilityModule4, } = foo || A {}; (A { prop: { toAssign = "default"; }, } = A { prop: "propval" }); someReallyLongThingStoredInAMapWithAReallyBigName[pageletID] = if _someVariableThatWeAreCheckingForFalsiness { Date.now() - _someVariableThatWeAreCheckingForFalsiness } else { 0 }; const aVeryLongNameThatGoesOnAndOn = this.someOtherObject.someOtherNestedObject.someLongFunctionName(); this.someObject.someOtherNestedObject = this.someOtherObject.whyNotNestAnotherOne.someLongFunctionName(); this.isaverylongmethodexpression.withmultiplelevels = { this.isanotherverylongexpression.thatisalsoassigned = 0; }; const areaPercentageDiff = ( topRankedZoneFit.areaPercentageRemaining - previousZoneFitNow.areaPercentageRemaining ).toFixed(2); aParticularlyLongAndObnoxiousNameForIllustrativePurposes = anotherVeryLongNameForIllustrativePurposes; aParticularlyLongAndObnoxiousNameForIllustrativePurposes = "a very long string for illustrative purposes".length; aParticularlyLongAndObnoxiousNameForIllustrativePurposes = anotherVeryLongNameForIllustrativePurposes(); aParticularlyLongAndObnoxiousNameForIllustrativePurposes = anotherVeryLongNameForIllustrativePurposes.length; aParticularlyLongAndObnoxiousNameForIllustrativePurposes = anotherVeryLongNameForIllustrativePurposes + 1; trait foo { fn bar() { const median = if dates.length % 2 { dates[half].getTime() } else { (dates[half - 1].getTime() + dates[half].getTime()) / 2.0 }; } } manifestCache[templateId] = readFileSync( "${MANIFESTS_PATH}/${templateId}.json", A { encoding: "utf-8" } ); this.dummy.type1.dummyPropertyFunction = { this.dummy.type2.dummyPropertyFunction = { this.dummy.type3.dummyPropertyFunction = { this.dummy.type4.dummyPropertyFunction = { this.dummy.type5.dummyPropertyFunction = { this.dummy.type6.dummyPropertyFunction = { this.dummy.type7.dummyPropertyFunction = { this.dummy.type8.dummyPropertyFunction = || { return "dummy"; }; }; }; }; }; }; }; }; if something { const otherBrandsWithThisAdjacencyCount123 = Object.values( edge.to.edges ).length; } const A { qfwvfkwjdqgz, bctsyljqucgz, xuodxhmgwwpw } = qbhtcuzxwedz( yrwimwkjeeiu, njwvozigdkfi, alvvjgkmnmhd ); async fn f() { const A { data, status } = request.delete( "/account/${accountId}/documents/${type}/${documentNumber}", A { validateStatus: || true } ).await; return A { data, status }; } const data1 = request.delete( "----------------------------------------------", A { validateStatus: || true } ); const data2 = request.delete( "----------------------------------------------x", A { validateStatus: || true } ); const data3 = request.delete( "----------------------------------------------xx", A { validateStatus: || true } ); const data4 = request.delete( "----------------------------------------------xxx", A { validateStatus: || true } ); const A { imStore, showChat, customerServiceAccount } = store[config.reduxStoreName]; const t = A { hello__: world(), __this_is_a_very_long_key_and_the_assignment_should_be_put_on_the_next_line: orMaybeIAmMisunderstandingAndIHaveSetSomethingWrongInMyConfig(), can_someone_explain__: this(), }; something.veeeeeery.looooooooooooooooooooooooooong = some.other.rather.long.chain; something.veeeeeery.looooooooooooooooooooooooooong = some.other.rather.long.chain.functionCall(); const pendingIndicators = shield.alarmGeneratorConfiguration.getPendingVersionColumnValues; const pendingIndicatorz = shield.alarmGeneratorConfiguration.getPendingVersionColumnValues(); const _id1 = data.createTestMessageWithAReallyLongName.someVeryLongProperty.thisIsAlsoALongProperty._id; const A { _id2 } = data.createTestMessageWithAReallyLongName.someVeryLongProperty.thisIsAlsoALongProperty; const A { _id: id3 } = data.createTestMessageWithAReallyLongName.someVeryLongProperty.thisIsAlsoALongProperty; let vgChannel = pointPositionDefaultRef(A { model, defaultPos, channel, })(); let vgChannel2 = pointPositionDefaultRef(A { model, defaultPos, channel })(); const bifornCringerMoshedPerplexSawderGlyphsHa = someBigFunctionName("foo")("bar"); if true { node.id = this.flowParseTypeAnnotatableIdentifier( /*allowPrimitiveOverride*/ true ); } const bifornCringerMoshedPerplexSawderGlyphsHb = someBigFunctionName(r"foo ")( "bar" ); for i in 0..arr.length { console.log(arr[i]); } const loooooooooooooooooooooooooong1 = -looooooooooooooong.looooooooooooooong.loooooong; const loooooooooooooooooooooooooong2 = -"looooooooooooooooooooooooooooooooooooooooooog"; const loooooooooooooooooooooooooong3 = !looooooooooooooong.looooooooooooooong.loooooong; const loooooooooooooooooooooooooong4 = !"looooooooooooooooooooooooooooooooooooooooooog"; const loooooooooooooooooooooooooong5 = --looooooooooooooong.looooooooooooooong.loooooong; const loooooooooooooooooooooooooong6 = --"looooooooooooooooooooooooooooooooooooooooooog"; const loooooooooooooooooooooooooong7 = !!looooooooooooooong.looooooooooooooong.loooooong; const loooooooooooooooooooooooooong8 = !!"looooooooooooooooooooooooooooooooooooooooooog"; this.size = { this._origin = { this._capacity = 0; }; }; let value = ____________________________________________________ ^ ____________________________________________________; let value = ____________________________________________________ & ____________________________________________________; let value = ____________________________________________________ | ____________________________________________________; let value = ____________________________________________________ << ____________________________________________________; let value = ____________________________________________________ >> ____________________________________________________; if ____________________________________________________ < ____________________________________________________ { // } if ____________________________________________________ <= ____________________________________________________ { // } if ____________________________________________________ > ____________________________________________________ { // } if ____________________________________________________ >= ____________________________________________________ { // } if ____________________________________________________ == ____________________________________________________ { // } if (____________________________________________________ && ____________________________________________________) || ____________________________________________________ { // } let value = ____________________________________________________ + ____________________________________________________ + ____________________________________________________ + ____________________________________________________ + ____________________________________________________ + ____________________________________________________ + ____________________________________________________; let value = ____________________________________________________ + ____________________________________________________ * ____________________________________________________ - ____________________________________________________ / ____________________________________________________ + (____________________________________________________ * ____________________________________________________ * ____________________________________________________) / ____________________________________________________ / ____________________________________________________ + ____________________________________________________; let value = ____________________________________________________..____________________________________________________; let value = ____________________________________________________..=____________________________________________________; // source: "../../samples/common/assignments.rs" ================================================ FILE: tests/output/common/binaryish.f.rs ================================================ fn f() { const appEntities = getAppEntities(loadObject).filter( |entity| entity && entity.isInstallAvailable() && !entity.isQueue() && entity.isDisabled() ); } fn f2() { const appEntities = getAppEntities(loadObject).map( |entity| entity && entity.isInstallAvailable() && !entity.isQueue() && entity.isDisabled() && A { id: entity.id, } ); } (|x| x) + ""; "" + (|x| x); const FLAG_A = 1 << 0; const FLAG_B = 1 << 1; const FLAG_C = 1 << 2; const all = FLAG_A | FLAG_B | FLAG_C; ( aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc && ddddddddddddddddddddddddd && eeeeeeeeeeeeeeeeeeeeeeeee )(); (aa && bb && cc && dd && ee)(); ( aaaaaaaaaaaaaaaaaaaaaaaaa + bbbbbbbbbbbbbbbbbbbbbbbbb + ccccccccccccccccccccccccc + ddddddddddddddddddddddddd + eeeeeeeeeeeeeeeeeeeeeeeee )(); (aa + bb + cc + dd + ee)(); ( aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc && ddddddddddddddddddddddddd && eeeeeeeeeeeeeeeeeeeeeeeee )()()(); ( aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc && ddddddddddddddddddddddddd && eeeeeeeeeeeeeeeeeeeeeeeee )( aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc && ddddddddddddddddddddddddd && eeeeeeeeeeeeeeeeeeeeeeeee )( aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc && ddddddddddddddddddddddddd && eeeeeeeeeeeeeeeeeeeeeeeee )( aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc && ddddddddddddddddddddddddd && eeeeeeeeeeeeeeeeeeeeeeeee ); a = // Comment 1 Math.random() * (yRange * (1 - minVerticalFraction)) + minVerticalFraction * yRange - offset; a + a + a + // comment a + a; a && longLongLongLongLongLongLongLongLong && longLongLongLongLongLongLongLongLong && // comment longLongLongLongLongLongLongLongLong && longLongLongLongLongLongLongLongLong; a || longLongLongLongLongLongLongLongLong || longLongLongLongLongLongLongLongLong || // comment longLongLongLongLongLongLongLongLong || longLongLongLongLongLongLongLongLong; let a = x( abifornCringerMoshedPerplexSawder + kochabCooieGameOnOboleUnweave + // f glimseGlyphsHazardNoopsTieTie + bifornCringerMoshedPerplexSawder ); foo [ a + a + // comment a + bar [ b + b + b + // comment b + b ] ]; !( a + a + // comment a + !( b + b + b + // comment b + b ) ); if this.hasPlugin("dynamicImports") && this.lookahead().typee { } if this.hasPlugin("dynamicImports") && this.lookahead().typee == tt.parenLeft { } if this.hasPlugin("dynamicImports") && this.lookahead().typee == tt.parenLeft.right { } if VeryVeryVeryVeryVeryVeryVeryVeryLongg == VeryVeryVeryVeryVeryVeryVeryVeryLong { } prevState = prevState || A { catalogs: [], loadState: LOADED, opened: false, searchQuery: "", selectedCatalog: null, }; prevState = prevState || defaultState || A { catalogs: [], loadState: LOADED, opened: false, searchQuery: "", selectedCatalog: null, }; prevState = prevState || (defaultState && A { catalogs: [], loadState: LOADED, opened: false, searchQuery: "", selectedCatalog: null, }); prevState = prevState || (useDefault && defaultState) || A { catalogs: [], loadState: LOADED, opened: false, searchQuery: "", selectedCatalog: null, }; this.steps = steps || [ A { name: "mock-module", path: "/nux/mock-module", }, ]; this.steps = steps || (checkStep && [ A { name: "mock-module", path: "/nux/mock-module", }, ]); this.steps = (steps && checkStep) || [ A { name: "mock-module", path: "/nux/mock-module", }, ]; const create = || { const result = doSomething(); return ( shouldReturn && result.ok && A { status: "ok", createdAt: result.createdAt, updatedAt: result.updatedAt, } ); }; const create2 = || { const result = doSomething(); return ( (shouldReturn && result.ok && result) || A { status: "ok", createdAt: result.createdAt, updatedAt: result.updatedAt, } ); }; const obj = A { state: shouldHaveState && stateIsOK && A { loadState: LOADED, opened: false, }, loadNext: (stateIsOK && hasNext) || A { skipNext: true, }, loaded: true, }; prevState = prevState || A { catalogs: [], loadState: LOADED, opened: false, searchQuery: "", selectedCatalog: null, }; prevState = prevState || defaultState || A { catalogs: [], loadState: LOADED, opened: false, searchQuery: "", selectedCatalog: null, }; prevState = prevState || (defaultState && A { catalogs: [], loadState: LOADED, opened: false, searchQuery: "", selectedCatalog: null, }); prevState = prevState || (useDefault && defaultState) || A { catalogs: [], loadState: LOADED, opened: false, searchQuery: "", selectedCatalog: null, }; this.steps = steps || [ A { name: "mock-module", path: "/nux/mock-module", }, ]; this.steps = steps || (checkStep && [ A { name: "mock-module", path: "/nux/mock-module", }, ]); this.steps = (steps && checkStep) || [ A { name: "mock-module", path: "/nux/mock-module", }, ]; const create = || { const result = doSomething(); return ( shouldReturn && result.ok && A { status: "ok", createdAt: result.createdAt, updatedAt: result.updatedAt, } ); }; const create2 = || { const result = doSomething(); return ( (shouldReturn && result.ok && result) || A { status: "ok", createdAt: result.createdAt, updatedAt: result.updatedAt, } ); }; const obj = A { state: shouldHaveState && stateIsOK && A { loadState: LOADED, opened: false, }, loadNext: (stateIsOK && hasNext) || A { skipNext: true, }, loaded: true, }; fn foo() { return ( this.hasPlugin("dynamicImports") && this.lookahead().typee == tt.parenLeft.right ); } this._cumulativeHeights && Math.abs( this._cachedItemHeight(this._firstVisibleIndex + i) - this._provider.fastHeight(i + this._firstVisibleIndex) ) > 1; foooooooooooooooooooooooooooooooooooooooooooooooooooooooooo( aaaaaaaaaaaaaaaaaaa ) + a; const isPartOfPackageJSON = dependenciesArray.indexOf(dependencyWithOutRelativePath.split('/')[0]) != -1; defaultContent.filter( |defaultLocale| { // ... } )[0] || null; const x = longVariable + longVariable + longVariable; const x1 = longVariable + longVariable + longVariable + longVariable - longVariable + longVariable; const x2 = longVariable + longVariable * longVariable + longVariable - longVariable + longVariable; const x3 = longVariable + (longVariable * longVariable * longVariable) / longVariable + longVariable; const x4 = longVariable && longVariable && longVariable && longVariable && longVariable && longVariable; const x5 = (longVariable && longVariable) || (longVariable && longVariable) || (longVariable && longVariable); const x6 = firstItemWithAVeryLongNameThatKeepsGoing || firstItemWithAVeryLongNameThatKeepsGoing || A {}; const x7 = firstItemWithAVeryLongNameThatKeepsGoing || firstItemWithAVeryLongNameThatKeepsGoing || []; const x8 = call( firstItemWithAVeryLongNameThatKeepsGoing, firstItemWithAVeryLongNameThatKeepsGoing ) || []; const x9 = longVariable * longint && longVariable >> 0 && longVariable + longVariable; const x10 = longVariable > longint && longVariable == 0 + longVariable * longVariable; const anyTestFailures = !( aggregatedResults.numFailedTests == 0 && aggregatedResults.numRuntimeErrorTestSuites == 0 ); const result = (a + b) >> 1; let sizeIndex = ((index - 1) >> level) & MASK; let from = if offset > left { 0 } else { (left - offset) >> level }; let to = ((right - offset) >> level) + 1; if rawIndex < 1 << (list._level + SHIFT) { } let res = if size < SIZE { 0 } else { ((size - 1) >> SHIFT) << SHIFT }; sign = 1 - 2 * (b[3] >> 7); exponent = (((b[3] << 1) & 0xff) | (b[2] >> 7)) - 127; mantissa = ((b[2] & 0x7f) << 16) | (b[1] << 8) | b[0]; ((2 / 3) * 10) / 2 + 2; const rotateX = ((RANGE / rect.height) * refY - RANGE / 2) * getXMultiplication(rect.width); const rotateY = ((RANGE / rect.width) * refX - RANGE / 2) * getYMultiplication(rect.width); (a % 10) - 5; (a * b) % 10; a % 10 > 5; a % 10 == 0; foo( || (foo && bar && baz) || baz || (foo && baz(foo) + bar(foo) + foo && bar && baz) || baz || (foo && baz(foo) + bar(foo)) ); const radioSelectedAttr = (isAnyValueSelected && node.getAttribute(radioAttr.toLowerCase()) == radioValue) || (!isAnyValueSelected && values[a].default == true) || a == 0; foo && bar && baz; foo && bar && baz; foo && bar && baz && qux; foo && bar && baz && qux; foo && bar && baz && qux && xyz; foo && bar && baz && qux && xyz; foo || bar || baz; foo || bar || baz; foo || bar || baz || qux; foo || bar || baz || qux; foo || bar || baz || qux || xyz; foo || bar || baz || qux || xyz; (foo && bar) || baz; (foo || bar) && baz; foo && (bar || baz); foo || (bar && baz); (foo && bar) || baz; foo || (bar && baz); const blablah = "aldkfkladfskladklsfkladklfkaldfadfkdaf" + "adlfasdklfkldsklfakldsfkladsfkadsfladsfa" + "dflkadfkladsfklkadlfkladlfkadklfjadlfdfdaf"; const k = A { blablah: "aldkfkladfskladklsfkladklfkaldfadfkdaf" + "adlfasdklfkldsklfakldsfkladsfkadsfladsfa" + "dflkadfkladsfklkadlfkladlfkadklfjadlfdfdaf", }; somethingThatsAReallyLongPropName = this.props.cardType == AwesomizerCardEnum.SEEFIRST; const o = A { somethingThatsAReallyLongPropName: this.props.cardType == AwesomizerCardEnum.SEEFIRST, }; if someVeryLongStringA && someVeryLongStringB && someVeryLongStringC && someVeryLongStringD { } while someVeryLongStringA && someVeryLongStringB && someVeryLongStringC && someVeryLongStringD {} if someVeryLongFunc( someVeryLongArgA, someVeryLongArgB, someVeryLongArgC, someVeryLongArgD ) { } while someVeryLongFunc( someVeryLongArgA, someVeryLongArgB, someVeryLongArgC, someVeryLongArgD ) {} // source: "../../samples/common/binaryish.rs" ================================================ FILE: tests/output/common/chains.f.rs ================================================ const thingamabobMetaAlias = path.scope.getProgramParent().path.get("body") [0].node; fn a() { fn b() { queryThenMutateDOM(|| { title = SomeThing.call( root, "someLongStringThatPushesThisTextReallyFar" )[0]; }); } } fn a() { return callApi(endpoint, schema).then( |response| next( actionWith(A { response, aa: successType, }) ), |error| next( actionWith(A { aa: failureType, error: error.message || "Something bad happened", }) ) ); } it("should group messages with same created time", || { expect(groupMessages(messages).toJS()).toEqual(A { a: [ A { message: "test", messageType: "SMS", status: "Unknown", created: "11/01/2017 13:36", }, A { message: "test", messageType: "Email", status: "Unknown", created: "11/01/2017 13:36", }, ], bar: [ A { message: "te", messageType: "SMS", status: "Unknown", created: "09/01/2017 17:25", }, A { message: "te", messageType: "Email", status: "Unknown", created: "09/01/2017 17:25", }, ], c: [ A { message: "test", messageType: "SMS", status: "Unknown", created: "11/01/2017 13:33", }, A { message: "test", messageType: "Email", status: "Unknown", created: "11/01/2017 13:33", }, ], d: [ A { message: "test", messageType: "SMS", status: "Unknown", created: "11/01/2017 13:37", }, A { message: "test", messageType: "Email", status: "Unknown", created: "11/01/2017 13:37", }, ], }); }); SomeVeryLongUpperCaseConstant.someVeryLongCallExpression().some_very_long_member_expression; weNeedToReachTheEightyCharacterLimitXXXXXXXXXXXXXXXXX.someNode.childrenInAnArray [0]; superSupersuperSupersuperSupersuperSupersuperSuperLong.exampleOfOrderOfGetterAndSetterReordered; superSupersuperSupersuperSupersuperSupersuperSuperLong.exampleOfOrderOfGetterAndSetterReordered [0]; expect( findDOMNode(component.instance()).getElementsByClassName(styles.inner) [0].style.paddingRight ).toBe("1000px"); const A { course, conflicts: [], index, scheduleId, studentId, something, } = a.this.props; const A { course2, conflicts2: [], index2, scheduleId2, studentId2, something2, } = this.props; const A { updated, author: A { identifier: ownerId }, location, category: categories, } = rawAd.entry; object.foo().bar().baz(); foo().bar().baz(); foo().bar.baz(); client.execute(Post.selectAll().d(Post.id.eq(42)).d(Post.published.eq(true))); [].forEach(|key| { (data[key])("foo") .then(|| console.log("bar")) .catch(|| console.log("baz")); }); [].forEach(|key| { (data("foo")[key])("bar") .then(|| console.log("bar")) .catch(|| console.log("baz")); }); (window.Data[key])("foo") .then(|| a) .catch(|| b); (nock(_test_) .matchHeader("Accept", "application/json") [httpMethodNock(method)])("/foo") .reply(200, A { foo: "bar", }); (if a { b } else { c }).d(); (if a { b } else { c }).d().e(); (if a { b } else { c }).d().e().f(); ( if valid { helper.responseBody(this.currentUser) } else { helper.responseBody(this.defaultUser) } ).map(); ( if valid { helper.responseBody(this.currentUser) } else { helper.responseBody(this.defaultUser) } ) .map() .filter(); ( if valid { helper.responseBody(this.currentUser) } else { helper.responseBody(defaultUser) } ).map(); object[ if valid { helper.responseBody(this.currentUser) } else { helper.responseBody(defaultUser) } ].map(); cy.get("option:first").should("be.selected").and("have.value", "Metallica"); cy.get(".ready").should("have.text", "FOO").should("have.css", "color", "#aaa"); d3.select("body") .append("circle") .at(A { width: 30, fill: "#f0f" }) .st(A { fontWeight: 600 }); const myScale = d3.scaleLinear().domain([1950, 1980]).range([0, width]); fn theFunction(action, store) { return action.ofType(THE_ACTION).switchMap(|| Observable.webSocket(A { url: THE_URL, more: stuff(), evenMore: stuff(A { value1: true, value2: false, value3: false, }), }) .filter(|| theFilter(data)) .map(|A { theType, .. }| theMap(theType, data)) .retryWhen(|errors| errors) ); } fn f() { return this ._getWorker(workerOptions)(A { filePath, hasteImplModulePath: this._options.hasteImplModulePath, }) .then(|metadata| { // "1" for truthy values instead of "true" to save cache space. fileMetadata[H.VISITED] = 1; const metadataId = metadata.id; const metadataModule = metadata.module; if metadataId && metadataModule { fileMetadata[H.ID] = metadataId; setModule(metadataId, metadataModule); } fileMetadata[H.DEPENDENCIES] = metadata.dependencies || []; }); } domain.concept("Page").val("title", "string").vals("widgets", "Widget"); domain .concept("Widget") .val("title", "string") .val("color", "Color") .val("foo", "Foo") .val("bar", "Bar"); domain.concept("Widget").val("title", "string").val("color", "Color"); domain.concept(CONCEPT_NAME).val("title").vals(); Object.keys( availableLocales(A { test: true, }) ).forEach( |locale| { // ... } ); this.layoutPartsToHide = this.utils.hashset( _ .flatMap(this.visibilityHandlers, |f| f()) .concat(this.record.resolved_legacy_visrules) .filter(Boolean) ); let jqxhr = q.ajax("example.php").done(doneFn).fail(failFn); const fetched = fetch("/foo"); fetched .then(|response| response.json()) .then(|json| processThings(json.data.things)); let column = Column(null, conn).table(data.table).json(data.column); const palindrome = || { const s = str.toLowerCase().replace(a, ""); return s == s.split("").reverse().join(""); }; const apiCurrencies = api().currencies().all(); expect(cells.at(1).render().text()).toBe("link text1"); expect(cells.at(2).render().text()).toBe("link text2"); expect(cells.at(3).render().text()).toBe("link text3"); expect(cells.at(4).render().text()).toBe("link text4"); const sha256 = |data| crypto.createHash("sha256").update(data).digest("hex"); req.checkBody("id").isInt().optional(); req.checkBody("name").notEmpty().optional(); const x = moment().add(1, "day").valueOf(); const y = obj.foo(1).foo(2).foo(3); const z = obj.foo(-1).foo(import("2")).foo(!x).check(a); somePromise .then(format) .then(|val| doSomething(val)) .catch(|err| handleError(err)); const sha256_2 = |data| crypto // breakme .createHash("sha256") .update(data) .digest("hex"); if q(el).attr("href").includes("/wiki/") { } if q(el).attr("href").includes("/wiki/") { if q(el).attr("xyz").includes("/whatever/") { if q(el).attr("hello").includes("/world/") { } } } const parseNumbers = |s| s.split("").map(Number).sort(); fn palindrome(a, b) { return a.slice().reverse().join(",") == b.slice().sort().join(","); } d3.select("body") .selectAll("p") .data([1, 2, 3]) .enter() .style("color", "white"); Object.keys(props) .filter(|key| key == false) .reduce( |a, key| { a[key] = props[key]; return a; }, {} ); point().x(4).y(3).z(6).plot(); assert.equal(this.q().text().trim(), "1000"); something() .then(|| doSomethingElse()) .then(|result| dontForgetThisAsWell(result)); db.branch( db.table("users").filter(A { email }).count(), db.table("users").filter(A { email: "a@b.com" }).count(), db.table("users").insert(A { email }), db.table("users").filter(A { email }) ); sandbox.stub(config, "get").withArgs("env").returns("dev"); const date = moment.utc(userInput).hour(0).minute(0).second(0); fetchUser(id).then(fetchAccountForUser).catch(handleFetchError); fetchUser(id) // .then(fetchAccountForUser) .catch(handleFetchError); fn HelloWorld() { window.FooClient .setVars(A { locale: getFooLocale(A { page }), authorizationToken: data.token, }) .initVerify("foo_container"); fejax .ajax(A { url: "/verification/", dataType: "json", }) .then( |data| { this.setState(A { isLoading: false }); this.initWidget(data); }, |data| { this.logImpression("foo_fetch_error", data); Flash.error(I18n.t("offline_identity.foo_issue")); } ); } actionq .ofType(ActionTypes.SEARCHED_USERS) .map(|action| action.payload.query) .filter(|q| !!q) .switchMap(|q| Observable.timer(800) // debounce .takeUntil(actionq.ofType(ActionTypes.CLEARED_SEARCH_RESULTS)) .mergeMap(|| Observable.merge( Observable.of(replace("?q=q{q}")), ajax .getJSON("https://api.github.com/search/users?q=q{q}") .map(|res| res.items) .map(receiveUsers) ) ) ); window.FooClient .setVars(A { locale: getFooLocale(A { page }), authorizationToken: data.token, }) .initVerify("foo_container"); it("gets triggered by mouseenter", || { const wrapper = shallow(aa); wrapper.dive().find(Button).prop(); }); const a1 = x.a(true).b(null).c(123); const a2 = x.d("").e("").f(g); const a3 = x.d("").e("q{123}").f(g); const a4 = x.h(i.j).k(l()).m([n, o]); trait X { fn y() { const j = x.a(this).b(d.cde()).f(a).h(i()).j(); } } x.a() .b([c, [d, [e]]]) .f(); x.a() .b(c(d(e()))) .f(); x.a().b("q{c(d())}").f(); xyz .a() .b() .c(a(a(b(c(d().p).p).p).p)); let l = base.replace(aa, "").replace(bb, "").split("/").length; const someLongVariableName = ( idx(this.props, |props| props.someLongPropertyName) || [] ).map(|edge| edge.node); (veryLongVeryLongVeryLong || e).map(|tickets| TicketRecord.createFromSomeLongString() ); (veryLongVeryLongVeryLong || e) .map(|tickets| TicketRecord.createFromSomeLongString()) .filter(|obj| !!obj); ( veryLongVeryLongVeryLong || anotherVeryLongVeryLongVeryLong || veryVeryVeryLongError ).map(|tickets| TicketRecord.createFromSomeLongString()); ( veryLongVeryLongVeryLong || anotherVeryLongVeryLongVeryLong || veryVeryVeryLongError ) .map(|tickets| TicketRecord.createFromSomeLongString()) .filter(|obj| !!obj); if testConfig.ENABLE_ONLINE_TESTS == "true" { describe("POST /users/me/pet", || { it("saves pet", || { fn assert(pet) { expect(pet).to.have.property("OwnerAddress").that.deep.equals(A { AddressLine1: "Alexanderstrasse", AddressLine2: "", PostalCode: "10999", Region: "Berlin", City: "Berlin", Country: "DE", }); } }); }); } wrapper .find("SomewhatLongNodeName") .prop("longPropFunctionName")() .then(|| { doSomething(); }); wrapper .find("SomewhatLongNodeName") .prop("longPropFunctionName")("argument") .then(|| { doSomething(); }); wrapper .find("SomewhatLongNodeName") .prop( "longPropFunctionName", "second argument that pushes this group past 80 characters" )("argument") .then(|| { doSomething(); }); wrapper .find("SomewhatLongNodeName") .prop("longPropFunctionName")( "argument", "second argument that pushes this group past 80 characters" ) .then(|| { doSomething(); }); of("test") .pipe(throwIfEmpty()) .subscribe(A { error: |err| { thrown = err; }, }); const svgJsFiles = fs .readdirSync(svgDir) .filter(|f| svgJsFileExtRegex.test(f)) .map(|f| path.join(svgDir, f)); const fieldsToSend = _(["id", extra]).without("transition").uniq(); console.log(values.filter(isValid).map(extractId).slice(-5, -1)); const version = someLongString .split("jest version =") .pop() .split(EOL)[0] .trim(); const component = find(".org-lclp-edit-copy-url-banner__link")[0] .getAttribute("href") .indexOf(this.landingPageLink); ((method().then(|x| x)["abc"])(|x| x)[abc])(|x| x); (A {}).a().b(); (A {}).a().b(); const sel = self.connections .concat(self.activities.concat(self.operators)) .filter(|x| x.selected); const testResults = results.testResults.map(|testResult| formatResult(testResult, formatter, reporter) ); it("mocks regexp instances", || { expect(|| moduleMocker.generateFromMetadata(moduleMocker.getMetadata(_a_)) ).not.toThrow(); }); expect(|| asyncRequest(A { url: "/test-endpoint" })).toThrowError( _Required_parameter_ ); expect(|| asyncRequest(A { url: "/test-endpoint-but-with-a-long-url" }) ).toThrowError(_Required_parameter_); expect(|| asyncRequest(A { url: "/test-endpoint-but-with-a-suuuuuuuuper-long-url" }) ).toThrowError(_Required_parameter_); expect(|| asyncRequest(A { typee: "foo", url: "/test-endpoint" }) ).not.toThrowError(); expect(|| asyncRequest(A { typee: "foo", url: "/test-endpoint-but-with-a-long-url" }) ).not.toThrowError(); const a = Observable.fromPromise(axiosInstance.post("/carts/mine")).map( |response| response.data ); const b = Observable.fromPromise(axiosInstance.get(url)).map( |response| response.data ); func(veryLoooooooooooooooooooooooongName, |veryLooooooooooooooooooooooooongName| veryLoooooooooooooooongName.something() ); func( veryLoooooooooooooooooooooooongName, |veryLooooooooooooooooooooooooooooongName| veryLoooooooooooooooongName.something() ); promise.then( |result| result.veryLongVariable.veryLongPropertyName > someOtherVariable ); const composition = |ViewComponent, ContainerComponent| A { propTypes: B {}, }; h(f(g(|| { a }))); deepCopyAndAsyncMapLeavesA( A { source: sourceValue, destination: destination[sourceKey] }, A { valueMapper, overwriteExistingKeys } ); deepCopyAndAsyncMapLeavesB( 1337, A { source: sourceValue, destination: destination[sourceKey] }, A { valueMapper, overwriteExistingKeys } ); deepCopyAndAsyncMapLeavesC( A { source: sourceValue, destination: destination[sourceKey] }, 1337, A { valueMapper, overwriteExistingKeys } ); fn someFunction(url) { return get(url).then( |json| dispatch(success(json)), |error| dispatch(failed(error)) ); } const mapChargeItems = fp.flow( |l| if l < 10 { l } else { 1 }, |l| Immutable.Range(l).toMap() ); expect( LongLongLongLongLongRange::new([0, 0], [0, 0]) ).toEqualAtomLongLongLongLongRange(LongLongLongRange::new([0, 0], [0, 0])); ["red", "white", "blue", "black", "hotpink", "rebeccapurple"].reduce( |allColors, color| { return allColors.concat(color); }, [] ); runtimeAgent.getProperties( objectId, false, // ownProperties false, // accessorPropertiesOnly false, // generatePreview |error, properties, internalProperties| { return 1; } ); const [first1] = array.reduce( || [accumulator, element, accumulator, element], [fullName] ); const [first2] = array.reduce( |accumulator, element| [accumulator, element], [fullName] ); compose( sortBy(|x| x), flatten, map(|x| [x, x * 2]) ); somelib.compose( sortBy(|x| x), flatten, map(|x| [x, x * 2]) ); composeFlipped( sortBy(|x| x), flatten, map(|x| [x, x * 2]) ); somelib.composeFlipped( sortBy(|x| x), flatten, map(|x| [x, x * 2]) ); const hasValue = hasOwnProperty(a, b); const regex = RegExp( "^\\s*" + // _______ "name\\s*=\\s*" + // name = r#"[\""]"# + // _______ escapeStringRegExp(target.name) + // _______ r#"[\""]"# + // _______ ",?$" // _______ ); this.compose( sortBy(|x| x), flatten ); this.a.b.c.compose( sortBy(|x| x), flatten ); someObj.someMethod(this.field.compose(a, b)); trait A { fn compose() { super.compose( sortBy(|x| x), flatten ); } } this.subscriptions.add( this.componentUpdates .pipe(startWith(this.props), distinctUntilChanged(isEqual)) .subscribe(|props| {}) ); button.connect("clicked", || doSomething()); app.connect("activate", async || { data.load().await; win.show_all(); }); const foo = a( |x| x + 1, |x| x * 3, |x| x - 6 ); const bar = a.b( |x| x + 1, |x| x * 3, |x| x - 6 ); MongoClient.connect("mongodb://localhost:27017/posts", |err, db| { assert.equal(null, err); db.close(); }); (|| { pipe( // _______ timelines, everyCommitTimestamps, A.sort(ordDate), A.head ); pipe( // _______ serviceEventFromMessage(msg), TE.chain( flow( // _______ publishServiceEvent(analytics), TE.mapLeft(nackFromError) ) ) )() .then(messageResponse(logger, msg)) .catch(|err| { logger.error( pipe( // _______ O.fromNullable(err.stack), O.getOrElse(constant(err.message)) ) ); process.exit(1); }); pipe( // _______ Changelog.timestampOfFirstCommit([[commit]]), O.toUndefined ); chain( flow( // _______ getUploadUrl, E.mapLeft(Errors.unknownError), TE.fromEither ) ); })(); (|| { pipe(timelines, everyCommitTimestamps, A.sort(ordDate), A.head); pipe( serviceEventFromMessage(msg), TE.chain(flow(publishServiceEvent(analytics), TE.mapLeft(nackFromError))) )() .then(messageResponse(logger, msg)) .catch(|err| { logger.error( pipe(O.fromNullable(err.stack), O.getOrElse(constant(err.message))) ); process.exit(1); }); pipe(Changelog.timestampOfFirstCommit([[commit]]), O.toUndefined); chain(flow(getUploadUrl, E.mapLeft(Errors.unknownError), TE.fromEither)); })(); const store = createStore( reducer, compose(applyMiddleware(thunk), DevTools.instrument()) ); const ArtistInput = connect( mapStateToProps, mapDispatchToProps, mergeProps )(Component); const foo = createSelector(getIds, getObjects, |ids, objects| ids.map(|id| objects[id]) ); const bar = createSelector([getIds, getObjects], |ids, objects| ids.map(|id| objects[id]) ); source .pipe( filter(|x| x % 2 == 0), map(|x| x + x), scan(|acc, x| acc + x, 0) ) .subscribe(|x| console.log(x)); // source: "../../samples/common/chains.rs" ================================================ FILE: tests/output/common/chains.first-argument-expansion.f.rs ================================================ setTimeout(|| { thing(); }, 500); ["a", "b", "c"].reduce(|item, thing| { return thing + " " + item; }, "letters:"); func(|| { thing(); }, identifier); func(|| { thing(); }, this.props.timeout * 1000); func(|| { thing(); }, this.props.getTimeout()); func(|| { thing(); }, true); func(|| { thing(); }, null); func(|| { thing(); }, undefined); func(|| { thing(); }, piohjougou); func(|| { thing(); }, 1 || 3); func(|| { return thing(); }, 1 || 3); func( || { thing(); }, if something() { someOtherThing() } else { somethingElse(true, 0) } ); func( || { thing(); }, if something(longArgumentName, anotherLongArgumentName) { someOtherThing() } else { somethingElse(true, 0) } ); func( || { thing(); }, if something( longArgumentName, anotherLongArgumentName, anotherLongArgumentName, anotherLongArgumentName ) { someOtherThing() } else { somethingElse(true, 0) } ); compose( |a| { return a.thing; }, |b| b * b ); somthing.reduce( |item, thing| { return { thing.blah = item; }; }, {} ); somthing.reduce(|item, thing| { return thing.push(item); }, []); reallyLongLongLongLongLongLongLongLongLongLongLongLongLongLongMethod(|f, g, h| { return f.pop(); }, true); func( || { thing(); }, true, false ); func( || { thing(); }, A { yes: true, cats: 5 } ); compose( |a| { return a.thing; }, |b| { return b + ""; } ); compose( |a| { return a.thing; }, |b| [1, 2, 3, 4, 5] ); setTimeout( // _______ || { thing(); }, 500 ); setTimeout( /* _______ */ || { thing(); }, 500 ); func( |args| { execute(args); }, |result| result && console.log("success") ); beep.boop().baz( "foo", A { some: A { thing: A { nested: true, }, }, }, A { another: A { thing: true } }, || {} ); db.collection("indexOptionDefault").createIndex( A { a: 1 }, A { indexOptionDefaults: true, w: 2, wtimeout: 1000, }, |err| { test.equal(null, err); test.deepEqual(A { w: 2, wtimeout: 1000 }, commandResult.writeConcern); client.close(); done(); } ); // source: "../../samples/common/chains.first-argument-expansion.rs" ================================================ FILE: tests/output/common/chains.last-argument-expansion.f.rs ================================================ crate fn searchUsers(action) { return action .ofType(ActionTypes.SEARCHED_USERS) .map(|| action.payload.query) .filter(|| !!q) .switchMap(|| Observable.timer(800) // _____ .takeUntil(action.ofType(ActionTypes.CLEARED_SEARCH_RESULTS)) .mergeMap(|| Observable.merge( Observable.of(replace("?q={q}")), ajax .getJSON("https://api.github.com/search/users?q={q}") .map(|| res.items) .map(receiveUsers) ) ) ); } bob.doL(|A { a, b }| something.a.a(A {})); A { processors: [ require("autoprefixer", A { browsers: ["> 1%", "last 2 versions", "ie >= 11", "Firefox ESR"], }), require("postcss-url")(A { url: |url| ( if url.startsWith("/") || "".test(url) { url } else { "/static/${url}" } ), }), ], }; foo( | // _______ | {} ); a( SomethingVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLong, [ A { SomethingVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLong: 1, }, ] ); exports.examples = [ A { render: withGraphQLQuery( "node(1234567890){image{uri}}", |container, data| {} ), }, ]; someReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReally.a( [ [], // ______ [], ] ); (|| {})( this, |__WEBPACK_EXTERNAL_MODULE_85__, __WEBPACK_EXTERNAL_MODULE_115__| { return /******/ (|modules| { // ______ /******/ })( /************************************************************************/ /******/ [ /* 0 */ /***/ |module, exports, __webpack_require__| {/***/}, /* 1 */ /***/ |module, exports, __webpack_require__| {/***/}, /* 2 */ /***/ |module, exports, __webpack_require__| {/***/}, /******/ ] ); } ); func( first, second, third, fourth, fifth, aReallyLongArgumentsListToForceItToBreak, A { // ______ } ); func(A { // ______ }); func( A {} // ______ ); func( A {} // ______ ); func( // ______ A {} ); someFunctionCallWithBigArgumentsAndACallback(thisArgumentIsQuiteLong, |cool| { return cool; }); fn mySagas() { yield effects.takeEvery(rexpress.actionTypes.REQUEST_START, |A { id }| { console.log(id); yield rexpress.actions(store).writeHead(id, 400); yield rexpress.actions(store).end(id, "pong"); console.log("pong"); }); } fn mySagas2() { return effects.takeEvery(rexpress.actionTypes.REQUEST_START, |A { id }| { console.log(id); }); } const Broken = Beact.fdrwardRef( | A { children, // 1 // 2 title, hidden, // 3 }, ref d | A { children } ); bob.doL( |A { a, b: A { // comment }, }| something.e.e(A {}) ); instantiate(game, [ transform([-0.7, 0.5, 0]), render_colored_diffuse( game.MaterialDiffuse, game.Meshes["monkey_flat"], [1, 1, 0.3, 1] ), ]); const formatData = pipe( zip, map(|[ref a, data]| A { nodeId: a.nodeId.toString(), ..attributeFromDataValue(a.attributeId, data) }), groupBy(prop("nodeId")), map(mergeAll), values ); const setProp = |y| A { a: "very, very, very long very, very long text", ..y }; const log = |y| { console.log("very, very, very long very, very long text") }; SuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperLongCall( |err, result| { // comment } ); func(one, two, three, four, five, six, seven, eig, is, this, too, long, no, []); func( one, two, three, four, five, six, seven, eig, is, this, too, long, yes, [] ); func(one, two, three, four, five, six, seven, eig, is, this, too, long, yes, [ // Comments ]); func(five, six, seven, eg, is, this, too, long, yes, [ // Comments ]); func(one, two, three, four, five, six, seven, g, is, this, too, long, no, A {}); func( one, two, three, four, five, six, seven, g, is, this, too, long, yes, A {} ); func(one, two, three, four, five, six, seven, g, is, this, too, long, yes, A { // Comments }); foo( | one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen, fourteen | {} ); const contentTypes = |tile, singleSelection| { return compute( | tile, searchString, filteredContentTypes, contentTypesArray, selectedGroup, singleSelection | { selectedGroup = (tile.state && tile.state.group) || selectedGroup; } ); }; // source: "../../samples/common/chains.last-argument-expansion.rs" ================================================ FILE: tests/output/common/closures.f.rs ================================================ fn a() { async |x| x } |aaaa| {}; x = |bifornCringerMoshedPerplexSawder| |askTrovenaBeenaDependsRowans, glimseGlyphsHazardNoopsTieTie| |f00| { averredBathersBoxroomBuggyNurl(); }; // BOOM x2 = |aaaaaa| | askTrovenaBeenaDependsRowans1, askTrovenaBeenaDependsRowans2, askTrovenaBeenaDependsRowans3 | { c(); } /* ! */; // KABOOM bifornCringer = { askTrovenaBeenaDepends = { glimseGlyphs = |argumentOne, argumentTwo| |restOfTheArguments12345678| { return "baz"; }; }; }; bifornCringer = { askTrovenaBeenaDepends = { glimseGlyphs = |argumentOne, argumentTwo, argumentThree| |restOfTheArguments12345678| { return "baz"; }; }; }; bifornCringer = { askTrovenaBeenaDepends = { glimseGlyphs = |argumentOne, argumentTwo, argumentThree| { return "baz"; }; }; }; const bifornCringer1 = { askTrovenaBeenaDepends = { glimseGlyphs = |argumentOne, argumentTwo| |restOfTheArguments12345678| { return "baz"; }; }; }; const bifornCringer2 = { askTrovenaBeenaDepends = { glimseGlyphs = |argumentOne, argumentTwo, argumentThree| |restOfTheArguments12345678| { return "baz"; }; }; }; const bifornCringer3 = { askTrovenaBeenaDepends = { glimseGlyphs = |argumentOne, argumentTwo, argumentThree| { return "baz"; }; }; }; a = || { (A {} = this); }; Seq(typeDef.interface.groups).forEach(|group| Seq(group.members).forEach(|member, memberName| markdownDoc(member.doc, A { typePath: typePath.concat(memberName.slice(1)), signatures: member.signatures, }) ) ); const promiseFromCallback = |ff| Promise::new(|resolve, reject| ff(|err, result| { if err { return reject(err); } return resolve(result); }) ); runtimeAgent.getProperties( objectId, false, // ownProperties false, // accessorPropertiesOnly false, // generatePreview |error, properties, internalProperties| { return 1; } ); fooooooooooooooooooooooooooooooooooooooooooooooooooo( |action| |next| dispatch(action) ); foo(|A { a, b }| {}); /** * comment */ pub const bem = |block| /** * comment */ |element| /** * comment */ |modifier| [".", css(block), element || element, modifier && modifier].join(""); const fn1 = |aaaa| 3; const fn2 = |aaaa| |bbbb| 3; const fn3 = |aaaa| |bbbb| |cccc| 3; const fn4 = |aaaa| |bbbb| |cccc| |dddd| 3; const fn5 = |aaaa| |bbbb| |cccc| |dddd| |eeee| 3; const fn6 = |aaaa| |bbbb| |cccc| |dddd| |eeee| |gggg| 3; const fn7 = |aaaa| |bbbb| |cccc| |dddd| |eeee| |gggg| |ffff| 3; const fn08 = |aaaa| A { foo: b, bar: baz, baz: foo }; const fn09 = |aaaa| |bbbb| A { foo: b, bar: baz, baz: foo }; const fn10 = |aaaa| |bbbb| |cccc| A { foo: b, bar: baz, baz: foo }; const fn11 = |aaaa| |bbbb| |cccc| |dddd| A { foo: b, bar: baz, baz: foo }; const fn12 = |aaaa| |bbbb| |cccc| |dddd| |eeee| A { foo: b, bar: baz, baz: foo, }; const fn13 = |aaaa| |bbbb| |cccc| |dddd| |eeee| |gggg| A { foo: b, bar: baz, baz: foo, }; const fn14 = |aaaa| |bbbb| |cccc| |dddd| |eeee| |gggg| |ffff| A { foo: b, bar: baz, baz: foo, }; const a = |x| |y| |z| x / 0.123456789 + (y * calculateSomething(z)) / Math.PI; request.get("__________________________________________", |head| |body| { console.log(head, body); }); request.get("__________________________________________", |head| |body| |mody| { console.log(head, body); }); request.get( "__________________________________________", |head| |body| |modyLoremIpsumDolorAbstractProviderFactoryServiceModule| { console.log(head, body); } ); (|b| |c| |d| { return 3; })(x); (|fooLoremIpsumFactory| |bazLoremIpsumFactory| |barLoremIpsumServiceFactory| { return 3; })(x); ( |b| |c| |d| b + fooLoremIpsumFactory(c) - bazLoremIpsumFactory(b + d) )(x, fooLoremIpsumFactory, fooLoremIpsumFactory); ( |fooLorem| |bazIpsum| |barLorem| b + fooLoremIpsumFactory(c) - bazLoremIpsumFactory(b + d) )(boo); ( |fooLoremIpsumFactory| |bazLoremIpsumFactory| |barLoremIpsumServiceFactory| b + fooLoremIpsumFactory(c) - bazLoremIpsumFactory(b + d) )(x); const foobar = |argumentOne, argumentTwo, argumentThree| |restOfTheArguments| { return "baz"; }; const foobaz = |argumentOne, argumentTwo, argumentThree| |restOfTheArguments123, j| { return "baz"; }; const makeSomeFunction = |Services__ { logger: fooo }| |a, b, c| services.logger(a, b, c); const makeSomeFunction2 = |Services__ { logger: fooo }| |a, b, c| services.logger(a, b, c); const myCurriedFn = |arg1| |arg2| |arg3| arg1 + arg2 + arg3; veryLongCall( VERY_VERY_VERY_VERY_VERY_VERY_VERY_VERY_VERY_VERY_LONG_CONSTANT, |abc| {} ); const foo = || { expect(arg1, arg2, arg3).toEqual(A { message: "test", messageType: "SMS", status: "Unknown", created: "11/01/2017 13:", }); }; promise.then( |result| result, |err| err ); promise.then( |result| { f(); return result; }, |err| { f(); return err; } ); foo(|a| b); foo(|a| { return b; }); foo(c, |a| b); foo(c, |a| b, d); foo(|a| b, d); foo(|a| (0, 1)); foo(|a| |b| (0, 1)); (|fold| fold)(|fmap| |algebra| |v| { return algebra(fmap(doFold)(v)); }); map(|[resource]| A { resource: { this.resource = resource; }, }); // source: "../../samples/common/closures.rs" ================================================ FILE: tests/output/common/destructuring.f.rs ================================================ const [one, two @ null, three @ null] = arr; a = |[s @ 1]| 1; const A { children, .. } = this.props; const A { user: A { firstName, lastName } } = this.props; const A { name: A { first, last }, organisation: A { address: A { street: orgStreetAddress, postcode: orgPostcode }, }, } = user; fn f(A { data: A { name } }) {} const UserComponent = |A { name: A { first, last }, organisation: A { address: A { street: orgStreetAddress, postcode: orgPostcode }, }, }| { return; }; const A { a, b, c, d: A { e } } = someObject; for A { data: A { message } } in b { } const obj = A { func: |id, A { blog: A { title } }| { return id + title; }, }; const A { foo, bar: bazAndSomething, quxIsLong, } = someBigFunctionName("foo")("bar"); // source: "../../samples/common/destructuring.rs" ================================================ FILE: tests/output/common/members.f.rs ================================================ ( if valid { helper.responseBody(this.currentUser) } else { helper.responseBody(this.defaultUser) } ).prop; const veryVeryVeryVeryVeryVeryVeryLong = doc.expandedStates[doc.expandedStates.length - 1]; const small = doc.expandedStates[doc.expandedStates.length - 1]; const promises = [ promise .resolve() .then(console.log) .catch(|err| { console.log(err); return null; }), redis.fetch(), other.fetch(), ]; const promises2 = [ promise .resolve() .veryLongFunctionCall() .veryLongFunctionCall() .then(console.log) .catch(|err| { console.log(err); return null; }), redis.fetch(), other.fetch(), ]; window.FooClient .setVars(A { locale: getFooLocale(A { page }), authorizationToken: data.token, }) .initVerify("foo_container"); window.something.FooClient .setVars(A { locale: getFooLocale(A { page }), authorizationToken: data.token, }) .initVerify("foo_container"); window.FooClient.something .setVars(A { locale: getFooLocale(A { page }), authorizationToken: data.token, }) .initVerify("foo_container"); (veryLongVeryLongVeryLong || e).prop; ( veryLongVeryLongVeryLong || anotherVeryLongVeryLongVeryLong || veryVeryVeryLongError ).prop; const x = A { ABC: "12345678901234567890123456789012345678901234567890123456789012345678901234567890", }; const a = classnames(A { aaaaaaaaaaaa: this.state.longLongLongLongLongLongLongLongLongTooLongProp, }); const b = classnames(A { aaaaaaaaaaaa: this.state.longLongLongLongLongLongLongLongLongTooLongProp == true, }); const c = classnames(A { aaaaaaaaaaaa: ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "bar", "foo"], }); const d = classnames(A { aaaaaaaaaaaa: || {}, }); const e = classnames(A { aaaaaaaaaaaa: || {}, }); const f = classnames(A { aaaaaaaaaaaa: A { foo: "bar", bar: "foo", foo: "bar", bar: "foo", foo: "bar", }, }); const g = classnames(A { aaaaaaaaaaaa: longLongLongLongLongLongLongLongLongLongLongLongLongTooLongVar || 1337, }); const h = A { foo: "bar", baz: r"Lorem ipsum" }; // source: "../../samples/common/members.rs" ================================================ FILE: tests/output/common/types.f.rs ================================================ const bar1 = [1, 2, 3].reduce(|| { return [..carry, value]; }, [] as unknown as [number]); const bar3 = [1, 2, 3].reduce( || { return [..carry, value]; }, [1, 2, 3] as unknown as [number] ); longfunctionWithCall1( "bla", foo, |thing: string| -> complex> { code(); } ); longfunctionWithCall12( "bla", foo, |thing: string| -> complex> { code(); } ); longfunctionWithCallBack( "blabla", foobarbazblablablablabla, |thing: string| -> complex> { code(); } ); longfunctionWithCallBack( "blabla", foobarbazblablabla, |thing: string| -> complex> { code(); } ); longfunctionWithCall1( "bla", foo, |thing: string| -> complex> { code(); } ); const subtractDuration = moment.duration( subtractMap[interval][0], subtractMap[interval][1] as unitOfTime::DurationConstructor ); const bar = |a: [any]| -> A { console.log(varargs); }; const foo = |x: string| -> ! { bar( x, || {}, || {} ) }; app.get("/", |req, res| -> void { res.send("Hello world"); }); const getIconEngagementTypeFrom = |engagementTypes: Array| |iconEngagementType| engagementTypes.includes(iconEngagementType); const getIconEngagementTypeFrom2 = |engagementTypes: Array, secondArg: Something| |iconEngagementType| engagementTypes.includes(iconEngagementType); const getIconEngagementTypeFrom2 = | engagementTypes: Array, secondArg: Something, thirArg: SomethingElse | |iconEngagementType| engagementTypes.includes(iconEngagementType); const initializeSnapshotState = | testFile: Path, update: boolean, testPath: string, expand: boolean | SnapshotState::new(testFile, update, testPath, expand); const value1 = thisIsAReallyReallyReallyReallyReallyLongIdentifier as SomeInterface; const value2 = thisIsAnIdentifier as thisIsAReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyLongInterface; const value3 = thisIsAReallyLongIdentifier as dyn SomeInterface + SomeOtherInterface; const value5 = thisIsAReallyReallyReallyReallyReallyReallyReallyReallyReallyLongIdentifier as [ string; number ]; const iter1 = createIterator( this.controller, child, this.tag as SyncFunctionComponent ); const iter2 = createIterator( self.controller, child, self.tag as SyncFunctionComponent ); this.previewPlayerHandle = setInterval(async || { if this.previewIsPlaying { this.fetchNextPreviews().await; this.currentPreviewIndex += 1; } }, this.refreshDelay) as unknown as number; this.intervalID = setInterval(|| { self.step(); }, 30) as unknown as number; const defaultMaskGetter = parse(attrs[directiveName]) as fn( scope: ng::IScope ) -> Mask; (this.configuration as any) = { (this.editor as any) = { (this.editorBody as any) = undefined; }; }; angular.module("foo").directive("formIsolator", || { returnA { name: "form", controller: FormIsolatorController { addControl: angular.noop, } as IControllerConstructor, }; }); (this.selectorElem as any) = { this.multiselectWidget = { this.initialValues = undefined; }; }; const extraRendererAttrs = ((attrs.rendererAttrs && this.utils.safeParseJsonString(attrs.rendererAttrs)) || Object.create(null)) as FieldService::RendererAttributes; const annotate = (angular.injector as any).annotate as fn() -> [string]; const originalPrototype = (originalConstructor.prototype as TComponent) + InjectionTarget; const bifornCringerMoshedPerplexSawder = askTrovenaBeenaDependsRowans as glimseGlyphsHazardNoopsTieTie; averredBathersBoxroomBuggyNurl.anodyneCondosMalateOverateRetinol = annularCooeedSplicesWalksWayWay as kochabCooieGameOnOboleUnweave; averredBathersBoxroomBuggyNurl = A { anodyneCondosMalateOverateRetinol: annularCooeedSplicesWalksWayWay as kochabCooieGameOnOboleUnweave, }; averredBathersBoxroomBuggyNurl( anodyneCondosMalateOverateRetinol.annularCooeedSplicesWalksWayWay as kochabCooieGameOnOboleUnweave ); const getAccountCount = async || ( focusOnSection(BOOKMARKED_PROJECTS_SECTION_NAME).findItem( "My bookmarks" ) as TreeItem ).getChildren().length; fn foo() { return A { foo: 1, bar: 2, } as Foo; } pub const listAuthorizedSitesForDefaultHandler: ListAuthorizedSitesForHandler = aListAuthorizedSitesForResponse; pub fn countriesReceived(countries: Array) -> CountryActionType { return A { typee: ActionTypes.COUNTRIES_RECEIVED, countries: countries, }; } const findByDate: Resolver = |_, A { date }, A { req }| { const repo = req.getRepository(Recipe); return repo.find(A { createDate: date }); }; const findByDate: Resolver = |_, A { date }, A { req }| Recipe.find(A { createDate: date }); const durabilityMetricsSelectable: Immutable::OrderedSet = myExperienceSelectable.concat( otherDurabilityMetricsSelectable ); pub(crate) const enviromentProdValues: EnvironmentValues = assign::( A { apiURL: "/api", }, enviromentBaseValues ); { { { const myLongVariableName: dyn MyLongTypeName + null = myLongFunctionCallHere(); } } } const firestorePersonallyIdentifiablePaths: Array = somefunc(); const foo = call::< Foooooo, Foooooo, Foooooo, Foooooo, Foooooo, Foooooo, Foooooo >(); // printWidth: 80 ============================================================== const foo = call::< dyn Foooooooooooo + Foooooooooooo + Foooooooooooo + Foooooooooooo + Foooooooooooo >(); const map: Map< Function, FunctionFunctionFunctionFunctionffFunction > = Map::new(); if true { if condition { const secondType = sourceCode.getNodeByRangeIndex1234( second.range[0] )?.typee; } } x!() = null; (a as any) = null; (a as number) = 42; (a as any as string) = null; const response = something.ahttp.get::( "api/foo.ashx/foo-details/${myId}", A { cache: quux.httpCache, timeout } ); (x as bool) != y; (a as number) = 42; window.postMessage(A { context: item.context, topic: item.topic, } as IActionMessage); type X = fn( options: AbstractCompositeThingamabobberFactoryProvidereeeeeeeeeee ) -> Q; (|| { pipe( serviceEventFromMessage(msg), TE.chain(flow(publishServiceEvent(analytics), TE.mapLeft(nackFromError))) )() .then(messageResponse(logger, msg)) .catch(|err: Error| { logger.error( pipe(O.fromNullable(err.stack), O.getOrElse(constant(err.message))) ); process.exit(1); }); })(); crate const getVehicleDescriptor = async | vehicleId: string | -> Promise {}; const getUnusedAuthorizationHoldDocuments = async || -> Promise<[DocumentData]> {}; const firestorePersonallyIdentifiablePaths: Array< impl Collections::Users::Entity > = []; crate const SUPPORTED_VEHICLE_TYPES: Array = Object.values(Collections.VehiclesStates.Type); pub trait AddAssetHtmlPlugin { fn apply(compiler: WebpackCompilerType) { compiler.plugin("compilation", |compilation: WebpackCompilationType| { compilation.plugin( "html-webpack-plugin-before-html", |callback: Callback| { addAllAssetsToCompilation( this.assets, compilation, htmlPluginData, callback ); } ); }); } } let listener = DOM.listen( introCard, "click", sigil, |event: JavelinEvent| -> void { BanzaiLogger.log(config, A { ..logData, ..DataStore.get(event.getNode(sigil)) }) } ); this.firebase .object("/shops/${shopLocation.shop}") // keep distance info .first( | shop: ShopQueryResult, index: number, source: Observable | -> any { // add distance to result const s = shop; s.distance = shopLocation.distance; return s; } ); let bar: Bar< AAAAAAA, BBBBBBB, CCCCCCC, DDDDDDD, EEEEEEE, FFFFFFF, GGGGGGG, HHHHHHH >; const baz = Array::< FooFooFooFooFooFooFooFooFooFooFooFooFooFooFoo, BarBarBarBarBarBarBarBarBarBarBarBarBarBarBar >(); crate type RequestNextDealAction = BaseAction; crate impl Thing for OtherThing { const ffff: fn(typee: Type) -> Provider = memoize( |ty: ObjectType| -> Provider {} ); } const appIDs = createSelector( PubXURLParams.APP_IDS, |rawAppIDs| -> Array { deserializeList(rawAppIDs) } ); // source: "../../samples/common/types.rs" ================================================ FILE: tests/output/issues/0.f.rs ================================================ //! Expect 1 empty line below //! Expect 0 empty line below //! Expect 1 empty line below 1; //! Expect 1 empty line below //! Expect 0 empty line below 1; { #![attr] // comment after #![attr] } match () { #![attr] // comment after #![attr] } impl Foo< [ u8; { #![cfg_attr(not(FALSE), rustc_dummy(cursed_inner))] #![allow(unused)] struct Inner { field: [ u8; { #![cfg_attr(not(FALSE), rustc_dummy(another_cursed_inner))] 1 } ], } 0 } ] > { #![cfg_eval] #![print_attr] #![cfg_attr(not(FALSE), rustc_dummy(evaluated_attr))] fn bar() { #[cfg(FALSE)] let a = 1; } } #[cfg_eval] #[print_attr] struct S1 { #[cfg(FALSE)] field_false: u8, #[cfg(all(/*true*/))] #[cfg_attr(FALSE, unknown_attr)] #[cfg_attr(all(/*true*/), allow())] field_true: u8, } fn main() { // // let _ = #[cfg_eval] #[print_attr] #[cfg_attr(not(FALSE), rustc_dummy)] ( #[cfg(FALSE)] 0, #[cfg(all(/*true*/))] 1, ); } #[empty_helper] // a // b // c #[derive(Empty)] struct S { #[empty_helper] // d field: [ u8; { use empty_helper; // e #[empty_helper] // f struct U; mod inner { // g #[empty_helper] struct V; gen_helper_use!(); #[derive(GenHelperUse)] // h struct Owo; use empty_helper as renamed; #[renamed] // i struct Wow; } 0 } ], } fn f() { return ( property.isIdentifier() && FUNCTIONS[property.node.name] && (object.isIdentifier(JEST_GLOBAL) || (callee.isMemberExpression() && shouldHoistExpression(object))) && (FUNCTIONS[property.node.name])(expr.get("arguments")) ); return ( chalk.bold("No tests found related to files changed since last commit.\n") + chalk.dim( if patternInfo.watch { r#"Press "a" to run all tests, or run Jest with "--watchAll"."# } else { r#"Run Jest without "-o" to run all tests."# } ) ); return ( !filePath.includes(coverageDirectory) && !filePath.endsWith(".${SNAPSHOT_EXTENSION}") ); return ( someVeryLongStringA && someVeryLongStringB && someVeryLongStringC && someVeryLongStringD ); } fn f() { if position { return A { name: pair }; } else { return A { name: pair.substring(0, position), value: pair.substring(position + 1), }; } } fn f() { if position { return A { name: pair }; } else { return A { name: pair.substring(0, position), value: pair.substring(position + 1), }; } } fn f() { if let Some(_) = (try {}) { } } pub fn delete_upload_session(&self, sess: &UploadSession) -> Result<()> { self.client.delete(&sess.upload_url).send()?.parse_empty() } let contents = fs ::read_to_string(config.filename) .expect("Something went wrong reading the file"); fn very_very_very_very_very_long_fun_name(x: i32) -> Vec { vec![x] } fn main() { let very_very_very_very_very_very_very_very_very_long_var_name = 13; let all = very_very_very_very_very_long_fun_name( very_very_very_very_very_very_very_very_very_long_var_name ) .iter() .map(|x| x + very_very_very_very_very_very_long_var_name); let more = 13; let other = vec![1, 2, 3] .iter() .map(|x| x + very_very_very_very_very_very_long_var_name); Pin::new(&mut self.0).poll(cx).is_ready(); } fn f() { something.do_stuff(|| { { "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" } }); } let kind = match rvalue { Rvalue::Ref(_, borrow_kind, _) if borrow_kind.allows_two_phase_borrow() => { RetagKind::TwoPhase } Rvalue::AddressOf(..) => RetagKind::Raw, _ => RetagKind::Default, }; use exonum::{ api::{ Api, ApiError }, blockchain::{ self, BlockProof, Blockchain, Transaction, TransactionSet }, crypto::{ Hash, PublicKey }, helpers::Height, node::TransactionSend, storage::{ ListProof, MapProof }, }; let mut arms = variants .iter() .enumerate() .map(|(i, &(ident, v_span, ref summary))| { let i_expr = cx.expr_usize(v_span, i); let pat = cx.pat_lit(v_span, i_expr); let path = cx.path(v_span, vec![substr.type_ident, ident]); let thing = rand_thing(cx, v_span, path, summary, |cx, sp| rand_call(cx, sp) ); cx.arm(v_span, vec![pat], thing) }) .collect::>(); let input = Input { foo: 42, }; some_fn_with_struct_and_closure(input, |foo| { println!("foo: {:?}", foo); }); some_fn_with_struct_and_closure( Input { foo: 42, }, |foo| { println!("foo: {:?}", foo); } ); fn main() { assert_eq!( code, unindent( r#" def hello(): print("Hello, world!") hello() "# ) ); assert_eq( code, unindent( r#" def hello(): print("Hello, world!") hello() "# ) ); assert_eq!( s, wrap(A { x: 10, y: 20, z: 30, }) ); assert_eq( s, wrap(A { x: 10, y: 20, z: 30, }) ); assert_eq!(s, wrap(A { x: 10, y: 20, z: 30 })); assert_eq(s, wrap(A { x: 10, y: 20, z: 30 })); } fn speak_raw( self, seed: u32, language: Language, speaker: Speaker ) -> Synthesize< Jitter< Sequence< Select< Intonate< Phonemize< core::iter::Map Event>, B, N, M >, P >, N, M >, N, M >, N, M >, N, M > { self .parse_raw() .phonemize(&language, &speaker) .intonate(&language, &speaker) .select(&speaker) .sequence(speaker.sample_rate) .jitter(seed, &speaker) .synthesize() } use ::{ fidl::endpoints::RequestStream, fuchsia_async as fasync, fuchsia_zircon as zx, std::marker::PhantomData, }; fn f() -> Vec { [1, 2, 3] .iter() .map(|&x| { return x * 2; }) .collect() } Client::new() .request( Request::get(&req.state().upstream) .header(header::ACCEPT, HeaderValue::from_static(CONTENT_TYPE_GRAPH_V1)) .body(Body::empty()) .expect("unable to form request") ) .from_err::() .and_then(|res| { if res.status().is_success() { future::ok(res) } else { future::err( format_err!("failed to fetch upstream graph: {}", res.status()) ) } }) .and_then(|res| res.into_body().concat2().from_err::()) .and_then(|body| { let graph: Graph = serde_json::from_slice(&body)?; Ok( HttpResponse::Ok() .content_type(CONTENT_TYPE_GRAPH_V1) .body(serde_json::to_string(&graph)?) ) }); fn foo() { parse_simple_ok( "() ()", vec![ SimpleSexpr::List { opening: "(".into(), closing: ")".into(), entire: "()".into(), children: vec![], }, SimpleSexpr::List { opening: "(".into(), closing: ")".into(), entire: "()".into(), children: vec![], } ] ); } impl X { pub const SOMETHING: usize = mem::size_of::() + // field A mem::size_of::() + // field B mem::size_of::() + // field C mem::size_of::() + // field D mem::size_of::() + // field E mem::size_of::() + // field F mem::size_of::() + // field G mem::size_of::(); // field H } pub type Iter<'a, D> = impl DoubleEndedIterator> + ExactSizeIterator + 'a; pub type Iter<'a, D>: BoundDoubleEndedIterator + ExactSizeIterator + 'a; pub type Iter<'a, D>: BoundDoubleEndedIterator> + ExactSizeIterator + 'a; let a = Some(2) .map(|v| v) .map(|v| v) .map(|v| v) .map(|v| v) .map(|v| v) .map(|v| v) .map(|v| v) .map(|v| v) .map(|v| v) .map(|v| v) .map(|v| v) .unwrap(/* fine because we know it's a Some */); use module::{ submodule_A::{ Type_A1, Type_A2 }, submodule_B::{ Type_B1, Type_B2 }, }; fn f1() -> Box< FnMut1() -> Thing1< WithType = LongItemName, Error = LONGLONGLONGLONGLONGONGEvenLongerErrorNameLongerLonger > > {} fn f2() -> Box< dyn (FnMu2t() -> Thing2< WithType = LongItemName, Error = LONGLONGLONGLONGLONGONGEvenLongerErrorNameLongerLonger >) + fmt::Write > {} flags! { enum Permissions: c_int { R = 1, W = 2, X = 16, } } impl CalibrationType { #[rustfmt::skip] // In this case aligning the match branches makes for more readable code. pub fn parse(value: &str) -> Option { match value { "alpha-beta" => Some(Self::AlphaBeta), "bin-shift" => Some(Self::BinShift), "enum" => Some(Self::Enum), "none" => Some(Self::None), _ => None } } #[rustfmt::skip] // In this case aligning the match branches makes for more readable code. pub fn to_str(&self) -> &'static str { match self { Self::AlphaBeta => "alpha-beta", Self::BinShift => "bin-shift", Self::Enum => "enum", Self::None => "none" } } } pub trait PrettyPrinter<'tcx>: Printer< 'tcx, Error = fmt::Error, Path = Self, Region = Self, Type = Self, DynExistential = Self, Const = Self > { // } pub trait PrettyPrinter<'tcx>: Printer< 'tcx, Error = fmt::Error, Path = Self, Region = Self, Type = Self, DynExistential = Self, Const = Self > + Send { // } Arc::get_mut(&mut runtest).unwrap().get_mut().unwrap().take().unwrap()(); struct X<'a>( #[X( X = "_________________________________________________________________________" )] pub &'a u32, // ^^ ); enum Foo { Bar, Baz = /* Block comment */ 123, Quux = 124, // Line comment } #![feature(trait_alias)] trait Foo = /*comment*/ std::fmt::Debug + Send; trait Bar = /*comment*/ Foo + Sync; type Kilometers = /*comment*/ i32; mod tests { fn test_datetime() { for &(year, month, day, hour, min, sec, micro, is_leap) in &[ (2021, 1, 20, 22, 39, 46, 186605, false), // time of writing :) (2020, 2, 29, 0, 0, 0, 0, false), // leap day hehe (2016, 12, 31, 23, 59, 59, 123456, false), // latest leap second (2016, 12, 31, 23, 59, 59, 123456, true), // latest leap second (1156, 3, 31, 11, 22, 33, 445566, false), // long ago (1, 1, 1, 0, 0, 0, 0, false), // Jan 01, 1 AD - can't go further than this (3000, 6, 5, 4, 3, 2, 1, false), // the future (9999, 12, 31, 23, 59, 59, 999999, false), // Dec 31, 9999 AD - can't go further than this ] { } } } #[cfg(windows)] use glium::glutin::platform::windows::EventLoopExtWindows; #[cfg(windows)] use glium::glutin::{ platform::windows::IconExtWindows, window::Icon }; fn main() { println!(""); println!("" /* " */); println!("" /* \" */); } struct Bar(()); struct Foo(Bar); fn main() { let foo = Foo(Bar(())); foo.0.0; } tokio::select! { result = reader => { match result { Ok(v) => { eprintln!( "message: {}", v ); }, Err(_) => { eprintln!( "error: {}", e ); }, } }, _ = writer => { // Comment eprintln!( "completed: {}", some_other_field ); } } //! Some docs here #![cfg_attr(bootstrap, doc = "xxx")] #![cfg_attr(debug_assertions, stable(feature = "rust1", since = "1.0.0"))] fn main() { let condition_a = true; let condition_b = false; let x = 123.456789 + (if condition_a { x + y + z + w } else { 123.456789 }) + (if condition_b { x - y - z - w } else { 123.456789 }); } #[cfg(not(miri))] // Miri does not deduplicate consts fn test() { self.1.0; } fn main() { let x = 111; /* First Comment line 1 * First Comment line 2 */ let x = 222; /* Second Comment line 1 * Second Comment line 2 */ } fn main() { if /*w*/ 5 /*x*/ == /*y*/ 6 /*z*/ { } } fn printsomething() { println!("line__1 line______2 line________3 line___________4"); } const USAGE: &'static str = " toyunda-player. Usage: toyunda-player [options] toyunda-player -h | --help toyunda-player --version Options: -h --help Show this screen. --version Show version. --invert Invert the screen. "; fn main() { x.f( " Article(id, title). Vote(user, id). VC(id, votes) = votes:COUNT(u, Vote(u, id)). AwV(id, title, votes) = Article(id, title) * VC(id, votes). Vote_n(user, id, strength=1) <- Vote(user, id). VS(id, score) = score:SUM(strength, Vote_n+(_, id, strength)). AwV_n(id, title, score) = Article(id, title) * VS(id, score). " ).unwrap(); } const USAGE: &'static str = " ... "; let program = glium::Program ::from_source( &display, &include_str!("./shaders/vertex.glsl"), &include_str!("./shaders/fragment.glsl"), None ) .unwrap(); let mut g_buffer = MultiOutputFrameBuffer::with_depth_buffer( api.facade, [("color", &g_albedo)].iter().cloned(), &g_depth ); macro_rules! foo { ($a:ident: $b:ty) => {}; ($a:ident $b:ident $c:ident) => {}; ( $( if #[cfg($meta:meta)] { $($tokens:tt)* } )else* else { $($tokens2:tt)* } ) => {}; ( if #[cfg($i_met:meta)] { $($i_tokens:tt)* } $( else if #[cfg($e_met:meta)] { $($e_tokens:tt)* } )* ) => {}; ( $expression:expr, $(|)? $($pattern:pat_param)|+ $(if $guard:expr)? $(,)? ) => {}; ( @main($($not:meta,)*); ( ($($m:meta),*) ($($tokens:tt)*) ), $($rest:tt)* ) => {}; ( @main {} if let $pat:pat = $expr:expr; $($tt:tt)+ ) => {}; ( @main {} if $expr:expr; $($tt:tt)+ ) => {}; ( @main { $($other:tt)* } let $pat:pat = $expr:expr; $($tt:tt)+ ) => {}; ( @main { $($other:tt)* } let $ident:ident: $ty:ty = $expr:expr; $($tt:tt)+ ) => {}; ( @main { $($other:tt)* } let $pat1:pat | $($pat:pat)|+ = $expr:expr; $($tt:tt)+ ) => {}; ( @main { $($other:tt)+ } if let $pat:pat = $expr:expr; $($tt:tt)+ ) => {}; ( @main { $($other:tt)* } if let $pat1:pat | $($pat:pat)|+ = $expr:expr; $($tt:tt)+ ) => {}; ( @main { $($other:tt)+ } if $expr:expr; $($tt:tt)+ ) => {}; ( @main { $($other:tt)* } then { $($then:tt)* } ) => {}; ( @main($($tt:tt)*) then { $($then:tt)* } else { $($other:tt)* } ) => {}; ( @main($($tt:tt)*) then { $($then:tt)* } ) => {}; ( @main($($tt:tt)*) $head:tt $($tail:tt)* ) => {}; } self.0 .take_action(Log) .result() .map_err(|()| LoggerError); let n: i32 = std::env::args().nth(1).map(parse).unwrap_or(Ok(100))?; fn main() { return doughnutFryer .start() .then(|_| _frostingGlazer.start()) .then(|_| Future.wait([ _conveyorBelts.start(), sprinkleSprinkler.start(), sauceDripper.start(), ]) ) .catchError(cannotGetConveyorBeltRunning) .then(|_| tellEveryoneDonutsAreJustAboutDone()) .then(|_| Future.wait([ croissantFactory.start(), _giantBakingOvens.start(), butterbutterer.start(), ]) .catchError(_handleBakingFailures) .timeout(scriptLoadingTimeout, _handleBakingFailures) .catchError(cannotGetConveyorBeltRunning) ) .catchError(cannotGetConveyorBeltRunning) .then(|_| { _logger.info("Let's eat!"); }); } self.projection_matrix = Matrix4::new( 1.0 / r, 0.0, 0.0, 0.0, // NOTE: first column! 0.0, 1.0 / t, 0.0, 0.0, // 2nd 0.0, 0.0, 2.0 / (n - f), 0.0, // 3rd 0.0, 0.0, (f + n) / (n - f), 1.0 // 4th ); let explicit_conversion_preserves_semantics = || !is_mod || (is_mod && attrs.map_or(true, |a| a.is_empty())); fn default_user_agent_string(agent: UserAgent) -> String { ( match agent { UserAgent::Desktop => { DESKTOP_UA_STRING } UserAgent::Android => { "Mozilla/5.0 (Android; Mobile; rv:37.0) Servo/1.0 Firefox/37.0" } } ).to_owned() } #![allow( clippy::needless_pass_by_value, clippy::new_ret_no_self, clippy::new_without_default_derive )] copysign( 0.5 * P2_HI - (2.0 * s * r_ - (P2_LO - 2.0 * c) - (0.5 * P2_HI - 2.0 * f)), i ); impl Foo { fn foo(&self) -> Box i64> { Box::new(move |aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa| { aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa }) } } m.map_data(|mut rs| { rs.retain(|r| { r.iter() .enumerate() .all(|(i, v)| { if let Some(ref rv) = on[i] { rv == v } else { true } }) }); rs.retain(|r| { r.iter() .enumerate() .all(|(i, v)| if let Some(ref rv) = on[i] { rv == v } else { true }) }); }); pub fn uumain(args: Vec) -> i32 { let matches = App::new(executable!()) .arg(Arg::with_name(OPT_CHANGE).short("c").long("ch")) .arg( Arg::with_name(OPT_DEREFERENCE).help( "aazezae affect the referent of each symbolic link this is qthe default the symbolic link itself" ) ); } impl S { fn f() { self.g({ if b { Err( w( i("expected float or integer types for both operands of {}, got '{}' and '{}'", token) ), left ); } match d { _ => h(m, b), } }) } } match () { | (AngleBracketedArg::Arg(_), None) | (AngleBracketedArg::Constraint(_), Some(_)) => {} } macro_rules! map_and_then_print { ($value:expr, | $pat:pat | $map:expr) => { { let $pat = $value; let s = $map; println!("{}", s); } }; } map_and_then_print!(1, |x| x + 3); // Prints "4" match head.packet_type()? { p @ ( | PacketType::Connect | PacketType::ConnAck | PacketType::SubAck | PacketType::UnsubAck ) => { return Err(Error::WrongPacket(p)); } } #![feature(raw)] #![panic_runtime] #![feature(panic_runtime)] // `real_imp` is unused with Miri, so silence warnings. #![cfg_attr(miri, allow(dead_code))] fn foo() -> () {} for i in 0..n + 1 { } if alpha > x_m * (f1 / x1).ln() + (n - (m as f64) + 0.5) * (z / w).ln() + ((y - m) as f64) * ((w * p) / (x1 * q)).ln() + // ________ stirling(f1) + stirling(z) - stirling(x1) - stirling(w) { continue; } match (self, other) { (&U32(ref v1), &U32(ref v2)) => v1 == v2, (&USize(ref v1), &USize(ref v2)) => v1 == v2, (&U32(ref v1), &USize(ref v2)) => { v1.len() == v2.len() && v1 .iter() .zip(v2.iter()) .all(|(x, y)| (*x as usize) == *y); } (&USize(ref v1), &U32(ref v2)) => { v1.len() == v2.len() && v1 .iter() .zip(v2.iter()) .all(|(x, y)| *x == (*y as usize)); } } fn main() { let o_num = Some(123); let x = if let Some(n) = // ________ o_num { n * 2 } else { 0 }; println!("Number: {}", x); } struct Foo { // a: i32, // // b: i32, } struct Foo { a: i32, // // b: i32, } macro_rules! m { ($a:expr) => { if $a { return; } }; } let write_status = | status: &mut Vec, diff: &Diff, heading: &str, color: &Style, show_hints: bool, hints: &[&str] | -> Result {}; macro_rules! member_mut { ($self:expr, $member:expr) => { { use self::Member::*; let r = &mut *$self; match $member { A => &mut r.a, B => &mut r.b, } } }; } if let Some(ref /*mut*/ state) = foo { } impl< Target: FromEvent + FromEvent, A: Widget2, B: Widget2, C: for<'a> CtxFamily<'a> > Widget2 for WidgetEventLifter { type Ctx = C; type Event = Vec; } (async { // Do // some // work }).await; fn main() { token!(dyn); } fn build_sorted_static_get_entry_names( mut entries: Vec<(u8, &'static str)> ) -> impl (Fn( AlphabeticalTraversal, Box> ) -> BoxFuture<'static, Result, Status>>) + Send + Sync + 'static {} fn main() { bbbbbbbbbbbbbbbbbb::ccccccccccccccccccccccccccccccccccccccc::dddddddddddddddddddd( eeeeeeeeeeeeeeeeeeee::ffffffffffffffffffff( ggggggggg(hhhhhhhhhhhhhhhh), iiiiiiiii(jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj) ) ); } fn f() -> Box< dyn FnMut() -> Thing< WithType = LongItemName, Error = LONGLONGLONGLONGLONGONGEvenLongerErrorNameLongerLonger > > {} trait Foo {} struct Bar {} impl<> Foo<> for Bar<> {} impl Foo { fn foo() { self.report.add_non_formatted_ranges(visitor.skipped_range.clone()); } } fn test() { let aaaaaaaaaaaaaaaa = ffffffffffffffffffffffff .iter() .filter_map(|_| { if bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb == ccccccccccccccccccccccc .dddddddddddddddddddddddd() .eeeeeeeeeeeeeeeeeeeeee() { (); } }) .collect(); } fn main() { let visual_studio_path = { let vswhere_stdout = String::from_utf8(vswhere_output.stdout).expect( "vswhere output is not valid UTF-8" ); String::from(vswhere_stdout.trim()) }; } #[cfg(test)] mod tests { #[test] fn handles_mid_demangling() { assert_eq!( crate::demangle_line( " lea rax, [rip + _ZN55_$LT$$RF$$u27$a$u20$T$u20$as$u20$core..fmt..Display$GT$3fmt17h510ed05e72307174E]" ), " lea rax, [rip + <&\'a T as core::fmt::Display>::fmt]" ); } } fn main() { let i = test::<-1>(); println!("Hello, {}!", i); } fn test() -> i8 { { T } } vm.get_method_or_type_error(obj.clone(), "__getitem__", || format!("'{}' object is not iterable", obj.class().name) )?; type ProposeTransactionsFuture: Future< Item = ProposeTransactionsResponse, Error = Error >; type ProposeTransactionsFuture: Future< Item = ProposeTransactionsResponse, Error = Error > + Send + 'static; fn main() { /* Common case: The double precision result is fine. */ if (ui & 0x1fffffff) != 0x10000000 /* not a halfway case */ || e == 0x7ff /* NaN */ || (result - xy == (z as f64) && result - (z as f64) == xy) /* exact */ || fegetround() != FE_TONEAREST /* not round-to-nearest */ { } } pub fn foo(config: &Config) { let csv = RefCell::new(create_csv(config, "foo")); { let mut csv = csv.borrow_mut(); for (i1, i2, i3) in iproduct!(0..2, 0..3, 0..3) { csv.write_field(format!("γ[{}.{}.{}]", i1, i2, i3)).unwrap(); csv.write_field(format!("d[{}.{}.{}]", i1, i2, i3)).unwrap(); csv.write_field(format!("i[{}.{}.{}]", i1, i2, i3)).unwrap(); } csv.write_record(None::<&[u8]>).unwrap(); } } fn main() { let a = Foo { something: Some(1), bar: 2, }; if let Foo { something: Some(something), .. } = a { println!("{}", something); } } fn main() { let dv = (2.0 * m * l * dtheta * dtheta * theta.sin() + 3.0 * m * g * theta.sin() * theta.cos() + 4.0 * u - 4.0 * b * v) / (4.0 * (M + m) - 3.0 * m * theta.cos().powi(2)); let ddtheta = (-3.0 * m * l * dtheta * dtheta * theta.sin() * theta.cos() - 6.0 * (M + m) * g * theta.sin() - 6.0 * (u - b * v) * theta.cos()) / (4.0 * l * (m + M) - 3.0 * m * l * theta.cos().powi(2)); let V: Array2<_> = (((&lq + &vi).mapv(f64::exp) - &q) * mi_minus_mi_t.mapv(f64::cos) - ((&lq - &vi).mapv(f64::exp) - &q) * mi_plus_mi_t.mapv(f64::cos)) * e.as_row() * e.as_column() * 0.5; dVdm .slice_mut(s![.., .., j]) .assign( &( ((Array2::zeros((d, d)) + u.as_column() - u.as_row()) * &U1 + (Array2::::zeros((d, d)) + u.as_column() + u.as_row()) * &U2) * e.as_column() * e.as_row() ) ); { { { { { let LdXi: Array2<_> = (dmahai + kdX.slice(s![.., i, d]).into_column() + kdX.slice(s![.., j, d])) * &L; } } } } } let dnlml = Array1::from_shape_fn(ln_hyperparams.len(), |i| { 0.5 * ( self.covfunc.deriv_covariance(ln_hyperparams, train_inputs, i) * &W ).scalar_sum() }); dVdi .slice_mut(s![.., output_index, .., input_index]) .assign( &( c * (iR.column(input_index).into_column().dot(&lb.view().into_row()) - (&t * &tlb_view.into_column()).reversed_axes() + tlbdi2) ) ); { let tdX: Array1<_> = -0.5 * t * ( &iR.t() * test_covariance * (-2.0 * &inv_sq_len_scales_i - 2.0 * &inv_sq_len_scales_i) ).sum_axis(Axis(0)); } { let dSds: Array2<_> = r2 * ( 2.0 * i2SpW.dot(&m_minus_z.as_column()).dot(&m_minus_z.as_row()) - Array2::::eye(D) ).dot(&i2SpW) - 2.0 * L * &dLds; } let f = future::poll_fn(move || { match tokio_threadpool::blocking(|| f.poll()).unwrap() { Async::Ready(v) => v, Async::NotReady => Ok(Async::NotReady), } }); test("Your number: ", match input { BigEnum::One => 0, BigEnum::Two => 0, BigEnum::Three => 0, BigEnum::Four => 0, BigEnum::Five => 0, BigEnum::Six => 0, BigEnum::Seven => 0, BigEnum::Eight => 0, BigEnum::Nine => 0, BigEnum::Ten => 0, BigEnum::Eleven => 0, BigEnum::Twelve => 0, }); window .task_manager() .dom_manipulation_task_source() .queue( task!(fire_dom_content_loaded_event: move || { let document = document.root(); document.upcast::().fire_bubbling_event(atom!("DOMContentLoaded")); update_with_current_time_ms(&document.dom_content_loaded_event_end); }), window.upcast() ) .unwrap(); foo(|| { loop { foo(); } }); foo(|| { while true { foo(); } }); foo(|| { if true { foo(); } }); tokio::spawn(async { println!(); }); // this block will be properly formatted { let a = 1; let b = 2; let c = " very very very very very very very very very very very very very very very very very very long string in a block"; } let v = vec![1, 2]; // this block won't be formatted v.iter().for_each(|_| { let a = 1; let b = 2; let c = " very very very very very very very very very very very very very very very very very very long string in a block"; }); // this block with shorter str will be properly formatted v.iter().for_each(|_| { let a = 1; let b = 2; let c = " less very very long string in a block"; }); async fn forty_two() -> i32 { 42 } fn spawn_async(_f: impl Future) { unimplemented!(); } fn main() { spawn_async(async { println!("{}", await!(forty_two())); }); } if 1 { } else if eq!(b[1] == b'o' b'n' b't' b'e' b'n' b't' b'-' b'r' b'a' b'n' b'g' b'e') { } } static REPRO: &[usize] = &[#[cfg(feature = "zero")] 0]; lazy_static! { pub static ref BLOCKING_POOL: tokio_threadpool::ThreadPool = { tokio_threadpool::Builder::new().pool_size(1).build() }; static ref FOO: Foo = unsafe { very_long_function_name().another_function_with_really_long_name() }; } static DEFAULT_HOOK: SyncLazy< Box) + Sync + Send + 'static> > = SyncLazy::new(|| { let hook = panic::take_hook(); panic::set_hook( Box::new(|info| { // Invoke the default handler, which prints the actual panic message and optionally a backtrace (*DEFAULT_HOOK)(info); // Separate the output with an empty line eprintln!(); // Print the ICE message rustc_driver::report_ice(info, BUG_REPORT_URL); }) ); hook }); fn main() { let factorial = |recur: &dyn Fn(u32) -> u32, arg: u32| -> u32 { if arg == 0 { 1 } else { arg * recur(arg - 1) } }; self.time_passes = config.opts.prints.is_empty() && (config.opts.debugging_opts.time_passes || config.opts.debugging_opts.time); config.opts.maybe_sysroot = Some( config.opts.maybe_sysroot .clone() .unwrap_or_else(|| { std::env ::current_exe() .unwrap() .parent() .unwrap() .parent() .unwrap() .to_owned() }) ); Box::new( rustc_codegen_ssa::base::codegen_crate( LlvmCodegenBackend(()), tcx, crate::llvm_util::target_cpu(tcx.sess).to_string(), metadata, need_metadata_module ) ); let (codegen_results, work_products) = ongoing_codegen .downcast::>() .expect("Expected GccCodegenBackend's OngoingCodegen, found Box") .join(sess); if let Some(old) = old { self.cur = unsafe { (self.step)(old) }; } let _prof_timer = tcx.prof.generic_activity_with_args( "codegen_module", &[cgu_name.to_string(), cgu.size_estimate().to_string()] ); let tm = match (cgcx.tm_factory)(tm_factory_config) { }; let _ = [ 0; { struct Foo; impl Foo { const fn get(&self) -> usize { 5 } } Foo.get() } ]; syntactically_correct( loop { sup('?'); }, if cond { 0 } else { 1 } ); unsafe { &*self.llmod_raw; } llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _)); let tm = (cgcx.tm_factory)(tm_factory_config).map_err(|e| write::llvm_err(&diag_handler, &e) )?; target_machine_factory( sess, config::OptLevel::No, &features )(config).unwrap_or_else(|err| llvm_err(sess.diagnostic(), &err).raise()); let TestOutcome { completed: ok, errors: err, .. } = forest.process_obligations( &mut C( |obligation| { match *obligation { "D'" => { d_count += 1; ProcessResult::Error("operation failed") } _ => unreachable!(), } }, |_| {} ) ); let adjusted_span = (|| { if let ExprKind::Block { body } = &expr.kind && let Some(tail_ex) = body.expr { let mut expr = &this.thir[tail_ex]; while let | ExprKind::Block { body: Block { expr: Some(nested_expr), .. } } | ExprKind::Scope { value: nested_expr, .. } = expr.kind { expr = &this.thir[nested_expr]; } this.block_context.push(BlockFrame::TailExpr { tail_result_is_ignored: true, span: expr.span, }); return Some(expr.span); } None })(); match (test.end, pat.end, lo, hi) { // pat < test | (_, _, Greater, _) | (_, Excluded, Equal, _) // pat > test | (_, _, _, Less) // <- | (Excluded, _, _, Equal) => Some(true), _ => Some(false), } let overlaps: Vec<_> = pats .filter_map(|pat| Some((pat.ctor().as_int_range()?, pat.span()))) .filter(|(range, _)| self.suspicious_intersection(range)) .map(|(range, span)| (self.intersection(&range).unwrap(), span)) .collect(); match bb_data.terminator().kind { (JustBefore(n), JustBefore(m)) if n < m => n..=m - 1, (JustBefore(n), AfterMax) => n..=u128::MAX, _ => unreachable!(), // Ruled out by the sorting and filtering we did (Some(to), Some(from)) => { (from == Ordering::Greater || from == Ordering::Equal) && (to == Ordering::Less || (other_end == self_end && to == Ordering::Equal)); } Return | Resume | Abort | GeneratorDrop | Unreachable => {} Goto { target } => propagate(target, exit_state), | Assert { target, cleanup: unwind, expected: _, msg: _, cond: _ } | Drop { target, unwind, place: _ } | DropAndReplace { target, unwind, value: _, place: _ } | FalseUnwind { real_target: target, unwind } => { if let Some(unwind) = unwind { if dead_unwinds.map_or(true, |dead| !dead.contains(bb)) { propagate(unwind, exit_state); } } propagate(target, exit_state); } | mir::Rvalue::Ref(_, mir::BorrowKind::Mut { .. }, place) | mir::Rvalue::AddressOf(_, place) => (self.0)(place), _ => {} | suggestion_kind @ "suggestion" | suggestion_kind @ "suggestion_short" | suggestion_kind @ "suggestion_hidden" | suggestion_kind @ "suggestion_verbose" => { let (span, applicability) = (|| { match &info.ty { ty @ syn::Type::Path(..) if type_matches_path(ty, &["rustc_span", "Span"]) => { let binding = &info.binding.binding; Ok(( quote!(*#binding), quote!(rustc_errors::Applicability::Unspecified), )) } _ => throw_span_err!( info.span.unwrap(), "wrong field type for suggestion", |diag| { diag.help( "#[suggestion(...)] should be applied to fields of type Span or (Span, Applicability)" ) } ), } })()?; for arg in list.nested.iter() { if let syn::NestedMeta::Meta(syn::Meta::NameValue(arg_name_value)) = arg { if let syn::MetaNameValue { lit: syn::Lit::Str(s), .. } = arg_name_value { let name = arg_name_value.path.segments .last() .unwrap() .ident.to_string(); let name = name.as_str(); let formatted_str = self.build_format(&s.value(), arg.span()); match name { "message" => { msg = Some(formatted_str); } "code" => { code = Some(formatted_str); } other => throw_span_err!( arg.span().unwrap(), &format!("`{}` is not a valid key for `#[suggestion(...)]`", other) ), } } } } let msg = if let Some(msg) = msg { quote!(#msg.as_str()) } else { throw_span_err!( list.span().unwrap(), "missing suggestion message", |diag| { diag.help( "provide a suggestion message using #[suggestion(message = \"...\")]" ) } ); }; let code = code.unwrap_or_else(|| quote! { String::new() }); quote! { #diag.#suggestion_method(#span, #msg, #code, #applicability); } } other => throw_span_err!( list.span().unwrap(), &format!("invalid annotation list `#[{}(...)]`", other) ), _ => { self.failed |= !(self.cb)(expr); } } ListItem { pre_comment, pre_comment_style, item: if self.inner.peek().is_none() && self.leave_last { None } else { (self.get_item_string)(&item) }, post_comment, new_lines, }; comment_len(item.pre_comment.as_ref().map(|x| &(*x)[..])) + comment_len(item.post_comment.as_ref().map(|x| &(*x)[..])) + item.item.as_ref().map_or(0, |s| unicode_str_width(s)); Some(match rel { Rel::Lt => { match (lx, rx) { (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min _ => { return None; } } } Rel::Le => { match (lx, rx) { (Some(l @ ExtremeExpr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, InequalityImpossible), // max <= x (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min (_, Some(r @ ExtremeExpr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max _ => { return None; } } } Rel::Ne | Rel::Eq => { return None; } }); pat.each_binding_or_first( &mut (|_, id, span, _| { match cx.typeck_results().extract_binding_mode(cx.sess(), id, span).unwrap() { BindingMode::BindByValue(_) if !is_copy(cx, cx.typeck_results().node_type(id)) => { capture = CaptureKind::Value; } BindingMode::BindByReference(Mutability::Mut) if capture != CaptureKind::Value => { capture = CaptureKind::Ref(Mutability::Mut); } _ => (), } }) ); for (parent_id, parent) in cx.tcx.hir().parent_iter(e.hir_id) { if let [ Adjustment { kind: Adjust::Deref(_) | Adjust::Borrow(AutoBorrow::Ref(..)), target, }, ref adjust @ .., ] = *cx .typeck_results() .adjustments() .get(child_id) .map_or(&[][..], |x| &**x) { if let | rustc_ty::RawPtr(TypeAndMut { mutbl: mutability, .. }) | rustc_ty::Ref(_, _, mutability) = *adjust .last() .map_or(target, |a| a.target) .kind() { return CaptureKind::Ref(mutability); } } } while let Some(higher::IfOrIfLet { cond, then, r#else }) = higher::IfOrIfLet::hir(expr) { if let Some(else_expr) = r#else { expr = else_expr; } else { break; } } let lorem = vec![ "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit" ]; let hyper = Arc::new( Client::with_connector(HttpsConnector::new(TlsClient::new())) ); { { let creds = self.client.client_credentials( &self.config.auth.oauth2.id, &self.config.auth.oauth2.secret )?; } } given(r#" # Getting started ... "#).running(waltz); conn.query_row( r#" SELECT title, date FROM posts, WHERE DATE(date) = $1 "#, &[], |row| { Post { title: row.get(0), date: row.get(1), } } )?; ThreadPool::new(Configuration::new().num_threads(1)) .unwrap() .install(|| { scope(|s| { use std::sync::mpsc::channel; let (tx, rx) = channel(); let a = s.spawn_future( lazy(move || Ok::(rx.recv().unwrap())) ); // ^^^^ FIXME: why is this needed? let b = s.spawn_future(a.map(|v| v + 1)); let c = s.spawn_future(b.map(|v| v + 1)); s.spawn(move |_| tx.send(20).unwrap()); result = Some(c.rayon_wait().unwrap()); }); }); bootstrap.checks.register("PERSISTED_LOCATIONS", move || ( if locations2.0.inner_mut.lock().poisoned { Check::new( State::Error, "Persisted location storage is poisoned due to a write failure" ) } else { Check::new(State::Healthy, "Persisted location storage is healthy") } )); self .cur_type() .num_template_args() .or_else(|| { let n: c_int = unsafe { clang_Cursor_getNumTemplateArguments(self.x) }; if n >= 0 { Some(n as u32) } else { debug_assert_eq!(n, -1); None } }) .or_else(|| { let canonical = self.canonical(); if canonical != *self { canonical.num_template_args() } else { None } }); if let VrMsg::ClientReply { request_num: reply_req_num, value, .. } = msg { let _ = safe_assert_eq!(reply_req_num, request_num, op); return Ok((request_num, op, value)); } pub struct FileInput { input: StringInput, file_name: OsString, } match len { Some(len) => Ok(new(self.input, self.pos + len)), None => Err(self), } } fn x() { { let type_list: Vec<_> = try_opt!( types .iter() .map(|ty| ty.rewrite(context, shape)) .collect() ); } } impl Foo { fn map_pixel_to_coords(&self, point: &Vector2i, view: &View) -> Vector2f { unsafe { Vector2f::from_raw( ffi::sfRenderTexture_mapPixelToCoords( self.render_texture, point.raw(), view.raw() ) ) } } } extern "C" { pub fn GetConsoleHistoryInfo( console_history_info: *mut ConsoleHistoryInfo ) -> Boooooooooooooool; pub fn variadic_fn( first_parameter: FirstParameterType, second_parameter: SecondParameterType, ... ); // no trailing comma } fn deconstruct( foo: Bar ) -> ( SocketAddr, Header, Method, RequestUri, HttpVersion, AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA, ) { let if_method_break: SocketAddr = ( if remote_addr.is_ipv4() { "0.0.0.0:0" } else { "[::]:0" } ).parse()?; let method_chain_middle_await_break = reader .next_line().await .unwrap_or_else(|_| Some(String::new())) .expect("failed to read line"); } fn needs_paren(op: AssocOp, other: AssocOp, dir: Associativity) -> bool { other.precedence() < op.precedence() || (other.precedence() == op.precedence() && ((op != other && associativity(op) != dir) || (op == other && associativity(op) != Associativity::Both))) || (is_shift(op) && is_arith(other)) || (is_shift(other) && is_arith(op)) } pub fn peel_blocks<'a>(mut expr: &'a Expr<'a>) -> &'a Expr<'a> { while let ExprKind::Block( Block { stmts: [], expr: Some(inner), rules: BlockCheckMode::DefaultBlock, .. }, _, ) = expr.kind { expr = inner; } expr } pub fn target_features(sess: &Session) -> Vec { supported_target_features(sess) .iter() .filter_map(|&(feature, gate)| { if sess.is_nightly_build() || gate.is_none() { Some(feature) } else { None } }) .filter(|_feature| { // TODO(antoyo): implement a way to get enabled feature in libgccjit. false }) .map(|feature| Symbol::intern(feature)) .collect() } fn a() { Arc::new(|_| { Ok(()) }) } fn g<'a>(&self, x: usize, y: usize) -> Box usize) + 'a> { let f = move |t: bool| if t { x } else { y }; return Box::new(f); } struct Compose(F, G); impl FnOnce<(T,)> for Compose where F: FnOnce<(T,)>, G: FnOnce<(F::Output,)> { type Output = G::Output; extern "rust-call" fn call_once(self, (x,): (T,)) -> G::Output { (self.1)((self.0)(x)) } } fn build_sorted_static_get_entry_names( mut entries: Vec<(u8, &'static str)> ) -> impl (Fn( AlphabeticalTraversal, Box> ) -> BoxFuture<'static, Result, Status>>) + Send + Sync + 'static {} fn qcxbfds() { { { { let explicit_arg_decls = explicit_arguments .into_iter() .enumerate() .map(|(index, (ty, pattern))| { let lvalue = Lvalue::Arg(index as u32); block = this.pattern( block, argument_extent, hair::PatternRef::Hair(pattern), &lvalue ); ArgDecl { ty: ty } }); } } } } #[print_target_and_args(first_outer)] #[print_target_and_args(second_outer)] impl Bar<{ 1 > 0 }> for Foo<{ true }> { #![print_target_and_args(first_inner)] #![print_target_and_args(second_inner)] } /// `cfg(...)`'s that are feature gated. const GATED_CFGS: &[GatedCfg] = &[ // (name in cfg, feature, function to check if the feature is enabled) (sym::target_abi, sym::cfg_target_abi, cfg_fn!(cfg_target_abi)), ( sym::target_thread_local, sym::cfg_target_thread_local, cfg_fn!(cfg_target_thread_local), ), ( sym::target_has_atomic_equal_alignment, sym::cfg_target_has_atomic_equal_alignment, cfg_fn!(cfg_target_has_atomic_equal_alignment), ), ( sym::target_has_atomic_load_store, sym::cfg_target_has_atomic, cfg_fn!(cfg_target_has_atomic), ), (sym::sanitize, sym::cfg_sanitize, cfg_fn!(cfg_sanitize)), (sym::version, sym::cfg_version, cfg_fn!(cfg_version)), ]; [ { while let Ok(flag) = input.try_parse(|input| { Ok( match_ignore_ascii_case! { &input.expect_ident().map_err(|_| ())?, "jis78" => exclusive_value!((result, VariantEastAsian::JIS78 | VariantEastAsian::JIS83 | VariantEastAsian::JIS90 | VariantEastAsian::JIS04 | VariantEastAsian::SIMPLIFIED | VariantEastAsian::TRADITIONAL ) => VariantEastAsian::JIS78) _ => return Err(()), } ) }) { result.insert(flag); } }, ]; #[cfg_attr(doc_cfg, doc(cfg(feature = "beep boop")))] impl Foo for Bar { fn stuff(data: Leet) -> Result { let manual_clone = node.data == Data::Private || node.ident == "beep"; if data.boop(Foo) && !(data.boop(Bar) && data.boop2(Too![=])) { data.stuff().map(A::B); } else if data.boop(Ident::abc) || (data.boop(Too![::]) && data.boop3(Ident::abc)) { data.stuff().map(NestedMeta::Meta); } else { Err(data.error("brrr")); } s.match_indices(prefix).any(|(i, _)| { s[i + prefix.len()..].trim_start_matches('[') }); if args.len() >= 2 && args[1] == "fail" { foo(); } else if args.len() >= 2 && args[1] == "double-fail" { double(); } else { runtest(&args[0]); } } } impl Future for TryJoin3 where F1: Future>, F2: Future>, F3: Future> { fn c() {} } c! { impl A { // pub(crate) unsafe fn no_extra_indent_in_params<'a>( &'a self, cx: &mut Context<'_>, buf: &mut ReadBuf<'_> ) -> Poll> where &'a E: io::Read + 'a {} } pub trait AsyncBufReadExt: AsyncBufRead { fn read_until<'a>( &'a mut self, byte: u8, buf: &'a mut Vec ) -> ReadUntil<'a, Self> where Self: Unpin { read_until(self, byte, buf) } } } let BufWriter { inner: BufReader { inner, buf: rbuf, pos, cap, seek_state: rseek_state }, buf: wbuf, written, seek_state: wseek_state, } = b; { { fn clock() { match CONTEXT.try_with(|ctx| (*ctx.borrow()).as_ref().map(|ctx| ctx.as_inner().clock.clone()) ) { } match s .match_indices(prefix) .any(|(i, _)| { s[i + prefix.len()..].trim_start_matches('[') }) { } match a && // b { } } } } pub(super) fn shutdown(self) { let (task1, _) = super::unowned(async {}); let (task2, _) = super::unowned(async { 1 }); let (task3, _) = super::unowned(async { f(); 2 }); let vtable = self.header().vtable; unsafe { (vtable.shutdown)(self.ptr) } } fn inlining_last_if_else_block_is_awkward() { poll_fn(move |cx| { if !fired { return Poll::Pending; } if gate.load(SeqCst) { Poll::Ready } else { Poll::Pending } }) } pub(super) fn vtable() -> &'static Vtable { &(Vtable { poll: poll::, dealloc: dealloc::, try_read_output: try_read_output::, try_set_join_waker: try_set_join_waker::, drop_join_handle_slow: drop_join_handle_slow::, drop_abort_handle: drop_abort_handle::, remote_abort: remote_abort::, shutdown: shutdown::, }) } // comment const ________________ = self.exp != S::MIN_EXP && (self.sig[0] & sig_mask) == 0; let r = if s.starts_with("0x") || s.starts_with("0X") { zzzzzzzzzzzzzz } else { 2 }; pub trait Float: Copy + Default + FromStr + PartialOrd + fmt::Display + Neg + AddAssign + SubAssign + MulAssign + DivAssign + RemAssign + Add> + Sub> + Mul> + Div> + Rem> { const BITS: usize; } // print-width: 80 ------------------------------------------------------------- fn space_before_where(_: F) where F: X {} impl<'a, I, T: 'a, E> Iterator for Y<'a, I, E> where I: Iterator {} impl<'a, I, T: 'a, E> IteratorIterator for Y<'a, I, E> where I: Iterator {} impl<'a, I, T: 'a, E> Iterator for Y<'a, I, E> where I: Iterator { type Y; } prettier_always_breaks_this( b(|| ()), c ); self .and_this() .map(|| 1) .unwrap_or(0); pub fn noop_visit_constraint( AssocConstraint { id, ident, gen_args, kind, span }: &mut AssocConstraint, vis: &mut T ) {} match kind { AssocConstraintKind::Equality { ref mut term } => { 1; } } impl X { pub fn ident(&self) -> Option { match self.kind { AttrKind::Normal(ref item, _) => { if item.path.segments.len() == 1 { Some(item.path.segments[0].ident) } else { None } } AttrKind::DocComment(..) => None, } } } #![attr] // comment to the right of attr /* */ a!(/**/); Thing(/* _______ */); pub const /* _______ */ a = {}; const a = "💖"; // ______________ // _______ _______ _______ /* _______ */ foo /* _______ */; this.call(a, /* _______ */ b); /* foo text */ /* fn a() { println!("b"); } // */ #[a = "a"] #[b] // v #[cfg_attr(rustfmt, rustfmt::skip)] pub static x: [i32; 0] = []; f!() /* comment */; f! {} /* comment */ f![] /* comment */; pub enum Foo { A, // `/** **/` B, // `/*!` C, } ProcessSystemError(A { code: acc.error.code, // _______ originalError: acc.error, // _______ }); foo( A {} // _______ ); fn c() {} /* a b */ const f = static async |source, block, opts| { for entry in source { yield async move || { const cid = persist(entry.content.serialize(), block, opts).await; return A { cid, path: entry.path, unixfs: UnixFS.unmarshal(entry.content.Data), node: entry.content, }; }; } }; type Expect_Parenthesized_dyn = Pin<&mut (dyn Future + Send)>; let mut Expect_Comma_after_first_match = match 0 { RuntimeFlavor::CurrentThread => quote_spanned! {last_stmt_start_span=> #crate_ident::runtime::Builder::new_current_thread() }, RuntimeFlavor::Threaded => quote_spanned! {last_stmt_start_span=> #crate_ident::runtime::Builder::new_multi_thread() }, }; ExpectNoSpreadComma { ..a // }; ExpectNoSpreadComma { ..a // }; ExpectNoSpreadComma { a, b: b, ..c // }; ExpectNoSpreadComma { a, b: b, ..c // }; ExpectNoSpreadComma { a, // .. }; ExpectNoSpreadComma { .. // }; let notify::event::Event { kind: notify::event::EventKind::Modify(_), paths, .. } = event; let notify::event::Event { kind: notify::event::EventKind::Modify(_), paths, .. } = event; // source: "../../samples/issues/0.rs" ================================================ FILE: tests/output/issues/14.f.rs ================================================ [10.0, 10.0, 10.0, 10]; // source: "../../samples/issues/14.rs" ================================================ FILE: tests/output/issues/21/fn_comment.f.rs ================================================ fn eof() {} // comment // source: "../../../samples/issues/21/fn_comment.rs" ================================================ FILE: tests/output/issues/21/fn_fn.f.rs ================================================ fn eof1() {} fn eof2() {} // source: "../../../samples/issues/21/fn_fn.rs" ================================================ FILE: tests/output/issues/21/fn_ln.f.rs ================================================ fn eof() {} // source: "../../../samples/issues/21/fn_ln.rs" ================================================ FILE: tests/output/issues/21/ln_fn_ln.f.rs ================================================ fn eof() {} // source: "../../../samples/issues/21/ln_fn_ln.rs" ================================================ FILE: tests/output/issues/21/mod.f.rs ================================================ mod eof {} // source: "../../../samples/issues/21/mod.rs" ================================================ FILE: tests/output/issues/22.f.rs ================================================ fn preserve_last_semicolon() { if let Some(left) = node.borrow().left.as_ref() { deque.push_back(left.clone()); } if let Some(right) = node.borrow().right.as_ref() { deque.push_back(right.clone()); }; } fn a() { if let Ok(_) = lock.try_lock() { }; } fn b() { let lock = std::sync::Mutex::new(10); match lock.try_lock() { Ok(_) => {} Err(_) => {} } match lock.try_lock() { Ok(_) => {} Err(_) => {} }; } fn c() { if let Ok(_) = lock.try_lock() { }; // comment } fn d() { if let Ok(_) = lock.try_lock() { }; // comment } fn e() { if let Ok(_) = lock.try_lock() { } /** comment */; } fn f() { if let Ok(_) = lock.try_lock() { }; } fn g() { if let Ok(_) = lock.try_lock() { }; // comment } fn h() { if let Ok(_) = lock { } if let Ok(_) = lock { } } fn i() { match lock { } match lock { } } fn inner_attr() { if let Ok(_) = lock.try_lock() { } #![attr] } // source: "../../samples/issues/22.rs" ================================================ FILE: tests/output/issues/25.f.rs ================================================ #[generator(yield(i32))] fn nums() { yield_!(3); } // some extra samples to track changes #[// 0 generator( // 1 // 2 yield( // 3 // 4 i32 // 5 ) // 6 )] // 7 // non-conventional syntax (does not format) #[#[a] generator( #[b] yield( #[c] i32 ))] #[generator (a( #[generator(b(i32))] i32 ) )] #[generator (a( #[generator(yield(i32))] i32 ) )] #[generator (yield( #[generator(b(i32))] i32 ) )] #[generator (yield( #[generator(yield(i32))] i32 ) )] fn f() { yield_!(3); } // macros in attr (does not format) #[attr(foo!( ))] fn f() {} // source: "../../samples/issues/25.rs" ================================================ FILE: tests/output/issues/nth-pass.f.1.rs ================================================ // prettier for javascript cannot format those in one pass return ( // _______ 42 * 84 + 2 ); return ( // _______ 42 + 84 * 2 ); foo.x.y // comment after parent // foo // comment 1 .bar() // comment after bar() // comment 2 .foobar // comment after // comment 3 .baz(x, y, z); let zzzz = // comment 0 expr?.another???.another????.another?.another?; // comment after parent // comment 1 // comment 2 // comment 3 [ { a = b; }, c, // ]; // format: lost 4 comments // source: "../../samples/issues/nth-pass.rs" ================================================ FILE: tests/output/issues/nth-pass.f.rs ================================================ // prettier for javascript cannot format those in one pass return ( // _______ 42 * 84 + 2 ); return ( // _______ 42 + 84 * 2 ); foo// comment after parent // foo .x.y // comment 1 .bar() // comment after bar() // comment 2 .foobar// comment after // comment 3 .baz(x, y, z); let zzzz = // comment 0 expr?.another???.another????.another?.another?; // comment after parent // comment 1 // comment 2 // comment 3 [ { a = b; }, c, // ]; // format: lost 4 comments // source: "../../samples/issues/nth-pass.rs" ================================================ FILE: tests/output/macros/cfg_if.f.rs ================================================ [ cfg_if! { if #[cfg(def)] { use std; 0 } }, cfg_if! { if #[cfg(def)] { use std; 0 } else { 1 } }, cfg_if! { if #[cfg(abc)] { 0 } else { 1 } }, cfg_if! { if #[cfg(abc)] { 0 } else if #[cfg(def)] { 1 } }, cfg_if! { if #[cfg(abc)] { 0 } else if #[cfg(def)] { 1 } else { 0 } }, cfg_if! {}, cfg_if! { // comment if #[cfg(abc)] { 0 } }, cfg_if! { if #[cfg(abc)] { /// comment /// comment /// comment struct A { //! comment a: u8, } } }, cfg_if! { if #[cfg(abc)] { struct A { //! comment // comment /// comment a: u8, } } }, cfg_if! { if #[cfg(abc)] { struct A { /// comment a: u8, } } }, cfg_if! { if #[cfg(abc)] { struct A { //! comment } } }, cfg_if! { if #[cfg(abc)] { struct A { /// comment } } }, cfg_if! { if true{} }, ]; // source: "../../samples/macros/cfg_if.rs" ================================================ FILE: tests/output/macros/if_chain.f.rs ================================================ [ if_chain! { if let Some(a) = b; if let Err(a) = b; let (a, b) = c; if 1 + 2; then { d=0; } }, if_chain! { then { d=0; } }, if_chain! { then { d=0; } else { d!(); } }, if_chain! { if let A::B | A::C = D; then { 0 } else { 1 } }, if_chain! { let Ok(a) | Err(b) = c; then { d!(); } else { d!(); } }, if_chain! { if 1 + 1; let a: u32 = 3; then { d!(); } else { d!(); } }, ]; // source: "../../samples/macros/if_chain.rs" ================================================ FILE: tests/output/macros/matches.f.rs ================================================ [ matches!(1 + 1, Some(_)), matches!(1 + 1, Some(_) | None if 1 + 1 == 2), matches!(1 + 1, | Some(_) | None if 1 + 1 == 2), ]; // source: "../../samples/macros/matches.rs" ================================================ FILE: tests/output/styling/blockify.f.rs ================================================ [ || 0, || { match 0 { } }, || ( if 0 { } ), || { loop { } }, || const {}, || async {}, || -> T { 0 }, || -> T { match 0 { } }, || -> T { if 0 { } }, || -> T { loop { } }, || -> T const {}, || -> T async {}, ]; // source: "../../samples/styling/blockify.rs" ================================================ FILE: tests/output/styling/canInlineBlockBody.f.rs ================================================ [ { if 0 { 0 } }, { if 0 { 0 } else { 0 } }, { while 0 { 0; } }, { unsafe { 0 } }, { 0; if 0 { 0 } }, { 0; if 0 { 0 } else { 0 } }, { 0; while 0 { 0; } }, { 0; unsafe { 0 } }, f(async {}), f(async { 1 }), f(async { 1; }), { async {} }, { async { 1 } }, { async { 1; } }, { 0; async {} }, { 0; async { 1 } }, { 0; async { 1; } }, if (0 as u8) < 1 {} else {}, { 0; if (0 as u8) < 1 { } else { } }, if (0 as u8) < 1 {} else if (0 as u8) < 1 {}, if 0 { } else { 0; }, if 0 { } else if 1 { 0; } else { }, if 0 { } else if 1 { } else { 0; }, if 0 { 0; } else { }, if 0 { 0; } else { 2 }, if 0 { 2 } else { 0; }, match 0 { 0 => 0, 0 => { 0 } }, f(if 0 { 1 } else { 2 }), f( { 0; }, if 0 { 1 } else { 2 } ), 0 + (if 0 { 1 } else { 2 }), { 0 + (if 0 { 1 } else { 2 }) }, ({ 0; }) + (if 0 { 1 } else { 2 }), match 0 { 0 => { break 0; } 0 => { o = 0; } 0 => match 0 { } 0 => if 0 {} else {} 0 => if 0 { } }, || { loop { match 0 { 0 => { break 0; } 0 => { o = 0; } 0 => match 0 { } 0 => if 0 {} else {} 0 => if 0 { } } } }, ]; // source: "../../samples/styling/canInlineBlockBody.rs" ================================================ FILE: tests/output/styling/needsParens.f.rs ================================================ let (A {} | a() | []) = (); if let A {} | a() | [] = () { } type A: B + C; type A: (impl B + C); trait A = B + C; trait A = (impl B + C); // source: "../../samples/styling/needsParens.rs" ================================================ FILE: tests/output/styling/needsSemi.f.rs ================================================ fn f() { #[cfg(unix)] { 0 } #[cfg(windows)] { 1 } } // source: "../../samples/styling/needsSemi.rs" ================================================ FILE: tests/output-ext/errors/foo.rs ================================================ > Error.toString() > ---------------------------------------------------------------------------------------------------- -1 1 | ~ ^ Unexpected End Of File, expected Expression 2 3 ---------------------------------------------------------------------------------------------------- ParserError at ext/jinx-rust/tests/samples/errors/foo.rs:1:1 > inspect(Error) > Unexpected End Of File, expected Expression at read_expression_lhs ext/jinx-rust/src/parser/read/expressions.ts:851:11 at fn ext/jinx-rust/src/parser/read/expressions.ts:875:13 at ES_withPrecedence ext/jinx-rust/src/parser/state/index.ts:784:14 at ES_withContext ext/jinx-rust/src/parser/state/index.ts:777:14 at read_stmt_expression ext/jinx-rust/src/parser/read/expressions.ts:874:9 at ExpressionStatement.read ext/jinx-rust/src/parser/read/statements.ts:78:22 at READ_NODE ext/jinx-rust/src/parser/state/constructor.ts:259:46 at ExpressionStatement.call ext/jinx-rust/src/parser/state/constructor.ts:245:4 at read_expr_or_macroInvocation_stmt ext/jinx-rust/src/parser/read/statements.ts:85:29 at read_statement ext/jinx-rust/src/parser/read/statements.ts:814:11 at EACH ext/jinx-rust/src/parser/read/statements.ts:821:42 at fn ext/jinx-rust/src/parser/state/index.ts:500:66 at with_outerAttributes ext/jinx-rust/src/parser/state/index.ts:957:9 at with_outerAttributes_fromStatementContext ext/jinx-rust/src/parser/state/index.ts:975:9 at read_group_noDelim ext/jinx-rust/src/parser/state/index.ts:500:18 ...filtered 5 lines { [stack]: 'Unexpected End Of File, expected Expression\n' + ' at \x1B[36mread_expression_lhs\x1B[39m \x1B[90mext/jinx-rust/src/parser/read/expressions.ts:851:11\x1B[39m\n' + ' at \x1B[36mfn\x1B[39m \x1B[90mext/jinx-rust/src/parser/read/expressions.ts:875:13\x1B[39m\n' + ' at \x1B[36mES_withPrecedence\x1B[39m \x1B[90mext/jinx-rust/src/parser/state/index.ts:784:14\x1B[39m\n' + ' at \x1B[36mES_withContext\x1B[39m \x1B[90mext/jinx-rust/src/parser/state/index.ts:777:14\x1B[39m\n' + ' at \x1B[36mread_stmt_expression\x1B[39m \x1B[90mext/jinx-rust/src/parser/read/expressions.ts:874:9\x1B[39m\n' + ' at \x1B[34mExpressionStatement.read\x1B[39m \x1B[90mext/jinx-rust/src/parser/read/statements.ts:78:22\x1B[39m\n' + ' at \x1B[36mREAD_NODE\x1B[39m \x1B[90mext/jinx-rust/src/parser/state/constructor.ts:259:46\x1B[39m\n' + ' at \x1B[36mExpressionStatement.call\x1B[39m \x1B[90mext/jinx-rust/src/parser/state/constructor.ts:245:4\x1B[39m\n' + ' at \x1B[36mread_expr_or_macroInvocation_stmt\x1B[39m \x1B[90mext/jinx-rust/src/parser/read/statements.ts:85:29\x1B[39m\n' + ' at \x1B[36mread_statement\x1B[39m \x1B[90mext/jinx-rust/src/parser/read/statements.ts:814:11\x1B[39m\n' + ' at \x1B[36mEACH\x1B[39m \x1B[90mext/jinx-rust/src/parser/read/statements.ts:821:42\x1B[39m\n' + ' at \x1B[36mfn\x1B[39m \x1B[90mext/jinx-rust/src/parser/state/index.ts:500:66\x1B[39m\n' + ' at \x1B[36mwith_outerAttributes\x1B[39m \x1B[90mext/jinx-rust/src/parser/state/index.ts:957:9\x1B[39m\n' + ' at \x1B[36mwith_outerAttributes_fromStatementContext\x1B[39m \x1B[90mext/jinx-rust/src/parser/state/index.ts:975:9\x1B[39m\n' + ' at \x1B[36mread_group_noDelim\x1B[39m \x1B[90mext/jinx-rust/src/parser/state/index.ts:500:18\x1B[39m\n' + '\x1B[90m ...filtered 5 lines\x1B[39m', [message]: 'Unexpected End Of File, expected Expression', loc: { url: 'ext/jinx-rust/tests/samples/errors/foo.rs:1:1', start: { line: 1, column: 1 } }, ctx: [ [length]: 0 ], toString: [Function (anonymous)] { [length]: 0, [name]: '', [prototype]: { [constructor]: [Circular *1] } }, parserState: { nodes: [ 'SourceFile (--1)', 'Program (...parsing)', 'ExpressionStatement (...parsing)', [length]: 3 ], discarded_nodes: [ [length]: 0 ], __ctx_Precedence: [ 0, 3, [length]: 2 ], max_Precedence_depth: 20, max_ES_ctx_depth: 12, max_TY_depth: 12, __es_optional_start: -1, __ctx_ES_i: 1, __ctx_ES_PRCD_i: 1, __ctx_TY_i: 0, __ctx_MC_i: 0 } } ================================================ FILE: tests/output-ext/expressions/block.f.rs ================================================ fn f() { ({ foo.0 }).0 = 0; (async {}).await; async move { } ({ a }).0 += { 0 }; try { } match (try {}) { } for lhs in &mut self.0 { *lhs += rhs; } for lhs in self.0.iter_mut() { } for _ in [1, 2, 3].into_iter() { } for elt in self { r = r + f(*elt); } for _ in [1, 2] { } for _ in [1.0, 2.0] { } if ( loop { } ) { } if let 0 = 1 { } if a % 5 == 0 { } let x: A = if a % 5 == 0 { }; let x = if let 0 = 1 { }; if let 0 = 1 { 3; } if ( { y = Foo { foo: x }; } ) { } if q == "" { } if ('x' as char) < ('y' as char) { } else { } let a = if 1 { 1 }; let a = if 1 { 0 } else if 1 { 0 }; let a = if (if 0 { 0 } else { 0 }) { 0 } else { 0 }; let a = if 0 { if 0 { 0 } else { 0 } } else { 0 }; let a = if 0 { 0 } else if 0 { 0 } else { 1 }; let a = if let 0 = (if let 0 = 0 { 0 } else { 0 }) { 0 } else { 0 }; for x in 0..10 { (async { Some(x) }).await.unwrap(); } for _ in 1.. { call_forever(); } unsafe { (Foo { b: () }).a; } if 1 { } else if let Some(a) = Some(1) { } } [ m::Pub { 0: loop { }, }, 2_usize + (loop { }), [ (); &({ loop { continue; } }) ], [ (); loop { break; } ], [ (); { while true { break; } 0 } ], [ (); { for _ in 0usize.. { } 0 } ], unsafe { *&raw mut y }, ]; a::b(async move { if let Err(e) = c(d).await { f!("g: {}", h); } }); // source: "../../../ext/jinx-rust/tests/samples/expressions/block.rs" ================================================ FILE: tests/output-ext/expressions/closure.f.rs ================================================ fn main() { let lam = |(a, ref b, c, ref mut d): (X, X, X, X)| {}; let x = |_: ()| (); let y = || x(()); let mut x = |_: ()| { outer = 4; () }; let x = move |_: ()| { let inner = outer; () }; const VTABLE: &'static VTable = &(VTable { _to_dst_ptr: |_: *mut ()| unsafe { std::mem::zeroed() }, }); let z = a(&mut (|x| x - 22)); let mut unboxed = || {}; Box::new(move |y| { x + y }); s( |f| (*f)(), Box::new(|| {}) ); (0..42).e(|_x| { match E(()) as R<(), _> { O(()) => s.push(()), E(_) => (), } }); <()>::a(|| ()); let f: &mut dyn FnMut<(_,), E = ()> = &mut (|_: <() as Lt<'_>>::T| {}); Box::new(move |v| { (|_| e.d()())(v); X }) as Box Q>; let _c = || { match b.0.c(1) as D<(), _> { _ => 0, } }; let f: &dyn Fn(i32) -> _ = &(|x| x + x); let f = |x: u32| -> u32 { 1 }; for f in &[d, g, |x| x] { a!("{}", f(6)); } (|| { (|| { c.d })(); (move || { a.b })(); })(); let q = a.e(async move { b(move || async move { d!() }) }); let g = { || z(i) }; let _ = || a.e(async { r }); let _ = E(0) .d() .q(|ref _a| true); let _ = !(4..5).a(|x| (x == 1 || x == 3 || x == 5)); let _ = !(1..3).a(|x| [1, 2, 3].b(&x)); let _ = !(1..3).a(|x| (x == 0 || [1, 2, 3].b(&x))); let _ = !(1..3).a(|x| ([1, 2, 3].b(&x) || x == 0)); let _ = !(1..3).a( |x| ([1, 2, 3].b(&x) || x == 0 || [4, 5, 6].c(&x) || x == -1) ); let hash: &Fn(&&Block) -> u64 = &(|block| -> u64 { 1 }); if outer_guard.map_or( true, |(Guard::If(e) | Guard::IfLet(_, e))| !is_local_used(cx, *e, binding_id) ) { } a = || b; [ foo(|| ()), |x: u32| x + 1, (|| Box::new(|| {}) as Box)(), |_: T| 3, move |x: isize, y| x + y + z, &mut (|| 22), &(|| 22), || { x += 1; }, call(&(|| {}), ()), <()>::drive(|| ()), h2(|_: (), _: (), _: (), _: ()| {}), move |a: isize, b| { a + b }, move |a: isize, b| { z; zz; a + b }, |x: usize| x * 2, |x: usize| ({ x }) * 2, |x: usize| ({ x })(), |x| lib::d!(x), |x| { match x { a => { g(a) } } }, |x| d!(x), |_| async { () }, |x, y| {}, |x: &u64, y: &u64| {}, |x: &u64, y| {}, |x, y: &u64| {}, match 0 { 2 => |a| 2, 1 => 0, }, [b, |a| 2], [|a| 2, b], async || 1, |ctx: Ctx<(String, String)>| -> io::Result { Ok(Response::new().with_body(ctx.params.0)) }, rayon::join( || recurse(left, is_less, pred, limit), || recurse(right, is_less, Some(pivot), limit) ), rayon::join( 1, || recurse(left, is_less, pred, limit), 2, || recurse(right, is_less, Some(pivot), limit) ), ]; bifornCringer = { askTrovenaBeenaDepends = { glimseGlyphs = |argumentOne, argumentTwo, argumentThree| |restOfTheArguments12345678| { return "baz"; }; }; }; aaaaaaaaaaaaaaaa.map(|x| { x += 1; x }).filter; let f = |x| { { { { x } } } }; let f = |x| { { { x } } }; let f = |x| { { x } }; let f = |x| { x }; let f = |x| x; } fn f(_n: isize) -> isize { id(|| { 1 }) - 0 } fn f() { || { x += y; } } struct A { b: [ (); match || 1 { a => 0, } ], } enum E { V( [ (); { let _ = || 1; 0 } ], ), } type Ty = [ (); { let _ = || 1; 0 } ]; // source: "../../../ext/jinx-rust/tests/samples/expressions/closure.rs" ================================================ FILE: tests/output-ext/expressions/expr.f.rs ================================================ fn main() { let a = async move {}; 9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999; // boop vec![1, 2, 3].len(); write!(vec![], "")?; println!(""); [0]; b.a; *foo += 1; let &_ = bar; let &mut _ = foo; if let _ = 0 { } while let _ = 0 {} let ((), ()) = ((), ()); let x: &[u8] = &[0]; let Foo { a, ref b, mut c, x: y, z: z } = foo; let x = &raw const y; let x = &raw mut y; a::, _>(box 1); if &raw const one == &raw mut one { } let _x = if false { 0 } else if true { panic!() } else { 10 }; let _: ::C; let a: A = A { name: 0 }; let b1 = &mut *b; let mut x: Box<_> = box 3; let x: (Box<_>,) = (box 1,); let &mut ref x = b; let &mut mut x = b; let ref mut y = b; let (a, b, c, d); let (mut c, mut d); let s = S { x: 3, y: 4 }; let mut r = R { c: Box::new(f) }; let _: &usize = &1; let _: &&usize = &&1; let _: &&&usize = &&&1; let _: &&&usize = &&&1; let _: &&&&usize = &&&&1; let _: &&&&usize = &&&&1; let _: &&&&&usize = &&&&&1; let x: T = **item; let &x = &(&1isize as &dyn T); let &x = &&(&1isize as &dyn T); let &&x = &&(&1isize as &dyn T); let &x = &1isize as &dyn T; let &&x = &1isize as &dyn T; let &&x = &(&1isize as &dyn T); let &&&x = &(&1isize as &dyn T); let box x = box 1isize as Box; let box box x = box 1isize as Box; let a = ((b[0] as u64) << 0) | ((b[1] as u64) << 8) | ((b[2] as u64) << 16) | ((b[3] as u64) << 24); let a = if let Err(b) = c { d } else { e!("") }; let mut n3 = N3 { n: N2(N1 { n: N0 { x: Box::new(42) } }) }; n3.n.0.n.x = n3.n.0.n.x; let mut t = (1, ((2, 3, (4, 5)),)); t.1.0.2.1 = t.1.0.2.1; let mut a: A<(), &mut i32> = try { 1 }; let _ = &mut *s.0.borrow_mut(); let _ = &mut *s[0].borrow_mut(); let x: Foo<_> = Bar::(PhantomData); let f = A:: { a: 10 }; let v: <() as Lt<'_>>::T = (); ::V() = E::V(); (::V {} = E::V()); let a = &mut b.0.0; let a = &mut b.0[2]; let _ = a::(b().await).await; let _ = a(b::().await).await; let _ = A == s!("e"); let a: &str = &b; ::a::(a!()); let (the, guardian, stands, resolute) = ( "the", "Turbofish", "remains", "undefeated", ); let _: (bool, bool) = (the < guardian, stands > resolute); let (A { x: _x, y: _y }, Z): (_, Z) = c( || B { x: X, y: Y }, || Z ); let _: A<{ 1 + 2 }>; let _: A<{ 5 }>; let A::<1, N>(N) = A::new(); let _ = Some(Foo { _a: 42 }).map(|a| a as Foo); let _ = { () = { () = { () = (); }; }; }; String::<>::from::<>("><>").chars::<>().rev::<>().collect::(); fn a(x: &f) { return while !x.f() { x.g(0); }; } let i = &f::s(0); >::e::(); let _: i32 = (match "" { "+" => ::std::ops::Add::add, "-" => ::std::ops::Sub::sub, "<" => |a, b| (a < b) as i32, _ => c!(), })(5, 5); [].e().f(|_: &i32| { [].e().f(move |_: &i32| { i += 1; }); }); let _x2 = X { a: 1, b: 2, ..DX }; i[i[0]] = 0; i[i[0] - 1] = 0; } [ b.a, X { len: 3 }, x.len > 3, x.len >> 3, vec![1, 2, 3].into_iter().collect::>(), X(1, 2, 3), (1, 2, 3), vec![1, 2, 3].len(), write!(vec![], "")?, &*d.borrow(), **bar == Test::Baz || **bar == Test::Qux, &foo[0..1], TypeId::of::(), &[*xs[0].x, *xs[1].x], &mut tup.0, <_>::f(), &(fop:: as fn()), a(), ::foo::bar::baz::f(), <() as ::foo::T>::Assoc::f(), [].a(), id::<[i32; 3]>([1, 2, 3]), m::Pub(0u8).method_with_priv_params(loop { }), >::INHERENT_ASSOC_CONST, ::f(0), a::>(), Foo { f: x.clone() }, a::<&str, (*const u8, u64)>(), a("".b()).c("").d().await, foo(&[vec![123]]).await, A::b::(x).d(E("x"))?.f(1), // std::<_ as _>, std::<0>, &raw const x, (A::a as fn(&(dyn A + 'static)) -> B)(&"c"), f::<::E>(), ::Item>>::from(), <>::B as C>::e(db), tuple.0.0, tuple.0.0, tuple /*special cases*/.0.0, //aaa (((),),), (1, (2, 3)).1.1, ((1, (2, (3, 4))).1.1.1)(1), 1, a((1, 2.0, 3)), b((1,)), (1).f::(), { *a = &a[1..]; }, a().await.0, a.b(c).await.d(e)?, 0 + 1, 0 * 1, 0 - 1, 0 / 1, 0 % 1, 0 & 1, 0 | 1, 0 << 1, 0 >> 1, 0 == 1, 0 != 1, 0 < 1, 0 > 1, 0 <= 1, 0 >= 1, { x -= 0; }, { x *= 0; }, { x /= 0; }, { x &= 0; }, { x %= 0; }, { x ^= 0; }, { x += 0; }, { x <<= 0; }, { x <<= 0; }, { x >>= 0; }, { x >>= 0; }, { x |= 0; }, A::<1>::B(), A::<1>::B {}, A::<1>(), A::<1> {}, { { } 2 }, &mut [0; 1][..], &B::::A[0], &B::::A.0[0], &B::::A.0.1[0], [[0; 1]; 1], std::ptr::null::().is_null(), &ss.1, &raw mut foo.x.0..1, &mut **d, [12, 34][0 + 1], g(f())(()), ]; fn f() { s.e() .f(E::s) .f(|f| f.a()) .f(R::e) .e(|a| *a >= q) .d() } fn f() { let q = E { r: f![] }; Q(Q(q)).s(|d| q.i(|mut d| { e.z(0); f.G = e; r }) ); } pub fn public_expr(_: [u8; a(0).0]) {} pub fn f() { return ::f(); } fn f() -> isize { ( { return 1; }, { return 2; }, ) } fn f(x: Box) -> Box<(Box, Box)> { box (x, x) } fn f(f: F) -> isize where F: FnOnce(isize) -> isize {} fn f() { if ( { return; } ) { } } fn f() { b! {} c } fn f(arg: T) -> String { return ::to_string(&arg); } fn f(a: A, b: u16) -> Box + 'static> { box (Invoker { a: a, b: b }) as Box + 'static> } fn f() { ( { return 1; }, { return 2; }, ) } pub trait Foo: Iterator::Key> {} fn f() { ::m!(S, x); } // source: "../../../ext/jinx-rust/tests/samples/expressions/expr.rs" ================================================ FILE: tests/output-ext/expressions/flow_expr.f.rs ================================================ pub fn main() { loop { return ({ break; }) as (); } return (); ({ return; }) as (); return if 1 { () } else { () }; return ({ return; }) as (); return { return { return; }; }; return try { 4 }; return; return 'aaa: loop { break 'aaa 1; }; loop { break 'aaa: loop { break 'aaa 1; }; } 'aaa: loop { break 'aaa 'bbb: loop { break 1; }; } let a = 'a: loop { break 'a 1; }; [ (); { return || { let tx; }; } ]; [ (); { return; } ]; [ (); { return match 0 { n => n, }; } ]; [ (); { return match () { 'a' => 0, _ => 0, }; } ]; let a = loop { break { return 0; () }; }; let a = loop { break { break; }; }; let a = loop { break loop { }; }; let a = loop { break { return 0; }; }; loop { if ( { break; } ) { } } for _ in ( { return (); 0..3 } ) { } loop { while ( { return; } ) { if ( { return; } ) { match ( { return; } ) { 1 => { if ( { return; } ) { return; } else { return; } } _ => { return; } }; } else if ( { return; } ) { return; } } if ( { return; } ) { break; } } let () = if 0 { } else { return; }; } // source: "../../../ext/jinx-rust/tests/samples/expressions/flow_expr.rs" ================================================ FILE: tests/output-ext/expressions/ident.f.rs ================================================ fn bare_crate(_: crate::a); fn bare_global(_: ::a); fn u8(u8: u8) { if u8 != 0u8 { } assert_eq!(8u8, { macro_rules! u8 { ( u8 ) => { mod u8 { pub fn u8<'u8: 'u8 + 'u8>(u8: &'u8 u8) -> &'u8 u8 { "u8"; u8 } } }; } let &u8: &u8 = u8::u8(&8u8); ::u8(0u8); u8!(u8); u8 }); let &u8: &u8 = u8::u8(&8u8); ::u8(0u8); u8!(u8); u8; let µ = 1.0; µ; } mod u8 { pub fn u8<'u8: 'u8 + 'u8>(u8: &'u8 u8) -> &'u8 u8 { "u8"; u8 } } // source: "../../../ext/jinx-rust/tests/samples/expressions/ident.rs" ================================================ FILE: tests/output-ext/expressions/literal.f.rs ================================================ [ ('\x0A', '\x0B', '\x0C', '\x0D', '\x20', '\u{85}', '\u{A0}'), ('\u{1680}', '\u{2000}', '\u{2001}', '\u{2002}', '\u{2003}'), ('\u{2004}', '\u{2005}', '\u{2006}', '\u{2007}', '\u{2008}'), ('\u{2009}', '\u{200A}', '\u{2028}', '\u{2029}', '\u{202F}'), ('\u{205F}', '\u{3000}'), ( "", r"\", "\n", "\t", "'", "\r", "\\\n", "\\\n ", "\\\n \u{a0} x", "\\\n \n x", ), (r"\u{0}x", r"\u{1F63b}}", r"\v", r"\💩", r"\●", "\\\r"), (r"\u{FFFFFF}", r"\u{ffffff}", r"\u{ffffff}"), ( r"\x", r"\x0", r"\xf", r"\xa", r"\xx", r"\xы", r"\x🦀", r"\xtt", r"\xff", r"\xFF", r"\x80", ), (r"\x0ff", r#"\"a"#, r"\na", r"\ra", r"\ta", r"\\a", r"\'a", r"\0a"), ( r"\u{DC00}", r"\u{DDDD}", r"\u{DFFF}", r"\u{D800}", r"\u{DAAA}", r"\u{DBFF}", ), ( r"\u", r"\u[0123]", r"\u{0x}", r"\u{", r"\u{0000", r"\u{}", r"\u{_0000}", r"\u{0000000}", ), (r"\0", r"\x00", r"\x5a", r"\x5A", r"\x7f", r"\x80", r"\xff", r"\xFF"), ("a", r#"\""#, r"\n", r"\r", r"\t", r"\\", r"\'"), ("a", 'a'), ("ы", 'ы'), ("🦀", '🦀'), (r#"\""#, '"'), (r"\n", '\n'), (r"\r", '\r'), (r"\t", '\t'), (r"\\", '\\'), (r"\'", '\''), (r"\0", '\0'), (r"\x00", '\0'), (r"\x5a", 'Z'), (r"\x5A", 'Z'), (r"\x7f", 127 as char), (r"\u{0}", '\0'), (r"\u{000000}", '\0'), (r"\u{41}", 'A'), (r"\u{0041}", 'A'), (r"\u{00_41}", 'A'), (r"\u{4__1__}", 'A'), (r"\u{1F63b}", '😻'), (b"a\n\r\t\\\'\"\0\xF0", br###"a"##b"###, b"a\"##b"), ( b"a\xF0\t", b'\xF0', br"a\n", b'a', b'\n', b'\r', b'\t', b'\\', b'\'', b'\"', b'\0', b'\xF0', ), (&1u16, &42i32, !0 as u32, !0 as u64), (4294967295, 0xffffffff, 0xffffffffffffffff, 18446744073709551615), (-2147483648i32).wrapping_sub(1), 2147483647, (-3.40282356e38_f32, f32::MIN, 3.40282356e38_f32, f32::MAX), (-1.7976931348623158e308_f64, f64::MIN, 1.7976931348623158e308_f64, f64::MAX), (!0xf0_isize & 0xff, 0xf0_isize | 0xf, 0xf_isize << 4, 0xf0_isize >> 4), ( 0b1010_1010_isize | 0b0101_0101, (-1000isize as usize) >> 3_usize, 2305843009213693827_usize, ), (-16 >> 2, a.0 - 1, a.0.1..2, (0).b0), ('\u{10__FFFF}', "\u{10_F0FF__}foo\u{1_0_0_0__}"), (0, 1, 0.1, 1.1, 1.0, 1.005, 1.0, 1.5, 1.5, 0.005, 0.0, 0.0), (0b1, 0B1, 0o1, 0O1, 0x1, 0X1), (0x123abcdef456abcdef, 0X123abcdef456ABCDEF, 0xdeadbeef), ( 0b111000, 0b000111, 0B111000, 0B000111, 0o111000, 0o000111, 0O111000, 0O000111, 0x111000, 0x000111, 0X111000, 0X000111, ), ( 1e1, 1e1, 1e-1, (1).e1, 0.1e1, 1.1e1, 1.1e10, 0.1e10, 0.1e-10, 1e1, 1e1, 1e-1, (1).E1, 0.1e1, 1.1e1, 1.1e10, 0.1e10, 0.1e-10, ), (0.5, 0.5, 0.5, 0.5, 0.5, 0.5), ( 500600.001230045, 1.005e60, 1.0e60, 0.005e60, 0.0e60, 0.0e60, 0.0e60, (0).e60, 0e60, 500600.001230045e60, ), ( 10, 9700, 10e100, 1_1, 1_1.1_1, 0o1_1, 0o0_11, 1.1_0_1e1, 1.1_0_1e1, 0.1_1, 0x1_1, 0xa_1, 0xa_1, 0b01_1, 0b0_1_1, ), (100).toString(), f!("\0="), (2).f64, (2).f64(), ]; fn f() { let n: f64 = 1234567890123456789012345678901234567890e-340; let n: f64 = 0.3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333; let s = "string literal"; let s = "literal with \ escaped newline"; let s = r"string literal"; let s = br"byte string literal"; let s = "foo\r\nbar\n\nbaz\n"; let v = !( (|(..): (_, _), __ @ _| __)((&*"\\", '🤔') /**/, {}) == ({ &[..=..][..]; }) ); // } // source: "../../../ext/jinx-rust/tests/samples/expressions/literal.rs" ================================================ FILE: tests/output-ext/expressions/match.f.rs ================================================ fn a() { match x { } match () { } match (Sd { x: A, y: () }) { } match *c { } match ((A, ()), ()) { } match [0u8; LARGE_SIZE] { } match na.kind { } match (T::T1(()), V::V2(true)) { } match (Sd { x: A, y: () }) { } match "a" { } match (&"foo", "bar") { } match (Foo { foo: true, bar: Some(10), baz: 20 }) { } match (l1, l2) { } match 0 { 0 if false => (), } match true { true => true, } let v: isize = match &*sl { }; let a: isize = match 1 { x if x < 2 => { 3 } x if x < 4 => { 5 } 6 => { 7 } _ => { 8 } }; let val = match ( match ( match ( match ( match () { () => (), } ) { () => (), } ) { () => (), } ) { () => (), } ) { () => (), }; let b: isize = match (A { x: 10, y: 20 }) { x if x.x < 5 && x.y < 5 => { 1 } A { .. } if x == 10 && y == 20 => { 2 } A { .. } => { 3 } }; match true { true if true => (), false if false => unsafe {} true => {} false => (), &[] => 0, &[a, b, c] => 3, &[a, ref d @ ..] => a, &[10, a, ref d @ ..] => 10, [h, ..] if h > n => 0, [h, ..] if h == n => 1, [h, ref ts] => foo(c, n - h) + foo(ts, n), [] => 0, &A::C(v, box ref a) => tail(e), &A::C(x, box A::S) => A::C(c, box A::R), 0 => { return e(j::h::r(a::e::d, "")); } n => { r = &mut a::d(&mut e, &mut [])[n..]; } box Q::V(ed) => match ed.q { box R::E(ref d) if d.d.r() => { true } } _ => panic!(), ref _x => unreachable!(), 0 => { return; } A { a: v } if *v.clone() == 42 => v, A((a,)) => { *a = 0; } Some(x) if let Some(y) = x => (x, y), Some((x, _)) if let Foo::Bar = bar(x) => panic!(), Some((_, x)) if let Foo::Baz = baz(x) => {} Some(x) if let Foo::Qux(y) = qux(x) => assert_eq!(y, 84), Ok(mut r) | Err(mut r) if true => { r = 1; } Color::Rgb(r, g, b) => (r | g) == 0 || (r | b) == 0 || (g | b) == 0, | not_red @ Color::Green | not_red @ Color::Blue | not_red @ Color::Rgb(..) | not_red @ Color::Cyan => format!("{:?}", not_red), Ok(x) if let Err(_) = x => {} // _ if let _ = !Foo{ a: 1 } => {}, _ if !(Foo { a: 1 }) => {} E { x: A, y: _ } => {} D { a: _a } | C { a: _a } if true => {} Some(a::B { misc: false, .. }) => {} ref _x if false => {} "b" => {} "b" => {} _ => {} () if f == Foo { x: 42 } => {} _ => {} 0 => {} a => {} a::X => {} _ => {} (a, ..) => {} 0..128 => {} 128..=255 => {} 128..=255 if 1 => {} (Some(_), None) | (None, Some(_)) => {} S::<{ a() }> => {} ((A, _), _) => {} [..] => {} &[] => {} &[1..=255] => {} C0 => {} T::A {} => {} &[_, _, ..] => {} [Some(..), None, ref tail @ ..] => {} [Some(..), Some(..), ref tail @ ..] => {} [None, None, ref tail @ ..] => {} [None, Some(..), ref tail @ ..] => {} [_, _, ref tail @ .., _] => {} (&"foo", &_) => {} (&&_, &_) => {} Foo { foo: true, bar: Some(_), .. } => {} Foo { foo: false, bar: None, .. } => {} Foo { foo: true, bar: None, .. } => {} Foo { foo: false, bar: Some(_), .. } => {} (Some(&[]), Ok(&[])) => {} (Some(&[_, ..]), Ok(_)) | (Some(&[_, ..]), Err(())) => {} (None, Ok(&[])) | (None, Err(())) | (None, Ok(&[_])) => {} (None, Ok(&[_, _, ..])) => {} (T::T1(()), V::V1(i)) => {} (T::T2(()), V::V2(b)) => {} Foo::Bar { bar: Bar::A, .. } => {} ::A::B(3) => {} ::A::B(_) if false => {} ::A::B(..) if false => {} ::A::B(_n) => {} ::A::B => {} ::A::B(::A::B) => {} ::A::B(::A::B(_)) => {} ::A::B(::A::B, ::A::B(_)) => {} ::A::B(::A::B(..), ::A::B) => {} ::A::B(..) => {} A::> { x: A(10, 11) } => {} ::B::< as C>::U> { x: A::(11, 16) } => {} isize::MIN..5 | 5..=isize::MAX => {} 0..5 | 5..=usize::MAX => {} (0..5, true) | (5..=usize::MAX, true) | (0..=usize::MAX, false) => {} [Ok(box ref a), ref xs @ .., Err(box b), Err(box ref mut c)] => {} [Ok(box a), ref xs @ .., Err(box ref b), Err(box ref c)] => {} box a => { Foo(box 1) } box [Ok(a), ref xs @ .., Err(ref b)] => {} ref a @ box b => {} ref a @ box ref b => {} Ok(ref a @ b) | Err(b @ ref a) => {} ref a @ Ok(ref b) | ref a @ Err(ref b) => {} ref a @ Ok(ref mut b) | ref a @ Err(ref mut b) if { *b = U; false } => {} ref mut a @ Ok(ref b) | ref mut a @ Err(ref b) if { *a = Err(U); false } => {} a @ Some((mut b @ ref mut c, d @ ref e)) => {} mut a @ Some([ref b, ref mut c]) => {} ref mut a @ Some([b, mut c]) => {} ref mut a @ Ok(ref mut b) | ref mut a @ Err(ref mut b) => {} ref bar @ Some(box n) if n > 0 => {} Some(ref bar @ box n) if n < 0 => {} ref x @ A { ref a, b: 20 } => {} (a, _) | (_, a) if a > 10 => 0, e @ &1..=2 | e @ &3..=4 => {} 0 | &1 => {} Ok(x) | Err(x) => 0, &(Ok(x) | Err(x)) => 0, Ok(mut x) | &Err(mut x) => 0, Some((a, _) | (_, a)) if a > 10 => 0, Some((a, _)) | Some((_, a)) if a > 10 => 0, Some(ref bar @ box Test::Baz | ref bar @ box Test::Qux) => 0, Some(x) if let Foo::Qux(y) = qux(x) => 0, [bar @ .., n] if n == &5 => {} &A { a: 2 } if a.b().c() => {} A::B { a } => {} &A::B { a } => {} box A::B { a } => {} (A::B { a },) => {} [A::B { a }] => {} C(A::B { a }, ()) => {} ((0 | 1,) | (2 | 3,),) => {} (Some(2..=255),) => {} (None | Some(0 | 1),) => {} (1 | 2,) => {} (1 | 2, 3 | 4) => {} ([] | [0 | 1..=255] | [_, ..],) => {} ((0, 0) | (0, 1),) => {} ((0, 0) | (1, 0),) => {} | Tri::A(Ok(mut x) | Err(mut x)) | Tri::B(&Ok(mut x) | Err(mut x)) | &Tri::C(Ok(mut x) | Err(mut x)) => 0, Wrap(Ok(mut x) | &Err(mut x)) => 0, Wrap(&(Ok(x) | Err(x))) => 0, Wrap(Ok(x) | Err(x)) => 0, () if if ( if (if 0 { 0 } else { 0 }) { 0 } else { 0 } ) { 0 } else { 0 } => 0, Add | Mul | And | Or | BitXor | BitAnd | BitOr | Eq | Ne => 0, Sub | Div | Rem | Shl | Shr | Lt | Le | Ge | Gt => 0, | ThisIsA::ReallyLongPatternNameToHelpOverflowTheNextValueOntoTheNextLine | ThisIsA::SecondValueSeparatedByAPipe | ThisIsA::ThirdValueSeparatedByAPipe => 0, MyEnum::Option1 if cfg!(target_os = "windows") => #[cfg(target_os = "windows")] { 1 } MyEnum::Option1 if cfg!(target_os = "windows") => (#[cfg(target_os = "windows")] 2), Some( RegionResolutionError::SubSupConflict( vid, _, SubregionOrigin::Subtype(box TypeTrace { cause, values }), sub_placeholder @ Region(Interned(RePlaceholder(_), _)), _, sup_placeholder @ Region(Interned(RePlaceholder(_), _)), _, ), ) => self.try_report_trait_placeholder_mismatch( Some(self.tcx().mk_region(ReVar(*vid))), cause, Some(*sub_placeholder), Some(*sup_placeholder), values ), GenericParamKind::Const { kw_span, default: Some(default), .. } => { kw_span.to(default.value.span) } } } // source: "../../../ext/jinx-rust/tests/samples/expressions/match.rs" ================================================ FILE: tests/output-ext/expressions/parens.f.rs ================================================ fn main() { holds_callable.callable(); (holds_callable.callable)(); a = { b = c; }; mystruct.myfield; foo().x; (Struct { a: 10, b: 20 }).a; (mystruct.function_field)(); let name: &'static str = (|| "Rust")(); let x: i32 = 2 + 3 * 4; let y: i32 = (2 + 3) * 4; let lhs = &this.thir[lhs]; (*f)(&x); *x * *x; println!("{}", (self.0)()); (self.0)(ecx, span, meta_item, &item, &mut (|a| items.push(a))); (|_, _, _| {})(0u8, 42u16, 0u8); (|_, _| {})(0u8, 42u16); let x = &[0u32, 42u32] as &[u32]; match x { [] => assert_eq!(0u32, 1), [_, ref y @ ..] => assert_eq!(&x[1] as *const u32 as usize, &y[0] as *const u32 as usize), } unsafe { assert_eq!(ABC as usize, 0); } &mut (|| Some(0 as *const ())) as &mut dyn FnMut() -> Option<*const ()>; unsafe { NUM = 6 * 7 + 1 + ((1u8 == 1u8) as u8); // 44 assert_eq!(*NUM_REF as i32, 44); } unsafe { puts(*argv as *const i8); } unsafe { puts( *( ((argv as usize) + intrinsics::size_of::<*const u8>()) as *const *const i8 ) ); } unsafe { puts( *( ((argv as usize) + 2 * intrinsics::size_of::<*const u8>()) as *const *const i8 ) ); } intrinsics::write_bytes(&mut uninit.value.value as *mut T, 0, 1); assert_eq!((slice_ptr as usize) % 4, 0); printf( "Hello %s\n\0" as *const str as *const i8, "printf\0" as *const str as *const i8 ); let hello: &[u8] = b"Hello\0" as &[u8; 6]; let ptr: *const i8 = hello as *const [u8] as *const i8; let world: Box<&str> = box "World!\0"; puts(*world as *const str as *const i8); assert_eq!(a.f(), "The method f"); assert_eq!((a.f)(), "The field f"); assert_eq!(((|()| 42u8) as fn(()) -> u8)(()), 42); assert_eq!(intrinsics::bitreverse(0b10101000u8), 0b00010101u8); assert_eq!(intrinsics::bswap(0xabu8), 0xabu8); assert_eq!(intrinsics::bswap(0xddccu16), 0xccddu16); assert_eq!(intrinsics::bswap(0xffee_ddccu32), 0xccdd_eeffu32); assert_eq!( intrinsics::bswap(0x1234_5678_ffee_ddccu64), 0xccdd_eeff_7856_3412u64 ); let mut passes: Vec<_> = passes .iter() .map(|p| p()) .collect(); (*DEFAULT_HOOK)(info); (group.apply)(&mut opts); Some((size, 1u128 << ((size.bits() as u128) - 1))); (lo == other_hi || hi == other_lo) && !self.is_singleton() && !other.is_singleton(); (|A { x: mut t }: A| { t = t + 1; t })(A { x: 34 }); (async || 2333)().await; (async move || -> u8 { 42 })(); S.g(1, 2)(true); &Ast::Num((*f)(x)); f(&mut "Hello".to_owned()); Box::new(move |x| f()(x)); let a = Some(1u8).map(|a| foo(a)); let c = Some(1u8).map(|a| ({ 1 + 2; foo })(a) ); true.then(|| mac!()); Some(1).map(closure_mac!()); let _: Option> = true.then(|| vec![]); let d = Some(1u8).map(|a| foo((|b| foo2(b))(a))); all(&[1, 2, 3], &&2, |x, y| below(x, y)); let a: Option>> = Some( vec![1i32, 2] ).map(|v| -> Box> { Box::new(v) }); #[allow(clippy::needless_return)] (|| { return 2; })(); (|| -> Option { None? })(); #[allow(clippy::try_err)] (|| -> Result { Err(2)? })(); } static mut NUM: u8 = 6 * 7; static NUM_REF: &'static u8 = unsafe { &NUM }; impl CoerceUnsized> for Unique where T: Unsize {} fn cvgsk_nichqsd_bhvior() { if let E1::V2 { .. } = (E1::V1 { f: true }) { intarvics::avort(); } if let E2::V1 { .. } = E2::V3:: { inzadqsics::abort(); } } impl<'a, 'b> FnOnce<(&'a &'b [u16],)> for IsNotEmpty { extern "rust-call" fn call_once(mut self, arg: (&'a &'b [u16],)) -> (u8, u8) { self.call_mut(arg) } extern "rust-call" fn call_once123( mut self, arg: (&'a &'b [u16],) ) -> (u8, u8) { self.call_mut(arg) } extern "rust-call" fn call_mut( &mut self, _arg: (&'a &'b [u16],) ) -> (u8, u8) { (0, 42) } } pub fn call_is_not_empty() { IsNotEmpty.call_once((&(&[0u16] as &[_]),)); } EnumTypeFoldableImpl! { impl<'tcx, T> TypeFoldable<'tcx> for Option { (Some)(a), (None), } where T: TypeFoldable<'tcx> } fn x() { a.b.c; a.b.c; a.b.c; a.b.c; a.b.c; a.b.c; a.b.c; a.b.c; a.b.c; a.b.c; a.b.c; a.b.c; a.b.c; a.b.c; a.b.c; a.b.c; foo(#[attr] a.b.c); foo(#[attr] a.b.c); foo(#[attr] a.b.c); foo(#[attr] a.b.c); foo(#[attr] a.b.c); foo(#[attr] a.b.c); foo(#[attr] a.b.c); foo(#[attr] a.b.c); } // source: "../../../ext/jinx-rust/tests/samples/expressions/parens.rs" ================================================ FILE: tests/output-ext/expressions/precedence.f.rs ================================================ fn main() { let _: &'static _ = &(|| { let _ = 0; 0 }); let _ = (match c(o.m(), o as T::T) { 0 if o::c() == 0 => 0, 0 => { return c(o::c()); } }) as T; let _ = if 0 == 0 && 0 == 0 { 0 == 0 && 0 == 0 } else { 0 }; let _ = if 0 == 0 || 0 == 0 { 0 == 0 || 0 == 0 } else { 0 }; let _ = if (0 == 0 || 0 == 0) && (0 == 0 || 0 == 0) { (0 == 0 || 0 == 0) && (0 == 0 || 0 == 0) } else { 0 }; let _ = if 0 == 0 && 0 == 0 && (0 == 0 || 0 == 0) { 0 == 0 && 0 == 0 && (0 == 0 || 0 == 0) } else { 0 }; let _ = if (0 == 0 || 0 == 0) && 0 == 0 && 0 == 0 { (0 == 0 || 0 == 0) && 0 == 0 && 0 == 0 } else { 0 }; let _ = if 0 == 0 && 0 == 0 && 0 == 0 && 0 == 0 { 0 == 0 && 0 == 0 && 0 == 0 && 0 == 0 } else { 0 }; let _ = if 0 == 0 && 0 != 0 { 0 == 0 && 0 != 0 } else { 0 }; let _ = if c!() && c!() { c!() && c!() } else { 0 }; if let _ = 0..|| 0 { } if let _ = 0..&&0 { } if let _ = 0..0 && 0 { } if let _ = { break 0; } && 0 { } _ = if 0 { 0 } else { 0 }; _ = (if 0 { 0 } else { 0 })(); _ = (if 0 { 0 } else { 0 }) as *mut _; for _ in &[c(1)] { c(0); } for _ in -0 + 0..=0 - 0 { } for _ in 0..o.m() { o = o ^ o[o]; } for i in 0..chunk_d - 1 { } unsafe { *o::() = 0; } } type o = ( Box u8) + 'static>, Box (dyn u8 + 'static)>, ); pub extern "ABI" fn f() { c! { pub static T: T = T {}; } #[attr(info)] { o.m(|a_0| ()) } c!(); { } c![]; { } c! {} { } c! {} { } c!(); { } c![]; { } { } { } { } (); { } { } { } (); { } { } { } (); []; { } (); { } [](); // {}()[]; } // { if a { 1 } else { 0 } + if b { 1 } else { 0 } } // { if a { 1 } else { 0 } + ( if b { 1 } else { 0 } ) } [ { ({ 0 }) - 0 }, { { 0; } || 0 }, { { 0; } &&0 }, { { 0; } &&(if 0 { 0 } else { 0 }) }, { { 0; } *0; }, { { 0; } *0 }, { { 0; } (0, 0) }, { { 0; } (0 || 0) && 0 }, { if 0 { } !0 }, { if 0 { } vec![0] }, { if 0 { } *0 || 0 }, { if 0 { } -0 }, { ( if 0 { } ).m() }, { (if 0 { })? }, { if 0 { } || 0 }, { if 0 { } || 0 }, { (if 0 { })? || 0 }, { ( if 0 { } ).m() || 0 }, { if 0 { } else { } |o| 0 }, { 0 + (if 0 { 0 } else { 0 })[0] }, { fn f() { loop { } } o:: as T }, { match 0 { } o[0] }, { match 0 { } (*0 < 0) as T }, { match 0 { } o.m(S { p }); }, { match 0 { } o.m(o.m() + 0); }, { match 0 { } if *0 < 0 { 0 } else { 0 } }, { (0..0) .m((0, 0), |a_0, _| { *o = (o.0, o.0 + o.0); c(*0) }) .m(&(|(a_0, _)| 0)) }, { ( 'label: loop { } ).p }, { (async { 0 + 0 }).await }, { ({ o.p }).p = 0; }, { ({ 0 }) + 0 }, { ({ 0 }) + 0 }, { ({ 0 }) + 0 + 0 }, { (if 0 { 0 } else { 0 }) + (if 0 { 0 } else { 0 }) }, { (if 0 { 0 } else { 0 }) + (if 0 { 0 } else { 0 }) }, { (if 0 { 0 } else { 0 }) + (if 0 { 0 } else { 0 }) }, { (if 0 { 0 } else { 0 })() }, { (if 0 { 0 } else { 0 })() }, { (match 0 { })() }, { (match 0 { })() }, { ({ 0 })() }, { ({ 0 })() }, { ({ 0 }) as u8 }, { ({ 0 }) as u8 }, { if 0 { &0; } &0 as &u8 }, { (if 0 { 0 } else { 0 }) as u8 }, { (if 0 { 0 } else { 0 }) as u8 }, { if 0 { &0; } else { &0; } &0 as &u8 }, { (match 0 { }) as u8 }, { (match 0 { }) as u8 }, { ({ o })[0] }, { ({ o })[0] }, { (if 0 { 0 } else { 0 })[0] }, { (if 0 { 0 } else { 0 })[0] }, { ( match 0 { } )[0] }, { ( match 0 { } )[0] }, { c!() & 0 }, { c![] & 0 }, { c! {} &0 }, { (c! {}) & 0 }, { { 0; } &1 }, { ({ 0 }) & 1 }, { { 0; } ..1 }, { ({ 0 })..1 }, a..b!(), { o.p.0 = 0; }, { o.p.0.0 = 0; }, { (*o.p).0 = 0; }, { (*o.p.0).0 = 0; }, &mut o.p.0, &mut o.p.0.0, &mut (*o.p).0, &mut (*o.p.0).0, o.p.0.m(0), o.p.0.0.m(0), (*o.p).0.m(0), (*o.p.0).0.m(0), o.p + *o + o, c(o.p..o.p + o.p), c( c(o.p, |_| { o.p = 0; }), 0 ), (0 && o.m(o.m()) == 0) || (!0 && o[0].p == 0) || 0 == 0, (0 && o.m(o.m()) == 0) || (!0 && o[0].p == 0) || 0 == 0, // x & y == 0 input // x & (y == 0) javascript precedence // (x & y) == 0 rust precedence (0 & 0) == 0, 0 & (0 == 0), (0 & 0) == 0, (0 as u8) * 0, (0 as u8) * 0, (0 as u8) / 0, (0 as u8) + 0, (0 as u8) + 0, { o = { o = { o = o; }; }; }, { o -= 0 - 0; }, { o -= 0 - 0; }, { o *= 0 * 0; }, { o *= 0 * 0; }, { o *= 0 * 99; }, { o /= 0 / 0; }, { o /= 0 / 0; }, { o &= 0 & 0; }, { o %= 0 % 0; }, { o ^= 0; }, { o ^= 0; }, { o += *0; }, { o += 0 + 0; }, { o <<= 0 << 0; }, { o = 0 - 0; }, { o = 0 * 0 * 0; }, { o = 0 * 0 + 0; }, { o = 0 * 0; }, { o = 0 / 0; }, { o = 0 & 0; }, { o = 0 ^ 0; }, { o = 0 + 0; }, { o = 0 << 0; }, (0 != 0) != 0, (0 != 0) == 0, (0 == 0) != 0, (0 == 0) == 0, 0 + 0 / 0, (0 + 0) >> 0, (0 % 0) * 0, (0 % 0) / 0, (0 % 0) % 0, (0 * 0) % 0, (0 / 0) % 0, 0 / 0 + 0, 0 & 0 & 0, 0 & (0 >> 0), (0 & 0) | 0, 0 ^ 0 ^ 0, (0 << 0) | 0, (0 << 0) >> 0, (0 >> 0) >> 0, 0 | (0 & 0), 0 | 0 | 0, // (0 x 0) x 0 =========================================================== 0 && 0 && 0, (0 && 0) || 0, { (0 && 0) = 0; }, (0 && 0) + 0, (0 && 0) * 0, (0 && 0) & 0, (0 && 0) << 0, (0 && 0) == 0, (0 && 0) > 0, 0 && 0..0, (0 || 0) && 0, 0 || 0 || 0, { (0 || 0) = 0; }, (0 || 0) + 0, (0 || 0) * 0, (0 || 0) & 0, (0 || 0) << 0, (0 || 0) == 0, (0 || 0) > 0, 0 || 0..0, ({ o = 0; }) && 0, ({ o = 0; }) || 0, // (o = 0) = 0, ({ o = 0; }) + 0, ({ o = 0; }) * 0, ({ o = 0; }) & 0, ({ o = 0; }) << 0, ({ o = 0; }) == 0, ({ o = 0; }) > 0, ({ o = 0; })..0, 0 + 0 && 0, 0 + 0 || 0, { (0 + 0) = 0; }, 0 + 0 + 0, (0 + 0) * 0, (0 + 0) & 0, (0 + 0) << 0, 0 + 0 == 0, 0 + 0 > 0, 0 + 0..0, 0 * 0 && 0, 0 * 0 || 0, { (0 * 0) = 0; }, 0 * 0 + 0, 0 * 0 * 0, (0 * 0) & 0, (0 * 0) << 0, 0 * 0 == 0, 0 * 0 > 0, 0 * 0..0, 0 & 0 && 0, 0 & 0 || 0, { (0 & 0) = 0; }, (0 & 0) + 0, (0 & 0) * 0, 0 & 0 & 0, (0 & 0) << 0, (0 & 0) == 0, 0 & 0 > 0, 0 & 0..0, 0 << 0 && 0, 0 << 0 || 0, { (0 << 0) = 0; }, (0 << 0) + 0, (0 << 0) * 0, (0 << 0) & 0, (0 << 0) << 0, (0 << 0) == 0, 0 << 0 > 0, 0 << 0..0, 0 == 0 && 0, 0 == 0 || 0, { (0 == 0) = 0; }, (0 == 0) + 0, (0 == 0) * 0, (0 == 0) & 0, (0 == 0) << 0, (0 == 0) == 0, (0 == 0) > 0, 0 == 0..0, 0 > 0 && 0, 0 > 0 || 0, { (0 > 0) = 0; }, (0 > 0) + 0, (0 > 0) * 0, (0 > 0) & 0, (0 > 0) << 0, (0 > 0) == 0, (0 > 0) > 0, 0 > 0..0, (0..0) && 0, (0..0) || 0, { (0..0) = 0; }, (0..0) + 0, (0..0) * 0, (0..0) & 0, (0..0) << 0, (0..0) == 0, (0..0) > 0, 0..0..0, // 0 x 0 x 0 =========================================================== 0 && 0 && 0, (0 && 0) || 0, { (0 && o) = 0; }, 0 && 0 + 0, 0 && 0 * 0, 0 && 0 & 0, 0 && 0 << 0, 0 && 0 == 0, 0 && 0 > 0, 0 && 0..0, 0 || (0 && 0), 0 || 0 || 0, { (0 || o) = 0; }, 0 || 0 + 0, 0 || 0 * 0, 0 || 0 & 0, 0 || 0 << 0, 0 || 0 == 0, 0 || 0 > 0, 0 || 0..0, { o = 0 && 0; }, { o = 0 || 0; }, { o = { o = 0; }; }, { o = 0 + 0; }, { o = 0 * 0; }, { o = 0 & 0; }, { o = 0 << 0; }, { o = 0 == 0; }, { o = 0 > 0; }, { o = 0..0; }, 0 + 0 && 0, 0 + 0 || 0, { (0 + o) = 0; }, 0 + 0 + 0, 0 + 0 * 0, (0 + 0) & 0, (0 + 0) << 0, 0 + 0 == 0, 0 + 0 > 0, 0 + 0..0, 0 * 0 && 0, 0 * 0 || 0, { (0 * o) = 0; }, 0 * 0 + 0, 0 * 0 * 0, (0 * 0) & 0, (0 * 0) << 0, 0 * 0 == 0, 0 * 0 > 0, 0 * 0..0, 0 & 0 && 0, 0 & 0 || 0, { (0 & o) = 0; }, 0 & (0 + 0), 0 & (0 * 0), 0 & 0 & 0, 0 & (0 << 0), (0 & 0) == 0, 0 & 0 > 0, 0 & 0..0, 0 << 0 && 0, 0 << 0 || 0, { (0 << o) = 0; }, 0 << (0 + 0), 0 << (0 * 0), (0 << 0) & 0, (0 << 0) << 0, (0 << 0) == 0, 0 << 0 > 0, 0 << 0..0, 0 == 0 && 0, 0 == 0 || 0, { (0 == o) = 0; }, 0 == 0 + 0, 0 == 0 * 0, 0 == (0 & 0), 0 == (0 << 0), (0 == 0) == 0, (0 == 0) > 0, 0 == 0..0, 0 > 0 && 0, 0 > 0 || 0, { (0 > o) = 0; }, 0 > 0 + 0, 0 > 0 * 0, 0 > 0 & 0, 0 > 0 << 0, (0 > 0) == 0, (0 > 0) > 0, 0 > 0..0, 0..0 && 0, 0..0 || 0, { 0..o = 0; }, 0..0 + 0, 0..0 * 0, 0..0 & 0, 0..0 << 0, 0..0 == 0, 0..0 > 0, 0..0..0, // 0 x (0 x 0) =========================================================== 0 && 0 && 0, 0 && (0 || 0), 0 && ({ o = 0; }), 0 && 0 + 0, 0 && 0 * 0, 0 && 0 & 0, 0 && 0 << 0, 0 && 0 == 0, 0 && 0 > 0, 0 && (0..0), 0 || (0 && 0), 0 || 0 || 0, 0 || ({ o = 0; }), 0 || 0 + 0, 0 || 0 * 0, 0 || 0 & 0, 0 || 0 << 0, 0 || 0 == 0, 0 || 0 > 0, 0 || (0..0), { o = 0 && 0; }, { o = 0 || 0; }, { o = { o = 0; }; }, { o = 0 + 0; }, { o = 0 * 0; }, { o = 0 & 0; }, { o = 0 << 0; }, { o = 0 == 0; }, { o = 0 > 0; }, { o = 0..0; }, 0 + (0 && 0), 0 + (0 || 0), 0 + ({ o = 0; }), 0 + (0 + 0), 0 + 0 * 0, 0 + (0 & 0), 0 + (0 << 0), 0 + (0 == 0), 0 + (0 > 0), 0 + (0..0), 0 * (0 && 0), 0 * (0 || 0), 0 * ({ o = 0; }), 0 * (0 + 0), 0 * (0 * 0), 0 * (0 & 0), 0 * (0 << 0), 0 * (0 == 0), 0 * (0 > 0), 0 * (0..0), 0 & (0 && 0), 0 & (0 || 0), 0 & ({ o = 0; }), 0 & (0 + 0), 0 & (0 * 0), 0 & (0 & 0), 0 & (0 << 0), 0 & (0 == 0), 0 & (0 > 0), 0 & (0..0), 0 << (0 && 0), 0 << (0 || 0), 0 << ({ o = 0; }), 0 << (0 + 0), 0 << (0 * 0), 0 << (0 & 0), 0 << (0 << 0), 0 << (0 == 0), 0 << (0 > 0), 0 << (0..0), 0 == (0 && 0), 0 == (0 || 0), 0 == ({ o = 0; }), 0 == 0 + 0, 0 == 0 * 0, 0 == (0 & 0), 0 == (0 << 0), 0 == (0 == 0), 0 == (0 > 0), 0 == (0..0), 0 > (0 && 0), 0 > (0 || 0), 0 > ({ o = 0; }), 0 > 0 + 0, 0 > 0 * 0, 0 > 0 & 0, 0 > 0 << 0, 0 > (0 == 0), 0 > (0 > 0), 0 > (0..0), ]; // source: "../../../ext/jinx-rust/tests/samples/expressions/precedence.rs" ================================================ FILE: tests/output-ext/expressions/range.f.rs ================================================ fn q() { if let 0..3 = 0 { } if let 0..Y = 0 { } if let X..3 = 0 { } if let X..Y = 0 { } if let 0..=3 = 0 { } if let 0..=Y = 0 { } if let X..=3 = 0 { } if let X..=Y = 0 { } if let 0..=3 = 0 { } if let 0..=Y = 0 { } if let X..=3 = 0 { } if let X..=Y = 0 { } if let 0.. = 0 { } if let X.. = 0 { } if let ..0 = 0 { } if let ..Y = 0 { } if let ..=3 = 0 { } if let ..=Y = 0 { } let 0..1; let 0..=1; let 0..=1; let ..0; let ..=0; let 0..; for _ in [0..1] { } for _ in [0..=1] { } for _ in [0..] { } for _ in [..1] { } for _ in [..=1] { } for _ in [b..c] { } for _ in [0..1, 2..3] { } for _ in [0..=1] { } for _ in 0..2 { } for _ in 0..=2 { } for _ in 0..=3 { } for _ in 0..=3 + 1 { } for _ in 0..=5 { } for _ in 0..=1 + 5 { } for _ in 1..=1 { } for _ in 1..=1 + 1 { } for _ in 0..13 + 13 { } for _ in 0..=13 - 7 { } for _ in 0..=f() { } for _ in 0..=1 + f() { } let _ = ..11 - 1; let _ = ..11; let _ = ..11; let _ = 1..=11; let _ = f() + 1..=f(); for _ in 1..=ONE { } let a = 0.0..1.1; if let 2..=0 = 3 { } if let 2..=0 = 3 { } if let 2..0 = 3 { } if let ..0 = 3 { } if let ..=0 = 3 { } if let 0.. = 5 { } if let 0..5 = 4 { } if let 0..=5 = 4 { } if let -1..=0 | 2..3 | 4 = x { } for x in -9 + 1..=9 - 2 { } if let [3..=14, ..] = xs { } match 0 { X.. | 0.. | 'a'.. | 0.0f32.. => {} ..=X | ..X => {} ..=0 | ..0 => {} ..='a' | ..'a' => {} ..=0.0f32 | ..0.0f32 => {} ..a => {} a.. => {} 1 | -3..0 => {} y @ (0..5 | 6) => {} y @ -5.. => {} y @ ..-7 => {} box 0..=9 => {} box 10..=15 => {} box 16..=20 => {} 0..1 => {} 0..1 => {} 0..1 => {} } [ 0..1, 0..1, 0..1, 0..1, 1.., .., 0..=1, 0..=1, 0..=1, // 0...1, // &0...9, &10..=15, // box 0...9, box 0..=9, ..1, ..=1, 0u32..10i32, *a.., ]; } fn f() { a.. } fn f() { a..b } fn f() { a()..b() } fn foo(-128..=127: i8) {} // source: "../../../ext/jinx-rust/tests/samples/expressions/range.rs" ================================================ FILE: tests/output-ext/features/arbitrary_enum_discriminant.f.rs ================================================ #![feature(arbitrary_enum_discriminant)] enum Enum { Unit = 1, Tuple() = 2, Struct {} = 3, } #[repr(u8)] enum Enum { Unit = 3, Tuple(u16) = 2, Struct { a: u8, b: u16, } = 1, } #[repr(i8)] enum E2 { A = 7, B = -2, } #[repr(C)] enum E3 { A = 42, B = 100, } #[repr(i128)] enum E4 { A = 0x1223_3445_5667_7889, B = -0x1223_3445_5667_7889, } enum ADT { First(u32, u32), Second(u64), } enum CLike1 { A, B, C, D, } enum CLike2 { A = 5, B = 2, C = 19, D, } #[repr(i8)] enum CLike3 { A = 5, B, C = -1, D, } enum ADT { First(u32, u32), Second(u64), } enum NullablePointer { Something(&'static u32), Nothing, } #[repr(isize)] enum Mixed { Unit = 3, Tuple(u16) = 2, Struct { a: u8, b: u16, } = 1, } enum MyWeirdOption { None = 0, Some(T) = std::mem::size_of::(), } enum Test { A(Box) = 0, B(usize) = (u64::MAX as i128) + 1, } pub enum Foo { A = 2, } pub enum Bar { A(Foo), B, C, } pub enum Size { One = 1, Two = 2, Three = 3, } #[repr(i128)] enum Signed { Zero = 0, Staircase = 0x01_02_03_04_05_06_07_08_09_0a_0b_0c_0d_0e_0f, U64Limit = (u64::MAX as i128) + 1, SmallNegative = -1, BigNegative = i128::MIN, Next, } #[repr(u128)] enum Unsigned { Zero = 0, Staircase = 0x01_02_03_04_05_06_07_08_09_0a_0b_0c_0d_0e_0f, U64Limit = (u64::MAX as u128) + 1, Next, } // source: "../../../ext/jinx-rust/tests/samples/features/arbitrary_enum_discriminant.rs" ================================================ FILE: tests/output-ext/features/associated_type_bounds.f.rs ================================================ #![feature(associated_type_bounds)] type X = A; fn f(_: F) where F: for<'a> Trait {} fn f<'b, F>() where for<'a> F: Iterator + 'b {} trait A: MP { fn f(&self) -> i32 where for<'a> IM: T::T<'a>>>; } // source: "../../../ext/jinx-rust/tests/samples/features/associated_type_bounds.rs" ================================================ FILE: tests/output-ext/features/async_closure.f.rs ================================================ #![feature(async_closure)] const X = async |x| 0; // source: "../../../ext/jinx-rust/tests/samples/features/async_closure.rs" ================================================ FILE: tests/output-ext/features/auto_traits.f.rs ================================================ #![feature(auto_traits)] auto trait T {} unsafe auto trait T {} pub auto trait T {} pub unsafe auto trait T {} auto trait T { #![attr] } #[attr_0] auto trait T { #![attr_1] // comment } // source: "../../../ext/jinx-rust/tests/samples/features/auto_traits.rs" ================================================ FILE: tests/output-ext/features/const_generics_defaults.f.rs ================================================ #![feature(const_generics_defaults)] struct Foo; struct Bar; struct Lots< const N1BlahFooUwU: usize = { 10 + 28 + (1872 / 10) * 3 }, const N2SecondParamOhmyyy: usize = { N1BlahFooUwU / 2 + 10 * 2 } >; struct Lott< const N1BlahFooUwU: usize = { // 1 1 }, const N2SecondParamOhmyyy: usize = { 2 } >; struct NamesRHard; struct FooBar< const LessThan100ButClose: usize = { 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 } >; struct FooBarrrrrrrr< const N: usize = { 13478234326456456444323871 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 } >; // source: "../../../ext/jinx-rust/tests/samples/features/const_generics_defaults.rs" ================================================ FILE: tests/output-ext/features/const_trait_impl.f.rs ================================================ #![feature(const_trait_impl)] impl const T for S {} impl const T for S {} impl const T for S { #![attr] } #[attr_0] impl const T for S { #![attr_1] // comment } fn foo() -> u8 where Self: ~const Bar {} struct S { D: dyn ~const ?Q, E: dyn ~const Q + 'a, F: dyn ~const Q, } struct S< T: ~const ?for<'a> Tr<'a> + 'static + ~const std::ops::Add, T: ~const ?for<'a: 'b> m::Trait<'a> >; trait F { fn bar() where Self: ~const Foo; fn c(); } const fn qux() {} const fn test1() {} const fn test2() {} // source: "../../../ext/jinx-rust/tests/samples/features/const_trait_impl.rs" ================================================ FILE: tests/output-ext/features/decl_macro.f.rs ================================================ #![feature(decl_macro)] macro m() {} // source: "../../../ext/jinx-rust/tests/samples/features/decl_macro.rs" ================================================ FILE: tests/output-ext/features/destructuring_assignment.f.rs ================================================ #![feature(destructuring_assignment)] fn main() { _ = 1; _ = DropRecorder(1); _val = DropRecorder(2); (_,) = (1, 2); (.., a) = (1, 2); (..) = (3, 4); ((a, b), c) = ((2, 3), d); ((a, .., b), .., ..) = ((4, 5), ()); (a, b) = (0, 1); (*foo(&mut x), *foo(&mut x)) = (5, 6); (a, _) = (8, 9); (a, .., b) = (1, 2); (a, a, b) = (1, 2); (a, b) += (3, 4); (a, b) = (0, 1); (a, b) = (3, 4); (b, ..) = (5, 6, 7); (b, a) = (a, b); (C, ..) = (0, 1); (c, d) = ("c".to_owned(), "d".to_owned()); (d, c) = (c, d); test() = TupleStruct(0, 0); (x, _) = (DropRecorder(3), DropRecorder(4)); [_, a, _] = [1, 2, 3]; [_] = [1, 2]; [..] = [1, 2, 3]; [a, .., b, ..] = [0, 1]; [a, .., b, c] = [1, 2, 3, 4, 5]; [a, a, b] = [1, 2]; [a, b] += [3, 4]; [a, b] = [0, 1]; [a, b] = [3, 4]; [c, ..] = [5, 6, 6]; as Test>::test() = TupleStruct(0, 0); Alias::SingleVariant(a, b) = Alias::SingleVariant(9, 10); Enum::SingleVariant(_) = Enum::SingleVariant(1, 2); Enum::SingleVariant(a, .., b, ..) = Enum::SingleVariant(0, 1); Enum::SingleVariant(a, a, b) = Enum::SingleVariant(1, 2); Enum::SingleVariant(a, b) = Enum::SingleVariant(7, 8); (S { x: a, ..s } = S { x: 3, y: 4 }); (S { x: a, y: b } += s); (S { x: a, y: b } = s); (Struct { .. } = Struct { a: 1, b: 4 }); (Struct { a, .. } = Struct { a: 1, b: 3 }); Struct { a, .. }; (Struct { a, ..d } = Struct { a: 1, b: 2 }); (Struct { a, b } = Struct { a: 0, b: 1 }); (Struct { a, b, c } = Struct { a: 0, b: 1 }); (Struct { a: _, b } = Struct { a: 1, b: 2 }); (Struct { a: b, b: a } = Struct { a: 1, b: 2 }); (Struct { a: TupleStruct((a, b), c), b: [d] } = Struct { a: TupleStruct((0, 1), 2), b: [3], }); test() = TupleStruct(0, 0); TupleStruct(_, a) = TupleStruct(2, 2); TupleStruct(_) = TupleStruct(1, 2); TupleStruct(..) = TupleStruct(3, 4); TupleStruct(5, 6).assign(&mut a, &mut b); TupleStruct(a, .., b, ..) = TupleStruct(0, 1); TupleStruct(a, .., b) = TupleStruct(1, 2); TupleStruct(a, a, b) = TupleStruct(1, 2); TupleStruct(a, b) = TupleStruct(0, 1); } // source: "../../../ext/jinx-rust/tests/samples/features/destructuring_assignment.rs" ================================================ FILE: tests/output-ext/features/generators.f.rs ================================================ #![feature(generators)] [ static move || { let a = A::> { b: E::r() }; yield (); }, |_| { a!("-> {}", { yield; }); }, ]; // source: "../../../ext/jinx-rust/tests/samples/features/generators.rs" ================================================ FILE: tests/output-ext/features/if_let_guard.f.rs ================================================ #![feature(if_let_guard)] fn main() { match e { A(ref u) if let a = b && let c = d => {} A(ref u) if let x { a: b, c: d } = e && let f = g => {} A(a) if let A(b) = a && let A(p) = b && p == z => {} } match e { A(a) if let A(b) = a && let A(p) = b && p == z => {} _ => {} } } // source: "../../../ext/jinx-rust/tests/samples/features/if_let_guard.rs" ================================================ FILE: tests/output-ext/features/inline_const.f.rs ================================================ #![feature(inline_const_pat)] fn f() { const {} } // source: "../../../ext/jinx-rust/tests/samples/features/inline_const.rs" ================================================ FILE: tests/output-ext/features/inline_const_pat.f.rs ================================================ #![feature(inline_const_pat)] fn f() { match () { y @ 0..const { 5 + 1 } => {} 1..=const { two() } => {} const { one() } => {} } } // source: "../../../ext/jinx-rust/tests/samples/features/inline_const_pat.rs" ================================================ FILE: tests/output-ext/features/let_chains.f.rs ================================================ #![feature(let_chains)] fn f() { if h && let A(x) = e { } if a && let c = d && 1 == 1 { } if a && let c = d && 1 == 1 { } if true && let x = 1 { let _ = x; } if let a = b && let c = d && 1 == 1 { } if let A { .. } = d(7, B) && let C { .. } = d(8, D) { } if let a = &e && let A(ref b) = a && let B = b.c { } if let a = b && let c = d && 1 == 1 { } if let A(_) = d(2, B(2)).c && let D { .. } = d(3, E) { } else { } if let A(a) = e && let A(b) = a && let A(p) = b && p == z { } else { } if let A(v) = x && v.q() { } if let A(_) = Q(0) && let E(_) = R(1) { } else if let G(1) = F(2) { } if let A(ref a) = e && let b = a && let _p = b { } if let A(ref a) = e && let R { c: d, y: _ } = a && let B = d { } while let a = &e && let A(ref b) = a && let B = b.c {} while let A(a) = e && let A(b) = a && let A(p) = b && p == z {} while let A(ref a) = e && let b = a && let _p = b {} while let A(ref a) = e && let R { c: d, y: _ } = a && let B = d {} } // source: "../../../ext/jinx-rust/tests/samples/features/let_chains.rs" ================================================ FILE: tests/output-ext/features/let_else.f.rs ================================================ #![feature(let_else)] let a = 1 else { 2 }; // source: "../../../ext/jinx-rust/tests/samples/features/let_else.rs" ================================================ FILE: tests/output-ext/features/negative_impls.f.rs ================================================ #![feature(negative_impls)] impl !Send for Test {} impl !Send for Foo {} impl !Sync for Foo {} impl !std::marker::Unpin for Foo {} impl !std::panic::RefUnwindSafe for Foo {} impl !std::panic::UnwindSafe for Foo {} impl !A::B for C where T: Copy {} impl !A for B where T: Sync {} impl !Send for A {} impl !Sync for A {} impl<'a, T> !MyPredicate<'a> for &T where T: 'a {} impl !Foo for &T where T: 'static {} impl !Future for Option where E: Sized {} // source: "../../../ext/jinx-rust/tests/samples/features/negative_impls.rs" ================================================ FILE: tests/output-ext/features/trait_alias.f.rs ================================================ #![feature(trait_alias)] trait A =; trait A = std::fmt::Debug + Send; // source: "../../../ext/jinx-rust/tests/samples/features/trait_alias.rs" ================================================ FILE: tests/output-ext/macro/attributes.f.rs ================================================ // a /// b fn a() {} fn b() { //! c } ////////////////////////////////// // d /// let heart = '❤️'; ////////////////////////////////// /// e /// f fn c() {} /* * g */ /** * h */ fn d() {} fn e() { /*! * i */ //! ```a //! b //! ``` } /********************************/ /* * j */ /********************************/ /** * k */ fn f() {} // before #[macro_use] // after extern crate x; a! { /// line 2 /// line 3 #[a(b, c(d(e(f = "g", h = "i"))))] pub enum X { /// line 6 /// line 7 A(B), /// line 10 C(D), } } // 5 comments inside a!{} /// ____ /// ____ #[attr_0] pub type A = Vec; #[attr_1] extern crate b as d; #![attr_2] #![attr_3] /** * directly below attr_2 and 1 line above attr_3 */ fn attr_3_3a_target() { #![attr_3a] #[attr_3b] fn attr_3b_target() {} #[attr_3c] fn attr_3c_target() {} } trait foo_C { #![attr_4] } #![attr_6] #[attr_5] fn main() { // comment #[attr] (); #[attr] [1; 4]; #[attr] Foo { data: () }; #[attr] if let Some(_) = Some(true) { } #[attr] if let Some(_) = Some(true) { } else if let Some(false) = Some(true) { } #[attr] if true { } #[attr] let _ = 0; #[attr] if true { } else if false { } else { } { #![attr] foo(); } #[attr] if true { } #[attr] (0, 1); #[attr] (0,); #[attr] 0; #[attr] [1, 2, 3]; #[attr] { #![attr] } #[attr] { foo(); } #[attr] 0; #[attr] expr_mac!(); #[attr] foo(); #[attr] let x = 1; #[attr] match () { _ => {} } #[attr] match () { #![attr] _ => (), } #[attr] unsafe {/**/} || #[attr] { return; }; let a = #[attr] [1; 4]; let a = #[attr] box 0; let a = #[attr] [1, 2, 3]; let a = #[attr] Foo { data: () }; let a = (#[attr] s).data; let a = (#[attr] t).0; let a = (#[attr] v)[0]; let a = #[attr] -0i32; let a = #[attr] !0; let a = #[attr] 'c'; let a = #[attr] ..; let a = #[attr] ..0; let a = #[attr] (#[attr] 0,); let a = #[attr] (#[attr] 0, 0); let a = #[attr] (); let a = #[attr] (0, 0); let a = #[attr] (0,); let a = #[attr] 0..; let a = #[attr] 0..0; let a = #[attr] 0; let a = #[attr] 0; let a = #[attr] [0, 0]; let a = #[attr] [0; 0]; let a = #[attr] { #![attr] }; let a = #[attr] { #![attr] let _ = (); () }; let a = #[attr] { #![attr] let _ = (); }; let a = #[attr] &(#[attr] 0); let a = #[attr] &0; let a = #[attr] &mut (#[attr] 0); let a = #[attr] &mut 0; let a = #[attr] || { #![attr] #[attr] () }; let a = #[attr] || (#[attr] ()); let a = #[attr] 0 + (#[attr] 0); let a = #[attr] 0 as usize; let a = #[attr] 0; let a = #[attr] 0..; let a = #[attr] 0..(#[attr] 0); let a = #[attr] (1i32).clone(); let a = #[attr] x! {}; let a = #[attr] x!(); let a = #[attr] x![]; let a = #[attr] false; let a = #[attr] x(); let a = #[attr] x!(); let a = #[attr] x!( #![attr] ); let a = #[attr] x![]; let a = #[attr] x![ #![attr] ]; let a = #[attr] x! {}; let a = #[attr] x! { #![attr] }; let a = #[attr] Foo { ..s }; let a = #[attr] Foo { data: (), ..s }; let a = #[attr] Foo { data: () }; let a = #[attr] for _ in 0..0 { #![attr] }; let a = #[attr] loop { #![attr] }; let a = #[attr] match 0 { #![attr] () => (), }; let a = #[attr] match 0 { #![attr] _ => (), }; let a = #[attr] move || { #![attr] #[attr] () }; let a = #[attr] move || (#[attr] ()); let a = #[attr] s.data; let a = #[attr] t.0; let a = #[attr] v[0]; let a = #[attr] while false { #![attr] }; let a = #[attr] while let None = Some(()) { #![attr] }; let a = #[attr] { x += 15; }; let a = #[attr] { x += 15; }; let a = #[attr] { x = 15; }; let a = #[attr] { x = 15; }; let a: [(); 0] = #[attr] []; let a: fn(&u32) -> u32 = #[attr] std::clone::Clone::clone; let a = #[attr] 1; let a = | #[allow(C)] a: u32, #[cfg(something)] b: i32, #[cfg_attr(something, cfg(nothing))] #[deny(C)] c: i32 | {}; qux(3 + (#[attr] 2)); foo3(x, #[attr] y, z); while false { let _ = #[attr] { continue; }; } while true { let _ = #[attr] { break; }; } match (Q { #[attr] C: 1 }) { Q { #[attr] C } => {} Q(#[attr] C) => {} #[attr] _ => {} } } static X: &[Y] = &[#[a(b = "c")] 0]; #[attr] const C: C = C { #[attr] field: 0, #[attr] field: 1 }; #[attr] struct S; #[attr] struct I { #[attr] i: u8, #[attr] pub i: u8, } #[attr] struct I(#[attr] u8, #[attr] pub u8); #[attr] struct BreaksWithComment( #[attr] u8, #[attr] // comment pub u8, ); struct C { #[attr] /// below attr a: b, } struct Q { #[attr] C: i32, } struct A<#[attr] 'a>(); struct A<#[attr] I>(I); enum E { #[attr] C(i32), } enum E<#[attr] 'b> {} enum E<#[attr] J> {} trait T { #![attr] } trait T<#[attr] 'c> {} trait T<#[attr] K> {} type Y<#[attr] 'd> = (); type Y<#[attr] L> = (); #[attr] type A = fn(#[a1] u8, #[a2] ...); impl<#[attr] 'e> A<'e> {} impl<#[attr] M> A {} impl<#[attr] 'f> T<'f> for A<'f> {} impl<#[attr] N> T for A {} #[attr] #[attr] macro_rules! m_e {} #[attr] macro_rules! m {} #[attr] fn f() {} #[attr] fn f(#[a1] a: u8) { let f = |#[a2] W(x), #[a3] y| (); } fn f<#[attr] 'g>() {} fn f<'e, #[attr] 'g>() {} fn f<#[attr] G>() {} fn f() {} fn f() where for<#[attr] 'i> X: for<#[attr] 'i> Y {} fn f(#[d(true)] a: i32, #[a2] b: i32, #[what = "how"] c: u32) {} fn f(#[a1] #[a2] a: i32, #[what = "how"] b: i32, #[e(true)] c: u32) {} fn b(#[cfg(x)] x: i32, y: i32) -> i32 {} fn f( #[a1] #[a2] &self, #[a1] #[a2] a: i32, #[what = "how"] b: i32, #[f(true)] c: u32 ) {} fn c(#[cfg(foo)] &mut self, #[deny(C)] b: i32) {} #[a = "q"] #[b = "q"] mod a { #![c = "q"] } #[a = "q"] pub static X: u8 = (); #[a = "q"] pub fn f() {} #[a = "q"] pub mod a {} #[a = "q"] extern "C" {} //(#[b(c(#(d = #e),*))]); a!(#[b(c(#(d = #e),*))]); //(#![b(c(#(d = #e),*))]); a!( #![b(c(#(d = #e),*))] ); #[attr] extern "C" { fn ffi(#[a1] a: i32, #[a2] ...); } #[attr] unsafe extern "C" fn f(a: i32, #[a1] mut args: ...) {} impl W { #[attr] fn f(#[a1] self, #[a2] a: u8) {} #[attr] fn f(#[a1] &self, #[a2] a: u8) {} #[attr] fn f<'a>(#[a1] &'a mut self, #[a2] a: u8) {} #[attr] fn f<'a>(#[a1] self: Box, #[a2] a: u8) {} #[attr] fn f(#[a1] #[a2] a: u8, #[a3] b: u8) {} } trait A { #[attr] fn f(#[a1] self, #[a2] a: u8); #[attr] fn f(#[a1] &self, #[a2] a: u8); #[attr] fn f<'a>(#[a1] &'a mut self, #[a2] a: u8); #[attr] fn f<'a>(#[a1] self: Box, #[a2] a: u8, #[a3] b: Vec); #[attr] fn f(#[a1] #[a2] a: u8, #[a3] b: u8); } // directly above #![doc(... #![doc( ___ = "____________________________________________________________", ___________________ = "_________________________________________________", ______________ = "_________________________________________________", ___________________ = "_________________________________________________", a(b(c(d))) )] //! 1 line below #![doc(... #![attr] //! aaa // bbb // ccc #![attr(b)] // ddd /// eee /// eee /// eee /// eee /// fff impl Bar { /// 0 /// 1 /// 2 /// 3 #[attr] #[doc = " ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ ___ "] fn foo(&mut self) -> isize {} /// \n 4 /// 5 /// 6 /// \n\n 7 /// 8 /// 9 pub fn f2(self) { (foo, bar) } #[attr] fn f3(self) -> Q {} /// \n 10 \n #[attrib1] /// 11 #[attrib2] // 12 /// 13 fn f4(self) -> A {} // \n 14 #[a(b = "c")] fn f5(self) -> X {} } struct Foo { #[derive(A, B, C, D, E)] foo: usize, } // expected_{x} comments inside each attribute #[should_panic] #[should_panic(expected_0 = "(")] #[should_panic(expected_1 = /* ( */ "(")] #[should_panic( /* ((((( */ expected_4 = /* ((((( */ /* ((((( */ "(" /* ((((( */ )] #[should_panic( /* (((((((( */ /* (((((((((()(((((((( */ expected_3 = "(" // (((((((( )] fn f() {} fn f() { #[allow(unreachable_code)] // right of attr Some(Err(error)); #[allow(unreachable_code)] // below attr Some(Err(error)); } fn f() { #![this_is_an_inner_attribute(foo)] foo(); } impl InnerAttributes() { #![this_is_an_inner_attribute(foo)] fn f() {} } mod InnerAttributes { #![this_is_an_inner_attribute(foo)] } fn f() { // Local #[attr(on(local))] let x = 3; // Item #[attr(on(item))] use foo; // Expr #[attr(on(expr))] { } // Semi #[attr(on(semi))] foo(); // Mac #[attr(on(mac))] foo!(); } #[derive( Add, Sub, Mul, Div, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Debug, Hash, Serialize, Mul )] /// #[derive( Add, Sub, Mul, Div, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Debug, Hash, Serialize, Deserialize )] pub struct HP(pub u8); // struct A { #[doc = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"] b: i32, } #[cfg( feature = "this_line_is_101_characters_long_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" )] pub fn foo() {} // #[clippy::bar] #[clippy::bar(a, b, c)] pub fn foo() {} mod v { #[derive(Debug, StructOpt)] #[structopt(about = "x")] pub struct Params { #[structopt(help = "x")] server: String, #[structopt(help = "x")] first_name: String, #[structopt(help = "x")] last_name: String, #[structopt( short = "j", long = "job", help = "The job to look at", parse(try_from_str) )] job: Option, } } #[cfg( not( all( feature = "std", any( target_os = "linux", target_os = "android", target_os = "netbsd", target_os = "dragonfly", target_os = "haiku", target_os = "emscripten", target_os = "solaris", target_os = "cloudabi", target_os = "macos", target_os = "ios", target_os = "freebsd", target_os = "openbsd", target_os = "redox", target_os = "fuchsia", windows, all(target_arch = "wasm32", feature = "stdweb"), all(target_arch = "wasm32", feature = "wasm-bindgen") ) ) ) )] type Os = NoSource; fn stmt_expr_attributes() { let foo; #[must_use] foo = false; } fn a() { match () { #![attr] } match () {#[attr]} } fn x() { match MyEnum { } } // 2 comments inside this attribute #[derive( /* ---------- ------------------------------------------------------------------- --------- */ Debug, Clone, /* --------------- */ Eq, PartialEq )] struct Foo { a: i32, b: T, } // 1 comment inside this attribute #[derive(/*Debug, */ Clone)] struct Foo; #[cfg( all( any( target_arch = "x86", target_arch = "x86_64", target_arch = "aarch64", target_arch = "powerpc64", target_arch = "powerpc64le", target_arch = "mips64", target_arch = "s390x", target_arch = "sparc64" ) ) )] const MIN_ALIGN: usize = 16; // source: "../../../ext/jinx-rust/tests/samples/macro/attributes.rs" ================================================ FILE: tests/output-ext/macro/macro.invocation.f.rs ================================================ declare_clippy_lint! { /// ### q /// ```rust /// let b: Vec<&str> = vec![]; /// if !b.is_empty() { /// panic!(q: {:?}", b); /// } /// ``` /// Use instead: /// ```rust /// let b: Vec<&str> = vec![]; /// assert!(b.is_empty(), "there are sad people: {:?}", b); /// ``` #[clippy::version = "1.57.0"] pub MANUAL_ASSERT, pedantic, "`panic!` and only a `panic!` in `if`-then statement" } fn aux(xs: Xs, ys: Ys) -> Expr!(Xs + Ys) where Xs: Add { xs + ys } declare_lint_pass!(Attributes => [ INLINE_ALWAYS, DEPRECATED_SEMVER, USELESS_ATTRIBUTE, BLANKET_CLIPPY_RESTRICTION_LINTS, ]); fn main() { let xs: HList!(&str, bool, Vec) = hlist!("foo", false, vec![]); let ys: HList!(u64, [u8; 3], ()) = hlist!(0, [0, 1, 2], ()); let zs: Expr!( HList![&str] + HList![bool] + HList![Vec] + (HList![u64] + HList![[u8; 3], ()]) + HList![] ) = aux(xs, ys); higher_order!(subst ($x:expr, $y:expr, $foo:expr) => (($x + $y, $foo))); assert_eq!(zs, hlist!["foo", false, vec![], 0, [0, 1, 2], ()]); quote!(fn $name() -> bool { true }); impl_lint_pass!(Arithmetic => [INTEGER_ARITHMETIC, FLOAT_ARITHMETIC]); let result = quote! { macro_rules! generated_foo { (1 $$x:expr $$($$y:tt,)* $$(= $$z:tt)*) => {}; } }; if !matches!( macro_name.as_str(), "assert_eq" | "debug_assert_eq" | "assert_ne" | "debug_assert_ne" ) { } if matches!(cx.tcx.type_of(id).kind(), ty::Adt(adt, _) if ty_adt.did() == adt.did()) { } if !matches!( get_expr_use_or_unification_node(tcx, expr), None | Some(( Node::Stmt(Stmt { kind: StmtKind::Expr(_) | StmtKind::Semi(_) | StmtKind::Local(Local { pat: Pat { kind: PatKind::Wild, .. }, .. }), .. }), _, )) ) { } if_chain! { if let ExprKind::If(cond, then, None) = expr.kind; if !matches!(cond.kind, ExprKind::Let(_)); if !expr.span.from_expansion(); let then = peel_blocks_with_stmt(then); if let Some(macro_call) = root_macro_call(then.span); if cx.tcx.item_name(macro_call.def_id) == sym::panic; if !cx.tcx.sess.source_map().is_multiline(cond.span); if let Some(format_args) = FormatArgsExpn::find_nested(cx, then, macro_call.expn); then { let mut applicability = Applicability::MachineApplicable; let format_args_snip = snippet_with_applicability(cx, format_args.inputs_span(), "..", &mut applicability); let cond = cond.peel_drop_temps(); let (cond, not) = match cond.kind { ExprKind::Unary(UnOp::Not, e) => (e, ""), _ => (cond, "!"), }; let cond_sugg = sugg::Sugg::hir_with_applicability(cx, cond, "..", &mut applicability).maybe_par(); let sugg = format!("assert!({not}{cond_sugg}, {format_args_snip});"); span_lint_and_sugg( cx, MANUAL_ASSERT, expr.span, "only a `panic!` in `if`-then statement", "try", sugg, Applicability::MachineApplicable, ); } } if_chain! { if meets_msrv(msrv.as_ref(), &msrvs::TOOL_ATTRIBUTES); // check cfg_attr if attr.has_name(sym::cfg_attr); if let Some(items) = attr.meta_item_list(); if items.len() == 2; // check for `rustfmt` if let Some(feature_item) = items[0].meta_item(); if feature_item.has_name(sym::rustfmt); // check for `rustfmt_skip` and `rustfmt::skip` if let Some(skip_item) = &items[1].meta_item(); if skip_item.has_name(sym!(rustfmt_skip)) || skip_item.path.segments.last().expect("empty path in attribute").ident.name == sym::skip; // Only lint outer attributes, because custom inner attributes are unstable // Tracking issue: https://github.com/rust-lang/rust/issues/54726 if attr.style == AttrStyle::Outer; then { span_lint_and_sugg( cx, DEPRECATED_CFG_ATTR, attr.span, "`cfg_attr` is deprecated for rustfmt and got replaced by tool attributes", "use", "#[rustfmt::skip]".to_string(), Applicability::MachineApplicable, ); } } if_chain! { if let ExprKind::Binary(ref op, left, right) = &expr.kind; if let Some((candidate, check)) = normalize_le_ge(op, left, right); if let Some((from, to)) = get_types_from_cast(check, INTS, "max_value", "MAX"); then { Conversion::try_new(candidate, from, to) } else { None } } let help = format!( "because `{}` is the {} value for this type, {}", snippet(cx, culprit.expr.span, "x"), match culprit.which { ExtremeType::Minimum => "minimum", ExtremeType::Maximum => "maximum", }, conclusion ); let msg = format!( "this `{}` can be collapsed into the outer `{}`", if matches!(inner, IfLetOrMatch::Match(..)) { "match" } else { "if let" }, if outer_is_match { "match" } else { "if let" } ); let mut contents = format!( indoc! { " #![warn(clippy::{})] fn main() {{ // test code goes here }} " }, lint_name ); format!( "store.register_{lint_pass}_pass(move || Box::new({module_name}::{camel_name}::new(msrv)));\n ", lint_pass = lint.pass, module_name = lint.name, camel_name = to_camel_case(lint.name) ); format!( indoc! { r#" # {} [package] name = "{}" version = "0.1.0" publish = false [workspace] "# }, hint, lint_name ); match iter.next() { // #[clippy::version = "version"] pub Some((TokenKind::Pound, _)) => { match_tokens!(iter, OpenBracket Ident Colon Colon Ident Eq Literal{..} CloseBracket Ident); } // pub Some((TokenKind::Ident, _)) => (), _ => { continue; } } let (name, group, desc) = match_tokens!( iter, // LINT_NAME Ident(name) Comma // group, Ident(group) Comma // "description" } Literal{..}(desc) CloseBrace // #[clippy::version = "version"] Pound OpenBracket Ident Colon Colon Ident Eq Literal{..} CloseBracket // pub LINT_NAME, Ident Ident(name) Comma // "description" Literal{kind: LiteralKind::Str{..},..}(reason) // ("old_name", Whitespace OpenParen Literal{kind: LiteralKind::Str{..},..}(old_name) Comma // "new_name"), Whitespace Literal{kind: LiteralKind::Str{..},..}(new_name) CloseParen Comma ); info!( //debug "{}: sending function_code={:04x} data={:04x} crc=0x{:04X} data={:02X?}", self.name, function_code, data, crc, output_cmd ); } cfg_if! { if #[cfg(feature = "std_detect_file_io")] { #[cfg_attr(test, macro_use(println))] extern crate std; #[allow(unused_imports)] use std::{ arch, fs, io, mem, sync }; } else { #[cfg(test)] #[macro_use(println)] extern crate std; #[allow(unused_imports)] use core::{ arch, mem, sync }; } } op_utils! { Add; AddAssign; Sub; SubAssign; Mul; MulAssign; Div; DivAssign; Rem; RemAssign; BitXor; BitXorAssign; BitAnd; BitAndAssign; BitOr; BitOrAssign; Shl; ShlAssign; Shr; ShrAssign; } msrv_aliases! { 1,53,0 { OR_PATTERNS, MANUAL_BITS } 1,52,0 { STR_SPLIT_ONCE } 1,51,0 { BORROW_AS_PTR, UNSIGNED_ABS } 1,50,0 { BOOL_THEN } 1,47,0 { TAU } 1,46,0 { CONST_IF_MATCH } 1,45,0 { STR_STRIP_PREFIX } 1,43,0 { LOG2_10, LOG10_2 } 1,42,0 { MATCHES_MACRO, SLICE_PATTERNS, PTR_SLICE_RAW_PARTS } 1,41,0 { RE_REBALANCING_COHERENCE, RESULT_MAP_OR_ELSE } 1,40,0 { MEM_TAKE, NON_EXHAUSTIVE, OPTION_AS_DEREF } 1,38,0 { POINTER_CAST } 1,37,0 { TYPE_ALIAS_ENUM_VARIANTS } 1,36,0 { ITERATOR_COPIED } 1,35,0 { OPTION_COPIED, RANGE_CONTAINS } 1,34,0 { TRY_FROM } 1,30,0 { ITERATOR_FIND_MAP, TOOL_ATTRIBUTES } 1,28,0 { FROM_BOOL } 1,17,0 { FIELD_INIT_SHORTHAND, STATIC_IN_CONST, EXPECT_ERR } 1,16,0 { STR_REPEAT } 1,24,0 { IS_ASCII_DIGIT } } kot! { struct W { foo: u8, bar: u16, } impl Clone for W { fn clone() -> W { panic!(); } } } kot! { a(mushkins mushkins mushkins mushkins mushkins mushkins mushkins mushkins mushkins mushkins) a [mushkins mushkins mushkins mushkins mushkins mushkins mushkins mushkins mushkins mushkins] a { mushkins mushkins mushkins mushkins mushkins mushkins mushkins mushkins mushkins mushkins } a } kot!(mushkins mushkins mushkins mushkins mushkins mushkins mushkins mushkins mushkins mushkins); kot![mushkins mushkins mushkins mushkins mushkins mushkins mushkins mushkins mushkins mushkins]; kot! { mushkins; mushkins; mushkins; mushkins; mushkins; mushkins; mushkins; mushkins; mushkins; mushkins; } #[rustc_dummy(mushkins mushkins mushkins mushkins mushkins mushkins mushkins mushkins mushkins mushkins)] #[rustc_dummy[mushkins mushkins mushkins mushkins mushkins mushkins mushkins mushkins mushkins mushkins]] #[rustc_dummy { mushkins mushkins mushkins mushkins mushkins mushkins mushkins mushkins mushkins mushkins }] #[rustc_dummy = "mushkins mushkins mushkins mushkins mushkins mushkins mushkins mushkins mushkins mushkins"] match t.kind() { ty::Int(i) => find_fit!(i, val, negative, I8 => [U8] => [I16, I32, I64, I128], I16 => [U16] => [I32, I64, I128], I32 => [U32] => [I64, I128], I64 => [U64] => [I128], I128 => [U128] => []), ty::Uint(u) => find_fit!(u, val, negative, U8 => [U8, U16, U32, U64, U128] => [], U16 => [U16, U32, U64, U128] => [], U32 => [U32, U64, U128] => [], U64 => [U64, U128] => [], U128 => [U128] => []), _ => None, } x! { /// [d]: ../b.md#a pub G, d, "c", @d = x { b: "a", }; } throw_span_err!( attr.span().unwrap(), &format!( "the `#[{}{}]` attribute can only be applied to fields of type {}", name, match meta { Meta::Path(_) => "", Meta::NameValue(_) => " = ...", Meta::List(_) => "(...)", }, ty_name ) ); provide! { <'tcx> tcx, def_id, other, cdata, explicit_item_bounds => { table } explicit_predicates_of => { table } adt_destructor => { let _ = cdata; tcx.calculate_dtor(def_id, |_,_| Ok(())) } extern_crate => { let r = *cdata.extern_crate.lock(); r.map(|c| &*tcx.arena.alloc(c)) } reachable_non_generics => { let reachable_non_generics = tcx .exported_symbols(cdata.cnum) .iter() .filter_map(|&(exported_symbol, export_info)| { if let ExportedSymbol::NonGeneric(def_id) = exported_symbol { Some((def_id, export_info)) } else { None } }) .collect(); reachable_non_generics } dep_kind => { let r = *cdata.dep_kind.lock(); r } module_children => { let mut result = SmallVec::<[_; 8]>::new(); cdata.for_each_module_child(def_id.index, |child| result.push(child), tcx.sess); tcx.arena.alloc_slice(&result) } missing_extern_crate_item => { let r = matches!(*cdata.extern_crate.borrow(), Some(extern_crate) if !extern_crate.is_direct()); r } used_crate_source => { Lrc::clone(&cdata.source) } debugger_visualizers => { cdata.get_debugger_visualizers() } exported_symbols => { let syms = cdata.exported_symbols(tcx); // a syms } } cfg_if::cfg_if! { if #[cfg(unix)] { } else if #[cfg( any( target_os = "hermit", target_os = "solid_asp3", all(target_vendor = "fortanix", target_env = "sgx") ) )] { } else if #[cfg(all(windows, not(miri)))] { } } ast_fragments! { Expr(P) { "expression"; one fn visit_expr; fn visit_expr; fn make_expr; } Pat(P) { "pattern"; one fn visit_pat; fn visit_pat; fn make_pat; } Ty(P) { "type"; one fn visit_ty; fn visit_ty; fn make_ty; } Stmts(SmallVec<[ast::Stmt; 1]>) { "statement"; many fn flat_map_stmt; fn visit_stmt(); fn make_stmts; } Items(SmallVec<[P; 1]>) { "item"; many fn flat_map_item; fn visit_item(); fn make_items; } TraitItems(SmallVec<[P; 1]>) { "trait item"; many fn flat_map_trait_item; fn visit_assoc_item(AssocCtxt::Trait); fn make_trait_items; } ImplItems(SmallVec<[P; 1]>) { "impl item"; many fn flat_map_impl_item; fn visit_assoc_item(AssocCtxt::Impl); fn make_impl_items; } ForeignItems(SmallVec<[P; 1]>) { "foreign item"; many fn flat_map_foreign_item; fn visit_foreign_item(); fn make_foreign_items; } Arms(SmallVec<[ast::Arm; 1]>) { "match arm"; many fn flat_map_arm; fn visit_arm(); fn make_arms; } ExprFields(SmallVec<[ast::ExprField; 1]>) { "field expression"; many fn flat_map_expr_field; fn visit_expr_field(); fn make_expr_fields; } PatFields(SmallVec<[ast::PatField; 1]>) { "field pattern"; many fn flat_map_pat_field; fn visit_pat_field(); fn make_pat_fields; } GenericParams(SmallVec<[ast::GenericParam; 1]>) { "generic parameter"; many fn flat_map_generic_param; fn visit_generic_param(); fn make_generic_params; } Params(SmallVec<[ast::Param; 1]>) { "function parameter"; many fn flat_map_param; fn visit_param(); fn make_params; } FieldDefs(SmallVec<[ast::FieldDef; 1]>) { "field"; many fn flat_map_field_def; fn visit_field_def(); fn make_field_defs; } Variants(SmallVec<[ast::Variant; 1]>) { "variant"; many fn flat_map_variant; fn visit_variant(); fn make_variants; } Crate(ast::Crate) { "crate"; one fn visit_crate; fn visit_crate; fn make_crate; } } sides_mapping_methods! { MainStartCrossStart::InlineStartBlockStart => { main_start <=> inline_start, cross_start <=> block_start, main_end <=> inline_end, cross_end <=> block_end, } } fuzz_target!(|data: &[u8]| ( if let Some(first) = data.first() { let index = *first as usize; if index >= ENCODINGS.len() { return; } let encoding = ENCODINGS[index]; dispatch_test(encoding, &data[1..]); } )); assert_eq!(count_compound_ops!(foo<=>bar << { }; } macro_rules! bracket { () => { }; } macro_rules! paren { () => { }; } macro_rules! macro_rules { () => {}; } macro_rules! {} macro m($S:ident, $x:ident) {} pub macro create_struct($a:ident) {} pub(crate) macro mac { ($arg:expr) => { $arg + $arg }; } // source: "../../../ext/jinx-rust/tests/samples/macro/macro.item.rs" ================================================ FILE: tests/output-ext/macro/macro.match.f.rs ================================================ pub macro c { () => (); // _______ // _______ ($msg:expr $(,)?) => (); ( $fmt:expr, $($arg:tt)* ) => (); ($foo:expr) => {}; ($($t:tt)+) => (); ($left:expr, $(|)? $($pattern:pat_param)|+ $(if $guard:expr)? $(,)?) => (); ( $left:expr, $(|)? $($pattern:pat_param)|+ $(if $guard:expr)?, $($arg:tt)+ ) => (); // ______ ("{}", $aze:expr $(,)?) => (); ($($t:tt)+) => (); ($x:pat | $y:pat) => {}; ($($x:pat)+ | $($y:pat)+) => {}; ($x:pat_param | $y:pat_param) => {}; ($x:pat_param | $y:pat) => {}; ($x:pat | $y:pat_param) => {}; } macro_rules! c { // ____ // ____ // ____ // // ____ // ____ // ____ // ____ // // ____ // ____ // ____ ( @ { // ____ // ____ start = $start:expr; // ____ // ____ ($($count:tt)*) // ____ // ____ // ____ // ____ // ____ // ____ $( ($($skip:tt)*) $bind:pat = $fut:expr, if $c:expr => $handle:expr, )+; // ____ $else:expr } ) => {}; // ____ // ____ // ____ ( @ { start = $start:expr; ($($s:tt)*) $($t:tt)* } $p:pat = $f:expr, if $c:expr => $h:block, $($r:tt)* ) => {}; ( @ { start = $start:expr; ($($s:tt)*) $($t:tt)* } $p:pat = $f:expr, if $c:expr => $h:expr ) => {}; ( @ { start = $start:expr; ($($s:tt)*) $($t:tt)* } $p:pat = $f:expr => $h:expr, $($r:tt)* ) => {}; ( @ { start = $start:expr; ($($s:tt)*) $($t:tt)* } $p:pat = $f:expr => $h:expr ) => {}; ( @ { start = $start:expr; $($t:tt)* } else => $else:expr $(,)? ) => {}; ( @ { start = $start:expr; $($t:tt)* } ) => {}; (($($id:ident),*)) => (()); ([$($id:ident),*]) => (()); ({ $($id:ident),* }) => (()); // ____ ( biased; $p:pat = $($t:tt)* ) => {}; ( $p:pat = $($t:tt)* ) => {}; () => {}; ($($tts:tt)+) => { loom::thread_local!{ $($tts)+ } }; ( @ { // ____ // ____ ($($count:tt)*) // ____ $( ($($skip:tt)*) $e:expr, )* } ) => {}; // ____ ( @ { ($($s:tt)*) $($t:tt)* } $e:expr, $($r:tt)* ) => {}; ( $( $(#[$cfg:meta])* $name:ident, )* ) => {}; // ____ ($($e:expr),* $(,)?) => {}; () => {}; ( $(#[$attr:meta])* $vis:vis static $name:ident: $t:ty; $($rest:tt)* ) => {}; ( $(#[$attr:meta])* $vis:vis static $name:ident: $t:ty ) => {}; (Send & $(!)?Sync & $(!)?Unpin, $value:expr) => {}; (!Send & $(!)?Sync & $(!)?Unpin, $value:expr) => {}; ( $($f:ident $(< $($generic:ty),* >)?)::+($($arg:ty),*): $($tok:tt)* ) => {}; ($i:ident, $start:ident, $($delta:expr),* $(,)?) => {}; ($i:ident, $start:ident) => {}; ($($name:ident = $sem:ident($bits:tt: $exp_bits:tt)),*) => {}; ($ty:ident < $t:tt >) => {}; ( const SUPPORTS_CUSTOM_INNER_ATTRS: bool = $inner_attrs:literal; $($ty:path),* ) => {}; ($($name:literal => $feature:ident)*) => {}; ($($T:ident { $($field:ident: $A:ident),* $(,)? })*) => {}; ($wr:ident.write_facts_to_path($this:ident.[$($field:ident,)*])) => {}; ( $in_:expr, { $param:expr, $flags:expr, $width:expr, $prec:expr, $len:expr, $type_:expr, $pos:expr, } ) => {}; ( ($($dollar:tt $placeholder:ident)*); $($($values:ident),+);*: $($test:tt)* ) => {}; ($($name:ident: $($($p:ident),* => $call:ident),*;)*) => {}; ($($name:ident($($arg:ident),*) => $llvm_capi:ident),+ $(,)?) => {}; ($name:expr, fn() -> $ret:expr) => {}; ($name:expr, fn(...) -> $ret:expr) => {}; ($name:expr, fn($($arg:expr),*) -> $ret:expr) => {}; ($($field_ty:expr),*) => {}; ($($name:ident: $($($p:ident),* => $call:ident),*;)*) => {}; ( $where:expr, { $($what_fmt:expr),+ } $(expected { $($expected_fmt:expr),+ })? ) => {}; ( $e:expr, $where:expr, $( $($p:pat_param)|+ => { $($what_fmt:expr),+ } $(expected { $($expected_fmt:expr),+ })? ),+ $(,)? ) => {}; ( $(#[$attr:meta])* pub enum $name:ident { $( $(#[$var_attr:meta])* $variant:ident = $e:expr, )* } ) => {}; ( $(#[$attr:meta])* pub enum $name:ident { $( $(#[$var_attr:meta])* $variant:ident, )* } ) => {}; (impl $fblock:tt [$($c:tt,)*] [$block:tt $(, $rest:tt)*]) => {}; (impl $fblock:tt [$($blocks:tt,)*] []) => {}; ($($ecode:ident: $message:expr,)*; $($code:ident,)*) => {}; ( $(#[$attrs:meta])* pub fn $n:ident(&self, $($name:ident: $ty:ty),* $(,)?) -> &Self ) => {}; ( $enc:expr, // _______ $idx:expr, // _______ $struct:expr, // _______ $struct_name:ident, // _______ [$($name:ident),+ $(,)?], // _______ [$($ignore:ident),+ $(,)?] // _______ ) => {}; ( $( $Kind:ident($AstTy:ty) { $kind_name:expr; $( one fn $mut_visit_ast:ident; fn $visit_ast:ident; )? $( many fn $flat_map_ast_elt:ident; fn $visit_ast_elt:ident($($args:tt)*); )? fn $make_ast:ident; } )* ) => {}; ($ty:ident { $($field:ident $(: $value:expr)*),+ $(,)? }) => {}; ($ty:ident::$method:ident($($value:expr),*)) => {}; ( $( $(#[doc = $doc:tt])* (accepted, $feature:ident, $ver:expr, $issue:expr, None), )+ ) => {}; ( $( $(#[$attr:meta])* $variant:ident $($group:expr)?, $module:ident::$name:ident, $method:ident, $target:expr, $generics:expr; )* ) => {}; ( [ $( $(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*); )* ] ) => {}; ( [$hir:tt], [ $( $(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*); )* ] ) => {}; ( [ $span:expr, $($fmt:tt)* ] $arg:expr, $($rest:tt)* ) => {}; ($($T:ty),*) => {}; (#$var:ident) => {}; ( $call:ident! $extra:tt ($($b1:tt)*) ($($curr:tt)*) ) => {}; ( $call:ident!($($extra:tt)*) #$var:ident ) => {}; ( $tokens:ident ($($b3:tt)*) ($($b2:tt)*) ($($b1:tt)*) ($($curr:tt)*) ($($a1:tt)*) ($($a2:tt)*) ($($a3:tt)*) ) => {}; ($tokens:ident $b3:tt $b2:tt $b1:tt @ $a1:tt $a2:tt $a3:tt) => {}; ( $tokens:ident $b3:tt $b2:tt $b1:tt (#) ($($inner:tt)*) *$a3:tt ) => {}; ( [$($attrs_pub:tt)*] enum $name:ident #no_visit $($rest:tt)* ) => {}; ( $(#[$enum_attr:meta])* $pub:ident $enum:ident $name:ident #$tag:ident $body:tt $($remaining:tt)* ) => {}; ( $pub:ident $enum:ident $name:ident { $( $(#[$variant_attr:meta])* $variant:ident $(($($member:ident)::+))*, )* } $($remaining:tt)* ) => {}; ( ($($arms:tt)*) $tokens:ident $name:ident { $variant:ident $member:ident, $($next:tt)* } ) => {}; ( $mac:ident!( $(#[$m:meta])* $pub:ident $($t:tt)* ) ) => {}; ($($token:tt pub struct $name:ident #[$doc:meta])*) => {}; ($($token:tt pub struct $name:ident / $len:tt #[$doc:meta])*) => {}; { $($name:ident)::+$(< $param:ident >)? $([$field:tt $this:ident $other:ident])* $(![$ignore:tt])*; !$next:tt $($rest:tt)* } => {}; { $($name:ident)::+; $([ $($variant:ident)::+; $([$field:tt $this:ident $other:ident])* $(![$ignore:tt])* ])* } => {}; { $($name:ident)::+; $([ $($variant:ident)::+; $($fields:tt)* ])* $next:ident $($rest:tt)* } => {}; (($expr:ident) as $t:ty, @ $snapshot:literal) => {}; ( $(#[$smeta:meta])* pub struct $stratname:ident [$($sgen:tt)*] [$($swhere:tt)*] ($innerstrat:ty) -> $stratvtty:ty; $(#[$vmeta:meta])* pub struct $vtname:ident [$($vgen:tt)*] [$($vwhere:tt)*] ($innervt:ty) -> $actualty:ty; ) => {}; { $ head: expr } => { Cons ( $ head , Nil ) }; { $ head: expr, $ ($ tail: expr), * } => { Cons ( $ head , hlist ! ( $ ( $ tail ) , * ) ) }; { $ head: ty } => { Cons < $ head , Nil > }; { $ head: ty, $ ($ tail: ty), * } => { Cons < $ head , HList ! ( $ ( $ tail ) , * ) > }; { ($ ($ LHS: tt) +) } => { Expr ! ( $ ( $ LHS ) + ) }; { HList![$ ($ LHS: tt) *] + $ ($ RHS: tt) + } => { < Expr ! ( HList ! [ $ ( $ LHS ) * ] ) as Add < Expr ! ( $ ( $ RHS ) + ) >> :: Output }; { $ LHS: tt + $ ($ RHS: tt) + } => { < Expr ! ( $ LHS ) as Add < Expr ! ( $ ( $ RHS ) + ) >> :: Output }; { $ LHS: ty } => { $ LHS }; ( $( $name:ident { $( fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)*; )* } ),* $(,)? ) => {}; } // source: "../../../ext/jinx-rust/tests/samples/macro/macro.match.rs" ================================================ FILE: tests/output-ext/macro/macro.tokens.f.rs ================================================ macro_rules! a { (+) => { + }; (+=) => { += }; (&) => { & }; (&&) => { && }; (&=) => { &= }; (@) => { @ }; (!) => { ! }; (^) => { ^ }; (^=) => { ^= }; (:) => { : }; (::) => { :: }; (,) => { , }; (/) => { / }; (/=) => { /= }; (.) => { . }; (..) => { .. }; (...) => { ... }; (..=) => { ..= }; (=) => { = }; (==) => { == }; (>=) => { >= }; (>) => { > }; (<=) => { <= }; (<) => { < }; (*=) => { *= }; (!=) => { != }; (|) => { | }; (|=) => { |= }; (||) => { || }; (#) => { # }; (?) => { ? }; (->) => { -> }; (< -) => { <- }; (%) => { % }; (%=) => { %= }; (=>) => { => }; (;) => { ; }; (<<) => { << }; (<<=) => { <<= }; (>>) => { >> }; (>>=) => { >>= }; (*) => { * }; (-) => { - }; (-=) => { -= }; (~) => { ~ }; } a! { + } a! { += } a! { & } a! { && } a! { &= } a! { @ } a! { ! } a! { ^ } a! { ^= } a! { : } a! { :: } a! { , } a! { / } a! { /= } a! { . } a! { .. } a! { ... } a! { ..= } a! { = } a! { == } a! { >= } a! { > } a! { <= } a! { < } a! { *= } a! { != } a! { | } a! { |= } a! { || } a! { # } a! { ? } a! { -> } a! { <- } a! { % } a! { %= } a! { => } a! { ; } a! { << } a! { <<= } a! { >> } a! { >>= } a! { * } a! { - } a! { -= } a! { ~ } b![+]; b![+=]; b![&]; b![&&]; b![&=]; b![@]; b![!]; b![^]; b![^=]; b![:]; b![::]; b![,]; b![/]; b![/=]; b![.]; b![..]; b![...]; b![..=]; b![=]; b![==]; b![>=]; b![>]; b![<=]; b![<]; b![*=]; b![!=]; b![|]; b![|=]; b![||]; b![#]; b![?]; b![->]; b![<-]; b![%]; b![%=]; b![=>]; b![;]; b![<<]; b![<<=]; b![>>]; b![>>=]; b![*]; b![-]; b![-=]; b![~]; c!(+); c!(+=); c!(&); c!(&&); c!(&=); c!(@); c!(!); c!(^); c!(^=); c!(:); c!(::); c!(,); c!(/); c!(/=); c!(.); c!(..); c!(...); c!(..=); c!(=); c!(==); c!(>=); c!(>); c!(<=); c!(<); c!(*=); c!(!=); c!(|); c!(|=); c!(||); c!(#); c!(?); c!(->); c!(<-); c!(%); c!(%=); c!(=>); c!(;); c!(<<); c!(<<=); c!(>>); c!(>>=); c!(*); c!(-); c!(-=); c!(~); macro_rules! x { ($p:pat =>) => {}; ($p:pat,) => {}; ($p:pat =) => {}; ($p:pat |) => {}; ($p:pat if) => {}; ($p:pat in) => {}; ($e:expr =>) => {}; ($e:expr,) => {}; ($e:expr;) => {}; ($t:ty {}) => {}; ($t:ty,) => {}; ($t:ty =>) => {}; ($t:ty:) => {}; ($t:ty =) => {}; ($t:ty >) => {}; ($t:ty;) => {}; ($t:ty |) => {}; ($t:ty as) => {}; ($t:ty where) => {}; ($t:ty []) => {}; ($t:ty $b:block) => {}; ($s:stmt =>) => {}; ($s:stmt,) => {}; ($s:stmt;) => {}; ($p:path {}) => {}; ($p:path,) => {}; ($p:path =>) => {}; ($p:path:) => {}; ($p:path =) => {}; ($p:path >) => {}; ($p:path;) => {}; ($p:path |) => {}; ($p:path as) => {}; ($p:path where) => {}; ($p:path []) => {}; ($p:path $b:block) => {}; ($b:block ()) => {}; ($b:block []) => {}; ($b:block {}) => {}; ($b:block,) => {}; ($b:block =>) => {}; ($b:block:) => {}; ($b:block =) => {}; ($b:block >) => {}; ($b:block;) => {}; ($b:block |) => {}; ($b:block +) => {}; ($b:block ident) => {}; ($b:block $p:pat) => {}; ($b:block $e:expr) => {}; ($b:block $t:ty) => {}; ($b:block $s:stmt) => {}; ($b:block $p:path) => {}; ($b:block $c:block) => {}; ($b:block $i:ident) => {}; ($b:block $t:tt) => {}; ($b:block $i:item) => {}; ($b:block $m:meta) => {}; ($i:ident()) => {}; ($i:ident []) => {}; ($i:ident {}) => {}; ($i:ident,) => {}; ($i:ident =>) => {}; ($i:ident:) => {}; ($i:ident =) => {}; ($i:ident >) => {}; ($i:ident;) => {}; ($i:ident |) => {}; ($i:ident +) => {}; ($i:ident ident) => {}; ($i:ident $p:pat) => {}; ($i:ident $e:expr) => {}; ($i:ident $t:ty) => {}; ($i:ident $s:stmt) => {}; ($i:ident $p:path) => {}; ($i:ident $b:block) => {}; ($i:ident $j:ident) => {}; ($i:ident $t:tt) => {}; ($i:ident $j:item) => {}; ($i:ident $m:meta) => {}; ($t:tt ()) => {}; ($t:tt []) => {}; ($t:tt {}) => {}; ($t:tt,) => {}; ($t:tt =>) => {}; ($t:tt:) => {}; ($t:tt =) => {}; ($t:tt >) => {}; ($t:tt;) => {}; ($t:tt |) => {}; ($t:tt +) => {}; ($t:tt ident) => {}; ($t:tt $p:pat) => {}; ($t:tt $e:expr) => {}; ($t:tt $v:ty) => {}; ($t:tt $s:stmt) => {}; ($t:tt $p:path) => {}; ($t:tt $b:block) => {}; ($t:tt $i:ident) => {}; ($t:tt $v:tt) => {}; ($t:tt $i:item) => {}; ($t:tt $m:meta) => {}; ($i:item ()) => {}; ($i:item []) => {}; ($i:item {}) => {}; ($i:item,) => {}; ($i:item =>) => {}; ($i:item:) => {}; ($i:item =) => {}; ($i:item >) => {}; ($i:item;) => {}; ($i:item |) => {}; ($i:item +) => {}; ($i:item ident) => {}; ($i:item $p:pat) => {}; ($i:item $e:expr) => {}; ($i:item $t:ty) => {}; ($i:item $s:stmt) => {}; ($i:item $p:path) => {}; ($i:item $b:block) => {}; ($i:item $j:ident) => {}; ($i:item $t:tt) => {}; ($i:item $j:item) => {}; ($i:item $m:meta) => {}; ($m:meta ()) => {}; ($m:meta []) => {}; ($m:meta {}) => {}; ($m:meta,) => {}; ($m:meta =>) => {}; ($m:meta:) => {}; ($m:meta =) => {}; ($m:meta >) => {}; ($m:meta;) => {}; ($m:meta |) => {}; ($m:meta +) => {}; ($m:meta ident) => {}; ($m:meta $p:pat) => {}; ($m:meta $e:expr) => {}; ($m:meta $t:ty) => {}; ($m:meta $s:stmt) => {}; ($m:meta $p:path) => {}; ($m:meta $b:block) => {}; ($m:meta $i:ident) => {}; ($m:meta $t:tt) => {}; ($m:meta $i:item) => {}; ($m:meta $n:meta) => {}; ($ty:ty <) => (); //~ ERROR `$ty:ty` is followed by `<`, which is not allowed for `ty` ($ty:ty < foo,) => (); //~ ERROR `$ty:ty` is followed by `<`, which is not allowed for `ty` ($ty:ty,) => (); (($ty:ty)) => (); ({ $ty:ty }) => (); ([$ty:ty]) => (); ($bl:block <) => (); ($pa:pat >) => (); //~ ERROR `$pa:pat` is followed by `>`, which is not allowed for `pat` ($pa:pat,) => (); ($pa:pat $pb:pat $ty:ty,) => (); //~^ ERROR `$pa:pat` is followed by `$pb:pat`, which is not allowed //~^^ ERROR `$pb:pat` is followed by `$ty:ty`, which is not allowed ($($ty:ty)* -) => (); //~ ERROR `$ty:ty` is followed by `-` ($($a:ty, $b:ty)* -) => (); //~ ERROR `$b:ty` is followed by `-` ($($ty:ty)-+) => (); //~ ERROR `$ty:ty` is followed by `-`, which is not allowed for `ty` ( $($a:expr)* $($b:tt)* ) => { }; //~^ ERROR `$a:expr` is followed by `$b:tt`, which is not allowed for `expr` fragments ( $b:block, $e:expr, $i:ident, $it:item, $l:lifetime, $lit:literal, $m:meta, $p:pat, $pth:path, $s:stmt, $tt:tt, $ty:ty, $vis:vis ) => { }; } #![rustc_dummy("hi", 1, 2, 1.012, pi = 3.14, bye, name("John"))] #[rustfmt::r#final(final)] lexes! { a #foo } lexes! { continue 'foo; } lexes! { match "..." { } } lexes! { r#let#foo } // Identifier<"r#let"; raw: true> PunctuationToken<#> Identifier<"foo"> fn f() { unsafe { asm!(""); asm!("", options()); asm!("", options(nostack, nomem)); asm!("{}", in(reg) 4); asm!("{0}", out(reg) a); asm!("{name}", name = inout(reg) b); asm!("{} {}", out(reg) _, inlateout(reg) b => _); asm!("", out("al") _, lateout("rcx") _); asm!("beep~", "boop!"); asm!("beep~ {}, 42", "boop! {}, 24", in(reg) a, out(reg) b); asm!("boop! {1}, 24", "beep~ {0}, 42", in(reg) a, out(reg) b); asm!("beep~ {}, 42", "boop! {name}, 24", in(reg) a, name = out(reg) b); asm!("beep~ boop!"); asm!("beep~\nboop!"); asm!("beep~\n\tboop!"); asm!("beep~\nboop!", "boop3\nboop4"); } } debug!(?value); debug!( "VariantDef::new(name = {:?}, variant_did = {:?}, ctor_def_id = {:?}, discr = {:?}, fields = {:?}, ctor_kind = {:?}, adt_kind = {:?}, parent_did = {:?})", name, variant_did, ctor_def_id, discr, fields, ctor_kind, adt_kind, parent_did ); slice_interners!( substs: _intern_substs(GenericArg<'tcx>), canonical_var_infos: _intern_canonical_var_infos(CanonicalVarInfo<'tcx>), poly_existential_predicates: _intern_poly_existential_predicates(ty::Binder<'tcx, ExistentialPredicate<'tcx>>), predicates: _intern_predicates(Predicate<'tcx>), projs: _intern_projs(ProjectionKind), place_elems: _intern_place_elems(PlaceElem<'tcx>), bound_variable_kinds: _intern_bound_variable_kinds(ty::BoundVariableKind), ); impl_binder_encode_decode! { &'tcx ty::List>, ty::FnSig<'tcx>, ty::ExistentialPredicate<'tcx>, ty::TraitRef<'tcx>, Vec>, } impl_arena_copy_decoder! {<'tcx> Span, rustc_span::symbol::Ident, ty::Variance, rustc_span::def_id::DefId, rustc_span::def_id::LocalDefId, (rustc_middle::middle::exported_symbols::ExportedSymbol<'tcx>, rustc_middle::middle::exported_symbols::SymbolExportInfo), } bitflags! { #[derive(HashStable, TyEncodable, TyDecodable)] pub struct AdtFlags: u32 { const NO_ADT_FLAGS = 0; /// Indicates whether the ADT is an enum. const IS_ENUM = 1 << 0; /// Indicates whether the ADT is a union. const IS_UNION = 1 << 1; /// Indicates whether the ADT is a struct. const IS_STRUCT = 1 << 2; /// Indicates whether the ADT is a struct and has a constructor. const HAS_CTOR = 1 << 3; /// Indicates whether the type is `PhantomData`. const IS_PHANTOM_DATA = 1 << 4; /// Indicates whether the type has a `#[fundamental]` attribute. const IS_FUNDAMENTAL = 1 << 5; /// Indicates whether the type is `Box`. const IS_BOX = 1 << 6; /// Indicates whether the type is `ManuallyDrop`. const IS_MANUALLY_DROP = 1 << 7; /// Indicates whether the variant list of this ADT is `#[non_exhaustive]`. /// (i.e., this flag is never set unless this ADT is an enum). const IS_VARIANT_LIST_NON_EXHAUSTIVE = 1 << 8; } } rustc_dep_node_append!([define_dep_nodes!][ <'tcx> // We use this for most things when incr. comp. is turned off. [] Null, [anon] TraitSelect, // WARNING: if `Symbol` is changed, make sure you update `make_compile_codegen_unit` below. [] CompileCodegenUnit(Symbol), // WARNING: if `MonoItem` is changed, make sure you update `make_compile_mono_item` below. // Only used by rustc_codegen_cranelift [] CompileMonoItem(MonoItem), ]); decl_derive!([Decodable] => serialize::decodable_derive); let ret = structure.gen_impl( quote! { gen impl rustc_errors::AddSubdiagnostic for @Self { fn add_to_diagnostic(self, #diag: &mut rustc_errors::Diagnostic) { use rustc_errors::{Applicability, IntoDiagnosticArg}; #implementation } } } ); // source: "../../../ext/jinx-rust/tests/samples/macro/macro.tokens.rs" ================================================ FILE: tests/output-ext/macro/macro.transform.f.rs ================================================ macro_rules! x { () => { $cx.pass.$f(&$cx.context, $($args),*); $(pub struct $sem;)* $(pub type $name = IeeeFloat<$sem>;)* $(impl Semantics for $sem { const BITS: usize = $bits; const PRECISION: usize = ($bits - 1 - $exp_bits) + 1; const MAX_EXP: ExpInt = (1 << ($exp_bits - 1)) - 1; })* for elem in $list { $visitor.$method(elem) } for elem in $list { $visitor.$method(elem, $($extra_args,)*) } }; ($this:expr; $($x:expr),*) => ( $this.arena.alloc_from_iter([$($x),*]) ); (path, < $type:ty as $trait:path > ::$name:ident) => { <$type as $trait>::$name }; (ty, < $type:ty as $trait:ty > ::$name:ident) => { <$type as $trait>::$name }; ( $fnname:ident, $arg:ident, $ty:ty, $body:block, $val:expr, $pat:pat, $res:path ) => ( { fn $fnname($arg: $ty) -> Option<$ty> $body match $fnname($val) { Some($pat) => { $res } _ => { panic!(); } } } ); ($l:lifetime, $l2:lifetime) => { fn f<$l: $l2, $l2>(arg: &$l str, arg2: &$l2 str) -> &$l str { arg } }; ($a:lifetime) => { $a: loop { break $a; panic!("failed"); } }; ($a:lifetime) => { break $a; }; ($b:lifetime) => { 'b: loop { // comment break $b; // comment } }; ($l:lifetime) => { fn f(arg: &$l str) -> &$l str { arg } }; ($l:lifetime) => { fn f<$l>(arg: &$l str) -> &$l str { arg } }; ($s:literal ..= $e:literal) => { match 3 { $s ..= $e => "literal, in range", _ => "literal, other", } }; ($s:pat) => { match 3 { $s => "pat, single", _ => "pat, other", } }; ($s:literal ..= $e:literal) => { &format!("macro caught literal: {} ..= {}", $s, $e) }; ( ($s:expr) ..= ($e:expr) ) => { // comment &format!("macro caught expr: {} ..= {}", $s, $e) }; ($s:expr, $e:expr) => { { let mut v = Vec::new(); for i in $s .. $e { v.push(i); } "expr" } }; ($at:meta) => { #[cfg($at)] static MISTYPED: () = "foo"; }; ($($x:tt)*) => { $($x)* }; (subst $lhs:tt => $rhs:tt) => ( { macro_rules! anon { $lhs => $rhs } anon!(1_usize, 2_usize, "foo") } ); ($x:expr; $fragment:ident) => { macro_rules! inner { ($y:$fragment) => { $x + $y } } }; ($expr:expr, $($($pat:pat)|+ => $expr_arm:expr),+) => { match $expr { $( $( $pat => $expr_arm, )+ )+ } }; ($nm:ident, #[$a:meta], $i:item) => (mod $nm { #[$a] $i }); ($p:pat | $p2:pat) => { { match Some(1u8) { $p | $p2 => {} _ => {} } } }; ($p:pat in $e:expr) => { { let mut iter = $e.into_iter(); while let $p = iter.next() {} } }; ($p:pat if $e:expr) => { { match Some(1u8) { $p if $e => {} _ => {} } } }; ($name:ident { $($variant:ident = $value:expr,)* }) => { enum $name { $($variant = $value,)* } fn foo(value: i32) -> Option<$name> { match value { $( $value => Some($name::$variant), )* _ => None } } }; ($f:ident, ($($x:ident),*), $body:block) => ( fn $f( $( $x : isize),* ) -> isize $body ); ( < $a:expr; > $($b:tt)* ) => { Keep(parse_item!($a),parse_list!($($b)*)) }; ( $a:tt $($b:tt)* ) => { Skip(parse_item!($a), parse_list!($($b)*)) }; ($x:tt) => (type Alias = $x;); ($($code:tt)*) => { expr!(thread::spawn(move|| {$($code)*}).join()) }; ($($m:ident $($f:ident $v:tt)+),*) => { $($(macro_rules! $f { () => { $v } })+)* $(macro_rules! $m { () => { $(fn $f() -> i32 { $v })+ } })* }; ($n:ident $x:expr) => { macro_rules! $n { ($y:expr) => { $x + $y }; } }; ($name:ident) => { #[derive(Debug)] struct Foo { #[cfg(not(FALSE))] field: fn($name: bool) } }; { $A:ty, $B:ty } => { ($A, $B) }; ($id1:ident, $id2:ident, $e:expr) => ( fn foo(a:T, b:T) -> T { match (a, b) { (T::A($id1), T::A($id2)) => T::A($e), (T::B($id1), T::B($id2)) => T::B($e), _ => panic!() } } ); ($expression:expr, $($pattern:pat)|+ $(if $guard:expr)? $(,)?) => { match $expression { $( $pattern )|+ $( if $guard )? => true, _ => false } }; ( $dst:expr, $($arg:tt)* ) => ($dst.write_fmt(format_args!($($arg)*))); ($x:pat |) => (); () => { // comment // comment mod bar { #[derive(Double)] struct Bar($crate::Foo); } mod qself { #[derive(Double)] struct QSelf(<::Foo as $crate::Trait>::Assoc); } mod qself_recurse { #[derive(Double)] struct QSelfRecurse(<<$crate::Foo as $crate::Trait>::Assoc as $crate::Trait>::Assoc); } mod qself_in_const { #[derive(Double)] #[repr(u32)] enum QSelfInConst { Variant = <::Foo as $crate::Trait>::CONST, } } }; ($item:item) => { #[derive(Print)] struct Foo { #[cfg(FALSE)] removed: bool, field: [bool; { $item 0 }] } }; { $(#[$attr:meta])* pub $name:ident, $_reason:expr } => { $(#[$attr])* #[allow(dead_code)] pub static $name: ClippyDeprecatedLint = ClippyDeprecatedLint {}; }; ($($name:ident $assign:ident)*) => { /// comment pub static BINOP_TRAITS: &[LangItem] = &[$(LangItem::$name,)*]; /// comment pub static OP_ASSIGN_TRAITS: &[LangItem] = &[$(LangItem::$assign,)*]; /// comment pub fn binop_traits(kind: hir::BinOpKind) -> Option<(LangItem, LangItem)> { match kind { $(hir::BinOpKind::$name => Some((LangItem::$name, LangItem::$assign)),)* _ => None, } } }; ($($t:ident),*) => { $(impl HirNode for hir::$t<'_> { fn hir_id(&self) -> HirId { self.hir_id } fn span(&self) -> Span { self.span } })* }; ( $( $major:literal, $minor:literal, $patch:literal { $($name:ident),* $(,)? } )* ) => { $($( pub const $name: RustcVersion = RustcVersion::new($major, $minor, $patch); )*)* }; ( impl $imp:ident, $method:ident for $t:ty, type Output = $o:ty ) => { impl $imp<$t> for &$t { type Output = $o; fn $method(self, other: $t) -> $o { $imp::$method(self, &other) } } impl $imp<&$t> for $t { type Output = $o; fn $method(self, other: &$t) -> $o { $imp::$method(&self, other) } } impl $imp for $t { type Output = $o; fn $method(self, other: $t) -> $o { $imp::$method(&self, &other) } } }; ( $iter:ident, $($token:ident $({ $($fields:tt)* })? $(($capture:ident))?)* ) => { { $($(let $capture =)? if let Some((TokenKind::$token $({$($fields)*})?, _x)) = $iter.next() { _x } else { continue; };)* #[allow(clippy::unused_unit)] { ($($($capture,)?)*) } } }; (exp $e:expr) => { $e }; ( exp $($t:tt)+ ) => { exp!($($t)+) }; {} => { Nil }; { $ head: expr } => { Cons ( $ head , Nil ) }; { $ head: expr, $ ($ tail: expr), * } => { Cons ( $ head , hlist ! ( $ ( $ tail ) , * ) ) }; {} => { Nil }; { $ head: ty } => { Cons < $ head , Nil > }; { $ head: ty, $ ($ tail: ty), * } => { Cons < $ head , HList ! ( $ ( $ tail ) , * ) > }; { ($ ($ LHS: tt) +) } => { Expr ! ( $ ( $ LHS ) + ) }; { HList![$ ($ LHS: tt) *] + $ ($ RHS: tt) + } => { < Expr ! ( HList ! [ $ ( $ LHS ) * ] ) as Add < Expr ! ( $ ( $ RHS ) + ) >> :: Output }; { $ LHS: tt + $ ($ RHS: tt) + } => { < Expr ! ( $ LHS ) as Add < Expr ! ( $ ( $ RHS ) + ) >> :: Output }; { $ LHS: ty } => { $ LHS }; ( [$elem_ty:ident; $elem_count:expr]: $id:ident | $test_tt:tt | $source:ident ) => { impl From<$source> for $id { #[inline] fn from(source: $source) -> Self { fn static_assert_same_number_of_lanes() where T: crate::sealed::Simd, U: crate::sealed::Simd, { } use llvm::simd_cast; static_assert_same_number_of_lanes::<$id, $source>(); Simd(unsafe { simd_cast(source.0) }) } } // comment // comment /* comment */ test_if!{ $test_tt: interpolate_idents! { mod [$id _from_ $source] { use super::*; #[test] fn from() { assert_eq!($id::lanes(), $source::lanes()); let source: $source = Default::default(); let vec: $id = Default::default(); let e = $id::from(source); assert_eq!(e, vec); let e: $id = source.into(); assert_eq!(e, vec); } } } } }; ( [ $elem_ty:ident; $elem_count:expr ]: $id:ident | $test_tt:tt | $($source:ident),* ) => { $( impl_from_vector!([$elem_ty; $elem_count]: $id | $test_tt | $source); )* }; ( $( $(#[$cfg:meta])* $name:ident, )* ) => { [$($(#[$cfg])* (b!($name), $name::bench as fn(&str) -> C<(), ()>),)*] }; ( $( $(#[$attr:meta])* pub fn $func:ident($input:ident: &str) -> String; )+ ) => { $( $( #[$attr] )* #[proc_macro_derive($func)] pub fn $func(_input: ::proc_macro::TokenStream) -> ::proc_macro::TokenStream { panic!() } )+ }; ( $( $(#[$attr:meta])* pub fn $func:ident($input:ident: &str) -> String $body:block )+ ) => { $( // comment $( #[$attr] )* #[proc_macro_derive($func)] pub fn $func(input: f!()) -> f!() { unsafe { a(0); } panic!() } )+ }; ( $context:ty, [ $( $(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*); )* ] ) => ( $(#[inline(always)] fn $name(&mut self, _: $context, $(_: $arg),*) {})* ); ( [], [$hir:tt], [$($methods:tt)*] ) => ( pub trait LateLintPass<$hir>: LintPass { expand_lint_pass_methods!(&LateContext<$hir>, [$($methods)*]); } ); ([$($passes:ident),*], $self:ident, $name:ident, $params:tt) => ( { $($self.$passes.$name $params;)* } ); ( $passes:tt, [ $( $(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*); )* ] ) => ( $(fn $name(&mut self, context: &LateContext<'tcx>, $($param: $arg),*) { expand_combined_late_lint_pass_method!($passes, self, $name, (context, $($param),*)); })* ); ( [$v:vis $name:ident, [$($passes:ident: $constructor:expr,)*]], [$hir:tt], $methods:tt ) => ( #[allow(non_snake_case)] $v struct $name { $($passes: $passes,)* } impl $name { $v fn new() -> Self { Self { $($passes: $constructor,)* } } $v fn get_lints() -> LintArray { let mut lints = Vec::new(); $(lints.extend_from_slice(&$passes::get_lints());)* lints } } impl<'tcx> LateLintPass<'tcx> for $name { expand_combined_late_lint_pass_methods!([$($passes),*], $methods); } #[allow(rustc::lint_pass_impl_without_macro)] impl LintPass for $name { fn name(&self) -> &'static str { panic!() } } ); ($macro:path, $args:tt) => ( $macro!($args, [ fn check_param(a: &ast::Param); ]); ); ( $context:ty, [ $( $(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*); )* ] ) => ( $(#[inline(always)] fn $name(&mut self, _: $context, $(_: $arg),*) {})* ); ( [], [$($methods:tt)*] ) => ( pub trait EarlyLintPass: LintPass { expand_early_lint_pass_methods!(&EarlyContext<'_>, [$($methods)*]); } ); ([$($passes:ident),*], $self:ident, $name:ident, $params:tt) => ( { $($self.$passes.$name $params;)* } ); ( $passes:tt, [ $( $(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*); )* ] ) => ( $(fn $name(&mut self, context: &EarlyContext<'_>, $($param: $arg),*) { expand_combined_early_lint_pass_method!($passes, self, $name, (context, $($param),*)); })* ); ( [$v:vis $name:ident, [$($passes:ident: $constructor:expr,)*]], $methods:tt ) => ( #[allow(non_snake_case)] $v struct $name { $($passes: $passes,)* } impl $name { $v fn new() -> Self { Self { $($passes: $constructor,)* } } $v fn get_lints() -> LintArray { let mut lints = Vec::new(); $(lints.extend_from_slice(&$passes::get_lints());)* lints } } impl EarlyLintPass for $name { expand_combined_early_lint_pass_methods!([$($passes),*], $methods); } #[allow(rustc::lint_pass_impl_without_macro)] impl LintPass for $name { fn name(&self) -> &'static str { panic!() } } ); ( $ty:expr, $val:expr, $negative:expr, $($type:ident => [$($utypes:expr),*] => [$($itypes:expr),*]),+ ) => { { let _neg = if negative { 1 } else { 0 }; match $ty { $($type => { $(if !negative && val <= uint_ty_range($utypes).1 { return Some($utypes.name_str()) })* $(if val <= int_ty_range($itypes).1 as u128 + _neg { return Some($itypes.name_str()) })* None },)+ _ => None } } }; ( $(#[$attr:meta])* $vis:vis $tool:ident::$NAME:ident, $Level:ident, $desc:expr ) => ( $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false} ); ( $(#[$attr:meta])* $vis:vis $tool:ident::$NAME:ident, $Level:ident, $desc:expr, report_in_external_macro: $rep:expr ) => ( $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep} ); ( $(#[$attr:meta])* $vis:vis $tool:ident::$NAME:ident, $Level:ident, $desc:expr, $external:expr ) => ( $(#[$attr])* $vis static $NAME: &$crate::Lint = &$crate::Lint { name: &concat!(stringify!($tool), "::", stringify!($NAME)), default_level: $crate::$Level, desc: $desc, edition_lint_opts: None, report_in_external_macro: $external, future_incompatible: None, is_plugin: true, feature_gate: None, crate_level_only: false, }; ); ( $(#[$attr:meta])* $vis:vis $NAME:ident, $Level:ident, $desc:expr ) => ( $crate::declare_lint!( $(#[$attr])* $vis $NAME, $Level, $desc, ); ); ( $(#[$attr:meta])* $vis:vis $NAME:ident, $Level:ident, $desc:expr, $(@feature_gate = $gate:expr;)? $( @future_incompatible = FutureIncompatibleInfo { $($field:ident: $val:expr),* $(,)* }; )? $($v:ident),* ) => ( $(#[$attr])* $vis static $NAME: &$crate::Lint = &$crate::Lint { name: stringify!($NAME), default_level: $crate::$Level, desc: $desc, edition_lint_opts: None, is_plugin: false, $($v: true,)* $(feature_gate: Some($gate),)* $(future_incompatible: Some($crate::FutureIncompatibleInfo { $($field: $val,)* ..$crate::FutureIncompatibleInfo::default_fields_for_macro() }),)* ..$crate::Lint::default_fields_for_macro() }; ); ( $(#[$attr:meta])* $vis:vis $NAME:ident, $Level:ident, $desc:expr, $lint_edition:expr => $edition_level:ident ) => ( $(#[$attr])* $vis static $NAME: &$crate::Lint = &$crate::Lint { name: stringify!($NAME), default_level: $crate::$Level, desc: $desc, edition_lint_opts: Some(($lint_edition, $crate::Level::$edition_level)), report_in_external_macro: false, is_plugin: false, }; ); ($($lint:expr),*,) => { lint_array!( $($lint),* ) }; ($($lint:expr),*) => { { vec![$($lint),*] } }; ($ty:ty => [$($lint:expr),* $(,)?]) => { impl $crate::LintPass for $ty { fn name(&self) -> &'static str { stringify!($ty) } } impl $ty { pub fn get_lints() -> $crate::LintArray { $crate::lint_array!($($lint),*) } } }; ( $(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?] ) => { $(#[$m])* #[derive(Copy, Clone)] pub struct $name; $crate::impl_lint_pass!($name => [$($lint),*]); }; ($cfg:meta, $($method:ident),*) => { { #[cfg($cfg)] fn init() { extern "C" { $(fn $method();)* } unsafe { $($method();)* } } #[cfg(not($cfg))] fn init() { } init(); } }; ( $attr:expr, $nested_attr:expr ) => {{ throw_invalid_nested_attr!($attr, $nested_attr, |diag| diag) }}; ($attr:expr, $nested_attr:expr, $f:expr) => { { let diag = crate::diagnostics::error::invalid_nested_attr($attr, $nested_attr); return Err(crate::diagnostics::error::_throw_err(diag, $f)); } }; ( $attr:expr, $meta:expr ) => {{ throw_invalid_attr!($attr, $meta, |diag| diag) }}; ($attr:expr, $meta:expr, $f:expr) => { { let diag = crate::diagnostics::error::invalid_attr($attr, $meta); return Err(crate::diagnostics::error::_throw_err(diag, $f)); } }; ($span:expr, $msg:expr) => {{ throw_span_err!($span, $msg, |diag| diag) }}; ($span:expr, $msg:expr, $f:expr) => { { let diag = span_err($span, $msg); return Err(crate::diagnostics::error::_throw_err(diag, $f)); } }; ($ty:ty { $(($($pat:tt)*))* }) => { impl FixedSizeEncoding for Option<$ty> { type ByteArray = [u8;1]; #[inline] fn from_bytes(b: &[u8;1]) -> Self { use $ty::*; if b[0] == 0 { return None; } match b[0] - 1 { $(${index()} => Some($($pat)*),)* _ => panic!("Unexpected ImplPolarity code: {:?}", b[0]), } } #[inline] fn write_to_bytes(self, b: &mut [u8;1]) { use $ty::*; b[0] = match self { None => 0, $(Some($($pat)*) => 1 + ${index()},)* } } } }; ($msg:expr) => ({ $crate::util::bug::bug_fmt(::std::format_args!($msg)) }); ($msg:expr,) => ({ $crate::bug!($msg) }); ( $fmt:expr, $($arg:tt)+ ) => ( { $crate::util::bug::bug_fmt(::std::format_args!($fmt, $($arg)+)) } ); ( $span:expr, $msg:expr ) => ({ $crate::util::bug::span_bug_fmt($span, ::std::format_args!($msg)) }); ($span:expr, $msg:expr,) => ({ $crate::span_bug!($span, $msg) }); ( $span:expr, $fmt:expr, $($arg:tt)+ ) => ( { $crate::util::bug::span_bug_fmt($span, ::std::format_args!($fmt, $($arg)+)) } ); (for < $tcx:lifetime > { $($ty:ty,)+ }) => { $( impl<$tcx> $crate::ty::Lift<$tcx> for $ty { type Lifted = Self; fn lift_to_tcx(self, _: $crate::ty::TyCtxt<$tcx>) -> Option { Some(self) } } )+ }; ($($ty:ty,)+) => { CloneLiftImpls! { for <'tcx> { $($ty,)+ } } }; (for < $tcx:lifetime > { $($ty:ty,)+ }) => { $( impl<$tcx> $crate::ty::fold::TypeFoldable<$tcx> for $ty { fn try_super_fold_with>( self, _: &mut F ) -> ::std::result::Result<$ty, F::Error> { Ok(self) } fn super_visit_with>( &self, _: &mut F) -> ::std::ops::ControlFlow { ::std::ops::ControlFlow::CONTINUE } } )+ }; ($($ty:ty,)+) => { TrivialTypeFoldableImpls! { for <'tcx> { $($ty,)+ } } }; ($($t:tt)*) => { TrivialTypeFoldableImpls! { $($t)* } CloneLiftImpls! { $($t)* } }; ( impl < $($p:tt),* > TypeFoldable < $tcx:tt > for $s:path { $($variants:tt)* } $( where $($wc:tt)* )* ) => { impl<$($p),*> $crate::ty::fold::TypeFoldable<$tcx> for $s $(where $($wc)*)* { fn try_super_fold_with>( self, folder: &mut V, ) -> ::std::result::Result { EnumTypeFoldableImpl!(@FoldVariants(self, folder) input($($variants)*) output()) } fn super_visit_with>( &self, visitor: &mut V, ) -> ::std::ops::ControlFlow { EnumTypeFoldableImpl!(@VisitVariants(self, visitor) input($($variants)*) output()) } } }; ($($ty:ty),+ $(,)?) => { $( impl $crate::ty::ParameterizedOverTcx for $ty { #[allow(unused_lifetimes)] type Value<'tcx> = $ty; } )* }; ($($ident:ident),+ $(,)?) => { $( impl $crate::ty::ParameterizedOverTcx for $ident<'static> { type Value<'tcx> = $ident<'tcx>; } )* }; ($($field:ident: $method:ident($ty:ty)),+ $(,)?) => ( impl<'tcx> TyCtxt<'tcx> { $(pub fn $method(self, v: &[$ty]) -> &'tcx List<$ty> { self.interners.$field.intern_ref(v, || { InternedInSet(List::from_arena(&*self.arena, v)) }).0 })+ } ); ($($name:ident: $method:ident($ty:ty): $ret_ctor:ident -> $ret_ty:ty,)+) => { $(impl<'tcx> Borrow<$ty> for InternedInSet<'tcx, $ty> { fn borrow<'a>(&'a self) -> &'a $ty { &self.0 } } impl<'tcx> PartialEq for InternedInSet<'tcx, $ty> { fn eq(&self, other: &Self) -> bool { // comment // comment self.0 == other.0 } } impl<'tcx> Eq for InternedInSet<'tcx, $ty> {} impl<'tcx> Hash for InternedInSet<'tcx, $ty> { fn hash(&self, s: &mut H) { // comment // comment self.0.hash(s) } } impl<'tcx> TyCtxt<'tcx> { pub fn $method(self, v: $ty) -> $ret_ty { $ret_ctor(Interned::new_unchecked(self.interners.$name.intern(v, |v| { InternedInSet(self.interners.arena.alloc(v)) }).0)) } })+ }; ($DecoderName:ident < $($typaram:tt),* >) => { mod __ty_decoder_impl { use std::borrow::Cow; use rustc_serialize::Decoder; use super::$DecoderName; impl<$($typaram ),*> Decoder for $DecoderName<$($typaram),*> { $crate::__impl_decoder_methods! { read_u128 -> u128; read_u64 -> u64; read_u32 -> u32; read_u16 -> u16; read_u8 -> u8; read_usize -> usize; read_i128 -> i128; read_i64 -> i64; read_i32 -> i32; read_i16 -> i16; read_i8 -> i8; read_isize -> isize; read_bool -> bool; read_f64 -> f64; read_f32 -> f32; read_char -> char; read_str -> &str; } #[inline] fn read_raw_bytes(&mut self, len: usize) -> &[u8] { self.opaque.read_raw_bytes(len) } } } }; ($($t:ty),+ $(,)?) => { $( impl<'tcx, E: TyEncoder>> Encodable for ty::Binder<'tcx, $t> { fn encode(&self, e: &mut E) -> Result<(), E::Error> { self.bound_vars().encode(e)?; self.as_ref().skip_binder().encode(e) } } impl<'tcx, D: TyDecoder>> Decodable for ty::Binder<'tcx, $t> { fn decode(decoder: &mut D) -> Self { let bound_vars = Decodable::decode(decoder); ty::Binder::bind_with_vars(Decodable::decode(decoder), bound_vars) } } )* }; (< $tcx:tt > $($ty:ty,)*) => { $(impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for $ty { #[inline] fn decode(decoder: &mut D) -> &'tcx Self { decoder.interner().arena.alloc(Decodable::decode(decoder)) } } impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for [$ty] { #[inline] fn decode(decoder: &mut D) -> &'tcx Self { decoder.interner().arena.alloc_from_iter( as Decodable>::decode(decoder)) } })* }; ([$($a:tt $name:ident: $ty:ty,)*]) => { $( impl_arena_allocatable_decoder!($a [$name: $ty]); )* }; ([] $args:tt) => {}; ([decode $(, $attrs:ident)*] [$name:ident: $ty:ty]) => { impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for $ty { #[inline] fn decode(decoder: &mut D) -> &'tcx Self { decode_arena_allocable(decoder) } } impl<'tcx, D: TyDecoder>> RefDecodable<'tcx, D> for [$ty] { #[inline] fn decode(decoder: &mut D) -> &'tcx Self { decode_arena_allocable_slice(decoder) } } }; ($($name:ident -> $ty:ty;)*) => { $( #[inline] fn $name(&mut self) -> $ty { self.opaque.$name() } )* }; (@ $lit:literal) => { write!(scoped_cx!(), $lit)? }; (@write($($data:expr),+)) => { write!(scoped_cx!(), $($data),+)? }; (@print($x:expr)) => { scoped_cx!() = $x.print(scoped_cx!())? }; (@$method:ident($($arg:expr),*)) => { scoped_cx!() = scoped_cx!().$method($($arg),*)? }; ($($elem:tt $(($($args:tt)*))?),+) => { { $(p!(@ $elem $(($($args)*))?);)+ } }; ($cx:ident) => { #[allow(unused_macros)] macro_rules! scoped_cx { () => { $cx }; } }; ( $( $(#[$a:meta])* fn $name:ident($helper:ident, $tl:ident); )+ ) => { $( #[must_use] pub struct $helper(bool); impl $helper { pub fn new() -> $helper { $helper($tl.with(|c| c.replace(true))) } } $(#[$a])* pub macro $name($e:expr) { { let _guard = $helper::new(); $e } } impl Drop for $helper { fn drop(&mut self) { $tl.with(|c| c.set(self.0)) } } )+ }; ($($ty:ty),+) => { // comment $(#[allow(unused_lifetimes)] impl<'tcx> fmt::Display for $ty { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { ty::tls::with(|tcx| { let cx = tcx.lift(*self) .expect("could not lift for printing") .print(FmtPrinter::new(tcx, Namespace::TypeNS))?; f.write_str(&cx.into_buffer())?; Ok(()) }) } })+ }; (($self:ident, $cx:ident): $($ty:ty $print:block)+) => { $(impl<'tcx, P: PrettyPrinter<'tcx>> Print<'tcx, P> for $ty { type Output = P; type Error = fmt::Error; fn print(&$self, $cx: P) -> Result { #[allow(unused_mut)] let mut $cx = $cx; define_scoped_cx!($cx); let _: () = $print; #[allow(unreachable_code)] Ok($cx) } })+ forward_display_to_print!($($ty),+); }; ($($ty:ty),*) => { $( impl From<$ty> for ScalarInt { #[inline] fn from(u: $ty) -> Self { Self { data: u128::from(u), size: std::mem::size_of::<$ty>() as u8, } } } )* }; ($($ty:ty),*) => { $( impl TryFrom for $ty { type Error = Size; #[inline] fn try_from(int: ScalarInt) -> Result { // comment // comment int.to_bits(Size::from_bytes(std::mem::size_of::<$ty>())) .map(|u| u.try_into().unwrap()) } } )* }; ( < $tcx:tt > $( [$($attrs:tt)*] $variant:ident $(($tuple_arg_ty:ty $(,)?))*, )* ) => ( #[macro_export] macro_rules! make_dep_kind_array { ($mod:ident) => {[ $($mod::$variant()),* ]}; } /// comment #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Encodable, Decodable)] #[allow(non_camel_case_types)] pub enum DepKind { $($variant),* } fn dep_kind_from_label_string(label: &str) -> Result { match label { $(stringify!($variant) => Ok(DepKind::$variant),)* _ => Err(()), } } /// comment /// comment #[allow(dead_code, non_upper_case_globals)] pub mod label_strs { $( pub const $variant: &str = stringify!($variant); )* } ); ($ty:ty { $(($($pat:tt)*))* }) => { impl FixedSizeEncoding for Option<$ty> { type ByteArray = [u8;1]; #[inline] fn from_bytes(b: &[u8;1]) -> Self { use $ty::*; if b[0] == 0 { return None; } match b[0] - 1 { $(${index()} => Some($($pat)*),)* _ => panic!("Unexpected ImplPolarity code: {:?}", b[0]), } } #[inline] fn write_to_bytes(self, b: &mut [u8;1]) { use $ty::*; b[0] = match self { None => 0, $(Some($($pat)*) => 1 + ${index()},)* } } } }; ($($name:ident: Table < $IDX:ty, $T:ty >),+ $(,)?) => { #[derive(MetadataEncodable, MetadataDecodable)] pub(crate) struct LazyTables { $($name: LazyTable<$IDX, $T>),+ } #[derive(Default)] struct TableBuilders { $($name: TableBuilder<$IDX, $T>),+ } impl TableBuilders { fn encode(&self, buf: &mut Encoder) -> LazyTables { LazyTables { $($name: self.$name.encode(buf)),+ } } } }; ($($name:ident($ty:ty);)*) => { $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> { self.opaque.$name(value) })* }; ($self:ident.$tables:ident.$table:ident [$def_id:expr] < -$value:expr) => { { { let value = $value; let lazy = $self.lazy(value); $self.$tables.$table.set($def_id.index, lazy); } } }; ( < $lt:tt > $tcx:ident, $def_id:ident, $other:ident, $cdata:ident, $name:ident => { table } ) => { provide_one! { <$lt> $tcx, $def_id, $other, $cdata, $name => { $cdata .root .tables .$name .get($cdata, $def_id.index) .map(|lazy| lazy.decode(($cdata, $tcx))) .process_decoded($tcx, || panic!("{:?} does not have a {:?}", $def_id, stringify!($name))) } } }; ( < $lt:tt > $tcx:ident, $def_id:ident, $other:ident, $cdata:ident, $( $name:ident => { $($compute:tt)* } )* ) => { pub fn provide_extern(providers: &mut ExternProviders) { $(provide_one! { <$lt> $tcx, $def_id, $other, $cdata, $name => { $($compute)* } })* *providers = ExternProviders { $($name,)* ..*providers }; } }; ( $(#[$attr:meta])* $vis:vis $NAME:ident, $Level:ident, $desc:expr ) => ( $crate::declare_lint!( $(#[$attr])* $vis $NAME, $Level, $desc, ); ); ( $(#[$attr:meta])* $vis:vis $NAME:ident, $Level:ident, $desc:expr, $(@feature_gate = $gate:expr;)? $( @future_incompatible = FutureIncompatibleInfo { $($field:ident: $val:expr),* $(,)* }; )? $($v:ident),* ) => ( $(#[$attr])* $vis static $NAME: &$crate::Lint = &$crate::Lint { name: stringify!($NAME), default_level: $crate::$Level, desc: $desc, edition_lint_opts: None, is_plugin: false, $($v: true,)* $(feature_gate: Some($gate),)* $(future_incompatible: Some($crate::FutureIncompatibleInfo { $($field: $val,)* ..$crate::FutureIncompatibleInfo::default_fields_for_macro() }),)* ..$crate::Lint::default_fields_for_macro() }; ); ( $(#[$attr:meta])* $vis:vis $NAME:ident, $Level:ident, $desc:expr, $lint_edition:expr => $edition_level:ident ) => ( $(#[$attr])* $vis static $NAME: &$crate::Lint = &$crate::Lint { name: stringify!($NAME), default_level: $crate::$Level, desc: $desc, edition_lint_opts: Some(($lint_edition, $crate::Level::$edition_level)), report_in_external_macro: false, is_plugin: false, }; ); ( $(#[$attr:meta])* $vis:vis $tool:ident::$NAME:ident, $Level:ident, $desc:expr ) => ( $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, false} ); ( $(#[$attr:meta])* $vis:vis $tool:ident::$NAME:ident, $Level:ident, $desc:expr, report_in_external_macro: $rep:expr ) => ( $crate::declare_tool_lint!{$(#[$attr])* $vis $tool::$NAME, $Level, $desc, $rep} ); ( $(#[$attr:meta])* $vis:vis $tool:ident::$NAME:ident, $Level:ident, $desc:expr, $external:expr ) => ( $(#[$attr])* $vis static $NAME: &$crate::Lint = &$crate::Lint { name: &concat!(stringify!($tool), "::", stringify!($NAME)), default_level: $crate::$Level, desc: $desc, edition_lint_opts: None, report_in_external_macro: $external, future_incompatible: None, is_plugin: true, feature_gate: None, crate_level_only: false, }; ); ($($lint:expr),*,) => { lint_array!( $($lint),* ) }; ($($lint:expr),*) => { { vec![$($lint),*] } }; ($ty:ty => [$($lint:expr),* $(,)?]) => { impl $crate::LintPass for $ty { fn name(&self) -> &'static str { stringify!($ty) } } impl $ty { pub fn get_lints() -> $crate::LintArray { $crate::lint_array!($($lint),*) } } }; ( $(#[$m:meta])* $name:ident => [$($lint:expr),* $(,)?] ) => { $(#[$m])* #[derive(Copy, Clone)] pub struct $name; $crate::impl_lint_pass!($name => [$($lint),*]); }; ( [$v:vis $name:ident, [$($passes:ident: $constructor:expr,)*]], [$hir:tt], $methods:tt ) => ( #[allow(non_snake_case)] $v struct $name { $($passes: $passes,)* } impl $name { $v fn new() -> Self { Self { $($passes: $constructor,)* } } $v fn get_lints() -> LintArray { let mut lints = Vec::new(); $(lints.extend_from_slice(&$passes::get_lints());)* lints } } impl<'tcx> LateLintPass<'tcx> for $name { expand_combined_late_lint_pass_methods!([$($passes),*], $methods); } #[allow(rustc::lint_pass_impl_without_macro)] impl LintPass for $name { fn name(&self) -> &'static str { panic!() } } ); ( $passes:tt, [ $( $(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*); )* ] ) => ( $(fn $name(&mut self, context: &LateContext<'tcx>, $($param: $arg),*) { expand_combined_late_lint_pass_method!($passes, self, $name, (context, $($param),*)); })* ); ([$($passes:ident),*], $self:ident, $name:ident, $params:tt) => ( { $($self.$passes.$name $params;)* } ); ( $context:ty, [ $( $(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*); )* ] ) => ( $(#[inline(always)] fn $name(&mut self, _: $context, $(_: $arg),*) {})* ); ( $context:ty, [ $( $(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*); )* ] ) => ( $(#[inline(always)] fn $name(&mut self, _: $context, $(_: $arg),*) {})* ); ([$($passes:ident),*], $self:ident, $name:ident, $params:tt) => ( { $($self.$passes.$name $params;)* } ); ( $passes:tt, [ $( $(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*); )* ] ) => ( $(fn $name(&mut self, context: &EarlyContext<'_>, $($param: $arg),*) { expand_combined_early_lint_pass_method!($passes, self, $name, (context, $($param),*)); })* ); ( [$v:vis $name:ident, [$($passes:ident: $constructor:expr,)*]], $methods:tt ) => ( #[allow(non_snake_case)] $v struct $name { $($passes: $passes,)* } impl $name { $v fn new() -> Self { Self { $($passes: $constructor,)* } } $v fn get_lints() -> LintArray { let mut lints = Vec::new(); $(lints.extend_from_slice(&$passes::get_lints());)* lints } } impl EarlyLintPass for $name { expand_combined_early_lint_pass_methods!([$($passes),*], $methods); } #[allow(rustc::lint_pass_impl_without_macro)] impl LintPass for $name { fn name(&self) -> &'static str { panic!() } } ); ($cx:expr, $f:ident, $($args:expr),*) => ( { $cx.pass.$f(&$cx.context, $($args),*); } ); ( [ $( $(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*); )* ] ) => ( $(fn $name(&mut self, context: &EarlyContext<'_>, $($param: $arg),*) { for obj in self.lints.iter_mut() { obj.$name(context, $($param),*); } })* ); ($ty:ty, $size:expr) => { const _: [(); $size] = [(); ::std::mem::size_of::<$ty>()]; }; ( $( $(#[$attr:meta])* $variant:ident $($group:expr)?, $module:ident::$name:ident, $method:ident, $target:expr, $generics:expr; )* ) => { enum_from_u32! { /// comment #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable)] pub enum LangItem { $( #[doc = concat!("The `", stringify!($name), "` lang item.")] /// comment $(#[$attr])* $variant, )* } } // comment }; ( $( $(#[doc = $doc:tt])* (removed, $feature:ident, $ver:expr, $issue:expr, None, $reason:expr), )+ ) => { /// comment pub const REMOVED_FEATURES: &[Feature] = &[ $( Feature { state: State::Removed { reason: $reason }, name: sym::$feature, since: $ver, issue: to_nonzero($issue), edition: None, } ),+ ]; }; ( $( $(#[doc = $doc:tt])* (stable_removed, $feature:ident, $ver:expr, $issue:expr, None), )+ ) => { /// comment pub const STABLE_REMOVED_FEATURES: &[Feature] = &[ $( Feature { state: State::Stabilized { reason: None }, name: sym::$feature, since: $ver, issue: to_nonzero($issue), edition: None, } ),+ ]; }; (Word) => { template!(@ true, None, None) }; (List: $descr:expr) => { template!(@ false, Some($descr), None) }; (NameValueStr: $descr:expr) => { template!(@ false, None, Some($descr)) }; (Word, List: $descr:expr) => { template!(@ true, Some($descr), None) }; ( Word, NameValueStr: $descr:expr ) => { template!(@ true, None, Some($descr)) }; (List: $descr1:expr, NameValueStr: $descr2:expr) => { template!(@ false, Some($descr1), Some($descr2)) }; (Word, List: $descr1:expr, NameValueStr: $descr2:expr) => { template!(@ true, Some($descr1), Some($descr2)) }; ( @ $word:expr, $list:expr, $name_value_str:expr ) => { AttributeTemplate { word: $word, list: $list, name_value_str: $name_value_str } }; ( $attr:ident, $typ:expr, $tpl:expr, $duplicates:expr $(, @ only_local: $only_local:expr)? $(,)? ) => { BuiltinAttribute { name: sym::$attr, only_local: or_default!(false, $($only_local)?), type_: $typ, template: $tpl, gate: Ungated, duplicates: $duplicates, } }; ($attr:ident) => { concat!("the `#[", stringify!($attr), "]` attribute is an experimental feature") }; ( $( $(#[doc = $doc:tt])* ($status:ident, $feature:ident, $ver:expr, $issue:expr, $edition:expr), )+ ) => { /// comment /// comment pub const ACTIVE_FEATURES: &[Feature] = &[$( // comment Feature { state: State::Active { set: set!($feature) }, name: sym::$feature, since: $ver, issue: to_nonzero($issue), edition: $edition, } ),+]; /// comment #[derive(Clone, Default, Debug)] pub struct Features { /// comment pub declared_lang_features: Vec<(Symbol, Span, Option)>, /// comment pub declared_lib_features: Vec<(Symbol, Span)>, /// comment pub active_features: FxHashSet, $( $(#[doc = $doc])* pub $feature: bool ),+ } impl Features { pub fn walk_feature_fields(&self, mut f: impl FnMut(&str, bool)) { $(f(stringify!($feature), self.$feature);)+ } /// comment pub fn active(&self, feature: Symbol) -> bool { self.active_features.contains(&feature) } /// comment /// comment /// comment pub fn enabled(&self, feature: Symbol) -> bool { match feature { $( sym::$feature => self.$feature, )* _ => panic!("`{}` was not listed in `declare_features`", feature), } } /// comment /// comment /// comment pub fn incomplete(&self, feature: Symbol) -> bool { match feature { $( sym::$feature => declare_features!(__status_to_bool $status), )* // comment _ if self.declared_lang_features.iter().any(|f| f.0 == feature) => false, _ if self.declared_lib_features.iter().any(|f| f.0 == feature) => false, _ => panic!("`{}` was not listed in `declare_features`", feature), } } } }; ( $( $Kind:ident($AstTy:ty) { $kind_name:expr; $( one fn $mut_visit_ast:ident; fn $visit_ast:ident; )? $( many fn $flat_map_ast_elt:ident; fn $visit_ast_elt:ident($($args:tt)*); )? fn $make_ast:ident; } )* ) => { /// comment /// comment pub enum AstFragment { OptExpr(Option>), $($Kind($AstTy),)* } /// comment #[derive(Copy, Clone, PartialEq, Eq)] pub enum AstFragmentKind { OptExpr, $($Kind,)* } impl AstFragmentKind { pub fn name(self) -> &'static str { match self { AstFragmentKind::OptExpr => "expression", $(AstFragmentKind::$Kind => $kind_name,)* } } fn make_from<'a>(self, result: Box) -> Option { match self { AstFragmentKind::OptExpr => result.make_expr().map(Some).map(AstFragment::OptExpr), $(AstFragmentKind::$Kind => result.$make_ast().map(AstFragment::$Kind),)* } } } impl AstFragment { pub fn add_placeholders(&mut self, placeholders: &[NodeId]) { if placeholders.is_empty() { return; } match self { $($(AstFragment::$Kind(ast) => ast.extend(placeholders.iter().flat_map(|id| { ${ignore(flat_map_ast_elt)} placeholder(AstFragmentKind::$Kind, *id, None).$make_ast() })),)?)* _ => panic!("unexpected AST fragment kind") } } pub fn make_opt_expr(self) -> Option> { match self { AstFragment::OptExpr(expr) => expr, _ => panic!("AstFragment::make_* called on the wrong kind of fragment"), } } $(pub fn $make_ast(self) -> $AstTy { match self { AstFragment::$Kind(ast) => ast, _ => panic!("AstFragment::make_* called on the wrong kind of fragment"), } })* fn make_ast(self) -> T::OutputTy { T::fragment_to_output(self) } pub fn mut_visit_with(&mut self, vis: &mut F) { match self { AstFragment::OptExpr(opt_expr) => { visit_clobber(opt_expr, |opt_expr| { if let Some(expr) = opt_expr { vis.filter_map_expr(expr) } else { None } }); } $($(AstFragment::$Kind(ast) => vis.$mut_visit_ast(ast),)?)* $($(AstFragment::$Kind(ast) => ast.flat_map_in_place(|ast| vis.$flat_map_ast_elt(ast)),)?)* } } pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) { match *self { AstFragment::OptExpr(Some(ref expr)) => visitor.visit_expr(expr), AstFragment::OptExpr(None) => {} $($(AstFragment::$Kind(ref ast) => visitor.$visit_ast(ast),)?)* $($(AstFragment::$Kind(ref ast) => for ast_elt in &ast[..] { visitor.$visit_ast_elt(ast_elt, $($args)*); })?)* } } } impl<'a> MacResult for crate::mbe::macro_rules::ParserAnyMacro<'a> { $(fn $make_ast(self: Box>) -> Option<$AstTy> { Some(self.make(AstFragmentKind::$Kind).$make_ast()) })* } }; ($($fld:ident: $t:ty,)*) => { /// comment /// comment #[derive(Default)] pub struct MacEager { $( pub $fld: Option<$t>, )* } impl MacEager { $( pub fn $fld(v: $t) -> Box { Box::new(MacEager { $fld: Some(v), ..Default::default() }) } )* } }; ( $session:expr, $span:expr, $code:ident, $($message:tt)* ) => ( { $session.struct_span_err_with_code( $span, &format!($($message)*), $crate::error_code!($code), ) } ); ( $(#[$attr:meta])* pub enum $name:ident { $( $(#[$var_attr:meta])* $variant:ident = $e:expr, )* } ) => { $(#[$attr])* pub enum $name { $($(#[$var_attr])* $variant = $e),* } impl $name { pub fn from_u32(u: u32) -> Option<$name> { $(if u == $name::$variant as u32 { return Some($name::$variant) })* None } } }; ( $(#[$attr:meta])* pub enum $name:ident { $( $(#[$var_attr:meta])* $variant:ident, )* } ) => { $(#[$attr])* pub enum $name { $($(#[$var_attr])* $variant,)* } impl $name { pub fn from_u32(u: u32) -> Option<$name> { $(if u == $name::$variant as u32 { return Some($name::$variant) })* None } } }; ( $e:expr, $where:expr, $( $($p:pat_param)|+ => { $($what_fmt:expr),+ } $(expected { $($expected_fmt:expr),+ })? ),+ $(,)? ) => { { match $e { Ok(x) => x, // comment // comment Err(e) => match e.kind() { $( $($p)|+ => throw_validation_failure!( $where, { $( $what_fmt ),+ } $( expected { $( $expected_fmt ),+ } )? ) ),+, #[allow(unreachable_patterns)] _ => Err::(e)?, } } } }; ( $where:expr, { $($what_fmt:expr),+ } $(expected { $($expected_fmt:expr),+ })? ) => { { let mut msg = String::new(); msg.push_str("encountered "); write!(&mut msg, $($what_fmt),+).unwrap(); $( msg.push_str(", but expected "); write!(&mut msg, $($expected_fmt),+).unwrap(); )? let path = rustc_middle::ty::print::with_no_trimmed_paths!({ let where_ = &$where; if !where_.is_empty() { let mut path = String::new(); write_path(&mut path, where_); Some(path) } else { None } }); throw_ub!(ValidationFailure { path, msg }) } }; ($($name:ident: $($($p:ident),* => $call:ident),*;)*) => { $(if name == sym::$name { match in_elem.kind() { $($(ty::$p(_))|* => { return Ok(bx.$call(args[0].immediate())) })* _ => {}, } require!(false, "unsupported operation on `{}` with element `{}`", in_ty, in_elem) })* }; ($($name:ident: $($($p:ident),* => $call:ident),*;)*) => { $(if name == sym::$name { match in_elem.kind() { $($(ty::$p(_))|* => { return Ok(bx.$call(args[0].immediate(), args[1].immediate())) })* _ => {}, } require!(false, "unsupported operation on `{}` with element `{}`", in_ty, in_elem) })* }; ( $register:ident; $(fn $name:ident($($arg_name:ident: $arg_ty:ty),*) -> $ret_ty:ty;)* ) => { #[cfg(feature = "jit")] #[allow(improper_ctypes)] extern "C" { $(fn $name($($arg_name: $arg_ty),*) -> $ret_ty;)* } #[cfg(feature = "jit")] pub(crate) fn $register(builder: &mut cranelift_jit::JITBuilder) { for (name, val) in [$((stringify!($name), $name as *const u8)),*] { builder.symbol(name, val); } } }; ( $fx:expr, $intrinsic:expr, $args:expr, _ => $unknown:block; $( $($($name:tt).*)|+ $(if $cond:expr)?, ($($a:ident $arg:ident),*) $content:block; )* ) => { match $intrinsic { $( $(intrinsic_pat!($($name).*))|* $(if $cond)? => { if let [$($arg),*] = $args { $(intrinsic_arg!($a $fx, $arg);)* $content } else { bug!("wrong number of args for intrinsic {:?}", $intrinsic); } } )* _ => $unknown, } }; ($($t:ty => $variant:path,)*) => { $( impl From<$t> for PrefValue { fn from(other: $t) -> Self { $variant(other.into()) } } )+ $( impl From> for PrefValue { fn from(other: Option<$t>) -> Self { other.map(|val| $variant(val.into())).unwrap_or(PrefValue::Missing) } } )+ }; ($($variant:path => $t:ty,)*) => { $( impl From for $t { #[allow(unsafe_code)] fn from(other: PrefValue) -> Self { if let $variant(value) = other { value.into() } else { panic!("Cannot convert {:?} to {:?}", other, std::any::type_name::<$t>()) } } } )+ $( impl From for Option<$t> { fn from(other: PrefValue) -> Self { if let PrefValue::Missing = other { None } else { Some(other.into()) } } } )+ }; ( $( $variant:path => { $($flex_relative_side:ident <= > $flow_relative_side:ident,)+ }, )+ ) => { pub fn sides_to_flex_relative(self, flow_relative: Sides) -> FlexRelativeSides { match self { $( $variant => FlexRelativeSides { $( $flex_relative_side: flow_relative.$flow_relative_side, )+ }, )+ } } pub fn sides_to_flow_relative(self, flex_relative: FlexRelativeSides) -> Sides { match self { $( $variant => Sides { $( $flow_relative_side: flex_relative.$flex_relative_side, )+ }, )+ } } }; ($($name:expr,)+) => { { $( atom_type.atom($name); )+ } }; ($tryer:ident, $getter:ident, $gltype:ty, $glcall:ident, $rstype:ty) => { #[allow(unsafe_code)] fn $tryer(self, parameter: GLenum) -> Option<$rstype> { let mut value = [<$gltype>::default()]; unsafe { self.$glcall(parameter, &mut value); } if self.get_error() != gl::NO_ERROR { None } else { Some(value[0] as $rstype) } } fn $getter(self, parameter: GLenum) -> $rstype { self.$tryer(parameter).unwrap() } }; ( $name:ident { $($variant:ident($kind:ident { $($param:ident = gl::$value:ident,)+ }),)+ } ) => { #[derive(Clone, Copy, Debug, Deserialize, Serialize)] pub enum $name { $( $variant($kind), )+} $( #[derive(Clone, Copy, Debug, Deserialize, Serialize)] #[repr(u32)] pub enum $kind { $( $param = gl::$value, )+} )+ impl $name { pub fn from_u32(value: u32) -> WebGLResult { match value { $($(gl::$value => Ok($name::$variant($kind::$param)),)+)+ _ => Err(WebGLError::InvalidEnum) } } } }; ( $( pub enum $name:ident { $($variant:ident = $mod:ident::$constant:ident,)+ } )* ) => { $( #[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf)] #[derive(PartialEq, Serialize)] #[repr(u32)] pub enum $name { $($variant = $mod::$constant,)+ } impl $name { pub fn from_gl_constant(constant: u32) -> Option { Some(match constant { $($mod::$constant => $name::$variant, )+ _ => return None, }) } #[inline] pub fn as_gl_constant(&self) -> u32 { *self as u32 } } )* }; ($t1:expr, $t2:expr, $t3:expr, $t4:expr) => { (($t1 as u32) << 24) | (($t2 as u32) << 16) | (($t3 as u32) << 8) | ($t4 as u32) }; ($result:expr) => ($result.map_err(|_| (()))?); ( $( $variant:path => { $($flex_relative_side:ident <= > $flow_relative_side:ident,)+ }, )+ ) => { pub fn sides_to_flex_relative(self, flow_relative: Sides) -> FlexRelativeSides { match self { $( $variant => FlexRelativeSides { $( $flex_relative_side: flow_relative.$flow_relative_side, )+ }, )+ } } pub fn sides_to_flow_relative(self, flex_relative: FlexRelativeSides) -> Sides { match self { $( $variant => Sides { $( $flow_relative_side: flex_relative.$flex_relative_side, )+ }, )+ } } }; ( $prev:ident, $name:ident, $($rest:ident,)* [$($tt:tt)*] ) => { capabilities!($name, $($rest,)* [$($tt)* $name = Self::$prev.bits << 1;]); }; ( [$($InSelector:tt)*] [$($CommonBounds:tt)*] [$($FromStr:tt)*] ) => { /// comment /// comment pub trait SelectorImpl: Clone + Debug + Sized + 'static { type ExtraMatchingData: Sized + Default + 'static; type AttrValue: $($InSelector)*; type Identifier: $($InSelector)*; type LocalName: $($InSelector)* + Borrow; type NamespaceUrl: $($CommonBounds)* + Default + Borrow; type NamespacePrefix: $($InSelector)* + Default; type BorrowedNamespaceUrl: ?Sized + Eq; type BorrowedLocalName: ?Sized + Eq; /// comment /// comment type NonTSPseudoClass: $($CommonBounds)* + NonTSPseudoClass; /// comment type PseudoElement: $($CommonBounds)* + PseudoElement; } }; ( [$($CommonBounds:tt)*] [$($FromStr:tt)*] ) => { with_all_bounds! { [$($CommonBounds)* + $($FromStr)* + ToCss] [$($CommonBounds)*] [$($FromStr)*] } }; ($({ $name:ident, $boxed:expr })+) => { /// comment /// comment /// comment pub mod computed_values { $( pub use crate::properties::longhands::$name::computed_value as $name; )+ // comment pub use crate::properties::longhands::border_top_style::computed_value as border_style; } }; ($($fun:ident = $flag:path;)*) => ( impl ThreadState { /// comment pub fn is_worker(self) -> bool { self.contains(ThreadState::IN_WORKER) } $( #[allow(missing_docs)] pub fn $fun(self) -> bool { self.contains($flag) } )* } ); ($self:ident.$checker:ident($value:ident)) => { if !$self.$checker(&$value) { return false; } }; ( $( #[$doc:meta] $name:tt $ident:ident / $setter:ident [$checker:tt]: $ty:ty, )+ ) => { /// comment #[derive(Clone, Debug, ToShmem)] pub struct CounterStyleRuleData { name: CustomIdent, generation: Wrapping, $( #[$doc] $ident: Option<$ty>, )+ /// comment pub source_location: SourceLocation, } impl CounterStyleRuleData { fn empty(name: CustomIdent, source_location: SourceLocation) -> Self { CounterStyleRuleData { name: name, generation: Wrapping(0), $( $ident: None, )+ source_location, } } $( #[$doc] pub fn $ident(&self) -> Option<&$ty> { self.$ident.as_ref() } )+ $( #[$doc] pub fn $setter(&mut self, value: $ty) -> bool { checker!(self.$checker(value)); self.$ident = Some(value); self.generation += Wrapping(1); true } )+ } }; ([$(($css:expr, $name:ident, $state:tt, $flags:tt),)*]) => { /// comment #[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, ToShmem)] pub enum NonTSPseudoClass { $( #[doc = $css] $name, )* /// comment Lang(Lang), /// comment Dir(Direction), /// comment MozLocaleDir(Direction), } }; ([$(($css:expr, $name:ident, $state:tt, $flags:tt),)*]) => { match *self { $(NonTSPseudoClass::$name => concat!(":", $css),)* NonTSPseudoClass::Lang(ref s) => { dest.write_str(":lang(")?; s.to_css(dest)?; return dest.write_char(')'); }, NonTSPseudoClass::MozLocaleDir(ref dir) => { dest.write_str(":-moz-locale-dir(")?; dir.to_css(&mut CssWriter::new(dest))?; return dest.write_char(')') }, NonTSPseudoClass::Dir(ref dir) => { dest.write_str(":dir(")?; dir.to_css(&mut CssWriter::new(dest))?; return dest.write_char(')') }, } }; ([$(($css:expr, $name:ident, $state:tt, $flags:tt),)*]) => { match_ignore_ascii_case! { &name, $($css => Some(NonTSPseudoClass::$name),)* "-moz-full-screen" => Some(NonTSPseudoClass::Fullscreen), "-moz-read-only" => Some(NonTSPseudoClass::ReadOnly), "-moz-read-write" => Some(NonTSPseudoClass::ReadWrite), "-moz-focusring" => Some(NonTSPseudoClass::FocusVisible), "-moz-ui-valid" => Some(NonTSPseudoClass::UserValid), "-moz-ui-invalid" => Some(NonTSPseudoClass::UserInvalid), "-webkit-autofill" => Some(NonTSPseudoClass::Autofill), _ => None, } }; ($t:ty, $addref:path, $release:path) => { unsafe impl RefCounted for $t { #[inline] fn addref(&self) { unsafe { $addref(self as *const _ as *mut _) } } #[inline] unsafe fn release(&self) { $release(self as *const _ as *mut _) } } }; ($($name:ident: $value:expr),+) => { expanded!( $( $name: $value, )+ ) }; ($($name:ident: $value:expr,)+) => { Longhands { $( $name: MaybeBoxed::maybe_boxed($value), )+ } }; (< $t:ident > for $ty:ty) => { impl<$t> ListAnimation<$t> for $ty { fn animate_repeatable_list( &self, other: &Self, procedure: Procedure, ) -> Result where T: Animate, { // comment if self.is_empty() || other.is_empty() { return Err(()); } use num_integer::lcm; let len = lcm(self.len(), other.len()); self.iter().cycle().zip(other.iter().cycle()).take(len).map(|(this, other)| { this.animate(other, procedure) }).collect() } fn squared_distance_repeatable_list( &self, other: &Self, ) -> Result where T: ComputeSquaredDistance, { if self.is_empty() || other.is_empty() { return Err(()); } use num_integer::lcm; let len = lcm(self.len(), other.len()); self.iter().cycle().zip(other.iter().cycle()).take(len).map(|(this, other)| { this.compute_squared_distance(other) }).sum() } fn animate_with_zero( &self, other: &Self, procedure: Procedure, ) -> Result where T: Animate + Clone + ToAnimatedZero { if procedure == Procedure::Add { return Ok( self.iter().chain(other.iter()).cloned().collect() ); } self.iter().zip_longest(other.iter()).map(|it| { match it { EitherOrBoth::Both(this, other) => { this.animate(other, procedure) }, EitherOrBoth::Left(this) => { this.animate(&this.to_animated_zero()?, procedure) }, EitherOrBoth::Right(other) => { other.to_animated_zero()?.animate(other, procedure) } } }).collect() } fn squared_distance_with_zero( &self, other: &Self, ) -> Result where T: ToAnimatedZero + ComputeSquaredDistance { self.iter().zip_longest(other.iter()).map(|it| { match it { EitherOrBoth::Both(this, other) => { this.compute_squared_distance(other) }, EitherOrBoth::Left(list) | EitherOrBoth::Right(list) => { list.to_animated_zero()?.compute_squared_distance(list) }, } }).sum() } } }; ($name:path) => { impl From for $name { fn from(bits: u8) -> $name { $name(crate::values::specified::align::AlignFlags::from_bits(bits) .expect("bits contain valid flag")) } } impl From<$name> for u8 { fn from(v: $name) -> u8 { v.0.bits() } } }; ($($method:ident($variant:ident => $rule_type:ident),)+) => { $( #[allow(missing_docs)] fn $method(&self, device: &Device, guard: &SharedRwLockReadGuard, mut f: F) where F: FnMut(&crate::stylesheets::$rule_type), { use crate::stylesheets::CssRule; for rule in self.effective_rules(device, guard) { if let CssRule::$variant(ref lock) = *rule { let rule = lock.read_with(guard); f(&rule) } } } )+ }; ($($variant_name:expr => $variant:ident($data:ident),)+) => { declare_viewport_descriptor_inner!([] [ $( $variant_name => $variant($data), )+ ] 0); }; ( [ $( $assigned_variant_name:expr => $assigned_variant:ident($assigned_data:ident) = $assigned_discriminant:expr, )* ] [ $next_variant_name:expr => $next_variant:ident($next_data:ident), $($variant_name:expr => $variant:ident($data:ident),)* ] $next_discriminant:expr ) => { declare_viewport_descriptor_inner! { [ $( $assigned_variant_name => $assigned_variant($assigned_data) = $assigned_discriminant, )* $next_variant_name => $next_variant($next_data) = $next_discriminant, ] [ $( $variant_name => $variant($data), )* ] $next_discriminant + 1 } }; ( [ $( $assigned_variant_name:expr => $assigned_variant:ident($assigned_data:ident) = $assigned_discriminant:expr, )* ] [] $number_of_variants:expr ) => { #[derive(Clone, Debug, PartialEq, ToShmem)] #[cfg_attr(feature = "servo", derive(MallocSizeOf))] #[allow(missing_docs)] pub enum ViewportDescriptor { $( $assigned_variant($assigned_data), )+ } impl ViewportDescriptor { #[allow(missing_docs)] pub fn discriminant_value(&self) -> usize { match *self { $( ViewportDescriptor::$assigned_variant(..) => $assigned_discriminant, )* } } } }; { $( $(#[$($meta:tt)+])* $ident:ident / $css:expr => $gecko:ident = $value:expr, )+ } => { bitflags! { #[derive(MallocSizeOf, ToResolvedValue, ToShmem)] /// comment pub struct VariantEastAsian: u16 { /// comment const NORMAL = 0; $( $(#[$($meta)+])* const $ident = $value; )+ } } impl ToCss for VariantEastAsian { fn to_css(&self, dest: &mut CssWriter) { $( if self.intersects(VariantEastAsian::$ident) { writer.raw_item($css)?; } )+ Ok(()) } } /// comment #[cfg(feature = "gecko")] #[inline] pub fn assert_variant_east_asian_matches() { use crate::gecko_bindings::structs; $(debug_assert_eq!(structs::$gecko as u16, VariantEastAsian::$ident.bits());)+ } impl SpecifiedValueInfo for VariantEastAsian { fn collect_completion_keywords(f: KeywordsCollectFn) { f(&["normal", $($css,)+]); } } }; ( $parser:ident, $abs:ident, $enum:ident, [$para:ident => $func:ident $(, $other_para:ident => $other_func:ident)*] ) => { { loop { let $para = $func(&mut $parser.chars)?; $( skip_comma_wsp(&mut $parser.chars); let $other_para = $other_func(&mut $parser.chars)?; )* $parser.path.push(PathCommand::$enum { $para $(, $other_para)*, $abs }); // comment if !skip_wsp(&mut $parser.chars) || $parser.chars.peek().map_or(true, |c| c.is_ascii_alphabetic()) { break; } skip_comma_wsp(&mut $parser.chars); } Ok(()) } }; (pub enum $name:ident { $($variant:ident = $css:expr,)+ }) => { #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[derive(Clone, Copy, Debug, Eq, Hash, MallocSizeOf, PartialEq, ToShmem)] pub enum $name { $($variant),+ } impl $name { /// comment pub fn parse<'i, 't>(input: &mut ::cssparser::Parser<'i, 't>) -> Result<$name, $crate::ParseError<'i>> { use cssparser::Token; let location = input.current_source_location(); match *input.next()? { Token::Ident(ref ident) => { Self::from_ident(ident).map_err(|()| { location.new_unexpected_token_error( Token::Ident(ident.clone()), ) }) } ref token => { Err(location.new_unexpected_token_error(token.clone())) } } } /// comment pub fn from_ident(ident: &str) -> Result<$name, ()> { match_ignore_ascii_case! { ident, $($css => Ok($name::$variant),)+ _ => Err(()) } } } impl $crate::ToCss for $name { fn to_css( &self, dest: &mut $crate::CssWriter, ) -> ::std::fmt::Result where W: ::std::fmt::Write, { match *self { $( $name::$variant => ::std::fmt::Write::write_str(dest, $css) ),+ } } } }; ($($ty:ty),*) => { $( impl $crate::ToShmem for $ty { fn to_shmem( &self, _builder: &mut $crate::SharedMemoryBuilder, ) -> $crate::Result { $crate::Result::Ok(::std::mem::ManuallyDrop::new(*self)) } } )* }; ($($fun:ident = $flag:ident;)*) => (); ($($name:expr,)+) => { { $( atom_type.atom($name); )+ } }; ( $name:ident { $($variant:ident($kind:ident { $($param:ident = gl::$value:ident,)+ }),)+ } ) => { #[derive(Clone, Copy, Debug, Deserialize, Serialize)] pub enum $name { $( $variant($kind), )+} $( #[derive(Clone, Copy, Debug, Deserialize, Serialize)] #[repr(u32)] pub enum $kind { $( $param = gl::$value, )+} )+ impl $name { pub fn from_u32(value: u32) -> WebGLResult { match value { $($(gl::$value => Ok($name::$variant($kind::$param)),)+)+ _ => Err(WebGLError::InvalidEnum) } } } }; ( $( pub enum $name:ident { $($variant:ident = $mod:ident::$constant:ident,)+ } )* ) => { $( #[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf)] #[derive(PartialEq, Serialize)] #[repr(u32)] pub enum $name { $($variant = $mod::$constant,)+ } impl $name { pub fn from_gl_constant(constant: u32) -> Option { Some(match constant { $($mod::$constant => $name::$variant, )+ _ => return None, }) } #[inline] pub fn as_gl_constant(&self) -> u32 { *self as u32 } } )* }; ($({ $name:ident, $boxed:expr })+) => { /// comment /// comment /// comment pub mod computed_values { $(pub use crate::properties::longhands::$name::computed_value as $name;)+ // comment pub use crate::properties::longhands::border_top_style::computed_value as border_style; } }; ($($fun:ident = $flag:path;)*) => ( impl ThreadState { /// comment pub fn is_worker(self) -> bool { self.contains(ThreadState::IN_WORKER) } $( #[allow(missing_docs)] pub fn $fun(self) -> bool { self.contains($flag) } )* } ); ([$(($css:expr, $name:ident, $state:tt, $flags:tt),)*]) => { /// comment #[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, ToShmem)] pub enum NonTSPseudoClass { $( #[doc = $css] $name, )* } }; ($($name:ident: $value:expr),+) => { expanded!( $( $name: $value, )+ ) }; ($($name:ident: $value:expr,)+) => { Longhands { $( $name: MaybeBoxed::maybe_boxed($value), )+ } }; ($($variant_name:expr => $variant:ident($data:ident),)+) => { declare_viewport_descriptor_inner!([] [ $( $variant_name => $variant($data), )+ ] 0); }; ( [ $( $assigned_variant_name:expr => $assigned_variant:ident($assigned_data:ident) = $assigned_discriminant:expr, )* ] [ $next_variant_name:expr => $next_variant:ident($next_data:ident), $($variant_name:expr => $variant:ident($data:ident),)* ] $next_discriminant:expr ) => { declare_viewport_descriptor_inner! { [ $( $assigned_variant_name => $assigned_variant($assigned_data) = $assigned_discriminant, )* $next_variant_name => $next_variant($next_data) = $next_discriminant, ] [ $( $variant_name => $variant($data), )* ] $next_discriminant + 1 } }; ($($name:expr,)+) => { f(&["symbols", $($name,)+]) }; ( $parser:ident, $abs:ident, $enum:ident, [$para:ident => $func:ident $(, $other_para:ident => $other_func:ident)*] ) => { { loop { let $para = $func(&mut $parser.chars)?; $( skip_comma_wsp(&mut $parser.chars); let $other_para = $other_func(&mut $parser.chars)?; )* $parser.path.push(PathCommand::$enum { $para $(, $other_para)*, $abs }); // comment if !skip_wsp(&mut $parser.chars) || $parser.chars.peek().map_or(true, |c| c.is_ascii_alphabetic()) { break; } skip_comma_wsp(&mut $parser.chars); } Ok(()) } }; ($({ $name:ident, $boxed:expr })+) => { $( let size = size_of::(); let is_boxed = $boxed; if (!is_boxed && size > threshold) || (is_boxed && size <= threshold) { bad_properties.push((stringify!($name), size, is_boxed)); } )+ }; ( $vis:vis const $name:ident: $ty:ty = $e:expr; ) => { $vis const $name: $ty = $e; }; ($vis:vis enum $name:ident {}) => { $vis struct $name {} }; ( $vis:vis extern "C" fn $name:ident() {} ) => { $vis extern "C" fn $name() {} }; ($vis:vis fn $name:ident() {}) => { $vis fn $name() {} }; ($vis:vis mod $name:ident {}) => { $vis mod $name {} }; ( $vis:vis static $name:ident: $ty:ty = $e:expr; ) => { $vis static $name: $ty = $e; }; ($vis:vis struct $name:ident;) => { $vis struct $name; }; ($vis:vis trait $name:ident {}) => { $vis trait $name {} }; ($vis:vis type $name:ident = $ty:ty;) => { $vis type $name = $ty; }; ( $vis:vis use $path:ident as $name:ident; ) => { $vis use self::$path as $name; }; ( $(#[$($attrs:tt)*])* $vis:vis struct $name:ident { $($body:tt)* } ) => { c! { @parse_fields $(#[$($attrs)*])*, $vis, $name, $($body)* } }; ( $(#[$($attrs:tt)*])* $vis:vis struct $name:ident($($body:tt)*); ) => { c! { @parse_tuple $(#[$($attrs)*])*, $vis, $name, $($body)* } }; ( @parse_fields $(#[$attrs:meta])*, $vis:vis, $name:ident, $($fvis:vis $fname:ident: $fty:ty),* $(,)* ) => { $(#[$attrs])* $vis struct $name { $($fvis $fname: $fty,)* } }; ( @parse_tuple $(#[$attrs:meta])*, $vis:vis, $name:ident, $($fvis:vis $fty:ty),* $(,)* ) => { $(#[$attrs])* $vis struct $name ( $($fvis $fty,)* ); }; ( $( $(#[$attr:meta])* struct $Name:ident impl $(< $($lifetime:lifetime),+ >)? Fn = | $( $arg:ident: $ArgTy:ty ),* | -> $ReturnTy:ty $body:block; )+ ) => { $( $( #[$attr] )* struct $Name; impl $( <$( $lifetime ),+> )? Fn<($( $ArgTy, )*)> for $Name { #[inline] extern "rust-call" fn call(&self, ($( $arg, )*): ($( $ArgTy, )*)) -> $ReturnTy { $body } } impl $( <$( $lifetime ),+> )? FnMut<($( $ArgTy, )*)> for $Name { #[inline] extern "rust-call" fn call_mut( &mut self, ($( $arg, )*): ($( $ArgTy, )*) ) -> $ReturnTy { Fn::call(&*self, ($( $arg, )*)) } } impl $( <$( $lifetime ),+> )? FnOnce<($( $ArgTy, )*)> for $Name { type Output = $ReturnTy; #[inline] extern "rust-call" fn call_once(self, ($( $arg, )*): ($( $ArgTy, )*)) -> $ReturnTy { Fn::call(&self, ($( $arg, )*)) } } )+ }; ( $( if #[cfg($i_meta:meta)] { $($i_tokens:tt)* } )else+ else { $($e_tokens:tt)* } ) => { cfg_if! { @__items () ; $( (( $i_meta ) ( $( $i_tokens )* )) , )+ (() ( $( $e_tokens )* )) , } }; (@__items($($_:meta,)*);) => {}; ( @__items($($no:meta,)*); ( ($($yes:meta)?) ($($tokens:tt)*) ), $($rest:tt,)* ) => { #[cfg(all( $( $yes , )? not(any( $( $no ),* )) ))] cfg_if! { @__identity $( $tokens )* } cfg_if! { @__items ( $( $no , )* $( $yes , )? ) ; $( $rest , )* } }; ( @__identity $($tokens:tt)* ) => { $( $tokens )* }; (impl $imp:ident, $method:ident for $t:ty, $u:ty) => { forward_ref_op_assign!(impl $imp, $method for $t, $u, #[stable(feature = "op_assign_builtins_by_ref", since = "1.22.0")]); }; ( impl const $imp:ident, $method:ident for $t:ty, $u:ty ) => { forward_ref_op_assign!(impl const $imp, $method for $t, $u, #[stable(feature = "op_assign_builtins_by_ref", since = "1.22.0")]); }; // comment ( impl const $imp:ident, $method:ident for $t:ty, $u:ty, #[$attr:meta] ) => { #[$attr] #[rustc_const_unstable(feature = "const_ops", issue = "90080")] impl const $imp<&$u> for $t { #[inline] fn $method(&mut self, other: &$u) { $imp::$method(self, *other); } } }; (impl $imp:ident, $method:ident for $t:ty, $u:ty, #[$attr:meta]) => { #[$attr] impl $imp<&$u> for $t { #[inline] fn $method(&mut self, other: &$u) { $imp::$method(self, *other); } } }; (@impl $($T:ident)+) => { maybe_tuple_doc! { $($T)+ @ #[stable(feature = "rust1", since = "1.0.0")] impl<$($T:PartialEq),+> PartialEq for ($($T,)+) where last_type!($($T,)+): ?Sized { #[inline] fn eq(&self, other: &($($T,)+)) -> bool { $( ${ignore(T)} self.${index()} == other.${index()} )&&+ } #[inline] fn ne(&self, other: &($($T,)+)) -> bool { $( ${ignore(T)} self.${index()} != other.${index()} )||+ } } } maybe_tuple_doc! { $($T)+ @ #[stable(feature = "rust1", since = "1.0.0")] impl<$($T:Eq),+> Eq for ($($T,)+) where last_type!($($T,)+): ?Sized {} } maybe_tuple_doc! { $($T)+ @ #[stable(feature = "rust1", since = "1.0.0")] impl<$($T:PartialOrd + PartialEq),+> PartialOrd for ($($T,)+) where last_type!($($T,)+): ?Sized { #[inline] fn partial_cmp(&self, other: &($($T,)+)) -> Option { lexical_partial_cmp!($( ${ignore(T)} self.${index()}, other.${index()} ),+) } #[inline] fn lt(&self, other: &($($T,)+)) -> bool { lexical_ord!(lt, $( ${ignore(T)} self.${index()}, other.${index()} ),+) } #[inline] fn le(&self, other: &($($T,)+)) -> bool { lexical_ord!(le, $( ${ignore(T)} self.${index()}, other.${index()} ),+) } #[inline] fn ge(&self, other: &($($T,)+)) -> bool { lexical_ord!(ge, $( ${ignore(T)} self.${index()}, other.${index()} ),+) } #[inline] fn gt(&self, other: &($($T,)+)) -> bool { lexical_ord!(gt, $( ${ignore(T)} self.${index()}, other.${index()} ),+) } } } maybe_tuple_doc! { $($T)+ @ #[stable(feature = "rust1", since = "1.0.0")] impl<$($T:Ord),+> Ord for ($($T,)+) where last_type!($($T,)+): ?Sized { #[inline] fn cmp(&self, other: &($($T,)+)) -> Ordering { lexical_cmp!($( ${ignore(T)} self.${index()}, other.${index()} ),+) } } } maybe_tuple_doc! { $($T)+ @ #[stable(feature = "rust1", since = "1.0.0")] impl<$($T:Default),+> Default for ($($T,)+) { #[inline] fn default() -> ($($T,)+) { ($({ let x: $T = Default::default(); x},)+) } } } }; ($left:expr, $right:expr $(,)?) => { match (&$left, &$right) { (left_val, right_val) => { if !(*left_val == *right_val) { let kind = $crate::panicking::AssertKind::Eq; // comment // comment // comment $crate::panicking::assert_failed(kind, &*left_val, &*right_val, $crate::option::Option::None); } } } }; ( $left:expr, $right:expr, $($arg:tt)+ ) => { match (&$left, &$right) { (left_val, right_val) => { if !(*left_val == *right_val) { let kind = $crate::panicking::AssertKind::Eq; // comment // comment // comment $crate::panicking::assert_failed(kind, &*left_val, &*right_val, $crate::option::Option::Some($crate::format_args!($($arg)+))); } } } }; ($left:expr, $(|)? $($pattern:pat_param)|+ $(if $guard:expr)? $(,)?) => { match $left { $( $pattern )|+ $( if $guard )? => {} ref left_val => { $crate::panicking::assert_matches_failed( left_val, $crate::stringify!($($pattern)|+ $(if $guard)?), $crate::option::Option::None ); } } }; ( $left:expr, $(|)? $($pattern:pat_param)|+ $(if $guard:expr)?, $($arg:tt)+ ) => { match $left { $( $pattern )|+ $( if $guard )? => {} ref left_val => { $crate::panicking::assert_matches_failed( left_val, $crate::stringify!($($pattern)|+ $(if $guard)?), $crate::option::Option::Some($crate::format_args!($($arg)+)) ); } } }; ( $expression:expr, $(|)? $($pattern:pat_param)|+ $(if $guard:expr)? $(,)? ) => { match $expression { $( $pattern )|+ $( if $guard )? => true, _ => false } }; ( enum $name:ident < $($T:ident),+ > { $($variant:ident $(($field:ident))?),* $(,)? } ) => { impl<$($T: Mark),+> Mark for $name <$($T),+> { type Unmarked = $name <$($T::Unmarked),+>; fn mark(unmarked: Self::Unmarked) -> Self { match unmarked { $($name::$variant $(($field))? => { $name::$variant $((Mark::mark($field)))? })* } } } impl<$($T: Unmark),+> Unmark for $name <$($T),+> { type Unmarked = $name <$($T::Unmarked),+>; fn unmark(self) -> Self::Unmarked { match self { $($name::$variant $(($field))? => { $name::$variant $((Unmark::unmark($field)))? })* } } } }; (struct $name:ident $(< $($T:ident),+ >)? { $($field:ident),* $(,)? }) => { impl),+)?> Encode for $name $(<$($T),+>)? { fn encode(self, w: &mut Writer, s: &mut S) { $(self.$field.encode(w, s);)* } } impl<'a, S, $($($T: for<'s> DecodeMut<'a, 's, S>),+)?> DecodeMut<'a, '_, S> for $name $(<$($T),+>)? { fn decode(r: &mut Reader<'a>, s: &mut S) -> Self { $name { $($field: DecodeMut::decode(r, s)),* } } } }; ( enum $name:ident $(< $($T:ident),+ >)? { $($variant:ident $(($field:ident))*),* $(,)? } ) => { impl),+)?> Encode for $name $(<$($T),+>)? { fn encode(self, w: &mut Writer, s: &mut S) { // comment // comment #[allow(non_upper_case_globals)] mod tag { #[repr(u8)] enum Tag { $($variant),* } $(pub const $variant: u8 = Tag::$variant as u8;)* } match self { $($name::$variant $(($field))* => { tag::$variant.encode(w, s); $($field.encode(w, s);)* })* } } } impl<'a, S, $($($T: for<'s> DecodeMut<'a, 's, S>),+)?> DecodeMut<'a, '_, S> for $name $(<$($T),+>)? { fn decode(r: &mut Reader<'a>, s: &mut S) -> Self { // comment // comment #[allow(non_upper_case_globals)] mod tag { #[repr(u8)] enum Tag { $($variant),* } $(pub const $variant: u8 = Tag::$variant as u8;)* } match u8::decode(r, s) { $(tag::$variant => { $(let $field = DecodeMut::decode(r, s);)* $name::$variant $(($field))* })* _ => unreachable!(), } } } }; ( $( fn $name:ident $(< $($param:ident),* >)? for $(extern $abi:tt)? fn( $($arg:ident: $arg_ty:ty),* ) -> $ret_ty:ty; )+ ) => { $(pub const fn $name< $($($param,)*)? F: Fn($($arg_ty),*) -> $ret_ty + Copy >(f: F) -> $(extern $abi)? fn($($arg_ty),*) -> $ret_ty { // comment // comment assert!(mem::size_of::() == 0, "selfless_reify: closure must be zero-sized"); $(extern $abi)? fn wrapper< $($($param,)*)? F: Fn($($arg_ty),*) -> $ret_ty + Copy >($($arg: $arg_ty),*) -> $ret_ty { let f = unsafe { // comment // comment mem::MaybeUninit::::uninit().assume_init() }; f($($arg),*) } let _f_proof = f; wrapper::< $($($param,)*)? F > })+ }; ( fn drop(&mut self, $arg:ident: $arg_ty:ty) ) => (fn drop(&mut self, $arg: $arg_ty) { mem::drop($arg) }); ( fn clone(&mut self, $arg:ident: $arg_ty:ty) -> $ret_ty:ty ) => (fn clone(&mut self, $arg: $arg_ty) -> $ret_ty { $arg.clone() }); ($e:expr) => { { loop { match $e { Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {} res => break res, } } } }; ($($x:ident),*) => { $( // comment )* }; } macro path_local($x:ident) { generic::ty::Path::new_local(sym::$x) } macro pathvec_std($($rest:ident)::+) { { vec![ $( sym::$rest ),+ ] } } macro path_std($($x:tt)*) { generic::ty::Path::new( pathvec_std!( $($x)* ) ) } macro takes_u32_returns_u32($ident:ident) { fn $ident(arg: u32) -> u32; } macro simple_nonterminal($nt_ident:ident, $nt_lifetime:lifetime, $nt_tt:tt) { macro n(a $nt_ident b $nt_lifetime c $nt_tt d) { struct S; } n!(a $nt_ident b $nt_lifetime c $nt_tt d); } macro complex_nonterminal($nt_item:item) { macro n(a $nt_item b) { struct S; } n!(a $nt_item b); // comment } // source: "../../../ext/jinx-rust/tests/samples/macro/macro.transform.rs" ================================================ FILE: tests/output-ext/miscellaneous/ast-program-locs-attr-dangling.f.rs ================================================ #!shebang // comment struct T;#[attr] // comment // source: "../../../ext/jinx-rust/tests/samples/miscellaneous/ast-program-locs-attr-dangling.rs" ================================================ FILE: tests/output-ext/miscellaneous/ast-program-locs-attr.f.rs ================================================ #!shebang // comment #[attr] struct T; // comment // source: "../../../ext/jinx-rust/tests/samples/miscellaneous/ast-program-locs-attr.rs" ================================================ FILE: tests/output-ext/miscellaneous/ast-program-locs.f.rs ================================================ #!shebang // comment struct T; // comment // source: "../../../ext/jinx-rust/tests/samples/miscellaneous/ast-program-locs.rs" ================================================ FILE: tests/output-ext/miscellaneous/empty-attr-dangling-x.f.rs ================================================ #[attr] #[attr] #[attr] // source: "../../../ext/jinx-rust/tests/samples/miscellaneous/empty-attr-dangling-x.rs" ================================================ FILE: tests/output-ext/miscellaneous/empty-attr-dangling.f.rs ================================================ #[attr] // source: "../../../ext/jinx-rust/tests/samples/miscellaneous/empty-attr-dangling.rs" ================================================ FILE: tests/output-ext/miscellaneous/empty-attr-x.f.rs ================================================ #![attr] #![attr] #![attr] // source: "../../../ext/jinx-rust/tests/samples/miscellaneous/empty-attr-x.rs" ================================================ FILE: tests/output-ext/miscellaneous/empty-attr.f.rs ================================================ #![attr] // source: "../../../ext/jinx-rust/tests/samples/miscellaneous/empty-attr.rs" ================================================ FILE: tests/output-ext/miscellaneous/empty-comment-block-x.f.rs ================================================ /* */ /* */ /* */ // source: "../../../ext/jinx-rust/tests/samples/miscellaneous/empty-comment-block-x.rs" ================================================ FILE: tests/output-ext/miscellaneous/empty-comment-block.f.rs ================================================ /* */ // source: "../../../ext/jinx-rust/tests/samples/miscellaneous/empty-comment-block.rs" ================================================ FILE: tests/output-ext/miscellaneous/empty-comment-x.f.rs ================================================ // // // // source: "../../../ext/jinx-rust/tests/samples/miscellaneous/empty-comment-x.rs" ================================================ FILE: tests/output-ext/miscellaneous/empty-comment.f.rs ================================================ // // source: "../../../ext/jinx-rust/tests/samples/miscellaneous/empty-comment.rs" ================================================ FILE: tests/output-ext/miscellaneous/empty-doc-block-x.f.rs ================================================ /** */ /** */ /** */ // source: "../../../ext/jinx-rust/tests/samples/miscellaneous/empty-doc-block-x.rs" ================================================ FILE: tests/output-ext/miscellaneous/empty-doc-block.f.rs ================================================ /** */ // source: "../../../ext/jinx-rust/tests/samples/miscellaneous/empty-doc-block.rs" ================================================ FILE: tests/output-ext/miscellaneous/empty-doc-x.f.rs ================================================ /// /// /// // source: "../../../ext/jinx-rust/tests/samples/miscellaneous/empty-doc-x.rs" ================================================ FILE: tests/output-ext/miscellaneous/empty-doc.f.rs ================================================ /// // source: "../../../ext/jinx-rust/tests/samples/miscellaneous/empty-doc.rs" ================================================ FILE: tests/output-ext/miscellaneous/empty.f.rs ================================================ // source: "../../../ext/jinx-rust/tests/samples/miscellaneous/empty.rs" ================================================ FILE: tests/output-ext/miscellaneous/shebang-b.f.rs ================================================ #!/usr/bin/env bash #![forbid(unsafe_code)] /* This line is ignored by bash # This block is ignored by rustc #*/ //! use std; // source: "../../../ext/jinx-rust/tests/samples/miscellaneous/shebang-b.rs" ================================================ FILE: tests/output-ext/miscellaneous/shebang.f.rs ================================================ #!/usr/bin/env rustx // source: "../../../ext/jinx-rust/tests/samples/miscellaneous/shebang.rs" ================================================ FILE: tests/output-ext/patterns/pattern.f.rs ================================================ fn a() { fn eq(&&other: S) { false } let -2147483648..=2147483647 = 1; let 0..=255 = 0u8; let -128..=127 = 0i8; let '\u{0000}'..='\u{10FFFF}' = 'v'; let f = |3: isize| println!("hello"); match *self { Foo::(ref x, ref y) => x, } let A { foo } = mka(); let A { foo } = mka(); let B { a, b, c } = mkb(); match mka() { A { foo: _foo } => {} } match Some(mka()) { S { .. } => (), Some(A { foo: _foo }) => {} None => {} _ => (), } match (x, y) { (1, 1) => 1, (2, 2) => 2, (1..=2, 2) => 3, _ => 4, } if let Some([b'@', filename @ ..]) = Some(b"@abc123") { println!("filename {:?}", filename); } fn f(X(_): A) {} let Ok(0): Option = 42u8; let Ok(0): Option; let Ok(0) = 42u8; match t { Bar::T1(_, Some(x)) => { return x * 3; } _ => { panic!(); } } match t { Bar::T1(_, Some::(x)) => { println!("{}", x); } _ => { panic!(); } } match unimplemented!() { &&&42 => {} FOO => {} _ => {} } fn f4(ref a @ box ref b: Box) {} fn f1(a @ ref b: U) {} fn _f(_a @ _b: u8) {} let s: &[bool] = &[true]; let s0: &[bool; 0] = &[]; let s1: &[bool; 1] = &[false; 1]; let s2: &[bool; 2] = &[false; 2]; let [] = s0; let [_] = s1; let [_, _] = s2; while let 0..=2 | 1 = 0 {} if let 0..=2 | 1 = 0 { } match 0u8 { 0 | 0 => {} } if let 0 | 0 = 0 { } else { return; } let mut arr = [U, U, U, U, U, U, U, U]; let mut tup = (U, U, U, U, U); let (Ok((V1(a) | V2(a) | V3(a), b)) | Err(Ok((a, b)) | Err((a, b)))): Result< _, Result<_, _> > = Ok((V1(1), 1)); let ( Ok((V1(a) | V2(a) | V3(a), ref b)) | Err(Ok((a, ref b)) | Err((a, ref b))) ): Result<_, Result<_, _>> = Ok((V1(1), 1)); let ( a, | Err((ref mut b, ref c, d)) | Ok( ( | Ok( | V1((ref c, d)) | V2((d, ref c)) | V3((ref c, Ok((_, d)) | Err((d, _)))), ) | Err((ref c, d)), ref mut b, ), ), ): (_, Result<_, _>) = (1, Ok((Ok(V3((1, Ok::<_, (i32, i32)>((1, 1))))), 1))); let [ref mut _x0, _, ref _x2, _, _x4, ref mut _x5, _x6, _] = arr; let [_, _, _x2, _, _, _x5, _, _] = arr; *_x0 = U; let a @ (b, c) = (S, S); let mut x @ B { b, .. } = B { a: 10, b: C { c: 20 } }; if let Some(x @ B { b: mut b @ C { c }, .. }) = some_b { } match x { Some(ref mut _y @ ..) => {} } let ref a @ box ref b = Box::new(NC); let a @ b @ c @ d = C; let a @ (b, c) = (C, mk_c()); let a @ P(b, P(c, d)) = P(mk_c(), P(C, C)); let a @ [b, c] = [C, C]; let a @ &(b, c) = &(C, C); let a @ &(b, &P(c, d)) = &(mk_c(), &P(C, C)); let a @ (mut b @ ref mut c, d @ ref e) = (u(), u()); let a @ ref b = U; let ref mut a @ ref mut b = U; let a @ &mut ref mut b = &mut U; let a @ &mut (ref mut b, ref mut c) = &mut (U, U); let a @ NC(b, c) = NC(C, C); let a @ NC(b, c @ NC(d, e)) = NC(C, NC(C, C)); let _a @ _b: u8 = 0; let &_ = &1_usize; let &&_ = &&1_usize; let &&&_ = &&&1_usize; let &&&_ = &&&1_usize; let &&&&_ = &&&&1_usize; let &&&&_ = &&&&1_usize; let &&&&&_ = &&&&&1_usize; } // source: "../../../ext/jinx-rust/tests/samples/patterns/pattern.rs" ================================================ FILE: tests/output-ext/patterns/rest.f.rs ================================================ fn b() { // fn foo(..: u8) {} let ..; let box ..; match x { .. | .. => {} } let &..; let &mut ..; let x @ ..; let ref x @ ..; let ref mut x @ ..; let (..); let (..); let (.., .., ..); let (.., P, ..); let A(..); let A(..); let A(.., .., ..); let A(.., P, ..); let [..]; let [..]; let [.., .., ..]; let [.., P, ..]; match x { .. | [(box .., &(..), &mut .., x @ ..), ref x @ ..] | ref mut x @ .. if x[..] => {} } a!(..); let [..]: &[u8]; let [..]: &[u8]; let (..): (u8,); let (..): (u8,); let (1, (Some(1), 2..=3)) = (1, (None, 2)); fn func((1, (Some(1), 2..=3)): (isize, (Option, isize))) {} fn fun([a, ref mut b, ref xs @ .., ref c, d]: [X; 6]) {} fn foo(a @ [b, mid @ .., c]: [C; 3]) {} let [..] = s; let [..] = s0; let [..] = s1; let [..] = s2; let [_, ..] = s1; let [.., _] = s1; let [_, ..] = s2; let [.., _] = s2; let [_, _, ..] = s2; let [_, .., _] = s2; let [.., _, _] = s2; let Box { 0: _, .. }: Box<()>; let Box { 1: _, .. }: Box<()>; let [ref _x0, _x1, _, mut _x3, .., ref _x6, _x7] = arr; let [ref _x0, ..] = arr; let [_x0, ..] = arr; let (.., ref mut _x3) = tup; let a @ [b, .., c] = [C, mk_c(), C]; let a @ [b, mid @ .., c] = [C, mk_c(), C]; } // source: "../../../ext/jinx-rust/tests/samples/patterns/rest.rs" ================================================ FILE: tests/output-ext/patterns/union.f.rs ================================================ fn fw1(H(Ok(mut x) | &Err(mut x)): H>) {} fn f1((Ok(mut x) | &Err(mut x)): R<'_>) {} fn fw2(H(&(Ok(x) | Err(x))): H>) {} fn fw3(H(Ok(x) | Err(x)): H>) {} fn f2(&(Ok(x) | Err(x)): R<'_>) {} fn f3((Ok(x) | Err(x)): R<'_>) {} fn fun((A | B): _) {} fn f(x @ (A::R(_) | D::E(_)): Q) {} fn x() { let (0 | 1 | _) = 0; if let 0 | 1 | 2 = 0 { } if let x @ 0 | x @ (1 | 2) = 0 { } if let H(Ok(mut x) | &Err(mut x)) = a { } if let H(&(Ok(x) | Err(x))) = a { } if let H(Ok(x) | Err(x)) = a { } for H(Ok(mut x) | &Err(mut x)) in std::iter::once(wres) { } for H(&(Ok(x) | Err(x))) in std::iter::once(wres) { } for H(Ok(x) | Err(x)) in std::iter::once(wres) { } let H(Ok(mut x) | &Err(mut x)) = wres; let H(Ok(x) | Err(x)) = wres; let H(&(Ok(x) | Err(x))) = wres; let ( | Tri::A(Ok(mut x) | Err(mut x)) | Tri::B(&Ok(mut x) | Err(mut x)) | &Tri::C(Ok(mut x) | Err(mut x)) ) = tri; let (B(A(a, _) | B(a)) | A(a, A(a, _) | B(a))) = B(B(1)); let (B(_) | A(A(a, _) | B(a), A(a, _) | B(a))) = B(B(1)); let (B(A(a, _) | B(a)) | A(A(a, _) | B(a), A(a, _) | B(a))) = B(B(1)); let (Ok(a) | Err(a)) = Ok(0); let (Ok(ref a) | Err(ref a)) = Ok(0); let (Ok(ref mut a) | Err(ref mut a)) = Ok(0); let (Ok((V1(a) | V2(a) | V3(a), b)) | Err(Ok((a, b)) | Err((a, b)))): Result< _, Result<_, _> > = Ok((V1(1), 1)); let ( Ok((V1(a) | V2(a) | V3(a), ref b)) | Err(Ok((a, ref b)) | Err((a, ref b))) ): Result<_, Result<_, _>> = Ok((V1(1), 1)); let ( a, | Err((ref mut b, ref c, d)) | Ok( ( | Ok( | V1((ref c, d)) | V2((d, ref c)) | V3((ref c, Ok((_, d)) | Err((d, _)))), ) | Err((ref c, d)), ref mut b, ), ), ): (_, Result<_, _>) = (1, Ok((Ok(V3((1, Ok::<_, (i32, i32)>((1, 1))))), 1))); for &(Ok(i) | Err(i)) in &v { } for Ok(i) | Err(i) in v { } if let &(None | Some(6 | 7)) = &opt { } if let Some(x @ (4 | 5 | 6)) = opt { } else { } while let Some(ref mut val @ (3 | 4 | 6)) = opt {} let (A | B); let (A | B); let (A | B): u8; let (A | B) = 0; let (A | B): u8 = 0; for A | B in 0 { } for A | B in 0 { } while let A | B = 0 {} while let A | B = 0 {} if let A | B = 0 { } if let A | B = 0 { } if let Ok(mut x) | &Err(mut x) = res { } if let &(Ok(x) | Err(x)) = res { } let (Ok(mut x) | &Err(mut x)) = res; let &(Ok(x) | Err(x)) = res; let (Ok(x) | Err(x)) = res; for Ok(mut x) | &Err(mut x) in std::iter::once(res) { } for &(Ok(x) | Err(x)) in std::iter::once(res) { } for Ok(x) | Err(x) in std::iter::once(res) { } let _ = |(A | B): u8| (); let (A | B); let (A | B,); let _ = |(A | B): u8| (); let (A | B); let (A | B,); let A(B | C); let E::V(B | C); let S { f1: B | C, f2 }; let E::V { f1: B | C, f2 }; let [A | B, .. | ..]; let (box 0 | 1); let (&0 | 1); let (&mut 0 | 1); let (x @ 0 | 1); let (ref x @ 0 | 1); let (ref mut x @ 0 | 1); let (a, A(a, _) | B(a)) = (0, A(1, 2)); let (A(a, _) | B(a), a) = (A(0, 1), 2); let (A(a, a) | B(a)) = A(0, 1); let (B(a) | A(a, a)) = A(0, 1); match A(0, 1) { A | B => 0, A | B => 0, B(a) | A(a, a) => 0, Ok(x @ 4) | Err(x @ (6 | 8)) => 0, Ok(x @ 1 | x @ 2) => 0, Err(x @ (0..=10 | 30..=40)) if x % 2 == 0 => 0, Err(x @ 0..=40) => 0, Some(box Test::Foo | box Test::Bar) => 0, &((true, y) | (y, true), z @ (0 | 4)) => (y as u8) + z, Foo::One(0) | Foo::One(1) | Foo::One(2) => 0, Foo::One(42 | 255) => 0, Foo::Two(42 | 255, 1024 | 2048) => 0, Foo::One(100 | 110..=120 | 210..=220) => 0, Foo::Two(0..=10 | 100..=110, 0 | _) => 0, ([] | [0 | 1..=255] | [_, ..],) => 0, ((0, 0) | (0, 1),) => 0, (a, _) | (_, a) if a > 10 => 0, Some((a, _)) | Some((_, a)) if a > 10 => 0, Some((a, _) | (_, a)) if a > 10 => 0, e @ &1..=2 | e @ &3..=4 => 0, Ok(mut x) | &Err(mut x) => 0, | Tri::A(Ok(mut x) | Err(mut x)) | Tri::B(&Ok(mut x) | Err(mut x)) | &Tri::C(Ok(mut x) | Err(mut x)) => 0, A | B => 0, A | B => 0, [.., Some(Test::Qux | Test::Foo)] => 0, [Some(Test::Foo), .., Some(Test::Baz | Test::Bar)] => 0, [.., Some(Test::Bar | Test::Baz), _] => 0, Some( | Test::Foo { first: 1024 | 2048, second: 2048 | 4096 } | Test::Bar { other: Some(Other::One | Other::Two) }, ) => 0, ( (a, _) | (_, a), (b @ _, _) | (_, b @ _), (c @ false, _) | (_, c @ true), ) if { guard_count += 1; (a, b, c) == target } => 0, | ((a, _), (b @ _, _), (c @ false, _)) | ((a, _), (b @ _, _), (_, c @ true)) | ((a, _), (_, b @ _), (c @ false, _)) | ((a, _), (_, b @ _), (_, c @ true)) | ((_, a), (b @ _, _), (c @ false, _)) | ((_, a), (b @ _, _), (_, c @ true)) | ((_, a), (_, b @ _), (c @ false, _)) | ((_, a), (_, b @ _), (_, c @ true)) if { guard_count += 1; (a, b, c) == target } => 0, } } accept_pat!(p | q); accept_pat!((p | q,)); accept_pat!(TS(p | q)); accept_pat!(NS { f: p | q }); accept_pat!([p | q]); // source: "../../../ext/jinx-rust/tests/samples/patterns/union.rs" ================================================ FILE: tests/output-ext/specifiers/extern.f.rs ================================================ type funky_func = extern "C" fn( unsafe extern "rust-call" fn( *const JSJitInfo, *mut JSContext, HandleObject, *mut libc::c_void, u32, *mut JSVal ) -> u8 ); extern "C" fn sup() {} extern "C" { fn some_fn() -> (); } extern { fn quux() -> (); // Post comment fn syscall( number: libc::c_long /* comment 1 */, /* comm 2 */ ... /* sup? */ ) -> libc::c_long; unsafe fn foo() -> *mut Bar; pub(super) const fn foo() -> *mut Bar; pub(crate) unsafe fn foo() -> *mut Bar; } // source: "../../../ext/jinx-rust/tests/samples/specifiers/extern.rs" ================================================ FILE: tests/output-ext/specifiers/pub.f.rs ================================================ enum E { pub U, pub(crate) T(u8), pub(super) T { f: String, }, } pub impl Tr for S { pub fn f() {} pub const C: u8 = 0; pub type T = u8; pub(in foo) fn f(&self) -> i32 { 0 } } pub struct Pub(Priv2); mod bar { pub use *; } pub trait Sized {} const MAIN: u8 = { pub trait Tr { fn f(); const C: u8; type T; } pub struct S { pub a: u8, } struct Ts(pub u8); pub impl Tr for S { pub fn f() {} pub const C: u8 = 0; pub type T = u8; } pub impl S { pub fn f() {} pub const C: u8 = 0; // pub type T = u8; } pub extern "C" { pub fn f(); pub static St: u8; } () }; pub(super) fn f(_: Priv) {} pub(crate) fn g(_: Priv) {} crate fn h(_: Priv) {} pub(crate) struct S1; pub(super) struct S2; pub(self) struct S3; pub(in ::core) struct S4; pub(in a::b) struct S5; pub type A; pub static b: Q; pub extern crate core; struct Bar(pub ()); pub struct C(pub isize, isize); pub struct D(pub isize); pub struct bool; pub struct Pub(pub T); pub type A; pub mod bar { pub use a::b::c; pub mod b {} pub struct S { pub(in foo) x: i32, } } pub macro m() {} pub(in Self::f) struct Z; pub extern crate self as name; pub use name::name as bug; // source: "../../../ext/jinx-rust/tests/samples/specifiers/pub.rs" ================================================ FILE: tests/output-ext/statements/const.f.rs ================================================ const X: u8; const B; const A: u8; pub const A: Self::AssocTy = 1; const FOO: dyn Fn() -> _ = ""; pub const FOO: &'static *const i32 = &(&0 as _); const TEST: fn() -> _ = 1; const MY_A: A = A { e: |s, a, b| { if s { let _ = (); } else if let Q(s) = b.r(|p| p.d()) { let _ = (); } }, }; // source: "../../../ext/jinx-rust/tests/samples/statements/const.rs" ================================================ FILE: tests/output-ext/statements/enum.f.rs ================================================ enum E {} enum E { Foo { limb_with_align16: Align16, }, Bar, } enum E { Foo { foo: u32, }, Bar { bar: u32, }, } enum A { Ok = u8::MAX - 1, Ok2 = -1, OhNo = u8::MIN, Bi64 = 0x8000_0000, orange = 8 >> 1, } enum A { union, } enum B { union {}, } enum C { union(), } enum E { A = { enum F { B, } 0 }, } enum E { _None, _Some(T), } enum E { EM(W), EM { x: X, }, EM(isize, Y), EM { u: isize, x: Z, }, EM([u8]), EM { x: str, }, EM(isize, [f32]), EM { u: isize, x: [u32], }, EM(Path1), EM { x: Path2, }, EM(isize, Path3), EM { u: isize, x: Path4, }, EM(dyn Foo), EM { x: dyn Bar, }, EM(isize, dyn FooBar), EM { u: isize, x: dyn BarFoo, }, EM(<&'static [i8] as Deref>::Target), EM { x: <&'static [char] as Deref>::Target, }, EM(isize, <&'static [f64] as Deref>::Target), EM { u: isize, x: <&'static [i32] as Deref>::Target, }, } enum E<'a, 'b, 'c: 'b> { A(extern "Rust" fn(&'a isize)), B(&'b [isize]), C(&'b mut &'c str), } pub enum X where D: Copy + Debug + Eq {} // source: "../../../ext/jinx-rust/tests/samples/statements/enum.rs" ================================================ FILE: tests/output-ext/statements/impl.f.rs ================================================ impl X {} impl X { fn f(); fn f() {} type Y; type Z: Ord; type W: Ord where Self: Eq; type W where Self: Eq; fn foo() { struct S; impl S { pub const X: u8 = 0; pub const fn bar() {} async fn qux() {} } } } impl X for () {} impl X for Y {} impl ! {} impl ! where u8: A {} impl ! where u8: A {} impl !Send for A {} impl <*const u8>::C {} impl ::C {} impl ::C {} impl <::B>::C {} impl<'a, I, T: 'a, E> Iterator for Y<'a, I, E> where I: Iterator {} impl S for E {} unsafe impl A for isize {} unsafe impl Send for A {} unsafe impl Sync for A {} impl<'a> A for &'a [isize] {} impl ::A::B for ::C {} impl ::A for () {} impl ::A {} impl A for [B; 1] {} impl A for (::D, E) {} impl ::A for [B; 0] {} impl<'a> A for &'a [isize] {} impl<'a> dyn T + 'a {} impl<'a> dyn T + 'a {} impl<'a> dyn ::Foo::Trait + 'a {} impl A for T {} impl<'a, 'b, 'c> S for &'a &'b &'c Q {} impl Foo for F {} impl A for T where for<'a> T: B<'a> {} impl<'a, T, const N: usize> IntoIterator for &'a Table {} impl A for (B,) {} impl !A for (B,) {} impl A for Box {} impl A for lib::Something {} impl A for D {} impl A {} // source: "../../../ext/jinx-rust/tests/samples/statements/impl.rs" ================================================ FILE: tests/output-ext/statements/self.f.rs ================================================ fn f(self) {} fn f(&self) {} fn f(mut self) {} fn f(&mut self) {} fn f(&'a self) {} fn f(&'a mut self) {} fn f(self: u8) {} fn f(mut self: u8) {} type X = fn(self); type X = fn(&self); // type X = fn(mut self); type X = fn(&mut self); type X = fn(&'a self); type X = fn(&'a mut self); type X = fn(self: u8); // type X = fn(mut self: u8); async fn foo<'b>(self: &'b Foo<'a>) -> &() { self.0 } fn f<'b>(self: &'b Foo<'a>) -> &() { self.0 } fn f<'a>(self: &Alias, arg: &'a ()) -> &() { arg } fn f(&mut self) -> u32; fn f(mut self: Box); fn f(self: _) {} fn f(self: &_) {} fn f(&self) -> Self; // fn f(self::S: S) {} // fn g(&self::S: &S) {} // fn h(&mut self::S: &mut S) {} // source: "../../../ext/jinx-rust/tests/samples/statements/self.rs" ================================================ FILE: tests/output-ext/statements/spread.f.rs ================================================ fn main() {} fn f1_1(x: isize, ...) {} fn f1_2(...) {} extern "C" fn f2_1(x: isize, ...) {} extern "C" fn f2_2(...) {} extern "C" fn f2_3(..., x: isize) {} extern fn f3_1(x: isize, ...) {} extern fn f3_2(...) {} extern fn f3_3(..., x: isize) {} extern { fn e_f1(...); fn e_f2(..., x: isize); } struct X; impl X { fn i_f1(x: isize, ...) {} fn i_f2(...) {} fn i_f3(..., x: isize, ...) {} fn i_f4(..., x: isize, ...) {} } trait T { fn t_f1(x: isize, ...) {} fn t_f2(x: isize, ...); fn t_f3(...) {} fn t_f4(...); fn t_f5(..., x: isize) {} fn t_f6(..., x: isize); } extern "C" { pub fn foo(x: i32, ...); } // source: "../../../ext/jinx-rust/tests/samples/statements/spread.rs" ================================================ FILE: tests/output-ext/statements/statements.f.rs ================================================ const _: () = { pub trait A { const _: () = (); } impl A for () { const _: () = (); } impl dyn A { const _: () = (); } }; extern r#"C"# { fn bar(); } extern r#"C"# fn foo() {} type T = extern r#"C"# fn(); extern "\x43" fn foo() {} extern "\x43" { fn bar(); } type T = extern "\x43" fn(); // extern crate async; // extern crate async as something_else; fn f1(); fn f2() {} fn f3(); trait X { fn f(); fn f() {} const Y: u8; } extern "C" { fn f(); fn f(); static X: u8; static mut Y: u8; // type E: where; type A: Ord; type A<'a> where 'a: 'static; type A where T: 'static; type A = u8; type A<'a: 'static, T: Ord + 'static> : Eq + PartialEq where T: 'static + Copy = Vec; } const async fn test() {} async unsafe fn test() {} const unsafe fn test() {} unsafe extern fn test() {} fn f() { async fn f(); unsafe fn f(); const fn f(); extern "C" fn f(); const async unsafe extern "C" fn f(); } const fn f(a: *const i32, b: i32) -> bool {} unsafe fn f(&self) -> u32; const unsafe fn f(v: u32) -> u32 {} unsafe fn f(func: unsafe fn() -> ()) -> () {} struct Range< const FROM: usize = 0, const LEN: usize = 0, const TO: usize = FROM >; impl From<[u8; 1 + 1]> for Foo {} fn f(d: [u8; 1 + 1]) -> A where [u8; 1 + 1]: From<[u8; 1 + 1]> {} fn f<'a, 'b, 'c, T>(x: foo::X<'a, T, 'b, 'c>) {} fn f() -> Option Option> { Some(|| Some(true)) } fn a() { let a = 0; let _b = 0; let _ = 0; let mut b = 0; let mut _b = 0; } enum Test3 { Var1, Var2(String), StillFine { def: i32, }, } enum E { UnitVariant, TupleVariant(), BracedVariant {}, T(T, [!; 0]), #[allow(dead_code)] U(U), } fn foobar() -> usize where (): Foobar {} mod a { extern "C" { pub fn free(x: *const u8); } } pub union U { pub a: u8, pub(super) b: u8, c: u8, } trait C { fn D(&self, f: F) where F: FnMut(A) -> Q; } trait A {} trait A: B::C {} trait A: B::C {} fn f() -> () {} fn f = i32>>() {} fn f(mut f: F) where F: FnMut(&mut R, bool) {} fn f(f: F) where F: for<'a> Fn(&'a isize, &'a isize) -> isize {} fn f(f: F) -> isize where F: Fn() -> isize { f() } async fn g(((ref a, ref mut b), (ref mut c, ref d)): ((A, A), (A, A))) {} pub unsafe extern "C" fn bar(_: i32, mut ap: ...) -> usize {} unsafe fn f(&self, x: &usize) { *self + *x; } fn f() {} fn f F<(&'a A,)>>(_: F) {} fn f(a: M) where M: A, M::B: C {} fn f(t: fn(&A)) where fn(&A): for<'a> F<(&'a A,)> {} #[no_mangle] pub extern "C" fn rust_no_mangle() -> i32 {} pub fn foo<'a, 'b>(x: Foo<'a, 'b>, _o: Option<&&()>) { let _y = x.foo; } const x: &'static dyn Fn() = &(|| e!("q")); const fn foo() -> i32 {} extern "\x43" fn foo() {} extern "\x43" { fn bar(); } type T = extern "\x43" fn(); extern r#"C"# fn foo() {} extern r#"C"# { fn bar(); } type T = extern r#"C"# fn(); // source: "../../../ext/jinx-rust/tests/samples/statements/statements.rs" ================================================ FILE: tests/output-ext/statements/static.f.rs ================================================ static A: u8; static B; static mut C: u8; static mut D; static X: u8; pub static B: &'static a = unsafe { &q }; static A: fn(_) -> u8 = |_| 8; static BOO: dyn Fn() -> _ = ""; static x: _; // source: "../../../ext/jinx-rust/tests/samples/statements/static.rs" ================================================ FILE: tests/output-ext/statements/struct.f.rs ================================================ struct S Q, B: 'a + Q, C: 'a, G: Q + 'a, H: Q, I:>; struct Empty1 {} struct Empty2; struct Empty7(); struct Align8Many { a: i32, b: i32, c: i32, d: u8, } struct A([T]); struct A(T); struct cat { done: extern "C" fn(usize), meows: usize, } struct Test3<'a, 'b, 'c> { x: extern "Rust" fn(&'a isize), y: extern "Rust" fn(&'b [isize]), c: extern "Rust" fn(&'c str), a: fn(u32) -> u32, b: extern "C" fn(u32) -> u32, c: unsafe fn(u32) -> u32, d: unsafe extern "C" fn(u32) -> u32, } struct Test4<'a, 'b: 'a> { x: &'a mut &'b isize, } struct Test6<'a, 'b: 'a> { x: &'a mut extern "Rust" fn(&'b isize), } struct Foo<'a> { x: Box &'a i32) + 'static>, } struct X; struct U {} struct P(T); struct A where U: E(U); struct A where U: E(U) -> R; struct A(U) where U: Eq; struct K<'a>(&'a ()); pub struct A([u8; 1]); pub(crate) struct S<'a, I, E>(I, &'a E); pub struct A(C); pub struct A(T); pub struct Table([Option; N]); struct B; struct A(C, ()); struct A(B) where B: Marker; struct A(T, U) where B: Marker; struct A<'a, S: B<'a> = i32>(S, &'a ()); struct S1(pub(in foo) (), pub T, pub(crate) (), pub ((), T)); struct G(*const T, *const U); pub struct Unique { s: *const T, } unsafe impl Send for Unique {} pub struct A(u32, ::b::Q); struct S(>::AS); pub struct A where I: B { w: ::G, } // source: "../../../ext/jinx-rust/tests/samples/statements/struct.rs" ================================================ FILE: tests/output-ext/statements/trait.f.rs ================================================ trait A {} trait A {} trait T2<'x, 'y>: T1<'x> {} trait T = S where >::T: H; trait A: B + E<()> {} trait A>: D {} trait A = B; trait A = B where T: C; trait A: B + C {} trait A = std::fmt::Display + std::fmt::Debug; trait B = std::fmt::Display + std::fmt::Debug; trait A = Default; trait A = B; trait A = B; trait A<'a, T: 'a> = B<&'a D>; trait A = 'static; trait A = D + E where F<(G, H)>: I; trait A = where D: F; trait A: T2 {} trait A {} trait A {} trait A {} trait A {} trait A {} trait A {} pub trait A {} pub trait C = A + B; pub trait A: Sized {} // source: "../../../ext/jinx-rust/tests/samples/statements/trait.rs" ================================================ FILE: tests/output-ext/statements/union.f.rs ================================================ union {}; union::b {}; union union<'union> { union: &'union union<'union>, } struct union; impl union { pub fn new() -> Self { union {} } } fn main() { let _u = union::new(); let mut r#async = 1; union as T; } // source: "../../../ext/jinx-rust/tests/samples/statements/union.rs" ================================================ FILE: tests/output-ext/statements/use.f.rs ================================================ pub use self::bb::{ aa, bb }; pub use self::cc::*; use Self::f; use ::super::{ S, Z }; use ::super::main; use a::*; use m::S; use ::{ ::{}, ::{} }; extern crate x; use std::mem::self; use foo::bar::self as abc; extern crate priv_impl_prim_ty as bar; extern crate crate_method_reexport_grrrrrrr2; use std::io::{ self, Error as IoError }; use std::net::{ self as stdnet, TcpStream }; use foo::{ Foo, bar::{ baz::{}, foobar::* }, * }; use foo::bar::baz::{ *, * }; use foo::{}; mod m { use S; use self::{ self }; use super::{ self }; } pub use ::E::*; use crate as _; pub use ::E::V::{ self }; use std::{ ops::A, marker::{ C, B } }; mod bar { pub use bar::*; pub use main as f; pub use super::*; use ::std::mem; use crate_method_reexport_grrrrrrr2::rust::add; crate struct Foo; } use rustc_hir::BinOpKind::{ Add, And, BitAnd, BitOr, BitXor, Div, Eq, Ge, Gtab, }; use rustc_ast::ast::{ ItemForeignMod, ItemImpl, ItemMac, ItemMod, ItemStatic, ItemDefaultImpl, }; use exceedingly::looooooooooooooooooooooooooooooooooooooooooooooooooooooooooong::import::path::{ ItemA, ItemB, }; use exceedingly::loooooooooooooooooooooooooooooooooooooooooooooooooooooooong::import::path::{ ItemA, ItemB, }; use list::{ // Some item SomeItem /* Comment */, /* Another item */ AnotherItem /* Another Comment */, // Last Item LastItem, }; use test::{ Other /* C */, /* A */ self /* B */ }; use rustc_ast::{ self }; use ::{ /* Pre-comment! */ Foo, Bar /* comment */ }; use Foo::{ Bar, Baz }; pub use rustc_ast::ast::{ Expr_, Expr, ExprAssign, ExprCall, ExprMethodCall, ExprPath, }; use rustc_ast::some::{}; use self; use std::io::{ self }; use std::io::self; mod Foo { pub use rustc_ast::ast::{ A }; mod Foo2 { pub use rustc_ast::ast::{ A, self, B }; } } fn test() { use Baz::*; use Qux; } use foo::bar::baz as baz; use bar::quux as kaas; use foo; use foo::{ self as bar, baz }; use foo::{ self as bar }; use foo::{ qux as bar }; use foo::{ baz, qux as bar }; use ::foo; use ::foo::{ Bar }; use ::foo::{ Bar, Baz }; use ::{ Foo }; use ::{ Bar, Baz }; use *; use *; error; use super::*; use foo::issue_1356::*; #[cfg(unix)] use self::unix::{}; use foo::{ a, bar::{ baz, qux, xxxxxxxxxxx, yyyyyyyyyyyyy, zzzzzzzzzzzzzzzz, foo::{ a, b, cxxxxxxxxxxxxx, yyyyyyyyyyyyyy, zzzzzzzzzzzzzzzz }, }, b, boo, c, }; use fooo::{ baar::{ foobar::{ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy, zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz, }, }, z, bar, bar::*, x, y, }; use exonum::{ api::{ Api, ApiError }, blockchain::{ self, BlockProof, Blockchain, Transaction, TransactionSet }, crypto::{ Hash, PublicKey }, helpers::Height, node::TransactionSend, storage::{ ListProof, MapProof }, }; use a::{ b::{ c::* } }; use a::{ b::{ c::{} } }; use a::{ b::{ c::d } }; use a::{ b::{ c::{ xxx, yyy, zzz } } }; /// a // b use c; #[macro_use] use imports_with_attr; use std::f64::consts::{ SQRT_2, E, PI }; #[rustfmt::skip] use std::fmt::{self, {Display, Formatter}}; // source: "../../../ext/jinx-rust/tests/samples/statements/use.rs" ================================================ FILE: tests/output-ext/types/cast.f.rs ================================================ fn a() { if (5u64 as i32 as u16) == 0u16 { } [ (u64 as u8 as i8) == 9i8, &[1, 2, 3] as *const _ as *const [i32; 3], -0i16 as i8, !0u16 as u8, (0u16 << 15) as u8, (0u32 << 31) as u16, Foo::Bar as i8, 0 as i32 as i32, // 0 as i32: i32, // 0i32: i32 as i32, // 0i32: i32: i32 as u32 as i32, // 0i32: i32: i32, 0u8 as u32, a as fn(u8), // ::Assoc<3>, drop as fn(u8), &x as *const _, Box::new(A) as &dyn B, box (move |y: i32| -> i32 { x + y }) as Box< dyn (FnMut(i32) -> i32) + 'static >, &x as *const i16 as f32, &(|_| ()) as &dyn for<'x> Fn(>::V), TestStruct { x: 0x1234 as *const [isize; 2] }, !(FOO as *const usize).a(), !(42 as *const usize).a(), (0 as *const usize).a(), !("foo" as *const str).a(), (&x as T)[0], ] } const A: *const u8 = &0 as *const _ as *const Q as *const u8; // source: "../../../ext/jinx-rust/tests/samples/types/cast.rs" ================================================ FILE: tests/output-ext/types/never.f.rs ================================================ fn a() { a::(); let x: ! = a!(); let x: ! = unsafe { a::(C) }; >::from(never); } fn a(x: !) -> ! { x } fn foo(never: !) {} fn a(x: !) {} fn a(ref x: !) {} fn a(x: &[!]) {} fn a(x: B<(), !>) {} impl A for B { fn c(&self, d: &!) -> E {} } impl A for ! {} type A = !; // source: "../../../ext/jinx-rust/tests/samples/types/never.rs" ================================================ FILE: tests/output-ext/types/types.f.rs ================================================ type A where 'a: 'b + 'c = u8; type A where 'a: 'b + 'c = u8; type A where 'a: 'b = u8; type A where 'a: 'b = u8; type A where 'a: = u8; type A where 'a: = u8; type A = u8; // type A = for<'a, T> fn(); type A = for<'a: 'b + 'c> fn(); type A = for<'a: 'b> fn(); type A = for<'a: 'b> fn(); type A = for<'a: > fn(); type A = for<'a: > fn(); type A = for<'a> fn(); type A = for<> fn(); type A = Box u8) + 'static + Send + Sync>; type A = impl B; type A = u8; type A where for<'a> dyn for<'b> Trait1 + ?Trait2: 'a + Trait = u8; type A where T: = u8; type A where T: Trait = u8; type A where T: Trait + Trait = u8; type A where T: Trait = u8; type A where T: = u8; type A = ::X; pub type A where T: B = T; type A: Ord; type B: Ord = u8; type C: Ord where 'static: 'static = u8; type D<_T>: Ord; type E<_T>: Ord = u8; type F<_T>: Ord where 'static: 'static = u8; type Y where Self: Sized = u32; type Y: A where Self: Sized; pub const FN: &'static fn() = &(fop:: as fn()); const A: &&&u32 = &&&42; const CONST1: &[bool; 1] = &[true]; const CONST: &[Option<()>; 1] = &[Some(())]; const A: [u32; 1] = [4]; const F: &'static dyn PartialEq = &7u32; struct R<'a> { c: Box, } fn g() -> impl Tr2 {} fn leak_dyn_nonprincipal() -> Box {} fn method() -> Self::Pub {} fn f(arg: T) {} pub fn unused() -> usize {} fn start(_: isize, _: *const *const u8) -> isize {} fn as_ptr(&self) -> *const Self::Item; fn as_mut_ptr(&mut self) -> *mut Self::Item; fn as_ptr(&self) -> *const T { self as *const _ as *const _ } fn as_mut_ptr(&mut self) -> *mut T { self as *mut _ as *mut _ } fn y_uses_f(f: impl Fn()) {} fn infer(c: T) -> T { c } fn f1<'a, 'b, 'c>(_x: &'a u32, _y: &'b u32, _z: &'c u32) where 'c: 'a + 'b {} fn syntax() { A::(); A::(); fn y<'a>(y: &mut (dyn 'a + Send)); let z = y as &mut (dyn 'a + Send); let x: &'static str = "A"; fn A() -> Box<::T>; let a = |a, b: _| -> _ { 0 }; let a: &usize = &1; let a: &&usize = &&1; let a: &&&usize = &&&1; let a: &&&usize = &&&1; let a: &&&&usize = &&&&1; let a: &&&&usize = &&&&1; let a: &&&&&usize = &&&&&1; let a: Box = box 3 as Box; let a: Box; let a: Box; let a: Box; let a: Box; let a: Box; let a: Box; let a: Box; let a: Box; let a: Box; let a: &(dyn for<'a> Trait<'a> + 'static); let a: &dyn PartialEq = &7u32; let a: Option = None; let a = &() as *const () as *const Bottom; let a = id(|_: &isize, _: &isize| {}); let a = id(|_: &isize, _: &isize| {}); fn equal1(_: &T, _: &T) -> bool {} fn equal2(_: &T, _: &T) -> bool where T: {} fn A<'a>() where 'a: {} pub fn A(_: T) -> TypeId {} pub fn unused<'a, T>(_: &'a u32) {} let f: fn(_, i32) -> i32 = q; let _ = S::<>; let _ = E::<>::V; let a: i32<>; let a = ( A::b::(), A::b:: fn(&'static isize, &'a isize)>(), A::b:: fn(&'a isize, &'b isize)>(), A::b:: fn(&'b isize, &'a isize)>(), A::b:: fn(fn(&'a isize) -> &'a isize)>(), A::b:: fn(&'a isize) -> &'a isize)>(), A::b:: fn(&'a dyn Trait<'a>) -> Struct<'a>>(), A::b:: fn(&'a dyn Trait<'a>) -> Struct<'static>>(), A::b:: fn(&'a dyn Trait<'b>) -> Struct<'b>>(), A::b:: fn(&'a isize) -> &'a usize)>(), A::b:: fn(&'b isize) -> &'b usize)>(), A::b::>(), A::b:: Fn(&'static isize, &'a isize)>>(), A::b:: Fn(&'a isize, &'b isize)>>(), A::b:: Fn(&'b isize, &'a isize)>>(), A::b:: Fn(Box &'a isize>)>>(), A::b:: Fn(&'a isize) -> &'a isize>)>>(), a::>>(), a::>>>(), <&dyn A>::x(&e::r(1)), <&'static str>::f(&""), a::<>(), a as &[&dyn Fn(usize) -> ()], a::<&U>(a), a::(a), a::<&mut U>(a), ); let s: Foo<'a'> = Foo; let _: Foo<'b'> = s.into(); let s2: Foo<'a'> = Foo; let _: Foo<'a'> = s2; let s3: Foo<'a'> = Foo; let _ = s3; let s4: Foo<'a'> = Foo; } fn A(x: Option) -> Option {} fn f(x: fn(i32)) -> unsafe fn(i32) {} fn f<'b, L: X<&'b Q>>() {} struct A()]>(T, U); impl Q for () {} trait Q

{} trait Q {} trait H<'d, 'e>: for<'f> I<'d, 'f, 'e> + 'd {} trait F<'f>: for<'a> A<'a> + for<'e> E<'e> {} struct Q(A, T); struct Q, C>(A, B, C); impl<'a> A<'a> for &'a str { fn f>(self) -> &'a str {} } extern "C" fn A(a: T, b: T) -> T::Output { a + b } extern "C" { pub fn f<'a>(x: &'a i32); pub fn f<'b>(x: &'a i32, y: &'b i32); pub fn f<'a>(x: &'a i32, y: &i32) -> &'a i32; pub fn f<'b>(x: for<'c> fn(&'a i32)); pub fn f<'b>(x: for<'c> fn(&'b i32)); pub fn f<'b>(x: for<'c> fn(&'c i32)); pub fn f<'b>() -> for<'c> fn(&'a i32); pub fn f<'b>() -> for<'c> fn(&'b i32); pub fn f<'b>() -> for<'c> fn(&'c i32); } struct X<'x, 'y> { x: std::marker::PhantomData<&'x ()>, y: std::marker::PhantomData<&'y ()>, } struct G where for<'f> T: F<'f, As: E<'f>> + 'f { t: std::marker::PhantomData, } struct D where T: for<'c> C<'c, As: A<'c>> { t: std::marker::PhantomData, } fn f() where T: A, T::U: B {} fn f(a: isize, b: *const *const u8) -> isize {} fn f A>(mut a: G, b: A, c: A) -> A {} fn f + C>(x: T) -> T {} fn f>(x: B) -> C {} struct Whitespace { t: T, } struct TokenSplit { t: T, } fn f<'a, 'b, T>(t: T) -> isize where T: 'a, 'a: 'b, T: Eq { 0 } impl A> for C where T: D {} fn f() where T: for<'a> A<'a> + 'a {} fn f() where T: for<'g> H<'g, 'g, As: for<'h> H<'h, 'g> + 'g> {} fn f() where T: for<'i> H< 'i, 'i, As: for<'j> H<'j, 'i, As: for<'k> I<'i, 'k, 'j> + 'j> + 'i > {} fn f() where T: for<'l, 'i> H< 'l, 'i, As: for<'j> H<'j, 'i, As: for<'k> I<'l, 'k, 'j> + 'j> + 'i > {} fn f() where T: for<'l, 'i> H< 'l, 'i, As: for<'j> H<'j, 'i, As: for<'k> H<'j, 'k, As = X<'j, 'k>> + 'j> + 'i > {} fn f() where T: Fn(&(), &()) {} fn f() where T: Fn(&'a (), &()) {} fn f() where T: Fn(&(), Box) {} fn f() where T: Fn(&(), fn(&())) {} fn f() where T: Fn(&(), for<'a> fn(&'a ())) {} fn f() where T: Fn(&(), Box, &(), fn(&(), &())) {} fn f() where T: for<'a> Fn(&'a (), &()) {} fn f() where T: for<'a> Fn(&(), &'a ()) {} fn f() where T: for<'a> Fn(&'a (), &'a ()) {} fn f() where T: for<'a> Fn(&'a (), Box) {} fn f() where T: for<'a> Fn(&(), Box, &'a (), fn(&(), &())) {} fn f() where T: A, F: FnOnce(B) -> bool {} fn f() -> impl std::borrow::Borrow<::S> {} fn f(_: <() as A>::C) {} struct S<>; trait T<> {} enum E<> { V, } impl<> T<> for S<> {} fn f<'a>(x: for<'b, 'c: 'a + 'b> fn(&'a A, &'b B) -> &'c C) where F: for<'a, 'b: 'a> Fn(&'a A, &'b B) -> &'c C, for<'a, 'b: 'a> F: Fn(&'a A, &'b B) -> &'c C {} struct S Fn(&'a A, &'b B) -> &'c C>(F); struct S(F) where F: for<'a, 'b: 'a> Fn(&'a A, &'b B) -> &'c C; struct S(dyn for<'a, 'b: 'a> Fn(&'a A, &'b B) -> &'c C); type T = Box Fn(&'a A, &'b B) -> &'c C>; type L8 = L>>>>>>>; type L64 = L8>>>; impl A for T where T: B { type C<'a> = ::E<'a, 'static>; } impl A<<() as B>::D> for E where T: F, (): G {} type Y<'a> = &'a (); type Q<'a>; type Q<'a, 'b>; type Q<'a, 'b>; type Q<'a, 'b, T>; type Q<'a, 'b, T, U>; type Q<'a, 'b, T, U>; type Q<'a, 'b, T: S, U>; type Q<'a, 'b, T: S, U>: S; type Q<'a, 'b, T: S, U>: E + Into; type Q<'a, 'b, T: S, U> where T: E, U: Into; type Q<'a, 'b, T: S, U> : E + Into where T: E, U: Into; type Q<'a>: E as B>::A<'a, 'static>> where Self: 'a; type S<'a>: Iterator> + E>; type Z = dyn for<'x> Send; type A = (*const E::R, D); fn f(&self) -> Pin + '_>>; fn f(&self) -> Self::Y<'_> {} fn f(x: &()) -> &() {} fn f(x: &impl for<'a> X = &'a ()>) -> &() {} fn f<'a, T: for<'b> Fun = T>>(t: T) -> T::F<'a> {} fn f<'a, T: Fun = T>>(t: T) -> T::F<'a> {} fn f Sized>() {} fn f<'a, T1: X>(t: T1) -> T1::Y<'a>; fn f<'a>(s: Box = &'a ()>>) {} fn f<'a>(t: Self::Y<'a>) -> Self::Y<'a>; fn f X = &'a ()>>(x: &T) -> &() {} fn f<'a, T: ?Sized + Fun = [u8]>>(_: Box) -> &'static T::F<'a> {} fn f<'a>(t: &'a Self::F<'a>) -> &'a Self::F<'a> {} fn f() where T: S, for<'a> T::Item<'a>: Q {} fn f<'c, 'd>(s: Box>) {} fn f(e: &impl for<'a> X = &'a ()>) -> &'static () {} fn f X = &'a ()>>(x: &T) -> &'static () {} fn f(x: &mut dyn for<'a> E = &'a i32>) -> usize {} fn f() where 'static: 'static, dyn 'static: 'static + Copy {} fn f() where 'static: 'static, dyn 'static + ::Foo: 'static + Copy {} fn f() where F::B: Copy {} fn f() where ::B: Copy {} fn f>() where F::B: Copy {} fn f::Q>>(&self, r: &T) -> u64; fn f() -> impl Default {} fn f(t: Box Get>) {} fn f(t: Box Fn(i32) -> i32>) {} fn f(t: for<'a> fn(i32) -> i32) {} fn f(t: for<'a> unsafe fn(i32) -> i32) {} fn f(t: for<'a> extern "C" fn(i32) -> i32) {} fn f(t: for<'a> unsafe extern "C" fn(i32) -> i32) {} impl::C)> Callback for F {} impl Bar for Foo where A<{ N > 1 }>: B, A<{ M > 1 }>: B {} async fn f(_: impl for<'a> Add<&'a u8>, _: impl for<'b> Add<&'b u8>) {} async fn f<'a>(_: &'a ()) -> impl A {} fn f() where D::S: {} type T: Iterator::T>; struct R<'a> { s: dyn for<'b> E> + 'a, } fn f() -> [u8; 4 * 1024 * 1024 * 1024 * 1024] {} trait Foo where T: Borrow + ?Sized, U: ?Sized + 'b, 'a: 'b, Box: {} trait Map where for<'a> &'a Self: IntoIterator {} trait S: A + AsRef {} struct Bar([u8; (N + 2) as usize]) where [(); (N + 2) as usize]:; fn f() where D<{ N as usize as u16 }>: {} fn f() where for<'a> T: TraitA< 'a, AsA: for<'b> TraitB<'a, 'b, AsB: for<'c> TraitC<'a, 'b, 'c>> > {} fn f<'u, 'a, F>() where for<'b> F: Iterator B<'a, 'b, 'c> + for<'c> A<'a, 'c>> {} fn f(&self, db: &>::DynDb) {} pub fn f<'a, I>() -> impl B where I: A {} type S C<&'a u8>>> = D; type S; type A = a::b!(); type S where Self: Sized; fn f(&self, a: &!) {} type S where T: Display; type S<'a, T: Debug + 'a>: ?Sized = dyn Iterator; type S<'x> where T: 'x = &'x (); type S<'u, 'v> where 'u: 'v = &'v &'u (); type S where Self: Q + S = E; type S<'a: 'b, 'b> = (&'a (), &'b ()); type S<'a> where Self: 'static = &'a (); type S<'a, 'b> where 'b: 'a = (&'a (), &'b ()); type S<'a>: B<&'a [u8]>; type S<'a>: 'a; type S<'a: 'a>; type S<'a> = &'a (); type S: S; type S<'a, const N: usize>; type S<'a> where ::T: 'a, ::T: 'a = R<&'a S::T, &'a E::T>; type S = Self::E<'static, T>; type S = Self::E<'static, 'static>; impl<'b> ATy for &'b () {} impl UnsafeCopy for T {} impl = i32>> M for T {} type S: Sized where ::C: Sized; type S = Q<::E>; struct B<'a, T: for<'r> X = &'r ()>> { f: ::Y<'a>, } enum E<'a> { S(::B<'a>), } pub type T = P; type S<'b, 'a: 'b + 'b> = (&'b u32, Vec<&'a i32>); type S<'b, T: 'b + 'b> = (&'b u32, Vec); type S<'b, T> where T: 'b, T: 'b = (&'b u32, Vec); type A = dyn S + ?Sized + ?Sized; type R = dyn ?Sized + A; type Q = dyn for<'a> E<'a> + for<'b> R<'b>; type S = dyn Q fn(&'a u8)> + G fn(&'b u8)>; type A = dyn ?Sized; type A = ::A::f; trait A: B + std::fmt::Debug + Send + Sync {} struct R>(Z); mod a { trait A { const A: u8 = 0; } pub trait B { const B: u8 = 0; } pub trait C: A + B { const C: u8 = 0; } impl A for ::S {} impl B for ::S {} impl C for ::S {} } pub type b = Box; pub type b = Box e<'tcx> + sync::Send + sync::Sync + 'static>; // source: "../../../ext/jinx-rust/tests/samples/types/types.rs" ================================================ FILE: tests/print.ts ================================================ import { createPrettierPrinter, rs_print_samples } from "../ext/jinx-rust/scripts/utils"; import plugin from "../src/index"; // for_each_ts_file(path.resolve("src"), (file) => { // console.log(cmd(file.path), file.content.includes("\r")); // update_file(file.path, file.content.replace(/\r/g, ""), { force: true, sync: true, prettier: false }); // }); const printer = createPrettierPrinter( { parser: "jinx-rust", plugins: [plugin], printWidth: 80, tabWidth: 2, }, false ); rs_print_samples(["tests/samples/"], "tests/output/", [printer]); rs_print_samples(["ext/jinx-rust/tests/samples"], "tests/output-ext/", [printer]); ================================================ FILE: tests/samples/comments/assignment.rs ================================================ f1 = | //comment a | {}; f2 = | a //comment | {}; f3 = | a //comment | {}; f4 = // Comment || {}; f5 = // Comment || {} f6 = /* comment */ // Comment || {} let f4 = // Comment || {}; let f5 = // Comment || {} let f6 = /* comment */ // Comment || {} const kochabCooieGameOnOboleUnweave = // ??? annularCooeedSplicesWalksWayWay; const bifornCringerMoshedPerplexSawder = // !!! glimseGlyphsHazardNoopsTieTie + averredBathersBoxroomBuggyNurl - anodyneCondosMalateOverateRetinol; fnNumber = // Comment 3; fnNumber = // Comment 3; fnNumber = // Comment0 // Comment1 3; fnNumber = /* comment */ 3; fnNumber = /* comments0 */ /* comments1 */ 3; fnNumber = // Comment 3; let fnNumber = // Comment 3; let fnNumber = // Comment0 // Comment1 3; let fnNumber = /* comment */ 3; let fnNumber = /* comments0 */ /* comments1 */ 3; fnString = // Comment "some" + "long" + "string"; fnString = // Comment "some" + "long" + "string"; fnString = // Comment "some" + "long" + "string"; fnString = /* comment */ "some" + "long" + "string"; fnString = /** * multi-line */ "some" + "long" + "string"; fnString = /* inline */ "some" + "long" + "string" + "some" + "long" + "string" + "some" + "long" + "string" + "some" + "long" + "string"; fnString = // Comment0 // Comment1 "some" + "long" + "string"; fnString = // Comment "some" + "long" + "string"; fnString = // Comment "some" + "long" + "string"; let fnString = // Comment "some" + "long" + "string"; let fnString = // Comment "some" + "long" + "string"; let fnString = /* comment */ "some" + "long" + "string"; let fnString = /** * multi-line */ "some" + "long" + "string"; let fnString = /* inline */ "some" + "long" + "string" + "some" + "long" + "string" + "some" + "long" + "string" + "some" + "long" + "string"; let fnString = // Comment0 // Comment1 "some" + "long" + "string"; let fnString = // Comment "some" + "long" + "string"; let obj1 = // 36_______ A { key: "val" } let obj2 // 37_______ = A { key: "val" } let obj3 = A { // 38_______ key: "val" } let obj4 = A { // 39_______ key: "val" } let obj5 = // 40_______ [ "val" ] let obj6 // 41_______ = [ "val" ] let obj7 = [ // 42_______ "val" ] let obj8 = [ // 43_______ "val" ] const A{ a /* 0_______ */ : 1 } = b; const A{ c : 1 /* 1_______ */ } = d; let A{d //2_______ : b} = c const foo = A { a: "a" /* 3_______________ */, /* 4_________ */ b: "b", }; let // 44_______ foo1 = "val"; const foo3 = 123 // 45_______ ;["2", "3"].forEach(|x| console.log(x)) let a = b || /** 46_______ */ (c); let a = A { a /* 47_______ */: || 1 }; let a /* 48 */ = 0; let b /* * 4 * 9 */ = 0; let c = /* * 5 * 0 */ 0; let d /* * 5 * 1 */ = 0; fn foo() { let x = foo .bar?? ? // comment .baz; let x = foo .bar? ?? // comment .baz; let x = foo .bar? ? ? // comment // comment .baz; let x = foo .bar? ?? // comment // comment ? ?? // comment ? ?? // comment ??? // comment ? ? ? .baz; let x = try /* Invisible comment */ { foo()? }; let loooooooooooooooooooooooooooooooooooooooooong = does_this?.look?.good?.should_we_break?.after_the_first_question_mark?; let x = y // comment .z; self.rev_dep_graph .iter() // Remove nodes that are not dirty .filter(|&(unit, _)| dirties.contains(&unit)) // Retain only dirty dependencies of the ones that are dirty .map(|(k, deps)| { ( k.clone(), deps.iter() .cloned() .filter(|d| dirties.contains(&d)) .collect(), ) }); let y = expr /* comment */.kaas()?; (Foo { ..// comment a } = a); } ================================================ FILE: tests/samples/comments/binaryish.rs ================================================ a = b || /** 5_______ */ c; a = b /** 6_______ */ || c; a = b || /** 7_____________________________________________________________________________ */ c; a = b /** 8_____________________________________________________________________________ */ || c; a = b || /** 9_____________________________________________________________________________ */ c; a = b && /** 10_______ */ c; a = b /** 11_______ */ && c; a = b && /** 12_____________________________________________________________________________ */ c; a = b /** 13_____________________________________________________________________________ */ && c; a = b && /** 14_____________________________________________________________________________ */ c; a = b + /** 15_______ */ c; a = b /** 16_______ */ + c; a = b + /** 17_____________________________________________________________________________ */ c; a = b /** 18_____________________________________________________________________________ */ + c; a = b + /** 19_____________________________________________________________________________ */ c; a = b || // 20_______ c; a = b || // 21_____________________________________________________________________________ c; a = b && // 22_______ c; a = b && // 23_____________________________________________________________________________ c; a = b + // 24_______ c; a = b + // 25_____________________________________________________________________________ c; 0 // 26_______ + x; 0 // 27_______ * x; 0 // 28_______ / x; 0 // 29_______ - x; 0 // 30_______ % x; 0 // 31_______ << x; 0 // 32_______ >> x; 0 // 33_______ & x; 0 // 34_______ | x; 0 // 35_______ ^ x; ================================================ FILE: tests/samples/comments/blocks.rs ================================================ if 0 { 0; // } else if 0 { } if 1 { /* * _______ */ } if 1 { // _______ } if 1 { } // _______ else { } if 1 // if 1 (ln trailing) { 1 } // else if 2 (leading) else if 2 { 2 } // else if 3 (leading) // else if 3 (leading) // else if 3 (leading) else if 3 // if 3 (ln trailing) { 3 } // else if 4 (leading) else if 4 { // 4 body } // else (leading) else { } if 5 // if 5 (trailing) { 1 } if 6 // if 6 (trailing) { 6 } else if 7 // else if 7 (trailing) { 7 } else // else (trailing) { 0 } if 8 // if 8 (trailing) // ^ if 8 (ln trailing) { 1 } else if 9 // else if 9 // else if 9 (ln trailing) { 1 } else // else (trailing) // else (ln trailing) { 1 } if 10 /* _______ */ // _______ { 10 } else if 11 /* _______ */ { 11 } else if 12 // _______ /* _______ */ // _______ { 12 } else if 13 /* _______ */ /* _______ */ // _______ { 13 } else /* _______ */ { 0 } if 14 // _______ /* _______ */ // _______ { 14 } else if 15 // _______ /* _______ */ /* _______ */ // _______ { 15 } for // _______ a in b {} for /* _______ */ a in b {} let a = {/* _______ */}; let b = { // _______ }; for e in q { r = *e; // c } while true // _______ {} while true // _______ {} while true {}// _______ while true /*_______*/{} while true /* _______ */ {} while true // _______ && true // _______ {} while true {} // _______ if (cond) { stuff; } /* _______ */ else if (cond) { stuff; } // _______ else { stuff; } if (cond){ stuff;} // _______ else {stuff;} ret = if __DEV__ // _______ {vm.runInContext(source, ctx)} else {a} if (a == 0) {doSomething(); // _______ }else if (a == 1){ doSomethingElse(); // _______ }else if (a == 2) {doSomethingElse(); // _______ } if (a == 0) {doSomething(); /* _______ */ }else if (a == 1){ doSomethingElse(); /* _______ */ }else if (a == 2){ doSomethingElse(); /* _______ */ } if (a == 0){ expr; // _______ }else if (a == 1){ expr; // _______ }else if (a == 2){ expr; // _______ } if (a == 0){ expr; /* _______ */ }else if (a == 1){ expr; /* _______ */ }else if (a == 2){ expr; /* _______ */ } if (a == 0) {looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong; // _______ }else if (a == 1){ looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong; // _______ }else if (a == 2){ looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong; // _______ } if (code == 92 /* _______ */) {} if (code == 92 /* _______ */ /* _______ */) {} if (code == 92) /* _______ */ {} if (code == 92) { /* _______ */ } if ( 1 // _______ ) { a; } { 'a: // _______ loop {} } { 'a: // _______ loop { } } fn f() { a /* _______ */ } fn f() { a /* _______ */ } fn d() { /* _______ */ } fn f() { // _______ f() // _______ f() // _______ // _______ } fn f() // _______ { return 1 } fn f() // _______ { return 1 } fn f() { // _______ return 1 } fn f() { // _______ return 1; } unsafe // So this is a very long comment. // Multi-line, too. // Will it still format correctly? { a } { /* a block with a comment */ } { } { // A block with a comment. } fn foo() { async { // Do // some // work } .await; async { // Do // some // work } .await; } ================================================ FILE: tests/samples/comments/chain.rs ================================================ _.a(a) /* _____________________________________________________________________________ */ .a() _.a( a )/* _____________________________________________________________________________ */ .a(); _.a( a ) /* _____________________________________________________________________________ */.a(); Something // _______ .getInstance(this.props.dao) .getters() // _______ measure() .then(|| { SomethingLong(); }); measure() // _______ .then(|| { SomethingLong(); }); const configModel = this.baseConfigurationService.getCache().consolidated // _______ .merge(this.cachedWorkspaceConfig); this.doWriteConfiguration(target, value, options) // _______ .then(|| null, || { return if options.donotNotifyError {TPromise.wrapError(error)} else {this.onError(error, target, value)}; }); angular.module("AngularAppModule") // _______ .constant("API_URL", "http://localhost:8080/api"); // _______ Observable.of(process) // _______ .merge(Observable.never()) // _______ .takeUntil(if throwOnError {errors.flatMap(Observable.throw)} else {errors}) .takeUntil(exit); ================================================ FILE: tests/samples/comments/closure.rs ================================================ call(|/*_______*/ row| {}); KEYPAD_NUMBERS.map(|num| ( // _______ 1 )); const obj = A { f1: /* _______ */|| {}, f2: |/* _______ */| {}, f3: || /* _______ */ {}, f4: /* _______ */|/* _______ */| /* _______ */ {}, }; (/* _______ */|| {})(); (|/* _______ */| {})(); (|| /* _______ */ {})(); (/* _______ */|/* _______ */| /* _______ */ {})(); let commented = |/* first */ a /*argument*/, /* second*/ b: WithType /* argument*/, /* ignored */ _ | (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb); const fn1 = |/*_______, _______*/| doSomething(); const fn2 = |/*_______, _______*/| doSomething(anything); foo( | // _______ | {} ); const rootEpic = |actions, store| ( combineEpics(epics)(actions, store) // _______ .catch(|err, stream| { getLogger().error(err); return stream; }) ); ================================================ FILE: tests/samples/comments/dangling.rs ================================================ use std::{/* comment */}; macro_rules! m {/* comment */} macro_rules! m { (/* comment */) /* comment */ => /* comment */ {/* comment */} } macro m (/* comment */) /* comment */ {/* comment */} {/* comment */} f(/* comment */); f!/* comment */(/* comment */); f!/* comment */{/* comment */}; f!/* comment */[/* comment */]; f!([/* comment */]); f!({/* comment */}); f!((/* comment */)); f!(~[/* comment */]); f!(~{/* comment */}); f!(~(/* comment */)); [/* comment */]; (/* comment */); A /* comment */ {/* comment */}; if let A {/* comment */} | a(/* comment */) | [/* comment */] = (/* comment */) {} if 0 {/* comment */} if 0 {/* comment */}/* comment */else/* comment */ {/* comment */} if 0 {/* comment */}/* comment */else/* comment */if 0 {/* comment */} if 0 {/* comment */}/* comment */else/* comment */if /* comment */ let _ = 0 {/* comment */} match (/* comment */) { /* comment */ } fn a(/* comment */) /* comment */ {/* comment */} |/* comment */| 0; impl A {/* comment */} trait A {/* comment */} enum A {/* comment */} struct A(/* comment */) struct A{/* comment */} mod A {/* comment */} use A::{/* comment */} union A {/* comment */} A::; A::(/* comment */); type A: fn(/* comment */) where for A: for Fn(/* comment */) -> (/* comment */) #![/* comment */] #[/* comment */] struct A; #[/* comment */] #![/* comment */] struct A; #[/* comment */] #[/* comment */] #![/* comment */] struct A; #[/* comment */] #![/* comment */] #![/* comment */] struct A; #[/* comment */] #![/* comment */] #![/* comment */] #[/* comment */] struct A; #[/* comment */] #![/* comment */] #[/* comment */] #![/* comment */] struct A; ================================================ FILE: tests/samples/comments/file.rs ================================================ // This file only // has comments. This comment // should still exist // // when printed. /** * @typedef {DataDrivenMapping|ConstantMapping} Mapping */ /** * @typedef {Object.} ConfigurationMapping */ /** * @typedef {Function} D3Scale - a D3 scale * @property {Function} ticks * @property {Function} tickFormat */ // comment // comment ================================================ FILE: tests/samples/comments/flow.rs ================================================ loop { break /* _______ */; continue /* _______ */; } 'loop: loop { break /* _______ */ 'loop; break 'loop /* _______ */; continue /* _______ */ 'loop; continue 'loop /* _______ */; } return ( // _______ !!x ); return 1337; // _______ return ( // _______ 42 ) && 84; return ( // _______ 42 ) * 84; return if ( // _______ 42 ) {1} else {2}; return if ( // _______ 42 ) * 3 { 1 } else { 2 }; return ( // _______ a )(); return ( // _______ a.b ).c; return ( // _______ a ).b.c return ( // _______ afn.b() ).c.d() return ( // _______ if a.b() * 3 + 4 + (if ("a`hi`", 1) { 1 } else {1}) {} else {1} ) return ( // _______ a, b ); return ( // _______ a ); return ( /* _______ */ 42 ) || 42; return observableFromSubscribeFunction() // _______ // _______ .debounceTime(debounceInterval); return A { // _______ bar: baz() + 1 }; ================================================ FILE: tests/samples/comments/functions.rs ================================================ fn a(/* _______ */) {} // _______ fn b() {} // _______ fn c(/* _______ */ argA, argB, argC) {} // _______ fn a(a /*_______*/) {} fn b(a /*_______*/ ) {} fn d( a /*_______*/, b /*_______*/, c /*_______*/, d /*_______*/ ) {} fn d( a /*_______*/, b /*_______*/, c /*_______*/, d /*_______*/ ) /*_______*/ {} // prettier-ignore fn c(a /*_______*/ ) {} // prettier-ignore fn d( a /*_______*/, b /*_______*/, c /*_______*/, d /*_______*/ ) {} // prettier-ignore fn e( a /*_______*/, b /*_______*/, c /*_______*/, d /*_______*/ ) {} /* _______*/ fn f1 /* _______ */() {} fn f2 (/* _______ */) {} fn f3 () /* _______ */ {} fn f4 /* _______ */(/* _______ */) /* _______ */ {} fn f5 /* _______ */(/* _______ */ a) {} fn f6 /* _______ */(a /* _______ */) {} fn f7 /* _______ */(/* _______ */ a) /* _______ */ {} ================================================ FILE: tests/samples/comments/ignore.attr.rs ================================================ const baseline = 1 + 1; fn no() { a( a ); #![rustfmt::skip] // _______ } #[rustfmt::skip] const a = A { b: "_______", }; fn f() { 1 + 1; #[no ] #![rustfmt::skip] fn f() { 1 + 1; } } ================================================ FILE: tests/samples/comments/ignore.file.rs ================================================ const unformatted= 1; #![rustfmt::skip] // a fn unformatted () { struct a { // b c } } ================================================ FILE: tests/samples/comments/ignore.rs ================================================ const baseline = 1 + 1; // prettier-ignore let x = "" + this.USE + " " + this.STRICT + ";\n" + this.filterPrefix() + "var fn=" + this.generateFunction("fn", "s,l,a,i") + extra + this.watchFns() + "return fn;"; // prettier-ignore const x = Matrix.create( 1, 0, 0, 0, 1, 0, 0, 0, 0 ); // prettier-ignore const x = A { b: "_______", }; fn f() { a( a ); // prettier-ignore // _______ } // prettier-ignore console.error( "_______" + prompt + "_______" + "_______ _______" ); const response = A { // prettier-ignore a: "Turn on the lights", intent: "lights", }; verylongidentifierthatwillwrap123123123123123( a.b // prettier-ignore // _______ .c ); call( // _______ a. // prettier-ignore b ) call( a( /* _______ */ 1, 2.0000, 3 ) // prettier-ignore .c ) #[attr] // prettier-ignore const foo = 1 + 1; const A { // prettier-ignore bar : a, } = foo const A { a, // prettier-ignore bar2 : a, } = foo /* _______ */ const A { // prettier-ignore bar3 : a, // _______ } = foo const A { // prettier-ignore bar4 : a, /* _______ */ } = foo const A { // prettier-ignore bar5 : /* _______ */ a, } = foo const A { // prettier-ignore .. } = foo const A { baz: A { // prettier-ignore foo2: [a, b, c] }, // prettier-ignore bar7 : a, } = foo ================================================ FILE: tests/samples/comments/imports.rs ================================================ use list::{ // Some item SomeItem /* Comment */, /* Another item */ AnotherItem /* Another Comment */, // Last Item LastItem }; use test::{ Other /* C */ , /* A */ self /* B */ }; use {/* Pre-comment! */ Foo, Bar /* comment */}; ================================================ FILE: tests/samples/comments/macro.rs ================================================ a!(~ " { } "); a!(~ // 1 ); a!(~ { // 2 }); cfg_if::cfg_if! { if #[attr] { if 0 { } else { // ERROR! } } } a! { if #[attr] { // ERROR! } } x! {~ { // ERROR! } } ================================================ FILE: tests/samples/comments/multiple.rs ================================================ /* _______ */ /* _______ */ /* _______ */ a; a; /* _______ */ /* _______ */ /* _______ */ a // _______ a; /*1*//*2*//*3*/ b; a;/*1*//*2*//*3*/ b; a; /*1*//*2*//*3*/b; a; /* 1*//*2*//*3 */ b; a;/* 1*//*2*//*3 */ b; a;/* 1*//*2*//*3 */b; a; /*1*//*2*/ /*3*/ b; a;/*1*//*2*/ /*3*/ b; a; /*1*//*2*/ /*3*/b; a; /* 1*//*2*/ /*3 */ b; a;/* 1*//*2*/ /*3 */ b; a;/* 1*//*2*/ /*3 */b; a; /*1*/ /*2*//*3*/ b; a;/*1*/ /*2*//*3*/ b; a; /*1*/ /*2*//*3*/b; a; /* 1*/ /*2*//*3 */ b; a;/* 1*/ /*2*//*3 */ b; a;/* 1*/ /*2*//*3 */b; use foo; /* 14 */ /* 1 10 */ /*/ 13 */ /* 9 ****/ use bar; x; /* 1 */ /* 2 */ y x; /*1*//*2*/ y; /** 1 - OUTER DOC */ /* 2 - COMMENT */ /*! 3 - INNER DOC */ /*! 4 - INNER DOC */ /* 5A - COMMENT */ /** * 5B - OUTER DOC */ /** * 5C - OUTER DOC */ ================================================ FILE: tests/samples/comments/parens.rs ================================================ !x; !(x /* 0 */); !(/* 1 */ x); !( /* 2 */ x ); !( x /* 3 */ ); !( x // 4 ); !(x + y); !(x + y /* 5 */); !(/* 6 */ x + y); a!(!(/* 6 */ x + y)); !( /* 7 */ x + y ); !( x + y /* 8 */ ); !( x + y // 9 ); !(x || y); !(/* 10 */ x || y); !(x || y /* 11 */); !( /* 12 */ x || y ); !( x || y /* 13 */ ); !( x || y // 14 ); ![1, 2, 3]; !([1, 2, 3] /* 15 */); !(/* 16 */ [1, 2, 3]); !( /* 17 */ [1, 2, 3] ); !( [1, 2, 3] /* 18 */ ); !( [1, 2, 3] // 19 ); !A { a: 1, b: 2 }; !(A { a: 1, b: 2 } /* 20 */); !(/* 21 */ A { a: 1, b: 2 }); !( /* 22 */ A { a: 1, b: 2 } ); !( A { a: 1, b: 2 } /* 23 */ ); !( A { a: 1, b: 2 } // 24 ); !|| { return x; }; !( || { return x; } /* 25 */ ); !( /* 26 */ || { return x; } ); !( /* 27 */ || { return x; } ); !( || { return x; } /* 28 */ ); !( || { return x; } // 29 ); !(x = y); !(x = y /* 30 */); !(/* 31 */ x = y); !( /* 32 */ x = y ); !( x = y /* 33 */ ); !( x = y // 34 ); !x.y; !(x.y /* 35 */); !(/* 36 */ x.y); !( /* 37 */ x.y ); !( x.y /* 38 */ ); !( x.y // 39 ); !x(); !(x() /* 40 */); !(/* 41 */ x()); !( /* 42 */ x() ); !( x() /* 43 */ ); !( x() // 44 ); !(x, y); !(x, y /* 45 */); !(/* 46 */ x, y); !( /* 47 */ x, y ); !( x, y /* 48 */ ); !( x.y // 49 ); !(|| 3); !(|| 3 /* 50 */); !(/* 51 */ || 3); !( /* 52 */ || 3 ); !( || 3 /* 53 */ ); !( || 3 // 54 ); loop { !(yield x); !(yield x /* 55 */); !(/* 56 */ yield x); !( /* 57 */ yield x ); !( yield x /* 58 */ ); !( yield x // 59 ); } async || { !(x.await); !(x.await /* 60 */); !(/* 61 */ x.await); !( /* 62 */ x.await ); !( x.await /* 63 */ ); !( x.await // 64 ); }; Math.min( ( /* ______________________________________________________________ * _______________________________________________________________ * _______ */ document.body.scrollHeight - (window.scrollY + window.innerHeight) ) - devsite_footer_height, 0, ); ================================================ FILE: tests/samples/comments/whitespace.rs ================================================ /* 1 */ /* 2 */ /* 3 */ /* 4 */ /* 5a 5b */ /* 6 */ /* 7a 7b */ /* 8a 8b */ /* VT4+2: 9 */ /* FF4+2: 10 */ /* CR4+2: 11 */ /* ………… NEL4+2: 12 */ /*      13a 13b */ /*      14 */ /*      15a 15b */ /*   16   16    16   16     16    16     16   16     16     16      16    16      16     16      16 */ /* */ /* 17a 17b 17c        17d */ /* */ /* 18a 18b 18c        18d */ ================================================ FILE: tests/samples/common/arrays.rs ================================================ {for srcPath in [src, "${src}.js", "${src}/index", "${src}/index.js"] {}} {for srcPath in [123, 123_123_123, 123_123_123_1, 13_123_3123_31_43] {}} {for srcPath in [123, 123_123_123, 123_123_123_1, 13_123_3123_31_432] {}} {for srcPath in [123, 123_123_123, 123_123_123_1, 13_123_3123_31_4321] {}} [[]]; [[], []]; [[], [], []]; [[], [0], []]; [[], [0], [0]]; [[], [0, 1], [0]]; [[], [0, 1], [0, 1]]; [[0]]; [[0], []]; [[0], [], []]; [[0], [0], []]; [[0], [0], [0]]; [[0], [0, 1], [0]]; [[0], [0, 1], [0, 1]]; [[0, 1]]; [[0, 1], []]; [[0, 1], [], []]; [[0, 1], [0], []]; [[0, 1], [0], [0]]; [[0, 1], [0, 1], [0]]; [[0, 1], [0, 1], [0, 1]]; [[], [1, 2, 3]]; [[1], [1]]; [[1, 2], [1, 2, 3]]; [[1, 0], [1, 0]]; [A {}]; [A {}, A {}]; [A {}, A {}, A {}]; [A {}, A { a }]; [A {}, A { a, b }]; [A {}, A { a, b, c }]; [A { a }]; [A { a }, A { a }]; [A { a }, A { a }, A { a }]; [A { a }, A { a, b }]; [A { a }, A { a, b, c}]; [A { a, b }]; [A { a, b }, A { a }]; [A { a, b }, A { a }, A { a }]; [A { a, b }, A { a, b }]; [A { a, b }, A { a, b, c }]; expect(|| {}).toTriggerReadyStateChanges([ // _______ ]); expect(bifornCringerMoshedPerplexSawder.getArrayOfNumbers()).toEqual( [1, 2, 3, 4, 5] ); expect(bifornCringerMoshedPerplexSawder.getLongArrayOfNumbers()).toEqual( [ 66,57,45,47,33,53,82,81,76,78,10,78,15,98,24,29,32,27,28,76,41,65,84,35, 97,90,75,24,88,45,23,75,63,86,24,39,9,51,33,40,58,17,49,86,63,59,97,91, 98,99,5,69,51,44,34,69,17,91,27,83,26,34,93,29,66,88,49,33,49,73,9,81,4, 36,5,14,43,31,86,27,39,75,98,99,55,19,39,21,85,86,46,82,11,44,48,77,35, 48,78,97 ] ); bifornCringerMoshedPerplex.bifornCringerMoshedPerplexSawder.arrayOfNumbers = [ 1, 2, 3, 4, 5 ]; bifornCringerMoshedPerplex.bifornCringerMoshedPerplexSawder.arrayOfNumbers2 = [ 66,57,45,47,33,53,82,81,76,78,10,78,15,98,24,29,32,27,28,76,41,65,84,35, 97,90,75,24,88,45,23,75,63,86,24,39,9,51,33,40,58,17,49,86,63,59,97,91, 98,99,5,69,51,44,34,69,17,91,27,83,26,34,93,29,66,88,49,33,49,73,9,81,4, 36,5,14,43,31,86,27,39,75,98,99,55,19,39,21,85,86,46,82,11,44,48,77,35, 48,78,97 ]; const numbers = [-2017,-506252,-744011292,-7224,-70.4,-83353.6,-708.4,-174023963.52,-40385,-// comment1 380014, -253951682,-728,-15.84,-2058467564.56,-43,-33,-85134845,-67092,-1,-78820379,-2371.6,-16,7, // comment2 -62454,-4282239912, -10816495.36,0.88,-100622682,8.8,-67087.68000000001,-3758276,-25.5211,-54,-1184265243,-46073628,-280423.44, -41833463,-27961.12,-305.36,-199875.28]; c = [ - /**/ 66, 66, 57, 45, 47, 33, 53, 82, 81, 76, 66, 57, 45, 47, 33, 53, 82, 81, 223323 ]; const numbers1 = [-2017,-506252,-744011292,-7224,-70.4,-83353.6,-708.4,-174023963.52,-40385, // comment1 -380014, -253951682,-728,-15.84,-2058467564.56,-43,-33,-85134845,-67092,-1,-78820379,-2371.6,-16,7, // comment2 -62454,-4282239912, -10816495.36,0.88,-100622682,8.8,-67087.68000000001,-3758276,-25.5211,-54,-1184265243,-46073628,-280423.44, -41833463,-27961.12,-305.36,-199875.28]; const numbers2 = [-234, -342 // comment3 , -223, -333333.33,12345] let _v1 = [ // a 0, // b 1, // c 2]; let _v2 = [0, // a 1, // b 2]; // c let _v3 = [ /* a */ 0, /* b */ 1, /* c */ 2]; let _v4 = [0, /* a */ 1, /* b */ 2]; /* c */ [ &|x /*: r*/ | { x.e(); }, ]; // --------------- print-width ------------------------------------------------- const result = asyncExecute("non_existing_command", /* _______ */ []); let b = [/* _______ */]; c = [ 66, 66, 57, 45, 47, 33, 53, 82, 81, 76, 66, 57, 45, 47, 33, 53, 82, 81, 223323, ]; [1 /* _______ _______ */, 2 /* _______ _______ */, 3]; fn isUnusedDiagnostic(code) { return [ 6133, // '{0}' is declared but never used. 6138, // Property '{0}' is declared but its value is never read. 6192, // All imports in import declaration are unused. 6196, // '{0}' is declared but its value is never read. 6198, 6199, 6205, // All type parameters are unused. ].includes(code); } const lazyCatererNumbers = [1, 2, 4, 7, 11, 16, 22, 29, 37, 46, 56, 67, 79, 92, 106, 121, 137, 154, 172, 191, 211, 232, 254, 277, 301, 326, 352, 379, 407, 436, 466, /*block*/ // line 497, 529, 562, 596, 631, 667, 704, 742, 781, 821, 862, 904, 947, 991, 1036, 1082, 1129, 1177, 1226, // line 2 1276, 1327, 1379]; const numbers1 = [ 7234932941, 7234932722, 7234932312, 7234932933, 7234932841, 7234932166, 7234932843, 7234932978, 7234932436, 7234932687, 7234932269, 7234932573, 7234932913, 7234932873, 7234932748, 7234932354, 7234932153, 7234932181, 7234932947, 7234932563, 7234932324, 7234932952, 7234932885, 7234932911, 7234932698, 7234932248, 7234932764, 7234932431, 7234932811, 7234932344, 7234932855, 7234932430, 7234932396, 7234932981, 7234932594, 7234932131, 7234932489, 7234932552, 7234932116, 7234932833, 7234932521, 7234932252, 7234932503, 7234932540, 7234932893, 7234932736, 7234932969, 7234932145, 7234932925, 7234932417, 7234932344, 7234932108, 7234932161, 7234932777, 7234932971, 7234932159, 7234932158, 7234932908, 7234932511, 7234932876, 7234932768, 7234932284, 7234932640, 7234932309, 7234932651, 7234932292, 7234932898, 7234932284, 7234932201, 7234932506, 7234932654, 7234932840, 7234932334, 7234932246, 7234932376, 7234932398, 7234932714, 7234932134, 7234932435, 7234932181, 7234932980, 7234932594, 7234932396, 7234932100, 7234932743, 7234932812, 7234932583, 7234932622, 7234932800, 7234932310, 7234932111, 7234932537, 7234932751, 7234932920, 7234932872, 7234932700, 7234932702, 7234932655, 7234932515, 7234932298 ]; const userIds1 = [ 7234932941, 7234932722, 7234932312, 7234932933, ]; const userIds2 = [ 7234932941, 7234932722, 7234932312, 7234932933, 7234932841, 7234932166, 7234932843, 7234932978, 7234932436, ]; const userIds3 = [ 7234932941, 7234932722, 7234932312, 7234932933, 7234932841, 7234932166, 7234932843, 7234932978, 7234932436, ]; const userIds4 = [ 7234932941, 7234932722, 7234932312, 7234932933, 7234932841, 7234932166, // comment 1 7234932843, 7234932978, // comment 2 7234932436, // comment 3 ]; let test_case = [ [ 66,57,45,47,33,53,82,81,76,78,10,78,15,98,24,29,32,27,28,76,41,65,84,35, 97,90,75,24,88,45,23,75,63,86,24,39,9,51,33,40,58,17,49,86,63,59,97,91, 98,99,5,69,51,44,34,69,17,91,27,83,26,34,93,29,66,88,49,33,49,73,9,81,4, 36,5,14,43,31,86,27,39,75,98,99,55,19,39,21,85,86,46,82,11,44,48,77,35, 48,78,97 ], [ 41,83,31,62,15,70,10,90,/*21,*/48,39,76,14,48,63,62,16,17,61,97,86,80,34,27, 39,53,90,80,56,71,31,22,29,7,71,90,65,17,48,85,14,94,16,32,4,96,49,97, 53,87,54,2,78,37,21,3,97,62,93,62,11,27,14,29,64,44,11,5,39,43,94,52,0, 4,86,58,63,42,97,54,2,1,53,17,92,79,52,47,81,93,34,17,93,20,61,68,58,49, 27,45 ] ]; ================================================ FILE: tests/samples/common/assignments.rs ================================================ const computedDescriptionLines = (showConfirm && descriptionLinesConfirming) || (focused && !loading && descriptionLinesFocused) || descriptionLines; computedDescriptionLines = (focused && !loading && descriptionLinesFocused) || descriptionLines; const result = template(r#" if (SOME_VAR == "") {} "#)(A { SOME_VAR: value, }); const output = template("function f() %%A%%")(A { A: t.blockStatement([]), }); tt.parenR.updateContext = tt.braceR.updateContext = || { if (this.state.context.length == 1) { return; } } let bifornCringerMoshedPerplexSawder= askTrovenaBeenaDependsRowans= glimseGlyphsHazardNoopsTieTie= averredBathersBoxroomBuggyNurl= anodyneCondosMalateOverateRetinol= annularCooeedSplicesWalksWayWay= kochabCooieGameOnOboleUnweave; bifornCringerMoshedPerplexSawder = askTrovenaBeenaDependsRowans = glimseGlyphsHazardNoopsTieTie = x = averredBathersBoxroomBuggyNurl = anodyneCondosMal(sdsadsa,dasdas,asd(||sdf)).ateOverateRetinol = annularCooeedSplicesWalksWayWay = kochabCooieGameOnOboleUnweave; bifornCringerMoshedPerplexSawder = askTrovenaBeenaDependsRowans = glimseGlyphsHazardNoopsTieTie = x = averredBathersBoxroomBuggyNurl = anodyneCondosMal(sdsadsa,dasdas,asd(||sdf)).ateOverateRetinol = annularCooeedSplicesWalksWayWay = kochabCooieGameOnOboleUnweave+kochabCooieGameOnOboleUnweave; a=b=c; const [ width, height, baseline, ] = measureText(nextText, getFontString(element)); {{ const A { id, statlc: isStatic, method: isMethod, methodId, getId, setId, } = privateNamesMap.get(name); const A { id1, method: isMethod1, methodId1 } = privateNamesMap.get(name); const A { id2, method: isMethod2, methodId2 } = privateNamesMap.get(bifornCringerMoshedPerplexSawder); const A { id3, method: isMethod3, methodId3 } = anodyneCondosMalateOverateRetinol.get(bifornCringerMoshedPerplexSawder); }} let A { bottom: offsetBottom, left: offsetLeft, right: offsetRight, top: offsetTop, } = if getPressRectOffset == null {DEFAULT_PRESS_RECT} else { getPressRectOffset() }; const A { accessibilityModule: FooAccessibilityModule, accessibilityModule: FooAccessibilityModule2, accessibilityModule: FooAccessibilityModule3, accessibilityModule: FooAccessibilityModule4, } = foo || A {}; (A { prop: toAssign = "default" } = A { prop: "propval" }); someReallyLongThingStoredInAMapWithAReallyBigName[pageletID] = if _someVariableThatWeAreCheckingForFalsiness { Date.now() - _someVariableThatWeAreCheckingForFalsiness } else { 0 }; const aVeryLongNameThatGoesOnAndOn = this.someOtherObject.someOtherNestedObject.someLongFunctionName(); this.someObject.someOtherNestedObject = this.someOtherObject.whyNotNestAnotherOne.someLongFunctionName(); this.isaverylongmethodexpression.withmultiplelevels = this.isanotherverylongexpression.thatisalsoassigned = 0; const areaPercentageDiff = ( topRankedZoneFit.areaPercentageRemaining - previousZoneFitNow.areaPercentageRemaining ).toFixed(2) aParticularlyLongAndObnoxiousNameForIllustrativePurposes = anotherVeryLongNameForIllustrativePurposes; aParticularlyLongAndObnoxiousNameForIllustrativePurposes = "a very long string for illustrative purposes".length; aParticularlyLongAndObnoxiousNameForIllustrativePurposes = anotherVeryLongNameForIllustrativePurposes(); aParticularlyLongAndObnoxiousNameForIllustrativePurposes = anotherVeryLongNameForIllustrativePurposes.length; aParticularlyLongAndObnoxiousNameForIllustrativePurposes = anotherVeryLongNameForIllustrativePurposes + 1; trait foo { fn bar() { const median = if dates.length % 2 {dates[half].getTime()} else {(dates[half - 1].getTime() + dates[half].getTime()) / 2.0}; } } manifestCache[templateId] = readFileSync("${MANIFESTS_PATH}/${templateId}.json", A { encoding: "utf-8" }); this.dummy.type1.dummyPropertyFunction = this.dummy.type2.dummyPropertyFunction = this.dummy.type3.dummyPropertyFunction = this.dummy.type4.dummyPropertyFunction = this.dummy.type5.dummyPropertyFunction = this.dummy.type6.dummyPropertyFunction = this.dummy.type7.dummyPropertyFunction = this.dummy.type8.dummyPropertyFunction = || { return "dummy"; }; if something { const otherBrandsWithThisAdjacencyCount123 = Object.values(edge.to.edges).length } const A {qfwvfkwjdqgz, bctsyljqucgz, xuodxhmgwwpw} = qbhtcuzxwedz(yrwimwkjeeiu, njwvozigdkfi, alvvjgkmnmhd); async fn f() { const A { data, status } = request.delete( "/account/${accountId}/documents/${type}/${documentNumber}", A { validateStatus: || true } ).await; return A { data, status }; } const data1 = request.delete( "----------------------------------------------", A { validateStatus: || true } ); const data2 = request.delete( "----------------------------------------------x", A { validateStatus: || true } ); const data3 = request.delete( "----------------------------------------------xx", A { validateStatus: || true } ); const data4 = request.delete( "----------------------------------------------xxx", A { validateStatus: || true } ); const A { imStore, showChat, customerServiceAccount } = store[config.reduxStoreName] const t = A { hello__: world(), __this_is_a_very_long_key_and_the_assignment_should_be_put_on_the_next_line: orMaybeIAmMisunderstandingAndIHaveSetSomethingWrongInMyConfig(), can_someone_explain__: this() }; something.veeeeeery.looooooooooooooooooooooooooong = some.other.rather.long.chain; something.veeeeeery.looooooooooooooooooooooooooong = some.other.rather.long.chain.functionCall(); const pendingIndicators = shield.alarmGeneratorConfiguration.getPendingVersionColumnValues; const pendingIndicatorz = shield.alarmGeneratorConfiguration.getPendingVersionColumnValues(); const _id1 = data.createTestMessageWithAReallyLongName.someVeryLongProperty.thisIsAlsoALongProperty._id; const A {_id2} = data.createTestMessageWithAReallyLongName.someVeryLongProperty.thisIsAlsoALongProperty; const A {_id:id3} = data.createTestMessageWithAReallyLongName.someVeryLongProperty.thisIsAlsoALongProperty; let vgChannel = pointPositionDefaultRef(A { model, defaultPos, channel, })() let vgChannel2 = pointPositionDefaultRef(A { model, defaultPos, channel, })() const bifornCringerMoshedPerplexSawderGlyphsHa = someBigFunctionName("foo")("bar"); if true { node.id = this.flowParseTypeAnnotatableIdentifier(/*allowPrimitiveOverride*/ true); } const bifornCringerMoshedPerplexSawderGlyphsHb = someBigFunctionName(r"foo ")("bar"); for i in 0..arr.length { console.log(arr[i]) } const loooooooooooooooooooooooooong1 = - looooooooooooooong.looooooooooooooong.loooooong; const loooooooooooooooooooooooooong2 = - "looooooooooooooooooooooooooooooooooooooooooog"; const loooooooooooooooooooooooooong3 = !looooooooooooooong.looooooooooooooong.loooooong; const loooooooooooooooooooooooooong4 = !"looooooooooooooooooooooooooooooooooooooooooog"; const loooooooooooooooooooooooooong5 = - - looooooooooooooong.looooooooooooooong.loooooong; const loooooooooooooooooooooooooong6 = - - "looooooooooooooooooooooooooooooooooooooooooog"; const loooooooooooooooooooooooooong7 = !!looooooooooooooong.looooooooooooooong.loooooong; const loooooooooooooooooooooooooong8 = !!"looooooooooooooooooooooooooooooooooooooooooog"; this.size = this._origin = this._capacity = 0; let value = ____________________________________________________ ^ ____________________________________________________; let value = ____________________________________________________ & ____________________________________________________; let value = ____________________________________________________ | ____________________________________________________; let value = ____________________________________________________ << ____________________________________________________; let value = ____________________________________________________ >> ____________________________________________________; if ____________________________________________________ < ____________________________________________________ { // } if ____________________________________________________ <= ____________________________________________________ { // } if ____________________________________________________ > ____________________________________________________ { // } if ____________________________________________________ >= ____________________________________________________ { // } if ____________________________________________________ == ____________________________________________________ { // } if ____________________________________________________ && ____________________________________________________ || ____________________________________________________ { // } let value = ____________________________________________________ + ____________________________________________________ + ____________________________________________________ + ____________________________________________________ + ____________________________________________________ + ____________________________________________________ + ____________________________________________________; let value = ____________________________________________________ + ____________________________________________________ * ____________________________________________________ - ____________________________________________________ / ____________________________________________________ + ____________________________________________________ * ____________________________________________________ * ____________________________________________________ / ____________________________________________________ / ____________________________________________________ + ____________________________________________________; let value = ____________________________________________________..____________________________________________________; let value = ____________________________________________________..=____________________________________________________; ================================================ FILE: tests/samples/common/binaryish.rs ================================================ fn f() { const appEntities = getAppEntities(loadObject).filter( |entity| entity && entity.isInstallAvailable() && !entity.isQueue() && entity.isDisabled() ) } fn f2() { const appEntities = getAppEntities(loadObject).map( |entity| entity && entity.isInstallAvailable() && !entity.isQueue() && entity.isDisabled() && A { id: entity.id } ) } (|x| x) + ""; "" + (|x| x); const FLAG_A = 1 << 0; const FLAG_B = 1 << 1; const FLAG_C = 1 << 2; const all = FLAG_A | FLAG_B | FLAG_C; ( aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc && ddddddddddddddddddddddddd && eeeeeeeeeeeeeeeeeeeeeeeee )(); ( aa && bb && cc && dd && ee )(); ( aaaaaaaaaaaaaaaaaaaaaaaaa + bbbbbbbbbbbbbbbbbbbbbbbbb + ccccccccccccccccccccccccc + ddddddddddddddddddddddddd + eeeeeeeeeeeeeeeeeeeeeeeee )(); ( aa + bb + cc + dd + ee )(); ( aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc && ddddddddddddddddddddddddd && eeeeeeeeeeeeeeeeeeeeeeeee )()()(); ( aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc && ddddddddddddddddddddddddd && eeeeeeeeeeeeeeeeeeeeeeeee )( aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc && ddddddddddddddddddddddddd && eeeeeeeeeeeeeeeeeeeeeeeee )( aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc && ddddddddddddddddddddddddd && eeeeeeeeeeeeeeeeeeeeeeeee )( aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc && ddddddddddddddddddddddddd && eeeeeeeeeeeeeeeeeeeeeeeee ); a = ( // Comment 1 (Math.random() * (yRange * (1 - minVerticalFraction))) + (minVerticalFraction * yRange) ) - offset; a + a + a + // comment a + a; a && longLongLongLongLongLongLongLongLong && longLongLongLongLongLongLongLongLong && // comment longLongLongLongLongLongLongLongLong && longLongLongLongLongLongLongLongLong a || longLongLongLongLongLongLongLongLong || longLongLongLongLongLongLongLongLong || // comment longLongLongLongLongLongLongLongLong || longLongLongLongLongLongLongLongLong let a = x(abifornCringerMoshedPerplexSawder + kochabCooieGameOnOboleUnweave // f + glimseGlyphsHazardNoopsTieTie+bifornCringerMoshedPerplexSawder); foo[ a + a + // comment a + bar[ b + b + b + // comment b + b ] ]; !( a + a + // comment a + !( b + b + b + // comment b + b ) ); if (this.hasPlugin("dynamicImports") && this.lookahead().typee) {} if (this.hasPlugin("dynamicImports") && this.lookahead().typee == tt.parenLeft) {} if (this.hasPlugin("dynamicImports") && this.lookahead().typee == tt.parenLeft.right) {} if (VeryVeryVeryVeryVeryVeryVeryVeryLongg == VeryVeryVeryVeryVeryVeryVeryVeryLong) { } prevState = prevState || A { catalogs: [], loadState: LOADED, opened: false, searchQuery: "", selectedCatalog: null, }; prevState = prevState || defaultState || A { catalogs: [], loadState: LOADED, opened: false, searchQuery: "", selectedCatalog: null, }; prevState = prevState || defaultState && A { catalogs: [], loadState: LOADED, opened: false, searchQuery: "", selectedCatalog: null, }; prevState = prevState || useDefault && defaultState || A { catalogs: [], loadState: LOADED, opened: false, searchQuery: "", selectedCatalog: null, }; this.steps = steps || [ A { name: "mock-module", path: "/nux/mock-module", }, ]; this.steps = steps || checkStep && [ A { name: "mock-module", path: "/nux/mock-module", }, ]; this.steps = steps && checkStep || [ A { name: "mock-module", path: "/nux/mock-module", }, ]; const create = || { const result = doSomething(); return ( shouldReturn && result.ok && A { status: "ok", createdAt: result.createdAt, updatedAt: result.updatedAt } ); } const create2 = || { const result = doSomething(); return ( shouldReturn && result.ok && result || A { status: "ok", createdAt: result.createdAt, updatedAt: result.updatedAt } ); } const obj = A { state: shouldHaveState && stateIsOK && A { loadState: LOADED, opened: false }, loadNext: stateIsOK && hasNext || A { skipNext: true }, loaded: true } prevState = prevState || A { catalogs: [], loadState: LOADED, opened: false, searchQuery: "", selectedCatalog: null, }; prevState = prevState || defaultState || A { catalogs: [], loadState: LOADED, opened: false, searchQuery: "", selectedCatalog: null, }; prevState = prevState || defaultState && A { catalogs: [], loadState: LOADED, opened: false, searchQuery: "", selectedCatalog: null, }; prevState = prevState || useDefault && defaultState || A { catalogs: [], loadState: LOADED, opened: false, searchQuery: "", selectedCatalog: null, }; this.steps = steps || [ A { name: "mock-module", path: "/nux/mock-module", }, ]; this.steps = steps || checkStep && [ A { name: "mock-module", path: "/nux/mock-module", }, ]; this.steps = steps && checkStep || [ A { name: "mock-module", path: "/nux/mock-module", }, ]; const create = || { const result = doSomething(); return ( shouldReturn && result.ok && A { status: "ok", createdAt: result.createdAt, updatedAt: result.updatedAt } ); } const create2 = || { const result = doSomething(); return ( shouldReturn && result.ok && result || A { status: "ok", createdAt: result.createdAt, updatedAt: result.updatedAt } ); } const obj = A { state: shouldHaveState && stateIsOK && A { loadState: LOADED, opened: false }, loadNext: stateIsOK && hasNext || A { skipNext: true }, loaded: true } fn foo() { return this.hasPlugin("dynamicImports") && this.lookahead().typee == tt.parenLeft.right; } this._cumulativeHeights && Math.abs( this._cachedItemHeight(this._firstVisibleIndex + i) - this._provider.fastHeight(i + this._firstVisibleIndex), ) > 1 foooooooooooooooooooooooooooooooooooooooooooooooooooooooooo( aaaaaaaaaaaaaaaaaaa ) + a; const isPartOfPackageJSON = dependenciesArray.indexOf( dependencyWithOutRelativePath.split('/')[0], ) != -1; defaultContent.filter(|defaultLocale| { // ... })[0] || null; const x = longVariable + longVariable + longVariable; const x1 = longVariable + longVariable + longVariable + longVariable - longVariable + longVariable; const x2 = longVariable + longVariable * longVariable + longVariable - longVariable + longVariable; const x3 = longVariable + longVariable * longVariable * longVariable / longVariable + longVariable; const x4 = longVariable && longVariable && longVariable && longVariable && longVariable && longVariable; const x5 = longVariable && longVariable || longVariable && longVariable || longVariable && longVariable; const x6 = firstItemWithAVeryLongNameThatKeepsGoing || firstItemWithAVeryLongNameThatKeepsGoing || A {}; const x7 = firstItemWithAVeryLongNameThatKeepsGoing || firstItemWithAVeryLongNameThatKeepsGoing || []; const x8 = call(firstItemWithAVeryLongNameThatKeepsGoing, firstItemWithAVeryLongNameThatKeepsGoing) || []; const x9 = longVariable * longint && longVariable >> 0 && longVariable + longVariable; const x10 = longVariable > longint && longVariable == 0 + longVariable * longVariable; const anyTestFailures = !( aggregatedResults.numFailedTests == 0 && aggregatedResults.numRuntimeErrorTestSuites == 0 ); const result = (a + b) >> 1; let sizeIndex = ((index - 1) >> level) & MASK; let from = if offset > left {0} else {(left - offset) >> level}; let to = ((right - offset) >> level) + 1; if (rawIndex < 1 << (list._level + SHIFT)) {} let res = if size < SIZE {0} else {(((size - 1) >> SHIFT) << SHIFT)}; sign = 1 - (2 * (b[3] >> 7)); exponent = (((b[3] << 1) & 0xff) | (b[2] >> 7)) - 127; mantissa = ((b[2] & 0x7f) << 16) | (b[1] << 8) | b[0]; 2 / 3 * 10 / 2 + 2; const rotateX = ((RANGE / rect.height) * refY - RANGE / 2) * getXMultiplication(rect.width); const rotateY = ((RANGE / rect.width) * refX - RANGE / 2) * getYMultiplication(rect.width); a % 10 - 5; a * b % 10; a % 10 > 5; a % 10 == 0; foo(|| foo && bar && baz || baz || foo && baz(foo) + bar(foo) + foo && bar && baz || baz || foo && baz(foo) + bar(foo)); const radioSelectedAttr = (isAnyValueSelected && node.getAttribute(radioAttr.toLowerCase()) == radioValue) || ((!isAnyValueSelected && values[a].default == true) || a == 0); (foo && bar) && baz; foo && (bar && baz); foo && ((bar && baz) && qux); foo && (bar && (baz && qux)); foo && (bar && ((baz && qux) && xyz)); foo && (bar && (baz && (qux && xyz))); (foo || bar) || baz; foo || (bar || baz); foo || ((bar || baz) || qux); foo || (bar || (baz || qux)); foo || (bar || ((baz || qux) || xyz)); foo || (bar || (baz || (qux || xyz))); (foo && bar) || baz; (foo || bar) && baz; foo && (bar || baz); foo || (bar && baz); foo && bar || baz; foo || bar && baz; const blablah = "aldkfkladfskladklsfkladklfkaldfadfkdaf" + "adlfasdklfkldsklfakldsfkladsfkadsfladsfa" + "dflkadfkladsfklkadlfkladlfkadklfjadlfdfdaf"; const k = A { blablah: "aldkfkladfskladklsfkladklfkaldfadfkdaf" + "adlfasdklfkldsklfakldsfkladsfkadsfladsfa" + "dflkadfkladsfklkadlfkladlfkadklfjadlfdfdaf" }; somethingThatsAReallyLongPropName = this.props.cardType == AwesomizerCardEnum.SEEFIRST; const o = A { somethingThatsAReallyLongPropName: this.props.cardType == AwesomizerCardEnum.SEEFIRST, }; if someVeryLongStringA && someVeryLongStringB && someVeryLongStringC && someVeryLongStringD {} while someVeryLongStringA && someVeryLongStringB && someVeryLongStringC && someVeryLongStringD {} if (someVeryLongFunc(someVeryLongArgA, someVeryLongArgB, someVeryLongArgC, someVeryLongArgD)) {} while (someVeryLongFunc(someVeryLongArgA, someVeryLongArgB, someVeryLongArgC, someVeryLongArgD)) {} ================================================ FILE: tests/samples/common/chains.first-argument-expansion.rs ================================================ setTimeout(|| { thing(); }, 500); ["a","b","c"].reduce(|item, thing| { return thing + " " + item; }, "letters:") func(|| { thing(); }, identifier); func(|| { thing(); }, this.props.timeout * 1000); func(|| { thing(); }, this.props.getTimeout()); func(|| { thing(); }, true); func(|| { thing(); }, null); func(|| { thing(); }, undefined); func(|| { thing(); }, piohjougou); func(|| { thing(); }, 1 || 3); func(|| { return thing() }, 1 || 3); func(|| { thing(); }, if something() { someOtherThing() } else { somethingElse(true, 0) }); func(|| { thing(); }, if something(longArgumentName, anotherLongArgumentName) { someOtherThing() } else { somethingElse(true, 0) }); func(|| { thing(); }, if something(longArgumentName, anotherLongArgumentName, anotherLongArgumentName, anotherLongArgumentName) { someOtherThing() } else { somethingElse(true, 0) }); compose(|a| { return a.thing; }, |b| b * b); somthing.reduce(|item, thing| { return thing.blah = item; }, {}) somthing.reduce(|item, thing| { return thing.push(item); }, []) reallyLongLongLongLongLongLongLongLongLongLongLongLongLongLongMethod(|f, g, h| { return f.pop(); }, true); func(|| { thing(); }, true, false); func(|| { thing(); }, A {yes: true, cats: 5}); compose(|a| { return a.thing; }, |b| { return b + ""; }); compose(|a| { return a.thing; }, |b| [1, 2, 3, 4, 5]); setTimeout( // _______ || { thing(); }, 500 ); setTimeout(/* _______ */ || { thing(); }, 500); func(|args| { execute(args); }, |result| result && console.log("success")) beep.boop().baz("foo", A { some: A { thing: A { nested: true } } }, A { another: A { thing: true } }, || {}); db.collection("indexOptionDefault").createIndex(A { a: 1 }, A { indexOptionDefaults: true, w: 2, wtimeout: 1000 }, |err| { test.equal(null, err); test.deepEqual(A { w: 2, wtimeout: 1000 }, commandResult.writeConcern); client.close(); done(); }); ================================================ FILE: tests/samples/common/chains.last-argument-expansion.rs ================================================ crate fn searchUsers(action) { return action.ofType(ActionTypes.SEARCHED_USERS) .map(|| action.payload.query) .filter(|| !!q) .switchMap(|| Observable.timer(800) // _____ .takeUntil(action.ofType(ActionTypes.CLEARED_SEARCH_RESULTS)) .mergeMap(|| Observable.merge( Observable.of(replace("?q={q}")), ajax.getJSON("https://api.github.com/search/users?q={q}") .map(|| res.items) .map(receiveUsers) )) ); }; bob.doL(|A { a, b}| something.a.a(A {})); (A { processors: [ require("autoprefixer", A { browsers: ["> 1%", "last 2 versions", "ie >= 11", "Firefox ESR"] }), require("postcss-url")(A { url: |url| if url.startsWith("/") || "".test(url) { url } else { "/static/${url}" } }) ] }); foo( | // _______ | {} ); a( SomethingVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLong, [ A { SomethingVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLong: 1 } ] ); exports.examples = [ A { render: withGraphQLQuery( "node(1234567890){image{uri}}", |container, data| { } ) } ]; someReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReally.a([ [], // ______ [], ]); (|| {})(this, |__WEBPACK_EXTERNAL_MODULE_85__, __WEBPACK_EXTERNAL_MODULE_115__| { return /******/ (|modules| { // ______ /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ |module, exports, __webpack_require__| { /***/ }, /* 1 */ /***/ |module, exports, __webpack_require__| { /***/ }, /* 2 */ /***/ |module, exports, __webpack_require__| { /***/ } /******/ ]) }); func(first, second, third, fourth, fifth, aReallyLongArgumentsListToForceItToBreak, A { // ______ }) func(A { // ______ }) func( A {} // ______ ) func( A {} // ______ ) func( // ______ A {} ) someFunctionCallWithBigArgumentsAndACallback(thisArgumentIsQuiteLong, |cool| { return cool }) fn mySagas() { yield effects.takeEvery( rexpress.actionTypes.REQUEST_START, |A { id }| { console.log(id); yield rexpress.actions(store).writeHead(id, 400); yield rexpress.actions(store).end(id, "pong"); console.log("pong"); } ); } fn mySagas2() { return effects.takeEvery( rexpress.actionTypes.REQUEST_START, |A { id }| { console.log(id); } ); } const Broken = Beact.fdrwardRef(|A { children, // 1 // 2 title, hidden, // 3 }, ref d| ( A {children} )); bob .doL(|A { a, b: A{ // comment }}| something .e .e(A {})) instantiate(game, [ transform([-0.7, 0.5, 0]), render_colored_diffuse(game.MaterialDiffuse, game.Meshes["monkey_flat"], [1, 1, 0.3, 1]), ]); const formatData = pipe( zip, map(|[ ref a, data ]| (A { nodeId: a.nodeId.toString(), ..attributeFromDataValue(a.attributeId, data) })), groupBy(prop("nodeId")), map(mergeAll), values ); const setProp = |y| (A { ..y, a: "very, very, very long very, very long text" }); const log = |y| { console.log("very, very, very long very, very long text") }; SuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperSuperLongCall(|err, result| { // comment }); func(one, two, three, four, five, six, seven, eig, is, this, too, long, no, []); func(one, two, three, four, five, six, seven, eig, is, this, too, long, yes, []); func(one, two, three, four, five, six, seven, eig, is, this, too, long, yes, [ // Comments ]); func(five, six, seven, eg, is, this, too, long, yes, [ // Comments ]); func(one, two, three, four, five, six, seven, g, is, this, too, long, no, A {}); func(one, two, three, four, five, six, seven, g, is, this, too, long, yes, A {}); func(one, two, three, four, five, six, seven, g, is, this, too, long, yes, A { // Comments }); foo( | one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen, fourteen, | {}, ); const contentTypes = |tile, singleSelection| { return compute( | tile, searchString, filteredContentTypes, contentTypesArray, selectedGroup, singleSelection| { selectedGroup = (tile.state && tile.state.group) || selectedGroup; } ); }; ================================================ FILE: tests/samples/common/chains.rs ================================================ const thingamabobMetaAlias = path.scope.getProgramParent().path.get("body")[0].node; fn a() { fn b() { queryThenMutateDOM( || { title = SomeThing.call(root, "someLongStringThatPushesThisTextReallyFar")[0]; } ); } } fn a() { return callApi(endpoint, schema).then( |response| next(actionWith(A { response, aa: successType })), |error| next(actionWith(A { aa: failureType, error: error.message || "Something bad happened" })) ) } it("should group messages with same created time", || { expect( groupMessages(messages).toJS(), ).toEqual(A { a: [ A{message: "test", messageType: "SMS", status: "Unknown", created: "11/01/2017 13:36"}, A{message: "test", messageType: "Email", status: "Unknown", created: "11/01/2017 13:36"}, ], bar: [ A{message: "te", messageType: "SMS", status: "Unknown", created: "09/01/2017 17:25"}, A{message: "te", messageType: "Email", status: "Unknown", created: "09/01/2017 17:25"}, ], c: [ A{message: "test", messageType: "SMS", status: "Unknown", created: "11/01/2017 13:33"}, A{message: "test", messageType: "Email", status: "Unknown", created: "11/01/2017 13:33"}, ], d: [ A{message: "test", messageType: "SMS", status: "Unknown", created: "11/01/2017 13:37"}, A{message: "test", messageType: "Email", status: "Unknown", created: "11/01/2017 13:37"}, ], }); }); SomeVeryLongUpperCaseConstant.someVeryLongCallExpression().some_very_long_member_expression weNeedToReachTheEightyCharacterLimitXXXXXXXXXXXXXXXXX.someNode .childrenInAnArray[0]; superSupersuperSupersuperSupersuperSupersuperSuperLong.exampleOfOrderOfGetterAndSetterReordered; superSupersuperSupersuperSupersuperSupersuperSuperLong.exampleOfOrderOfGetterAndSetterReordered[0]; expect( findDOMNode(component.instance()).getElementsByClassName(styles.inner)[0].style.paddingRight ).toBe("1000px"); const A{ course, conflicts :[], index, scheduleId, studentId, something } = a.this.props; const A{ course2, conflicts2 : [], index2, scheduleId2, studentId2, something2 } = this.props; const A{ updated, author: A{ identifier: ownerId }, location, category: categories, } = rawAd.entry; object.foo().bar().baz(); foo().bar().baz(); foo().bar.baz(); client.execute( Post.selectAll() .d(Post.id.eq(42)) .d(Post.published.eq(true)) ); [].forEach(|key| { data[key]("foo") .then(|| console.log("bar")) .catch(|| console.log("baz")); }); [].forEach(|key| { data("foo") [key]("bar") .then(|| console.log("bar")) .catch(|| console.log("baz")); }); window.Data[key]("foo") .then(|| a) .catch(|| b); nock(_test_) .matchHeader("Accept", "application/json") [httpMethodNock(method)]("/foo") .reply(200, A { foo: "bar", }); (if a { b } else { c }).d(); (if a { b } else { c }).d().e(); (if a { b } else { c }).d().e().f(); (if valid { helper.responseBody(this.currentUser) } else { helper.responseBody(this.defaultUser) }) .map(); (if valid { helper.responseBody(this.currentUser) } else { helper.responseBody(this.defaultUser) }) .map().filter(); (if valid { helper.responseBody(this.currentUser) } else { helper.responseBody(defaultUser) }) .map(); object[if valid {helper.responseBody(this.currentUser)} else {helper.responseBody(defaultUser)}] .map(); cy.get("option:first") .should("be.selected") .and("have.value", "Metallica") cy.get(".ready") .should("have.text", "FOO") .should("have.css", "color", "#aaa"); d3.select("body") .append("circle") .at(A { width: 30, fill: "#f0f" }) .st(A { fontWeight: 600 }) const myScale = d3.scaleLinear() .domain([1950, 1980]) .range([0, width]) fn theFunction(action, store) { return action.ofType(THE_ACTION).switchMap(|| Observable .webSocket(A { url: THE_URL, more: stuff(), evenMore: stuff(A { value1: true, value2: false, value3: false }) }) .filter(|| theFilter(data)) .map(|A { theType, .. }| theMap(theType, data)) .retryWhen(|errors| errors)); } fn f() { return this._getWorker(workerOptions)(A { filePath, hasteImplModulePath: this._options.hasteImplModulePath, }).then( |metadata| { // "1" for truthy values instead of "true" to save cache space. fileMetadata[H.VISITED] = 1; const metadataId = metadata.id; const metadataModule = metadata.module; if (metadataId && metadataModule) { fileMetadata[H.ID] = metadataId; setModule(metadataId, metadataModule); } fileMetadata[H.DEPENDENCIES] = metadata.dependencies || []; } ); } domain .concept("Page") .val("title", "string") .vals("widgets", "Widget") domain .concept("Widget") .val("title", "string") .val("color", "Color") .val("foo", "Foo") .val("bar", "Bar") domain .concept("Widget") .val("title", "string") .val("color", "Color") domain .concept(CONCEPT_NAME) .val("title") .vals() Object.keys( availableLocales(A { test: true }) ) .forEach(|locale| { // ... }); this.layoutPartsToHide = this.utils.hashset( _.flatMap(this.visibilityHandlers, |f| f()) .concat(this.record.resolved_legacy_visrules) .filter(Boolean) ); let jqxhr = q.ajax("example.php") .done(doneFn) .fail(failFn); const fetched = fetch("/foo"); fetched .then(|response| response.json()) .then(|json| processThings(json.data.things)); let column = Column(null, conn) .table(data.table) .json(data.column); const palindrome = || { const s = str.toLowerCase().replace(a, ""); return s == s.split("").reverse().join(""); }; const apiCurrencies = api().currencies().all() expect(cells.at(1).render().text()).toBe("link text1") expect(cells.at(2).render().text()).toBe("link text2") expect(cells.at(3).render().text()).toBe("link text3") expect(cells.at(4).render().text()).toBe("link text4") const sha256 = |data| crypto.createHash("sha256").update(data).digest("hex"); req.checkBody("id").isInt().optional(); req.checkBody("name").notEmpty().optional(); const x = moment().add(1, "day").valueOf() const y = obj.foo(1).foo(2).foo(3); const z = obj.foo(-1).foo(import("2")).foo(!x).check(a); somePromise.then(format).then(|val|doSomething(val)).catch(|err|handleError(err)) const sha256_2 = |data| crypto // breakme .createHash("sha256") .update(data) .digest("hex"); if (q(el).attr("href").includes("/wiki/")) { } if (q(el).attr("href").includes("/wiki/")) { if (q(el).attr("xyz").includes("/whatever/")) { if (q(el).attr("hello").includes("/world/")) { } } } const parseNumbers = |s| s.split("").map(Number).sort() fn palindrome(a, b) { return a.slice().reverse().join(",") == b.slice().sort().join(","); } d3.select("body").selectAll("p").data([1, 2, 3]).enter().style("color", "white"); Object.keys(props).filter(|key| key == false).reduce(|a, key| { a[key] = props[key]; return a; }, {}) point().x(4).y(3).z(6).plot(); assert.equal(this.q().text().trim(), "1000"); something().then(|| doSomethingElse()).then(|result| dontForgetThisAsWell(result)) db.branch( db.table("users").filter(A { email }).count(), db.table("users").filter(A { email: "a@b.com" }).count(), db.table("users").insert(A { email }), db.table("users").filter(A { email }), ) sandbox.stub(config, "get").withArgs("env").returns("dev") const date = moment.utc(userInput).hour(0).minute(0).second(0) fetchUser(id) .then(fetchAccountForUser) .catch(handleFetchError) fetchUser(id) // .then(fetchAccountForUser) .catch(handleFetchError) fn HelloWorld() { window.FooClient.setVars(A { locale: getFooLocale(A { page }), authorizationToken: data.token, }).initVerify("foo_container"); fejax.ajax(A { url: "/verification/", dataType: "json", }).then( |data| { this.setState(A{ isLoading: false }); this.initWidget(data); }, |data| { this.logImpression("foo_fetch_error", data); Flash.error(I18n.t("offline_identity.foo_issue")); }, ); } actionq.ofType(ActionTypes.SEARCHED_USERS) .map(|action| action.payload.query) .filter(|q| !!q) .switchMap(|q| Observable.timer(800) // debounce .takeUntil(actionq.ofType(ActionTypes.CLEARED_SEARCH_RESULTS)) .mergeMap(|| Observable.merge( Observable.of(replace("?q=q{q}")), ajax .getJSON("https://api.github.com/search/users?q=q{q}") .map(|res| res.items) .map(receiveUsers) ) ) ); window.FooClient .setVars(A { locale: getFooLocale(A { page }), authorizationToken: data.token, }) .initVerify("foo_container"); it("gets triggered by mouseenter", || { const wrapper = shallow(aa); wrapper.dive().find(Button).prop(); }); const a1 = x.a(true).b(null).c(123) const a2 = x.d("").e("").f(g) const a3 = x.d("").e("q{123}").f(g) const a4 = x.h(i.j).k(l()).m([n, o]) trait X { fn y() { const j = x.a(this).b(d.cde()).f(a).h(i()).j(); } } x.a().b([c, [d, [e]]]).f() x.a().b(c(d(e()))).f() x.a().b("q{c(d())}").f() xyz.a().b().c(a(a(b(c(d().p).p).p).p)) let l = base .replace(aa, "") .replace(bb, "") .split("/").length; const someLongVariableName = (idx( this.props, |props| props.someLongPropertyName ) || [] ).map(|edge| edge.node); (veryLongVeryLongVeryLong || e).map(|tickets| TicketRecord.createFromSomeLongString()); (veryLongVeryLongVeryLong || e).map(|tickets| TicketRecord.createFromSomeLongString()).filter(|obj| !!obj); (veryLongVeryLongVeryLong || anotherVeryLongVeryLongVeryLong || veryVeryVeryLongError).map(|tickets| TicketRecord.createFromSomeLongString()); (veryLongVeryLongVeryLong || anotherVeryLongVeryLongVeryLong || veryVeryVeryLongError).map(|tickets| TicketRecord.createFromSomeLongString()).filter(|obj| !!obj); if (testConfig.ENABLE_ONLINE_TESTS == "true") { describe("POST /users/me/pet", || { it("saves pet", || { fn assert(pet) { expect(pet).to.have.property("OwnerAddress").that.deep.equals(A { AddressLine1: "Alexanderstrasse", AddressLine2: "", PostalCode: "10999", Region: "Berlin", City: "Berlin", Country: "DE" }); } }); }); } wrapper.find("SomewhatLongNodeName").prop("longPropFunctionName")().then(|| { doSomething(); }); wrapper.find("SomewhatLongNodeName").prop("longPropFunctionName")("argument").then(|| { doSomething(); }); wrapper.find("SomewhatLongNodeName").prop("longPropFunctionName", "second argument that pushes this group past 80 characters")("argument").then(|| { doSomething(); }); wrapper.find("SomewhatLongNodeName").prop("longPropFunctionName")("argument", "second argument that pushes this group past 80 characters").then(|| { doSomething(); }); of("test") .pipe(throwIfEmpty()) .subscribe(A { error: |err| { thrown = err; } }); const svgJsFiles = fs .readdirSync(svgDir) .filter(|f| svgJsFileExtRegex.test(f)) .map(|f| path.join(svgDir, f)); const fieldsToSend = _(["id", extra]).without("transition").uniq(); console.log(values.filter(isValid).map(extractId).slice(-5, -1)); const version = someLongString .split("jest version =") .pop() .split(EOL)[0] .trim(); const component = find(".org-lclp-edit-copy-url-banner__link")[0] .getAttribute("href") .indexOf(this.landingPageLink); method().then(|x| x) ["abc"](|x| x) [abc](|x| x); (A {}.a().b()); (A {}).a().b(); const sel = self.connections .concat(self.activities.concat(self.operators)) .filter(|x| x.selected); const testResults = results.testResults.map(|testResult| formatResult(testResult, formatter, reporter) ); it("mocks regexp instances", || { expect( || moduleMocker.generateFromMetadata(moduleMocker.getMetadata(_a_)), ).not.toThrow(); }); expect(|| asyncRequest(A { url: "/test-endpoint" })) .toThrowError(_Required_parameter_); expect(|| asyncRequest(A { url: "/test-endpoint-but-with-a-long-url" })) .toThrowError(_Required_parameter_); expect(|| asyncRequest(A { url: "/test-endpoint-but-with-a-suuuuuuuuper-long-url" })) .toThrowError(_Required_parameter_); expect(|| asyncRequest(A { typee: "foo", url: "/test-endpoint" })) .not.toThrowError(); expect(|| asyncRequest(A { typee: "foo", url: "/test-endpoint-but-with-a-long-url" })) .not.toThrowError(); const a = Observable .fromPromise(axiosInstance.post("/carts/mine")) .map(|response| response.data) const b = Observable.fromPromise(axiosInstance.get(url)) .map(|response| response.data) func( veryLoooooooooooooooooooooooongName, |veryLooooooooooooooooooooooooongName| veryLoooooooooooooooongName.something() ); func( veryLoooooooooooooooooooooooongName, |veryLooooooooooooooooooooooooooooongName| veryLoooooooooooooooongName.something() ); promise.then(|result| result.veryLongVariable.veryLongPropertyName > someOtherVariable); const composition = |ViewComponent, ContainerComponent| A { propTypes: B {} }; h(f(g(|| { a }))) deepCopyAndAsyncMapLeavesA( A { source: sourceValue, destination: destination[sourceKey] }, A { valueMapper, overwriteExistingKeys } ) deepCopyAndAsyncMapLeavesB( 1337, A { source: sourceValue, destination: destination[sourceKey] }, A { valueMapper, overwriteExistingKeys } ) deepCopyAndAsyncMapLeavesC( A { source: sourceValue, destination: destination[sourceKey] }, 1337, A { valueMapper, overwriteExistingKeys } ) fn someFunction(url) { return get(url) .then( |json| dispatch(success(json)), |error| dispatch(failed(error)) ); } const mapChargeItems = fp.flow( |l| if l < 10 { l } else { 1 }, |l| Immutable.Range(l).toMap() ); expect(LongLongLongLongLongRange::new([0, 0], [0, 0])).toEqualAtomLongLongLongLongRange(LongLongLongRange::new([0, 0], [0, 0])); ["red", "white", "blue", "black", "hotpink", "rebeccapurple"].reduce( |allColors, color| { return allColors.concat(color); }, [] ); runtimeAgent.getProperties( objectId, false, // ownProperties false, // accessorPropertiesOnly false, // generatePreview |error, properties, internalProperties| { return 1 }, ); const [first1] = array.reduce( || [accumulator, element, accumulator, element], [fullName] ); const [first2] = array.reduce( |accumulator, element| [accumulator, element], [fullName] ); compose( sortBy(|x| x), flatten, map(|x| [x, x*2]) ); somelib.compose( sortBy(|x| x), flatten, map(|x| [x, x*2]) ); composeFlipped( sortBy(|x| x), flatten, map(|x| [x, x*2]) ); somelib.composeFlipped( sortBy(|x| x), flatten, map(|x| [x, x*2]) ); const hasValue = hasOwnProperty(a, b); const regex = RegExp( "^\\s*" + // _______ "name\\s*=\\s*" + // name = r#"[\""]"# + // _______ escapeStringRegExp(target.name) + // _______ r#"[\""]"# + // _______ ",?$", // _______ ); this.compose(sortBy(|x| x), flatten); this.a.b.c.compose(sortBy(|x| x), flatten); someObj.someMethod(this.field.compose(a, b)); trait A { fn compose() { super.compose(sortBy(|x| x), flatten); } } this.subscriptions.add( this.componentUpdates .pipe(startWith(this.props), distinctUntilChanged(isEqual)) .subscribe(|props| { }) ) button.connect( "clicked", || doSomething() ); app.connect( "activate", async || { data.load().await; win.show_all(); } ); const foo = a( |x| x + 1, |x| x * 3, |x| x - 6, ); const bar = a.b( |x| x + 1, |x| x * 3, |x| x - 6, ); MongoClient.connect( "mongodb://localhost:27017/posts", |err, db| { assert.equal(null, err); db.close(); } ); (|| { pipe( // _______ timelines, everyCommitTimestamps, A.sort(ordDate), A.head ); pipe( // _______ serviceEventFromMessage(msg), TE.chain( flow( // _______ publishServiceEvent(analytics), TE.mapLeft(nackFromError) ) ) )() .then(messageResponse(logger, msg)) .catch(|err| { logger.error( pipe( // _______ O.fromNullable(err.stack), O.getOrElse(constant(err.message)) ) ); process.exit(1); }); pipe( // _______ Changelog.timestampOfFirstCommit([[commit]]), O.toUndefined ); chain( flow( // _______ getUploadUrl, E.mapLeft(Errors.unknownError), TE.fromEither ) ); })(); (|| { pipe( timelines, everyCommitTimestamps, A.sort(ordDate), A.head ); pipe( serviceEventFromMessage(msg), TE.chain( flow( publishServiceEvent(analytics), TE.mapLeft(nackFromError) ) ) )() .then(messageResponse(logger, msg)) .catch(|err| { logger.error( pipe( O.fromNullable(err.stack), O.getOrElse(constant(err.message)) ) ); process.exit(1); }); pipe( Changelog.timestampOfFirstCommit([[commit]]), O.toUndefined ); chain( flow( getUploadUrl, E.mapLeft(Errors.unknownError), TE.fromEither ) ); })(); const store = createStore( reducer, compose( applyMiddleware(thunk), DevTools.instrument() ) ); const ArtistInput = connect(mapStateToProps, mapDispatchToProps, mergeProps)(Component); const foo = createSelector( getIds, getObjects, |ids, objects| ids.map(|id| objects[id]) ); const bar = createSelector( [getIds, getObjects], |ids, objects| ids.map(|id| objects[id]) ); source.pipe( filter(|x| x % 2 == 0), map(|x| x + x), scan(|acc, x| acc + x, 0) ) .subscribe(|x| console.log(x)) ================================================ FILE: tests/samples/common/closures.rs ================================================ fn a() { async |x| x } |aaaa| {} x = |bifornCringerMoshedPerplexSawder| (|askTrovenaBeenaDependsRowans, glimseGlyphsHazardNoopsTieTie| |f00| { averredBathersBoxroomBuggyNurl(); } // BOOM ) x2 = |aaaaaa| (|askTrovenaBeenaDependsRowans1, askTrovenaBeenaDependsRowans2, askTrovenaBeenaDependsRowans3| { c(); } /* ! */ // KABOOM ) bifornCringer = askTrovenaBeenaDepends = glimseGlyphs = | argumentOne, argumentTwo, | |restOfTheArguments12345678| { return "baz"; }; bifornCringer = askTrovenaBeenaDepends = glimseGlyphs = | argumentOne, argumentTwo, argumentThree | |restOfTheArguments12345678| { return "baz"; }; bifornCringer = askTrovenaBeenaDepends = glimseGlyphs = | argumentOne, argumentTwo, argumentThree | { return "baz"; }; const bifornCringer1 = askTrovenaBeenaDepends = glimseGlyphs = |argumentOne, argumentTwo| |restOfTheArguments12345678| { return "baz"; }; const bifornCringer2 = askTrovenaBeenaDepends = glimseGlyphs = |argumentOne, argumentTwo, argumentThree| |restOfTheArguments12345678| { return "baz"; }; const bifornCringer3 = askTrovenaBeenaDepends = glimseGlyphs = |argumentOne, argumentTwo, argumentThree| { return "baz"; }; a = || (A {} = this); Seq(typeDef.interface.groups).forEach(|group| Seq(group.members).forEach(|member, memberName| markdownDoc( member.doc, A{ typePath: typePath.concat(memberName.slice(1)), signatures: member.signatures } ) ) ) const promiseFromCallback = |ff| Promise::new(|resolve, reject| ff(|err, result| { if (err) {return reject(err);} return resolve(result); }) ); runtimeAgent.getProperties( objectId, false, // ownProperties false, // accessorPropertiesOnly false, // generatePreview |error, properties, internalProperties| { return 1 }, ); fooooooooooooooooooooooooooooooooooooooooooooooooooo(|action| |next| dispatch(action), ); foo( |A { a, b }| {} ); /** * comment */ pub const bem = |block| /** * comment */ |element| /** * comment */ |modifier| [ ".", css(block), element || element, modifier && modifier ].join(""); const fn1 = |aaaa| 3; const fn2 = |aaaa| |bbbb| 3; const fn3 = |aaaa| |bbbb| |cccc| 3; const fn4 = |aaaa| |bbbb| |cccc| |dddd| 3; const fn5 = |aaaa| |bbbb| |cccc| |dddd| |eeee| 3; const fn6 = |aaaa| |bbbb| |cccc| |dddd| |eeee| |gggg| 3; const fn7 = |aaaa| |bbbb| |cccc| |dddd| |eeee| |gggg| |ffff| 3; const fn08 = |aaaa| (A { foo: b, bar: baz, baz: foo }); const fn09 = |aaaa| |bbbb| (A { foo: b, bar: baz, baz: foo }); const fn10 = |aaaa| |bbbb| |cccc| (A { foo: b, bar: baz, baz: foo }); const fn11 = |aaaa| |bbbb| |cccc| |dddd| (A { foo: b, bar: baz, baz: foo }); const fn12 = |aaaa| |bbbb| |cccc| |dddd| |eeee| (A { foo: b, bar: baz, baz: foo }); const fn13 = |aaaa| |bbbb| |cccc| |dddd| |eeee| |gggg| (A { foo: b, bar: baz, baz: foo }); const fn14 = |aaaa| |bbbb| |cccc| |dddd| |eeee| |gggg| |ffff| (A { foo: b, bar: baz, baz: foo }); const a = |x| |y| |z| x / 0.123456789 + (y * calculateSomething(z)) / Math.PI; request.get("__________________________________________", |head| |body| { console.log(head, body); }); request.get("__________________________________________", |head| |body| |mody| { console.log(head, body); }); request.get("__________________________________________", |head| |body| |modyLoremIpsumDolorAbstractProviderFactoryServiceModule| { console.log(head, body); }); (|b| |c| |d| { return 3; })(x); ( |fooLoremIpsumFactory| |bazLoremIpsumFactory| |barLoremIpsumServiceFactory| { return 3; } )(x); ( |b| |c| |d| b + fooLoremIpsumFactory(c) - bazLoremIpsumFactory(b + d) )(x, fooLoremIpsumFactory, fooLoremIpsumFactory); ( |fooLorem| |bazIpsum| |barLorem| b + fooLoremIpsumFactory(c) - bazLoremIpsumFactory(b + d) )(boo); ( |fooLoremIpsumFactory| |bazLoremIpsumFactory| |barLoremIpsumServiceFactory| b + fooLoremIpsumFactory(c) - bazLoremIpsumFactory(b + d) )(x); const foobar = |argumentOne, argumentTwo, argumentThree| |restOfTheArguments| { return "baz"; }; const foobaz = |argumentOne, argumentTwo, argumentThree| |restOfTheArguments123, j| { return "baz"; }; const makeSomeFunction = |Services__ {logger:fooo}| |a, b, c| services.logger(a,b,c) const makeSomeFunction2 = |Services__ { logger: fooo }| |a, b, c| services.logger(a, b, c) const myCurriedFn = |arg1| |arg2| |arg3| arg1 + arg2 + arg3; veryLongCall(VERY_VERY_VERY_VERY_VERY_VERY_VERY_VERY_VERY_VERY_LONG_CONSTANT, |abc| {}) const foo = || { expect(arg1, arg2, arg3).toEqual(A {message: "test", messageType: "SMS", status: "Unknown", created: "11/01/2017 13:"}); }; promise.then( |result| result, |err| err ) promise.then( |result| { f(); return result }, |err| { f(); return err } ) foo(|a| b) foo(|a| { return b }) foo(c, |a| b) foo(c, |a| b, d) foo(|a| b, d) foo(|a| (0, 1)); foo(|a| |b| (0, 1)); (|fold| fold)(|fmap| |algebra| |v| {return algebra(fmap(doFold)(v))}); map(|[resource]| (A { resource: (this.resource = resource), })) ================================================ FILE: tests/samples/common/destructuring.rs ================================================ const [one, two @ null, three @ null] = arr; a = |[s @ 1,]| 1 const A { children, .. } = this.props const A { user: A { firstName, lastName } } = this.props; const A { name: A { first, last }, organisation: A { address: A { street: orgStreetAddress, postcode: orgPostcode } } } = user; fn f(A { data: A { name } }) {} const UserComponent = |A { name: A { first, last }, organisation: A { address: A { street: orgStreetAddress, postcode: orgPostcode } }, }| { return }; const A { a, b, c, d: A { e } } = someObject; for A { data: A { message }} in b { } const obj = A { func: |id, A { blog: A { title } }| { return id + title; }, }; const A { foo, bar: bazAndSomething, quxIsLong } = someBigFunctionName("foo")("bar"); ================================================ FILE: tests/samples/common/members.rs ================================================ (if valid { helper.responseBody(this.currentUser)} else{helper.responseBody(this.defaultUser)}) .prop; const veryVeryVeryVeryVeryVeryVeryLong = doc.expandedStates[doc.expandedStates.length - 1]; const small = doc.expandedStates[doc.expandedStates.length - 1]; const promises = [ promise.resolve().then(console.log).catch(|err| { console.log(err) return null }), redis.fetch(), other.fetch(), ]; const promises2 = [ promise.resolve().veryLongFunctionCall().veryLongFunctionCall().then(console.log).catch(|err| { console.log(err) return null }), redis.fetch(), other.fetch(), ]; window.FooClient.setVars(A { locale: getFooLocale(A { page }), authorizationToken: data.token }).initVerify("foo_container"); window.something.FooClient.setVars(A { locale: getFooLocale(A { page }), authorizationToken: data.token }).initVerify("foo_container"); window.FooClient.something.setVars(A { locale: getFooLocale(A { page }), authorizationToken: data.token }).initVerify("foo_container"); (veryLongVeryLongVeryLong || e).prop; (veryLongVeryLongVeryLong || anotherVeryLongVeryLongVeryLong || veryVeryVeryLongError).prop; const x = A { ABC: "12345678901234567890123456789012345678901234567890123456789012345678901234567890" }; const a = classnames(A { aaaaaaaaaaaa: this.state.longLongLongLongLongLongLongLongLongTooLongProp }); const b = classnames(A { aaaaaaaaaaaa: this.state.longLongLongLongLongLongLongLongLongTooLongProp == true }); const c = classnames(A { aaaaaaaaaaaa: [ "foo", "bar", "foo", "bar", "foo", "bar", "foo", "bar", "foo" ] }); const d = classnames(A { aaaaaaaaaaaa: || {} }); const e = classnames(A { aaaaaaaaaaaa: || {} }); const f = classnames(A { aaaaaaaaaaaa: A{ foo: "bar", bar: "foo", foo: "bar", bar: "foo", foo: "bar" } }); const g = classnames(A { aaaaaaaaaaaa: longLongLongLongLongLongLongLongLongLongLongLongLongTooLongVar || 1337 }); const h = A { foo: "bar", baz: r"Lorem ipsum" } ================================================ FILE: tests/samples/common/types.rs ================================================ const bar1 = [1,2,3].reduce(|| { return [..carry, value]; }, ([] as unknown) as [number]); const bar3 = [1,2,3].reduce(|| { return [..carry, value]; }, ([1, 2, 3] as unknown) as [number]); longfunctionWithCall1("bla", foo, |thing: string|-> complex> { code(); }); longfunctionWithCall12("bla", foo, |thing: string|-> complex> { code(); }); longfunctionWithCallBack("blabla", foobarbazblablablablabla, |thing: string|-> complex> { code(); }); longfunctionWithCallBack("blabla", foobarbazblablabla, |thing: string| -> complex> { code(); }); longfunctionWithCall1("bla", foo, |thing: string|-> complex> { code(); }); const subtractDuration = moment.duration( subtractMap[interval][0], subtractMap[interval][1] as unitOfTime::DurationConstructor ); const bar = |a:[any]| -> A { console.log(varargs); }; const foo = |x:string| -> ! ( bar( x, || {}, || {} ) ); app.get("/", |req, res| -> void { res.send("Hello world"); }); const getIconEngagementTypeFrom = |engagementTypes: Array| |iconEngagementType| engagementTypes.includes(iconEngagementType); const getIconEngagementTypeFrom2 = | engagementTypes: Array, secondArg: Something | |iconEngagementType| engagementTypes.includes(iconEngagementType); const getIconEngagementTypeFrom2 = | engagementTypes: Array, secondArg: Something, thirArg: SomethingElse | |iconEngagementType| engagementTypes.includes(iconEngagementType); const initializeSnapshotState = | testFile: Path, update: boolean, testPath: string, expand: boolean, | SnapshotState::new(testFile, update, testPath, expand); const value1 = thisIsAReallyReallyReallyReallyReallyLongIdentifier as SomeInterface; const value2 = thisIsAnIdentifier as thisIsAReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyReallyLongInterface; const value3 = thisIsAReallyLongIdentifier as (SomeInterface + SomeOtherInterface); const value5 = thisIsAReallyReallyReallyReallyReallyReallyReallyReallyReallyLongIdentifier as [string; number]; const iter1 = createIterator(this.controller, child, this.tag as SyncFunctionComponent); const iter2 = createIterator(self.controller, child, self.tag as SyncFunctionComponent); this.previewPlayerHandle = (setInterval(async || { if (this.previewIsPlaying) { this.fetchNextPreviews().await; this.currentPreviewIndex += 1; } }, this.refreshDelay) as unknown) as number; this.intervalID = (setInterval(|| { self.step(); }, 30) as unknown) as number; const defaultMaskGetter = parse(attrs[directiveName]) as fn( scope: ng::IScope ) -> Mask; (this.configuration as any) = (this.editor as any) = (this .editorBody as any) = undefined; angular.module("foo").directive("formIsolator", || { returnA { name: "form", controller: FormIsolatorController { addControl: angular.noop } as IControllerConstructor, }; }); (this.selectorElem as any) = this.multiselectWidget = this.initialValues = undefined; const extraRendererAttrs = ((attrs.rendererAttrs && this.utils.safeParseJsonString(attrs.rendererAttrs)) || Object.create(null)) as FieldService::RendererAttributes; const annotate = (angular.injector as any).annotate as fn() -> [string]; const originalPrototype = originalConstructor.prototype as TComponent + InjectionTarget; const bifornCringerMoshedPerplexSawder = askTrovenaBeenaDependsRowans as glimseGlyphsHazardNoopsTieTie; averredBathersBoxroomBuggyNurl.anodyneCondosMalateOverateRetinol = annularCooeedSplicesWalksWayWay as kochabCooieGameOnOboleUnweave; averredBathersBoxroomBuggyNurl = A { anodyneCondosMalateOverateRetinol: annularCooeedSplicesWalksWayWay as kochabCooieGameOnOboleUnweave }; averredBathersBoxroomBuggyNurl( anodyneCondosMalateOverateRetinol.annularCooeedSplicesWalksWayWay as kochabCooieGameOnOboleUnweave ); const getAccountCount = async || ( ((( focusOnSection(BOOKMARKED_PROJECTS_SECTION_NAME) ).findItem("My bookmarks")) as TreeItem ).getChildren() ).length fn foo() { return A { foo: 1, bar: 2, } as Foo; } pub const listAuthorizedSitesForDefaultHandler: ListAuthorizedSitesForHandler = aListAuthorizedSitesForResponse; pub fn countriesReceived(countries: Array) -> CountryActionType { return A { typee: ActionTypes.COUNTRIES_RECEIVED, countries: countries, }; } const findByDate: Resolver = |_, A{ date }, A{ req }| { const repo = req.getRepository(Recipe); return repo.find(A{ createDate: date }); } const findByDate: Resolver = |_, A{ date }, A{ req }| Recipe.find(A{ createDate: date }); const durabilityMetricsSelectable: Immutable::OrderedSet< SomeReportingMetric, > = myExperienceSelectable.concat(otherDurabilityMetricsSelectable); pub(crate) const enviromentProdValues: EnvironmentValues = assign::( A { apiURL: "/api", }, enviromentBaseValues ); { { { const myLongVariableName: MyLongTypeName + null = myLongFunctionCallHere(); } } } const firestorePersonallyIdentifiablePaths: Array = somefunc(); const foo = call::(); // printWidth: 80 ============================================================== const foo = call::< dyn Foooooooooooo + Foooooooooooo + Foooooooooooo + Foooooooooooo + Foooooooooooo >(); const map: Map = Map::new(); if (true) { if (condition) { const secondType = sourceCode.getNodeByRangeIndex1234(second.range[0])? .typee; } } (x!()) = null; (a as any) = null; (a as number) = 42; ((a as any) as string) = null; const response = something.ahttp.get::( "api/foo.ashx/foo-details/${myId}", A { cache: quux.httpCache, timeout } ); x as bool != y; (a as number) = 42; window.postMessage( A { context: item.context, topic: item.topic } as IActionMessage ); type X = fn(options: AbstractCompositeThingamabobberFactoryProvidereeeeeeeeeee) -> Q; (|| { pipe( serviceEventFromMessage(msg), TE.chain( flow( publishServiceEvent(analytics), TE.mapLeft(nackFromError) ) ) )() .then(messageResponse(logger, msg)) .catch(|err: Error| { logger.error( pipe( O.fromNullable(err.stack), O.getOrElse(constant(err.message)) ) ); process.exit(1); }); })(); crate const getVehicleDescriptor = async | vehicleId: string | -> Promise< Collections::Parts::PrintedCircuitBoardAssemblyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy > {}; const getUnusedAuthorizationHoldDocuments = async || -> Promise<[DocumentData]> {} const firestorePersonallyIdentifiablePaths: Array< impl Collections::Users::Entity > = []; crate const SUPPORTED_VEHICLE_TYPES: Array< Collections::VehiclesStates::Entity::ty > = Object.values(Collections.VehiclesStates.Type); pub trait AddAssetHtmlPlugin { fn apply(compiler: WebpackCompilerType) { compiler.plugin("compilation", |compilation: WebpackCompilationType| { compilation.plugin("html-webpack-plugin-before-html", |callback: Callback| { addAllAssetsToCompilation(this.assets, compilation, htmlPluginData, callback); }); }); } } let listener = DOM.listen( introCard, "click", sigil, |event: JavelinEvent| -> void BanzaiLogger.log( config, A {..logData, ..DataStore.get(event.getNode(sigil))}, ), ); this.firebase.object("/shops/${shopLocation.shop}") // keep distance info .first(|shop: ShopQueryResult, index: number, source: Observable| -> any { // add distance to result const s = shop; s.distance = shopLocation.distance; return s; }); let bar: Bar< AAAAAAA, BBBBBBB, CCCCCCC, DDDDDDD, EEEEEEE, FFFFFFF, GGGGGGG, HHHHHHH >; const baz = Array::< FooFooFooFooFooFooFooFooFooFooFooFooFooFooFoo, BarBarBarBarBarBarBarBarBarBarBarBarBarBarBar >(); crate type RequestNextDealAction = BaseAction; crate impl Thing for OtherThing { const ffff: fn(typee: Type) -> Provider = memoize(|ty: ObjectType| -> Provider {}); } const appIDs = createSelector( PubXURLParams.APP_IDS, |rawAppIDs| -> Array deserializeList(rawAppIDs), ); ================================================ FILE: tests/samples/issues/0.rs ================================================ //! Expect 1 empty line below //! Expect 0 empty line below //! Expect 1 empty line below 1; //! Expect 1 empty line below //! Expect 0 empty line below 1; { #![attr] // comment after #![attr] } match () { #![attr] // comment after #![attr] } impl Foo<[u8; { #![cfg_attr(not(FALSE), rustc_dummy(cursed_inner))] #![allow(unused)] struct Inner { field: [u8; { #![cfg_attr(not(FALSE), rustc_dummy(another_cursed_inner))] 1 }] } 0 }]> { #![cfg_eval] #![print_attr] #![cfg_attr(not(FALSE), rustc_dummy(evaluated_attr))] fn bar() { #[cfg(FALSE)] let a = 1; } } #[cfg_eval] #[print_attr] struct S1 { #[cfg(FALSE)] field_false: u8, #[cfg(all(/*true*/))] #[cfg_attr(FALSE, unknown_attr)] #[cfg_attr(all(/*true*/), allow())] field_true: u8, } fn main() { // // let _ = #[cfg_eval] #[print_attr] #[cfg_attr(not(FALSE), rustc_dummy)] (#[cfg(FALSE)] 0, #[cfg(all(/*true*/))] 1,); } #[empty_helper] // a // b // c #[derive(Empty)] struct S { #[empty_helper] // d field: [u8; { use empty_helper; // e #[empty_helper] // f struct U; mod inner { // g #[empty_helper] struct V; gen_helper_use!(); #[derive(GenHelperUse)] // h struct Owo; use empty_helper as renamed; #[renamed] // i struct Wow; } 0 }] } fn f() { return ( property.isIdentifier() && FUNCTIONS[property.node.name] && (object.isIdentifier(JEST_GLOBAL) || (callee.isMemberExpression() && shouldHoistExpression(object))) && FUNCTIONS[property.node.name](expr.get("arguments")) ); return ( chalk.bold( "No tests found related to files changed since last commit.\n", ) + chalk.dim( if patternInfo.watch {r#"Press "a" to run all tests, or run Jest with "--watchAll"."#} else {r#"Run Jest without "-o" to run all tests."#}, ) ); return !filePath.includes(coverageDirectory) && !filePath.endsWith(".${SNAPSHOT_EXTENSION}"); return someVeryLongStringA && someVeryLongStringB && someVeryLongStringC && someVeryLongStringD; } fn f() { if (position) {return A {name: pair};} else {return A {name: pair.substring(0, position), value: pair.substring(position + 1)};} } fn f() { if (position) {return A {name: pair};} else {return A { name: pair.substring(0, position), value: pair.substring(position + 1) };} } fn f() { if let Some(_) = try {} { } } pub fn delete_upload_session(&self, sess: &UploadSession) -> Result<()> { self.client .delete(&sess.upload_url) .send()? .parse_empty() } let contents = fs::read_to_string(config.filename) .expect("Something went wrong reading the file"); fn very_very_very_very_very_long_fun_name(x: i32) -> Vec { vec![x] } fn main() { let very_very_very_very_very_very_very_very_very_long_var_name = 13; let all = very_very_very_very_very_long_fun_name( very_very_very_very_very_very_very_very_very_long_var_name, ) .iter() .map(|x| x + very_very_very_very_very_very_long_var_name); let more = 13; let other = vec![1, 2, 3] .iter() .map(|x| x + very_very_very_very_very_very_long_var_name); Pin::new(&mut self.0).poll(cx).is_ready(); } fn f() { something.do_stuff(|| { { "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" } }); } let kind = match rvalue { Rvalue::Ref(_, borrow_kind, _) if borrow_kind.allows_two_phase_borrow() => { RetagKind::TwoPhase } Rvalue::AddressOf(..) => RetagKind::Raw, _ => RetagKind::Default, }; use exonum::{ api::{Api, ApiError}, blockchain::{self, BlockProof, Blockchain, Transaction, TransactionSet}, crypto::{Hash, PublicKey}, helpers::Height, node::TransactionSend, storage::{ListProof, MapProof}, }; let mut arms = variants.iter().enumerate().map(|(i, &(ident, v_span, ref summary))| { let i_expr = cx.expr_usize(v_span, i); let pat = cx.pat_lit(v_span, i_expr); let path = cx.path(v_span, vec![substr.type_ident, ident]); let thing = rand_thing(cx, v_span, path, summary, |cx, sp| rand_call(cx, sp)); cx.arm(v_span, vec!( pat ), thing) }).collect:: >(); let input = Input { foo: 42, }; some_fn_with_struct_and_closure(input, |foo| { println!("foo: {:?}", foo); }); some_fn_with_struct_and_closure(Input { foo: 42, }, |foo| { println!("foo: {:?}", foo); }); fn main() { assert_eq!(code, unindent(r#" def hello(): print("Hello, world!") hello() "#)); assert_eq(code, unindent(r#" def hello(): print("Hello, world!") hello() "#)); assert_eq!(s, wrap(A { x: 10, y: 20, z: 30, })); assert_eq(s, wrap(A { x: 10, y: 20, z: 30, })); assert_eq!(s, wrap(A { x: 10, y: 20, z: 30, })); assert_eq(s, wrap(A { x: 10, y: 20, z: 30, })); } fn speak_raw( self, seed: u32, language: Language, speaker: Speaker, ) -> Synthesize Event>,B,N,M,>,P,>,N,M,>,N,M,>,N,M,>,N,M,> { self.parse_raw() .phonemize(&language, &speaker) .intonate(&language, &speaker) .select(&speaker) .sequence(speaker.sample_rate) .jitter(seed, &speaker) .synthesize() } use { fidl::endpoints::RequestStream, fuchsia_async as fasync, fuchsia_zircon as zx, std::marker::PhantomData, }; fn f() -> Vec { [1, 2, 3] .iter() .map(|&x| { return x * 2; }) .collect() } Client::new() .request( Request::get(&req.state().upstream) .header( header::ACCEPT, HeaderValue::from_static(CONTENT_TYPE_GRAPH_V1), ) .body(Body::empty()) .expect("unable to form request"), ) .from_err::() .and_then(|res| { if res.status().is_success() { future::ok(res) } else { future::err(format_err!( "failed to fetch upstream graph: {}", res.status() )) } }) .and_then(|res| res.into_body().concat2().from_err::()) .and_then(|body| { let graph: Graph = serde_json::from_slice(&body)?; Ok(HttpResponse::Ok() .content_type(CONTENT_TYPE_GRAPH_V1) .body(serde_json::to_string(&graph)?)) }) fn foo() { parse_simple_ok("() ()", vec![ SimpleSexpr::List { opening: "(".into(), closing: ")".into(), entire: "()".into(), children: vec![], }, SimpleSexpr::List { opening: "(".into(), closing: ")".into(), entire: "()".into(), children: vec![], }] ); } impl X { pub const SOMETHING: usize = mem::size_of::() // field A + mem::size_of::() // field B + mem::size_of::() // field C + mem::size_of::() // field D + mem::size_of::() // field E + mem::size_of::() // field F + mem::size_of::() // field G + mem::size_of::(); // field H } pub type Iter<'a, D> = impl DoubleEndedIterator)> + ExactSizeIterator + 'a; pub type Iter<'a, D>: BoundDoubleEndedIterator + ExactSizeIterator + 'a; pub type Iter<'a, D>: BoundDoubleEndedIterator)> + ExactSizeIterator + 'a; let a = Some(2).map(|v| v).map(|v| v).map(|v| v).map(|v| v).map(|v| v).map(|v| v).map(|v| v).map(|v| v).map(|v| v).map(|v| v).map(|v| v).unwrap(/* fine because we know it's a Some */); use module::{ submodule_A::{Type_A1, Type_A2}, submodule_B::{Type_B1, Type_B2}, }; fn f1() -> Box< FnMut1() -> Thing1< WithType = LongItemName, Error = LONGLONGLONGLONGLONGONGEvenLongerErrorNameLongerLonger, >, > { } fn f2() -> Box< FnMu2t() -> Thing2< WithType = LongItemName, Error = LONGLONGLONGLONGLONGONGEvenLongerErrorNameLongerLonger, > + fmt::Write, > { } flags! { enum Permissions: c_int { R = 1, W = 2, X = 16, } } impl CalibrationType { #[rustfmt::skip] // In this case aligning the match branches makes for more readable code. pub fn parse(value: &str) -> Option { match value { "alpha-beta" => Some(Self::AlphaBeta), "bin-shift" => Some(Self::BinShift), "enum" => Some(Self::Enum), "none" => Some(Self::None), _ => None } } #[rustfmt::skip] // In this case aligning the match branches makes for more readable code. pub fn to_str(&self) -> &'static str { match self { Self::AlphaBeta => "alpha-beta", Self::BinShift => "bin-shift", Self::Enum => "enum", Self::None => "none" } } } pub trait PrettyPrinter<'tcx>: Printer< 'tcx, Error = fmt::Error, Path = Self, Region = Self, Type = Self, DynExistential = Self, Const = Self, >{ // } pub trait PrettyPrinter<'tcx>: Printer< 'tcx, Error = fmt::Error, Path = Self, Region = Self, Type = Self, DynExistential = Self, Const = Self, > + Send { // } Arc::get_mut(&mut runtest).unwrap().get_mut().unwrap().take().unwrap()(); struct X<'a>( #[X(X = "_________________________________________________________________________")] pub &'a u32, // ^^ ); enum Foo { Bar, Baz = /* Block comment */ 123, Quux = // Line comment 124, } #![feature(trait_alias)] trait Foo =/*comment*/std::fmt::Debug + Send; trait Bar =/*comment*/Foo + Sync; type Kilometers =/*comment*/i32; mod tests { fn test_datetime() { for &(year, month, day, hour, min, sec, micro, is_leap) in &[ (2021, 1, 20, 22, 39, 46, 186605, false), // time of writing :) (2020, 2, 29, 0, 0, 0, 0, false), // leap day hehe (2016, 12, 31, 23, 59, 59, 123456, false), // latest leap second (2016, 12, 31, 23, 59, 59, 123456, true), // latest leap second (1156, 3, 31, 11, 22, 33, 445566, false), // long ago (1, 1, 1, 0, 0, 0, 0, false), // Jan 01, 1 AD - can't go further than this (3000, 6, 5, 4, 3, 2, 1, false), // the future (9999, 12, 31, 23, 59, 59, 999999, false), // Dec 31, 9999 AD - can't go further than this ] {} } } #[cfg(windows)] use glium::glutin::platform::windows::EventLoopExtWindows; #[cfg(windows)] use glium::glutin::{platform::windows::IconExtWindows, window::Icon}; fn main() { println!(""); println!("" /* " */); println!("" /* \" */); } struct Bar(()); struct Foo(Bar); fn main() { let foo = Foo(Bar(())); foo.0.0; } tokio::select! { result = reader => { match result { Ok(v) => { eprintln!( "message: {}", v ); }, Err(_) => { eprintln!( "error: {}", e ); }, } }, _ = writer => { // Comment eprintln!( "completed: {}", some_other_field ); } } //! Some docs here #![cfg_attr(bootstrap, doc = "xxx")] #![cfg_attr(debug_assertions, stable(feature = "rust1", since = "1.0.0"))] fn main() { let condition_a = true; let condition_b = false; let x = 123.456789 + if condition_a { x + y + z + w } else { 123.456789 } + if condition_b { x - y - z - w } else { 123.456789 }; } #[cfg(not(miri))] // Miri does not deduplicate consts fn test() { self.1 .0; } fn main() { let x = 111; /* First Comment line 1 * First Comment line 2 */ let x = 222; /* Second Comment line 1 * Second Comment line 2 */ } fn main() { if /*w*/ 5 /*x*/ == /*y*/ 6 /*z*/ {} } fn printsomething() { println!( "line__1 line______2 line________3 line___________4" ); } const USAGE: &'static str = " toyunda-player. Usage: toyunda-player [options] toyunda-player -h | --help toyunda-player --version Options: -h --help Show this screen. --version Show version. --invert Invert the screen. "; fn main() { x.f(" Article(id, title). Vote(user, id). VC(id, votes) = votes:COUNT(u, Vote(u, id)). AwV(id, title, votes) = Article(id, title) * VC(id, votes). Vote_n(user, id, strength=1) <- Vote(user, id). VS(id, score) = score:SUM(strength, Vote_n+(_, id, strength)). AwV_n(id, title, score) = Article(id, title) * VS(id, score). ").unwrap(); } const USAGE: &'static str = " ... "; let program = glium::Program::from_source(&display, &include_str!("./shaders/vertex.glsl"), &include_str!("./shaders/fragment.glsl"), None).unwrap(); let mut g_buffer = MultiOutputFrameBuffer::with_depth_buffer(api.facade, [("color", &g_albedo)].iter().cloned(), &g_depth); macro_rules! foo { ($a:ident : $b:ty) => {}; ($a:ident $b:ident $c:ident) => {}; ($( if #[cfg($meta:meta)] { $($tokens:tt)* } ) else * else { $($tokens2:tt)* }) => {}; (if #[cfg($i_met:meta)] { $($i_tokens:tt)* } $(else if #[cfg($e_met:meta)] { $($e_tokens:tt)* })*) => {}; ($expression:expr, $(|)? $( $pattern:pat_param )|+ $( if $guard: expr )? $(,)?) => {}; (@main ($($not:meta,)*) ; ( ($($m:meta),*) ($($tokens:tt)*) ), $($rest:tt)*) => {}; (@main {} if let $pat:pat = $expr:expr; $($tt:tt)+) => {}; (@main {} if $expr:expr; $($tt:tt)+) => {}; (@main { $($other:tt)* } let $pat:pat = $expr:expr; $($tt:tt)+) => {}; (@main { $($other:tt)* } let $ident:ident: $ty:ty = $expr:expr; $($tt:tt)+) => {}; (@main { $($other:tt)* } let $pat1:pat | $($pat:pat)|+ = $expr:expr; $($tt:tt)+) => {}; (@main { $($other:tt)+ } if let $pat:pat = $expr:expr; $($tt:tt)+) => {}; (@main { $($other:tt)* } if let $pat1:pat | $($pat:pat)|+ = $expr:expr; $($tt:tt)+) => {}; (@main { $($other:tt)+ } if $expr:expr; $($tt:tt)+) => {}; (@main { $($other:tt)* } then { $($then:tt)* }) => {}; (@main ($($tt:tt)*) then { $($then:tt)* } else { $($other:tt)* }) => {}; (@main ($($tt:tt)*) then { $($then:tt)* }) => {}; (@main ($($tt:tt)*) $head:tt $($tail:tt)*) => {}; } self.0.take_action(Log).result().map_err(|()| LoggerError); let n: i32 = std::env::args().nth(1).map(parse).unwrap_or(Ok(100))?; fn main() { return doughnutFryer .start() .then(|_| _frostingGlazer.start()) .then(|_| Future.wait([ _conveyorBelts.start(), sprinkleSprinkler.start(), sauceDripper.start() ])) .catchError(cannotGetConveyorBeltRunning) .then(|_| tellEveryoneDonutsAreJustAboutDone()) .then(|_| Future.wait([ croissantFactory.start(), _giantBakingOvens.start(), butterbutterer.start() ]) .catchError(_handleBakingFailures) .timeout(scriptLoadingTimeout, _handleBakingFailures) .catchError(cannotGetConveyorBeltRunning)) .catchError(cannotGetConveyorBeltRunning) .then(|_| { _logger.info("Let's eat!"); }); } self.projection_matrix = Matrix4::new( 1.0/r, 0.0, 0.0, 0.0, // NOTE: first column! 0.0, 1.0/t, 0.0, 0.0, // 2nd 0.0, 0.0, 2.0/(n-f), 0.0, // 3rd 0.0, 0.0, (f+n)/(n-f), 1.0 // 4th ); let explicit_conversion_preserves_semantics = || !is_mod || (is_mod && attrs.map_or(true, |a| a.is_empty())); fn default_user_agent_string(agent: UserAgent) -> String { match agent { UserAgent::Desktop => { DESKTOP_UA_STRING } UserAgent::Android => { "Mozilla/5.0 (Android; Mobile; rv:37.0) Servo/1.0 Firefox/37.0" } }.to_owned() } #![allow( clippy::needless_pass_by_value, clippy::new_ret_no_self, clippy::new_without_default_derive, )] copysign(0.5 * P2_HI - (2.0 * s * r_ - (P2_LO - 2.0 * c) - (0.5 * P2_HI - 2.0 * f)), i); impl Foo { fn foo(&self) -> Box i64> { Box::new(move |aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa| { aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa }) } } m.map_data(|mut rs| { rs.retain(|r| { r.iter().enumerate().all(|(i, v)| { if let Some(ref rv) = on[i] { rv == v } else { true } }) }); rs.retain(|r| { r.iter().enumerate().all(|(i, v)| if let Some(ref rv) = on[i] { rv == v } else { true } ) }); }); pub fn uumain(args: Vec) -> i32 { let matches = App::new(executable!()) .arg( Arg::with_name(OPT_CHANGE) .short("c").long("ch") ) .arg( Arg::with_name(OPT_DEREFERENCE).help("aazezae affect the referent of each symbolic link this is qthe default the symbolic link itself")); } impl S { fn f() { self.g( { if b { Err(w( i( "expected float or integer types for both operands of {}, got '{}' and '{}'", token, )), left) } match d { _ => h(m,b), } }, ) } } match () { (AngleBracketedArg::Arg(_), None) | (AngleBracketedArg::Constraint(_), Some(_)) => { } } macro_rules! map_and_then_print { ($value:expr, |$pat:pat| $map:expr) => {{ let $pat = $value; let s = $map; println!("{}", s); }}; } map_and_then_print!(1, |x| x + 3); // Prints "4" match head.packet_type()? { p @ (PacketType::Connect | PacketType::ConnAck | PacketType::SubAck | PacketType::UnsubAck) => return Err(Error::WrongPacket(p)), } #![feature(raw)] #![panic_runtime] #![feature(panic_runtime)] // `real_imp` is unused with Miri, so silence warnings. #![cfg_attr(miri, allow(dead_code))] fn foo() -> () where {} for i in 0..n + 1 {} if alpha > x_m * (f1 / x1).ln() + (n - (m as f64) + 0.5) * (z / w).ln() + ((y - m) as f64) * (w * p / (x1 * q)).ln() // ________ + stirling(f1) + stirling(z) - stirling(x1) - stirling(w) { continue; } match (self, other) { (&U32(ref v1), &U32(ref v2)) => v1 == v2, (&USize(ref v1), &USize(ref v2)) => v1 == v2, (&U32(ref v1), &USize(ref v2)) => { v1.len() == v2.len() && v1.iter().zip(v2.iter()).all(|(x, y)| *x as usize == *y) } (&USize(ref v1), &U32(ref v2)) => { v1.len() == v2.len() && v1.iter().zip(v2.iter()).all(|(x, y)| *x == *y as usize) } } fn main() { let o_num = Some(123); let x = if let Some(n) = // ________ o_num { n * 2 } else { 0 }; println!("Number: {}", x); } struct Foo { // a: i32, // // b: i32, } struct Foo { a: i32, // // b: i32, } macro_rules! m { ($a:expr) => { if $a { return; } }; } let write_status = | status: &mut Vec, diff: &Diff, heading: &str, color: &Style, show_hints: bool, hints: &[&str] | -> Result {} macro_rules! member_mut { ($self:expr, $member:expr) => {{ use self::Member::*; let r = &mut *$self; match $member { A => &mut r.a, B => &mut r.b, } }}; } if let Some(ref /*mut*/ state) = foo { } impl< Target: FromEvent + FromEvent, A: Widget2, B: Widget2, C: for<'a> CtxFamily<'a>, > Widget2 for WidgetEventLifter { type Ctx = C; type Event = Vec; } async { // Do // some // work }.await; fn main() { token!(dyn); } fn build_sorted_static_get_entry_names( mut entries: Vec<(u8, &'static str)>, ) -> (impl Fn( AlphabeticalTraversal, Box>, ) -> BoxFuture<'static, Result, Status>> + Send + Sync + 'static) { } fn main() { bbbbbbbbbbbbbbbbbb::ccccccccccccccccccccccccccccccccccccccc::dddddddddddddddddddd( eeeeeeeeeeeeeeeeeeee::ffffffffffffffffffff( ggggggggg(hhhhhhhhhhhhhhhh), iiiiiiiii(jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj), ), ); } fn f() -> Box< dyn FnMut() -> Thing< WithType = LongItemName, Error = LONGLONGLONGLONGLONGONGEvenLongerErrorNameLongerLonger>, >{ } trait Foo where {} struct Bar where {} impl<> Foo<> for Bar<> where {} impl Foo { fn foo() { self.report.add_non_formatted_ranges(visitor.skipped_range.clone()); } } fn test() { let aaaaaaaaaaaaaaaa = ffffffffffffffffffffffff .iter() .filter_map(|_| { if bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb == ccccccccccccccccccccccc .dddddddddddddddddddddddd() .eeeeeeeeeeeeeeeeeeeeee() { (); } }) .collect(); } fn main() { let visual_studio_path = { let vswhere_stdout = String::from_utf8(vswhere_output.stdout) .expect("vswhere output is not valid UTF-8"); String::from(vswhere_stdout.trim()) }; } #[cfg(test)] mod tests { #[test] fn handles_mid_demangling() { assert_eq!( crate::demangle_line(" lea rax, [rip + _ZN55_$LT$$RF$$u27$a$u20$T$u20$as$u20$core..fmt..Display$GT$3fmt17h510ed05e72307174E]"), " lea rax, [rip + <&\'a T as core::fmt::Display>::fmt]"); } } fn main() { let i = test::<-1>(); println!("Hello, {}!", i); } fn test() -> i8 { {T} } vm.get_method_or_type_error( obj.clone(), "__getitem__", || format!("'{}' object is not iterable", obj.class().name) )?; type ProposeTransactionsFuture: Future< Item = ProposeTransactionsResponse, Error = Error, >; type ProposeTransactionsFuture: Future< Item = ProposeTransactionsResponse, Error = Error, > + Send + 'static; fn main() { /* Common case: The double precision result is fine. */ if (ui & 0x1fffffff) != 0x10000000 /* not a halfway case */ || e == 0x7ff /* NaN */ || (result - xy == z as f64 && result - z as f64 == xy) /* exact */ || fegetround() != FE_TONEAREST /* not round-to-nearest */ { } } pub fn foo(config: &Config) { let csv = RefCell::new(create_csv(config, "foo")); { let mut csv = csv.borrow_mut(); for (i1, i2, i3) in iproduct!(0..2, 0..3, 0..3) { csv.write_field(format!("γ[{}.{}.{}]", i1, i2, i3)) .unwrap(); csv.write_field(format!("d[{}.{}.{}]", i1, i2, i3)).unwrap(); csv.write_field(format!("i[{}.{}.{}]", i1, i2, i3)).unwrap(); } csv.write_record(None::<&[u8]>).unwrap(); } } fn main() { let a = Foo { something: Some(1), bar: 2, }; if let Foo { something: Some(something), .. } = a { println!("{}", something); } } fn main() { let dv = (2. * m * l * dtheta * dtheta * theta.sin() + 3. * m * g * theta.sin() * theta.cos() + 4. * u - 4. * b * v) / (4. * (M + m) - 3. * m * theta.cos().powi(2)); let ddtheta = (-3. * m * l * dtheta * dtheta * theta.sin() * theta.cos() - 6. * (M + m) * g * theta.sin() - 6. * (u - b * v) * theta.cos()) / (4. * l * (m + M) - 3. * m * l * theta.cos().powi(2)); let V: Array2<_> = (((&lq + &vi).mapv(f64::exp) - &q) * (mi_minus_mi_t).mapv(f64::cos) - ((&lq - &vi).mapv(f64::exp) - &q) * (mi_plus_mi_t).mapv(f64::cos)) * e.as_row() * e.as_column() * 0.5; dVdm.slice_mut(s![.., .., j]).assign( &(((Array2::zeros((d, d)) + u.as_column() - u.as_row()) * &U1 + (Array2::::zeros((d, d)) + u.as_column() + u.as_row()) * &U2) * e.as_column() * e.as_row()), ); { { { { { let LdXi: Array2<_> = (dmahai + kdX.slice(s![.., i, d]).into_column() + kdX.slice(s![.., j, d])) * &L; } } } } } let dnlml = Array1::from_shape_fn(ln_hyperparams.len(), |i| { 0.5 * ( self.covfunc.deriv_covariance(ln_hyperparams, train_inputs, i) * &W ).scalar_sum() }); dVdi.slice_mut(s![.., output_index, .., input_index]) .assign( &(c * (iR .column(input_index) .into_column() .dot(&lb.view().into_row()) - (&t * &tlb_view.into_column()).reversed_axes() + tlbdi2)), ); { let tdX: Array1<_> = -0.5 * t * (&iR.t() * test_covariance * (-2. * &inv_sq_len_scales_i - 2. * &inv_sq_len_scales_i)) .sum_axis(Axis(0)); } { let dSds: Array2<_> = r2 * (2. * i2SpW.dot(&m_minus_z.as_column()).dot(&m_minus_z.as_row()) - Array2::::eye(D)) .dot(&i2SpW) - 2. * L * &dLds; } let f = future::poll_fn(move || { match tokio_threadpool::blocking(|| f.poll()).unwrap() { Async::Ready(v) => v, Async::NotReady => Ok(Async::NotReady), } }); test("Your number: ", match input { BigEnum::One => 0, BigEnum::Two => 0, BigEnum::Three => 0, BigEnum::Four => 0, BigEnum::Five => 0, BigEnum::Six => 0, BigEnum::Seven => 0, BigEnum::Eight => 0, BigEnum::Nine => 0, BigEnum::Ten => 0, BigEnum::Eleven => 0, BigEnum::Twelve => 0, }); window .task_manager() .dom_manipulation_task_source() .queue( task!(fire_dom_content_loaded_event: move || { let document = document.root(); document.upcast::().fire_bubbling_event(atom!("DOMContentLoaded")); update_with_current_time_ms(&document.dom_content_loaded_event_end); }), window.upcast(), ) .unwrap(); foo(|| { loop { foo(); } }); foo(|| { while true { foo(); } }); foo(|| { if true { foo(); } }); tokio::spawn(async { println!(); }); // this block will be properly formatted { let a = 1; let b=2; let c = " very very very very very very very very very very very very very very very very very very long string in a block"; } let v = vec![1, 2]; // this block won't be formatted v.iter().for_each(|_| { let a = 1; let b=2; let c = " very very very very very very very very very very very very very very very very very very long string in a block"; }); // this block with shorter str will be properly formatted v.iter().for_each(|_| { let a = 1; let b=2; let c = " less very very long string in a block"; }); async fn forty_two() -> i32 { 42 } fn spawn_async(_f: impl Future) { unimplemented!(); } fn main() { spawn_async(async { println!("{}", await!(forty_two())); }); } if 1 {} else if eq!(b[1] == b'o' b'n' b't' b'e' b'n' b't' b'-' b'r' b'a' b'n' b'g' b'e' ) {} } static REPRO: &[usize] = &[ #[cfg(feature = "zero")] 0, ]; lazy_static! { pub static ref BLOCKING_POOL: tokio_threadpool::ThreadPool = { tokio_threadpool::Builder::new().pool_size(1).build() }; static ref FOO: Foo = unsafe { very_long_function_name().another_function_with_really_long_name() }; } static DEFAULT_HOOK: SyncLazy) + Sync + Send + 'static>> = SyncLazy::new(|| { let hook = panic::take_hook(); panic::set_hook(Box::new(|info| { // Invoke the default handler, which prints the actual panic message and optionally a backtrace (*DEFAULT_HOOK)(info); // Separate the output with an empty line eprintln!(); // Print the ICE message rustc_driver::report_ice(info, BUG_REPORT_URL); })); hook }); fn main() { let factorial = |recur: &dyn Fn(u32) -> u32, arg: u32| -> u32 { if arg == 0 {1} else {arg * recur(arg-1)} }; self.time_passes = config.opts.prints.is_empty() && (config.opts.debugging_opts.time_passes || config.opts.debugging_opts.time); config.opts.maybe_sysroot = Some(config.opts.maybe_sysroot.clone().unwrap_or_else(|| { std::env::current_exe().unwrap().parent().unwrap().parent().unwrap().to_owned() })); Box::new(rustc_codegen_ssa::base::codegen_crate( LlvmCodegenBackend(()), tcx, crate::llvm_util::target_cpu(tcx.sess).to_string(), metadata, need_metadata_module, )); let (codegen_results, work_products) = ongoing_codegen .downcast::>() .expect("Expected GccCodegenBackend's OngoingCodegen, found Box") .join(sess); if let Some(old) = old { self.cur = unsafe { (self.step)(old) }; } let _prof_timer = tcx.prof.generic_activity_with_args( "codegen_module", &[cgu_name.to_string(), cgu.size_estimate().to_string()], ); let tm = match (cgcx.tm_factory)(tm_factory_config) {}; let _ = [0; {struct Foo; impl Foo {const fn get(&self) -> usize {5}}; Foo.get()}]; syntactically_correct(loop { sup( '?'); }, if cond { 0 } else { 1 }); unsafe { &*self.llmod_raw } llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _)); let tm = (cgcx.tm_factory)(tm_factory_config).map_err(|e| write::llvm_err(&diag_handler, &e))?; target_machine_factory(sess, config::OptLevel::No, &features)(config) .unwrap_or_else(|err| llvm_err(sess.diagnostic(), &err).raise()); let TestOutcome { completed: ok, errors: err, .. } = forest.process_obligations(&mut C( |obligation| match *obligation { "D'" => { d_count += 1; ProcessResult::Error("operation failed") } _ => unreachable!(), }, |_| {}, )); let adjusted_span = (|| { if let ExprKind::Block { body } = &expr.kind && let Some(tail_ex) = body.expr { let mut expr = &this.thir[tail_ex]; while let ExprKind::Block { body: Block { expr: Some(nested_expr), .. }, } | ExprKind::Scope { value: nested_expr, .. } = expr.kind { expr = &this.thir[nested_expr]; } this.block_context.push(BlockFrame::TailExpr { tail_result_is_ignored: true, span: expr.span, }); return Some(expr.span); } None })(); match (test.end, pat.end, lo, hi) { // pat < test (_, _, Greater, _) | (_, Excluded, Equal, _) | // pat > test (_, _, _, Less) | // <- (Excluded, _, _, Equal) => Some(true), _ => Some(false), } let overlaps: Vec<_> = pats .filter_map(|pat| Some((pat.ctor().as_int_range()?, pat.span()))) .filter(|(range, _)| self.suspicious_intersection(range)) .map(|(range, span)| (self.intersection(&range).unwrap(), span)) .collect(); match bb_data.terminator().kind { (JustBefore(n), JustBefore(m)) if n < m => n..=(m - 1), (JustBefore(n), AfterMax) => n..=u128::MAX, _ => unreachable!(), // Ruled out by the sorting and filtering we did (Some(to), Some(from)) => { (from == Ordering::Greater || from == Ordering::Equal) && (to == Ordering::Less || (other_end == self_end && to == Ordering::Equal)) } Return | Resume | Abort | GeneratorDrop | Unreachable => {} Goto { target } => propagate(target, exit_state), Assert { target, cleanup: unwind, expected: _, msg: _, cond: _ } | Drop { target, unwind, place: _ } | DropAndReplace { target, unwind, value: _, place: _ } | FalseUnwind { real_target: target, unwind } => { if let Some(unwind) = unwind { if dead_unwinds.map_or(true, |dead| !dead.contains(bb)) { propagate(unwind, exit_state); } } propagate(target, exit_state); } mir::Rvalue::Ref(_, mir::BorrowKind::Mut { .. }, place) | mir::Rvalue::AddressOf(_, place) => (self.0)(place), _ => {} suggestion_kind @ "suggestion" | suggestion_kind @ "suggestion_short" | suggestion_kind @ "suggestion_hidden" | suggestion_kind @ "suggestion_verbose" => { let (span, applicability) = (|| match &info.ty { ty @ syn::Type::Path(..) if type_matches_path(ty, &["rustc_span", "Span"]) => { let binding = &info.binding.binding; Ok(( quote!(*#binding), quote!(rustc_errors::Applicability::Unspecified), )) } _ => throw_span_err!( info.span.unwrap(), "wrong field type for suggestion", |diag| { diag.help("#[suggestion(...)] should be applied to fields of type Span or (Span, Applicability)") } ), })()?; for arg in list.nested.iter() { if let syn::NestedMeta::Meta(syn::Meta::NameValue(arg_name_value)) = arg { if let syn::MetaNameValue { lit: syn::Lit::Str(s), .. } = arg_name_value { let name = arg_name_value .path .segments .last() .unwrap() .ident .to_string(); let name = name.as_str(); let formatted_str = self.build_format(&s.value(), arg.span()); match name { "message" => { msg = Some(formatted_str); } "code" => { code = Some(formatted_str); } other => throw_span_err!( arg.span().unwrap(), &format!( "`{}` is not a valid key for `#[suggestion(...)]`", other ) ), } } } } let msg = if let Some(msg) = msg { quote!(#msg.as_str()) } else { throw_span_err!( list.span().unwrap(), "missing suggestion message", |diag| { diag.help("provide a suggestion message using #[suggestion(message = \"...\")]") } ); }; let code = code.unwrap_or_else(|| quote! { String::new() }); quote! { #diag.#suggestion_method(#span, #msg, #code, #applicability); } } other => throw_span_err!( list.span().unwrap(), &format!("invalid annotation list `#[{}(...)]`", other) ), _ => self.failed |= !(self.cb)(expr), } ListItem { pre_comment, pre_comment_style, item: if self.inner.peek().is_none() && self.leave_last { None } else { (self.get_item_string)(&item) }, post_comment, new_lines, }; comment_len(item.pre_comment.as_ref().map(|x| &(*x)[..])) + comment_len(item.post_comment.as_ref().map(|x| &(*x)[..])) + item.item.as_ref().map_or(0, |s| unicode_str_width(s)); Some(match rel { Rel::Lt => { match (lx, rx) { (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, AlwaysFalse), // max < x (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, AlwaysFalse), // x < min _ => return None, } }, Rel::Le => { match (lx, rx) { (Some(l @ ExtremeExpr { which: Minimum, .. }), _) => (l, AlwaysTrue), // min <= x (Some(l @ ExtremeExpr { which: Maximum, .. }), _) => (l, InequalityImpossible), // max <= x (_, Some(r @ ExtremeExpr { which: Minimum, .. })) => (r, InequalityImpossible), // x <= min (_, Some(r @ ExtremeExpr { which: Maximum, .. })) => (r, AlwaysTrue), // x <= max _ => return None, } }, Rel::Ne | Rel::Eq => return None, }); pat.each_binding_or_first(&mut |_, id, span, _| match cx .typeck_results() .extract_binding_mode(cx.sess(), id, span) .unwrap() { BindingMode::BindByValue(_) if !is_copy(cx, cx.typeck_results().node_type(id)) => { capture = CaptureKind::Value; }, BindingMode::BindByReference(Mutability::Mut) if capture != CaptureKind::Value => { capture = CaptureKind::Ref(Mutability::Mut); }, _ => (), }); for (parent_id, parent) in cx.tcx.hir().parent_iter(e.hir_id) { if let [ Adjustment { kind: Adjust::Deref(_) | Adjust::Borrow(AutoBorrow::Ref(..)), target, }, ref adjust @ .., ] = *cx .typeck_results() .adjustments() .get(child_id) .map_or(&[][..], |x| &**x) { if let rustc_ty::RawPtr(TypeAndMut { mutbl: mutability, .. }) | rustc_ty::Ref(_, _, mutability) = *adjust.last().map_or(target, |a| a.target).kind() { return CaptureKind::Ref(mutability); } } } while let Some(higher::IfOrIfLet { cond, then, r#else }) = higher::IfOrIfLet::hir(expr) { if let Some(else_expr) = r#else { expr = else_expr; } else { break; } } let lorem = vec!["ipsum","dolor","sit","amet","consectetur","adipiscing","elit"]; let hyper = Arc::new(Client::with_connector(HttpsConnector::new(TlsClient::new()))); { { let creds = self.client .client_credentials(&self.config.auth.oauth2.id, &self.config.auth.oauth2.secret)?; } } given( r#" # Getting started ... "#, ) .running(waltz); conn.query_row( r#" SELECT title, date FROM posts, WHERE DATE(date) = $1 "#, &[], |row| { Post { title: row.get(0), date: row.get(1), } }, )?; ThreadPool::new(Configuration::new().num_threads(1)) .unwrap() .install( || { scope( |s| { use std::sync::mpsc::channel; let (tx, rx) = channel(); let a = s.spawn_future(lazy(move || Ok::(rx.recv().unwrap()))); // ^^^^ FIXME: why is this needed? let b = s.spawn_future(a.map(|v| v + 1)); let c = s.spawn_future(b.map(|v| v + 1)); s.spawn(move |_| tx.send(20).unwrap()); result = Some(c.rayon_wait().unwrap()); }, ); }, ); bootstrap.checks.register( "PERSISTED_LOCATIONS", move || if locations2.0.inner_mut.lock().poisoned { Check::new( State::Error, "Persisted location storage is poisoned due to a write failure", ) } else { Check::new(State::Healthy, "Persisted location storage is healthy") }, ); self.cur_type() .num_template_args() .or_else(|| { let n: c_int = unsafe { clang_Cursor_getNumTemplateArguments(self.x) }; if n >= 0 { Some(n as u32) } else { debug_assert_eq!(n, -1); None } }) .or_else(|| { let canonical = self.canonical(); if canonical != *self { canonical.num_template_args() } else { None } }); if let VrMsg::ClientReply {request_num: reply_req_num, value, ..} = msg { let _ = safe_assert_eq!(reply_req_num, request_num, op); return Ok((request_num, op, value)); } pub struct FileInput { input: StringInput, file_name: OsString, } match len { Some(len) => Ok(new(self.input, self.pos + len)), None => Err(self), } } fn x() { { let type_list: Vec<_> = try_opt!(types.iter().map(|ty| ty.rewrite(context, shape)).collect()); } } impl Foo { fn map_pixel_to_coords(&self, point: &Vector2i, view: &View) -> Vector2f { unsafe { Vector2f::from_raw(ffi::sfRenderTexture_mapPixelToCoords(self.render_texture, point.raw(), view.raw())) } } } extern "C" { pub fn GetConsoleHistoryInfo(console_history_info: *mut ConsoleHistoryInfo) -> Boooooooooooooool; pub fn variadic_fn(first_parameter: FirstParameterType, second_parameter: SecondParameterType, ...); // no trailing comma } fn deconstruct(foo: Bar) -> (SocketAddr, Header, Method, RequestUri, HttpVersion, AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA) { let if_method_break: SocketAddr = if remote_addr.is_ipv4() { "0.0.0.0:0" } else { "[::]:0" } .parse()?; let method_chain_middle_await_break = reader .next_line() .await .unwrap_or_else(|_| Some(String::new())) .expect("failed to read line"); } fn needs_paren(op: AssocOp, other: AssocOp, dir: Associativity) -> bool { other.precedence() < op.precedence() || (other.precedence() == op.precedence() && ((op != other && associativity(op) != dir) || (op == other && associativity(op) != Associativity::Both))) || is_shift(op) && is_arith(other) || is_shift(other) && is_arith(op) } pub fn peel_blocks<'a>(mut expr: &'a Expr<'a>) -> &'a Expr<'a> { while let ExprKind::Block( Block { stmts: [], expr: Some(inner), rules: BlockCheckMode::DefaultBlock, .. }, _, ) = expr.kind { expr = inner; } expr } pub fn target_features(sess: &Session) -> Vec { supported_target_features(sess) .iter() .filter_map( |&(feature, gate)| { if sess.is_nightly_build() || gate.is_none() { Some(feature) } else { None } }, ) .filter(|_feature| { // TODO(antoyo): implement a way to get enabled feature in libgccjit. false }) .map(|feature| Symbol::intern(feature)) .collect() } fn a() { Arc::new(|_| { Ok(()) })} fn g<'a>(&self, x: usize, y:usize) -> Box usize + 'a> { let f = move |t: bool| if t { x } else { y }; return Box::new(f); } struct Compose(F, G); impl FnOnce<(T,)> for Compose where F: FnOnce<(T,)>, G: FnOnce<(F::Output,)>, { type Output = G::Output; extern "rust-call" fn call_once(self, (x,): (T,)) -> G::Output { (self.1)((self.0)(x)) } } fn build_sorted_static_get_entry_names( mut entries: Vec<(u8, &'static str)>, ) -> (impl Fn( AlphabeticalTraversal, Box>, ) -> BoxFuture<'static, Result, Status>> + Send + Sync + 'static) { } fn qcxbfds() { {{{ let explicit_arg_decls = explicit_arguments.into_iter() .enumerate() .map(|(index, (ty, pattern))| { let lvalue = Lvalue::Arg(index as u32); block = this.pattern(block, argument_extent, hair::PatternRef::Hair(pattern), &lvalue); ArgDecl { ty: ty } }); }}} } #[print_target_and_args(first_outer)] #[print_target_and_args(second_outer)] impl Bar<{1 > 0}> for Foo<{true}> { #![print_target_and_args(first_inner)] #![print_target_and_args(second_inner)] } /// `cfg(...)`'s that are feature gated. const GATED_CFGS: &[GatedCfg] = &[ // (name in cfg, feature, function to check if the feature is enabled) (sym::target_abi, sym::cfg_target_abi, cfg_fn!(cfg_target_abi)), (sym::target_thread_local, sym::cfg_target_thread_local, cfg_fn!(cfg_target_thread_local)), ( sym::target_has_atomic_equal_alignment, sym::cfg_target_has_atomic_equal_alignment, cfg_fn!(cfg_target_has_atomic_equal_alignment), ), (sym::target_has_atomic_load_store, sym::cfg_target_has_atomic, cfg_fn!(cfg_target_has_atomic)), (sym::sanitize, sym::cfg_sanitize, cfg_fn!(cfg_sanitize)), (sym::version, sym::cfg_version, cfg_fn!(cfg_version)), ]; [ { while let Ok(flag) = input.try_parse(|input| { Ok( match_ignore_ascii_case! { &input.expect_ident().map_err(|_| ())?, "jis78" => exclusive_value!((result, VariantEastAsian::JIS78 | VariantEastAsian::JIS83 | VariantEastAsian::JIS90 | VariantEastAsian::JIS04 | VariantEastAsian::SIMPLIFIED | VariantEastAsian::TRADITIONAL ) => VariantEastAsian::JIS78) _ => return Err(()), }, ) }) { result.insert(flag); } } ] #[cfg_attr(doc_cfg, doc(cfg(feature = "beep boop")))] impl Foo for Bar { fn stuff(data: Leet) -> Result { let manual_clone = node.data == Data::Private || node.ident == "beep"; if data.boop(Foo) && !(data.boop(Bar) && data.boop2(Too![=])) { data.stuff().map(A::B) } else if data.boop(Ident::abc) || data.boop(Too![::]) && data.boop3(Ident::abc) { data.stuff().map(NestedMeta::Meta) } else { Err(data.error("brrr")) } s.match_indices(prefix).any(|(i, _)| { s[i + prefix.len()..].trim_start_matches('[') }) if args.len() >= 2 && args[1] == "fail" { foo(); } else if args.len() >= 2 && args[1] == "double-fail" { double(); } else { runtest(&args[0]); } } } impl Future for TryJoin3 where F1: Future>, F2: Future>, F3: Future> { fn c() {} } c! { impl A { // pub(crate) unsafe fn no_extra_indent_in_params<'a>( &'a self, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll> where &'a E: io::Read + 'a, {} } pub trait AsyncBufReadExt: AsyncBufRead { fn read_until<'a>(&'a mut self, byte: u8, buf: &'a mut Vec) -> ReadUntil<'a, Self> where Self: Unpin { read_until(self, byte, buf) } } } let BufWriter { inner: BufReader { inner, buf: rbuf, pos, cap, seek_state: rseek_state, }, buf: wbuf, written, seek_state: wseek_state, } = b; { { fn clock(){ match CONTEXT.try_with(|ctx| (*ctx.borrow()).as_ref().map(|ctx| ctx.as_inner().clock.clone())) {} match s.match_indices(prefix).any(|(i, _)| { s[i + prefix.len()..].trim_start_matches('[') }) {} match a // && b {} } } } pub(super) fn shutdown(self) { let (task1, _) = super::unowned(async {}); let (task2, _) = super::unowned(async { 1 }); let (task3, _) = super::unowned(async { f(); 2 }); let vtable = self.header().vtable; unsafe { (vtable.shutdown)(self.ptr) } } fn inlining_last_if_else_block_is_awkward() { poll_fn(move |cx| { if !fired { return Poll::Pending; } if gate.load(SeqCst) { Poll::Ready } else { Poll::Pending } }) } pub(super) fn vtable() -> &'static Vtable { &(Vtable { poll: poll::, dealloc: dealloc::, try_read_output: try_read_output::, try_set_join_waker: try_set_join_waker::, drop_join_handle_slow: drop_join_handle_slow::, drop_abort_handle: drop_abort_handle::, remote_abort: remote_abort::, shutdown: shutdown::, }) } // comment const ________________ = self.exp != S::MIN_EXP && (self.sig[0] & sig_mask) == 0; let r = if s.starts_with("0x") || s.starts_with("0X") { zzzzzzzzzzzzzz } else { 2 }; pub trait Float: Copy + Default + FromStr + PartialOrd + fmt::Display + Neg + AddAssign + SubAssign + MulAssign + DivAssign + RemAssign + Add> + Sub> + Mul> + Div> + Rem> { const BITS: usize; } // print-width: 80 ------------------------------------------------------------- fn space_before_where(_: F) where F: X {} impl<'a, I, T: 'a, E> Iterator for Y<'a, I, E> where I: Iterator,{} impl<'a, I, T: 'a, E> IteratorIterator for Y<'a, I, E> where I: Iterator,{} impl<'a, I, T: 'a, E> Iterator for Y<'a, I, E> where I: Iterator,{ type Y; } prettier_always_breaks_this(b(|| ()), c); self.and_this() .map(|| 1) .unwrap_or(0); pub fn noop_visit_constraint( AssocConstraint { id, ident, gen_args, kind, span }: &mut AssocConstraint, vis: &mut T, ) {} match kind { AssocConstraintKind::Equality { ref mut term } => { 1 } } impl X { pub fn ident(&self) -> Option { match self.kind { AttrKind::Normal(ref item, _) => { if item.path.segments.len() == 1 { Some(item.path.segments[0].ident) } else { None } } AttrKind::DocComment(..) => None, } } } #![attr] // comment to the right of attr /* */ a!(/**/); Thing(/* _______ */); pub /* _______ */ const a = {}; const a = "💖" // ______________ // _______ _______ _______ /* _______ */ foo /* _______ */; this.call(a, /* _______ */ b); /* foo text */ /* fn a() { println!("b"); } // */ #[a="a"] #[b] // v #[cfg_attr(rustfmt, rustfmt::skip)] pub static x: [i32; 0] = []; f!()/* comment */; f!{}/* comment */; f![]/* comment */; pub enum Foo { A, // `/** **/` B, // `/*!` C, } ProcessSystemError(A { code: acc.error.code, // _______ originalError: acc.error, // _______ }); foo(A {} // _______ ); fn c() {} /* a b */ const f = static async |source, block, opts| { for entry in source { yield async move || { const cid = persist(entry.content.serialize(), block, opts).await; return A { cid, path: entry.path, unixfs: UnixFS.unmarshal(entry.content.Data), node: entry.content } } } }; type Expect_Parenthesized_dyn = Pin<&mut (dyn Future + Send)>; let mut Expect_Comma_after_first_match = match 0 { RuntimeFlavor::CurrentThread => quote_spanned! {last_stmt_start_span=> #crate_ident::runtime::Builder::new_current_thread() }, RuntimeFlavor::Threaded => quote_spanned! {last_stmt_start_span=> #crate_ident::runtime::Builder::new_multi_thread() }, }; ExpectNoSpreadComma { ..a// }; ExpectNoSpreadComma { ..a,// }; ExpectNoSpreadComma { a, b: b, ..c// }; ExpectNoSpreadComma { a, ..c,// b: b }; ExpectNoSpreadComma { .., a// }; ExpectNoSpreadComma { ..// }; let notify::event::Event { kind: notify::event::EventKind::Modify(_), paths, .. } = event; let notify::event::Event { .., kind: notify::event::EventKind::Modify(_), paths, } = event; ================================================ FILE: tests/samples/issues/14.rs ================================================ [10.00, 10.0, 10., 10]; ================================================ FILE: tests/samples/issues/21/fn_comment.rs ================================================ fn eof() {} // comment ================================================ FILE: tests/samples/issues/21/fn_fn.rs ================================================ fn eof1() {} fn eof2() {} ================================================ FILE: tests/samples/issues/21/fn_ln.rs ================================================ fn eof() {} ================================================ FILE: tests/samples/issues/21/ln_fn_ln.rs ================================================ fn eof(){} ================================================ FILE: tests/samples/issues/21/mod.rs ================================================ mod eof {} ================================================ FILE: tests/samples/issues/22.rs ================================================ fn preserve_last_semicolon() { if let Some(left) = node.borrow().left.as_ref() { deque.push_back(left.clone()); }; if let Some(right) = node.borrow().right.as_ref() { deque.push_back(right.clone()); }; } fn a() { if let Ok(_) = lock.try_lock() {}; } fn b() { let lock = std::sync::Mutex::new(10); match lock.try_lock() { Ok(_) => {} Err(_) => {} }; match lock.try_lock() { Ok(_) => {} Err(_) => {} }; } fn c() { if let Ok(_) = lock.try_lock() {}; // comment } fn d() { if let Ok(_) = lock.try_lock() {}; // comment } fn e() { if let Ok(_) = lock.try_lock() {}/** comment */; } fn f() { if let Ok(_) = lock.try_lock() { } ; } fn g() { if let Ok(_) = lock.try_lock() { } // comment ; } fn h() { if let Ok(_) = lock {}; if let Ok(_) = lock {}; } fn i() { match lock {}; match lock {}; } fn inner_attr() { if let Ok(_) = lock.try_lock() {}; #![attr] } ================================================ FILE: tests/samples/issues/25.rs ================================================ #[ generator( yield( i32 ) )] fn nums() { yield_!(3); } // some extra samples to track changes #[ // 0 generator // 1 ( // 2 yield // 3 ( // 4 i32 // 5 ) // 6 ) // 7 ] // non-conventional syntax (does not format) #[ #[a] generator( #[b] yield( #[c] i32 ))] #[generator (a( #[generator(b(i32))] i32 ) ) ] #[generator (a( #[generator(yield(i32))] i32 ) ) ] #[generator (yield( #[generator(b(i32))] i32 ) ) ] #[generator (yield( #[generator(yield(i32))] i32 ) ) ] fn f() { yield_!(3); } // macros in attr (does not format) #[attr(foo!( ))] fn f() {} ================================================ FILE: tests/samples/issues/nth-pass.rs ================================================ // prettier for javascript cannot format those in one pass return ( // _______ 42 ) * 84 + 2; return ( // _______ 42 ) + 84 * 2; foo // foo // comment after parent .x .y // comment 1 .bar() // comment after bar() // comment 2 .foobar // comment after // comment 3 .baz(x, y, z); let zzzz = expr? // comment after parent // comment 0 .another??? // comment 1 .another???? // comment 2 .another? // comment 3 .another?; [ a = b, c // ]; ================================================ FILE: tests/samples/macros/cfg_if.rs ================================================ [ cfg_if! { if #[cfg(def)]{ use std; 0 } }, cfg_if! { if #[cfg(def)]{ use std; 0 } else { 1 } }, cfg_if! { if #[cfg(abc)]{ 0 } else { 1 } }, cfg_if! { if #[cfg(abc)]{ 0 } else if #[cfg(def)] { 1 } }, cfg_if! { if #[cfg(abc)]{ 0 } else if #[cfg(def)] { 1 } else { 0 } }, cfg_if! {}, cfg_if! { // comment if #[cfg(abc)] { 0 } }, cfg_if! { if #[cfg(abc)] { /// comment /// comment /// comment struct A{ //! comment a: u8 } } }, cfg_if! { if #[cfg(abc)] { struct A{ //! comment // comment /// comment a: u8 } } }, cfg_if! { if #[cfg(abc)] { struct A{ /// comment a: u8 } } }, cfg_if! { if #[cfg(abc)] { struct A{ //! comment } } }, cfg_if! { if #[cfg(abc)] { struct A{ /// comment } } }, cfg_if! { if true{} } ] ================================================ FILE: tests/samples/macros/if_chain.rs ================================================ [ if_chain! { if let Some(a) = b; if let Err(a) = b; let (a, b) = c; if 1 + 2; then { d=0; } }, if_chain! { then { d=0; } }, if_chain! { then { d=0; } else { d!(); } }, if_chain! { if let A::B | A::C = D; then { 0 } else { 1 } }, if_chain! { let Ok(a) | Err(b) = c; then { d!(); } else { d!(); } }, if_chain! { if 1 + 1; let a: u32 = 3; then { d!(); } else { d!(); } } ] ================================================ FILE: tests/samples/macros/matches.rs ================================================ [ matches!(1 + 1, Some(_) ), matches!(1 + 1, Some(_) | None if 1 + 1 == 2), matches!(1 + 1, | Some(_) | None if 1 + 1 == 2) ] ================================================ FILE: tests/samples/styling/blockify.rs ================================================ [ || 0, || match 0 {}, || if 0 {}, || loop {}, || const {}, || async {}, || -> T 0, || -> T match 0 {}, || -> T if 0 {}, || -> T loop {}, || -> T const {}, || -> T async {} ] ================================================ FILE: tests/samples/styling/canInlineBlockBody.rs ================================================ [ { if 0 { 0 } }, { if 0 { 0 } else { 0 } }, { while 0 { 0 } }, { unsafe { 0 } }, { 0; if 0 { 0 } }, { 0; if 0 { 0 } else { 0 } }, { 0; while 0 { 0 } }, { 0; unsafe { 0 } }, f(async {}), f(async { 1 }), f(async { 1; }), { async {} }, { async { 1 } }, { async { 1; } }, { 0; async {} }, { 0; async { 1 } }, { 0; async { 1; } }, if (0 as u8) < 1 {} else {}, { 0; if (0 as u8) < 1 {} else {} }, if (0 as u8) < 1 {} else if (0 as u8) < 1 {}, if 0 {} else { 0; }, if 0 {} else if 1 { 0; } else {}, if 0 {} else if 1 {} else { 0; }, if 0 { 0; } else {}, if 0 { 0; } else { 2 }, if 0 { 2 } else { 0; }, match 0 { 0 => 0, 0 => { 0 } }, f(if 0 { 1 } else { 2 }), f({0;}, if 0 { 1 } else { 2 }), 0 + (if 0 { 1 } else { 2 }), { 0 + (if 0 { 1 } else { 2 }) }, ({0;}) + (if 0 { 1 } else { 2 }), match 0 { 0 => break 0, 0 => (o = 0), 0 => match 0 {}, 0 => if 0 {} else {}, 0 => if 0 {}, }, || loop { match 0 { 0 => break 0, 0 => (o = 0), 0 => match 0 {}, 0 => if 0 {} else {}, 0 => if 0 {}, } } ] ================================================ FILE: tests/samples/styling/needsParens.rs ================================================ let (A {} | a() | []) = (); if let (A {} | a() | []) = () {} type A: B + C; type A: impl B + C; trait A = B + C; trait A = impl B + C; ================================================ FILE: tests/samples/styling/needsSemi.rs ================================================ fn f() { #[cfg(unix)] { 0 } #[cfg(windows)] { 1 } } ================================================ FILE: tests/test.build.ts ================================================ import { exec } from "node:child_process"; import { inspect, promisify } from "node:util"; import prettier from "prettier"; import { testBuilds } from "../ext/jinx-rust/scripts/utils/build"; // import * as plugin_esm from "../index.js"; import plugin from "../src/index"; // test esm import await promisify(exec)('node -e "import(`./index.js`)"'); testBuilds( plugin, { esm: await import("../index.js"), cjs: (await import("../index.cjs")).default, }, function formatWithPlugin(file, plugin) { try { return { ext: "rs", content: prettier.format(file.content, { parser: "jinx-rust", plugins: [plugin], printWidth: 80, tabWidth: 2, filepath: file.cmd, }), }; } catch (e) { return { ext: "rs", content: inspect(e, { showHidden: true, getters: true }), }; } }, ["tests/samples", "ext/jinx-rust/tests/samples"] ); ================================================ FILE: tsconfig.base.json ================================================ { "compilerOptions": { "target": "ES2020", // upper target changes property order // module "module": "ESNext", "moduleResolution": "Node", "esModuleInterop": true, // types "lib": ["ESNext"], "skipLibCheck": true, "skipDefaultLibCheck": true, // checks "allowUnusedLabels": true, "exactOptionalPropertyTypes": true, "noFallthroughCasesInSwitch": true, // strict "strict": true, "noImplicitAny": false, "strictFunctionTypes": false, "strictPropertyInitialization": false, // Project "composite": true, "isolatedModules": true }, "ts-node": { "esm": true, "swc": true, "experimentalSpecifierResolution": "node" } } ================================================ FILE: tsconfig.build.json ================================================ { "extends": "./tsconfig.base.json", "include": ["src"], "compilerOptions": { // "declaration": true, // "declarationDir": "dist", // "emitDeclarationOnly": true, // "outDir": "dist", // "rootDir": "src", // "rootDirs": ["src", "dist"], "composite": false, "isolatedModules": false, "preserveConstEnums": false // "removeComments": false } } ================================================ FILE: tsconfig.json ================================================ { "extends": "./tsconfig.base.json", "include": ["src"], "compilerOptions": { "types": ["prettier", "jinx-rust"], "rootDir": "src" } }