From ac595dd57a151a16a168e6596404ada8f079b778 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Wed, 22 Jun 2022 22:14:32 -0500 Subject: [PATCH 01/69] Merge commit 'c4416f20dcaec5d93077f72470e83e150fb923b1' into sync-rustfmt --- .github/workflows/linux.yml | 14 +- .github/workflows/mac.yml | 10 +- .github/workflows/windows.yml | 11 +- CHANGELOG.md | 26 +- Cargo.lock | 2 +- Cargo.toml | 6 +- Configurations.md | 8 + ci/build_and_test.bat | 14 + ci/build_and_test.sh | 18 + ci/integration.sh | 2 +- config_proc_macro/Cargo.lock | 44 +- config_proc_macro/src/lib.rs | 4 + rust-toolchain | 2 +- src/cargo-fmt/main.rs | 3 +- src/comment.rs | 4 + src/config/mod.rs | 3 + src/expr.rs | 51 +- src/formatting.rs | 2 - src/imports.rs | 343 +- src/reorder.rs | 10 +- src/rewrite.rs | 13 - src/shape.rs | 4 +- src/visitor.rs | 7 +- .../doc_comment_code_block_width/100.rs | 16 + .../100_greater_max_width.rs | 17 + .../doc_comment_code_block_width/50.rs | 16 + .../imports_raw_identifiers/version_One.rs | 5 + .../imports_raw_identifiers/version_Two.rs | 5 + tests/source/performance/issue-4476.rs | 638 -- tests/source/performance/issue-5128.rs | 5127 ----------------- .../doc_comment_code_block_width/100.rs | 16 + .../100_greater_max_width.rs | 29 + .../doc_comment_code_block_width/50.rs | 22 + .../imports_raw_identifiers/version_One.rs | 5 + .../imports_raw_identifiers/version_Two.rs | 5 + tests/target/issue_5399.rs | 48 + tests/target/performance/issue-4476.rs | 705 --- tests/target/performance/issue-4867.rs | 13 - tests/target/performance/issue-5128.rs | 4898 ---------------- 39 files changed, 533 insertions(+), 11633 deletions(-) create mode 100755 ci/build_and_test.bat create mode 100755 ci/build_and_test.sh create mode 100644 tests/source/configs/doc_comment_code_block_width/100.rs create mode 100644 tests/source/configs/doc_comment_code_block_width/100_greater_max_width.rs create mode 100644 tests/source/configs/doc_comment_code_block_width/50.rs create mode 100644 tests/source/imports_raw_identifiers/version_One.rs create mode 100644 tests/source/imports_raw_identifiers/version_Two.rs delete mode 100644 tests/source/performance/issue-4476.rs delete mode 100644 tests/source/performance/issue-5128.rs create mode 100644 tests/target/configs/doc_comment_code_block_width/100.rs create mode 100644 tests/target/configs/doc_comment_code_block_width/100_greater_max_width.rs create mode 100644 tests/target/configs/doc_comment_code_block_width/50.rs create mode 100644 tests/target/imports_raw_identifiers/version_One.rs create mode 100644 tests/target/imports_raw_identifiers/version_Two.rs create mode 100644 tests/target/issue_5399.rs delete mode 100644 tests/target/performance/issue-4476.rs delete mode 100644 tests/target/performance/issue-4867.rs delete mode 100644 tests/target/performance/issue-5128.rs diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 6a3f9d89d98fc..bce9b0c8d5a95 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -35,15 +35,5 @@ jobs: sh rustup-init.sh -y --default-toolchain none rustup target add ${{ matrix.target }} - - name: build - run: | - rustc -Vv - cargo -V - cargo build - env: - RUSTFLAGS: '-D warnings' - - - name: test - run: cargo test - env: - RUSTFLAGS: '-D warnings' + - name: Build and Test + run: ./ci/build_and_test.sh diff --git a/.github/workflows/mac.yml b/.github/workflows/mac.yml index 7dfda3142ca9d..89a980c42c5a0 100644 --- a/.github/workflows/mac.yml +++ b/.github/workflows/mac.yml @@ -32,11 +32,5 @@ jobs: sh rustup-init.sh -y --default-toolchain none rustup target add ${{ matrix.target }} - - name: build - run: | - rustc -Vv - cargo -V - cargo build - - - name: test - run: cargo test + - name: Build and Test + run: ./ci/build_and_test.sh diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index 4ebc296384905..ec37c714b0851 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -57,13 +57,6 @@ jobs: if: matrix.target == 'x86_64-pc-windows-gnu' && matrix.channel == 'nightly' shell: bash - - name: build - run: | - rustc -Vv - cargo -V - cargo build - shell: cmd - - - name: test - run: cargo test + - name: Build and Test shell: cmd + run: ci\build_and_test.bat diff --git a/CHANGELOG.md b/CHANGELOG.md index bfc155cd656a6..0c1893bf8c387 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,29 @@ ## [Unreleased] -## [1.5.0] 2022-06-13 +## [1.5.1] 2022-06-24 + +**N.B** A bug was introduced in v1.5.0/nightly-2022-06-15 which modified formatting. If you happened to run rustfmt over your code with one of those ~10 nightlies it's possible you may have seen formatting changes, and you may see additional changes after this fix since that bug has now been reverted. + +### Fixed + +- Correct an issue introduced in v1.5.0 where formatting changes were unintentionally introduced in a few cases with a large/long construct in a right hand side position (e.g. a large chain on the RHS of a local/assignment statement) +- `cargo fmt --version` properly displays the version value again [#5395](https://github.com/rust-lang/rustfmt/issues/5395) + +### Changed + +- Properly sort imports containing raw identifiers [#3791](https://github.com/rust-lang/rustfmt/issues/3791) (note this is change version gated, and not applied by default) + +### Added + +- Add new configuration option, `doc_comment_code_block_width`, which allows for setting a shorter width limit to use for formatting code snippets in doc comments [#5384](https://github.com/rust-lang/rustfmt/issues/5384) + +### Install/Download Options +- **rustup (nightly)** - nightly-2022-06-24 +- **GitHub Release Binaries** - [Release v1.5.1](https://github.com/rust-lang/rustfmt/releases/tag/v1.5.0) +- **Build from source** - [Tag v1.5.1](https://github.com/rust-lang/rustfmt/tree/v1.5.1), see instructions for how to [install rustfmt from source][install-from-source] + +## [1.5.0] 2022-06-14 ### Changed @@ -75,7 +97,7 @@ - Improved performance when formatting large and deeply nested expression trees, often found in generated code, which have many expressions that exceed `max_width` [#5128](https://github.com/rust-lang/rustfmt/issues/5128), [#4867](https://github.com/rust-lang/rustfmt/issues/4867), [#4476](https://github.com/rust-lang/rustfmt/issues/4476), [#5139](https://github.com/rust-lang/rustfmt/pull/5139) ### Install/Download Options -- **rustup (nightly)** - *pending* +- **rustup (nightly)** - nightly-2022-06-15 - **GitHub Release Binaries** - [Release v1.5.0](https://github.com/rust-lang/rustfmt/releases/tag/v1.5.0) - **Build from source** - [Tag v1.5.0](https://github.com/rust-lang/rustfmt/tree/v1.5.0), see instructions for how to [install rustfmt from source][install-from-source] diff --git a/Cargo.lock b/Cargo.lock index 639d35886dcda..311df226da19d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -485,7 +485,7 @@ dependencies = [ [[package]] name = "rustfmt-nightly" -version = "1.5.0" +version = "1.5.1" dependencies = [ "annotate-snippets", "anyhow", diff --git a/Cargo.toml b/Cargo.toml index f26e982406234..7a4e02d69eddc 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustfmt-nightly" -version = "1.5.0" +version = "1.5.1" description = "Tool to find and fix Rust formatting issues" repository = "https://github.com/rust-lang/rustfmt" readme = "README.md" @@ -65,3 +65,7 @@ rustfmt-config_proc_macro = { version = "0.2", path = "config_proc_macro" } rustc-workspace-hack = "1.0.0" # Rustc dependencies are loaded from the sysroot, Cargo doesn't know about them. + +[package.metadata.rust-analyzer] +# This package uses #[feature(rustc_private)] +rustc_private = true diff --git a/Configurations.md b/Configurations.md index 8c84614352ca2..8b96b9d36892a 100644 --- a/Configurations.md +++ b/Configurations.md @@ -926,6 +926,14 @@ fn add_one(x: i32) -> i32 { } ``` +## `doc_comment_code_block_width` + +Max width for code snippets included in doc comments. Only used if [`format_code_in_doc_comments`](#format_code_in_doc_comments) is true. + +- **Default value**: `100` +- **Possible values**: any positive integer that is less than or equal to the value specified for [`max_width`](#max_width) +- **Stable**: No (tracking issue: [#5359](https://github.com/rust-lang/rustfmt/issues/5359)) + ## `format_generated_files` Format generated files. A file is considered generated diff --git a/ci/build_and_test.bat b/ci/build_and_test.bat new file mode 100755 index 0000000000000..ef41017783feb --- /dev/null +++ b/ci/build_and_test.bat @@ -0,0 +1,14 @@ +set "RUSTFLAGS=-D warnings" + +:: Print version information +rustc -Vv || exit /b 1 +cargo -V || exit /b 1 + +:: Build and test main crate +cargo build --locked || exit /b 1 +cargo test || exit /b 1 + +:: Build and test other crates +cd config_proc_macro || exit /b 1 +cargo build --locked || exit /b 1 +cargo test || exit /b 1 diff --git a/ci/build_and_test.sh b/ci/build_and_test.sh new file mode 100755 index 0000000000000..8fa0f67b0d021 --- /dev/null +++ b/ci/build_and_test.sh @@ -0,0 +1,18 @@ +#!/bin/bash + +set -euo pipefail + +export RUSTFLAGS="-D warnings" + +# Print version information +rustc -Vv +cargo -V + +# Build and test main crate +cargo build --locked +cargo test + +# Build and test other crates +cd config_proc_macro +cargo build --locked +cargo test diff --git a/ci/integration.sh b/ci/integration.sh index 0269e3ee4af93..562d5d70c70ba 100755 --- a/ci/integration.sh +++ b/ci/integration.sh @@ -15,7 +15,7 @@ set -ex # it again. # #which cargo-fmt || cargo install --force -CFG_RELEASE=nightly CFG_RELEASE_CHANNEL=nightly cargo install --path . --force +CFG_RELEASE=nightly CFG_RELEASE_CHANNEL=nightly cargo install --path . --force --locked echo "Integration tests for: ${INTEGRATION}" cargo fmt -- --version diff --git a/config_proc_macro/Cargo.lock b/config_proc_macro/Cargo.lock index abcf9654e5d77..ecf561f28fb6a 100644 --- a/config_proc_macro/Cargo.lock +++ b/config_proc_macro/Cargo.lock @@ -1,68 +1,68 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. +version = 3 + [[package]] name = "proc-macro2" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e98a83a9f9b331f54b924e68a66acb1bb35cb01fb0a23645139967abefb697e8" dependencies = [ - "unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "unicode-xid", ] [[package]] name = "quote" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053a8c8bcc71fcce321828dc897a98ab9760bef03a4fc36693c231e5b3216cfe" dependencies = [ - "proc-macro2 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", + "proc-macro2", ] [[package]] name = "rustfmt-config_proc_macro" -version = "0.1.2" +version = "0.2.0" dependencies = [ - "proc-macro2 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.99 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)", + "proc-macro2", + "quote", + "serde", + "syn", ] [[package]] name = "serde" version = "1.0.99" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fec2851eb56d010dc9a21b89ca53ee75e6528bab60c11e89d38390904982da9f" dependencies = [ - "serde_derive 1.0.99 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.99" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4dc18c61206b08dc98216c98faa0232f4337e1e1b8574551d5bad29ea1b425" dependencies = [ - "proc-macro2 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)", + "proc-macro2", + "quote", + "syn", ] [[package]] name = "syn" version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66850e97125af79138385e9b88339cbcd037e3f28ceab8c5ad98e64f0f1f80bf" dependencies = [ - "proc-macro2 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "proc-macro2", + "quote", + "unicode-xid", ] [[package]] name = "unicode-xid" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" - -[metadata] -"checksum proc-macro2 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "e98a83a9f9b331f54b924e68a66acb1bb35cb01fb0a23645139967abefb697e8" -"checksum quote 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "053a8c8bcc71fcce321828dc897a98ab9760bef03a4fc36693c231e5b3216cfe" -"checksum serde 1.0.99 (registry+https://github.com/rust-lang/crates.io-index)" = "fec2851eb56d010dc9a21b89ca53ee75e6528bab60c11e89d38390904982da9f" -"checksum serde_derive 1.0.99 (registry+https://github.com/rust-lang/crates.io-index)" = "cb4dc18c61206b08dc98216c98faa0232f4337e1e1b8574551d5bad29ea1b425" -"checksum syn 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)" = "66850e97125af79138385e9b88339cbcd037e3f28ceab8c5ad98e64f0f1f80bf" -"checksum unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "826e7639553986605ec5979c7dd957c7895e93eabed50ab2ffa7f6128a75097c" +checksum = "826e7639553986605ec5979c7dd957c7895e93eabed50ab2ffa7f6128a75097c" diff --git a/config_proc_macro/src/lib.rs b/config_proc_macro/src/lib.rs index 513018213192d..e772c53f42361 100644 --- a/config_proc_macro/src/lib.rs +++ b/config_proc_macro/src/lib.rs @@ -29,6 +29,8 @@ pub fn config_type(_args: TokenStream, input: TokenStream) -> TokenStream { /// Used to conditionally output the TokenStream for tests that need to be run on nightly only. /// /// ```rust +/// # use rustfmt_config_proc_macro::nightly_only_test; +/// /// #[nightly_only_test] /// #[test] /// fn test_needs_nightly_rustfmt() { @@ -49,6 +51,8 @@ pub fn nightly_only_test(_args: TokenStream, input: TokenStream) -> TokenStream /// Used to conditionally output the TokenStream for tests that need to be run on stable only. /// /// ```rust +/// # use rustfmt_config_proc_macro::stable_only_test; +/// /// #[stable_only_test] /// #[test] /// fn test_needs_stable_rustfmt() { diff --git a/rust-toolchain b/rust-toolchain index 813e5e2c10fea..2640a9e0ecc28 100644 --- a/rust-toolchain +++ b/rust-toolchain @@ -1,3 +1,3 @@ [toolchain] -channel = "nightly-2022-06-06" +channel = "nightly-2022-06-21" components = ["rustc-dev"] diff --git a/src/cargo-fmt/main.rs b/src/cargo-fmt/main.rs index 55fd75f6de9b8..9031d29b45f7f 100644 --- a/src/cargo-fmt/main.rs +++ b/src/cargo-fmt/main.rs @@ -14,7 +14,7 @@ use std::path::{Path, PathBuf}; use std::process::Command; use std::str; -use clap::{CommandFactory, Parser}; +use clap::{AppSettings, CommandFactory, Parser}; #[path = "test/mod.rs"] #[cfg(test)] @@ -22,6 +22,7 @@ mod cargo_fmt_tests; #[derive(Parser)] #[clap( + global_setting(AppSettings::NoAutoVersion), bin_name = "cargo fmt", about = "This utility formats all bin and lib files of \ the current crate using rustfmt." diff --git a/src/comment.rs b/src/comment.rs index eb195b1f7628f..4d565afc1e026 100644 --- a/src/comment.rs +++ b/src/comment.rs @@ -730,6 +730,10 @@ impl<'a> CommentRewrite<'a> { { let mut config = self.fmt.config.clone(); config.set().wrap_comments(false); + let comment_max_width = config + .doc_comment_code_block_width() + .min(config.max_width()); + config.set().max_width(comment_max_width); if let Some(s) = crate::format_code_block(&self.code_block_buffer, &config, false) { diff --git a/src/config/mod.rs b/src/config/mod.rs index a516952818783..f49c18d3a4603 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -57,6 +57,8 @@ create_config! { // Comments. macros, and strings wrap_comments: bool, false, false, "Break comments to fit on the line"; format_code_in_doc_comments: bool, false, false, "Format the code snippet in doc comments."; + doc_comment_code_block_width: usize, 100, false, "Maximum width for code snippets in doc \ + comments. No effect unless format_code_in_doc_comments = true"; comment_width: usize, 80, false, "Maximum length of comments. No effect unless wrap_comments = true"; normalize_comments: bool, false, false, "Convert /* */ comments to // comments where possible"; @@ -532,6 +534,7 @@ chain_width = 60 single_line_if_else_max_width = 50 wrap_comments = false format_code_in_doc_comments = false +doc_comment_code_block_width = 100 comment_width = 80 normalize_comments = false normalize_doc_attributes = false diff --git a/src/expr.rs b/src/expr.rs index 4ccf1ca70c9d9..e4cc93026f10b 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -1,6 +1,5 @@ use std::borrow::Cow; use std::cmp::min; -use std::collections::HashMap; use itertools::Itertools; use rustc_ast::token::{Delimiter, LitKind}; @@ -23,7 +22,7 @@ use crate::macros::{rewrite_macro, MacroPosition}; use crate::matches::rewrite_match; use crate::overflow::{self, IntoOverflowableItem, OverflowableItem}; use crate::pairs::{rewrite_all_pairs, rewrite_pair, PairParts}; -use crate::rewrite::{QueryId, Rewrite, RewriteContext}; +use crate::rewrite::{Rewrite, RewriteContext}; use crate::shape::{Indent, Shape}; use crate::source_map::{LineRangeUtils, SpanUtils}; use crate::spanned::Spanned; @@ -54,54 +53,6 @@ pub(crate) fn format_expr( expr_type: ExprType, context: &RewriteContext<'_>, shape: Shape, -) -> Option { - // when max_width is tight, we should check all possible formattings, in order to find - // if we can fit expression in the limit. Doing it recursively takes exponential time - // relative to input size, and people hit it with rustfmt takes minutes in #4476 #4867 #5128 - // By memoization of format_expr function, we format each pair of expression and shape - // only once, so worst case execution time becomes O(n*max_width^3). - if context.inside_macro() || context.is_macro_def { - // span ids are not unique in macros, so we don't memoize result of them. - return format_expr_inner(expr, expr_type, context, shape); - } - let clean; - let query_id = QueryId { - shape, - span: expr.span, - }; - if let Some(map) = context.memoize.take() { - if let Some(r) = map.get(&query_id) { - let r = r.clone(); - context.memoize.set(Some(map)); // restore map in the memoize cell for other users - return r; - } - context.memoize.set(Some(map)); - clean = false; - } else { - context.memoize.set(Some(HashMap::default())); - clean = true; // We got None, so we are the top level called function. When - // this function finishes, no one is interested in what is in the map, because - // all of them are sub expressions of this top level expression, and this is - // done. So we should clean up memoize map to save some memory. - } - - let r = format_expr_inner(expr, expr_type, context, shape); - if clean { - context.memoize.set(None); - } else { - if let Some(mut map) = context.memoize.take() { - map.insert(query_id, r.clone()); // insert the result in the memoize map - context.memoize.set(Some(map)); // so it won't be computed again - } - } - r -} - -fn format_expr_inner( - expr: &ast::Expr, - expr_type: ExprType, - context: &RewriteContext<'_>, - shape: Shape, ) -> Option { skip_out_of_file_lines_range!(context, expr.span); diff --git a/src/formatting.rs b/src/formatting.rs index e644ea50effd7..1dfd8a514f0bc 100644 --- a/src/formatting.rs +++ b/src/formatting.rs @@ -2,7 +2,6 @@ use std::collections::HashMap; use std::io::{self, Write}; -use std::rc::Rc; use std::time::{Duration, Instant}; use rustc_ast::ast; @@ -203,7 +202,6 @@ impl<'a, T: FormatHandler + 'a> FormatContext<'a, T> { self.config, &snippet_provider, self.report.clone(), - Rc::default(), ); visitor.skip_context.update_with_attrs(&self.krate.attrs); visitor.is_macro_def = is_macro_def; diff --git a/src/imports.rs b/src/imports.rs index 559ed3917dba7..8d41c881589e5 100644 --- a/src/imports.rs +++ b/src/imports.rs @@ -15,7 +15,7 @@ use rustc_span::{ use crate::comment::combine_strs_with_missing_comments; use crate::config::lists::*; use crate::config::ImportGranularity; -use crate::config::{Edition, IndentStyle}; +use crate::config::{Edition, IndentStyle, Version}; use crate::lists::{ definitive_tactic, itemize_list, write_list, ListFormatting, ListItem, Separator, }; @@ -92,7 +92,7 @@ impl<'a> FmtVisitor<'a> { // FIXME we do a lot of allocation to make our own representation. #[derive(Clone, Eq, Hash, PartialEq)] -pub(crate) enum UseSegment { +pub(crate) enum UseSegmentKind { Ident(String, Option), Slf(Option), Super(Option), @@ -101,6 +101,12 @@ pub(crate) enum UseSegment { List(Vec), } +#[derive(Clone, Eq, PartialEq)] +pub(crate) struct UseSegment { + pub(crate) kind: UseSegmentKind, + pub(crate) version: Version, +} + #[derive(Clone)] pub(crate) struct UseTree { pub(crate) path: Vec, @@ -134,34 +140,38 @@ impl Spanned for UseTree { impl UseSegment { // Clone a version of self with any top-level alias removed. fn remove_alias(&self) -> UseSegment { - match *self { - UseSegment::Ident(ref s, _) => UseSegment::Ident(s.clone(), None), - UseSegment::Slf(_) => UseSegment::Slf(None), - UseSegment::Super(_) => UseSegment::Super(None), - UseSegment::Crate(_) => UseSegment::Crate(None), - _ => self.clone(), + let kind = match self.kind { + UseSegmentKind::Ident(ref s, _) => UseSegmentKind::Ident(s.clone(), None), + UseSegmentKind::Slf(_) => UseSegmentKind::Slf(None), + UseSegmentKind::Super(_) => UseSegmentKind::Super(None), + UseSegmentKind::Crate(_) => UseSegmentKind::Crate(None), + _ => return self.clone(), + }; + UseSegment { + kind, + version: self.version, } } // Check if self == other with their aliases removed. fn equal_except_alias(&self, other: &Self) -> bool { - match (self, other) { - (UseSegment::Ident(ref s1, _), UseSegment::Ident(ref s2, _)) => s1 == s2, - (UseSegment::Slf(_), UseSegment::Slf(_)) - | (UseSegment::Super(_), UseSegment::Super(_)) - | (UseSegment::Crate(_), UseSegment::Crate(_)) - | (UseSegment::Glob, UseSegment::Glob) => true, - (UseSegment::List(ref list1), UseSegment::List(ref list2)) => list1 == list2, + match (&self.kind, &other.kind) { + (UseSegmentKind::Ident(ref s1, _), UseSegmentKind::Ident(ref s2, _)) => s1 == s2, + (UseSegmentKind::Slf(_), UseSegmentKind::Slf(_)) + | (UseSegmentKind::Super(_), UseSegmentKind::Super(_)) + | (UseSegmentKind::Crate(_), UseSegmentKind::Crate(_)) + | (UseSegmentKind::Glob, UseSegmentKind::Glob) => true, + (UseSegmentKind::List(ref list1), UseSegmentKind::List(ref list2)) => list1 == list2, _ => false, } } fn get_alias(&self) -> Option<&str> { - match self { - UseSegment::Ident(_, a) - | UseSegment::Slf(a) - | UseSegment::Super(a) - | UseSegment::Crate(a) => a.as_deref(), + match &self.kind { + UseSegmentKind::Ident(_, a) + | UseSegmentKind::Slf(a) + | UseSegmentKind::Super(a) + | UseSegmentKind::Crate(a) => a.as_deref(), _ => None, } } @@ -175,19 +185,24 @@ impl UseSegment { if name.is_empty() || name == "{{root}}" { return None; } - Some(match name { - "self" => UseSegment::Slf(None), - "super" => UseSegment::Super(None), - "crate" => UseSegment::Crate(None), + let kind = match name { + "self" => UseSegmentKind::Slf(None), + "super" => UseSegmentKind::Super(None), + "crate" => UseSegmentKind::Crate(None), _ => { let mod_sep = if modsep { "::" } else { "" }; - UseSegment::Ident(format!("{}{}", mod_sep, name), None) + UseSegmentKind::Ident(format!("{}{}", mod_sep, name), None) } + }; + + Some(UseSegment { + kind, + version: context.config.version(), }) } fn contains_comment(&self) -> bool { - if let UseSegment::List(list) = self { + if let UseSegmentKind::List(list) = &self.kind { list.iter().any(|subtree| subtree.contains_comment()) } else { false @@ -254,20 +269,38 @@ impl fmt::Debug for UseTree { impl fmt::Debug for UseSegment { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt::Display::fmt(self, f) + fmt::Display::fmt(&self.kind, f) } } impl fmt::Display for UseSegment { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(&self.kind, f) + } +} + +impl Hash for UseSegment { + fn hash(&self, state: &mut H) { + self.kind.hash(state); + } +} + +impl fmt::Debug for UseSegmentKind { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(self, f) + } +} + +impl fmt::Display for UseSegmentKind { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { - UseSegment::Glob => write!(f, "*"), - UseSegment::Ident(ref s, Some(ref alias)) => write!(f, "{} as {}", s, alias), - UseSegment::Ident(ref s, None) => write!(f, "{}", s), - UseSegment::Slf(..) => write!(f, "self"), - UseSegment::Super(..) => write!(f, "super"), - UseSegment::Crate(..) => write!(f, "crate"), - UseSegment::List(ref list) => { + UseSegmentKind::Glob => write!(f, "*"), + UseSegmentKind::Ident(ref s, Some(ref alias)) => write!(f, "{} as {}", s, alias), + UseSegmentKind::Ident(ref s, None) => write!(f, "{}", s), + UseSegmentKind::Slf(..) => write!(f, "self"), + UseSegmentKind::Super(..) => write!(f, "super"), + UseSegmentKind::Crate(..) => write!(f, "crate"), + UseSegmentKind::List(ref list) => { write!(f, "{{")?; for (i, item) in list.iter().enumerate() { if i != 0 { @@ -411,13 +444,19 @@ impl UseTree { } } + let version = context.config.version(); + match a.kind { UseTreeKind::Glob => { // in case of a global path and the glob starts at the root, e.g., "::*" if a.prefix.segments.len() == 1 && leading_modsep { - result.path.push(UseSegment::Ident("".to_owned(), None)); + let kind = UseSegmentKind::Ident("".to_owned(), None); + result.path.push(UseSegment { kind, version }); } - result.path.push(UseSegment::Glob); + result.path.push(UseSegment { + kind: UseSegmentKind::Glob, + version, + }); } UseTreeKind::Nested(ref list) => { // Extract comments between nested use items. @@ -438,16 +477,18 @@ impl UseTree { // in case of a global path and the nested list starts at the root, // e.g., "::{foo, bar}" if a.prefix.segments.len() == 1 && leading_modsep { - result.path.push(UseSegment::Ident("".to_owned(), None)); + let kind = UseSegmentKind::Ident("".to_owned(), None); + result.path.push(UseSegment { kind, version }); } - result.path.push(UseSegment::List( + let kind = UseSegmentKind::List( list.iter() .zip(items) .map(|(t, list_item)| { Self::from_ast(context, &t.0, Some(list_item), None, None, None) }) .collect(), - )); + ); + result.path.push(UseSegment { kind, version }); } UseTreeKind::Simple(ref rename, ..) => { // If the path has leading double colons and is composed of only 2 segments, then we @@ -469,13 +510,15 @@ impl UseTree { Some(rewrite_ident(context, ident).to_owned()) } }); - let segment = match name.as_ref() { - "self" => UseSegment::Slf(alias), - "super" => UseSegment::Super(alias), - "crate" => UseSegment::Crate(alias), - _ => UseSegment::Ident(name, alias), + let kind = match name.as_ref() { + "self" => UseSegmentKind::Slf(alias), + "super" => UseSegmentKind::Super(alias), + "crate" => UseSegmentKind::Crate(alias), + _ => UseSegmentKind::Ident(name, alias), }; + let segment = UseSegment { kind, version }; + // `name` is already in result. result.path.pop(); result.path.push(segment); @@ -492,13 +535,13 @@ impl UseTree { let mut aliased_self = false; // Remove foo::{} or self without attributes. - match last { + match last.kind { _ if self.attrs.is_some() => (), - UseSegment::List(ref list) if list.is_empty() => { + UseSegmentKind::List(ref list) if list.is_empty() => { self.path = vec![]; return self; } - UseSegment::Slf(None) if self.path.is_empty() && self.visibility.is_some() => { + UseSegmentKind::Slf(None) if self.path.is_empty() && self.visibility.is_some() => { self.path = vec![]; return self; } @@ -506,15 +549,19 @@ impl UseTree { } // Normalise foo::self -> foo. - if let UseSegment::Slf(None) = last { + if let UseSegmentKind::Slf(None) = last.kind { if !self.path.is_empty() { return self; } } // Normalise foo::self as bar -> foo as bar. - if let UseSegment::Slf(_) = last { - if let Some(UseSegment::Ident(_, None)) = self.path.last() { + if let UseSegmentKind::Slf(_) = last.kind { + if let Some(UseSegment { + kind: UseSegmentKind::Ident(_, None), + .. + }) = self.path.last() + { aliased_self = true; } } @@ -522,9 +569,12 @@ impl UseTree { let mut done = false; if aliased_self { match self.path.last_mut() { - Some(UseSegment::Ident(_, ref mut old_rename)) => { + Some(UseSegment { + kind: UseSegmentKind::Ident(_, ref mut old_rename), + .. + }) => { assert!(old_rename.is_none()); - if let UseSegment::Slf(Some(rename)) = last.clone() { + if let UseSegmentKind::Slf(Some(rename)) = last.clone().kind { *old_rename = Some(rename); done = true; } @@ -538,15 +588,15 @@ impl UseTree { } // Normalise foo::{bar} -> foo::bar - if let UseSegment::List(ref list) = last { + if let UseSegmentKind::List(ref list) = last.kind { if list.len() == 1 && list[0].to_string() != "self" { normalize_sole_list = true; } } if normalize_sole_list { - match last { - UseSegment::List(list) => { + match last.kind { + UseSegmentKind::List(list) => { for seg in &list[0].path { self.path.push(seg.clone()); } @@ -557,10 +607,13 @@ impl UseTree { } // Recursively normalize elements of a list use (including sorting the list). - if let UseSegment::List(list) = last { + if let UseSegmentKind::List(list) = last.kind { let mut list = list.into_iter().map(UseTree::normalize).collect::>(); list.sort(); - last = UseSegment::List(list); + last = UseSegment { + kind: UseSegmentKind::List(list), + version: last.version, + }; } self.path.push(last); @@ -620,10 +673,10 @@ impl UseTree { if self.path.is_empty() || self.contains_comment() { return vec![self]; } - match self.path.clone().last().unwrap() { - UseSegment::List(list) => { + match &self.path.clone().last().unwrap().kind { + UseSegmentKind::List(list) => { if list.len() == 1 && list[0].path.len() == 1 { - if let UseSegment::Slf(..) = list[0].path[0] { + if let UseSegmentKind::Slf(..) = list[0].path[0].kind { return vec![self]; }; } @@ -671,12 +724,15 @@ impl UseTree { /// If this tree ends in `::self`, rewrite it to `::{self}`. fn nest_trailing_self(mut self) -> UseTree { - if let Some(UseSegment::Slf(..)) = self.path.last() { + if let Some(UseSegment { + kind: UseSegmentKind::Slf(..), + .. + }) = self.path.last() + { let self_segment = self.path.pop().unwrap(); - self.path.push(UseSegment::List(vec![UseTree::from_path( - vec![self_segment], - DUMMY_SP, - )])); + let version = self_segment.version; + let kind = UseSegmentKind::List(vec![UseTree::from_path(vec![self_segment], DUMMY_SP)]); + self.path.push(UseSegment { kind, version }); } self } @@ -692,7 +748,8 @@ fn merge_rest( return None; } if a.len() != len && b.len() != len { - if let UseSegment::List(ref list) = a[len] { + let version = a[len].version; + if let UseSegmentKind::List(ref list) = a[len].kind { let mut list = list.clone(); merge_use_trees_inner( &mut list, @@ -700,7 +757,8 @@ fn merge_rest( merge_by, ); let mut new_path = b[..len].to_vec(); - new_path.push(UseSegment::List(list)); + let kind = UseSegmentKind::List(list); + new_path.push(UseSegment { kind, version }); return Some(new_path); } } else if len == 1 { @@ -709,15 +767,28 @@ fn merge_rest( } else { (&b[0], &a[1..]) }; + let kind = UseSegmentKind::Slf(common.get_alias().map(ToString::to_string)); + let version = a[0].version; let mut list = vec![UseTree::from_path( - vec![UseSegment::Slf(common.get_alias().map(ToString::to_string))], + vec![UseSegment { kind, version }], DUMMY_SP, )]; match rest { - [UseSegment::List(rest_list)] => list.extend(rest_list.clone()), + [ + UseSegment { + kind: UseSegmentKind::List(rest_list), + .. + }, + ] => list.extend(rest_list.clone()), _ => list.push(UseTree::from_path(rest.to_vec(), DUMMY_SP)), } - return Some(vec![b[0].clone(), UseSegment::List(list)]); + return Some(vec![ + b[0].clone(), + UseSegment { + kind: UseSegmentKind::List(list), + version, + }, + ]); } else { len -= 1; } @@ -727,7 +798,9 @@ fn merge_rest( ]; list.sort(); let mut new_path = b[..len].to_vec(); - new_path.push(UseSegment::List(list)); + let kind = UseSegmentKind::List(list); + let version = a[0].version; + new_path.push(UseSegment { kind, version }); Some(new_path) } @@ -805,19 +878,33 @@ impl PartialOrd for UseTree { } impl Ord for UseSegment { fn cmp(&self, other: &UseSegment) -> Ordering { - use self::UseSegment::*; + use self::UseSegmentKind::*; fn is_upper_snake_case(s: &str) -> bool { s.chars() .all(|c| c.is_uppercase() || c == '_' || c.is_numeric()) } - match (self, other) { - (&Slf(ref a), &Slf(ref b)) - | (&Super(ref a), &Super(ref b)) - | (&Crate(ref a), &Crate(ref b)) => a.cmp(b), - (&Glob, &Glob) => Ordering::Equal, - (&Ident(ref ia, ref aa), &Ident(ref ib, ref ab)) => { + match (&self.kind, &other.kind) { + (Slf(ref a), Slf(ref b)) + | (Super(ref a), Super(ref b)) + | (Crate(ref a), Crate(ref b)) => match (a, b) { + (Some(sa), Some(sb)) => { + if self.version == Version::Two { + sa.trim_start_matches("r#").cmp(sb.trim_start_matches("r#")) + } else { + a.cmp(b) + } + } + (_, _) => a.cmp(b), + }, + (Glob, Glob) => Ordering::Equal, + (Ident(ref pia, ref aa), Ident(ref pib, ref ab)) => { + let (ia, ib) = if self.version == Version::Two { + (pia.trim_start_matches("r#"), pib.trim_start_matches("r#")) + } else { + (pia.as_str(), pib.as_str()) + }; // snake_case < CamelCase < UPPER_SNAKE_CASE if ia.starts_with(char::is_uppercase) && ib.starts_with(char::is_lowercase) { return Ordering::Greater; @@ -835,15 +922,21 @@ impl Ord for UseSegment { if ident_ord != Ordering::Equal { return ident_ord; } - if aa.is_none() && ab.is_some() { - return Ordering::Less; - } - if aa.is_some() && ab.is_none() { - return Ordering::Greater; + match (aa, ab) { + (None, Some(_)) => Ordering::Less, + (Some(_), None) => Ordering::Greater, + (Some(aas), Some(abs)) => { + if self.version == Version::Two { + aas.trim_start_matches("r#") + .cmp(abs.trim_start_matches("r#")) + } else { + aas.cmp(abs) + } + } + (None, None) => Ordering::Equal, } - aa.cmp(ab) } - (&List(ref a), &List(ref b)) => { + (List(ref a), List(ref b)) => { for (a, b) in a.iter().zip(b.iter()) { let ord = a.cmp(b); if ord != Ordering::Equal { @@ -853,16 +946,16 @@ impl Ord for UseSegment { a.len().cmp(&b.len()) } - (&Slf(_), _) => Ordering::Less, - (_, &Slf(_)) => Ordering::Greater, - (&Super(_), _) => Ordering::Less, - (_, &Super(_)) => Ordering::Greater, - (&Crate(_), _) => Ordering::Less, - (_, &Crate(_)) => Ordering::Greater, - (&Ident(..), _) => Ordering::Less, - (_, &Ident(..)) => Ordering::Greater, - (&Glob, _) => Ordering::Less, - (_, &Glob) => Ordering::Greater, + (Slf(_), _) => Ordering::Less, + (_, Slf(_)) => Ordering::Greater, + (Super(_), _) => Ordering::Less, + (_, Super(_)) => Ordering::Greater, + (Crate(_), _) => Ordering::Less, + (_, Crate(_)) => Ordering::Greater, + (Ident(..), _) => Ordering::Less, + (_, Ident(..)) => Ordering::Greater, + (Glob, _) => Ordering::Less, + (_, Glob) => Ordering::Greater, } } } @@ -906,7 +999,7 @@ fn rewrite_nested_use_tree( } let has_nested_list = use_tree_list.iter().any(|use_segment| { use_segment.path.last().map_or(false, |last_segment| { - matches!(last_segment, UseSegment::List(..)) + matches!(last_segment.kind, UseSegmentKind::List(..)) }) }); @@ -957,17 +1050,19 @@ fn rewrite_nested_use_tree( impl Rewrite for UseSegment { fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { - Some(match self { - UseSegment::Ident(ref ident, Some(ref rename)) => format!("{} as {}", ident, rename), - UseSegment::Ident(ref ident, None) => ident.clone(), - UseSegment::Slf(Some(ref rename)) => format!("self as {}", rename), - UseSegment::Slf(None) => "self".to_owned(), - UseSegment::Super(Some(ref rename)) => format!("super as {}", rename), - UseSegment::Super(None) => "super".to_owned(), - UseSegment::Crate(Some(ref rename)) => format!("crate as {}", rename), - UseSegment::Crate(None) => "crate".to_owned(), - UseSegment::Glob => "*".to_owned(), - UseSegment::List(ref use_tree_list) => rewrite_nested_use_tree( + Some(match self.kind { + UseSegmentKind::Ident(ref ident, Some(ref rename)) => { + format!("{} as {}", ident, rename) + } + UseSegmentKind::Ident(ref ident, None) => ident.clone(), + UseSegmentKind::Slf(Some(ref rename)) => format!("self as {}", rename), + UseSegmentKind::Slf(None) => "self".to_owned(), + UseSegmentKind::Super(Some(ref rename)) => format!("super as {}", rename), + UseSegmentKind::Super(None) => "super".to_owned(), + UseSegmentKind::Crate(Some(ref rename)) => format!("crate as {}", rename), + UseSegmentKind::Crate(None) => "crate".to_owned(), + UseSegmentKind::Glob => "*".to_owned(), + UseSegmentKind::List(ref use_tree_list) => rewrite_nested_use_tree( context, use_tree_list, // 1 = "{" and "}" @@ -1016,6 +1111,7 @@ mod test { struct Parser<'a> { input: Peekable>, + version: Version, } impl<'a> Parser<'a> { @@ -1028,34 +1124,40 @@ mod test { } fn push_segment( + &self, result: &mut Vec, buf: &mut String, alias_buf: &mut Option, ) { + let version = self.version; if !buf.is_empty() { let mut alias = None; swap(alias_buf, &mut alias); match buf.as_ref() { "self" => { - result.push(UseSegment::Slf(alias)); + let kind = UseSegmentKind::Slf(alias); + result.push(UseSegment { kind, version }); *buf = String::new(); *alias_buf = None; } "super" => { - result.push(UseSegment::Super(alias)); + let kind = UseSegmentKind::Super(alias); + result.push(UseSegment { kind, version }); *buf = String::new(); *alias_buf = None; } "crate" => { - result.push(UseSegment::Crate(alias)); + let kind = UseSegmentKind::Crate(alias); + result.push(UseSegment { kind, version }); *buf = String::new(); *alias_buf = None; } _ => { let mut name = String::new(); swap(buf, &mut name); - result.push(UseSegment::Ident(name, alias)); + let kind = UseSegmentKind::Ident(name, alias); + result.push(UseSegment { kind, version }); } } } @@ -1070,21 +1172,29 @@ mod test { '{' => { assert!(buf.is_empty()); self.bump(); - result.push(UseSegment::List(self.parse_list())); + let kind = UseSegmentKind::List(self.parse_list()); + result.push(UseSegment { + kind, + version: self.version, + }); self.eat('}'); } '*' => { assert!(buf.is_empty()); self.bump(); - result.push(UseSegment::Glob); + let kind = UseSegmentKind::Glob; + result.push(UseSegment { + kind, + version: self.version, + }); } ':' => { self.bump(); self.eat(':'); - Self::push_segment(&mut result, &mut buf, &mut alias_buf); + self.push_segment(&mut result, &mut buf, &mut alias_buf); } '}' | ',' => { - Self::push_segment(&mut result, &mut buf, &mut alias_buf); + self.push_segment(&mut result, &mut buf, &mut alias_buf); return UseTree { path: result, span: DUMMY_SP, @@ -1110,7 +1220,7 @@ mod test { } } } - Self::push_segment(&mut result, &mut buf, &mut alias_buf); + self.push_segment(&mut result, &mut buf, &mut alias_buf); UseTree { path: result, span: DUMMY_SP, @@ -1136,6 +1246,7 @@ mod test { let mut parser = Parser { input: s.chars().peekable(), + version: Version::One, }; parser.parse_in_list() } diff --git a/src/reorder.rs b/src/reorder.rs index 8ae297de25bc2..9e4a668aa4930 100644 --- a/src/reorder.rs +++ b/src/reorder.rs @@ -12,7 +12,7 @@ use rustc_ast::ast; use rustc_span::{symbol::sym, Span}; use crate::config::{Config, GroupImportsTactic}; -use crate::imports::{normalize_use_trees_with_granularity, UseSegment, UseTree}; +use crate::imports::{normalize_use_trees_with_granularity, UseSegmentKind, UseTree}; use crate::items::{is_mod_decl, rewrite_extern_crate, rewrite_mod}; use crate::lists::{itemize_list, write_list, ListFormatting, ListItem}; use crate::rewrite::RewriteContext; @@ -182,16 +182,16 @@ fn group_imports(uts: Vec) -> Vec> { external_imports.push(ut); continue; } - match &ut.path[0] { - UseSegment::Ident(id, _) => match id.as_ref() { + match &ut.path[0].kind { + UseSegmentKind::Ident(id, _) => match id.as_ref() { "std" | "alloc" | "core" => std_imports.push(ut), _ => external_imports.push(ut), }, - UseSegment::Slf(_) | UseSegment::Super(_) | UseSegment::Crate(_) => { + UseSegmentKind::Slf(_) | UseSegmentKind::Super(_) | UseSegmentKind::Crate(_) => { local_imports.push(ut) } // These are probably illegal here - UseSegment::Glob | UseSegment::List(_) => external_imports.push(ut), + UseSegmentKind::Glob | UseSegmentKind::List(_) => external_imports.push(ut), } } diff --git a/src/rewrite.rs b/src/rewrite.rs index f97df70cc6a7b..4a3bd129d16f5 100644 --- a/src/rewrite.rs +++ b/src/rewrite.rs @@ -12,7 +12,6 @@ use crate::shape::Shape; use crate::skip::SkipContext; use crate::visitor::SnippetProvider; use crate::FormatReport; -use rustc_data_structures::stable_map::FxHashMap; pub(crate) trait Rewrite { /// Rewrite self into shape. @@ -25,22 +24,10 @@ impl Rewrite for ptr::P { } } -#[derive(Clone, PartialEq, Eq, Hash)] -pub(crate) struct QueryId { - pub(crate) shape: Shape, - pub(crate) span: Span, -} - -// We use Option instead of HashMap, because in case of `None` -// the function clean the memoize map, but it doesn't clean when -// there is `Some(empty)`, so they are different. -pub(crate) type Memoize = Rc>>>>; - #[derive(Clone)] pub(crate) struct RewriteContext<'a> { pub(crate) parse_sess: &'a ParseSess, pub(crate) config: &'a Config, - pub(crate) memoize: Memoize, pub(crate) inside_macro: Rc>, // Force block indent style even if we are using visual indent style. pub(crate) use_block: Cell, diff --git a/src/shape.rs b/src/shape.rs index b3f785a9470ee..4376fd12b5260 100644 --- a/src/shape.rs +++ b/src/shape.rs @@ -4,7 +4,7 @@ use std::ops::{Add, Sub}; use crate::Config; -#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Copy, Clone, Debug)] pub(crate) struct Indent { // Width of the block indent, in characters. Must be a multiple of // Config::tab_spaces. @@ -139,7 +139,7 @@ impl Sub for Indent { // 8096 is close enough to infinite for rustfmt. const INFINITE_SHAPE_WIDTH: usize = 8096; -#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Copy, Clone, Debug)] pub(crate) struct Shape { pub(crate) width: usize, // The current indentation of code. diff --git a/src/visitor.rs b/src/visitor.rs index 3ff56d52f92d6..9a0e0752c12f5 100644 --- a/src/visitor.rs +++ b/src/visitor.rs @@ -17,7 +17,7 @@ use crate::items::{ use crate::macros::{macro_style, rewrite_macro, rewrite_macro_def, MacroPosition}; use crate::modules::Module; use crate::parse::session::ParseSess; -use crate::rewrite::{Memoize, Rewrite, RewriteContext}; +use crate::rewrite::{Rewrite, RewriteContext}; use crate::shape::{Indent, Shape}; use crate::skip::{is_skip_attr, SkipContext}; use crate::source_map::{LineRangeUtils, SpanUtils}; @@ -71,7 +71,6 @@ impl SnippetProvider { pub(crate) struct FmtVisitor<'a> { parent_context: Option<&'a RewriteContext<'a>>, - pub(crate) memoize: Memoize, pub(crate) parse_sess: &'a ParseSess, pub(crate) buffer: String, pub(crate) last_pos: BytePos, @@ -759,7 +758,6 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { ctx.config, ctx.snippet_provider, ctx.report.clone(), - ctx.memoize.clone(), ); visitor.skip_context.update(ctx.skip_context.clone()); visitor.set_parent_context(ctx); @@ -771,12 +769,10 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { config: &'a Config, snippet_provider: &'a SnippetProvider, report: FormatReport, - memoize: Memoize, ) -> FmtVisitor<'a> { FmtVisitor { parent_context: None, parse_sess: parse_session, - memoize, buffer: String::with_capacity(snippet_provider.big_snippet.len() * 2), last_pos: BytePos(0), block_indent: Indent::empty(), @@ -999,7 +995,6 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { RewriteContext { parse_sess: self.parse_sess, config: self.config, - memoize: self.memoize.clone(), inside_macro: Rc::new(Cell::new(false)), use_block: Cell::new(false), is_if_else_block: Cell::new(false), diff --git a/tests/source/configs/doc_comment_code_block_width/100.rs b/tests/source/configs/doc_comment_code_block_width/100.rs new file mode 100644 index 0000000000000..515780761670c --- /dev/null +++ b/tests/source/configs/doc_comment_code_block_width/100.rs @@ -0,0 +1,16 @@ +// rustfmt-format_code_in_doc_comments: true +// rustfmt-doc_comment_code_block_width: 100 + +/// ```rust +/// impl Test { +/// pub const fn from_bytes(v: &[u8]) -> Result { +/// Self::from_bytes_manual_slice(v, 0, v.len() ) +/// } +/// } +/// ``` + +impl Test { + pub const fn from_bytes(v: &[u8]) -> Result { + Self::from_bytes_manual_slice(v, 0, v.len() ) + } +} diff --git a/tests/source/configs/doc_comment_code_block_width/100_greater_max_width.rs b/tests/source/configs/doc_comment_code_block_width/100_greater_max_width.rs new file mode 100644 index 0000000000000..96505c69714e5 --- /dev/null +++ b/tests/source/configs/doc_comment_code_block_width/100_greater_max_width.rs @@ -0,0 +1,17 @@ +// rustfmt-max_width: 50 +// rustfmt-format_code_in_doc_comments: true +// rustfmt-doc_comment_code_block_width: 100 + +/// ```rust +/// impl Test { +/// pub const fn from_bytes(v: &[u8]) -> Result { +/// Self::from_bytes_manual_slice(v, 0, v.len() ) +/// } +/// } +/// ``` + +impl Test { + pub const fn from_bytes(v: &[u8]) -> Result { + Self::from_bytes_manual_slice(v, 0, v.len() ) + } +} diff --git a/tests/source/configs/doc_comment_code_block_width/50.rs b/tests/source/configs/doc_comment_code_block_width/50.rs new file mode 100644 index 0000000000000..2c6307951c84e --- /dev/null +++ b/tests/source/configs/doc_comment_code_block_width/50.rs @@ -0,0 +1,16 @@ +// rustfmt-format_code_in_doc_comments: true +// rustfmt-doc_comment_code_block_width: 50 + +/// ```rust +/// impl Test { +/// pub const fn from_bytes(v: &[u8]) -> Result { +/// Self::from_bytes_manual_slice(v, 0, v.len() ) +/// } +/// } +/// ``` + +impl Test { + pub const fn from_bytes(v: &[u8]) -> Result { + Self::from_bytes_manual_slice(v, 0, v.len() ) + } +} diff --git a/tests/source/imports_raw_identifiers/version_One.rs b/tests/source/imports_raw_identifiers/version_One.rs new file mode 100644 index 0000000000000..bc4b5b135696a --- /dev/null +++ b/tests/source/imports_raw_identifiers/version_One.rs @@ -0,0 +1,5 @@ +// rustfmt-version:One + +use websocket::client::ClientBuilder; +use websocket::r#async::futures::Stream; +use websocket::result::WebSocketError; diff --git a/tests/source/imports_raw_identifiers/version_Two.rs b/tests/source/imports_raw_identifiers/version_Two.rs new file mode 100644 index 0000000000000..88e7fbd01ca6e --- /dev/null +++ b/tests/source/imports_raw_identifiers/version_Two.rs @@ -0,0 +1,5 @@ +// rustfmt-version:Two + +use websocket::client::ClientBuilder; +use websocket::r#async::futures::Stream; +use websocket::result::WebSocketError; diff --git a/tests/source/performance/issue-4476.rs b/tests/source/performance/issue-4476.rs deleted file mode 100644 index 8da3f19b62d60..0000000000000 --- a/tests/source/performance/issue-4476.rs +++ /dev/null @@ -1,638 +0,0 @@ -use super::SemverParser; - -#[allow(dead_code, non_camel_case_types)] -#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] -pub enum Rule { - EOI, - range_set, - logical_or, - range, - empty, - hyphen, - simple, - primitive, - primitive_op, - partial, - xr, - xr_op, - nr, - tilde, - caret, - qualifier, - parts, - part, - space, -} -#[allow(clippy::all)] -impl ::pest::Parser for SemverParser { - fn parse<'i>( - rule: Rule, - input: &'i str, - ) -> ::std::result::Result<::pest::iterators::Pairs<'i, Rule>, ::pest::error::Error> { - mod rules { - pub mod hidden { - use super::super::Rule; - #[inline] - #[allow(dead_code, non_snake_case, unused_variables)] - pub fn skip( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - Ok(state) - } - } - pub mod visible { - use super::super::Rule; - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn range_set( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::range_set, |state| { - state.sequence(|state| { - self::SOI(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state).and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::range(state)) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - state - .sequence(|state| { - self::logical_or(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::range(state)) - }) - .and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state).and_then(|state| { - state.sequence(|state| { - self::logical_or(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::range(state)) - }) - }) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state).and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::EOI(state)) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn logical_or( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::logical_or, |state| { - state.sequence(|state| { - state - .sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state).and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| state.match_string("||")) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state).and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn range( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::range, |state| { - self::hyphen(state) - .or_else(|state| { - state.sequence(|state| { - self::simple(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - state - .sequence(|state| { - state - .optional(|state| state.match_string(",")) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - self::space(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state) - .and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::simple(state)) - }) - .and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state).and_then(|state| { - state.sequence(|state| { - state - .optional(|state| state.match_string(",")) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - self::space(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state) - .and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::simple(state)) - }) - }) - }) - }) - }) - }) - }) - }) - }) - }) - .or_else(|state| self::empty(state)) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn empty( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::empty, |state| state.match_string("")) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn hyphen( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::hyphen, |state| { - state.sequence(|state| { - self::partial(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - self::space(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state).and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| state.match_string("-")) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - self::space(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state).and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::partial(state)) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn simple( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::simple, |state| { - self::primitive(state) - .or_else(|state| self::partial(state)) - .or_else(|state| self::tilde(state)) - .or_else(|state| self::caret(state)) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn primitive( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::primitive, |state| { - state.sequence(|state| { - self::primitive_op(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state).and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::partial(state)) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn primitive_op( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::primitive_op, |state| { - state - .match_string("<=") - .or_else(|state| state.match_string(">=")) - .or_else(|state| state.match_string(">")) - .or_else(|state| state.match_string("<")) - .or_else(|state| state.match_string("=")) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn partial( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::partial, |state| { - state.sequence(|state| { - self::xr(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.optional(|state| { - state.sequence(|state| { - state - .match_string(".") - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::xr(state)) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.optional(|state| { - state.sequence(|state| { - state - .match_string(".") - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::xr(state)) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| state.optional(|state| self::qualifier(state))) - }) - }) - }) - }) - }) - }) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn xr( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::xr, |state| { - self::xr_op(state).or_else(|state| self::nr(state)) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn xr_op( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::xr_op, |state| { - state - .match_string("x") - .or_else(|state| state.match_string("X")) - .or_else(|state| state.match_string("*")) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn nr( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::nr, |state| { - state.match_string("0").or_else(|state| { - state.sequence(|state| { - state - .match_range('1'..'9') - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - state.match_range('0'..'9').and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state) - .and_then(|state| state.match_range('0'..'9')) - }) - }) - }) - }) - }) - }) - }) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn tilde( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::tilde, |state| { - state.sequence(|state| { - state - .match_string("~>") - .or_else(|state| state.match_string("~")) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state).and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::partial(state)) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn caret( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::caret, |state| { - state.sequence(|state| { - state - .match_string("^") - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state).and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::partial(state)) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn qualifier( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::qualifier, |state| { - state.sequence(|state| { - state - .match_string("-") - .or_else(|state| state.match_string("+")) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::parts(state)) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn parts( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::parts, |state| { - state.sequence(|state| { - self::part(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - state - .sequence(|state| { - state - .match_string(".") - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::part(state)) - }) - .and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state).and_then(|state| { - state.sequence(|state| { - state - .match_string(".") - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::part(state)) - }) - }) - }) - }) - }) - }) - }) - }) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn part( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::part, |state| { - self::nr(state).or_else(|state| { - state.sequence(|state| { - state - .match_string("-") - .or_else(|state| state.match_range('0'..'9')) - .or_else(|state| state.match_range('A'..'Z')) - .or_else(|state| state.match_range('a'..'z')) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - state - .match_string("-") - .or_else(|state| state.match_range('0'..'9')) - .or_else(|state| state.match_range('A'..'Z')) - .or_else(|state| state.match_range('a'..'z')) - .and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state).and_then(|state| { - state - .match_string("-") - .or_else(|state| state.match_range('0'..'9')) - .or_else(|state| state.match_range('A'..'Z')) - .or_else(|state| state.match_range('a'..'z')) - }) - }) - }) - }) - }) - }) - }) - }) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn space( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state - .match_string(" ") - .or_else(|state| state.match_string("\t")) - } - #[inline] - #[allow(dead_code, non_snake_case, unused_variables)] - pub fn EOI( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::EOI, |state| state.end_of_input()) - } - #[inline] - #[allow(dead_code, non_snake_case, unused_variables)] - pub fn SOI( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.start_of_input() - } - } - pub use self::visible::*; - } - ::pest::state(input, |state| match rule { - Rule::range_set => rules::range_set(state), - Rule::logical_or => rules::logical_or(state), - Rule::range => rules::range(state), - Rule::empty => rules::empty(state), - Rule::hyphen => rules::hyphen(state), - Rule::simple => rules::simple(state), - Rule::primitive => rules::primitive(state), - Rule::primitive_op => rules::primitive_op(state), - Rule::partial => rules::partial(state), - Rule::xr => rules::xr(state), - Rule::xr_op => rules::xr_op(state), - Rule::nr => rules::nr(state), - Rule::tilde => rules::tilde(state), - Rule::caret => rules::caret(state), - Rule::qualifier => rules::qualifier(state), - Rule::parts => rules::parts(state), - Rule::part => rules::part(state), - Rule::space => rules::space(state), - Rule::EOI => rules::EOI(state), - }) - } -} \ No newline at end of file diff --git a/tests/source/performance/issue-5128.rs b/tests/source/performance/issue-5128.rs deleted file mode 100644 index 3adce49601c0c..0000000000000 --- a/tests/source/performance/issue-5128.rs +++ /dev/null @@ -1,5127 +0,0 @@ - -fn takes_a_long_time_to_rustfmt() { - let inner_cte = vec![Node { - node: Some(node::Node::CommonTableExpr(Box::new(CommonTableExpr { - ctename: String::from("ranked_by_age_within_key"), - aliascolnames: vec![], - ctematerialized: CteMaterialize::Default as i32, - ctequery: Some(Box::new(Node { - node: Some(node::Node::SelectStmt(Box::new(SelectStmt { - distinct_clause: vec![], - into_clause: None, - target_list: vec![ - Node { - node: Some(node::Node::ResTarget(Box::new(ResTarget { - name: String::from(""), - indirection: vec![], - val: Some(Box::new(Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::AStar(AStar{})) - }], - location: 80 - })) - })), - location: 80 - }))) - }, - Node { - node: Some(node::Node::ResTarget(Box::new(ResTarget { - name: String::from("rank_in_key"), - indirection: vec![], - val: Some(Box::new(Node { - node: Some(node::Node::FuncCall(Box::new(FuncCall { - funcname: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("row_number") - })) - }], - args: vec![], - agg_order: vec![], - agg_filter: None, - agg_within_group: false, - agg_star: false, - agg_distinct: false, - func_variadic: false, - over: Some(Box::new(WindowDef { - name: String::from(""), - refname: String::from(""), - partition_clause: vec![ - Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("synthetic_key") - })) - }], location: 123 - })) - }], order_clause: vec![Node { - node: Some(node::Node::SortBy(Box::new(SortBy { - node: Some(Box::new(Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("logical_timestamp") - })) - }], location: 156 - })) - })), - sortby_dir: SortByDir::SortbyDesc as i32, - sortby_nulls: SortByNulls::SortbyNullsDefault as i32, - use_op: vec![], - location: -1 - }))) - }], frame_options: 1058, start_offset: None, end_offset: None, location: 109 - })), - location: 91 - }))) - })), - location: 91 - }))) - }], - from_clause: vec![Node { - node: Some(node::Node::RangeVar(RangeVar { - catalogname: String::from(""), schemaname: String::from("_supertables"), relname: String::from("9999-9999-9999"), inh: true, relpersistence: String::from("p"), alias: None, location: 206 - })) - }], - where_clause: Some(Box::new(Node { - node: Some(node::Node::AExpr(Box::new(AExpr { - kind: AExprKind::AexprOp as i32, - name: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("<=") - })) - }], - lexpr: Some(Box::new(Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("logical_timestamp") - })) - }], - location: 250 - })) - })), - rexpr: Some(Box::new(Node { - node: Some(node::Node::AConst(Box::new(AConst { - val: Some(Box::new(Node { - node: Some(node::Node::Integer(Integer { - ival: 9000 - })) - })), - location: 271 - }))) - })), - location: 268 - }))) - })), - group_clause: vec![], - having_clause: None, - window_clause: vec![], - values_lists: vec![], - sort_clause: vec![], - limit_offset: None, - limit_count: None, - limit_option: LimitOption::Default as i32, - locking_clause: vec![], - with_clause: None, - op: SetOperation::SetopNone as i32, - all: false, - larg: None, - rarg: None - }))), - })), - location: 29, - cterecursive: false, - cterefcount: 0, - ctecolnames: vec![], - ctecoltypes: vec![], - ctecoltypmods: vec![], - ctecolcollations: vec![], - }))), - }]; - let outer_cte = vec![Node { - node: Some(node::Node::CommonTableExpr(Box::new(CommonTableExpr { - ctename: String::from("table_name"), - aliascolnames: vec![], - ctematerialized: CteMaterialize::Default as i32, - ctequery: Some(Box::new(Node { - node: Some(node::Node::SelectStmt(Box::new(SelectStmt { - distinct_clause: vec![], - into_clause: None, - target_list: vec![ - Node { - node: Some(node::Node::ResTarget(Box::new(ResTarget { - name: String::from("column1"), - indirection: vec![], - val: Some(Box::new(Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("c1"), - })), - }], - location: 301, - })), - })), - location: 301, - }))), - }, - Node { - node: Some(node::Node::ResTarget(Box::new(ResTarget { - name: String::from("column2"), - indirection: vec![], - val: Some(Box::new(Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("c2"), - })), - }], - location: 324, - })), - })), - location: 324, - }))), - }, - ], - from_clause: vec![Node { - node: Some(node::Node::RangeVar(RangeVar { - catalogname: String::from(""), - schemaname: String::from(""), - relname: String::from("ranked_by_age_within_key"), - inh: true, - relpersistence: String::from("p"), - alias: None, - location: 347, - })), - }], - where_clause: Some(Box::new(Node { - node: Some(node::Node::BoolExpr(Box::new(BoolExpr { - xpr: None, - boolop: BoolExprType::AndExpr as i32, - args: vec![ - Node { - node: Some(node::Node::AExpr(Box::new(AExpr { - kind: AExprKind::AexprOp as i32, - name: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("="), - })), - }], - lexpr: Some(Box::new(Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::String( - String2 { - str: String::from("rank_in_key"), - }, - )), - }], - location: 382, - })), - })), - rexpr: Some(Box::new(Node { - node: Some(node::Node::AConst(Box::new(AConst { - val: Some(Box::new(Node { - node: Some(node::Node::Integer( - Integer { ival: 1 }, - )), - })), - location: 396, - }))), - })), - location: 394, - }))), - }, - Node { - node: Some(node::Node::AExpr(Box::new(AExpr { - kind: AExprKind::AexprOp as i32, - name: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("="), - })), - }], - lexpr: Some(Box::new(Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::String( - String2 { - str: String::from("is_deleted"), - }, - )), - }], - location: 402, - })), - })), - rexpr: Some(Box::new(Node { - node: Some(node::Node::TypeCast(Box::new( - TypeCast { - arg: Some(Box::new(Node { - node: Some(node::Node::AConst( - Box::new(AConst { - val: Some(Box::new(Node { - node: Some( - node::Node::String( - String2 { - str: - String::from( - "f", - ), - }, - ), - ), - })), - location: 415, - }), - )), - })), - type_name: Some(TypeName { - names: vec![ - Node { - node: Some(node::Node::String( - String2 { - str: String::from( - "pg_catalog", - ), - }, - )), - }, - Node { - node: Some(node::Node::String( - String2 { - str: String::from( - "bool", - ), - }, - )), - }, - ], - type_oid: 0, - setof: false, - pct_type: false, - typmods: vec![], - typemod: -1, - array_bounds: vec![], - location: -1, - }), - location: -1, - }, - ))), - })), - location: 413, - }))), - }, - ], - location: 398, - }))), - })), - group_clause: vec![], - having_clause: None, - window_clause: vec![], - values_lists: vec![], - sort_clause: vec![], - limit_offset: None, - limit_count: None, - limit_option: LimitOption::Default as i32, - locking_clause: vec![], - with_clause: Some(WithClause { - ctes: inner_cte, - recursive: false, - location: 24, - }), - op: SetOperation::SetopNone as i32, - all: false, - larg: None, - rarg: None, - }))), - })), - location: 5, - cterecursive: false, - cterefcount: 0, - ctecolnames: vec![], - ctecoltypes: vec![], - ctecoltypmods: vec![], - ctecolcollations: vec![], - }))), - }]; - let expected_result = ParseResult { - version: 130003, - stmts: vec![RawStmt { - stmt: Some(Box::new(Node { - node: Some(node::Node::SelectStmt(Box::new(SelectStmt { - distinct_clause: vec![], - into_clause: None, - - target_list: vec![Node { - node: Some(node::Node::ResTarget(Box::new(ResTarget { - name: String::from(""), - indirection: vec![], - val: Some(Box::new(Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("column1"), - })), - }], - location: 430, - })), - })), - location: 430, - }))), - }], - from_clause: vec![Node { - node: Some(node::Node::RangeVar(RangeVar { - catalogname: String::from(""), - schemaname: String::from(""), - relname: String::from("table_name"), - inh: true, - relpersistence: String::from("p"), - alias: None, - location: 443, - })), - }], - where_clause: Some(Box::new(Node { - node: Some(node::Node::AExpr(Box::new(AExpr { - kind: AExprKind::AexprOp as i32, - name: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from(">"), - })), - }], - lexpr: Some(Box::new(Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("column2"), - })), - }], - location: 460, - })), - })), - rexpr: Some(Box::new(Node { - node: Some(node::Node::AConst(Box::new(AConst { - val: Some(Box::new(Node { - node: Some(node::Node::Integer(Integer { - ival: 9000, - })), - })), - location: 470, - }))), - })), - location: 468, - }))), - })), - group_clause: vec![], - having_clause: None, - window_clause: vec![], - values_lists: vec![], - sort_clause: vec![], - limit_offset: None, - limit_count: None, - limit_option: LimitOption::Default as i32, - locking_clause: vec![], - with_clause: Some(WithClause { - ctes: outer_cte, - recursive: false, - location: 0, - }), - op: SetOperation::SetopNone as i32, - all: false, - larg: None, - rarg: None, - }))), - })), - stmt_location: 0, - stmt_len: 0, - }], - }; - -} -#[derive(Clone, PartialEq)] -pub struct ParseResult { - - pub version: i32, - - pub stmts: Vec, -} -#[derive(Clone, PartialEq)] -pub struct ScanResult { - - pub version: i32, - - pub tokens: Vec, -} -#[derive(Clone, PartialEq)] -pub struct Node { - pub node: ::core::option::Option, -} -/// Nested message and enum types in `Node`. -pub mod node { - #[derive(Clone, PartialEq)] - pub enum Node { - - Alias(super::Alias), - - RangeVar(super::RangeVar), - - TableFunc(Box), - - Expr(super::Expr), - - Var(Box), - - Param(Box), - - Aggref(Box), - - GroupingFunc(Box), - - WindowFunc(Box), - - SubscriptingRef(Box), - - FuncExpr(Box), - - NamedArgExpr(Box), - - OpExpr(Box), - - DistinctExpr(Box), - - NullIfExpr(Box), - - ScalarArrayOpExpr(Box), - - BoolExpr(Box), - - SubLink(Box), - - SubPlan(Box), - - AlternativeSubPlan(Box), - - FieldSelect(Box), - - FieldStore(Box), - - RelabelType(Box), - - CoerceViaIo(Box), - - ArrayCoerceExpr(Box), - - ConvertRowtypeExpr(Box), - - CollateExpr(Box), - - CaseExpr(Box), - - CaseWhen(Box), - - CaseTestExpr(Box), - - ArrayExpr(Box), - - RowExpr(Box), - - RowCompareExpr(Box), - - CoalesceExpr(Box), - - MinMaxExpr(Box), - - SqlvalueFunction(Box), - - XmlExpr(Box), - - NullTest(Box), - - BooleanTest(Box), - - CoerceToDomain(Box), - - CoerceToDomainValue(Box), - - SetToDefault(Box), - - CurrentOfExpr(Box), - - NextValueExpr(Box), - - InferenceElem(Box), - - TargetEntry(Box), - - RangeTblRef(super::RangeTblRef), - - JoinExpr(Box), - - FromExpr(Box), - - OnConflictExpr(Box), - - IntoClause(Box), - - RawStmt(Box), - - Query(Box), - - InsertStmt(Box), - - DeleteStmt(Box), - - UpdateStmt(Box), - - SelectStmt(Box), - - AlterTableStmt(super::AlterTableStmt), - - AlterTableCmd(Box), - - AlterDomainStmt(Box), - - SetOperationStmt(Box), - - GrantStmt(super::GrantStmt), - - GrantRoleStmt(super::GrantRoleStmt), - - AlterDefaultPrivilegesStmt(super::AlterDefaultPrivilegesStmt), - - ClosePortalStmt(super::ClosePortalStmt), - - ClusterStmt(super::ClusterStmt), - - CopyStmt(Box), - - CreateStmt(super::CreateStmt), - - DefineStmt(super::DefineStmt), - - DropStmt(super::DropStmt), - - TruncateStmt(super::TruncateStmt), - - CommentStmt(Box), - - FetchStmt(super::FetchStmt), - - IndexStmt(Box), - - CreateFunctionStmt(super::CreateFunctionStmt), - - AlterFunctionStmt(super::AlterFunctionStmt), - - DoStmt(super::DoStmt), - - RenameStmt(Box), - - RuleStmt(Box), - - NotifyStmt(super::NotifyStmt), - - ListenStmt(super::ListenStmt), - - UnlistenStmt(super::UnlistenStmt), - - TransactionStmt(super::TransactionStmt), - - ViewStmt(Box), - - LoadStmt(super::LoadStmt), - - CreateDomainStmt(Box), - - CreatedbStmt(super::CreatedbStmt), - - DropdbStmt(super::DropdbStmt), - - VacuumStmt(super::VacuumStmt), - - ExplainStmt(Box), - - CreateTableAsStmt(Box), - - CreateSeqStmt(super::CreateSeqStmt), - - AlterSeqStmt(super::AlterSeqStmt), - - VariableSetStmt(super::VariableSetStmt), - - VariableShowStmt(super::VariableShowStmt), - - DiscardStmt(super::DiscardStmt), - - CreateTrigStmt(Box), - - CreatePlangStmt(super::CreatePLangStmt), - - CreateRoleStmt(super::CreateRoleStmt), - - AlterRoleStmt(super::AlterRoleStmt), - - DropRoleStmt(super::DropRoleStmt), - - LockStmt(super::LockStmt), - - ConstraintsSetStmt(super::ConstraintsSetStmt), - - ReindexStmt(super::ReindexStmt), - - CheckPointStmt(super::CheckPointStmt), - - CreateSchemaStmt(super::CreateSchemaStmt), - - AlterDatabaseStmt(super::AlterDatabaseStmt), - - AlterDatabaseSetStmt(super::AlterDatabaseSetStmt), - - AlterRoleSetStmt(super::AlterRoleSetStmt), - - CreateConversionStmt(super::CreateConversionStmt), - - CreateCastStmt(super::CreateCastStmt), - - CreateOpClassStmt(super::CreateOpClassStmt), - - CreateOpFamilyStmt(super::CreateOpFamilyStmt), - - AlterOpFamilyStmt(super::AlterOpFamilyStmt), - - PrepareStmt(Box), - - ExecuteStmt(super::ExecuteStmt), - - DeallocateStmt(super::DeallocateStmt), - - DeclareCursorStmt(Box), - - CreateTableSpaceStmt(super::CreateTableSpaceStmt), - - DropTableSpaceStmt(super::DropTableSpaceStmt), - - AlterObjectDependsStmt(Box), - - AlterObjectSchemaStmt(Box), - - AlterOwnerStmt(Box), - - AlterOperatorStmt(super::AlterOperatorStmt), - - AlterTypeStmt(super::AlterTypeStmt), - - DropOwnedStmt(super::DropOwnedStmt), - - ReassignOwnedStmt(super::ReassignOwnedStmt), - - CompositeTypeStmt(super::CompositeTypeStmt), - - CreateEnumStmt(super::CreateEnumStmt), - - CreateRangeStmt(super::CreateRangeStmt), - - AlterEnumStmt(super::AlterEnumStmt), - - AlterTsdictionaryStmt(super::AlterTsDictionaryStmt), - - AlterTsconfigurationStmt(super::AlterTsConfigurationStmt), - - CreateFdwStmt(super::CreateFdwStmt), - - AlterFdwStmt(super::AlterFdwStmt), - - CreateForeignServerStmt(super::CreateForeignServerStmt), - - AlterForeignServerStmt(super::AlterForeignServerStmt), - - CreateUserMappingStmt(super::CreateUserMappingStmt), - - AlterUserMappingStmt(super::AlterUserMappingStmt), - - DropUserMappingStmt(super::DropUserMappingStmt), - - AlterTableSpaceOptionsStmt(super::AlterTableSpaceOptionsStmt), - - AlterTableMoveAllStmt(super::AlterTableMoveAllStmt), - - SecLabelStmt(Box), - - CreateForeignTableStmt(super::CreateForeignTableStmt), - - ImportForeignSchemaStmt(super::ImportForeignSchemaStmt), - - CreateExtensionStmt(super::CreateExtensionStmt), - - AlterExtensionStmt(super::AlterExtensionStmt), - - AlterExtensionContentsStmt(Box), - - CreateEventTrigStmt(super::CreateEventTrigStmt), - - AlterEventTrigStmt(super::AlterEventTrigStmt), - - RefreshMatViewStmt(super::RefreshMatViewStmt), - - ReplicaIdentityStmt(super::ReplicaIdentityStmt), - - AlterSystemStmt(super::AlterSystemStmt), - - CreatePolicyStmt(Box), - - AlterPolicyStmt(Box), - - CreateTransformStmt(super::CreateTransformStmt), - - CreateAmStmt(super::CreateAmStmt), - - CreatePublicationStmt(super::CreatePublicationStmt), - - AlterPublicationStmt(super::AlterPublicationStmt), - - CreateSubscriptionStmt(super::CreateSubscriptionStmt), - - AlterSubscriptionStmt(super::AlterSubscriptionStmt), - - DropSubscriptionStmt(super::DropSubscriptionStmt), - - CreateStatsStmt(super::CreateStatsStmt), - - AlterCollationStmt(super::AlterCollationStmt), - - CallStmt(Box), - - AlterStatsStmt(super::AlterStatsStmt), - - AExpr(Box), - - ColumnRef(super::ColumnRef), - - ParamRef(super::ParamRef), - - AConst(Box), - - FuncCall(Box), - - AStar(super::AStar), - - AIndices(Box), - - AIndirection(Box), - - AArrayExpr(super::AArrayExpr), - - ResTarget(Box), - - MultiAssignRef(Box), - - TypeCast(Box), - - CollateClause(Box), - - SortBy(Box), - - WindowDef(Box), - - RangeSubselect(Box), - - RangeFunction(super::RangeFunction), - - RangeTableSample(Box), - - RangeTableFunc(Box), - - RangeTableFuncCol(Box), - - TypeName(super::TypeName), - - ColumnDef(Box), - - IndexElem(Box), - - Constraint(Box), - - DefElem(Box), - - RangeTblEntry(Box), - - RangeTblFunction(Box), - - TableSampleClause(Box), - - WithCheckOption(Box), - - SortGroupClause(super::SortGroupClause), - - GroupingSet(super::GroupingSet), - - WindowClause(Box), - - ObjectWithArgs(super::ObjectWithArgs), - - AccessPriv(super::AccessPriv), - - CreateOpClassItem(super::CreateOpClassItem), - - TableLikeClause(super::TableLikeClause), - - FunctionParameter(Box), - - LockingClause(super::LockingClause), - - RowMarkClause(super::RowMarkClause), - - XmlSerialize(Box), - - WithClause(super::WithClause), - - InferClause(Box), - - OnConflictClause(Box), - - CommonTableExpr(Box), - - RoleSpec(super::RoleSpec), - - TriggerTransition(super::TriggerTransition), - - PartitionElem(Box), - - PartitionSpec(super::PartitionSpec), - - PartitionBoundSpec(super::PartitionBoundSpec), - - PartitionRangeDatum(Box), - - PartitionCmd(super::PartitionCmd), - - VacuumRelation(super::VacuumRelation), - - InlineCodeBlock(super::InlineCodeBlock), - - CallContext(super::CallContext), - - Integer(super::Integer), - - Float(super::Float), - - String(super::String2), - - BitString(super::BitString), - - Null(super::Null), - - List(super::List), - - IntList(super::IntList), - - OidList(super::OidList), - } -} -#[derive(Clone, PartialEq)] -pub struct Integer { - /// machine integer - - pub ival: i32, -} -#[derive(Clone, PartialEq)] -pub struct Float { - /// string - - pub str: String, -} -#[derive(Clone, PartialEq)] -pub struct String2 { - /// string - - pub str: String, -} -#[derive(Clone, PartialEq)] -pub struct BitString { - /// string - - pub str: String, -} -/// intentionally empty -#[derive(Clone, PartialEq)] -pub struct Null {} -#[derive(Clone, PartialEq)] -pub struct List { - - pub items: Vec, -} -#[derive(Clone, PartialEq)] -pub struct OidList { - - pub items: Vec, -} -#[derive(Clone, PartialEq)] -pub struct IntList { - - pub items: Vec, -} -#[derive(Clone, PartialEq)] -pub struct Alias { - - pub aliasname: String, - - pub colnames: Vec, -} -#[derive(Clone, PartialEq)] -pub struct RangeVar { - - pub catalogname: String, - - pub schemaname: String, - - pub relname: String, - - pub inh: bool, - - pub relpersistence: String, - - pub alias: ::core::option::Option, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct TableFunc { - - pub ns_uris: Vec, - - pub ns_names: Vec, - - pub docexpr: ::core::option::Option>, - - pub rowexpr: ::core::option::Option>, - - pub colnames: Vec, - - pub coltypes: Vec, - - pub coltypmods: Vec, - - pub colcollations: Vec, - - pub colexprs: Vec, - - pub coldefexprs: Vec, - - pub notnulls: Vec, - - pub ordinalitycol: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct Expr {} -#[derive(Clone, PartialEq)] -pub struct Var { - - pub xpr: ::core::option::Option>, - - pub varno: u32, - - pub varattno: i32, - - pub vartype: u32, - - pub vartypmod: i32, - - pub varcollid: u32, - - pub varlevelsup: u32, - - pub varnosyn: u32, - - pub varattnosyn: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct Param { - - pub xpr: ::core::option::Option>, - - pub paramkind: i32, - - pub paramid: i32, - - pub paramtype: u32, - - pub paramtypmod: i32, - - pub paramcollid: u32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct Aggref { - - pub xpr: ::core::option::Option>, - - pub aggfnoid: u32, - - pub aggtype: u32, - - pub aggcollid: u32, - - pub inputcollid: u32, - - pub aggtranstype: u32, - - pub aggargtypes: Vec, - - pub aggdirectargs: Vec, - - pub args: Vec, - - pub aggorder: Vec, - - pub aggdistinct: Vec, - - pub aggfilter: ::core::option::Option>, - - pub aggstar: bool, - - pub aggvariadic: bool, - - pub aggkind: String, - - pub agglevelsup: u32, - - pub aggsplit: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct GroupingFunc { - - pub xpr: ::core::option::Option>, - - pub args: Vec, - - pub refs: Vec, - - pub cols: Vec, - - pub agglevelsup: u32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct WindowFunc { - - pub xpr: ::core::option::Option>, - - pub winfnoid: u32, - - pub wintype: u32, - - pub wincollid: u32, - - pub inputcollid: u32, - - pub args: Vec, - - pub aggfilter: ::core::option::Option>, - - pub winref: u32, - - pub winstar: bool, - - pub winagg: bool, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct SubscriptingRef { - - pub xpr: ::core::option::Option>, - - pub refcontainertype: u32, - - pub refelemtype: u32, - - pub reftypmod: i32, - - pub refcollid: u32, - - pub refupperindexpr: Vec, - - pub reflowerindexpr: Vec, - - pub refexpr: ::core::option::Option>, - - pub refassgnexpr: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct FuncExpr { - - pub xpr: ::core::option::Option>, - - pub funcid: u32, - - pub funcresulttype: u32, - - pub funcretset: bool, - - pub funcvariadic: bool, - - pub funcformat: i32, - - pub funccollid: u32, - - pub inputcollid: u32, - - pub args: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct NamedArgExpr { - - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub name: String, - - pub argnumber: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct OpExpr { - - pub xpr: ::core::option::Option>, - - pub opno: u32, - - pub opfuncid: u32, - - pub opresulttype: u32, - - pub opretset: bool, - - pub opcollid: u32, - - pub inputcollid: u32, - - pub args: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct DistinctExpr { - - pub xpr: ::core::option::Option>, - - pub opno: u32, - - pub opfuncid: u32, - - pub opresulttype: u32, - - pub opretset: bool, - - pub opcollid: u32, - - pub inputcollid: u32, - - pub args: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct NullIfExpr { - - pub xpr: ::core::option::Option>, - - pub opno: u32, - - pub opfuncid: u32, - - pub opresulttype: u32, - - pub opretset: bool, - - pub opcollid: u32, - - pub inputcollid: u32, - - pub args: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct ScalarArrayOpExpr { - - pub xpr: ::core::option::Option>, - - pub opno: u32, - - pub opfuncid: u32, - - pub use_or: bool, - - pub inputcollid: u32, - - pub args: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct BoolExpr { - - pub xpr: ::core::option::Option>, - - pub boolop: i32, - - pub args: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct SubLink { - - pub xpr: ::core::option::Option>, - - pub sub_link_type: i32, - - pub sub_link_id: i32, - - pub testexpr: ::core::option::Option>, - - pub oper_name: Vec, - - pub subselect: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct SubPlan { - - pub xpr: ::core::option::Option>, - - pub sub_link_type: i32, - - pub testexpr: ::core::option::Option>, - - pub param_ids: Vec, - - pub plan_id: i32, - - pub plan_name: String, - - pub first_col_type: u32, - - pub first_col_typmod: i32, - - pub first_col_collation: u32, - - pub use_hash_table: bool, - - pub unknown_eq_false: bool, - - pub parallel_safe: bool, - - pub set_param: Vec, - - pub par_param: Vec, - - pub args: Vec, - - pub startup_cost: f64, - - pub per_call_cost: f64, -} -#[derive(Clone, PartialEq)] -pub struct AlternativeSubPlan { - - pub xpr: ::core::option::Option>, - - pub subplans: Vec, -} -#[derive(Clone, PartialEq)] -pub struct FieldSelect { - - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub fieldnum: i32, - - pub resulttype: u32, - - pub resulttypmod: i32, - - pub resultcollid: u32, -} -#[derive(Clone, PartialEq)] -pub struct FieldStore { - - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub newvals: Vec, - - pub fieldnums: Vec, - - pub resulttype: u32, -} -#[derive(Clone, PartialEq)] -pub struct RelabelType { - - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub resulttype: u32, - - pub resulttypmod: i32, - - pub resultcollid: u32, - - pub relabelformat: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CoerceViaIo { - - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub resulttype: u32, - - pub resultcollid: u32, - - pub coerceformat: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct ArrayCoerceExpr { - - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub elemexpr: ::core::option::Option>, - - pub resulttype: u32, - - pub resulttypmod: i32, - - pub resultcollid: u32, - - pub coerceformat: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct ConvertRowtypeExpr { - - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub resulttype: u32, - - pub convertformat: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CollateExpr { - - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub coll_oid: u32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CaseExpr { - - pub xpr: ::core::option::Option>, - - pub casetype: u32, - - pub casecollid: u32, - - pub arg: ::core::option::Option>, - - pub args: Vec, - - pub defresult: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CaseWhen { - - pub xpr: ::core::option::Option>, - - pub expr: ::core::option::Option>, - - pub result: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CaseTestExpr { - - pub xpr: ::core::option::Option>, - - pub type_id: u32, - - pub type_mod: i32, - - pub collation: u32, -} -#[derive(Clone, PartialEq)] -pub struct ArrayExpr { - - pub xpr: ::core::option::Option>, - - pub array_typeid: u32, - - pub array_collid: u32, - - pub element_typeid: u32, - - pub elements: Vec, - - pub multidims: bool, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct RowExpr { - - pub xpr: ::core::option::Option>, - - pub args: Vec, - - pub row_typeid: u32, - - pub row_format: i32, - - pub colnames: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct RowCompareExpr { - - pub xpr: ::core::option::Option>, - - pub rctype: i32, - - pub opnos: Vec, - - pub opfamilies: Vec, - - pub inputcollids: Vec, - - pub largs: Vec, - - pub rargs: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CoalesceExpr { - - pub xpr: ::core::option::Option>, - - pub coalescetype: u32, - - pub coalescecollid: u32, - - pub args: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct MinMaxExpr { - - pub xpr: ::core::option::Option>, - - pub minmaxtype: u32, - - pub minmaxcollid: u32, - - pub inputcollid: u32, - - pub op: i32, - - pub args: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct SqlValueFunction { - - pub xpr: ::core::option::Option>, - - pub op: i32, - - pub r#type: u32, - - pub typmod: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct XmlExpr { - - pub xpr: ::core::option::Option>, - - pub op: i32, - - pub name: String, - - pub named_args: Vec, - - pub arg_names: Vec, - - pub args: Vec, - - pub xmloption: i32, - - pub r#type: u32, - - pub typmod: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct NullTest { - - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub nulltesttype: i32, - - pub argisrow: bool, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct BooleanTest { - - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub booltesttype: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CoerceToDomain { - - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub resulttype: u32, - - pub resulttypmod: i32, - - pub resultcollid: u32, - - pub coercionformat: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CoerceToDomainValue { - - pub xpr: ::core::option::Option>, - - pub type_id: u32, - - pub type_mod: i32, - - pub collation: u32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct SetToDefault { - - pub xpr: ::core::option::Option>, - - pub type_id: u32, - - pub type_mod: i32, - - pub collation: u32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CurrentOfExpr { - - pub xpr: ::core::option::Option>, - - pub cvarno: u32, - - pub cursor_name: String, - - pub cursor_param: i32, -} -#[derive(Clone, PartialEq)] -pub struct NextValueExpr { - - pub xpr: ::core::option::Option>, - - pub seqid: u32, - - pub type_id: u32, -} -#[derive(Clone, PartialEq)] -pub struct InferenceElem { - - pub xpr: ::core::option::Option>, - - pub expr: ::core::option::Option>, - - pub infercollid: u32, - - pub inferopclass: u32, -} -#[derive(Clone, PartialEq)] -pub struct TargetEntry { - - pub xpr: ::core::option::Option>, - - pub expr: ::core::option::Option>, - - pub resno: i32, - - pub resname: String, - - pub ressortgroupref: u32, - - pub resorigtbl: u32, - - pub resorigcol: i32, - - pub resjunk: bool, -} -#[derive(Clone, PartialEq)] -pub struct RangeTblRef { - - pub rtindex: i32, -} -#[derive(Clone, PartialEq)] -pub struct JoinExpr { - - pub jointype: i32, - - pub is_natural: bool, - - pub larg: ::core::option::Option>, - - pub rarg: ::core::option::Option>, - - pub using_clause: Vec, - - pub quals: ::core::option::Option>, - - pub alias: ::core::option::Option, - - pub rtindex: i32, -} -#[derive(Clone, PartialEq)] -pub struct FromExpr { - - pub fromlist: Vec, - - pub quals: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct OnConflictExpr { - - pub action: i32, - - pub arbiter_elems: Vec, - - pub arbiter_where: ::core::option::Option>, - - pub constraint: u32, - - pub on_conflict_set: Vec, - - pub on_conflict_where: ::core::option::Option>, - - pub excl_rel_index: i32, - - pub excl_rel_tlist: Vec, -} -#[derive(Clone, PartialEq)] -pub struct IntoClause { - - pub rel: ::core::option::Option, - - pub col_names: Vec, - - pub access_method: String, - - pub options: Vec, - - pub on_commit: i32, - - pub table_space_name: String, - - pub view_query: ::core::option::Option>, - - pub skip_data: bool, -} -#[derive(Clone, PartialEq)] -pub struct RawStmt { - - pub stmt: ::core::option::Option>, - - pub stmt_location: i32, - - pub stmt_len: i32, -} -#[derive(Clone, PartialEq)] -pub struct Query { - - pub command_type: i32, - - pub query_source: i32, - - pub can_set_tag: bool, - - pub utility_stmt: ::core::option::Option>, - - pub result_relation: i32, - - pub has_aggs: bool, - - pub has_window_funcs: bool, - - pub has_target_srfs: bool, - - pub has_sub_links: bool, - - pub has_distinct_on: bool, - - pub has_recursive: bool, - - pub has_modifying_cte: bool, - - pub has_for_update: bool, - - pub has_row_security: bool, - - pub cte_list: Vec, - - pub rtable: Vec, - - pub jointree: ::core::option::Option>, - - pub target_list: Vec, - - pub r#override: i32, - - pub on_conflict: ::core::option::Option>, - - pub returning_list: Vec, - - pub group_clause: Vec, - - pub grouping_sets: Vec, - - pub having_qual: ::core::option::Option>, - - pub window_clause: Vec, - - pub distinct_clause: Vec, - - pub sort_clause: Vec, - - pub limit_offset: ::core::option::Option>, - - pub limit_count: ::core::option::Option>, - - pub limit_option: i32, - - pub row_marks: Vec, - - pub set_operations: ::core::option::Option>, - - pub constraint_deps: Vec, - - pub with_check_options: Vec, - - pub stmt_location: i32, - - pub stmt_len: i32, -} -#[derive(Clone, PartialEq)] -pub struct InsertStmt { - - pub relation: ::core::option::Option, - - pub cols: Vec, - - pub select_stmt: ::core::option::Option>, - - pub on_conflict_clause: ::core::option::Option>, - - pub returning_list: Vec, - - pub with_clause: ::core::option::Option, - - pub r#override: i32, -} -#[derive(Clone, PartialEq)] -pub struct DeleteStmt { - - pub relation: ::core::option::Option, - - pub using_clause: Vec, - - pub where_clause: ::core::option::Option>, - - pub returning_list: Vec, - - pub with_clause: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct UpdateStmt { - - pub relation: ::core::option::Option, - - pub target_list: Vec, - - pub where_clause: ::core::option::Option>, - - pub from_clause: Vec, - - pub returning_list: Vec, - - pub with_clause: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct SelectStmt { - - pub distinct_clause: Vec, - - pub into_clause: ::core::option::Option>, - - pub target_list: Vec, - - pub from_clause: Vec, - - pub where_clause: ::core::option::Option>, - - pub group_clause: Vec, - - pub having_clause: ::core::option::Option>, - - pub window_clause: Vec, - - pub values_lists: Vec, - - pub sort_clause: Vec, - - pub limit_offset: ::core::option::Option>, - - pub limit_count: ::core::option::Option>, - - pub limit_option: i32, - - pub locking_clause: Vec, - - pub with_clause: ::core::option::Option, - - pub op: i32, - - pub all: bool, - - pub larg: ::core::option::Option>, - - pub rarg: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct AlterTableStmt { - - pub relation: ::core::option::Option, - - pub cmds: Vec, - - pub relkind: i32, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterTableCmd { - - pub subtype: i32, - - pub name: String, - - pub num: i32, - - pub newowner: ::core::option::Option, - - pub def: ::core::option::Option>, - - pub behavior: i32, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterDomainStmt { - - pub subtype: String, - - pub type_name: Vec, - - pub name: String, - - pub def: ::core::option::Option>, - - pub behavior: i32, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct SetOperationStmt { - - pub op: i32, - - pub all: bool, - - pub larg: ::core::option::Option>, - - pub rarg: ::core::option::Option>, - - pub col_types: Vec, - - pub col_typmods: Vec, - - pub col_collations: Vec, - - pub group_clauses: Vec, -} -#[derive(Clone, PartialEq)] -pub struct GrantStmt { - - pub is_grant: bool, - - pub targtype: i32, - - pub objtype: i32, - - pub objects: Vec, - - pub privileges: Vec, - - pub grantees: Vec, - - pub grant_option: bool, - - pub behavior: i32, -} -#[derive(Clone, PartialEq)] -pub struct GrantRoleStmt { - - pub granted_roles: Vec, - - pub grantee_roles: Vec, - - pub is_grant: bool, - - pub admin_opt: bool, - - pub grantor: ::core::option::Option, - - pub behavior: i32, -} -#[derive(Clone, PartialEq)] -pub struct AlterDefaultPrivilegesStmt { - - pub options: Vec, - - pub action: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct ClosePortalStmt { - - pub portalname: String, -} -#[derive(Clone, PartialEq)] -pub struct ClusterStmt { - - pub relation: ::core::option::Option, - - pub indexname: String, - - pub options: i32, -} -#[derive(Clone, PartialEq)] -pub struct CopyStmt { - - pub relation: ::core::option::Option, - - pub query: ::core::option::Option>, - - pub attlist: Vec, - - pub is_from: bool, - - pub is_program: bool, - - pub filename: String, - - pub options: Vec, - - pub where_clause: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct CreateStmt { - - pub relation: ::core::option::Option, - - pub table_elts: Vec, - - pub inh_relations: Vec, - - pub partbound: ::core::option::Option, - - pub partspec: ::core::option::Option, - - pub of_typename: ::core::option::Option, - - pub constraints: Vec, - - pub options: Vec, - - pub oncommit: i32, - - pub tablespacename: String, - - pub access_method: String, - - pub if_not_exists: bool, -} -#[derive(Clone, PartialEq)] -pub struct DefineStmt { - - pub kind: i32, - - pub oldstyle: bool, - - pub defnames: Vec, - - pub args: Vec, - - pub definition: Vec, - - pub if_not_exists: bool, - - pub replace: bool, -} -#[derive(Clone, PartialEq)] -pub struct DropStmt { - - pub objects: Vec, - - pub remove_type: i32, - - pub behavior: i32, - - pub missing_ok: bool, - - pub concurrent: bool, -} -#[derive(Clone, PartialEq)] -pub struct TruncateStmt { - - pub relations: Vec, - - pub restart_seqs: bool, - - pub behavior: i32, -} -#[derive(Clone, PartialEq)] -pub struct CommentStmt { - - pub objtype: i32, - - pub object: ::core::option::Option>, - - pub comment: String, -} -#[derive(Clone, PartialEq)] -pub struct FetchStmt { - - pub direction: i32, - - pub how_many: i64, - - pub portalname: String, - - pub ismove: bool, -} -#[derive(Clone, PartialEq)] -pub struct IndexStmt { - - pub idxname: String, - - pub relation: ::core::option::Option, - - pub access_method: String, - - pub table_space: String, - - pub index_params: Vec, - - pub index_including_params: Vec, - - pub options: Vec, - - pub where_clause: ::core::option::Option>, - - pub exclude_op_names: Vec, - - pub idxcomment: String, - - pub index_oid: u32, - - pub old_node: u32, - - pub old_create_subid: u32, - - pub old_first_relfilenode_subid: u32, - - pub unique: bool, - - pub primary: bool, - - pub isconstraint: bool, - - pub deferrable: bool, - - pub initdeferred: bool, - - pub transformed: bool, - - pub concurrent: bool, - - pub if_not_exists: bool, - - pub reset_default_tblspc: bool, -} -#[derive(Clone, PartialEq)] -pub struct CreateFunctionStmt { - - pub is_procedure: bool, - - pub replace: bool, - - pub funcname: Vec, - - pub parameters: Vec, - - pub return_type: ::core::option::Option, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterFunctionStmt { - - pub objtype: i32, - - pub func: ::core::option::Option, - - pub actions: Vec, -} -#[derive(Clone, PartialEq)] -pub struct DoStmt { - - pub args: Vec, -} -#[derive(Clone, PartialEq)] -pub struct RenameStmt { - - pub rename_type: i32, - - pub relation_type: i32, - - pub relation: ::core::option::Option, - - pub object: ::core::option::Option>, - - pub subname: String, - - pub newname: String, - - pub behavior: i32, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct RuleStmt { - - pub relation: ::core::option::Option, - - pub rulename: String, - - pub where_clause: ::core::option::Option>, - - pub event: i32, - - pub instead: bool, - - pub actions: Vec, - - pub replace: bool, -} -#[derive(Clone, PartialEq)] -pub struct NotifyStmt { - - pub conditionname: String, - - pub payload: String, -} -#[derive(Clone, PartialEq)] -pub struct ListenStmt { - - pub conditionname: String, -} -#[derive(Clone, PartialEq)] -pub struct UnlistenStmt { - - pub conditionname: String, -} -#[derive(Clone, PartialEq)] -pub struct TransactionStmt { - - pub kind: i32, - - pub options: Vec, - - pub savepoint_name: String, - - pub gid: String, - - pub chain: bool, -} -#[derive(Clone, PartialEq)] -pub struct ViewStmt { - - pub view: ::core::option::Option, - - pub aliases: Vec, - - pub query: ::core::option::Option>, - - pub replace: bool, - - pub options: Vec, - - pub with_check_option: i32, -} -#[derive(Clone, PartialEq)] -pub struct LoadStmt { - - pub filename: String, -} -#[derive(Clone, PartialEq)] -pub struct CreateDomainStmt { - - pub domainname: Vec, - - pub type_name: ::core::option::Option, - - pub coll_clause: ::core::option::Option>, - - pub constraints: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CreatedbStmt { - - pub dbname: String, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct DropdbStmt { - - pub dbname: String, - - pub missing_ok: bool, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct VacuumStmt { - - pub options: Vec, - - pub rels: Vec, - - pub is_vacuumcmd: bool, -} -#[derive(Clone, PartialEq)] -pub struct ExplainStmt { - - pub query: ::core::option::Option>, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CreateTableAsStmt { - - pub query: ::core::option::Option>, - - pub into: ::core::option::Option>, - - pub relkind: i32, - - pub is_select_into: bool, - - pub if_not_exists: bool, -} -#[derive(Clone, PartialEq)] -pub struct CreateSeqStmt { - - pub sequence: ::core::option::Option, - - pub options: Vec, - - pub owner_id: u32, - - pub for_identity: bool, - - pub if_not_exists: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterSeqStmt { - - pub sequence: ::core::option::Option, - - pub options: Vec, - - pub for_identity: bool, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct VariableSetStmt { - - pub kind: i32, - - pub name: String, - - pub args: Vec, - - pub is_local: bool, -} -#[derive(Clone, PartialEq)] -pub struct VariableShowStmt { - - pub name: String, -} -#[derive(Clone, PartialEq)] -pub struct DiscardStmt { - - pub target: i32, -} -#[derive(Clone, PartialEq)] -pub struct CreateTrigStmt { - - pub trigname: String, - - pub relation: ::core::option::Option, - - pub funcname: Vec, - - pub args: Vec, - - pub row: bool, - - pub timing: i32, - - pub events: i32, - - pub columns: Vec, - - pub when_clause: ::core::option::Option>, - - pub isconstraint: bool, - - pub transition_rels: Vec, - - pub deferrable: bool, - - pub initdeferred: bool, - - pub constrrel: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct CreatePLangStmt { - - pub replace: bool, - - pub plname: String, - - pub plhandler: Vec, - - pub plinline: Vec, - - pub plvalidator: Vec, - - pub pltrusted: bool, -} -#[derive(Clone, PartialEq)] -pub struct CreateRoleStmt { - - pub stmt_type: i32, - - pub role: String, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterRoleStmt { - - pub role: ::core::option::Option, - - pub options: Vec, - - pub action: i32, -} -#[derive(Clone, PartialEq)] -pub struct DropRoleStmt { - - pub roles: Vec, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct LockStmt { - - pub relations: Vec, - - pub mode: i32, - - pub nowait: bool, -} -#[derive(Clone, PartialEq)] -pub struct ConstraintsSetStmt { - - pub constraints: Vec, - - pub deferred: bool, -} -#[derive(Clone, PartialEq)] -pub struct ReindexStmt { - - pub kind: i32, - - pub relation: ::core::option::Option, - - pub name: String, - - pub options: i32, - - pub concurrent: bool, -} -#[derive(Clone, PartialEq)] -pub struct CheckPointStmt {} -#[derive(Clone, PartialEq)] -pub struct CreateSchemaStmt { - - pub schemaname: String, - - pub authrole: ::core::option::Option, - - pub schema_elts: Vec, - - pub if_not_exists: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterDatabaseStmt { - - pub dbname: String, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterDatabaseSetStmt { - - pub dbname: String, - - pub setstmt: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct AlterRoleSetStmt { - - pub role: ::core::option::Option, - - pub database: String, - - pub setstmt: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct CreateConversionStmt { - - pub conversion_name: Vec, - - pub for_encoding_name: String, - - pub to_encoding_name: String, - - pub func_name: Vec, - - pub def: bool, -} -#[derive(Clone, PartialEq)] -pub struct CreateCastStmt { - - pub sourcetype: ::core::option::Option, - - pub targettype: ::core::option::Option, - - pub func: ::core::option::Option, - - pub context: i32, - - pub inout: bool, -} -#[derive(Clone, PartialEq)] -pub struct CreateOpClassStmt { - - pub opclassname: Vec, - - pub opfamilyname: Vec, - - pub amname: String, - - pub datatype: ::core::option::Option, - - pub items: Vec, - - pub is_default: bool, -} -#[derive(Clone, PartialEq)] -pub struct CreateOpFamilyStmt { - - pub opfamilyname: Vec, - - pub amname: String, -} -#[derive(Clone, PartialEq)] -pub struct AlterOpFamilyStmt { - - pub opfamilyname: Vec, - - pub amname: String, - - pub is_drop: bool, - - pub items: Vec, -} -#[derive(Clone, PartialEq)] -pub struct PrepareStmt { - - pub name: String, - - pub argtypes: Vec, - - pub query: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct ExecuteStmt { - - pub name: String, - - pub params: Vec, -} -#[derive(Clone, PartialEq)] -pub struct DeallocateStmt { - - pub name: String, -} -#[derive(Clone, PartialEq)] -pub struct DeclareCursorStmt { - - pub portalname: String, - - pub options: i32, - - pub query: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct CreateTableSpaceStmt { - - pub tablespacename: String, - - pub owner: ::core::option::Option, - - pub location: String, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct DropTableSpaceStmt { - - pub tablespacename: String, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterObjectDependsStmt { - - pub object_type: i32, - - pub relation: ::core::option::Option, - - pub object: ::core::option::Option>, - - pub extname: ::core::option::Option>, - - pub remove: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterObjectSchemaStmt { - - pub object_type: i32, - - pub relation: ::core::option::Option, - - pub object: ::core::option::Option>, - - pub newschema: String, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterOwnerStmt { - - pub object_type: i32, - - pub relation: ::core::option::Option, - - pub object: ::core::option::Option>, - - pub newowner: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct AlterOperatorStmt { - - pub opername: ::core::option::Option, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterTypeStmt { - - pub type_name: Vec, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct DropOwnedStmt { - - pub roles: Vec, - - pub behavior: i32, -} -#[derive(Clone, PartialEq)] -pub struct ReassignOwnedStmt { - - pub roles: Vec, - - pub newrole: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct CompositeTypeStmt { - - pub typevar: ::core::option::Option, - - pub coldeflist: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CreateEnumStmt { - - pub type_name: Vec, - - pub vals: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CreateRangeStmt { - - pub type_name: Vec, - - pub params: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterEnumStmt { - - pub type_name: Vec, - - pub old_val: String, - - pub new_val: String, - - pub new_val_neighbor: String, - - pub new_val_is_after: bool, - - pub skip_if_new_val_exists: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterTsDictionaryStmt { - - pub dictname: Vec, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterTsConfigurationStmt { - - pub kind: i32, - - pub cfgname: Vec, - - pub tokentype: Vec, - - pub dicts: Vec, - - pub r#override: bool, - - pub replace: bool, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct CreateFdwStmt { - - pub fdwname: String, - - pub func_options: Vec, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterFdwStmt { - - pub fdwname: String, - - pub func_options: Vec, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CreateForeignServerStmt { - - pub servername: String, - - pub servertype: String, - - pub version: String, - - pub fdwname: String, - - pub if_not_exists: bool, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterForeignServerStmt { - - pub servername: String, - - pub version: String, - - pub options: Vec, - - pub has_version: bool, -} -#[derive(Clone, PartialEq)] -pub struct CreateUserMappingStmt { - - pub user: ::core::option::Option, - - pub servername: String, - - pub if_not_exists: bool, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterUserMappingStmt { - - pub user: ::core::option::Option, - - pub servername: String, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct DropUserMappingStmt { - - pub user: ::core::option::Option, - - pub servername: String, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterTableSpaceOptionsStmt { - - pub tablespacename: String, - - pub options: Vec, - - pub is_reset: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterTableMoveAllStmt { - - pub orig_tablespacename: String, - - pub objtype: i32, - - pub roles: Vec, - - pub new_tablespacename: String, - - pub nowait: bool, -} -#[derive(Clone, PartialEq)] -pub struct SecLabelStmt { - - pub objtype: i32, - - pub object: ::core::option::Option>, - - pub provider: String, - - pub label: String, -} -#[derive(Clone, PartialEq)] -pub struct CreateForeignTableStmt { - - pub base_stmt: ::core::option::Option, - - pub servername: String, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct ImportForeignSchemaStmt { - - pub server_name: String, - - pub remote_schema: String, - - pub local_schema: String, - - pub list_type: i32, - - pub table_list: Vec, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CreateExtensionStmt { - - pub extname: String, - - pub if_not_exists: bool, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterExtensionStmt { - - pub extname: String, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterExtensionContentsStmt { - - pub extname: String, - - pub action: i32, - - pub objtype: i32, - - pub object: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct CreateEventTrigStmt { - - pub trigname: String, - - pub eventname: String, - - pub whenclause: Vec, - - pub funcname: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterEventTrigStmt { - - pub trigname: String, - - pub tgenabled: String, -} -#[derive(Clone, PartialEq)] -pub struct RefreshMatViewStmt { - - pub concurrent: bool, - - pub skip_data: bool, - - pub relation: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct ReplicaIdentityStmt { - - pub identity_type: String, - - pub name: String, -} -#[derive(Clone, PartialEq)] -pub struct AlterSystemStmt { - - pub setstmt: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct CreatePolicyStmt { - - pub policy_name: String, - - pub table: ::core::option::Option, - - pub cmd_name: String, - - pub permissive: bool, - - pub roles: Vec, - - pub qual: ::core::option::Option>, - - pub with_check: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct AlterPolicyStmt { - - pub policy_name: String, - - pub table: ::core::option::Option, - - pub roles: Vec, - - pub qual: ::core::option::Option>, - - pub with_check: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct CreateTransformStmt { - - pub replace: bool, - - pub type_name: ::core::option::Option, - - pub lang: String, - - pub fromsql: ::core::option::Option, - - pub tosql: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct CreateAmStmt { - - pub amname: String, - - pub handler_name: Vec, - - pub amtype: String, -} -#[derive(Clone, PartialEq)] -pub struct CreatePublicationStmt { - - pub pubname: String, - - pub options: Vec, - - pub tables: Vec, - - pub for_all_tables: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterPublicationStmt { - - pub pubname: String, - - pub options: Vec, - - pub tables: Vec, - - pub for_all_tables: bool, - - pub table_action: i32, -} -#[derive(Clone, PartialEq)] -pub struct CreateSubscriptionStmt { - - pub subname: String, - - pub conninfo: String, - - pub publication: Vec, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterSubscriptionStmt { - - pub kind: i32, - - pub subname: String, - - pub conninfo: String, - - pub publication: Vec, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct DropSubscriptionStmt { - - pub subname: String, - - pub missing_ok: bool, - - pub behavior: i32, -} -#[derive(Clone, PartialEq)] -pub struct CreateStatsStmt { - - pub defnames: Vec, - - pub stat_types: Vec, - - pub exprs: Vec, - - pub relations: Vec, - - pub stxcomment: String, - - pub if_not_exists: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterCollationStmt { - - pub collname: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CallStmt { - - pub funccall: ::core::option::Option>, - - pub funcexpr: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct AlterStatsStmt { - - pub defnames: Vec, - - pub stxstattarget: i32, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct AExpr { - - pub kind: i32, - - pub name: Vec, - - pub lexpr: ::core::option::Option>, - - pub rexpr: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct ColumnRef { - - pub fields: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct ParamRef { - - pub number: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct AConst { - - pub val: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct FuncCall { - - pub funcname: Vec, - - pub args: Vec, - - pub agg_order: Vec, - - pub agg_filter: ::core::option::Option>, - - pub agg_within_group: bool, - - pub agg_star: bool, - - pub agg_distinct: bool, - - pub func_variadic: bool, - - pub over: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct AStar {} -#[derive(Clone, PartialEq)] -pub struct AIndices { - - pub is_slice: bool, - - pub lidx: ::core::option::Option>, - - pub uidx: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct AIndirection { - - pub arg: ::core::option::Option>, - - pub indirection: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AArrayExpr { - - pub elements: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct ResTarget { - - pub name: String, - - pub indirection: Vec, - - pub val: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct MultiAssignRef { - - pub source: ::core::option::Option>, - - pub colno: i32, - - pub ncolumns: i32, -} -#[derive(Clone, PartialEq)] -pub struct TypeCast { - - pub arg: ::core::option::Option>, - - pub type_name: ::core::option::Option, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CollateClause { - - pub arg: ::core::option::Option>, - - pub collname: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct SortBy { - - pub node: ::core::option::Option>, - - pub sortby_dir: i32, - - pub sortby_nulls: i32, - - pub use_op: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct WindowDef { - - pub name: String, - - pub refname: String, - - pub partition_clause: Vec, - - pub order_clause: Vec, - - pub frame_options: i32, - - pub start_offset: ::core::option::Option>, - - pub end_offset: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct RangeSubselect { - - pub lateral: bool, - - pub subquery: ::core::option::Option>, - - pub alias: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct RangeFunction { - - pub lateral: bool, - - pub ordinality: bool, - - pub is_rowsfrom: bool, - - pub functions: Vec, - - pub alias: ::core::option::Option, - - pub coldeflist: Vec, -} -#[derive(Clone, PartialEq)] -pub struct RangeTableSample { - - pub relation: ::core::option::Option>, - - pub method: Vec, - - pub args: Vec, - - pub repeatable: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct RangeTableFunc { - - pub lateral: bool, - - pub docexpr: ::core::option::Option>, - - pub rowexpr: ::core::option::Option>, - - pub namespaces: Vec, - - pub columns: Vec, - - pub alias: ::core::option::Option, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct RangeTableFuncCol { - - pub colname: String, - - pub type_name: ::core::option::Option, - - pub for_ordinality: bool, - - pub is_not_null: bool, - - pub colexpr: ::core::option::Option>, - - pub coldefexpr: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct TypeName { - - pub names: Vec, - - pub type_oid: u32, - - pub setof: bool, - - pub pct_type: bool, - - pub typmods: Vec, - - pub typemod: i32, - - pub array_bounds: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct ColumnDef { - - pub colname: String, - - pub type_name: ::core::option::Option, - - pub inhcount: i32, - - pub is_local: bool, - - pub is_not_null: bool, - - pub is_from_type: bool, - - pub storage: String, - - pub raw_default: ::core::option::Option>, - - pub cooked_default: ::core::option::Option>, - - pub identity: String, - - pub identity_sequence: ::core::option::Option, - - pub generated: String, - - pub coll_clause: ::core::option::Option>, - - pub coll_oid: u32, - - pub constraints: Vec, - - pub fdwoptions: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct IndexElem { - - pub name: String, - - pub expr: ::core::option::Option>, - - pub indexcolname: String, - - pub collation: Vec, - - pub opclass: Vec, - - pub opclassopts: Vec, - - pub ordering: i32, - - pub nulls_ordering: i32, -} -#[derive(Clone, PartialEq)] -pub struct Constraint { - - pub contype: i32, - - pub conname: String, - - pub deferrable: bool, - - pub initdeferred: bool, - - pub location: i32, - - pub is_no_inherit: bool, - - pub raw_expr: ::core::option::Option>, - - pub cooked_expr: String, - - pub generated_when: String, - - pub keys: Vec, - - pub including: Vec, - - pub exclusions: Vec, - - pub options: Vec, - - pub indexname: String, - - pub indexspace: String, - - pub reset_default_tblspc: bool, - - pub access_method: String, - - pub where_clause: ::core::option::Option>, - - pub pktable: ::core::option::Option, - - pub fk_attrs: Vec, - - pub pk_attrs: Vec, - - pub fk_matchtype: String, - - pub fk_upd_action: String, - - pub fk_del_action: String, - - pub old_conpfeqop: Vec, - - pub old_pktable_oid: u32, - - pub skip_validation: bool, - - pub initially_valid: bool, -} -#[derive(Clone, PartialEq)] -pub struct DefElem { - - pub defnamespace: String, - - pub defname: String, - - pub arg: ::core::option::Option>, - - pub defaction: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct RangeTblEntry { - - pub rtekind: i32, - - pub relid: u32, - - pub relkind: String, - - pub rellockmode: i32, - - pub tablesample: ::core::option::Option>, - - pub subquery: ::core::option::Option>, - - pub security_barrier: bool, - - pub jointype: i32, - - pub joinmergedcols: i32, - - pub joinaliasvars: Vec, - - pub joinleftcols: Vec, - - pub joinrightcols: Vec, - - pub functions: Vec, - - pub funcordinality: bool, - - pub tablefunc: ::core::option::Option>, - - pub values_lists: Vec, - - pub ctename: String, - - pub ctelevelsup: u32, - - pub self_reference: bool, - - pub coltypes: Vec, - - pub coltypmods: Vec, - - pub colcollations: Vec, - - pub enrname: String, - - pub enrtuples: f64, - - pub alias: ::core::option::Option, - - pub eref: ::core::option::Option, - - pub lateral: bool, - - pub inh: bool, - - pub in_from_cl: bool, - - pub required_perms: u32, - - pub check_as_user: u32, - - pub selected_cols: Vec, - - pub inserted_cols: Vec, - - pub updated_cols: Vec, - - pub extra_updated_cols: Vec, - - pub security_quals: Vec, -} -#[derive(Clone, PartialEq)] -pub struct RangeTblFunction { - - pub funcexpr: ::core::option::Option>, - - pub funccolcount: i32, - - pub funccolnames: Vec, - - pub funccoltypes: Vec, - - pub funccoltypmods: Vec, - - pub funccolcollations: Vec, - - pub funcparams: Vec, -} -#[derive(Clone, PartialEq)] -pub struct TableSampleClause { - - pub tsmhandler: u32, - - pub args: Vec, - - pub repeatable: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct WithCheckOption { - - pub kind: i32, - - pub relname: String, - - pub polname: String, - - pub qual: ::core::option::Option>, - - pub cascaded: bool, -} -#[derive(Clone, PartialEq)] -pub struct SortGroupClause { - - pub tle_sort_group_ref: u32, - - pub eqop: u32, - - pub sortop: u32, - - pub nulls_first: bool, - - pub hashable: bool, -} -#[derive(Clone, PartialEq)] -pub struct GroupingSet { - - pub kind: i32, - - pub content: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct WindowClause { - - pub name: String, - - pub refname: String, - - pub partition_clause: Vec, - - pub order_clause: Vec, - - pub frame_options: i32, - - pub start_offset: ::core::option::Option>, - - pub end_offset: ::core::option::Option>, - - pub start_in_range_func: u32, - - pub end_in_range_func: u32, - - pub in_range_coll: u32, - - pub in_range_asc: bool, - - pub in_range_nulls_first: bool, - - pub winref: u32, - - pub copied_order: bool, -} -#[derive(Clone, PartialEq)] -pub struct ObjectWithArgs { - - pub objname: Vec, - - pub objargs: Vec, - - pub args_unspecified: bool, -} -#[derive(Clone, PartialEq)] -pub struct AccessPriv { - - pub priv_name: String, - - pub cols: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CreateOpClassItem { - - pub itemtype: i32, - - pub name: ::core::option::Option, - - pub number: i32, - - pub order_family: Vec, - - pub class_args: Vec, - - pub storedtype: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct TableLikeClause { - - pub relation: ::core::option::Option, - - pub options: u32, - - pub relation_oid: u32, -} -#[derive(Clone, PartialEq)] -pub struct FunctionParameter { - - pub name: String, - - pub arg_type: ::core::option::Option, - - pub mode: i32, - - pub defexpr: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct LockingClause { - - pub locked_rels: Vec, - - pub strength: i32, - - pub wait_policy: i32, -} -#[derive(Clone, PartialEq)] -pub struct RowMarkClause { - - pub rti: u32, - - pub strength: i32, - - pub wait_policy: i32, - - pub pushed_down: bool, -} -#[derive(Clone, PartialEq)] -pub struct XmlSerialize { - - pub xmloption: i32, - - pub expr: ::core::option::Option>, - - pub type_name: ::core::option::Option, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct WithClause { - - pub ctes: Vec, - - pub recursive: bool, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct InferClause { - - pub index_elems: Vec, - - pub where_clause: ::core::option::Option>, - - pub conname: String, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct OnConflictClause { - - pub action: i32, - - pub infer: ::core::option::Option>, - - pub target_list: Vec, - - pub where_clause: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CommonTableExpr { - - pub ctename: String, - - pub aliascolnames: Vec, - - pub ctematerialized: i32, - - pub ctequery: ::core::option::Option>, - - pub location: i32, - - pub cterecursive: bool, - - pub cterefcount: i32, - - pub ctecolnames: Vec, - - pub ctecoltypes: Vec, - - pub ctecoltypmods: Vec, - - pub ctecolcollations: Vec, -} -#[derive(Clone, PartialEq)] -pub struct RoleSpec { - - pub roletype: i32, - - pub rolename: String, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct TriggerTransition { - - pub name: String, - - pub is_new: bool, - - pub is_table: bool, -} -#[derive(Clone, PartialEq)] -pub struct PartitionElem { - - pub name: String, - - pub expr: ::core::option::Option>, - - pub collation: Vec, - - pub opclass: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct PartitionSpec { - - pub strategy: String, - - pub part_params: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct PartitionBoundSpec { - - pub strategy: String, - - pub is_default: bool, - - pub modulus: i32, - - pub remainder: i32, - - pub listdatums: Vec, - - pub lowerdatums: Vec, - - pub upperdatums: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct PartitionRangeDatum { - - pub kind: i32, - - pub value: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct PartitionCmd { - - pub name: ::core::option::Option, - - pub bound: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct VacuumRelation { - - pub relation: ::core::option::Option, - - pub oid: u32, - - pub va_cols: Vec, -} -#[derive(Clone, PartialEq)] -pub struct InlineCodeBlock { - - pub source_text: String, - - pub lang_oid: u32, - - pub lang_is_trusted: bool, - - pub atomic: bool, -} -#[derive(Clone, PartialEq)] -pub struct CallContext { - - pub atomic: bool, -} -#[derive(Clone, PartialEq)] -pub struct ScanToken { - - pub start: i32, - - pub end: i32, - - pub token: i32, - - pub keyword_kind: i32, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum OverridingKind { - Undefined = 0, - OverridingNotSet = 1, - OverridingUserValue = 2, - OverridingSystemValue = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum QuerySource { - Undefined = 0, - QsrcOriginal = 1, - QsrcParser = 2, - QsrcInsteadRule = 3, - QsrcQualInsteadRule = 4, - QsrcNonInsteadRule = 5, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum SortByDir { - Undefined = 0, - SortbyDefault = 1, - SortbyAsc = 2, - SortbyDesc = 3, - SortbyUsing = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum SortByNulls { - Undefined = 0, - SortbyNullsDefault = 1, - SortbyNullsFirst = 2, - SortbyNullsLast = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum AExprKind { - Undefined = 0, - AexprOp = 1, - AexprOpAny = 2, - AexprOpAll = 3, - AexprDistinct = 4, - AexprNotDistinct = 5, - AexprNullif = 6, - AexprOf = 7, - AexprIn = 8, - AexprLike = 9, - AexprIlike = 10, - AexprSimilar = 11, - AexprBetween = 12, - AexprNotBetween = 13, - AexprBetweenSym = 14, - AexprNotBetweenSym = 15, - AexprParen = 16, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum RoleSpecType { - Undefined = 0, - RolespecCstring = 1, - RolespecCurrentUser = 2, - RolespecSessionUser = 3, - RolespecPublic = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum TableLikeOption { - Undefined = 0, - CreateTableLikeComments = 1, - CreateTableLikeConstraints = 2, - CreateTableLikeDefaults = 3, - CreateTableLikeGenerated = 4, - CreateTableLikeIdentity = 5, - CreateTableLikeIndexes = 6, - CreateTableLikeStatistics = 7, - CreateTableLikeStorage = 8, - CreateTableLikeAll = 9, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum DefElemAction { - Undefined = 0, - DefelemUnspec = 1, - DefelemSet = 2, - DefelemAdd = 3, - DefelemDrop = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum PartitionRangeDatumKind { - Undefined = 0, - PartitionRangeDatumMinvalue = 1, - PartitionRangeDatumValue = 2, - PartitionRangeDatumMaxvalue = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum RteKind { - RtekindUndefined = 0, - RteRelation = 1, - RteSubquery = 2, - RteJoin = 3, - RteFunction = 4, - RteTablefunc = 5, - RteValues = 6, - RteCte = 7, - RteNamedtuplestore = 8, - RteResult = 9, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum WcoKind { - WcokindUndefined = 0, - WcoViewCheck = 1, - WcoRlsInsertCheck = 2, - WcoRlsUpdateCheck = 3, - WcoRlsConflictCheck = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum GroupingSetKind { - Undefined = 0, - GroupingSetEmpty = 1, - GroupingSetSimple = 2, - GroupingSetRollup = 3, - GroupingSetCube = 4, - GroupingSetSets = 5, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum CteMaterialize { - CtematerializeUndefined = 0, - Default = 1, - Always = 2, - Never = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum SetOperation { - Undefined = 0, - SetopNone = 1, - SetopUnion = 2, - SetopIntersect = 3, - SetopExcept = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum ObjectType { - Undefined = 0, - ObjectAccessMethod = 1, - ObjectAggregate = 2, - ObjectAmop = 3, - ObjectAmproc = 4, - ObjectAttribute = 5, - ObjectCast = 6, - ObjectColumn = 7, - ObjectCollation = 8, - ObjectConversion = 9, - ObjectDatabase = 10, - ObjectDefault = 11, - ObjectDefacl = 12, - ObjectDomain = 13, - ObjectDomconstraint = 14, - ObjectEventTrigger = 15, - ObjectExtension = 16, - ObjectFdw = 17, - ObjectForeignServer = 18, - ObjectForeignTable = 19, - ObjectFunction = 20, - ObjectIndex = 21, - ObjectLanguage = 22, - ObjectLargeobject = 23, - ObjectMatview = 24, - ObjectOpclass = 25, - ObjectOperator = 26, - ObjectOpfamily = 27, - ObjectPolicy = 28, - ObjectProcedure = 29, - ObjectPublication = 30, - ObjectPublicationRel = 31, - ObjectRole = 32, - ObjectRoutine = 33, - ObjectRule = 34, - ObjectSchema = 35, - ObjectSequence = 36, - ObjectSubscription = 37, - ObjectStatisticExt = 38, - ObjectTabconstraint = 39, - ObjectTable = 40, - ObjectTablespace = 41, - ObjectTransform = 42, - ObjectTrigger = 43, - ObjectTsconfiguration = 44, - ObjectTsdictionary = 45, - ObjectTsparser = 46, - ObjectTstemplate = 47, - ObjectType = 48, - ObjectUserMapping = 49, - ObjectView = 50, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum DropBehavior { - Undefined = 0, - DropRestrict = 1, - DropCascade = 2, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum AlterTableType { - Undefined = 0, - AtAddColumn = 1, - AtAddColumnRecurse = 2, - AtAddColumnToView = 3, - AtColumnDefault = 4, - AtCookedColumnDefault = 5, - AtDropNotNull = 6, - AtSetNotNull = 7, - AtDropExpression = 8, - AtCheckNotNull = 9, - AtSetStatistics = 10, - AtSetOptions = 11, - AtResetOptions = 12, - AtSetStorage = 13, - AtDropColumn = 14, - AtDropColumnRecurse = 15, - AtAddIndex = 16, - AtReAddIndex = 17, - AtAddConstraint = 18, - AtAddConstraintRecurse = 19, - AtReAddConstraint = 20, - AtReAddDomainConstraint = 21, - AtAlterConstraint = 22, - AtValidateConstraint = 23, - AtValidateConstraintRecurse = 24, - AtAddIndexConstraint = 25, - AtDropConstraint = 26, - AtDropConstraintRecurse = 27, - AtReAddComment = 28, - AtAlterColumnType = 29, - AtAlterColumnGenericOptions = 30, - AtChangeOwner = 31, - AtClusterOn = 32, - AtDropCluster = 33, - AtSetLogged = 34, - AtSetUnLogged = 35, - AtDropOids = 36, - AtSetTableSpace = 37, - AtSetRelOptions = 38, - AtResetRelOptions = 39, - AtReplaceRelOptions = 40, - AtEnableTrig = 41, - AtEnableAlwaysTrig = 42, - AtEnableReplicaTrig = 43, - AtDisableTrig = 44, - AtEnableTrigAll = 45, - AtDisableTrigAll = 46, - AtEnableTrigUser = 47, - AtDisableTrigUser = 48, - AtEnableRule = 49, - AtEnableAlwaysRule = 50, - AtEnableReplicaRule = 51, - AtDisableRule = 52, - AtAddInherit = 53, - AtDropInherit = 54, - AtAddOf = 55, - AtDropOf = 56, - AtReplicaIdentity = 57, - AtEnableRowSecurity = 58, - AtDisableRowSecurity = 59, - AtForceRowSecurity = 60, - AtNoForceRowSecurity = 61, - AtGenericOptions = 62, - AtAttachPartition = 63, - AtDetachPartition = 64, - AtAddIdentity = 65, - AtSetIdentity = 66, - AtDropIdentity = 67, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum GrantTargetType { - Undefined = 0, - AclTargetObject = 1, - AclTargetAllInSchema = 2, - AclTargetDefaults = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum VariableSetKind { - Undefined = 0, - VarSetValue = 1, - VarSetDefault = 2, - VarSetCurrent = 3, - VarSetMulti = 4, - VarReset = 5, - VarResetAll = 6, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum ConstrType { - Undefined = 0, - ConstrNull = 1, - ConstrNotnull = 2, - ConstrDefault = 3, - ConstrIdentity = 4, - ConstrGenerated = 5, - ConstrCheck = 6, - ConstrPrimary = 7, - ConstrUnique = 8, - ConstrExclusion = 9, - ConstrForeign = 10, - ConstrAttrDeferrable = 11, - ConstrAttrNotDeferrable = 12, - ConstrAttrDeferred = 13, - ConstrAttrImmediate = 14, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum ImportForeignSchemaType { - Undefined = 0, - FdwImportSchemaAll = 1, - FdwImportSchemaLimitTo = 2, - FdwImportSchemaExcept = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum RoleStmtType { - Undefined = 0, - RolestmtRole = 1, - RolestmtUser = 2, - RolestmtGroup = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum FetchDirection { - Undefined = 0, - FetchForward = 1, - FetchBackward = 2, - FetchAbsolute = 3, - FetchRelative = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum FunctionParameterMode { - Undefined = 0, - FuncParamIn = 1, - FuncParamOut = 2, - FuncParamInout = 3, - FuncParamVariadic = 4, - FuncParamTable = 5, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum TransactionStmtKind { - Undefined = 0, - TransStmtBegin = 1, - TransStmtStart = 2, - TransStmtCommit = 3, - TransStmtRollback = 4, - TransStmtSavepoint = 5, - TransStmtRelease = 6, - TransStmtRollbackTo = 7, - TransStmtPrepare = 8, - TransStmtCommitPrepared = 9, - TransStmtRollbackPrepared = 10, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum ViewCheckOption { - Undefined = 0, - NoCheckOption = 1, - LocalCheckOption = 2, - CascadedCheckOption = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum ClusterOption { - Undefined = 0, - CluoptRecheck = 1, - CluoptVerbose = 2, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum DiscardMode { - Undefined = 0, - DiscardAll = 1, - DiscardPlans = 2, - DiscardSequences = 3, - DiscardTemp = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum ReindexObjectType { - Undefined = 0, - ReindexObjectIndex = 1, - ReindexObjectTable = 2, - ReindexObjectSchema = 3, - ReindexObjectSystem = 4, - ReindexObjectDatabase = 5, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum AlterTsConfigType { - AlterTsconfigTypeUndefined = 0, - AlterTsconfigAddMapping = 1, - AlterTsconfigAlterMappingForToken = 2, - AlterTsconfigReplaceDict = 3, - AlterTsconfigReplaceDictForToken = 4, - AlterTsconfigDropMapping = 5, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum AlterSubscriptionType { - Undefined = 0, - AlterSubscriptionOptions = 1, - AlterSubscriptionConnection = 2, - AlterSubscriptionPublication = 3, - AlterSubscriptionRefresh = 4, - AlterSubscriptionEnabled = 5, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum OnCommitAction { - Undefined = 0, - OncommitNoop = 1, - OncommitPreserveRows = 2, - OncommitDeleteRows = 3, - OncommitDrop = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum ParamKind { - Undefined = 0, - ParamExtern = 1, - ParamExec = 2, - ParamSublink = 3, - ParamMultiexpr = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum CoercionContext { - Undefined = 0, - CoercionImplicit = 1, - CoercionAssignment = 2, - CoercionExplicit = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum CoercionForm { - Undefined = 0, - CoerceExplicitCall = 1, - CoerceExplicitCast = 2, - CoerceImplicitCast = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum BoolExprType { - Undefined = 0, - AndExpr = 1, - OrExpr = 2, - NotExpr = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum SubLinkType { - Undefined = 0, - ExistsSublink = 1, - AllSublink = 2, - AnySublink = 3, - RowcompareSublink = 4, - ExprSublink = 5, - MultiexprSublink = 6, - ArraySublink = 7, - CteSublink = 8, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum RowCompareType { - Undefined = 0, - RowcompareLt = 1, - RowcompareLe = 2, - RowcompareEq = 3, - RowcompareGe = 4, - RowcompareGt = 5, - RowcompareNe = 6, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum MinMaxOp { - Undefined = 0, - IsGreatest = 1, - IsLeast = 2, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum SqlValueFunctionOp { - SqlvalueFunctionOpUndefined = 0, - SvfopCurrentDate = 1, - SvfopCurrentTime = 2, - SvfopCurrentTimeN = 3, - SvfopCurrentTimestamp = 4, - SvfopCurrentTimestampN = 5, - SvfopLocaltime = 6, - SvfopLocaltimeN = 7, - SvfopLocaltimestamp = 8, - SvfopLocaltimestampN = 9, - SvfopCurrentRole = 10, - SvfopCurrentUser = 11, - SvfopUser = 12, - SvfopSessionUser = 13, - SvfopCurrentCatalog = 14, - SvfopCurrentSchema = 15, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum XmlExprOp { - Undefined = 0, - IsXmlconcat = 1, - IsXmlelement = 2, - IsXmlforest = 3, - IsXmlparse = 4, - IsXmlpi = 5, - IsXmlroot = 6, - IsXmlserialize = 7, - IsDocument = 8, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum XmlOptionType { - Undefined = 0, - XmloptionDocument = 1, - XmloptionContent = 2, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum NullTestType { - Undefined = 0, - IsNull = 1, - IsNotNull = 2, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum BoolTestType { - Undefined = 0, - IsTrue = 1, - IsNotTrue = 2, - IsFalse = 3, - IsNotFalse = 4, - IsUnknown = 5, - IsNotUnknown = 6, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum CmdType { - Undefined = 0, - CmdUnknown = 1, - CmdSelect = 2, - CmdUpdate = 3, - CmdInsert = 4, - CmdDelete = 5, - CmdUtility = 6, - CmdNothing = 7, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum JoinType { - Undefined = 0, - JoinInner = 1, - JoinLeft = 2, - JoinFull = 3, - JoinRight = 4, - JoinSemi = 5, - JoinAnti = 6, - JoinUniqueOuter = 7, - JoinUniqueInner = 8, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum AggStrategy { - Undefined = 0, - AggPlain = 1, - AggSorted = 2, - AggHashed = 3, - AggMixed = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum AggSplit { - Undefined = 0, - AggsplitSimple = 1, - AggsplitInitialSerial = 2, - AggsplitFinalDeserial = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum SetOpCmd { - Undefined = 0, - SetopcmdIntersect = 1, - SetopcmdIntersectAll = 2, - SetopcmdExcept = 3, - SetopcmdExceptAll = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum SetOpStrategy { - Undefined = 0, - SetopSorted = 1, - SetopHashed = 2, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum OnConflictAction { - Undefined = 0, - OnconflictNone = 1, - OnconflictNothing = 2, - OnconflictUpdate = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum LimitOption { - Undefined = 0, - Default = 1, - Count = 2, - WithTies = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum LockClauseStrength { - Undefined = 0, - LcsNone = 1, - LcsForkeyshare = 2, - LcsForshare = 3, - LcsFornokeyupdate = 4, - LcsForupdate = 5, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum LockWaitPolicy { - Undefined = 0, - LockWaitBlock = 1, - LockWaitSkip = 2, - LockWaitError = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum LockTupleMode { - Undefined = 0, - LockTupleKeyShare = 1, - LockTupleShare = 2, - LockTupleNoKeyExclusive = 3, - LockTupleExclusive = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum KeywordKind { - NoKeyword = 0, - UnreservedKeyword = 1, - ColNameKeyword = 2, - TypeFuncNameKeyword = 3, - ReservedKeyword = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum Token { - Nul = 0, - /// Single-character tokens that are returned 1:1 (identical with "self" list in scan.l) - /// Either supporting syntax, or single-character operators (some can be both) - /// Also see - /// - /// "%" - Ascii37 = 37, - /// "(" - Ascii40 = 40, - /// ")" - Ascii41 = 41, - /// "*" - Ascii42 = 42, - /// "+" - Ascii43 = 43, - /// "," - Ascii44 = 44, - /// "-" - Ascii45 = 45, - /// "." - Ascii46 = 46, - /// "/" - Ascii47 = 47, - /// ":" - Ascii58 = 58, - /// ";" - Ascii59 = 59, - /// "<" - Ascii60 = 60, - /// "=" - Ascii61 = 61, - /// ">" - Ascii62 = 62, - /// "?" - Ascii63 = 63, - /// "[" - Ascii91 = 91, - /// "\" - Ascii92 = 92, - /// "]" - Ascii93 = 93, - /// "^" - Ascii94 = 94, - /// Named tokens in scan.l - Ident = 258, - Uident = 259, - Fconst = 260, - Sconst = 261, - Usconst = 262, - Bconst = 263, - Xconst = 264, - Op = 265, - Iconst = 266, - Param = 267, - Typecast = 268, - DotDot = 269, - ColonEquals = 270, - EqualsGreater = 271, - LessEquals = 272, - GreaterEquals = 273, - NotEquals = 274, - SqlComment = 275, - CComment = 276, - AbortP = 277, - AbsoluteP = 278, - Access = 279, - Action = 280, - AddP = 281, - Admin = 282, - After = 283, - Aggregate = 284, - All = 285, - Also = 286, - Alter = 287, - Always = 288, - Analyse = 289, - Analyze = 290, - And = 291, - Any = 292, - Array = 293, - As = 294, - Asc = 295, - Assertion = 296, - Assignment = 297, - Asymmetric = 298, - At = 299, - Attach = 300, - Attribute = 301, - Authorization = 302, - Backward = 303, - Before = 304, - BeginP = 305, - Between = 306, - Bigint = 307, - Binary = 308, - Bit = 309, - BooleanP = 310, - Both = 311, - By = 312, - Cache = 313, - Call = 314, - Called = 315, - Cascade = 316, - Cascaded = 317, - Case = 318, - Cast = 319, - CatalogP = 320, - Chain = 321, - CharP = 322, - Character = 323, - Characteristics = 324, - Check = 325, - Checkpoint = 326, - Class = 327, - Close = 328, - Cluster = 329, - Coalesce = 330, - Collate = 331, - Collation = 332, - Column = 333, - Columns = 334, - Comment = 335, - Comments = 336, - Commit = 337, - Committed = 338, - Concurrently = 339, - Configuration = 340, - Conflict = 341, - Connection = 342, - Constraint = 343, - Constraints = 344, - ContentP = 345, - ContinueP = 346, - ConversionP = 347, - Copy = 348, - Cost = 349, - Create = 350, - Cross = 351, - Csv = 352, - Cube = 353, - CurrentP = 354, - CurrentCatalog = 355, - CurrentDate = 356, - CurrentRole = 357, - CurrentSchema = 358, - CurrentTime = 359, - CurrentTimestamp = 360, - CurrentUser = 361, - Cursor = 362, - Cycle = 363, - DataP = 364, - Database = 365, - DayP = 366, - Deallocate = 367, - Dec = 368, - DecimalP = 369, - Declare = 370, - Default = 371, - Defaults = 372, - Deferrable = 373, - Deferred = 374, - Definer = 375, - DeleteP = 376, - Delimiter = 377, - Delimiters = 378, - Depends = 379, - Desc = 380, - Detach = 381, - Dictionary = 382, - DisableP = 383, - Discard = 384, - Distinct = 385, - Do = 386, - DocumentP = 387, - DomainP = 388, - DoubleP = 389, - Drop = 390, - Each = 391, - Else = 392, - EnableP = 393, - Encoding = 394, - Encrypted = 395, - EndP = 396, - EnumP = 397, - Escape = 398, - Event = 399, - Except = 400, - Exclude = 401, - Excluding = 402, - Exclusive = 403, - Execute = 404, - Exists = 405, - Explain = 406, - Expression = 407, - Extension = 408, - External = 409, - Extract = 410, - FalseP = 411, - Family = 412, - Fetch = 413, - Filter = 414, - FirstP = 415, - FloatP = 416, - Following = 417, - For = 418, - Force = 419, - Foreign = 420, - Forward = 421, - Freeze = 422, - From = 423, - Full = 424, - Function = 425, - Functions = 426, - Generated = 427, - Global = 428, - Grant = 429, - Granted = 430, - Greatest = 431, - GroupP = 432, - Grouping = 433, - Groups = 434, - Handler = 435, - Having = 436, - HeaderP = 437, - Hold = 438, - HourP = 439, - IdentityP = 440, - IfP = 441, - Ilike = 442, - Immediate = 443, - Immutable = 444, - ImplicitP = 445, - ImportP = 446, - InP = 447, - Include = 448, - Including = 449, - Increment = 450, - Index = 451, - Indexes = 452, - Inherit = 453, - Inherits = 454, - Initially = 455, - InlineP = 456, - InnerP = 457, - Inout = 458, - InputP = 459, - Insensitive = 460, - Insert = 461, - Instead = 462, - IntP = 463, - Integer = 464, - Intersect = 465, - Interval = 466, - Into = 467, - Invoker = 468, - Is = 469, - Isnull = 470, - Isolation = 471, - Join = 472, - Key = 473, - Label = 474, - Language = 475, - LargeP = 476, - LastP = 477, - LateralP = 478, - Leading = 479, - Leakproof = 480, - Least = 481, - Left = 482, - Level = 483, - Like = 484, - Limit = 485, - Listen = 486, - Load = 487, - Local = 488, - Localtime = 489, - Localtimestamp = 490, - Location = 491, - LockP = 492, - Locked = 493, - Logged = 494, - Mapping = 495, - Match = 496, - Materialized = 497, - Maxvalue = 498, - Method = 499, - MinuteP = 500, - Minvalue = 501, - Mode = 502, - MonthP = 503, - Move = 504, - NameP = 505, - Names = 506, - National = 507, - Natural = 508, - Nchar = 509, - New = 510, - Next = 511, - Nfc = 512, - Nfd = 513, - Nfkc = 514, - Nfkd = 515, - No = 516, - None = 517, - Normalize = 518, - Normalized = 519, - Not = 520, - Nothing = 521, - Notify = 522, - Notnull = 523, - Nowait = 524, - NullP = 525, - Nullif = 526, - NullsP = 527, - Numeric = 528, - ObjectP = 529, - Of = 530, - Off = 531, - Offset = 532, - Oids = 533, - Old = 534, - On = 535, - Only = 536, - Operator = 537, - Option = 538, - Options = 539, - Or = 540, - Order = 541, - Ordinality = 542, - Others = 543, - OutP = 544, - OuterP = 545, - Over = 546, - Overlaps = 547, - Overlay = 548, - Overriding = 549, - Owned = 550, - Owner = 551, - Parallel = 552, - Parser = 553, - Partial = 554, - Partition = 555, - Passing = 556, - Password = 557, - Placing = 558, - Plans = 559, - Policy = 560, - Position = 561, - Preceding = 562, - Precision = 563, - Preserve = 564, - Prepare = 565, - Prepared = 566, - Primary = 567, - Prior = 568, - Privileges = 569, - Procedural = 570, - Procedure = 571, - Procedures = 572, - Program = 573, - Publication = 574, - Quote = 575, - Range = 576, - Read = 577, - Real = 578, - Reassign = 579, - Recheck = 580, - Recursive = 581, - Ref = 582, - References = 583, - Referencing = 584, - Refresh = 585, - Reindex = 586, - RelativeP = 587, - Release = 588, - Rename = 589, - Repeatable = 590, - Replace = 591, - Replica = 592, - Reset = 593, - Restart = 594, - Restrict = 595, - Returning = 596, - Returns = 597, - Revoke = 598, - Right = 599, - Role = 600, - Rollback = 601, - Rollup = 602, - Routine = 603, - Routines = 604, - Row = 605, - Rows = 606, - Rule = 607, - Savepoint = 608, - Schema = 609, - Schemas = 610, - Scroll = 611, - Search = 612, - SecondP = 613, - Security = 614, - Select = 615, - Sequence = 616, - Sequences = 617, - Serializable = 618, - Server = 619, - Session = 620, - SessionUser = 621, - Set = 622, - Sets = 623, - Setof = 624, - Share = 625, - Show = 626, - Similar = 627, - Simple = 628, - Skip = 629, - Smallint = 630, - Snapshot = 631, - Some = 632, - SqlP = 633, - Stable = 634, - StandaloneP = 635, - Start = 636, - Statement = 637, - Statistics = 638, - Stdin = 639, - Stdout = 640, - Storage = 641, - Stored = 642, - StrictP = 643, - StripP = 644, - Subscription = 645, - Substring = 646, - Support = 647, - Symmetric = 648, - Sysid = 649, - SystemP = 650, - Table = 651, - Tables = 652, - Tablesample = 653, - Tablespace = 654, - Temp = 655, - Template = 656, - Temporary = 657, - TextP = 658, - Then = 659, - Ties = 660, - Time = 661, - Timestamp = 662, - To = 663, - Trailing = 664, - Transaction = 665, - Transform = 666, - Treat = 667, - Trigger = 668, - Trim = 669, - TrueP = 670, - Truncate = 671, - Trusted = 672, - TypeP = 673, - TypesP = 674, - Uescape = 675, - Unbounded = 676, - Uncommitted = 677, - Unencrypted = 678, - Union = 679, - Unique = 680, - Unknown = 681, - Unlisten = 682, - Unlogged = 683, - Until = 684, - Update = 685, - User = 686, - Using = 687, - Vacuum = 688, - Valid = 689, - Validate = 690, - Validator = 691, - ValueP = 692, - Values = 693, - Varchar = 694, - Variadic = 695, - Varying = 696, - Verbose = 697, - VersionP = 698, - View = 699, - Views = 700, - Volatile = 701, - When = 702, - Where = 703, - WhitespaceP = 704, - Window = 705, - With = 706, - Within = 707, - Without = 708, - Work = 709, - Wrapper = 710, - Write = 711, - XmlP = 712, - Xmlattributes = 713, - Xmlconcat = 714, - Xmlelement = 715, - Xmlexists = 716, - Xmlforest = 717, - Xmlnamespaces = 718, - Xmlparse = 719, - Xmlpi = 720, - Xmlroot = 721, - Xmlserialize = 722, - Xmltable = 723, - YearP = 724, - YesP = 725, - Zone = 726, - NotLa = 727, - NullsLa = 728, - WithLa = 729, - Postfixop = 730, - Uminus = 731, -} diff --git a/tests/target/configs/doc_comment_code_block_width/100.rs b/tests/target/configs/doc_comment_code_block_width/100.rs new file mode 100644 index 0000000000000..c010a28aab615 --- /dev/null +++ b/tests/target/configs/doc_comment_code_block_width/100.rs @@ -0,0 +1,16 @@ +// rustfmt-format_code_in_doc_comments: true +// rustfmt-doc_comment_code_block_width: 100 + +/// ```rust +/// impl Test { +/// pub const fn from_bytes(v: &[u8]) -> Result { +/// Self::from_bytes_manual_slice(v, 0, v.len()) +/// } +/// } +/// ``` + +impl Test { + pub const fn from_bytes(v: &[u8]) -> Result { + Self::from_bytes_manual_slice(v, 0, v.len()) + } +} diff --git a/tests/target/configs/doc_comment_code_block_width/100_greater_max_width.rs b/tests/target/configs/doc_comment_code_block_width/100_greater_max_width.rs new file mode 100644 index 0000000000000..6bcb99b915ff9 --- /dev/null +++ b/tests/target/configs/doc_comment_code_block_width/100_greater_max_width.rs @@ -0,0 +1,29 @@ +// rustfmt-max_width: 50 +// rustfmt-format_code_in_doc_comments: true +// rustfmt-doc_comment_code_block_width: 100 + +/// ```rust +/// impl Test { +/// pub const fn from_bytes( +/// v: &[u8], +/// ) -> Result { +/// Self::from_bytes_manual_slice( +/// v, +/// 0, +/// v.len(), +/// ) +/// } +/// } +/// ``` + +impl Test { + pub const fn from_bytes( + v: &[u8], + ) -> Result { + Self::from_bytes_manual_slice( + v, + 0, + v.len(), + ) + } +} diff --git a/tests/target/configs/doc_comment_code_block_width/50.rs b/tests/target/configs/doc_comment_code_block_width/50.rs new file mode 100644 index 0000000000000..e8ab6f28bdc5a --- /dev/null +++ b/tests/target/configs/doc_comment_code_block_width/50.rs @@ -0,0 +1,22 @@ +// rustfmt-format_code_in_doc_comments: true +// rustfmt-doc_comment_code_block_width: 50 + +/// ```rust +/// impl Test { +/// pub const fn from_bytes( +/// v: &[u8], +/// ) -> Result { +/// Self::from_bytes_manual_slice( +/// v, +/// 0, +/// v.len(), +/// ) +/// } +/// } +/// ``` + +impl Test { + pub const fn from_bytes(v: &[u8]) -> Result { + Self::from_bytes_manual_slice(v, 0, v.len()) + } +} diff --git a/tests/target/imports_raw_identifiers/version_One.rs b/tests/target/imports_raw_identifiers/version_One.rs new file mode 100644 index 0000000000000..bc4b5b135696a --- /dev/null +++ b/tests/target/imports_raw_identifiers/version_One.rs @@ -0,0 +1,5 @@ +// rustfmt-version:One + +use websocket::client::ClientBuilder; +use websocket::r#async::futures::Stream; +use websocket::result::WebSocketError; diff --git a/tests/target/imports_raw_identifiers/version_Two.rs b/tests/target/imports_raw_identifiers/version_Two.rs new file mode 100644 index 0000000000000..22bfe93122f95 --- /dev/null +++ b/tests/target/imports_raw_identifiers/version_Two.rs @@ -0,0 +1,5 @@ +// rustfmt-version:Two + +use websocket::r#async::futures::Stream; +use websocket::client::ClientBuilder; +use websocket::result::WebSocketError; diff --git a/tests/target/issue_5399.rs b/tests/target/issue_5399.rs new file mode 100644 index 0000000000000..17364c38919a2 --- /dev/null +++ b/tests/target/issue_5399.rs @@ -0,0 +1,48 @@ +// rustfmt-max_width: 140 + +impl NotificationRepository { + fn set_status_changed( + &self, + repo_tx_conn: &RepoTxConn, + rid: &RoutableId, + changed_at: NaiveDateTime, + ) -> NukeResult> { + repo_tx_conn.run(move |conn| { + let res = diesel::update(client_notification::table) + .filter( + client_notification::routable_id.eq(DieselRoutableId(rid.clone())).and( + client_notification::changed_at + .lt(changed_at) + .or(client_notification::changed_at.is_null()), + ), + ) + .set(client_notification::changed_at.eq(changed_at)) + .returning(( + client_notification::id, + client_notification::changed_at, + client_notification::polled_at, + client_notification::notified_at, + )) + .get_result::<(Uuid, Option, Option, Option)>(conn) + .optional()?; + + match res { + Some(row) => { + let client_id = client_contract::table + .inner_join(client_notification::table) + .filter(client_notification::id.eq(row.0)) + .select(client_contract::client_id) + .get_result::(conn)?; + + Ok(Some(NotificationStatus { + client_id: client_id.into(), + changed_at: row.1, + polled_at: row.2, + notified_at: row.3, + })) + } + None => Ok(None), + } + }) + } +} diff --git a/tests/target/performance/issue-4476.rs b/tests/target/performance/issue-4476.rs deleted file mode 100644 index 30567f2644b74..0000000000000 --- a/tests/target/performance/issue-4476.rs +++ /dev/null @@ -1,705 +0,0 @@ -use super::SemverParser; - -#[allow(dead_code, non_camel_case_types)] -#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] -pub enum Rule { - EOI, - range_set, - logical_or, - range, - empty, - hyphen, - simple, - primitive, - primitive_op, - partial, - xr, - xr_op, - nr, - tilde, - caret, - qualifier, - parts, - part, - space, -} -#[allow(clippy::all)] -impl ::pest::Parser for SemverParser { - fn parse<'i>( - rule: Rule, - input: &'i str, - ) -> ::std::result::Result<::pest::iterators::Pairs<'i, Rule>, ::pest::error::Error> { - mod rules { - pub mod hidden { - use super::super::Rule; - #[inline] - #[allow(dead_code, non_snake_case, unused_variables)] - pub fn skip( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - Ok(state) - } - } - pub mod visible { - use super::super::Rule; - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn range_set( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::range_set, |state| { - state.sequence(|state| { - self::SOI(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state) - .and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::range(state)) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - state - .sequence(|state| { - self::logical_or(state) - .and_then(|state| { - super::hidden::skip(state) - }) - .and_then(|state| self::range(state)) - }) - .and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state).and_then( - |state| { - state.sequence(|state| { - self::logical_or(state) - .and_then(|state| { - super::hidden::skip( - state, - ) - }) - .and_then(|state| { - self::range(state) - }) - }) - }, - ) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state) - .and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::EOI(state)) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn logical_or( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::logical_or, |state| { - state.sequence(|state| { - state - .sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state) - .and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| state.match_string("||")) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state) - .and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn range( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::range, |state| { - self::hyphen(state) - .or_else(|state| { - state.sequence(|state| { - self::simple(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - state - .sequence(|state| { - state - .optional(|state| { - state.match_string(",") - }) - .and_then(|state| { - super::hidden::skip(state) - }) - .and_then(|state| { - state.sequence(|state| { - self::space(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state) - .and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - }) - }) - .and_then(|state| { - super::hidden::skip(state) - }) - .and_then(|state| { - self::simple(state) - }) - }) - .and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state) - .and_then(|state| { - state.sequence( - |state| { - state - .optional(|state| state.match_string(",")) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - self::space(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state) - .and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::simple(state)) - }, - ) - }) - }) - }) - }) - }) - }) - }) - }) - }) - .or_else(|state| self::empty(state)) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn empty( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::empty, |state| state.match_string("")) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn hyphen( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::hyphen, |state| { - state.sequence(|state| { - self::partial(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - self::space(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state) - .and_then(|state| { - self::space(state) - }) - }) - }) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| state.match_string("-")) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - self::space(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state) - .and_then(|state| { - self::space(state) - }) - }) - }) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::partial(state)) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn simple( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::simple, |state| { - self::primitive(state) - .or_else(|state| self::partial(state)) - .or_else(|state| self::tilde(state)) - .or_else(|state| self::caret(state)) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn primitive( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::primitive, |state| { - state.sequence(|state| { - self::primitive_op(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state) - .and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::partial(state)) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn primitive_op( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::primitive_op, |state| { - state - .match_string("<=") - .or_else(|state| state.match_string(">=")) - .or_else(|state| state.match_string(">")) - .or_else(|state| state.match_string("<")) - .or_else(|state| state.match_string("=")) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn partial( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::partial, |state| { - state.sequence(|state| { - self::xr(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.optional(|state| { - state.sequence(|state| { - state - .match_string(".") - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::xr(state)) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.optional(|state| { - state.sequence(|state| { - state - .match_string(".") - .and_then(|state| { - super::hidden::skip(state) - }) - .and_then(|state| self::xr(state)) - .and_then(|state| { - super::hidden::skip(state) - }) - .and_then(|state| { - state.optional(|state| { - self::qualifier(state) - }) - }) - }) - }) - }) - }) - }) - }) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn xr( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::xr, |state| { - self::xr_op(state).or_else(|state| self::nr(state)) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn xr_op( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::xr_op, |state| { - state - .match_string("x") - .or_else(|state| state.match_string("X")) - .or_else(|state| state.match_string("*")) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn nr( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::nr, |state| { - state.match_string("0").or_else(|state| { - state.sequence(|state| { - state - .match_range('1'..'9') - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - state.match_range('0'..'9').and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state).and_then( - |state| state.match_range('0'..'9'), - ) - }) - }) - }) - }) - }) - }) - }) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn tilde( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::tilde, |state| { - state.sequence(|state| { - state - .match_string("~>") - .or_else(|state| state.match_string("~")) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state) - .and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::partial(state)) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn caret( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::caret, |state| { - state.sequence(|state| { - state - .match_string("^") - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - self::space(state).and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state) - .and_then(|state| self::space(state)) - }) - }) - }) - }) - }) - }) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::partial(state)) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn qualifier( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::qualifier, |state| { - state.sequence(|state| { - state - .match_string("-") - .or_else(|state| state.match_string("+")) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| self::parts(state)) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn parts( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::parts, |state| { - state.sequence(|state| { - self::part(state) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - state - .sequence(|state| { - state - .match_string(".") - .and_then(|state| { - super::hidden::skip(state) - }) - .and_then(|state| self::part(state)) - }) - .and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state).and_then( - |state| { - state.sequence(|state| { - state - .match_string(".") - .and_then(|state| { - super::hidden::skip( - state, - ) - }) - .and_then(|state| { - self::part(state) - }) - }) - }, - ) - }) - }) - }) - }) - }) - }) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn part( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::part, |state| { - self::nr(state).or_else(|state| { - state.sequence(|state| { - state - .match_string("-") - .or_else(|state| state.match_range('0'..'9')) - .or_else(|state| state.match_range('A'..'Z')) - .or_else(|state| state.match_range('a'..'z')) - .and_then(|state| super::hidden::skip(state)) - .and_then(|state| { - state.sequence(|state| { - state.optional(|state| { - state - .match_string("-") - .or_else(|state| state.match_range('0'..'9')) - .or_else(|state| state.match_range('A'..'Z')) - .or_else(|state| state.match_range('a'..'z')) - .and_then(|state| { - state.repeat(|state| { - state.sequence(|state| { - super::hidden::skip(state).and_then( - |state| { - state - .match_string("-") - .or_else(|state| { - state.match_range( - '0'..'9', - ) - }) - .or_else(|state| { - state.match_range( - 'A'..'Z', - ) - }) - .or_else(|state| { - state.match_range( - 'a'..'z', - ) - }) - }, - ) - }) - }) - }) - }) - }) - }) - }) - }) - }) - } - #[inline] - #[allow(non_snake_case, unused_variables)] - pub fn space( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state - .match_string(" ") - .or_else(|state| state.match_string("\t")) - } - #[inline] - #[allow(dead_code, non_snake_case, unused_variables)] - pub fn EOI( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.rule(Rule::EOI, |state| state.end_of_input()) - } - #[inline] - #[allow(dead_code, non_snake_case, unused_variables)] - pub fn SOI( - state: Box<::pest::ParserState>, - ) -> ::pest::ParseResult>> { - state.start_of_input() - } - } - pub use self::visible::*; - } - ::pest::state(input, |state| match rule { - Rule::range_set => rules::range_set(state), - Rule::logical_or => rules::logical_or(state), - Rule::range => rules::range(state), - Rule::empty => rules::empty(state), - Rule::hyphen => rules::hyphen(state), - Rule::simple => rules::simple(state), - Rule::primitive => rules::primitive(state), - Rule::primitive_op => rules::primitive_op(state), - Rule::partial => rules::partial(state), - Rule::xr => rules::xr(state), - Rule::xr_op => rules::xr_op(state), - Rule::nr => rules::nr(state), - Rule::tilde => rules::tilde(state), - Rule::caret => rules::caret(state), - Rule::qualifier => rules::qualifier(state), - Rule::parts => rules::parts(state), - Rule::part => rules::part(state), - Rule::space => rules::space(state), - Rule::EOI => rules::EOI(state), - }) - } -} diff --git a/tests/target/performance/issue-4867.rs b/tests/target/performance/issue-4867.rs deleted file mode 100644 index 336dae1b64ab8..0000000000000 --- a/tests/target/performance/issue-4867.rs +++ /dev/null @@ -1,13 +0,0 @@ -mod modA { - mod modB { - mod modC { - mod modD { - mod modE { - fn func() { - state . rule (Rule :: myrule , | state | { state . sequence (| state | { state . sequence (| state | { state . match_string ("abc") . and_then (| state | { super :: hidden :: skip (state) }) . and_then (| state | { state . match_string ("def") }) }) . and_then (| state | { super :: hidden :: skip (state) }) . and_then (| state | { state . sequence (| state | { state . optional (| state | { state . sequence (| state | { state . match_string ("abc") . and_then (| state | { super :: hidden :: skip (state) }) . and_then (| state | { state . match_string ("def") }) }) . and_then (| state | { state . repeat (| state | { state . sequence (| state | { super :: hidden :: skip (state) . and_then (| state | { state . sequence (| state | { state . match_string ("abc") . and_then (| state | { super :: hidden :: skip (state) }) . and_then (| state | { state . match_string ("def") }) }) }) }) }) }) }) }) }) }) }); - } - } - } - } - } -} diff --git a/tests/target/performance/issue-5128.rs b/tests/target/performance/issue-5128.rs deleted file mode 100644 index ba9ebfc6243f2..0000000000000 --- a/tests/target/performance/issue-5128.rs +++ /dev/null @@ -1,4898 +0,0 @@ -fn takes_a_long_time_to_rustfmt() { - let inner_cte = vec![Node { - node: Some(node::Node::CommonTableExpr(Box::new(CommonTableExpr { - ctename: String::from("ranked_by_age_within_key"), - aliascolnames: vec![], - ctematerialized: CteMaterialize::Default as i32, - ctequery: Some(Box::new(Node { - node: Some(node::Node::SelectStmt(Box::new(SelectStmt { - distinct_clause: vec![], - into_clause: None, - target_list: vec![ - Node { - node: Some(node::Node::ResTarget(Box::new(ResTarget { - name: String::from(""), - indirection: vec![], - val: Some(Box::new(Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::AStar(AStar {})), - }], - location: 80, - })), - })), - location: 80, - }))), - }, - Node { - node: Some(node::Node::ResTarget(Box::new(ResTarget { - name: String::from("rank_in_key"), - indirection: vec![], - val: Some(Box::new(Node { - node: Some(node::Node::FuncCall(Box::new(FuncCall { - funcname: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("row_number"), - })), - }], - args: vec![], - agg_order: vec![], - agg_filter: None, - agg_within_group: false, - agg_star: false, - agg_distinct: false, - func_variadic: false, - over: Some(Box::new(WindowDef { - name: String::from(""), - refname: String::from(""), - partition_clause: vec![Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("synthetic_key"), - })), - }], - location: 123, - })), - }], - order_clause: vec![Node { - node: Some(node::Node::SortBy(Box::new(SortBy { - node: Some(Box::new(Node { - node: Some(node::Node::ColumnRef( - ColumnRef { - fields: vec![Node { - node: Some(node::Node::String( - String2 { - str: String::from( - "logical_timestamp", - ), - }, - )), - }], - location: 156, - }, - )), - })), - sortby_dir: SortByDir::SortbyDesc as i32, - sortby_nulls: SortByNulls::SortbyNullsDefault - as i32, - use_op: vec![], - location: -1, - }))), - }], - frame_options: 1058, - start_offset: None, - end_offset: None, - location: 109, - })), - location: 91, - }))), - })), - location: 91, - }))), - }, - ], - from_clause: vec![Node { - node: Some(node::Node::RangeVar(RangeVar { - catalogname: String::from(""), - schemaname: String::from("_supertables"), - relname: String::from("9999-9999-9999"), - inh: true, - relpersistence: String::from("p"), - alias: None, - location: 206, - })), - }], - where_clause: Some(Box::new(Node { - node: Some(node::Node::AExpr(Box::new(AExpr { - kind: AExprKind::AexprOp as i32, - name: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("<="), - })), - }], - lexpr: Some(Box::new(Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("logical_timestamp"), - })), - }], - location: 250, - })), - })), - rexpr: Some(Box::new(Node { - node: Some(node::Node::AConst(Box::new(AConst { - val: Some(Box::new(Node { - node: Some(node::Node::Integer(Integer { ival: 9000 })), - })), - location: 271, - }))), - })), - location: 268, - }))), - })), - group_clause: vec![], - having_clause: None, - window_clause: vec![], - values_lists: vec![], - sort_clause: vec![], - limit_offset: None, - limit_count: None, - limit_option: LimitOption::Default as i32, - locking_clause: vec![], - with_clause: None, - op: SetOperation::SetopNone as i32, - all: false, - larg: None, - rarg: None, - }))), - })), - location: 29, - cterecursive: false, - cterefcount: 0, - ctecolnames: vec![], - ctecoltypes: vec![], - ctecoltypmods: vec![], - ctecolcollations: vec![], - }))), - }]; - let outer_cte = vec![Node { - node: Some(node::Node::CommonTableExpr(Box::new(CommonTableExpr { - ctename: String::from("table_name"), - aliascolnames: vec![], - ctematerialized: CteMaterialize::Default as i32, - ctequery: Some(Box::new(Node { - node: Some(node::Node::SelectStmt(Box::new(SelectStmt { - distinct_clause: vec![], - into_clause: None, - target_list: vec![ - Node { - node: Some(node::Node::ResTarget(Box::new(ResTarget { - name: String::from("column1"), - indirection: vec![], - val: Some(Box::new(Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("c1"), - })), - }], - location: 301, - })), - })), - location: 301, - }))), - }, - Node { - node: Some(node::Node::ResTarget(Box::new(ResTarget { - name: String::from("column2"), - indirection: vec![], - val: Some(Box::new(Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("c2"), - })), - }], - location: 324, - })), - })), - location: 324, - }))), - }, - ], - from_clause: vec![Node { - node: Some(node::Node::RangeVar(RangeVar { - catalogname: String::from(""), - schemaname: String::from(""), - relname: String::from("ranked_by_age_within_key"), - inh: true, - relpersistence: String::from("p"), - alias: None, - location: 347, - })), - }], - where_clause: Some(Box::new(Node { - node: Some(node::Node::BoolExpr(Box::new(BoolExpr { - xpr: None, - boolop: BoolExprType::AndExpr as i32, - args: vec![ - Node { - node: Some(node::Node::AExpr(Box::new(AExpr { - kind: AExprKind::AexprOp as i32, - name: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("="), - })), - }], - lexpr: Some(Box::new(Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("rank_in_key"), - })), - }], - location: 382, - })), - })), - rexpr: Some(Box::new(Node { - node: Some(node::Node::AConst(Box::new(AConst { - val: Some(Box::new(Node { - node: Some(node::Node::Integer(Integer { - ival: 1, - })), - })), - location: 396, - }))), - })), - location: 394, - }))), - }, - Node { - node: Some(node::Node::AExpr(Box::new(AExpr { - kind: AExprKind::AexprOp as i32, - name: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("="), - })), - }], - lexpr: Some(Box::new(Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("is_deleted"), - })), - }], - location: 402, - })), - })), - rexpr: Some(Box::new(Node { - node: Some(node::Node::TypeCast(Box::new(TypeCast { - arg: Some(Box::new(Node { - node: Some(node::Node::AConst(Box::new( - AConst { - val: Some(Box::new(Node { - node: Some(node::Node::String( - String2 { - str: String::from("f"), - }, - )), - })), - location: 415, - }, - ))), - })), - type_name: Some(TypeName { - names: vec![ - Node { - node: Some(node::Node::String( - String2 { - str: String::from("pg_catalog"), - }, - )), - }, - Node { - node: Some(node::Node::String( - String2 { - str: String::from("bool"), - }, - )), - }, - ], - type_oid: 0, - setof: false, - pct_type: false, - typmods: vec![], - typemod: -1, - array_bounds: vec![], - location: -1, - }), - location: -1, - }))), - })), - location: 413, - }))), - }, - ], - location: 398, - }))), - })), - group_clause: vec![], - having_clause: None, - window_clause: vec![], - values_lists: vec![], - sort_clause: vec![], - limit_offset: None, - limit_count: None, - limit_option: LimitOption::Default as i32, - locking_clause: vec![], - with_clause: Some(WithClause { - ctes: inner_cte, - recursive: false, - location: 24, - }), - op: SetOperation::SetopNone as i32, - all: false, - larg: None, - rarg: None, - }))), - })), - location: 5, - cterecursive: false, - cterefcount: 0, - ctecolnames: vec![], - ctecoltypes: vec![], - ctecoltypmods: vec![], - ctecolcollations: vec![], - }))), - }]; - let expected_result = ParseResult { - version: 130003, - stmts: vec![RawStmt { - stmt: Some(Box::new(Node { - node: Some(node::Node::SelectStmt(Box::new(SelectStmt { - distinct_clause: vec![], - into_clause: None, - - target_list: vec![Node { - node: Some(node::Node::ResTarget(Box::new(ResTarget { - name: String::from(""), - indirection: vec![], - val: Some(Box::new(Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("column1"), - })), - }], - location: 430, - })), - })), - location: 430, - }))), - }], - from_clause: vec![Node { - node: Some(node::Node::RangeVar(RangeVar { - catalogname: String::from(""), - schemaname: String::from(""), - relname: String::from("table_name"), - inh: true, - relpersistence: String::from("p"), - alias: None, - location: 443, - })), - }], - where_clause: Some(Box::new(Node { - node: Some(node::Node::AExpr(Box::new(AExpr { - kind: AExprKind::AexprOp as i32, - name: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from(">"), - })), - }], - lexpr: Some(Box::new(Node { - node: Some(node::Node::ColumnRef(ColumnRef { - fields: vec![Node { - node: Some(node::Node::String(String2 { - str: String::from("column2"), - })), - }], - location: 460, - })), - })), - rexpr: Some(Box::new(Node { - node: Some(node::Node::AConst(Box::new(AConst { - val: Some(Box::new(Node { - node: Some(node::Node::Integer(Integer { ival: 9000 })), - })), - location: 470, - }))), - })), - location: 468, - }))), - })), - group_clause: vec![], - having_clause: None, - window_clause: vec![], - values_lists: vec![], - sort_clause: vec![], - limit_offset: None, - limit_count: None, - limit_option: LimitOption::Default as i32, - locking_clause: vec![], - with_clause: Some(WithClause { - ctes: outer_cte, - recursive: false, - location: 0, - }), - op: SetOperation::SetopNone as i32, - all: false, - larg: None, - rarg: None, - }))), - })), - stmt_location: 0, - stmt_len: 0, - }], - }; -} -#[derive(Clone, PartialEq)] -pub struct ParseResult { - pub version: i32, - - pub stmts: Vec, -} -#[derive(Clone, PartialEq)] -pub struct ScanResult { - pub version: i32, - - pub tokens: Vec, -} -#[derive(Clone, PartialEq)] -pub struct Node { - pub node: ::core::option::Option, -} -/// Nested message and enum types in `Node`. -pub mod node { - #[derive(Clone, PartialEq)] - pub enum Node { - Alias(super::Alias), - - RangeVar(super::RangeVar), - - TableFunc(Box), - - Expr(super::Expr), - - Var(Box), - - Param(Box), - - Aggref(Box), - - GroupingFunc(Box), - - WindowFunc(Box), - - SubscriptingRef(Box), - - FuncExpr(Box), - - NamedArgExpr(Box), - - OpExpr(Box), - - DistinctExpr(Box), - - NullIfExpr(Box), - - ScalarArrayOpExpr(Box), - - BoolExpr(Box), - - SubLink(Box), - - SubPlan(Box), - - AlternativeSubPlan(Box), - - FieldSelect(Box), - - FieldStore(Box), - - RelabelType(Box), - - CoerceViaIo(Box), - - ArrayCoerceExpr(Box), - - ConvertRowtypeExpr(Box), - - CollateExpr(Box), - - CaseExpr(Box), - - CaseWhen(Box), - - CaseTestExpr(Box), - - ArrayExpr(Box), - - RowExpr(Box), - - RowCompareExpr(Box), - - CoalesceExpr(Box), - - MinMaxExpr(Box), - - SqlvalueFunction(Box), - - XmlExpr(Box), - - NullTest(Box), - - BooleanTest(Box), - - CoerceToDomain(Box), - - CoerceToDomainValue(Box), - - SetToDefault(Box), - - CurrentOfExpr(Box), - - NextValueExpr(Box), - - InferenceElem(Box), - - TargetEntry(Box), - - RangeTblRef(super::RangeTblRef), - - JoinExpr(Box), - - FromExpr(Box), - - OnConflictExpr(Box), - - IntoClause(Box), - - RawStmt(Box), - - Query(Box), - - InsertStmt(Box), - - DeleteStmt(Box), - - UpdateStmt(Box), - - SelectStmt(Box), - - AlterTableStmt(super::AlterTableStmt), - - AlterTableCmd(Box), - - AlterDomainStmt(Box), - - SetOperationStmt(Box), - - GrantStmt(super::GrantStmt), - - GrantRoleStmt(super::GrantRoleStmt), - - AlterDefaultPrivilegesStmt(super::AlterDefaultPrivilegesStmt), - - ClosePortalStmt(super::ClosePortalStmt), - - ClusterStmt(super::ClusterStmt), - - CopyStmt(Box), - - CreateStmt(super::CreateStmt), - - DefineStmt(super::DefineStmt), - - DropStmt(super::DropStmt), - - TruncateStmt(super::TruncateStmt), - - CommentStmt(Box), - - FetchStmt(super::FetchStmt), - - IndexStmt(Box), - - CreateFunctionStmt(super::CreateFunctionStmt), - - AlterFunctionStmt(super::AlterFunctionStmt), - - DoStmt(super::DoStmt), - - RenameStmt(Box), - - RuleStmt(Box), - - NotifyStmt(super::NotifyStmt), - - ListenStmt(super::ListenStmt), - - UnlistenStmt(super::UnlistenStmt), - - TransactionStmt(super::TransactionStmt), - - ViewStmt(Box), - - LoadStmt(super::LoadStmt), - - CreateDomainStmt(Box), - - CreatedbStmt(super::CreatedbStmt), - - DropdbStmt(super::DropdbStmt), - - VacuumStmt(super::VacuumStmt), - - ExplainStmt(Box), - - CreateTableAsStmt(Box), - - CreateSeqStmt(super::CreateSeqStmt), - - AlterSeqStmt(super::AlterSeqStmt), - - VariableSetStmt(super::VariableSetStmt), - - VariableShowStmt(super::VariableShowStmt), - - DiscardStmt(super::DiscardStmt), - - CreateTrigStmt(Box), - - CreatePlangStmt(super::CreatePLangStmt), - - CreateRoleStmt(super::CreateRoleStmt), - - AlterRoleStmt(super::AlterRoleStmt), - - DropRoleStmt(super::DropRoleStmt), - - LockStmt(super::LockStmt), - - ConstraintsSetStmt(super::ConstraintsSetStmt), - - ReindexStmt(super::ReindexStmt), - - CheckPointStmt(super::CheckPointStmt), - - CreateSchemaStmt(super::CreateSchemaStmt), - - AlterDatabaseStmt(super::AlterDatabaseStmt), - - AlterDatabaseSetStmt(super::AlterDatabaseSetStmt), - - AlterRoleSetStmt(super::AlterRoleSetStmt), - - CreateConversionStmt(super::CreateConversionStmt), - - CreateCastStmt(super::CreateCastStmt), - - CreateOpClassStmt(super::CreateOpClassStmt), - - CreateOpFamilyStmt(super::CreateOpFamilyStmt), - - AlterOpFamilyStmt(super::AlterOpFamilyStmt), - - PrepareStmt(Box), - - ExecuteStmt(super::ExecuteStmt), - - DeallocateStmt(super::DeallocateStmt), - - DeclareCursorStmt(Box), - - CreateTableSpaceStmt(super::CreateTableSpaceStmt), - - DropTableSpaceStmt(super::DropTableSpaceStmt), - - AlterObjectDependsStmt(Box), - - AlterObjectSchemaStmt(Box), - - AlterOwnerStmt(Box), - - AlterOperatorStmt(super::AlterOperatorStmt), - - AlterTypeStmt(super::AlterTypeStmt), - - DropOwnedStmt(super::DropOwnedStmt), - - ReassignOwnedStmt(super::ReassignOwnedStmt), - - CompositeTypeStmt(super::CompositeTypeStmt), - - CreateEnumStmt(super::CreateEnumStmt), - - CreateRangeStmt(super::CreateRangeStmt), - - AlterEnumStmt(super::AlterEnumStmt), - - AlterTsdictionaryStmt(super::AlterTsDictionaryStmt), - - AlterTsconfigurationStmt(super::AlterTsConfigurationStmt), - - CreateFdwStmt(super::CreateFdwStmt), - - AlterFdwStmt(super::AlterFdwStmt), - - CreateForeignServerStmt(super::CreateForeignServerStmt), - - AlterForeignServerStmt(super::AlterForeignServerStmt), - - CreateUserMappingStmt(super::CreateUserMappingStmt), - - AlterUserMappingStmt(super::AlterUserMappingStmt), - - DropUserMappingStmt(super::DropUserMappingStmt), - - AlterTableSpaceOptionsStmt(super::AlterTableSpaceOptionsStmt), - - AlterTableMoveAllStmt(super::AlterTableMoveAllStmt), - - SecLabelStmt(Box), - - CreateForeignTableStmt(super::CreateForeignTableStmt), - - ImportForeignSchemaStmt(super::ImportForeignSchemaStmt), - - CreateExtensionStmt(super::CreateExtensionStmt), - - AlterExtensionStmt(super::AlterExtensionStmt), - - AlterExtensionContentsStmt(Box), - - CreateEventTrigStmt(super::CreateEventTrigStmt), - - AlterEventTrigStmt(super::AlterEventTrigStmt), - - RefreshMatViewStmt(super::RefreshMatViewStmt), - - ReplicaIdentityStmt(super::ReplicaIdentityStmt), - - AlterSystemStmt(super::AlterSystemStmt), - - CreatePolicyStmt(Box), - - AlterPolicyStmt(Box), - - CreateTransformStmt(super::CreateTransformStmt), - - CreateAmStmt(super::CreateAmStmt), - - CreatePublicationStmt(super::CreatePublicationStmt), - - AlterPublicationStmt(super::AlterPublicationStmt), - - CreateSubscriptionStmt(super::CreateSubscriptionStmt), - - AlterSubscriptionStmt(super::AlterSubscriptionStmt), - - DropSubscriptionStmt(super::DropSubscriptionStmt), - - CreateStatsStmt(super::CreateStatsStmt), - - AlterCollationStmt(super::AlterCollationStmt), - - CallStmt(Box), - - AlterStatsStmt(super::AlterStatsStmt), - - AExpr(Box), - - ColumnRef(super::ColumnRef), - - ParamRef(super::ParamRef), - - AConst(Box), - - FuncCall(Box), - - AStar(super::AStar), - - AIndices(Box), - - AIndirection(Box), - - AArrayExpr(super::AArrayExpr), - - ResTarget(Box), - - MultiAssignRef(Box), - - TypeCast(Box), - - CollateClause(Box), - - SortBy(Box), - - WindowDef(Box), - - RangeSubselect(Box), - - RangeFunction(super::RangeFunction), - - RangeTableSample(Box), - - RangeTableFunc(Box), - - RangeTableFuncCol(Box), - - TypeName(super::TypeName), - - ColumnDef(Box), - - IndexElem(Box), - - Constraint(Box), - - DefElem(Box), - - RangeTblEntry(Box), - - RangeTblFunction(Box), - - TableSampleClause(Box), - - WithCheckOption(Box), - - SortGroupClause(super::SortGroupClause), - - GroupingSet(super::GroupingSet), - - WindowClause(Box), - - ObjectWithArgs(super::ObjectWithArgs), - - AccessPriv(super::AccessPriv), - - CreateOpClassItem(super::CreateOpClassItem), - - TableLikeClause(super::TableLikeClause), - - FunctionParameter(Box), - - LockingClause(super::LockingClause), - - RowMarkClause(super::RowMarkClause), - - XmlSerialize(Box), - - WithClause(super::WithClause), - - InferClause(Box), - - OnConflictClause(Box), - - CommonTableExpr(Box), - - RoleSpec(super::RoleSpec), - - TriggerTransition(super::TriggerTransition), - - PartitionElem(Box), - - PartitionSpec(super::PartitionSpec), - - PartitionBoundSpec(super::PartitionBoundSpec), - - PartitionRangeDatum(Box), - - PartitionCmd(super::PartitionCmd), - - VacuumRelation(super::VacuumRelation), - - InlineCodeBlock(super::InlineCodeBlock), - - CallContext(super::CallContext), - - Integer(super::Integer), - - Float(super::Float), - - String(super::String2), - - BitString(super::BitString), - - Null(super::Null), - - List(super::List), - - IntList(super::IntList), - - OidList(super::OidList), - } -} -#[derive(Clone, PartialEq)] -pub struct Integer { - /// machine integer - pub ival: i32, -} -#[derive(Clone, PartialEq)] -pub struct Float { - /// string - pub str: String, -} -#[derive(Clone, PartialEq)] -pub struct String2 { - /// string - pub str: String, -} -#[derive(Clone, PartialEq)] -pub struct BitString { - /// string - pub str: String, -} -/// intentionally empty -#[derive(Clone, PartialEq)] -pub struct Null {} -#[derive(Clone, PartialEq)] -pub struct List { - pub items: Vec, -} -#[derive(Clone, PartialEq)] -pub struct OidList { - pub items: Vec, -} -#[derive(Clone, PartialEq)] -pub struct IntList { - pub items: Vec, -} -#[derive(Clone, PartialEq)] -pub struct Alias { - pub aliasname: String, - - pub colnames: Vec, -} -#[derive(Clone, PartialEq)] -pub struct RangeVar { - pub catalogname: String, - - pub schemaname: String, - - pub relname: String, - - pub inh: bool, - - pub relpersistence: String, - - pub alias: ::core::option::Option, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct TableFunc { - pub ns_uris: Vec, - - pub ns_names: Vec, - - pub docexpr: ::core::option::Option>, - - pub rowexpr: ::core::option::Option>, - - pub colnames: Vec, - - pub coltypes: Vec, - - pub coltypmods: Vec, - - pub colcollations: Vec, - - pub colexprs: Vec, - - pub coldefexprs: Vec, - - pub notnulls: Vec, - - pub ordinalitycol: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct Expr {} -#[derive(Clone, PartialEq)] -pub struct Var { - pub xpr: ::core::option::Option>, - - pub varno: u32, - - pub varattno: i32, - - pub vartype: u32, - - pub vartypmod: i32, - - pub varcollid: u32, - - pub varlevelsup: u32, - - pub varnosyn: u32, - - pub varattnosyn: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct Param { - pub xpr: ::core::option::Option>, - - pub paramkind: i32, - - pub paramid: i32, - - pub paramtype: u32, - - pub paramtypmod: i32, - - pub paramcollid: u32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct Aggref { - pub xpr: ::core::option::Option>, - - pub aggfnoid: u32, - - pub aggtype: u32, - - pub aggcollid: u32, - - pub inputcollid: u32, - - pub aggtranstype: u32, - - pub aggargtypes: Vec, - - pub aggdirectargs: Vec, - - pub args: Vec, - - pub aggorder: Vec, - - pub aggdistinct: Vec, - - pub aggfilter: ::core::option::Option>, - - pub aggstar: bool, - - pub aggvariadic: bool, - - pub aggkind: String, - - pub agglevelsup: u32, - - pub aggsplit: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct GroupingFunc { - pub xpr: ::core::option::Option>, - - pub args: Vec, - - pub refs: Vec, - - pub cols: Vec, - - pub agglevelsup: u32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct WindowFunc { - pub xpr: ::core::option::Option>, - - pub winfnoid: u32, - - pub wintype: u32, - - pub wincollid: u32, - - pub inputcollid: u32, - - pub args: Vec, - - pub aggfilter: ::core::option::Option>, - - pub winref: u32, - - pub winstar: bool, - - pub winagg: bool, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct SubscriptingRef { - pub xpr: ::core::option::Option>, - - pub refcontainertype: u32, - - pub refelemtype: u32, - - pub reftypmod: i32, - - pub refcollid: u32, - - pub refupperindexpr: Vec, - - pub reflowerindexpr: Vec, - - pub refexpr: ::core::option::Option>, - - pub refassgnexpr: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct FuncExpr { - pub xpr: ::core::option::Option>, - - pub funcid: u32, - - pub funcresulttype: u32, - - pub funcretset: bool, - - pub funcvariadic: bool, - - pub funcformat: i32, - - pub funccollid: u32, - - pub inputcollid: u32, - - pub args: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct NamedArgExpr { - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub name: String, - - pub argnumber: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct OpExpr { - pub xpr: ::core::option::Option>, - - pub opno: u32, - - pub opfuncid: u32, - - pub opresulttype: u32, - - pub opretset: bool, - - pub opcollid: u32, - - pub inputcollid: u32, - - pub args: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct DistinctExpr { - pub xpr: ::core::option::Option>, - - pub opno: u32, - - pub opfuncid: u32, - - pub opresulttype: u32, - - pub opretset: bool, - - pub opcollid: u32, - - pub inputcollid: u32, - - pub args: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct NullIfExpr { - pub xpr: ::core::option::Option>, - - pub opno: u32, - - pub opfuncid: u32, - - pub opresulttype: u32, - - pub opretset: bool, - - pub opcollid: u32, - - pub inputcollid: u32, - - pub args: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct ScalarArrayOpExpr { - pub xpr: ::core::option::Option>, - - pub opno: u32, - - pub opfuncid: u32, - - pub use_or: bool, - - pub inputcollid: u32, - - pub args: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct BoolExpr { - pub xpr: ::core::option::Option>, - - pub boolop: i32, - - pub args: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct SubLink { - pub xpr: ::core::option::Option>, - - pub sub_link_type: i32, - - pub sub_link_id: i32, - - pub testexpr: ::core::option::Option>, - - pub oper_name: Vec, - - pub subselect: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct SubPlan { - pub xpr: ::core::option::Option>, - - pub sub_link_type: i32, - - pub testexpr: ::core::option::Option>, - - pub param_ids: Vec, - - pub plan_id: i32, - - pub plan_name: String, - - pub first_col_type: u32, - - pub first_col_typmod: i32, - - pub first_col_collation: u32, - - pub use_hash_table: bool, - - pub unknown_eq_false: bool, - - pub parallel_safe: bool, - - pub set_param: Vec, - - pub par_param: Vec, - - pub args: Vec, - - pub startup_cost: f64, - - pub per_call_cost: f64, -} -#[derive(Clone, PartialEq)] -pub struct AlternativeSubPlan { - pub xpr: ::core::option::Option>, - - pub subplans: Vec, -} -#[derive(Clone, PartialEq)] -pub struct FieldSelect { - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub fieldnum: i32, - - pub resulttype: u32, - - pub resulttypmod: i32, - - pub resultcollid: u32, -} -#[derive(Clone, PartialEq)] -pub struct FieldStore { - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub newvals: Vec, - - pub fieldnums: Vec, - - pub resulttype: u32, -} -#[derive(Clone, PartialEq)] -pub struct RelabelType { - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub resulttype: u32, - - pub resulttypmod: i32, - - pub resultcollid: u32, - - pub relabelformat: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CoerceViaIo { - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub resulttype: u32, - - pub resultcollid: u32, - - pub coerceformat: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct ArrayCoerceExpr { - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub elemexpr: ::core::option::Option>, - - pub resulttype: u32, - - pub resulttypmod: i32, - - pub resultcollid: u32, - - pub coerceformat: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct ConvertRowtypeExpr { - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub resulttype: u32, - - pub convertformat: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CollateExpr { - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub coll_oid: u32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CaseExpr { - pub xpr: ::core::option::Option>, - - pub casetype: u32, - - pub casecollid: u32, - - pub arg: ::core::option::Option>, - - pub args: Vec, - - pub defresult: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CaseWhen { - pub xpr: ::core::option::Option>, - - pub expr: ::core::option::Option>, - - pub result: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CaseTestExpr { - pub xpr: ::core::option::Option>, - - pub type_id: u32, - - pub type_mod: i32, - - pub collation: u32, -} -#[derive(Clone, PartialEq)] -pub struct ArrayExpr { - pub xpr: ::core::option::Option>, - - pub array_typeid: u32, - - pub array_collid: u32, - - pub element_typeid: u32, - - pub elements: Vec, - - pub multidims: bool, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct RowExpr { - pub xpr: ::core::option::Option>, - - pub args: Vec, - - pub row_typeid: u32, - - pub row_format: i32, - - pub colnames: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct RowCompareExpr { - pub xpr: ::core::option::Option>, - - pub rctype: i32, - - pub opnos: Vec, - - pub opfamilies: Vec, - - pub inputcollids: Vec, - - pub largs: Vec, - - pub rargs: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CoalesceExpr { - pub xpr: ::core::option::Option>, - - pub coalescetype: u32, - - pub coalescecollid: u32, - - pub args: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct MinMaxExpr { - pub xpr: ::core::option::Option>, - - pub minmaxtype: u32, - - pub minmaxcollid: u32, - - pub inputcollid: u32, - - pub op: i32, - - pub args: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct SqlValueFunction { - pub xpr: ::core::option::Option>, - - pub op: i32, - - pub r#type: u32, - - pub typmod: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct XmlExpr { - pub xpr: ::core::option::Option>, - - pub op: i32, - - pub name: String, - - pub named_args: Vec, - - pub arg_names: Vec, - - pub args: Vec, - - pub xmloption: i32, - - pub r#type: u32, - - pub typmod: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct NullTest { - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub nulltesttype: i32, - - pub argisrow: bool, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct BooleanTest { - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub booltesttype: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CoerceToDomain { - pub xpr: ::core::option::Option>, - - pub arg: ::core::option::Option>, - - pub resulttype: u32, - - pub resulttypmod: i32, - - pub resultcollid: u32, - - pub coercionformat: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CoerceToDomainValue { - pub xpr: ::core::option::Option>, - - pub type_id: u32, - - pub type_mod: i32, - - pub collation: u32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct SetToDefault { - pub xpr: ::core::option::Option>, - - pub type_id: u32, - - pub type_mod: i32, - - pub collation: u32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CurrentOfExpr { - pub xpr: ::core::option::Option>, - - pub cvarno: u32, - - pub cursor_name: String, - - pub cursor_param: i32, -} -#[derive(Clone, PartialEq)] -pub struct NextValueExpr { - pub xpr: ::core::option::Option>, - - pub seqid: u32, - - pub type_id: u32, -} -#[derive(Clone, PartialEq)] -pub struct InferenceElem { - pub xpr: ::core::option::Option>, - - pub expr: ::core::option::Option>, - - pub infercollid: u32, - - pub inferopclass: u32, -} -#[derive(Clone, PartialEq)] -pub struct TargetEntry { - pub xpr: ::core::option::Option>, - - pub expr: ::core::option::Option>, - - pub resno: i32, - - pub resname: String, - - pub ressortgroupref: u32, - - pub resorigtbl: u32, - - pub resorigcol: i32, - - pub resjunk: bool, -} -#[derive(Clone, PartialEq)] -pub struct RangeTblRef { - pub rtindex: i32, -} -#[derive(Clone, PartialEq)] -pub struct JoinExpr { - pub jointype: i32, - - pub is_natural: bool, - - pub larg: ::core::option::Option>, - - pub rarg: ::core::option::Option>, - - pub using_clause: Vec, - - pub quals: ::core::option::Option>, - - pub alias: ::core::option::Option, - - pub rtindex: i32, -} -#[derive(Clone, PartialEq)] -pub struct FromExpr { - pub fromlist: Vec, - - pub quals: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct OnConflictExpr { - pub action: i32, - - pub arbiter_elems: Vec, - - pub arbiter_where: ::core::option::Option>, - - pub constraint: u32, - - pub on_conflict_set: Vec, - - pub on_conflict_where: ::core::option::Option>, - - pub excl_rel_index: i32, - - pub excl_rel_tlist: Vec, -} -#[derive(Clone, PartialEq)] -pub struct IntoClause { - pub rel: ::core::option::Option, - - pub col_names: Vec, - - pub access_method: String, - - pub options: Vec, - - pub on_commit: i32, - - pub table_space_name: String, - - pub view_query: ::core::option::Option>, - - pub skip_data: bool, -} -#[derive(Clone, PartialEq)] -pub struct RawStmt { - pub stmt: ::core::option::Option>, - - pub stmt_location: i32, - - pub stmt_len: i32, -} -#[derive(Clone, PartialEq)] -pub struct Query { - pub command_type: i32, - - pub query_source: i32, - - pub can_set_tag: bool, - - pub utility_stmt: ::core::option::Option>, - - pub result_relation: i32, - - pub has_aggs: bool, - - pub has_window_funcs: bool, - - pub has_target_srfs: bool, - - pub has_sub_links: bool, - - pub has_distinct_on: bool, - - pub has_recursive: bool, - - pub has_modifying_cte: bool, - - pub has_for_update: bool, - - pub has_row_security: bool, - - pub cte_list: Vec, - - pub rtable: Vec, - - pub jointree: ::core::option::Option>, - - pub target_list: Vec, - - pub r#override: i32, - - pub on_conflict: ::core::option::Option>, - - pub returning_list: Vec, - - pub group_clause: Vec, - - pub grouping_sets: Vec, - - pub having_qual: ::core::option::Option>, - - pub window_clause: Vec, - - pub distinct_clause: Vec, - - pub sort_clause: Vec, - - pub limit_offset: ::core::option::Option>, - - pub limit_count: ::core::option::Option>, - - pub limit_option: i32, - - pub row_marks: Vec, - - pub set_operations: ::core::option::Option>, - - pub constraint_deps: Vec, - - pub with_check_options: Vec, - - pub stmt_location: i32, - - pub stmt_len: i32, -} -#[derive(Clone, PartialEq)] -pub struct InsertStmt { - pub relation: ::core::option::Option, - - pub cols: Vec, - - pub select_stmt: ::core::option::Option>, - - pub on_conflict_clause: ::core::option::Option>, - - pub returning_list: Vec, - - pub with_clause: ::core::option::Option, - - pub r#override: i32, -} -#[derive(Clone, PartialEq)] -pub struct DeleteStmt { - pub relation: ::core::option::Option, - - pub using_clause: Vec, - - pub where_clause: ::core::option::Option>, - - pub returning_list: Vec, - - pub with_clause: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct UpdateStmt { - pub relation: ::core::option::Option, - - pub target_list: Vec, - - pub where_clause: ::core::option::Option>, - - pub from_clause: Vec, - - pub returning_list: Vec, - - pub with_clause: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct SelectStmt { - pub distinct_clause: Vec, - - pub into_clause: ::core::option::Option>, - - pub target_list: Vec, - - pub from_clause: Vec, - - pub where_clause: ::core::option::Option>, - - pub group_clause: Vec, - - pub having_clause: ::core::option::Option>, - - pub window_clause: Vec, - - pub values_lists: Vec, - - pub sort_clause: Vec, - - pub limit_offset: ::core::option::Option>, - - pub limit_count: ::core::option::Option>, - - pub limit_option: i32, - - pub locking_clause: Vec, - - pub with_clause: ::core::option::Option, - - pub op: i32, - - pub all: bool, - - pub larg: ::core::option::Option>, - - pub rarg: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct AlterTableStmt { - pub relation: ::core::option::Option, - - pub cmds: Vec, - - pub relkind: i32, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterTableCmd { - pub subtype: i32, - - pub name: String, - - pub num: i32, - - pub newowner: ::core::option::Option, - - pub def: ::core::option::Option>, - - pub behavior: i32, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterDomainStmt { - pub subtype: String, - - pub type_name: Vec, - - pub name: String, - - pub def: ::core::option::Option>, - - pub behavior: i32, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct SetOperationStmt { - pub op: i32, - - pub all: bool, - - pub larg: ::core::option::Option>, - - pub rarg: ::core::option::Option>, - - pub col_types: Vec, - - pub col_typmods: Vec, - - pub col_collations: Vec, - - pub group_clauses: Vec, -} -#[derive(Clone, PartialEq)] -pub struct GrantStmt { - pub is_grant: bool, - - pub targtype: i32, - - pub objtype: i32, - - pub objects: Vec, - - pub privileges: Vec, - - pub grantees: Vec, - - pub grant_option: bool, - - pub behavior: i32, -} -#[derive(Clone, PartialEq)] -pub struct GrantRoleStmt { - pub granted_roles: Vec, - - pub grantee_roles: Vec, - - pub is_grant: bool, - - pub admin_opt: bool, - - pub grantor: ::core::option::Option, - - pub behavior: i32, -} -#[derive(Clone, PartialEq)] -pub struct AlterDefaultPrivilegesStmt { - pub options: Vec, - - pub action: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct ClosePortalStmt { - pub portalname: String, -} -#[derive(Clone, PartialEq)] -pub struct ClusterStmt { - pub relation: ::core::option::Option, - - pub indexname: String, - - pub options: i32, -} -#[derive(Clone, PartialEq)] -pub struct CopyStmt { - pub relation: ::core::option::Option, - - pub query: ::core::option::Option>, - - pub attlist: Vec, - - pub is_from: bool, - - pub is_program: bool, - - pub filename: String, - - pub options: Vec, - - pub where_clause: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct CreateStmt { - pub relation: ::core::option::Option, - - pub table_elts: Vec, - - pub inh_relations: Vec, - - pub partbound: ::core::option::Option, - - pub partspec: ::core::option::Option, - - pub of_typename: ::core::option::Option, - - pub constraints: Vec, - - pub options: Vec, - - pub oncommit: i32, - - pub tablespacename: String, - - pub access_method: String, - - pub if_not_exists: bool, -} -#[derive(Clone, PartialEq)] -pub struct DefineStmt { - pub kind: i32, - - pub oldstyle: bool, - - pub defnames: Vec, - - pub args: Vec, - - pub definition: Vec, - - pub if_not_exists: bool, - - pub replace: bool, -} -#[derive(Clone, PartialEq)] -pub struct DropStmt { - pub objects: Vec, - - pub remove_type: i32, - - pub behavior: i32, - - pub missing_ok: bool, - - pub concurrent: bool, -} -#[derive(Clone, PartialEq)] -pub struct TruncateStmt { - pub relations: Vec, - - pub restart_seqs: bool, - - pub behavior: i32, -} -#[derive(Clone, PartialEq)] -pub struct CommentStmt { - pub objtype: i32, - - pub object: ::core::option::Option>, - - pub comment: String, -} -#[derive(Clone, PartialEq)] -pub struct FetchStmt { - pub direction: i32, - - pub how_many: i64, - - pub portalname: String, - - pub ismove: bool, -} -#[derive(Clone, PartialEq)] -pub struct IndexStmt { - pub idxname: String, - - pub relation: ::core::option::Option, - - pub access_method: String, - - pub table_space: String, - - pub index_params: Vec, - - pub index_including_params: Vec, - - pub options: Vec, - - pub where_clause: ::core::option::Option>, - - pub exclude_op_names: Vec, - - pub idxcomment: String, - - pub index_oid: u32, - - pub old_node: u32, - - pub old_create_subid: u32, - - pub old_first_relfilenode_subid: u32, - - pub unique: bool, - - pub primary: bool, - - pub isconstraint: bool, - - pub deferrable: bool, - - pub initdeferred: bool, - - pub transformed: bool, - - pub concurrent: bool, - - pub if_not_exists: bool, - - pub reset_default_tblspc: bool, -} -#[derive(Clone, PartialEq)] -pub struct CreateFunctionStmt { - pub is_procedure: bool, - - pub replace: bool, - - pub funcname: Vec, - - pub parameters: Vec, - - pub return_type: ::core::option::Option, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterFunctionStmt { - pub objtype: i32, - - pub func: ::core::option::Option, - - pub actions: Vec, -} -#[derive(Clone, PartialEq)] -pub struct DoStmt { - pub args: Vec, -} -#[derive(Clone, PartialEq)] -pub struct RenameStmt { - pub rename_type: i32, - - pub relation_type: i32, - - pub relation: ::core::option::Option, - - pub object: ::core::option::Option>, - - pub subname: String, - - pub newname: String, - - pub behavior: i32, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct RuleStmt { - pub relation: ::core::option::Option, - - pub rulename: String, - - pub where_clause: ::core::option::Option>, - - pub event: i32, - - pub instead: bool, - - pub actions: Vec, - - pub replace: bool, -} -#[derive(Clone, PartialEq)] -pub struct NotifyStmt { - pub conditionname: String, - - pub payload: String, -} -#[derive(Clone, PartialEq)] -pub struct ListenStmt { - pub conditionname: String, -} -#[derive(Clone, PartialEq)] -pub struct UnlistenStmt { - pub conditionname: String, -} -#[derive(Clone, PartialEq)] -pub struct TransactionStmt { - pub kind: i32, - - pub options: Vec, - - pub savepoint_name: String, - - pub gid: String, - - pub chain: bool, -} -#[derive(Clone, PartialEq)] -pub struct ViewStmt { - pub view: ::core::option::Option, - - pub aliases: Vec, - - pub query: ::core::option::Option>, - - pub replace: bool, - - pub options: Vec, - - pub with_check_option: i32, -} -#[derive(Clone, PartialEq)] -pub struct LoadStmt { - pub filename: String, -} -#[derive(Clone, PartialEq)] -pub struct CreateDomainStmt { - pub domainname: Vec, - - pub type_name: ::core::option::Option, - - pub coll_clause: ::core::option::Option>, - - pub constraints: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CreatedbStmt { - pub dbname: String, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct DropdbStmt { - pub dbname: String, - - pub missing_ok: bool, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct VacuumStmt { - pub options: Vec, - - pub rels: Vec, - - pub is_vacuumcmd: bool, -} -#[derive(Clone, PartialEq)] -pub struct ExplainStmt { - pub query: ::core::option::Option>, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CreateTableAsStmt { - pub query: ::core::option::Option>, - - pub into: ::core::option::Option>, - - pub relkind: i32, - - pub is_select_into: bool, - - pub if_not_exists: bool, -} -#[derive(Clone, PartialEq)] -pub struct CreateSeqStmt { - pub sequence: ::core::option::Option, - - pub options: Vec, - - pub owner_id: u32, - - pub for_identity: bool, - - pub if_not_exists: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterSeqStmt { - pub sequence: ::core::option::Option, - - pub options: Vec, - - pub for_identity: bool, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct VariableSetStmt { - pub kind: i32, - - pub name: String, - - pub args: Vec, - - pub is_local: bool, -} -#[derive(Clone, PartialEq)] -pub struct VariableShowStmt { - pub name: String, -} -#[derive(Clone, PartialEq)] -pub struct DiscardStmt { - pub target: i32, -} -#[derive(Clone, PartialEq)] -pub struct CreateTrigStmt { - pub trigname: String, - - pub relation: ::core::option::Option, - - pub funcname: Vec, - - pub args: Vec, - - pub row: bool, - - pub timing: i32, - - pub events: i32, - - pub columns: Vec, - - pub when_clause: ::core::option::Option>, - - pub isconstraint: bool, - - pub transition_rels: Vec, - - pub deferrable: bool, - - pub initdeferred: bool, - - pub constrrel: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct CreatePLangStmt { - pub replace: bool, - - pub plname: String, - - pub plhandler: Vec, - - pub plinline: Vec, - - pub plvalidator: Vec, - - pub pltrusted: bool, -} -#[derive(Clone, PartialEq)] -pub struct CreateRoleStmt { - pub stmt_type: i32, - - pub role: String, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterRoleStmt { - pub role: ::core::option::Option, - - pub options: Vec, - - pub action: i32, -} -#[derive(Clone, PartialEq)] -pub struct DropRoleStmt { - pub roles: Vec, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct LockStmt { - pub relations: Vec, - - pub mode: i32, - - pub nowait: bool, -} -#[derive(Clone, PartialEq)] -pub struct ConstraintsSetStmt { - pub constraints: Vec, - - pub deferred: bool, -} -#[derive(Clone, PartialEq)] -pub struct ReindexStmt { - pub kind: i32, - - pub relation: ::core::option::Option, - - pub name: String, - - pub options: i32, - - pub concurrent: bool, -} -#[derive(Clone, PartialEq)] -pub struct CheckPointStmt {} -#[derive(Clone, PartialEq)] -pub struct CreateSchemaStmt { - pub schemaname: String, - - pub authrole: ::core::option::Option, - - pub schema_elts: Vec, - - pub if_not_exists: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterDatabaseStmt { - pub dbname: String, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterDatabaseSetStmt { - pub dbname: String, - - pub setstmt: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct AlterRoleSetStmt { - pub role: ::core::option::Option, - - pub database: String, - - pub setstmt: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct CreateConversionStmt { - pub conversion_name: Vec, - - pub for_encoding_name: String, - - pub to_encoding_name: String, - - pub func_name: Vec, - - pub def: bool, -} -#[derive(Clone, PartialEq)] -pub struct CreateCastStmt { - pub sourcetype: ::core::option::Option, - - pub targettype: ::core::option::Option, - - pub func: ::core::option::Option, - - pub context: i32, - - pub inout: bool, -} -#[derive(Clone, PartialEq)] -pub struct CreateOpClassStmt { - pub opclassname: Vec, - - pub opfamilyname: Vec, - - pub amname: String, - - pub datatype: ::core::option::Option, - - pub items: Vec, - - pub is_default: bool, -} -#[derive(Clone, PartialEq)] -pub struct CreateOpFamilyStmt { - pub opfamilyname: Vec, - - pub amname: String, -} -#[derive(Clone, PartialEq)] -pub struct AlterOpFamilyStmt { - pub opfamilyname: Vec, - - pub amname: String, - - pub is_drop: bool, - - pub items: Vec, -} -#[derive(Clone, PartialEq)] -pub struct PrepareStmt { - pub name: String, - - pub argtypes: Vec, - - pub query: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct ExecuteStmt { - pub name: String, - - pub params: Vec, -} -#[derive(Clone, PartialEq)] -pub struct DeallocateStmt { - pub name: String, -} -#[derive(Clone, PartialEq)] -pub struct DeclareCursorStmt { - pub portalname: String, - - pub options: i32, - - pub query: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct CreateTableSpaceStmt { - pub tablespacename: String, - - pub owner: ::core::option::Option, - - pub location: String, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct DropTableSpaceStmt { - pub tablespacename: String, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterObjectDependsStmt { - pub object_type: i32, - - pub relation: ::core::option::Option, - - pub object: ::core::option::Option>, - - pub extname: ::core::option::Option>, - - pub remove: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterObjectSchemaStmt { - pub object_type: i32, - - pub relation: ::core::option::Option, - - pub object: ::core::option::Option>, - - pub newschema: String, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterOwnerStmt { - pub object_type: i32, - - pub relation: ::core::option::Option, - - pub object: ::core::option::Option>, - - pub newowner: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct AlterOperatorStmt { - pub opername: ::core::option::Option, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterTypeStmt { - pub type_name: Vec, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct DropOwnedStmt { - pub roles: Vec, - - pub behavior: i32, -} -#[derive(Clone, PartialEq)] -pub struct ReassignOwnedStmt { - pub roles: Vec, - - pub newrole: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct CompositeTypeStmt { - pub typevar: ::core::option::Option, - - pub coldeflist: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CreateEnumStmt { - pub type_name: Vec, - - pub vals: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CreateRangeStmt { - pub type_name: Vec, - - pub params: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterEnumStmt { - pub type_name: Vec, - - pub old_val: String, - - pub new_val: String, - - pub new_val_neighbor: String, - - pub new_val_is_after: bool, - - pub skip_if_new_val_exists: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterTsDictionaryStmt { - pub dictname: Vec, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterTsConfigurationStmt { - pub kind: i32, - - pub cfgname: Vec, - - pub tokentype: Vec, - - pub dicts: Vec, - - pub r#override: bool, - - pub replace: bool, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct CreateFdwStmt { - pub fdwname: String, - - pub func_options: Vec, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterFdwStmt { - pub fdwname: String, - - pub func_options: Vec, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CreateForeignServerStmt { - pub servername: String, - - pub servertype: String, - - pub version: String, - - pub fdwname: String, - - pub if_not_exists: bool, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterForeignServerStmt { - pub servername: String, - - pub version: String, - - pub options: Vec, - - pub has_version: bool, -} -#[derive(Clone, PartialEq)] -pub struct CreateUserMappingStmt { - pub user: ::core::option::Option, - - pub servername: String, - - pub if_not_exists: bool, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterUserMappingStmt { - pub user: ::core::option::Option, - - pub servername: String, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct DropUserMappingStmt { - pub user: ::core::option::Option, - - pub servername: String, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterTableSpaceOptionsStmt { - pub tablespacename: String, - - pub options: Vec, - - pub is_reset: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterTableMoveAllStmt { - pub orig_tablespacename: String, - - pub objtype: i32, - - pub roles: Vec, - - pub new_tablespacename: String, - - pub nowait: bool, -} -#[derive(Clone, PartialEq)] -pub struct SecLabelStmt { - pub objtype: i32, - - pub object: ::core::option::Option>, - - pub provider: String, - - pub label: String, -} -#[derive(Clone, PartialEq)] -pub struct CreateForeignTableStmt { - pub base_stmt: ::core::option::Option, - - pub servername: String, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct ImportForeignSchemaStmt { - pub server_name: String, - - pub remote_schema: String, - - pub local_schema: String, - - pub list_type: i32, - - pub table_list: Vec, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CreateExtensionStmt { - pub extname: String, - - pub if_not_exists: bool, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterExtensionStmt { - pub extname: String, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterExtensionContentsStmt { - pub extname: String, - - pub action: i32, - - pub objtype: i32, - - pub object: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct CreateEventTrigStmt { - pub trigname: String, - - pub eventname: String, - - pub whenclause: Vec, - - pub funcname: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterEventTrigStmt { - pub trigname: String, - - pub tgenabled: String, -} -#[derive(Clone, PartialEq)] -pub struct RefreshMatViewStmt { - pub concurrent: bool, - - pub skip_data: bool, - - pub relation: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct ReplicaIdentityStmt { - pub identity_type: String, - - pub name: String, -} -#[derive(Clone, PartialEq)] -pub struct AlterSystemStmt { - pub setstmt: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct CreatePolicyStmt { - pub policy_name: String, - - pub table: ::core::option::Option, - - pub cmd_name: String, - - pub permissive: bool, - - pub roles: Vec, - - pub qual: ::core::option::Option>, - - pub with_check: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct AlterPolicyStmt { - pub policy_name: String, - - pub table: ::core::option::Option, - - pub roles: Vec, - - pub qual: ::core::option::Option>, - - pub with_check: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct CreateTransformStmt { - pub replace: bool, - - pub type_name: ::core::option::Option, - - pub lang: String, - - pub fromsql: ::core::option::Option, - - pub tosql: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct CreateAmStmt { - pub amname: String, - - pub handler_name: Vec, - - pub amtype: String, -} -#[derive(Clone, PartialEq)] -pub struct CreatePublicationStmt { - pub pubname: String, - - pub options: Vec, - - pub tables: Vec, - - pub for_all_tables: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterPublicationStmt { - pub pubname: String, - - pub options: Vec, - - pub tables: Vec, - - pub for_all_tables: bool, - - pub table_action: i32, -} -#[derive(Clone, PartialEq)] -pub struct CreateSubscriptionStmt { - pub subname: String, - - pub conninfo: String, - - pub publication: Vec, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AlterSubscriptionStmt { - pub kind: i32, - - pub subname: String, - - pub conninfo: String, - - pub publication: Vec, - - pub options: Vec, -} -#[derive(Clone, PartialEq)] -pub struct DropSubscriptionStmt { - pub subname: String, - - pub missing_ok: bool, - - pub behavior: i32, -} -#[derive(Clone, PartialEq)] -pub struct CreateStatsStmt { - pub defnames: Vec, - - pub stat_types: Vec, - - pub exprs: Vec, - - pub relations: Vec, - - pub stxcomment: String, - - pub if_not_exists: bool, -} -#[derive(Clone, PartialEq)] -pub struct AlterCollationStmt { - pub collname: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CallStmt { - pub funccall: ::core::option::Option>, - - pub funcexpr: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct AlterStatsStmt { - pub defnames: Vec, - - pub stxstattarget: i32, - - pub missing_ok: bool, -} -#[derive(Clone, PartialEq)] -pub struct AExpr { - pub kind: i32, - - pub name: Vec, - - pub lexpr: ::core::option::Option>, - - pub rexpr: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct ColumnRef { - pub fields: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct ParamRef { - pub number: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct AConst { - pub val: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct FuncCall { - pub funcname: Vec, - - pub args: Vec, - - pub agg_order: Vec, - - pub agg_filter: ::core::option::Option>, - - pub agg_within_group: bool, - - pub agg_star: bool, - - pub agg_distinct: bool, - - pub func_variadic: bool, - - pub over: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct AStar {} -#[derive(Clone, PartialEq)] -pub struct AIndices { - pub is_slice: bool, - - pub lidx: ::core::option::Option>, - - pub uidx: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct AIndirection { - pub arg: ::core::option::Option>, - - pub indirection: Vec, -} -#[derive(Clone, PartialEq)] -pub struct AArrayExpr { - pub elements: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct ResTarget { - pub name: String, - - pub indirection: Vec, - - pub val: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct MultiAssignRef { - pub source: ::core::option::Option>, - - pub colno: i32, - - pub ncolumns: i32, -} -#[derive(Clone, PartialEq)] -pub struct TypeCast { - pub arg: ::core::option::Option>, - - pub type_name: ::core::option::Option, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CollateClause { - pub arg: ::core::option::Option>, - - pub collname: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct SortBy { - pub node: ::core::option::Option>, - - pub sortby_dir: i32, - - pub sortby_nulls: i32, - - pub use_op: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct WindowDef { - pub name: String, - - pub refname: String, - - pub partition_clause: Vec, - - pub order_clause: Vec, - - pub frame_options: i32, - - pub start_offset: ::core::option::Option>, - - pub end_offset: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct RangeSubselect { - pub lateral: bool, - - pub subquery: ::core::option::Option>, - - pub alias: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct RangeFunction { - pub lateral: bool, - - pub ordinality: bool, - - pub is_rowsfrom: bool, - - pub functions: Vec, - - pub alias: ::core::option::Option, - - pub coldeflist: Vec, -} -#[derive(Clone, PartialEq)] -pub struct RangeTableSample { - pub relation: ::core::option::Option>, - - pub method: Vec, - - pub args: Vec, - - pub repeatable: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct RangeTableFunc { - pub lateral: bool, - - pub docexpr: ::core::option::Option>, - - pub rowexpr: ::core::option::Option>, - - pub namespaces: Vec, - - pub columns: Vec, - - pub alias: ::core::option::Option, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct RangeTableFuncCol { - pub colname: String, - - pub type_name: ::core::option::Option, - - pub for_ordinality: bool, - - pub is_not_null: bool, - - pub colexpr: ::core::option::Option>, - - pub coldefexpr: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct TypeName { - pub names: Vec, - - pub type_oid: u32, - - pub setof: bool, - - pub pct_type: bool, - - pub typmods: Vec, - - pub typemod: i32, - - pub array_bounds: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct ColumnDef { - pub colname: String, - - pub type_name: ::core::option::Option, - - pub inhcount: i32, - - pub is_local: bool, - - pub is_not_null: bool, - - pub is_from_type: bool, - - pub storage: String, - - pub raw_default: ::core::option::Option>, - - pub cooked_default: ::core::option::Option>, - - pub identity: String, - - pub identity_sequence: ::core::option::Option, - - pub generated: String, - - pub coll_clause: ::core::option::Option>, - - pub coll_oid: u32, - - pub constraints: Vec, - - pub fdwoptions: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct IndexElem { - pub name: String, - - pub expr: ::core::option::Option>, - - pub indexcolname: String, - - pub collation: Vec, - - pub opclass: Vec, - - pub opclassopts: Vec, - - pub ordering: i32, - - pub nulls_ordering: i32, -} -#[derive(Clone, PartialEq)] -pub struct Constraint { - pub contype: i32, - - pub conname: String, - - pub deferrable: bool, - - pub initdeferred: bool, - - pub location: i32, - - pub is_no_inherit: bool, - - pub raw_expr: ::core::option::Option>, - - pub cooked_expr: String, - - pub generated_when: String, - - pub keys: Vec, - - pub including: Vec, - - pub exclusions: Vec, - - pub options: Vec, - - pub indexname: String, - - pub indexspace: String, - - pub reset_default_tblspc: bool, - - pub access_method: String, - - pub where_clause: ::core::option::Option>, - - pub pktable: ::core::option::Option, - - pub fk_attrs: Vec, - - pub pk_attrs: Vec, - - pub fk_matchtype: String, - - pub fk_upd_action: String, - - pub fk_del_action: String, - - pub old_conpfeqop: Vec, - - pub old_pktable_oid: u32, - - pub skip_validation: bool, - - pub initially_valid: bool, -} -#[derive(Clone, PartialEq)] -pub struct DefElem { - pub defnamespace: String, - - pub defname: String, - - pub arg: ::core::option::Option>, - - pub defaction: i32, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct RangeTblEntry { - pub rtekind: i32, - - pub relid: u32, - - pub relkind: String, - - pub rellockmode: i32, - - pub tablesample: ::core::option::Option>, - - pub subquery: ::core::option::Option>, - - pub security_barrier: bool, - - pub jointype: i32, - - pub joinmergedcols: i32, - - pub joinaliasvars: Vec, - - pub joinleftcols: Vec, - - pub joinrightcols: Vec, - - pub functions: Vec, - - pub funcordinality: bool, - - pub tablefunc: ::core::option::Option>, - - pub values_lists: Vec, - - pub ctename: String, - - pub ctelevelsup: u32, - - pub self_reference: bool, - - pub coltypes: Vec, - - pub coltypmods: Vec, - - pub colcollations: Vec, - - pub enrname: String, - - pub enrtuples: f64, - - pub alias: ::core::option::Option, - - pub eref: ::core::option::Option, - - pub lateral: bool, - - pub inh: bool, - - pub in_from_cl: bool, - - pub required_perms: u32, - - pub check_as_user: u32, - - pub selected_cols: Vec, - - pub inserted_cols: Vec, - - pub updated_cols: Vec, - - pub extra_updated_cols: Vec, - - pub security_quals: Vec, -} -#[derive(Clone, PartialEq)] -pub struct RangeTblFunction { - pub funcexpr: ::core::option::Option>, - - pub funccolcount: i32, - - pub funccolnames: Vec, - - pub funccoltypes: Vec, - - pub funccoltypmods: Vec, - - pub funccolcollations: Vec, - - pub funcparams: Vec, -} -#[derive(Clone, PartialEq)] -pub struct TableSampleClause { - pub tsmhandler: u32, - - pub args: Vec, - - pub repeatable: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct WithCheckOption { - pub kind: i32, - - pub relname: String, - - pub polname: String, - - pub qual: ::core::option::Option>, - - pub cascaded: bool, -} -#[derive(Clone, PartialEq)] -pub struct SortGroupClause { - pub tle_sort_group_ref: u32, - - pub eqop: u32, - - pub sortop: u32, - - pub nulls_first: bool, - - pub hashable: bool, -} -#[derive(Clone, PartialEq)] -pub struct GroupingSet { - pub kind: i32, - - pub content: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct WindowClause { - pub name: String, - - pub refname: String, - - pub partition_clause: Vec, - - pub order_clause: Vec, - - pub frame_options: i32, - - pub start_offset: ::core::option::Option>, - - pub end_offset: ::core::option::Option>, - - pub start_in_range_func: u32, - - pub end_in_range_func: u32, - - pub in_range_coll: u32, - - pub in_range_asc: bool, - - pub in_range_nulls_first: bool, - - pub winref: u32, - - pub copied_order: bool, -} -#[derive(Clone, PartialEq)] -pub struct ObjectWithArgs { - pub objname: Vec, - - pub objargs: Vec, - - pub args_unspecified: bool, -} -#[derive(Clone, PartialEq)] -pub struct AccessPriv { - pub priv_name: String, - - pub cols: Vec, -} -#[derive(Clone, PartialEq)] -pub struct CreateOpClassItem { - pub itemtype: i32, - - pub name: ::core::option::Option, - - pub number: i32, - - pub order_family: Vec, - - pub class_args: Vec, - - pub storedtype: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct TableLikeClause { - pub relation: ::core::option::Option, - - pub options: u32, - - pub relation_oid: u32, -} -#[derive(Clone, PartialEq)] -pub struct FunctionParameter { - pub name: String, - - pub arg_type: ::core::option::Option, - - pub mode: i32, - - pub defexpr: ::core::option::Option>, -} -#[derive(Clone, PartialEq)] -pub struct LockingClause { - pub locked_rels: Vec, - - pub strength: i32, - - pub wait_policy: i32, -} -#[derive(Clone, PartialEq)] -pub struct RowMarkClause { - pub rti: u32, - - pub strength: i32, - - pub wait_policy: i32, - - pub pushed_down: bool, -} -#[derive(Clone, PartialEq)] -pub struct XmlSerialize { - pub xmloption: i32, - - pub expr: ::core::option::Option>, - - pub type_name: ::core::option::Option, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct WithClause { - pub ctes: Vec, - - pub recursive: bool, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct InferClause { - pub index_elems: Vec, - - pub where_clause: ::core::option::Option>, - - pub conname: String, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct OnConflictClause { - pub action: i32, - - pub infer: ::core::option::Option>, - - pub target_list: Vec, - - pub where_clause: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct CommonTableExpr { - pub ctename: String, - - pub aliascolnames: Vec, - - pub ctematerialized: i32, - - pub ctequery: ::core::option::Option>, - - pub location: i32, - - pub cterecursive: bool, - - pub cterefcount: i32, - - pub ctecolnames: Vec, - - pub ctecoltypes: Vec, - - pub ctecoltypmods: Vec, - - pub ctecolcollations: Vec, -} -#[derive(Clone, PartialEq)] -pub struct RoleSpec { - pub roletype: i32, - - pub rolename: String, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct TriggerTransition { - pub name: String, - - pub is_new: bool, - - pub is_table: bool, -} -#[derive(Clone, PartialEq)] -pub struct PartitionElem { - pub name: String, - - pub expr: ::core::option::Option>, - - pub collation: Vec, - - pub opclass: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct PartitionSpec { - pub strategy: String, - - pub part_params: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct PartitionBoundSpec { - pub strategy: String, - - pub is_default: bool, - - pub modulus: i32, - - pub remainder: i32, - - pub listdatums: Vec, - - pub lowerdatums: Vec, - - pub upperdatums: Vec, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct PartitionRangeDatum { - pub kind: i32, - - pub value: ::core::option::Option>, - - pub location: i32, -} -#[derive(Clone, PartialEq)] -pub struct PartitionCmd { - pub name: ::core::option::Option, - - pub bound: ::core::option::Option, -} -#[derive(Clone, PartialEq)] -pub struct VacuumRelation { - pub relation: ::core::option::Option, - - pub oid: u32, - - pub va_cols: Vec, -} -#[derive(Clone, PartialEq)] -pub struct InlineCodeBlock { - pub source_text: String, - - pub lang_oid: u32, - - pub lang_is_trusted: bool, - - pub atomic: bool, -} -#[derive(Clone, PartialEq)] -pub struct CallContext { - pub atomic: bool, -} -#[derive(Clone, PartialEq)] -pub struct ScanToken { - pub start: i32, - - pub end: i32, - - pub token: i32, - - pub keyword_kind: i32, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum OverridingKind { - Undefined = 0, - OverridingNotSet = 1, - OverridingUserValue = 2, - OverridingSystemValue = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum QuerySource { - Undefined = 0, - QsrcOriginal = 1, - QsrcParser = 2, - QsrcInsteadRule = 3, - QsrcQualInsteadRule = 4, - QsrcNonInsteadRule = 5, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum SortByDir { - Undefined = 0, - SortbyDefault = 1, - SortbyAsc = 2, - SortbyDesc = 3, - SortbyUsing = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum SortByNulls { - Undefined = 0, - SortbyNullsDefault = 1, - SortbyNullsFirst = 2, - SortbyNullsLast = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum AExprKind { - Undefined = 0, - AexprOp = 1, - AexprOpAny = 2, - AexprOpAll = 3, - AexprDistinct = 4, - AexprNotDistinct = 5, - AexprNullif = 6, - AexprOf = 7, - AexprIn = 8, - AexprLike = 9, - AexprIlike = 10, - AexprSimilar = 11, - AexprBetween = 12, - AexprNotBetween = 13, - AexprBetweenSym = 14, - AexprNotBetweenSym = 15, - AexprParen = 16, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum RoleSpecType { - Undefined = 0, - RolespecCstring = 1, - RolespecCurrentUser = 2, - RolespecSessionUser = 3, - RolespecPublic = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum TableLikeOption { - Undefined = 0, - CreateTableLikeComments = 1, - CreateTableLikeConstraints = 2, - CreateTableLikeDefaults = 3, - CreateTableLikeGenerated = 4, - CreateTableLikeIdentity = 5, - CreateTableLikeIndexes = 6, - CreateTableLikeStatistics = 7, - CreateTableLikeStorage = 8, - CreateTableLikeAll = 9, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum DefElemAction { - Undefined = 0, - DefelemUnspec = 1, - DefelemSet = 2, - DefelemAdd = 3, - DefelemDrop = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum PartitionRangeDatumKind { - Undefined = 0, - PartitionRangeDatumMinvalue = 1, - PartitionRangeDatumValue = 2, - PartitionRangeDatumMaxvalue = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum RteKind { - RtekindUndefined = 0, - RteRelation = 1, - RteSubquery = 2, - RteJoin = 3, - RteFunction = 4, - RteTablefunc = 5, - RteValues = 6, - RteCte = 7, - RteNamedtuplestore = 8, - RteResult = 9, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum WcoKind { - WcokindUndefined = 0, - WcoViewCheck = 1, - WcoRlsInsertCheck = 2, - WcoRlsUpdateCheck = 3, - WcoRlsConflictCheck = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum GroupingSetKind { - Undefined = 0, - GroupingSetEmpty = 1, - GroupingSetSimple = 2, - GroupingSetRollup = 3, - GroupingSetCube = 4, - GroupingSetSets = 5, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum CteMaterialize { - CtematerializeUndefined = 0, - Default = 1, - Always = 2, - Never = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum SetOperation { - Undefined = 0, - SetopNone = 1, - SetopUnion = 2, - SetopIntersect = 3, - SetopExcept = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum ObjectType { - Undefined = 0, - ObjectAccessMethod = 1, - ObjectAggregate = 2, - ObjectAmop = 3, - ObjectAmproc = 4, - ObjectAttribute = 5, - ObjectCast = 6, - ObjectColumn = 7, - ObjectCollation = 8, - ObjectConversion = 9, - ObjectDatabase = 10, - ObjectDefault = 11, - ObjectDefacl = 12, - ObjectDomain = 13, - ObjectDomconstraint = 14, - ObjectEventTrigger = 15, - ObjectExtension = 16, - ObjectFdw = 17, - ObjectForeignServer = 18, - ObjectForeignTable = 19, - ObjectFunction = 20, - ObjectIndex = 21, - ObjectLanguage = 22, - ObjectLargeobject = 23, - ObjectMatview = 24, - ObjectOpclass = 25, - ObjectOperator = 26, - ObjectOpfamily = 27, - ObjectPolicy = 28, - ObjectProcedure = 29, - ObjectPublication = 30, - ObjectPublicationRel = 31, - ObjectRole = 32, - ObjectRoutine = 33, - ObjectRule = 34, - ObjectSchema = 35, - ObjectSequence = 36, - ObjectSubscription = 37, - ObjectStatisticExt = 38, - ObjectTabconstraint = 39, - ObjectTable = 40, - ObjectTablespace = 41, - ObjectTransform = 42, - ObjectTrigger = 43, - ObjectTsconfiguration = 44, - ObjectTsdictionary = 45, - ObjectTsparser = 46, - ObjectTstemplate = 47, - ObjectType = 48, - ObjectUserMapping = 49, - ObjectView = 50, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum DropBehavior { - Undefined = 0, - DropRestrict = 1, - DropCascade = 2, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum AlterTableType { - Undefined = 0, - AtAddColumn = 1, - AtAddColumnRecurse = 2, - AtAddColumnToView = 3, - AtColumnDefault = 4, - AtCookedColumnDefault = 5, - AtDropNotNull = 6, - AtSetNotNull = 7, - AtDropExpression = 8, - AtCheckNotNull = 9, - AtSetStatistics = 10, - AtSetOptions = 11, - AtResetOptions = 12, - AtSetStorage = 13, - AtDropColumn = 14, - AtDropColumnRecurse = 15, - AtAddIndex = 16, - AtReAddIndex = 17, - AtAddConstraint = 18, - AtAddConstraintRecurse = 19, - AtReAddConstraint = 20, - AtReAddDomainConstraint = 21, - AtAlterConstraint = 22, - AtValidateConstraint = 23, - AtValidateConstraintRecurse = 24, - AtAddIndexConstraint = 25, - AtDropConstraint = 26, - AtDropConstraintRecurse = 27, - AtReAddComment = 28, - AtAlterColumnType = 29, - AtAlterColumnGenericOptions = 30, - AtChangeOwner = 31, - AtClusterOn = 32, - AtDropCluster = 33, - AtSetLogged = 34, - AtSetUnLogged = 35, - AtDropOids = 36, - AtSetTableSpace = 37, - AtSetRelOptions = 38, - AtResetRelOptions = 39, - AtReplaceRelOptions = 40, - AtEnableTrig = 41, - AtEnableAlwaysTrig = 42, - AtEnableReplicaTrig = 43, - AtDisableTrig = 44, - AtEnableTrigAll = 45, - AtDisableTrigAll = 46, - AtEnableTrigUser = 47, - AtDisableTrigUser = 48, - AtEnableRule = 49, - AtEnableAlwaysRule = 50, - AtEnableReplicaRule = 51, - AtDisableRule = 52, - AtAddInherit = 53, - AtDropInherit = 54, - AtAddOf = 55, - AtDropOf = 56, - AtReplicaIdentity = 57, - AtEnableRowSecurity = 58, - AtDisableRowSecurity = 59, - AtForceRowSecurity = 60, - AtNoForceRowSecurity = 61, - AtGenericOptions = 62, - AtAttachPartition = 63, - AtDetachPartition = 64, - AtAddIdentity = 65, - AtSetIdentity = 66, - AtDropIdentity = 67, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum GrantTargetType { - Undefined = 0, - AclTargetObject = 1, - AclTargetAllInSchema = 2, - AclTargetDefaults = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum VariableSetKind { - Undefined = 0, - VarSetValue = 1, - VarSetDefault = 2, - VarSetCurrent = 3, - VarSetMulti = 4, - VarReset = 5, - VarResetAll = 6, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum ConstrType { - Undefined = 0, - ConstrNull = 1, - ConstrNotnull = 2, - ConstrDefault = 3, - ConstrIdentity = 4, - ConstrGenerated = 5, - ConstrCheck = 6, - ConstrPrimary = 7, - ConstrUnique = 8, - ConstrExclusion = 9, - ConstrForeign = 10, - ConstrAttrDeferrable = 11, - ConstrAttrNotDeferrable = 12, - ConstrAttrDeferred = 13, - ConstrAttrImmediate = 14, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum ImportForeignSchemaType { - Undefined = 0, - FdwImportSchemaAll = 1, - FdwImportSchemaLimitTo = 2, - FdwImportSchemaExcept = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum RoleStmtType { - Undefined = 0, - RolestmtRole = 1, - RolestmtUser = 2, - RolestmtGroup = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum FetchDirection { - Undefined = 0, - FetchForward = 1, - FetchBackward = 2, - FetchAbsolute = 3, - FetchRelative = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum FunctionParameterMode { - Undefined = 0, - FuncParamIn = 1, - FuncParamOut = 2, - FuncParamInout = 3, - FuncParamVariadic = 4, - FuncParamTable = 5, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum TransactionStmtKind { - Undefined = 0, - TransStmtBegin = 1, - TransStmtStart = 2, - TransStmtCommit = 3, - TransStmtRollback = 4, - TransStmtSavepoint = 5, - TransStmtRelease = 6, - TransStmtRollbackTo = 7, - TransStmtPrepare = 8, - TransStmtCommitPrepared = 9, - TransStmtRollbackPrepared = 10, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum ViewCheckOption { - Undefined = 0, - NoCheckOption = 1, - LocalCheckOption = 2, - CascadedCheckOption = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum ClusterOption { - Undefined = 0, - CluoptRecheck = 1, - CluoptVerbose = 2, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum DiscardMode { - Undefined = 0, - DiscardAll = 1, - DiscardPlans = 2, - DiscardSequences = 3, - DiscardTemp = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum ReindexObjectType { - Undefined = 0, - ReindexObjectIndex = 1, - ReindexObjectTable = 2, - ReindexObjectSchema = 3, - ReindexObjectSystem = 4, - ReindexObjectDatabase = 5, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum AlterTsConfigType { - AlterTsconfigTypeUndefined = 0, - AlterTsconfigAddMapping = 1, - AlterTsconfigAlterMappingForToken = 2, - AlterTsconfigReplaceDict = 3, - AlterTsconfigReplaceDictForToken = 4, - AlterTsconfigDropMapping = 5, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum AlterSubscriptionType { - Undefined = 0, - AlterSubscriptionOptions = 1, - AlterSubscriptionConnection = 2, - AlterSubscriptionPublication = 3, - AlterSubscriptionRefresh = 4, - AlterSubscriptionEnabled = 5, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum OnCommitAction { - Undefined = 0, - OncommitNoop = 1, - OncommitPreserveRows = 2, - OncommitDeleteRows = 3, - OncommitDrop = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum ParamKind { - Undefined = 0, - ParamExtern = 1, - ParamExec = 2, - ParamSublink = 3, - ParamMultiexpr = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum CoercionContext { - Undefined = 0, - CoercionImplicit = 1, - CoercionAssignment = 2, - CoercionExplicit = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum CoercionForm { - Undefined = 0, - CoerceExplicitCall = 1, - CoerceExplicitCast = 2, - CoerceImplicitCast = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum BoolExprType { - Undefined = 0, - AndExpr = 1, - OrExpr = 2, - NotExpr = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum SubLinkType { - Undefined = 0, - ExistsSublink = 1, - AllSublink = 2, - AnySublink = 3, - RowcompareSublink = 4, - ExprSublink = 5, - MultiexprSublink = 6, - ArraySublink = 7, - CteSublink = 8, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum RowCompareType { - Undefined = 0, - RowcompareLt = 1, - RowcompareLe = 2, - RowcompareEq = 3, - RowcompareGe = 4, - RowcompareGt = 5, - RowcompareNe = 6, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum MinMaxOp { - Undefined = 0, - IsGreatest = 1, - IsLeast = 2, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum SqlValueFunctionOp { - SqlvalueFunctionOpUndefined = 0, - SvfopCurrentDate = 1, - SvfopCurrentTime = 2, - SvfopCurrentTimeN = 3, - SvfopCurrentTimestamp = 4, - SvfopCurrentTimestampN = 5, - SvfopLocaltime = 6, - SvfopLocaltimeN = 7, - SvfopLocaltimestamp = 8, - SvfopLocaltimestampN = 9, - SvfopCurrentRole = 10, - SvfopCurrentUser = 11, - SvfopUser = 12, - SvfopSessionUser = 13, - SvfopCurrentCatalog = 14, - SvfopCurrentSchema = 15, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum XmlExprOp { - Undefined = 0, - IsXmlconcat = 1, - IsXmlelement = 2, - IsXmlforest = 3, - IsXmlparse = 4, - IsXmlpi = 5, - IsXmlroot = 6, - IsXmlserialize = 7, - IsDocument = 8, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum XmlOptionType { - Undefined = 0, - XmloptionDocument = 1, - XmloptionContent = 2, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum NullTestType { - Undefined = 0, - IsNull = 1, - IsNotNull = 2, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum BoolTestType { - Undefined = 0, - IsTrue = 1, - IsNotTrue = 2, - IsFalse = 3, - IsNotFalse = 4, - IsUnknown = 5, - IsNotUnknown = 6, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum CmdType { - Undefined = 0, - CmdUnknown = 1, - CmdSelect = 2, - CmdUpdate = 3, - CmdInsert = 4, - CmdDelete = 5, - CmdUtility = 6, - CmdNothing = 7, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum JoinType { - Undefined = 0, - JoinInner = 1, - JoinLeft = 2, - JoinFull = 3, - JoinRight = 4, - JoinSemi = 5, - JoinAnti = 6, - JoinUniqueOuter = 7, - JoinUniqueInner = 8, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum AggStrategy { - Undefined = 0, - AggPlain = 1, - AggSorted = 2, - AggHashed = 3, - AggMixed = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum AggSplit { - Undefined = 0, - AggsplitSimple = 1, - AggsplitInitialSerial = 2, - AggsplitFinalDeserial = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum SetOpCmd { - Undefined = 0, - SetopcmdIntersect = 1, - SetopcmdIntersectAll = 2, - SetopcmdExcept = 3, - SetopcmdExceptAll = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum SetOpStrategy { - Undefined = 0, - SetopSorted = 1, - SetopHashed = 2, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum OnConflictAction { - Undefined = 0, - OnconflictNone = 1, - OnconflictNothing = 2, - OnconflictUpdate = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum LimitOption { - Undefined = 0, - Default = 1, - Count = 2, - WithTies = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum LockClauseStrength { - Undefined = 0, - LcsNone = 1, - LcsForkeyshare = 2, - LcsForshare = 3, - LcsFornokeyupdate = 4, - LcsForupdate = 5, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum LockWaitPolicy { - Undefined = 0, - LockWaitBlock = 1, - LockWaitSkip = 2, - LockWaitError = 3, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum LockTupleMode { - Undefined = 0, - LockTupleKeyShare = 1, - LockTupleShare = 2, - LockTupleNoKeyExclusive = 3, - LockTupleExclusive = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum KeywordKind { - NoKeyword = 0, - UnreservedKeyword = 1, - ColNameKeyword = 2, - TypeFuncNameKeyword = 3, - ReservedKeyword = 4, -} -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] -#[repr(i32)] -pub enum Token { - Nul = 0, - /// Single-character tokens that are returned 1:1 (identical with "self" list in scan.l) - /// Either supporting syntax, or single-character operators (some can be both) - /// Also see - /// - /// "%" - Ascii37 = 37, - /// "(" - Ascii40 = 40, - /// ")" - Ascii41 = 41, - /// "*" - Ascii42 = 42, - /// "+" - Ascii43 = 43, - /// "," - Ascii44 = 44, - /// "-" - Ascii45 = 45, - /// "." - Ascii46 = 46, - /// "/" - Ascii47 = 47, - /// ":" - Ascii58 = 58, - /// ";" - Ascii59 = 59, - /// "<" - Ascii60 = 60, - /// "=" - Ascii61 = 61, - /// ">" - Ascii62 = 62, - /// "?" - Ascii63 = 63, - /// "[" - Ascii91 = 91, - /// "\" - Ascii92 = 92, - /// "]" - Ascii93 = 93, - /// "^" - Ascii94 = 94, - /// Named tokens in scan.l - Ident = 258, - Uident = 259, - Fconst = 260, - Sconst = 261, - Usconst = 262, - Bconst = 263, - Xconst = 264, - Op = 265, - Iconst = 266, - Param = 267, - Typecast = 268, - DotDot = 269, - ColonEquals = 270, - EqualsGreater = 271, - LessEquals = 272, - GreaterEquals = 273, - NotEquals = 274, - SqlComment = 275, - CComment = 276, - AbortP = 277, - AbsoluteP = 278, - Access = 279, - Action = 280, - AddP = 281, - Admin = 282, - After = 283, - Aggregate = 284, - All = 285, - Also = 286, - Alter = 287, - Always = 288, - Analyse = 289, - Analyze = 290, - And = 291, - Any = 292, - Array = 293, - As = 294, - Asc = 295, - Assertion = 296, - Assignment = 297, - Asymmetric = 298, - At = 299, - Attach = 300, - Attribute = 301, - Authorization = 302, - Backward = 303, - Before = 304, - BeginP = 305, - Between = 306, - Bigint = 307, - Binary = 308, - Bit = 309, - BooleanP = 310, - Both = 311, - By = 312, - Cache = 313, - Call = 314, - Called = 315, - Cascade = 316, - Cascaded = 317, - Case = 318, - Cast = 319, - CatalogP = 320, - Chain = 321, - CharP = 322, - Character = 323, - Characteristics = 324, - Check = 325, - Checkpoint = 326, - Class = 327, - Close = 328, - Cluster = 329, - Coalesce = 330, - Collate = 331, - Collation = 332, - Column = 333, - Columns = 334, - Comment = 335, - Comments = 336, - Commit = 337, - Committed = 338, - Concurrently = 339, - Configuration = 340, - Conflict = 341, - Connection = 342, - Constraint = 343, - Constraints = 344, - ContentP = 345, - ContinueP = 346, - ConversionP = 347, - Copy = 348, - Cost = 349, - Create = 350, - Cross = 351, - Csv = 352, - Cube = 353, - CurrentP = 354, - CurrentCatalog = 355, - CurrentDate = 356, - CurrentRole = 357, - CurrentSchema = 358, - CurrentTime = 359, - CurrentTimestamp = 360, - CurrentUser = 361, - Cursor = 362, - Cycle = 363, - DataP = 364, - Database = 365, - DayP = 366, - Deallocate = 367, - Dec = 368, - DecimalP = 369, - Declare = 370, - Default = 371, - Defaults = 372, - Deferrable = 373, - Deferred = 374, - Definer = 375, - DeleteP = 376, - Delimiter = 377, - Delimiters = 378, - Depends = 379, - Desc = 380, - Detach = 381, - Dictionary = 382, - DisableP = 383, - Discard = 384, - Distinct = 385, - Do = 386, - DocumentP = 387, - DomainP = 388, - DoubleP = 389, - Drop = 390, - Each = 391, - Else = 392, - EnableP = 393, - Encoding = 394, - Encrypted = 395, - EndP = 396, - EnumP = 397, - Escape = 398, - Event = 399, - Except = 400, - Exclude = 401, - Excluding = 402, - Exclusive = 403, - Execute = 404, - Exists = 405, - Explain = 406, - Expression = 407, - Extension = 408, - External = 409, - Extract = 410, - FalseP = 411, - Family = 412, - Fetch = 413, - Filter = 414, - FirstP = 415, - FloatP = 416, - Following = 417, - For = 418, - Force = 419, - Foreign = 420, - Forward = 421, - Freeze = 422, - From = 423, - Full = 424, - Function = 425, - Functions = 426, - Generated = 427, - Global = 428, - Grant = 429, - Granted = 430, - Greatest = 431, - GroupP = 432, - Grouping = 433, - Groups = 434, - Handler = 435, - Having = 436, - HeaderP = 437, - Hold = 438, - HourP = 439, - IdentityP = 440, - IfP = 441, - Ilike = 442, - Immediate = 443, - Immutable = 444, - ImplicitP = 445, - ImportP = 446, - InP = 447, - Include = 448, - Including = 449, - Increment = 450, - Index = 451, - Indexes = 452, - Inherit = 453, - Inherits = 454, - Initially = 455, - InlineP = 456, - InnerP = 457, - Inout = 458, - InputP = 459, - Insensitive = 460, - Insert = 461, - Instead = 462, - IntP = 463, - Integer = 464, - Intersect = 465, - Interval = 466, - Into = 467, - Invoker = 468, - Is = 469, - Isnull = 470, - Isolation = 471, - Join = 472, - Key = 473, - Label = 474, - Language = 475, - LargeP = 476, - LastP = 477, - LateralP = 478, - Leading = 479, - Leakproof = 480, - Least = 481, - Left = 482, - Level = 483, - Like = 484, - Limit = 485, - Listen = 486, - Load = 487, - Local = 488, - Localtime = 489, - Localtimestamp = 490, - Location = 491, - LockP = 492, - Locked = 493, - Logged = 494, - Mapping = 495, - Match = 496, - Materialized = 497, - Maxvalue = 498, - Method = 499, - MinuteP = 500, - Minvalue = 501, - Mode = 502, - MonthP = 503, - Move = 504, - NameP = 505, - Names = 506, - National = 507, - Natural = 508, - Nchar = 509, - New = 510, - Next = 511, - Nfc = 512, - Nfd = 513, - Nfkc = 514, - Nfkd = 515, - No = 516, - None = 517, - Normalize = 518, - Normalized = 519, - Not = 520, - Nothing = 521, - Notify = 522, - Notnull = 523, - Nowait = 524, - NullP = 525, - Nullif = 526, - NullsP = 527, - Numeric = 528, - ObjectP = 529, - Of = 530, - Off = 531, - Offset = 532, - Oids = 533, - Old = 534, - On = 535, - Only = 536, - Operator = 537, - Option = 538, - Options = 539, - Or = 540, - Order = 541, - Ordinality = 542, - Others = 543, - OutP = 544, - OuterP = 545, - Over = 546, - Overlaps = 547, - Overlay = 548, - Overriding = 549, - Owned = 550, - Owner = 551, - Parallel = 552, - Parser = 553, - Partial = 554, - Partition = 555, - Passing = 556, - Password = 557, - Placing = 558, - Plans = 559, - Policy = 560, - Position = 561, - Preceding = 562, - Precision = 563, - Preserve = 564, - Prepare = 565, - Prepared = 566, - Primary = 567, - Prior = 568, - Privileges = 569, - Procedural = 570, - Procedure = 571, - Procedures = 572, - Program = 573, - Publication = 574, - Quote = 575, - Range = 576, - Read = 577, - Real = 578, - Reassign = 579, - Recheck = 580, - Recursive = 581, - Ref = 582, - References = 583, - Referencing = 584, - Refresh = 585, - Reindex = 586, - RelativeP = 587, - Release = 588, - Rename = 589, - Repeatable = 590, - Replace = 591, - Replica = 592, - Reset = 593, - Restart = 594, - Restrict = 595, - Returning = 596, - Returns = 597, - Revoke = 598, - Right = 599, - Role = 600, - Rollback = 601, - Rollup = 602, - Routine = 603, - Routines = 604, - Row = 605, - Rows = 606, - Rule = 607, - Savepoint = 608, - Schema = 609, - Schemas = 610, - Scroll = 611, - Search = 612, - SecondP = 613, - Security = 614, - Select = 615, - Sequence = 616, - Sequences = 617, - Serializable = 618, - Server = 619, - Session = 620, - SessionUser = 621, - Set = 622, - Sets = 623, - Setof = 624, - Share = 625, - Show = 626, - Similar = 627, - Simple = 628, - Skip = 629, - Smallint = 630, - Snapshot = 631, - Some = 632, - SqlP = 633, - Stable = 634, - StandaloneP = 635, - Start = 636, - Statement = 637, - Statistics = 638, - Stdin = 639, - Stdout = 640, - Storage = 641, - Stored = 642, - StrictP = 643, - StripP = 644, - Subscription = 645, - Substring = 646, - Support = 647, - Symmetric = 648, - Sysid = 649, - SystemP = 650, - Table = 651, - Tables = 652, - Tablesample = 653, - Tablespace = 654, - Temp = 655, - Template = 656, - Temporary = 657, - TextP = 658, - Then = 659, - Ties = 660, - Time = 661, - Timestamp = 662, - To = 663, - Trailing = 664, - Transaction = 665, - Transform = 666, - Treat = 667, - Trigger = 668, - Trim = 669, - TrueP = 670, - Truncate = 671, - Trusted = 672, - TypeP = 673, - TypesP = 674, - Uescape = 675, - Unbounded = 676, - Uncommitted = 677, - Unencrypted = 678, - Union = 679, - Unique = 680, - Unknown = 681, - Unlisten = 682, - Unlogged = 683, - Until = 684, - Update = 685, - User = 686, - Using = 687, - Vacuum = 688, - Valid = 689, - Validate = 690, - Validator = 691, - ValueP = 692, - Values = 693, - Varchar = 694, - Variadic = 695, - Varying = 696, - Verbose = 697, - VersionP = 698, - View = 699, - Views = 700, - Volatile = 701, - When = 702, - Where = 703, - WhitespaceP = 704, - Window = 705, - With = 706, - Within = 707, - Without = 708, - Work = 709, - Wrapper = 710, - Write = 711, - XmlP = 712, - Xmlattributes = 713, - Xmlconcat = 714, - Xmlelement = 715, - Xmlexists = 716, - Xmlforest = 717, - Xmlnamespaces = 718, - Xmlparse = 719, - Xmlpi = 720, - Xmlroot = 721, - Xmlserialize = 722, - Xmltable = 723, - YearP = 724, - YesP = 725, - Zone = 726, - NotLa = 727, - NullsLa = 728, - WithLa = 729, - Postfixop = 730, - Uminus = 731, -} From b3d4fb448c79240785d8ccd78b73d40c59fc5071 Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Tue, 21 Jun 2022 19:28:04 -0400 Subject: [PATCH 02/69] Allow `#[ignore]` tests to run in rustfmt's test suite There are some tests in the rustfmt test suite that are ignored by default. I believe these tests are ignored because they have caused issues with the the `rust-lang/rust` test suite. However, we recently experienced an issue (5395) that would have been avoided had these tests been running. With the introduction of the new `#[rustfmt_only_ci_test]` attribute macro we can run these tests when the `RUSTFMT_CI` environment variable is set, which will presumably only be set during rustfmts CI runs. When the environment variable is not set the `#[rustfmt_only_ci_test]` will be replaced with an `#[ignore]`. --- ci/build_and_test.bat | 1 + ci/build_and_test.sh | 1 + config_proc_macro/src/lib.rs | 13 +++++++++++++ tests/cargo-fmt/main.rs | 10 ++++++---- tests/rustfmt/main.rs | 6 ++++-- 5 files changed, 25 insertions(+), 6 deletions(-) diff --git a/ci/build_and_test.bat b/ci/build_and_test.bat index ef41017783feb..69dae1fff7b4d 100755 --- a/ci/build_and_test.bat +++ b/ci/build_and_test.bat @@ -1,4 +1,5 @@ set "RUSTFLAGS=-D warnings" +set "RUSTFMT_CI=1" :: Print version information rustc -Vv || exit /b 1 diff --git a/ci/build_and_test.sh b/ci/build_and_test.sh index 8fa0f67b0d021..94991853263ce 100755 --- a/ci/build_and_test.sh +++ b/ci/build_and_test.sh @@ -3,6 +3,7 @@ set -euo pipefail export RUSTFLAGS="-D warnings" +export RUSTFMT_CI=1 # Print version information rustc -Vv diff --git a/config_proc_macro/src/lib.rs b/config_proc_macro/src/lib.rs index e772c53f42361..0c54c132c97d8 100644 --- a/config_proc_macro/src/lib.rs +++ b/config_proc_macro/src/lib.rs @@ -69,3 +69,16 @@ pub fn stable_only_test(_args: TokenStream, input: TokenStream) -> TokenStream { TokenStream::from_str("").unwrap() } } + +/// Used to conditionally output the TokenStream for tests that should be run as part of rustfmts +/// test suite, but should be ignored when running in the rust-lang/rust test suite. +#[proc_macro_attribute] +pub fn rustfmt_only_ci_test(_args: TokenStream, input: TokenStream) -> TokenStream { + if option_env!("RUSTFMT_CI").is_some() { + input + } else { + let mut token_stream = TokenStream::from_str("#[ignore]").unwrap(); + token_stream.extend(input); + token_stream + } +} diff --git a/tests/cargo-fmt/main.rs b/tests/cargo-fmt/main.rs index 348876cd264fa..5aa4388518b8a 100644 --- a/tests/cargo-fmt/main.rs +++ b/tests/cargo-fmt/main.rs @@ -4,6 +4,8 @@ use std::env; use std::path::Path; use std::process::Command; +use rustfmt_config_proc_macro::rustfmt_only_ci_test; + /// Run the cargo-fmt executable and return its output. fn cargo_fmt(args: &[&str]) -> (String, String) { let mut bin_dir = env::current_exe().unwrap(); @@ -47,7 +49,7 @@ macro_rules! assert_that { }; } -#[ignore] +#[rustfmt_only_ci_test] #[test] fn version() { assert_that!(&["--version"], starts_with("rustfmt ")); @@ -56,7 +58,7 @@ fn version() { assert_that!(&["--", "--version"], starts_with("rustfmt ")); } -#[ignore] +#[rustfmt_only_ci_test] #[test] fn print_config() { assert_that!( @@ -65,7 +67,7 @@ fn print_config() { ); } -#[ignore] +#[rustfmt_only_ci_test] #[test] fn rustfmt_help() { assert_that!(&["--", "--help"], contains("Format Rust code")); @@ -73,7 +75,7 @@ fn rustfmt_help() { assert_that!(&["--", "--help=config"], contains("Configuration Options:")); } -#[ignore] +#[rustfmt_only_ci_test] #[test] fn cargo_fmt_out_of_line_test_modules() { // See also https://github.com/rust-lang/rustfmt/issues/5119 diff --git a/tests/rustfmt/main.rs b/tests/rustfmt/main.rs index 4c6d52726f3fe..636e3053e0f8e 100644 --- a/tests/rustfmt/main.rs +++ b/tests/rustfmt/main.rs @@ -5,6 +5,8 @@ use std::fs::remove_file; use std::path::Path; use std::process::Command; +use rustfmt_config_proc_macro::rustfmt_only_ci_test; + /// Run the rustfmt executable and return its output. fn rustfmt(args: &[&str]) -> (String, String) { let mut bin_dir = env::current_exe().unwrap(); @@ -47,7 +49,7 @@ macro_rules! assert_that { }; } -#[ignore] +#[rustfmt_only_ci_test] #[test] fn print_config() { assert_that!( @@ -76,7 +78,7 @@ fn print_config() { remove_file("minimal-config").unwrap(); } -#[ignore] +#[rustfmt_only_ci_test] #[test] fn inline_config() { // single invocation From 2ae63f0018a7e18deb7ac0063379c2350a631fca Mon Sep 17 00:00:00 2001 From: Tom Milligan Date: Fri, 10 Jun 2022 12:17:29 +0100 Subject: [PATCH 03/69] config_type: add unstable_variant attribute --- Cargo.lock | 2 +- Cargo.toml | 2 +- config_proc_macro/Cargo.lock | 2 +- config_proc_macro/Cargo.toml | 2 +- config_proc_macro/src/attrs.rs | 27 +++++-- config_proc_macro/src/item_enum.rs | 40 ++++++++++- config_proc_macro/tests/smoke.rs | 1 + src/config/config_type.rs | 90 ++++++++++++++++++----- src/config/mod.rs | 112 +++++++++++++++++++++++++++-- 9 files changed, 244 insertions(+), 34 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 311df226da19d..e51755289706c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -476,7 +476,7 @@ checksum = "fc71d2faa173b74b232dedc235e3ee1696581bb132fc116fa3626d6151a1a8fb" [[package]] name = "rustfmt-config_proc_macro" -version = "0.2.0" +version = "0.3.0" dependencies = [ "proc-macro2", "quote", diff --git a/Cargo.toml b/Cargo.toml index 7a4e02d69eddc..7438335eaa78f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -57,7 +57,7 @@ unicode-segmentation = "1.9" unicode-width = "0.1" unicode_categories = "0.1" -rustfmt-config_proc_macro = { version = "0.2", path = "config_proc_macro" } +rustfmt-config_proc_macro = { version = "0.3", path = "config_proc_macro" } # A noop dependency that changes in the Rust repository, it's a bit of a hack. # See the `src/tools/rustc-workspace-hack/README.md` file in `rust-lang/rust` diff --git a/config_proc_macro/Cargo.lock b/config_proc_macro/Cargo.lock index ecf561f28fb6a..49f2f72a8d219 100644 --- a/config_proc_macro/Cargo.lock +++ b/config_proc_macro/Cargo.lock @@ -22,7 +22,7 @@ dependencies = [ [[package]] name = "rustfmt-config_proc_macro" -version = "0.2.0" +version = "0.3.0" dependencies = [ "proc-macro2", "quote", diff --git a/config_proc_macro/Cargo.toml b/config_proc_macro/Cargo.toml index a41b3a5e6bf88..d10d0469cc401 100644 --- a/config_proc_macro/Cargo.toml +++ b/config_proc_macro/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rustfmt-config_proc_macro" -version = "0.2.0" +version = "0.3.0" edition = "2018" description = "A collection of procedural macros for rustfmt" license = "Apache-2.0/MIT" diff --git a/config_proc_macro/src/attrs.rs b/config_proc_macro/src/attrs.rs index 0baba046f9e91..dd18ff572cb1c 100644 --- a/config_proc_macro/src/attrs.rs +++ b/config_proc_macro/src/attrs.rs @@ -1,8 +1,10 @@ //! This module provides utilities for handling attributes on variants -//! of `config_type` enum. Currently there are two types of attributes -//! that could appear on the variants of `config_type` enum: `doc_hint` -//! and `value`. Both comes in the form of name-value pair whose value -//! is string literal. +//! of `config_type` enum. Currently there are the following attributes +//! that could appear on the variants of `config_type` enum: +//! +//! - `doc_hint`: name-value pair whose value is string literal +//! - `value`: name-value pair whose value is string literal +//! - `unstable_variant`: name only /// Returns the value of the first `doc_hint` attribute in the given slice or /// `None` if `doc_hint` attribute is not available. @@ -27,6 +29,11 @@ pub fn find_config_value(attrs: &[syn::Attribute]) -> Option { attrs.iter().filter_map(config_value).next() } +/// Returns `true` if the there is at least one `unstable` attribute in the given slice. +pub fn any_unstable_variant(attrs: &[syn::Attribute]) -> bool { + attrs.iter().any(is_unstable_variant) +} + /// Returns a string literal value if the given attribute is `value` /// attribute or `None` otherwise. pub fn config_value(attr: &syn::Attribute) -> Option { @@ -38,6 +45,11 @@ pub fn is_config_value(attr: &syn::Attribute) -> bool { is_attr_name_value(attr, "value") } +/// Returns `true` if the given attribute is an `unstable` attribute. +pub fn is_unstable_variant(attr: &syn::Attribute) -> bool { + is_attr_path(attr, "unstable_variant") +} + fn is_attr_name_value(attr: &syn::Attribute, name: &str) -> bool { attr.parse_meta().ok().map_or(false, |meta| match meta { syn::Meta::NameValue(syn::MetaNameValue { ref path, .. }) if path.is_ident(name) => true, @@ -45,6 +57,13 @@ fn is_attr_name_value(attr: &syn::Attribute, name: &str) -> bool { }) } +fn is_attr_path(attr: &syn::Attribute, name: &str) -> bool { + attr.parse_meta().ok().map_or(false, |meta| match meta { + syn::Meta::Path(path) if path.is_ident(name) => true, + _ => false, + }) +} + fn get_name_value_str_lit(attr: &syn::Attribute, name: &str) -> Option { attr.parse_meta().ok().and_then(|meta| match meta { syn::Meta::NameValue(syn::MetaNameValue { diff --git a/config_proc_macro/src/item_enum.rs b/config_proc_macro/src/item_enum.rs index dcee77a8549c5..731a7ea06077b 100644 --- a/config_proc_macro/src/item_enum.rs +++ b/config_proc_macro/src/item_enum.rs @@ -1,5 +1,6 @@ use proc_macro2::TokenStream; -use quote::quote; +use quote::{quote, quote_spanned}; +use syn::spanned::Spanned; use crate::attrs::*; use crate::utils::*; @@ -47,12 +48,23 @@ fn process_variant(variant: &syn::Variant) -> TokenStream { let metas = variant .attrs .iter() - .filter(|attr| !is_doc_hint(attr) && !is_config_value(attr)); + .filter(|attr| !is_doc_hint(attr) && !is_config_value(attr) && !is_unstable_variant(attr)); let attrs = fold_quote(metas, |meta| quote!(#meta)); let syn::Variant { ident, fields, .. } = variant; quote!(#attrs #ident #fields) } +/// Return the correct syntax to pattern match on the enum variant, discarding all +/// internal field data. +fn fields_in_variant(variant: &syn::Variant) -> TokenStream { + // With thanks to https://stackoverflow.com/a/65182902 + match &variant.fields { + syn::Fields::Unnamed(_) => quote_spanned! { variant.span() => (..) }, + syn::Fields::Unit => quote_spanned! { variant.span() => }, + syn::Fields::Named(_) => quote_spanned! { variant.span() => {..} }, + } +} + fn impl_doc_hint(ident: &syn::Ident, variants: &Variants) -> TokenStream { let doc_hint = variants .iter() @@ -60,12 +72,26 @@ fn impl_doc_hint(ident: &syn::Ident, variants: &Variants) -> TokenStream { .collect::>() .join("|"); let doc_hint = format!("[{}]", doc_hint); + + let variant_stables = variants + .iter() + .map(|v| (&v.ident, fields_in_variant(&v), !unstable_of_variant(v))); + let match_patterns = fold_quote(variant_stables, |(v, fields, stable)| { + quote! { + #ident::#v #fields => #stable, + } + }); quote! { use crate::config::ConfigType; impl ConfigType for #ident { fn doc_hint() -> String { #doc_hint.to_owned() } + fn stable_variant(&self) -> bool { + match self { + #match_patterns + } + } } } } @@ -123,13 +149,21 @@ fn impl_from_str(ident: &syn::Ident, variants: &Variants) -> TokenStream { } fn doc_hint_of_variant(variant: &syn::Variant) -> String { - find_doc_hint(&variant.attrs).unwrap_or(variant.ident.to_string()) + let mut text = find_doc_hint(&variant.attrs).unwrap_or(variant.ident.to_string()); + if unstable_of_variant(&variant) { + text.push_str(" (unstable)") + }; + text } fn config_value_of_variant(variant: &syn::Variant) -> String { find_config_value(&variant.attrs).unwrap_or(variant.ident.to_string()) } +fn unstable_of_variant(variant: &syn::Variant) -> bool { + any_unstable_variant(&variant.attrs) +} + fn impl_serde(ident: &syn::Ident, variants: &Variants) -> TokenStream { let arms = fold_quote(variants.iter(), |v| { let v_ident = &v.ident; diff --git a/config_proc_macro/tests/smoke.rs b/config_proc_macro/tests/smoke.rs index 940a8a0c251e4..c8a83e39c9efc 100644 --- a/config_proc_macro/tests/smoke.rs +++ b/config_proc_macro/tests/smoke.rs @@ -1,6 +1,7 @@ pub mod config { pub trait ConfigType: Sized { fn doc_hint() -> String; + fn stable_variant(&self) -> bool; } } diff --git a/src/config/config_type.rs b/src/config/config_type.rs index e37ed798cb559..26d57a13791a5 100644 --- a/src/config/config_type.rs +++ b/src/config/config_type.rs @@ -6,6 +6,14 @@ pub(crate) trait ConfigType: Sized { /// Returns hint text for use in `Config::print_docs()`. For enum types, this is a /// pipe-separated list of variants; for other types it returns "". fn doc_hint() -> String; + + /// Return `true` if the variant (i.e. value of this type) is stable. + /// + /// By default, return true for all values. Enums annotated with `#[config_type]` + /// are automatically implemented, based on the `#[unstable_variant]` annotation. + fn stable_variant(&self) -> bool { + true + } } impl ConfigType for bool { @@ -51,6 +59,13 @@ impl ConfigType for IgnoreList { } macro_rules! create_config { + // Options passed in to the macro. + // + // - $i: the ident name of the option + // - $ty: the type of the option value + // - $def: the default value of the option + // - $stb: true if the option is stable + // - $dstring: description of the option ($($i:ident: $ty:ty, $def:expr, $stb:expr, $( $dstring:expr ),+ );+ $(;)*) => ( #[cfg(test)] use std::collections::HashSet; @@ -61,9 +76,12 @@ macro_rules! create_config { #[derive(Clone)] #[allow(unreachable_pub)] pub struct Config { - // For each config item, we store a bool indicating whether it has - // been accessed and the value, and a bool whether the option was - // manually initialised, or taken from the default, + // For each config item, we store: + // + // - 0: true if the value has been access + // - 1: true if the option was manually initialized + // - 2: the option value + // - 3: true if the option is unstable $($i: (Cell, bool, $ty, bool)),+ } @@ -143,18 +161,13 @@ macro_rules! create_config { fn fill_from_parsed_config(mut self, parsed: PartialConfig, dir: &Path) -> Config { $( - if let Some(val) = parsed.$i { - if self.$i.3 { + if let Some(option_value) = parsed.$i { + let option_stable = self.$i.3; + if $crate::config::config_type::is_stable_option_and_value( + stringify!($i), option_stable, &option_value + ) { self.$i.1 = true; - self.$i.2 = val; - } else { - if crate::is_nightly_channel!() { - self.$i.1 = true; - self.$i.2 = val; - } else { - eprintln!("Warning: can't set `{} = {:?}`, unstable features are only \ - available in nightly channel.", stringify!($i), val); - } + self.$i.2 = option_value; } } )+ @@ -221,12 +234,22 @@ macro_rules! create_config { match key { $( stringify!($i) => { - self.$i.1 = true; - self.$i.2 = val.parse::<$ty>() + let option_value = val.parse::<$ty>() .expect(&format!("Failed to parse override for {} (\"{}\") as a {}", stringify!($i), val, stringify!($ty))); + + // Users are currently allowed to set unstable + // options/variants via the `--config` options override. + // + // There is ongoing discussion about how to move forward here: + // https://github.com/rust-lang/rustfmt/pull/5379 + // + // For now, do not validate whether the option or value is stable, + // just always set it. + self.$i.1 = true; + self.$i.2 = option_value; } )+ _ => panic!("Unknown config key in override: {}", key) @@ -424,3 +447,38 @@ macro_rules! create_config { } ) } + +pub(crate) fn is_stable_option_and_value( + option_name: &str, + option_stable: bool, + option_value: &T, +) -> bool +where + T: PartialEq + std::fmt::Debug + ConfigType, +{ + let nightly = crate::is_nightly_channel!(); + let variant_stable = option_value.stable_variant(); + match (nightly, option_stable, variant_stable) { + // Stable with an unstable option + (false, false, _) => { + eprintln!( + "Warning: can't set `{} = {:?}`, unstable features are only \ + available in nightly channel.", + option_name, option_value + ); + false + } + // Stable with a stable option, but an unstable variant + (false, true, false) => { + eprintln!( + "Warning: can't set `{} = {:?}`, unstable variants are only \ + available in nightly channel.", + option_name, option_value + ); + false + } + // Nightly: everything allowed + // Stable with stable option and variant: allowed + (true, _, _) | (false, true, true) => true, + } +} diff --git a/src/config/mod.rs b/src/config/mod.rs index f49c18d3a4603..eaada8db090a8 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -408,6 +408,15 @@ mod test { #[allow(dead_code)] mod mock { use super::super::*; + use rustfmt_config_proc_macro::config_type; + + #[config_type] + pub enum PartiallyUnstableOption { + V1, + V2, + #[unstable_variant] + V3, + } create_config! { // Options that are used by the generated functions @@ -451,6 +460,63 @@ mod test { // Options that are used by the tests stable_option: bool, false, true, "A stable option"; unstable_option: bool, false, false, "An unstable option"; + partially_unstable_option: PartiallyUnstableOption, PartiallyUnstableOption::V1, true, + "A partially unstable option"; + } + + #[cfg(test)] + mod partially_unstable_option { + use super::{Config, PartialConfig, PartiallyUnstableOption}; + use rustfmt_config_proc_macro::{nightly_only_test, stable_only_test}; + use std::path::Path; + + /// From the config file, we can fill with a stable variant + #[test] + fn test_from_toml_stable_value() { + let toml = r#" + partially_unstable_option = "V2" + "#; + let partial_config: PartialConfig = toml::from_str(toml).unwrap(); + let config = Config::default(); + let config = config.fill_from_parsed_config(partial_config, Path::new("")); + assert_eq!( + config.partially_unstable_option(), + PartiallyUnstableOption::V2 + ); + } + + /// From the config file, we cannot fill with an unstable variant (stable only) + #[stable_only_test] + #[test] + fn test_from_toml_unstable_value_on_stable() { + let toml = r#" + partially_unstable_option = "V3" + "#; + let partial_config: PartialConfig = toml::from_str(toml).unwrap(); + let config = Config::default(); + let config = config.fill_from_parsed_config(partial_config, Path::new("")); + assert_eq!( + config.partially_unstable_option(), + // default value from config, i.e. fill failed + PartiallyUnstableOption::V1 + ); + } + + /// From the config file, we can fill with an unstable variant (nightly only) + #[nightly_only_test] + #[test] + fn test_from_toml_unstable_value_on_nightly() { + let toml = r#" + partially_unstable_option = "V3" + "#; + let partial_config: PartialConfig = toml::from_str(toml).unwrap(); + let config = Config::default(); + let config = config.fill_from_parsed_config(partial_config, Path::new("")); + assert_eq!( + config.partially_unstable_option(), + PartiallyUnstableOption::V3 + ); + } } } @@ -489,6 +555,11 @@ mod test { assert_eq!(config.was_set().verbose(), false); } + const PRINT_DOCS_STABLE_OPTION: &str = "stable_option Default: false"; + const PRINT_DOCS_UNSTABLE_OPTION: &str = "unstable_option Default: false (unstable)"; + const PRINT_DOCS_PARTIALLY_UNSTABLE_OPTION: &str = + "partially_unstable_option [V1|V2|V3 (unstable)] Default: V1"; + #[test] fn test_print_docs_exclude_unstable() { use self::mock::Config; @@ -497,10 +568,9 @@ mod test { Config::print_docs(&mut output, false); let s = str::from_utf8(&output).unwrap(); - - assert_eq!(s.contains("stable_option"), true); - assert_eq!(s.contains("unstable_option"), false); - assert_eq!(s.contains("(unstable)"), false); + assert_eq!(s.contains(PRINT_DOCS_STABLE_OPTION), true); + assert_eq!(s.contains(PRINT_DOCS_UNSTABLE_OPTION), false); + assert_eq!(s.contains(PRINT_DOCS_PARTIALLY_UNSTABLE_OPTION), true); } #[test] @@ -511,9 +581,9 @@ mod test { Config::print_docs(&mut output, true); let s = str::from_utf8(&output).unwrap(); - assert_eq!(s.contains("stable_option"), true); - assert_eq!(s.contains("unstable_option"), true); - assert_eq!(s.contains("(unstable)"), true); + assert_eq!(s.contains(PRINT_DOCS_STABLE_OPTION), true); + assert_eq!(s.contains(PRINT_DOCS_UNSTABLE_OPTION), true); + assert_eq!(s.contains(PRINT_DOCS_PARTIALLY_UNSTABLE_OPTION), true); } #[test] @@ -921,4 +991,32 @@ make_backup = false assert_eq!(config.single_line_if_else_max_width(), 100); } } + + #[cfg(test)] + mod partially_unstable_option { + use super::mock::{Config, PartiallyUnstableOption}; + use super::*; + + /// From the command line, we can override with a stable variant. + #[test] + fn test_override_stable_value() { + let mut config = Config::default(); + config.override_value("partially_unstable_option", "V2"); + assert_eq!( + config.partially_unstable_option(), + PartiallyUnstableOption::V2 + ); + } + + /// From the command line, we can override with an unstable variant. + #[test] + fn test_override_unstable_value() { + let mut config = Config::default(); + config.override_value("partially_unstable_option", "V3"); + assert_eq!( + config.partially_unstable_option(), + PartiallyUnstableOption::V3 + ); + } + } } From 45f4f6ccf7fbccd81db84f2a7ee7881884668ab2 Mon Sep 17 00:00:00 2001 From: Nixon Enraght-Moony Date: Sat, 2 Jul 2022 18:25:55 +0100 Subject: [PATCH 04/69] ast: Add span to `Extern` --- src/items.rs | 2 +- src/utils.rs | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/items.rs b/src/items.rs index bab881f4b4e8d..8f35068e35f04 100644 --- a/src/items.rs +++ b/src/items.rs @@ -148,7 +148,7 @@ impl<'a> Item<'a> { Item { unsafety: fm.unsafety, abi: format_extern( - ast::Extern::from_abi(fm.abi), + ast::Extern::from_abi(fm.abi, DUMMY_SP), config.force_explicit_abi(), true, ), diff --git a/src/utils.rs b/src/utils.rs index 58fd95c656e79..4b26f4e40df98 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -138,8 +138,8 @@ pub(crate) fn format_extern( ) -> Cow<'static, str> { let abi = match ext { ast::Extern::None => "Rust".to_owned(), - ast::Extern::Implicit => "C".to_owned(), - ast::Extern::Explicit(abi) => abi.symbol_unescaped.to_string(), + ast::Extern::Implicit(_) => "C".to_owned(), + ast::Extern::Explicit(abi, _) => abi.symbol_unescaped.to_string(), }; if abi == "Rust" && !is_mod { From 35f4c55bf476884feadf525e110453f6815f8dd8 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Sun, 3 Jul 2022 22:09:42 -0500 Subject: [PATCH 05/69] refactor: remove some unnecessary clones --- src/chains.rs | 21 ++++++++++----------- src/expr.rs | 9 ++++----- src/macros.rs | 15 +++++++-------- src/utils.rs | 5 +++-- 4 files changed, 24 insertions(+), 26 deletions(-) diff --git a/src/chains.rs b/src/chains.rs index e26e24ec55ad6..5bccb22db4c17 100644 --- a/src/chains.rs +++ b/src/chains.rs @@ -70,8 +70,8 @@ use crate::rewrite::{Rewrite, RewriteContext}; use crate::shape::Shape; use crate::source_map::SpanUtils; use crate::utils::{ - self, first_line_width, last_line_extendable, last_line_width, mk_sp, rewrite_ident, - trimmed_last_line_width, wrap_str, + self, filtered_str_fits, first_line_width, last_line_extendable, last_line_width, mk_sp, + rewrite_ident, trimmed_last_line_width, wrap_str, }; pub(crate) fn rewrite_chain( @@ -810,15 +810,14 @@ impl<'a> ChainFormatter for ChainFormatterVisual<'a> { .visual_indent(self.offset) .sub_width(self.offset)?; let rewrite = item.rewrite(context, child_shape)?; - match wrap_str(rewrite, context.config.max_width(), shape) { - Some(rewrite) => root_rewrite.push_str(&rewrite), - None => { - // We couldn't fit in at the visual indent, try the last - // indent. - let rewrite = item.rewrite(context, parent_shape)?; - root_rewrite.push_str(&rewrite); - self.offset = 0; - } + if filtered_str_fits(&rewrite, context.config.max_width(), shape) { + root_rewrite.push_str(&rewrite); + } else { + // We couldn't fit in at the visual indent, try the last + // indent. + let rewrite = item.rewrite(context, parent_shape)?; + root_rewrite.push_str(&rewrite); + self.offset = 0; } self.shared.children = &self.shared.children[1..]; diff --git a/src/expr.rs b/src/expr.rs index e4cc93026f10b..13d068d0c2dd5 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -29,9 +29,9 @@ use crate::spanned::Spanned; use crate::string::{rewrite_string, StringFormat}; use crate::types::{rewrite_path, PathContext}; use crate::utils::{ - colon_spaces, contains_skip, count_newlines, first_line_ends_with, inner_attributes, - last_line_extendable, last_line_width, mk_sp, outer_attributes, semicolon_for_expr, - unicode_str_width, wrap_str, + colon_spaces, contains_skip, count_newlines, filtered_str_fits, first_line_ends_with, + inner_attributes, last_line_extendable, last_line_width, mk_sp, outer_attributes, + semicolon_for_expr, unicode_str_width, wrap_str, }; use crate::vertical::rewrite_with_alignment; use crate::visitor::FmtVisitor; @@ -2037,8 +2037,7 @@ fn choose_rhs( match (orig_rhs, new_rhs) { (Some(ref orig_rhs), Some(ref new_rhs)) - if wrap_str(new_rhs.clone(), context.config.max_width(), new_shape) - .is_none() => + if !filtered_str_fits(&new_rhs, context.config.max_width(), new_shape) => { Some(format!("{}{}", before_space_str, orig_rhs)) } diff --git a/src/macros.rs b/src/macros.rs index f4b2bcf281577..e78ef1f806678 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -35,8 +35,8 @@ use crate::shape::{Indent, Shape}; use crate::source_map::SpanUtils; use crate::spanned::Spanned; use crate::utils::{ - format_visibility, indent_next_line, is_empty_line, mk_sp, remove_trailing_white_spaces, - rewrite_ident, trim_left_preserve_layout, wrap_str, NodeIdExt, + filtered_str_fits, format_visibility, indent_next_line, is_empty_line, mk_sp, + remove_trailing_white_spaces, rewrite_ident, trim_left_preserve_layout, NodeIdExt, }; use crate::visitor::FmtVisitor; @@ -1241,15 +1241,14 @@ impl MacroBranch { } } }; - let new_body = wrap_str( - new_body_snippet.snippet.to_string(), - config.max_width(), - shape, - )?; + + if !filtered_str_fits(&new_body_snippet.snippet, config.max_width(), shape) { + return None; + } // Indent the body since it is in a block. let indent_str = body_indent.to_string(&config); - let mut new_body = LineClasses::new(new_body.trim_end()) + let mut new_body = LineClasses::new(new_body_snippet.snippet.trim_end()) .enumerate() .fold( (String::new(), true), diff --git a/src/utils.rs b/src/utils.rs index 58fd95c656e79..0e87d6bb50e2d 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -384,14 +384,15 @@ macro_rules! skip_out_of_file_lines_range_visitor { // Wraps String in an Option. Returns Some when the string adheres to the // Rewrite constraints defined for the Rewrite trait and None otherwise. pub(crate) fn wrap_str(s: String, max_width: usize, shape: Shape) -> Option { - if is_valid_str(&filter_normal_code(&s), max_width, shape) { + if filtered_str_fits(&s, max_width, shape) { Some(s) } else { None } } -fn is_valid_str(snippet: &str, max_width: usize, shape: Shape) -> bool { +pub(crate) fn filtered_str_fits(snippet: &str, max_width: usize, shape: Shape) -> bool { + let snippet = &filter_normal_code(snippet); if !snippet.is_empty() { // First line must fits with `shape.width`. if first_line_width(snippet) > shape.width { From 2403f827bf1e427a04ce45c88a64cbebe91041d7 Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Sat, 9 Jul 2022 17:54:59 -0400 Subject: [PATCH 06/69] Add test case for issue 1306 which was resolved Closes 1306 It's unclear when the issue was fixed, but it cannot be reproduced. --- tests/source/issue_1306.rs | 29 +++++++++++++++++++++++++++++ tests/target/issue_1306.rs | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 tests/source/issue_1306.rs create mode 100644 tests/target/issue_1306.rs diff --git a/tests/source/issue_1306.rs b/tests/source/issue_1306.rs new file mode 100644 index 0000000000000..03b78e34108cc --- /dev/null +++ b/tests/source/issue_1306.rs @@ -0,0 +1,29 @@ +// rustfmt-max_width: 160 +// rustfmt-fn_call_width: 96 +// rustfmt-fn_args_layout: Compressed +// rustfmt-trailing_comma: Always +// rustfmt-wrap_comments: true + +fn foo() { + for elem in try!(gen_epub_book::ops::parse_descriptor_file(&mut try!(File::open(&opts.source_file.1).map_err(|_| { + gen_epub_book::Error::Io { + desc: "input file", + op: "open", + more: None, + } + })), + "input file")) { + println!("{}", elem); + } +} + +fn write_content() { + io::copy(try!(File::open(in_f).map_err(|_| { + Error::Io { + desc: "Content", + op: "open", + more: None, + } + })), + w); +} diff --git a/tests/target/issue_1306.rs b/tests/target/issue_1306.rs new file mode 100644 index 0000000000000..6bb514cdfe550 --- /dev/null +++ b/tests/target/issue_1306.rs @@ -0,0 +1,33 @@ +// rustfmt-max_width: 160 +// rustfmt-fn_call_width: 96 +// rustfmt-fn_args_layout: Compressed +// rustfmt-trailing_comma: Always +// rustfmt-wrap_comments: true + +fn foo() { + for elem in try!(gen_epub_book::ops::parse_descriptor_file( + &mut try!(File::open(&opts.source_file.1).map_err(|_| { + gen_epub_book::Error::Io { + desc: "input file", + op: "open", + more: None, + } + })), + "input file" + )) { + println!("{}", elem); + } +} + +fn write_content() { + io::copy( + try!(File::open(in_f).map_err(|_| { + Error::Io { + desc: "Content", + op: "open", + more: None, + } + })), + w, + ); +} From 2964d0a5332fb0fd4d2c056ee9b651215b99b027 Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Thu, 30 Jun 2022 17:40:38 +0400 Subject: [PATCH 07/69] implement rustfmt formatting for `for<>` closure binders --- src/closures.rs | 33 +++++++++++++++++++++++++++------ src/expr.rs | 16 +++++++++++----- src/types.rs | 2 +- src/utils.rs | 2 +- 4 files changed, 40 insertions(+), 13 deletions(-) diff --git a/src/closures.rs b/src/closures.rs index e688db1c39d7c..88a6bebb68c84 100644 --- a/src/closures.rs +++ b/src/closures.rs @@ -11,6 +11,7 @@ use crate::overflow::OverflowableItem; use crate::rewrite::{Rewrite, RewriteContext}; use crate::shape::Shape; use crate::source_map::SpanUtils; +use crate::types::rewrite_lifetime_param; use crate::utils::{last_line_width, left_most_sub_expr, stmt_expr, NodeIdExt}; // This module is pretty messy because of the rules around closures and blocks: @@ -24,6 +25,7 @@ use crate::utils::{last_line_width, left_most_sub_expr, stmt_expr, NodeIdExt}; // can change whether it is treated as an expression or statement. pub(crate) fn rewrite_closure( + binder: &ast::ClosureBinder, capture: ast::CaptureBy, is_async: &ast::Async, movability: ast::Movability, @@ -36,7 +38,7 @@ pub(crate) fn rewrite_closure( debug!("rewrite_closure {:?}", body); let (prefix, extra_offset) = rewrite_closure_fn_decl( - capture, is_async, movability, fn_decl, body, span, context, shape, + binder, capture, is_async, movability, fn_decl, body, span, context, shape, )?; // 1 = space between `|...|` and body. let body_shape = shape.offset_left(extra_offset)?; @@ -227,6 +229,7 @@ fn rewrite_closure_block( // Return type is (prefix, extra_offset) fn rewrite_closure_fn_decl( + binder: &ast::ClosureBinder, capture: ast::CaptureBy, asyncness: &ast::Async, movability: ast::Movability, @@ -236,6 +239,17 @@ fn rewrite_closure_fn_decl( context: &RewriteContext<'_>, shape: Shape, ) -> Option<(String, usize)> { + let binder = match binder { + ast::ClosureBinder::For { generic_params, .. } if generic_params.is_empty() => { + "for<> ".to_owned() + } + ast::ClosureBinder::For { generic_params, .. } => { + let lifetime_str = rewrite_lifetime_param(context, shape, generic_params)?; + format!("for<{lifetime_str}> ") + } + ast::ClosureBinder::NotPresent => "".to_owned(), + }; + let immovable = if movability == ast::Movability::Static { "static " } else { @@ -250,7 +264,7 @@ fn rewrite_closure_fn_decl( // 4 = "|| {".len(), which is overconservative when the closure consists of // a single expression. let nested_shape = shape - .shrink_left(immovable.len() + is_async.len() + mover.len())? + .shrink_left(binder.len() + immovable.len() + is_async.len() + mover.len())? .sub_width(4)?; // 1 = | @@ -288,7 +302,7 @@ fn rewrite_closure_fn_decl( .tactic(tactic) .preserve_newline(true); let list_str = write_list(&item_vec, &fmt)?; - let mut prefix = format!("{}{}{}|{}|", immovable, is_async, mover, list_str); + let mut prefix = format!("{}{}{}{}|{}|", binder, immovable, is_async, mover, list_str); if !ret_str.is_empty() { if prefix.contains('\n') { @@ -312,8 +326,15 @@ pub(crate) fn rewrite_last_closure( expr: &ast::Expr, shape: Shape, ) -> Option { - if let ast::ExprKind::Closure(capture, ref is_async, movability, ref fn_decl, ref body, _) = - expr.kind + if let ast::ExprKind::Closure( + ref binder, + capture, + ref is_async, + movability, + ref fn_decl, + ref body, + _, + ) = expr.kind { let body = match body.kind { ast::ExprKind::Block(ref block, _) @@ -326,7 +347,7 @@ pub(crate) fn rewrite_last_closure( _ => body, }; let (prefix, extra_offset) = rewrite_closure_fn_decl( - capture, is_async, movability, fn_decl, body, expr.span, context, shape, + binder, capture, is_async, movability, fn_decl, body, expr.span, context, shape, )?; // If the closure goes multi line before its body, do not overflow the closure. if prefix.contains('\n') { diff --git a/src/expr.rs b/src/expr.rs index e4cc93026f10b..a7b73ba78c59e 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -203,11 +203,17 @@ pub(crate) fn format_expr( Some("yield".to_string()) } } - ast::ExprKind::Closure(capture, ref is_async, movability, ref fn_decl, ref body, _) => { - closures::rewrite_closure( - capture, is_async, movability, fn_decl, body, expr.span, context, shape, - ) - } + ast::ExprKind::Closure( + ref binder, + capture, + ref is_async, + movability, + ref fn_decl, + ref body, + _, + ) => closures::rewrite_closure( + binder, capture, is_async, movability, fn_decl, body, expr.span, context, shape, + ), ast::ExprKind::Try(..) | ast::ExprKind::Field(..) | ast::ExprKind::MethodCall(..) diff --git a/src/types.rs b/src/types.rs index 64a201e45ddd4..2627886db109d 100644 --- a/src/types.rs +++ b/src/types.rs @@ -1067,7 +1067,7 @@ pub(crate) fn can_be_overflowed_type( } /// Returns `None` if there is no `LifetimeDef` in the given generic parameters. -fn rewrite_lifetime_param( +pub(crate) fn rewrite_lifetime_param( context: &RewriteContext<'_>, shape: Shape, generic_params: &[ast::GenericParam], diff --git a/src/utils.rs b/src/utils.rs index 4b26f4e40df98..cd852855602e8 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -479,7 +479,7 @@ pub(crate) fn is_block_expr(context: &RewriteContext<'_>, expr: &ast::Expr, repr | ast::ExprKind::Binary(_, _, ref expr) | ast::ExprKind::Index(_, ref expr) | ast::ExprKind::Unary(_, ref expr) - | ast::ExprKind::Closure(_, _, _, _, ref expr, _) + | ast::ExprKind::Closure(_, _, _, _, _, ref expr, _) | ast::ExprKind::Try(ref expr) | ast::ExprKind::Yield(Some(ref expr)) => is_block_expr(context, expr, repr), // This can only be a string lit From f026688c2abd95fdfabe50ace0a422004d4c47d5 Mon Sep 17 00:00:00 2001 From: Maybe Waffle Date: Sun, 3 Jul 2022 16:11:46 +0400 Subject: [PATCH 08/69] Add rustfmt test for formatting `for<>` before closures --- tests/source/closure.rs | 10 ++++++++++ tests/target/closure.rs | 6 ++++++ 2 files changed, 16 insertions(+) diff --git a/tests/source/closure.rs b/tests/source/closure.rs index e93cc3fb40f59..b2d28b305d0ad 100644 --- a/tests/source/closure.rs +++ b/tests/source/closure.rs @@ -51,6 +51,16 @@ fn main() { "--emit=dep-info" } else { a } }); + + for<> || -> () {}; + for< >|| -> () {}; + for< +> || -> () {}; + +for< 'a + ,'b, +'c > |_: &'a (), _: &'b (), _: &'c ()| -> () {}; + } fn issue311() { diff --git a/tests/target/closure.rs b/tests/target/closure.rs index f3107d19c2fbf..e8b4ff7a96bb8 100644 --- a/tests/target/closure.rs +++ b/tests/target/closure.rs @@ -71,6 +71,12 @@ fn main() { a } }); + + for<> || -> () {}; + for<> || -> () {}; + for<> || -> () {}; + + for<'a, 'b, 'c> |_: &'a (), _: &'b (), _: &'c ()| -> () {}; } fn issue311() { From c240f3a6b3f0b7f91113dc999217f40f029a2776 Mon Sep 17 00:00:00 2001 From: Tom Milligan Date: Wed, 13 Jul 2022 01:31:19 +0100 Subject: [PATCH 09/69] feat: add skip_macro_invocations option (#5347) * feat: add skip_macro_names option * [review] update configuration documentation * [review] fix docstring * [feat] implement wildcard macro invocation skip * commit missed files * [review] test override skip macro names * [review] skip_macro_names -> skip_macro_invocations * [review] expand doc configuration * [review] add lots more tests * [review] add use alias test examples * [review] add link to standard macro behaviour --- Configurations.md | 56 +++++++++ src/config/config_type.rs | 7 ++ src/config/macro_names.rs | 118 ++++++++++++++++++ src/config/mod.rs | 20 +++ src/skip.rs | 10 +- src/test/configuration_snippet.rs | 7 +- src/visitor.rs | 13 +- tests/source/skip_macro_invocations/all.rs | 11 ++ .../skip_macro_invocations/all_and_name.rs | 11 ++ tests/source/skip_macro_invocations/empty.rs | 11 ++ tests/source/skip_macro_invocations/name.rs | 11 ++ .../skip_macro_invocations/name_unknown.rs | 6 + tests/source/skip_macro_invocations/names.rs | 16 +++ .../path_qualified_invocation_mismatch.rs | 6 + .../path_qualified_match.rs | 6 + .../path_qualified_name_mismatch.rs | 6 + .../use_alias_examples.rs | 32 +++++ tests/target/skip_macro_invocations/all.rs | 11 ++ .../skip_macro_invocations/all_and_name.rs | 11 ++ tests/target/skip_macro_invocations/empty.rs | 11 ++ tests/target/skip_macro_invocations/name.rs | 11 ++ .../skip_macro_invocations/name_unknown.rs | 6 + tests/target/skip_macro_invocations/names.rs | 16 +++ .../path_qualified_invocation_mismatch.rs | 6 + .../path_qualified_match.rs | 6 + .../path_qualified_name_mismatch.rs | 6 + .../use_alias_examples.rs | 32 +++++ 27 files changed, 459 insertions(+), 4 deletions(-) create mode 100644 src/config/macro_names.rs create mode 100644 tests/source/skip_macro_invocations/all.rs create mode 100644 tests/source/skip_macro_invocations/all_and_name.rs create mode 100644 tests/source/skip_macro_invocations/empty.rs create mode 100644 tests/source/skip_macro_invocations/name.rs create mode 100644 tests/source/skip_macro_invocations/name_unknown.rs create mode 100644 tests/source/skip_macro_invocations/names.rs create mode 100644 tests/source/skip_macro_invocations/path_qualified_invocation_mismatch.rs create mode 100644 tests/source/skip_macro_invocations/path_qualified_match.rs create mode 100644 tests/source/skip_macro_invocations/path_qualified_name_mismatch.rs create mode 100644 tests/source/skip_macro_invocations/use_alias_examples.rs create mode 100644 tests/target/skip_macro_invocations/all.rs create mode 100644 tests/target/skip_macro_invocations/all_and_name.rs create mode 100644 tests/target/skip_macro_invocations/empty.rs create mode 100644 tests/target/skip_macro_invocations/name.rs create mode 100644 tests/target/skip_macro_invocations/name_unknown.rs create mode 100644 tests/target/skip_macro_invocations/names.rs create mode 100644 tests/target/skip_macro_invocations/path_qualified_invocation_mismatch.rs create mode 100644 tests/target/skip_macro_invocations/path_qualified_match.rs create mode 100644 tests/target/skip_macro_invocations/path_qualified_name_mismatch.rs create mode 100644 tests/target/skip_macro_invocations/use_alias_examples.rs diff --git a/Configurations.md b/Configurations.md index 8b96b9d36892a..5579b5095afac 100644 --- a/Configurations.md +++ b/Configurations.md @@ -1014,6 +1014,62 @@ macro_rules! foo { See also [`format_macro_matchers`](#format_macro_matchers). +## `skip_macro_invocations` + +Skip formatting the bodies of macro invocations with the following names. + +rustfmt will not format any macro invocation for macros with names set in this list. +Including the special value "*" will prevent any macro invocations from being formatted. + +Note: This option does not have any impact on how rustfmt formats macro definitions. + +- **Default value**: `[]` +- **Possible values**: a list of macro name idents, `["name_0", "name_1", ..., "*"]` +- **Stable**: No (tracking issue: [#5346](https://github.com/rust-lang/rustfmt/issues/5346)) + +#### `[]` (default): + +rustfmt will follow its standard approach to formatting macro invocations. + +No macro invocations will be skipped based on their name. More information about rustfmt's standard macro invocation formatting behavior can be found in [#5437](https://github.com/rust-lang/rustfmt/discussions/5437). + +```rust +lorem!( + const _: u8 = 0; +); + +ipsum!( + const _: u8 = 0; +); +``` + +#### `["lorem"]`: + +The named macro invocations will be skipped. + +```rust +lorem!( + const _: u8 = 0; +); + +ipsum!( + const _: u8 = 0; +); +``` + +#### `["*"]`: + +The special selector `*` will skip all macro invocations. + +```rust +lorem!( + const _: u8 = 0; +); + +ipsum!( + const _: u8 = 0; +); +``` ## `format_strings` diff --git a/src/config/config_type.rs b/src/config/config_type.rs index 26d57a13791a5..48f4d9ce80e40 100644 --- a/src/config/config_type.rs +++ b/src/config/config_type.rs @@ -1,4 +1,5 @@ use crate::config::file_lines::FileLines; +use crate::config::macro_names::MacroSelectors; use crate::config::options::{IgnoreList, WidthHeuristics}; /// Trait for types that can be used in `Config`. @@ -46,6 +47,12 @@ impl ConfigType for FileLines { } } +impl ConfigType for MacroSelectors { + fn doc_hint() -> String { + String::from("[, ...]") + } +} + impl ConfigType for WidthHeuristics { fn doc_hint() -> String { String::new() diff --git a/src/config/macro_names.rs b/src/config/macro_names.rs new file mode 100644 index 0000000000000..26ad78d6dcae8 --- /dev/null +++ b/src/config/macro_names.rs @@ -0,0 +1,118 @@ +//! This module contains types and functions to support formatting specific macros. + +use itertools::Itertools; +use std::{fmt, str}; + +use serde::{Deserialize, Serialize}; +use serde_json as json; +use thiserror::Error; + +/// Defines the name of a macro. +#[derive(Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd, Deserialize, Serialize)] +pub struct MacroName(String); + +impl MacroName { + pub fn new(other: String) -> Self { + Self(other) + } +} + +impl fmt::Display for MacroName { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.fmt(f) + } +} + +impl From for String { + fn from(other: MacroName) -> Self { + other.0 + } +} + +/// Defines a selector to match against a macro. +#[derive(Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd, Deserialize, Serialize)] +pub enum MacroSelector { + Name(MacroName), + All, +} + +impl fmt::Display for MacroSelector { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Name(name) => name.fmt(f), + Self::All => write!(f, "*"), + } + } +} + +impl str::FromStr for MacroSelector { + type Err = std::convert::Infallible; + + fn from_str(s: &str) -> Result { + Ok(match s { + "*" => MacroSelector::All, + name => MacroSelector::Name(MacroName(name.to_owned())), + }) + } +} + +/// A set of macro selectors. +#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize)] +pub struct MacroSelectors(pub Vec); + +impl fmt::Display for MacroSelectors { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", self.0.iter().format(", ")) + } +} + +#[derive(Error, Debug)] +pub enum MacroSelectorsError { + #[error("{0}")] + Json(json::Error), +} + +// This impl is needed for `Config::override_value` to work for use in tests. +impl str::FromStr for MacroSelectors { + type Err = MacroSelectorsError; + + fn from_str(s: &str) -> Result { + let raw: Vec<&str> = json::from_str(s).map_err(MacroSelectorsError::Json)?; + Ok(Self( + raw.into_iter() + .map(|raw| { + MacroSelector::from_str(raw).expect("MacroSelector from_str is infallible") + }) + .collect(), + )) + } +} + +#[cfg(test)] +mod test { + use super::*; + use std::str::FromStr; + + #[test] + fn macro_names_from_str() { + let macro_names = MacroSelectors::from_str(r#"["foo", "*", "bar"]"#).unwrap(); + assert_eq!( + macro_names, + MacroSelectors( + [ + MacroSelector::Name(MacroName("foo".to_owned())), + MacroSelector::All, + MacroSelector::Name(MacroName("bar".to_owned())) + ] + .into_iter() + .collect() + ) + ); + } + + #[test] + fn macro_names_display() { + let macro_names = MacroSelectors::from_str(r#"["foo", "*", "bar"]"#).unwrap(); + assert_eq!(format!("{}", macro_names), "foo, *, bar"); + } +} diff --git a/src/config/mod.rs b/src/config/mod.rs index eaada8db090a8..0c6a3cbc9532a 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -13,6 +13,8 @@ pub use crate::config::file_lines::{FileLines, FileName, Range}; #[allow(unreachable_pub)] pub use crate::config::lists::*; #[allow(unreachable_pub)] +pub use crate::config::macro_names::{MacroSelector, MacroSelectors}; +#[allow(unreachable_pub)] pub use crate::config::options::*; #[macro_use] @@ -22,6 +24,7 @@ pub(crate) mod options; pub(crate) mod file_lines; pub(crate) mod lists; +pub(crate) mod macro_names; // This macro defines configuration options used in rustfmt. Each option // is defined as follows: @@ -67,6 +70,8 @@ create_config! { format_macro_matchers: bool, false, false, "Format the metavariable matching patterns in macros"; format_macro_bodies: bool, true, false, "Format the bodies of macros"; + skip_macro_invocations: MacroSelectors, MacroSelectors::default(), false, + "Skip formatting the bodies of macros invoked with the following names."; hex_literal_case: HexLiteralCase, HexLiteralCase::Preserve, false, "Format hexadecimal integer literals"; @@ -403,6 +408,7 @@ mod test { use super::*; use std::str; + use crate::config::macro_names::MacroName; use rustfmt_config_proc_macro::{nightly_only_test, stable_only_test}; #[allow(dead_code)] @@ -611,6 +617,7 @@ normalize_doc_attributes = false format_strings = false format_macro_matchers = false format_macro_bodies = true +skip_macro_invocations = [] hex_literal_case = "Preserve" empty_item_single_line = true struct_lit_single_line = true @@ -1019,4 +1026,17 @@ make_backup = false ); } } + + #[test] + fn test_override_skip_macro_invocations() { + let mut config = Config::default(); + config.override_value("skip_macro_invocations", r#"["*", "println"]"#); + assert_eq!( + config.skip_macro_invocations(), + MacroSelectors(vec![ + MacroSelector::All, + MacroSelector::Name(MacroName::new("println".to_owned())) + ]) + ); + } } diff --git a/src/skip.rs b/src/skip.rs index 0fdc097efc23f..8b2fd7736ae51 100644 --- a/src/skip.rs +++ b/src/skip.rs @@ -7,6 +7,7 @@ use rustc_ast_pretty::pprust; /// by other context. Query this context to know if you need skip a block. #[derive(Default, Clone)] pub(crate) struct SkipContext { + pub(crate) all_macros: bool, macros: Vec, attributes: Vec, } @@ -23,8 +24,15 @@ impl SkipContext { self.attributes.append(&mut other.attributes); } + pub(crate) fn update_macros(&mut self, other: T) + where + T: IntoIterator, + { + self.macros.extend(other.into_iter()); + } + pub(crate) fn skip_macro(&self, name: &str) -> bool { - self.macros.iter().any(|n| n == name) + self.all_macros || self.macros.iter().any(|n| n == name) } pub(crate) fn skip_attribute(&self, name: &str) -> bool { diff --git a/src/test/configuration_snippet.rs b/src/test/configuration_snippet.rs index c8fda7c8556db..c70b3c5facd50 100644 --- a/src/test/configuration_snippet.rs +++ b/src/test/configuration_snippet.rs @@ -27,8 +27,13 @@ impl ConfigurationSection { lazy_static! { static ref CONFIG_NAME_REGEX: regex::Regex = regex::Regex::new(r"^## `([^`]+)`").expect("failed creating configuration pattern"); + // Configuration values, which will be passed to `from_str`: + // + // - must be prefixed with `####` + // - must be wrapped in backticks + // - may by wrapped in double quotes (which will be stripped) static ref CONFIG_VALUE_REGEX: regex::Regex = - regex::Regex::new(r#"^#### `"?([^`"]+)"?`"#) + regex::Regex::new(r#"^#### `"?([^`]+?)"?`"#) .expect("failed creating configuration value pattern"); } diff --git a/src/visitor.rs b/src/visitor.rs index 9a0e0752c12f5..b93153de154a8 100644 --- a/src/visitor.rs +++ b/src/visitor.rs @@ -8,7 +8,7 @@ use rustc_span::{symbol, BytePos, Pos, Span}; use crate::attr::*; use crate::comment::{contains_comment, rewrite_comment, CodeCharKind, CommentCodeSlices}; use crate::config::Version; -use crate::config::{BraceStyle, Config}; +use crate::config::{BraceStyle, Config, MacroSelector}; use crate::coverage::transform_missing_snippet; use crate::items::{ format_impl, format_trait, format_trait_alias, is_mod_decl, is_use_item, rewrite_extern_crate, @@ -770,6 +770,15 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { snippet_provider: &'a SnippetProvider, report: FormatReport, ) -> FmtVisitor<'a> { + let mut skip_context = SkipContext::default(); + let mut macro_names = Vec::new(); + for macro_selector in config.skip_macro_invocations().0 { + match macro_selector { + MacroSelector::Name(name) => macro_names.push(name.to_string()), + MacroSelector::All => skip_context.all_macros = true, + } + } + skip_context.update_macros(macro_names); FmtVisitor { parent_context: None, parse_sess: parse_session, @@ -784,7 +793,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { is_macro_def: false, macro_rewrite_failure: false, report, - skip_context: Default::default(), + skip_context, } } diff --git a/tests/source/skip_macro_invocations/all.rs b/tests/source/skip_macro_invocations/all.rs new file mode 100644 index 0000000000000..d0437ee10fd15 --- /dev/null +++ b/tests/source/skip_macro_invocations/all.rs @@ -0,0 +1,11 @@ +// rustfmt-skip_macro_invocations: ["*"] + +// Should skip this invocation +items!( + const _: u8 = 0; +); + +// Should skip this invocation +renamed_items!( + const _: u8 = 0; +); diff --git a/tests/source/skip_macro_invocations/all_and_name.rs b/tests/source/skip_macro_invocations/all_and_name.rs new file mode 100644 index 0000000000000..1f6722344fe3b --- /dev/null +++ b/tests/source/skip_macro_invocations/all_and_name.rs @@ -0,0 +1,11 @@ +// rustfmt-skip_macro_invocations: ["*","items"] + +// Should skip this invocation +items!( + const _: u8 = 0; +); + +// Should also skip this invocation, as the wildcard covers it +renamed_items!( + const _: u8 = 0; +); diff --git a/tests/source/skip_macro_invocations/empty.rs b/tests/source/skip_macro_invocations/empty.rs new file mode 100644 index 0000000000000..f3dd89dc4db33 --- /dev/null +++ b/tests/source/skip_macro_invocations/empty.rs @@ -0,0 +1,11 @@ +// rustfmt-skip_macro_invocations: [] + +// Should not skip this invocation +items!( + const _: u8 = 0; +); + +// Should not skip this invocation +renamed_items!( + const _: u8 = 0; +); diff --git a/tests/source/skip_macro_invocations/name.rs b/tests/source/skip_macro_invocations/name.rs new file mode 100644 index 0000000000000..7fa5d3a6f715a --- /dev/null +++ b/tests/source/skip_macro_invocations/name.rs @@ -0,0 +1,11 @@ +// rustfmt-skip_macro_invocations: ["items"] + +// Should skip this invocation +items!( + const _: u8 = 0; +); + +// Should not skip this invocation +renamed_items!( + const _: u8 = 0; +); diff --git a/tests/source/skip_macro_invocations/name_unknown.rs b/tests/source/skip_macro_invocations/name_unknown.rs new file mode 100644 index 0000000000000..d56695325240d --- /dev/null +++ b/tests/source/skip_macro_invocations/name_unknown.rs @@ -0,0 +1,6 @@ +// rustfmt-skip_macro_invocations: ["unknown"] + +// Should not skip this invocation +items!( + const _: u8 = 0; +); diff --git a/tests/source/skip_macro_invocations/names.rs b/tests/source/skip_macro_invocations/names.rs new file mode 100644 index 0000000000000..a920381a4552c --- /dev/null +++ b/tests/source/skip_macro_invocations/names.rs @@ -0,0 +1,16 @@ +// rustfmt-skip_macro_invocations: ["foo","bar"] + +// Should skip this invocation +foo!( + const _: u8 = 0; +); + +// Should skip this invocation +bar!( + const _: u8 = 0; +); + +// Should not skip this invocation +baz!( + const _: u8 = 0; +); diff --git a/tests/source/skip_macro_invocations/path_qualified_invocation_mismatch.rs b/tests/source/skip_macro_invocations/path_qualified_invocation_mismatch.rs new file mode 100644 index 0000000000000..61296869a5065 --- /dev/null +++ b/tests/source/skip_macro_invocations/path_qualified_invocation_mismatch.rs @@ -0,0 +1,6 @@ +// rustfmt-skip_macro_invocations: ["items"] + +// Should not skip this invocation +self::items!( + const _: u8 = 0; +); diff --git a/tests/source/skip_macro_invocations/path_qualified_match.rs b/tests/source/skip_macro_invocations/path_qualified_match.rs new file mode 100644 index 0000000000000..9398918a9e11e --- /dev/null +++ b/tests/source/skip_macro_invocations/path_qualified_match.rs @@ -0,0 +1,6 @@ +// rustfmt-skip_macro_invocations: ["self::items"] + +// Should skip this invocation +self::items!( + const _: u8 = 0; +); diff --git a/tests/source/skip_macro_invocations/path_qualified_name_mismatch.rs b/tests/source/skip_macro_invocations/path_qualified_name_mismatch.rs new file mode 100644 index 0000000000000..4e3eb542dbea4 --- /dev/null +++ b/tests/source/skip_macro_invocations/path_qualified_name_mismatch.rs @@ -0,0 +1,6 @@ +// rustfmt-skip_macro_invocations: ["self::items"] + +// Should not skip this invocation +items!( + const _: u8 = 0; +); diff --git a/tests/source/skip_macro_invocations/use_alias_examples.rs b/tests/source/skip_macro_invocations/use_alias_examples.rs new file mode 100644 index 0000000000000..43cb8015de58a --- /dev/null +++ b/tests/source/skip_macro_invocations/use_alias_examples.rs @@ -0,0 +1,32 @@ +// rustfmt-skip_macro_invocations: ["aaa","ccc"] + +// These tests demonstrate a realistic use case with use aliases. +// The use statements should not impact functionality in any way. + +use crate::{aaa, bbb, ddd}; + +// No use alias, invocation in list +// Should skip this invocation +aaa!( + const _: u8 = 0; +); + +// Use alias, invocation in list +// Should skip this invocation +use crate::bbb as ccc; +ccc!( + const _: u8 = 0; +); + +// Use alias, invocation not in list +// Should not skip this invocation +use crate::ddd as eee; +eee!( + const _: u8 = 0; +); + +// No use alias, invocation not in list +// Should not skip this invocation +fff!( + const _: u8 = 0; +); diff --git a/tests/target/skip_macro_invocations/all.rs b/tests/target/skip_macro_invocations/all.rs new file mode 100644 index 0000000000000..d0437ee10fd15 --- /dev/null +++ b/tests/target/skip_macro_invocations/all.rs @@ -0,0 +1,11 @@ +// rustfmt-skip_macro_invocations: ["*"] + +// Should skip this invocation +items!( + const _: u8 = 0; +); + +// Should skip this invocation +renamed_items!( + const _: u8 = 0; +); diff --git a/tests/target/skip_macro_invocations/all_and_name.rs b/tests/target/skip_macro_invocations/all_and_name.rs new file mode 100644 index 0000000000000..1f6722344fe3b --- /dev/null +++ b/tests/target/skip_macro_invocations/all_and_name.rs @@ -0,0 +1,11 @@ +// rustfmt-skip_macro_invocations: ["*","items"] + +// Should skip this invocation +items!( + const _: u8 = 0; +); + +// Should also skip this invocation, as the wildcard covers it +renamed_items!( + const _: u8 = 0; +); diff --git a/tests/target/skip_macro_invocations/empty.rs b/tests/target/skip_macro_invocations/empty.rs new file mode 100644 index 0000000000000..4a398cc59c6ee --- /dev/null +++ b/tests/target/skip_macro_invocations/empty.rs @@ -0,0 +1,11 @@ +// rustfmt-skip_macro_invocations: [] + +// Should not skip this invocation +items!( + const _: u8 = 0; +); + +// Should not skip this invocation +renamed_items!( + const _: u8 = 0; +); diff --git a/tests/target/skip_macro_invocations/name.rs b/tests/target/skip_macro_invocations/name.rs new file mode 100644 index 0000000000000..c4d577269c6f0 --- /dev/null +++ b/tests/target/skip_macro_invocations/name.rs @@ -0,0 +1,11 @@ +// rustfmt-skip_macro_invocations: ["items"] + +// Should skip this invocation +items!( + const _: u8 = 0; +); + +// Should not skip this invocation +renamed_items!( + const _: u8 = 0; +); diff --git a/tests/target/skip_macro_invocations/name_unknown.rs b/tests/target/skip_macro_invocations/name_unknown.rs new file mode 100644 index 0000000000000..7ab1440395c32 --- /dev/null +++ b/tests/target/skip_macro_invocations/name_unknown.rs @@ -0,0 +1,6 @@ +// rustfmt-skip_macro_invocations: ["unknown"] + +// Should not skip this invocation +items!( + const _: u8 = 0; +); diff --git a/tests/target/skip_macro_invocations/names.rs b/tests/target/skip_macro_invocations/names.rs new file mode 100644 index 0000000000000..c6b41ff93d79d --- /dev/null +++ b/tests/target/skip_macro_invocations/names.rs @@ -0,0 +1,16 @@ +// rustfmt-skip_macro_invocations: ["foo","bar"] + +// Should skip this invocation +foo!( + const _: u8 = 0; +); + +// Should skip this invocation +bar!( + const _: u8 = 0; +); + +// Should not skip this invocation +baz!( + const _: u8 = 0; +); diff --git a/tests/target/skip_macro_invocations/path_qualified_invocation_mismatch.rs b/tests/target/skip_macro_invocations/path_qualified_invocation_mismatch.rs new file mode 100644 index 0000000000000..6e372c726952a --- /dev/null +++ b/tests/target/skip_macro_invocations/path_qualified_invocation_mismatch.rs @@ -0,0 +1,6 @@ +// rustfmt-skip_macro_invocations: ["items"] + +// Should not skip this invocation +self::items!( + const _: u8 = 0; +); diff --git a/tests/target/skip_macro_invocations/path_qualified_match.rs b/tests/target/skip_macro_invocations/path_qualified_match.rs new file mode 100644 index 0000000000000..9398918a9e11e --- /dev/null +++ b/tests/target/skip_macro_invocations/path_qualified_match.rs @@ -0,0 +1,6 @@ +// rustfmt-skip_macro_invocations: ["self::items"] + +// Should skip this invocation +self::items!( + const _: u8 = 0; +); diff --git a/tests/target/skip_macro_invocations/path_qualified_name_mismatch.rs b/tests/target/skip_macro_invocations/path_qualified_name_mismatch.rs new file mode 100644 index 0000000000000..aa57a2a655c4a --- /dev/null +++ b/tests/target/skip_macro_invocations/path_qualified_name_mismatch.rs @@ -0,0 +1,6 @@ +// rustfmt-skip_macro_invocations: ["self::items"] + +// Should not skip this invocation +items!( + const _: u8 = 0; +); diff --git a/tests/target/skip_macro_invocations/use_alias_examples.rs b/tests/target/skip_macro_invocations/use_alias_examples.rs new file mode 100644 index 0000000000000..799dd8c08af15 --- /dev/null +++ b/tests/target/skip_macro_invocations/use_alias_examples.rs @@ -0,0 +1,32 @@ +// rustfmt-skip_macro_invocations: ["aaa","ccc"] + +// These tests demonstrate a realistic use case with use aliases. +// The use statements should not impact functionality in any way. + +use crate::{aaa, bbb, ddd}; + +// No use alias, invocation in list +// Should skip this invocation +aaa!( + const _: u8 = 0; +); + +// Use alias, invocation in list +// Should skip this invocation +use crate::bbb as ccc; +ccc!( + const _: u8 = 0; +); + +// Use alias, invocation not in list +// Should not skip this invocation +use crate::ddd as eee; +eee!( + const _: u8 = 0; +); + +// No use alias, invocation not in list +// Should not skip this invocation +fff!( + const _: u8 = 0; +); From 0cb294f05c421d6b6ef266e3ec01c2d8739194b3 Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Wed, 15 Jun 2022 22:43:51 -0400 Subject: [PATCH 10/69] Deprecate and Rename `fn_args_layout` -> `fn_params_layout` fn_args_layout is now deprecated. This option was renamed to better communicate that it affects the layout of parameters in function signatures and not the layout of arguments in function calls. Because the `fn_args_layout` is a stable option the renamed option is also stable, however users who set `fn_args_layout` will get a warning message letting them know that the option has been renamed. --- Configurations.md | 116 +++++++++++++++++- src/config/config_type.rs | 25 +++- src/config/mod.rs | 13 +- src/items.rs | 2 +- tests/config/small_tabs.toml | 2 +- .../compressed.rs | 2 +- .../tall.rs | 2 +- .../vertical.rs | 2 +- tests/source/fn-custom-7.rs | 2 +- tests/source/fn-custom.rs | 2 +- tests/source/fn_args_layout-vertical.rs | 2 +- .../compressed.rs | 2 +- .../tall.rs | 2 +- .../vertical.rs | 2 +- tests/target/fn-custom-7.rs | 2 +- tests/target/fn-custom.rs | 2 +- tests/target/fn_args_layout-vertical.rs | 2 +- tests/target/issue-4791/issue_4928.rs | 2 +- 18 files changed, 164 insertions(+), 20 deletions(-) rename tests/source/configs/{fn_args_layout => fn_params_layout}/compressed.rs (92%) rename tests/source/configs/{fn_args_layout => fn_params_layout}/tall.rs (93%) rename tests/source/configs/{fn_args_layout => fn_params_layout}/vertical.rs (92%) rename tests/target/configs/{fn_args_layout => fn_params_layout}/compressed.rs (92%) rename tests/target/configs/{fn_args_layout => fn_params_layout}/tall.rs (94%) rename tests/target/configs/{fn_args_layout => fn_params_layout}/vertical.rs (94%) diff --git a/Configurations.md b/Configurations.md index 5579b5095afac..17eabd48759e3 100644 --- a/Configurations.md +++ b/Configurations.md @@ -645,7 +645,8 @@ trailing whitespaces. ## `fn_args_layout` -Control the layout of arguments in a function +This option is deprecated and has been renamed to `fn_params_layout` to better communicate that +it affects the layout of parameters in function signatures. - **Default value**: `"Tall"` - **Possible values**: `"Compressed"`, `"Tall"`, `"Vertical"` @@ -753,6 +754,8 @@ trait Lorem { } ``` +See also [`fn_params_layout`](#fn_params_layout) + ## `fn_call_width` Maximum width of the args of a function call before falling back to vertical formatting. @@ -765,6 +768,117 @@ By default this option is set as a percentage of [`max_width`](#max_width) provi See also [`max_width`](#max_width) and [`use_small_heuristics`](#use_small_heuristics) +## `fn_params_layout` + +Control the layout of parameters in function signatures. + +- **Default value**: `"Tall"` +- **Possible values**: `"Compressed"`, `"Tall"`, `"Vertical"` +- **Stable**: Yes + +#### `"Tall"` (default): + +```rust +trait Lorem { + fn lorem(ipsum: Ipsum, dolor: Dolor, sit: Sit, amet: Amet); + + fn lorem(ipsum: Ipsum, dolor: Dolor, sit: Sit, amet: Amet) { + // body + } + + fn lorem( + ipsum: Ipsum, + dolor: Dolor, + sit: Sit, + amet: Amet, + consectetur: Consectetur, + adipiscing: Adipiscing, + elit: Elit, + ); + + fn lorem( + ipsum: Ipsum, + dolor: Dolor, + sit: Sit, + amet: Amet, + consectetur: Consectetur, + adipiscing: Adipiscing, + elit: Elit, + ) { + // body + } +} +``` + +#### `"Compressed"`: + +```rust +trait Lorem { + fn lorem(ipsum: Ipsum, dolor: Dolor, sit: Sit, amet: Amet); + + fn lorem(ipsum: Ipsum, dolor: Dolor, sit: Sit, amet: Amet) { + // body + } + + fn lorem( + ipsum: Ipsum, dolor: Dolor, sit: Sit, amet: Amet, consectetur: Consectetur, + adipiscing: Adipiscing, elit: Elit, + ); + + fn lorem( + ipsum: Ipsum, dolor: Dolor, sit: Sit, amet: Amet, consectetur: Consectetur, + adipiscing: Adipiscing, elit: Elit, + ) { + // body + } +} +``` + +#### `"Vertical"`: + +```rust +trait Lorem { + fn lorem( + ipsum: Ipsum, + dolor: Dolor, + sit: Sit, + amet: Amet, + ); + + fn lorem( + ipsum: Ipsum, + dolor: Dolor, + sit: Sit, + amet: Amet, + ) { + // body + } + + fn lorem( + ipsum: Ipsum, + dolor: Dolor, + sit: Sit, + amet: Amet, + consectetur: Consectetur, + adipiscing: Adipiscing, + elit: Elit, + ); + + fn lorem( + ipsum: Ipsum, + dolor: Dolor, + sit: Sit, + amet: Amet, + consectetur: Consectetur, + adipiscing: Adipiscing, + elit: Elit, + ) { + // body + } +} +``` + + ## `fn_single_line` Put single-expression functions on a single line diff --git a/src/config/config_type.rs b/src/config/config_type.rs index 48f4d9ce80e40..90a67e12c5a71 100644 --- a/src/config/config_type.rs +++ b/src/config/config_type.rs @@ -127,6 +127,7 @@ macro_rules! create_config { | "array_width" | "chain_width" => self.0.set_heuristics(), "merge_imports" => self.0.set_merge_imports(), + "fn_args_layout" => self.0.set_fn_args_layout(), &_ => (), } } @@ -181,6 +182,7 @@ macro_rules! create_config { self.set_heuristics(); self.set_ignore(dir); self.set_merge_imports(); + self.set_fn_args_layout(); self } @@ -273,14 +275,21 @@ macro_rules! create_config { | "array_width" | "chain_width" => self.set_heuristics(), "merge_imports" => self.set_merge_imports(), + "fn_args_layout" => self.set_fn_args_layout(), &_ => (), } } #[allow(unreachable_pub)] pub fn is_hidden_option(name: &str) -> bool { - const HIDE_OPTIONS: [&str; 5] = - ["verbose", "verbose_diff", "file_lines", "width_heuristics", "merge_imports"]; + const HIDE_OPTIONS: [&str; 6] = [ + "verbose", + "verbose_diff", + "file_lines", + "width_heuristics", + "merge_imports", + "fn_args_layout" + ]; HIDE_OPTIONS.contains(&name) } @@ -430,6 +439,18 @@ macro_rules! create_config { } } + fn set_fn_args_layout(&mut self) { + if self.was_set().fn_args_layout() { + eprintln!( + "Warning: the `fn_args_layout` option is deprecated. \ + Use `fn_params_layout`. instead" + ); + if !self.was_set().fn_params_layout() { + self.fn_params_layout.2 = self.fn_args_layout(); + } + } + } + #[allow(unreachable_pub)] /// Returns `true` if the config key was explicitly set and is the default value. pub fn is_default(&self, key: &str) -> bool { diff --git a/src/config/mod.rs b/src/config/mod.rs index 0c6a3cbc9532a..5492519f3894a 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -124,7 +124,9 @@ create_config! { force_multiline_blocks: bool, false, false, "Force multiline closure bodies and match arms to be wrapped in a block"; fn_args_layout: Density, Density::Tall, true, - "Control the layout of arguments in a function"; + "(deprecated: use fn_params_layout instead)"; + fn_params_layout: Density, Density::Tall, true, + "Control the layout of parameters in function signatures."; brace_style: BraceStyle, BraceStyle::SameLineWhere, false, "Brace style for items"; control_brace_style: ControlBraceStyle, ControlBraceStyle::AlwaysSameLine, false, "Brace style for control flow constructs"; @@ -196,6 +198,7 @@ impl PartialConfig { cloned.width_heuristics = None; cloned.print_misformatted_file_names = None; cloned.merge_imports = None; + cloned.fn_args_layout = None; ::toml::to_string(&cloned).map_err(ToTomlError) } @@ -442,6 +445,12 @@ mod test { "Merge imports"; merge_imports: bool, false, false, "(deprecated: use imports_granularity instead)"; + // fn_args_layout renamed to fn_params_layout + fn_args_layout: Density, Density::Tall, true, + "(deprecated: use fn_params_layout instead)"; + fn_params_layout: Density, Density::Tall, true, + "Control the layout of parameters in a function signatures."; + // Width Heuristics use_small_heuristics: Heuristics, Heuristics::Default, true, "Whether to use different formatting for items and \ @@ -644,7 +653,7 @@ enum_discrim_align_threshold = 0 match_arm_blocks = true match_arm_leading_pipes = "Never" force_multiline_blocks = false -fn_args_layout = "Tall" +fn_params_layout = "Tall" brace_style = "SameLineWhere" control_brace_style = "AlwaysSameLine" trailing_semicolon = true diff --git a/src/items.rs b/src/items.rs index bab881f4b4e8d..6ab02e7f9239b 100644 --- a/src/items.rs +++ b/src/items.rs @@ -2602,7 +2602,7 @@ fn rewrite_params( ¶m_items, context .config - .fn_args_layout() + .fn_params_layout() .to_list_tactic(param_items.len()), Separator::Comma, one_line_budget, diff --git a/tests/config/small_tabs.toml b/tests/config/small_tabs.toml index c3cfd34317a37..4c37100894f83 100644 --- a/tests/config/small_tabs.toml +++ b/tests/config/small_tabs.toml @@ -3,7 +3,7 @@ comment_width = 80 tab_spaces = 2 newline_style = "Unix" brace_style = "SameLineWhere" -fn_args_layout = "Tall" +fn_params_layout = "Tall" trailing_comma = "Vertical" indent_style = "Block" reorder_imports = false diff --git a/tests/source/configs/fn_args_layout/compressed.rs b/tests/source/configs/fn_params_layout/compressed.rs similarity index 92% rename from tests/source/configs/fn_args_layout/compressed.rs rename to tests/source/configs/fn_params_layout/compressed.rs index 66a371c259f0c..eb573d3121f57 100644 --- a/tests/source/configs/fn_args_layout/compressed.rs +++ b/tests/source/configs/fn_params_layout/compressed.rs @@ -1,4 +1,4 @@ -// rustfmt-fn_args_layout: Compressed +// rustfmt-fn_params_layout: Compressed // Function arguments density trait Lorem { diff --git a/tests/source/configs/fn_args_layout/tall.rs b/tests/source/configs/fn_params_layout/tall.rs similarity index 93% rename from tests/source/configs/fn_args_layout/tall.rs rename to tests/source/configs/fn_params_layout/tall.rs index f11e86fd3139c..4be34f0fe4ac1 100644 --- a/tests/source/configs/fn_args_layout/tall.rs +++ b/tests/source/configs/fn_params_layout/tall.rs @@ -1,4 +1,4 @@ -// rustfmt-fn_args_layout: Tall +// rustfmt-fn_params_layout: Tall // Function arguments density trait Lorem { diff --git a/tests/source/configs/fn_args_layout/vertical.rs b/tests/source/configs/fn_params_layout/vertical.rs similarity index 92% rename from tests/source/configs/fn_args_layout/vertical.rs rename to tests/source/configs/fn_params_layout/vertical.rs index a23cc025225fb..674968023f997 100644 --- a/tests/source/configs/fn_args_layout/vertical.rs +++ b/tests/source/configs/fn_params_layout/vertical.rs @@ -1,4 +1,4 @@ -// rustfmt-fn_args_layout: Vertical +// rustfmt-fn_params_layout: Vertical // Function arguments density trait Lorem { diff --git a/tests/source/fn-custom-7.rs b/tests/source/fn-custom-7.rs index d5330196bf795..3ecd8701727ad 100644 --- a/tests/source/fn-custom-7.rs +++ b/tests/source/fn-custom-7.rs @@ -1,5 +1,5 @@ // rustfmt-normalize_comments: true -// rustfmt-fn_args_layout: Vertical +// rustfmt-fn_params_layout: Vertical // rustfmt-brace_style: AlwaysNextLine // Case with only one variable. diff --git a/tests/source/fn-custom.rs b/tests/source/fn-custom.rs index 77ced4c5e0e10..64ef0ecfaae49 100644 --- a/tests/source/fn-custom.rs +++ b/tests/source/fn-custom.rs @@ -1,4 +1,4 @@ -// rustfmt-fn_args_layout: Compressed +// rustfmt-fn_params_layout: Compressed // Test some of the ways function signatures can be customised. // Test compressed layout of args. diff --git a/tests/source/fn_args_layout-vertical.rs b/tests/source/fn_args_layout-vertical.rs index 759bc83d01570..fd6e3f0442ec1 100644 --- a/tests/source/fn_args_layout-vertical.rs +++ b/tests/source/fn_args_layout-vertical.rs @@ -1,4 +1,4 @@ -// rustfmt-fn_args_layout: Vertical +// rustfmt-fn_params_layout: Vertical // Empty list should stay on one line. fn do_bar( diff --git a/tests/target/configs/fn_args_layout/compressed.rs b/tests/target/configs/fn_params_layout/compressed.rs similarity index 92% rename from tests/target/configs/fn_args_layout/compressed.rs rename to tests/target/configs/fn_params_layout/compressed.rs index f189446e25d44..ff32f0f1d5868 100644 --- a/tests/target/configs/fn_args_layout/compressed.rs +++ b/tests/target/configs/fn_params_layout/compressed.rs @@ -1,4 +1,4 @@ -// rustfmt-fn_args_layout: Compressed +// rustfmt-fn_params_layout: Compressed // Function arguments density trait Lorem { diff --git a/tests/target/configs/fn_args_layout/tall.rs b/tests/target/configs/fn_params_layout/tall.rs similarity index 94% rename from tests/target/configs/fn_args_layout/tall.rs rename to tests/target/configs/fn_params_layout/tall.rs index 20f308973acbc..25a86799af0d8 100644 --- a/tests/target/configs/fn_args_layout/tall.rs +++ b/tests/target/configs/fn_params_layout/tall.rs @@ -1,4 +1,4 @@ -// rustfmt-fn_args_layout: Tall +// rustfmt-fn_params_layout: Tall // Function arguments density trait Lorem { diff --git a/tests/target/configs/fn_args_layout/vertical.rs b/tests/target/configs/fn_params_layout/vertical.rs similarity index 94% rename from tests/target/configs/fn_args_layout/vertical.rs rename to tests/target/configs/fn_params_layout/vertical.rs index 6c695a75df9a2..7a0e42415f3b9 100644 --- a/tests/target/configs/fn_args_layout/vertical.rs +++ b/tests/target/configs/fn_params_layout/vertical.rs @@ -1,4 +1,4 @@ -// rustfmt-fn_args_layout: Vertical +// rustfmt-fn_params_layout: Vertical // Function arguments density trait Lorem { diff --git a/tests/target/fn-custom-7.rs b/tests/target/fn-custom-7.rs index 2c20ac5a75249..f6a1a90c3fc68 100644 --- a/tests/target/fn-custom-7.rs +++ b/tests/target/fn-custom-7.rs @@ -1,5 +1,5 @@ // rustfmt-normalize_comments: true -// rustfmt-fn_args_layout: Vertical +// rustfmt-fn_params_layout: Vertical // rustfmt-brace_style: AlwaysNextLine // Case with only one variable. diff --git a/tests/target/fn-custom.rs b/tests/target/fn-custom.rs index 2eb2a973d243d..506d9de34370b 100644 --- a/tests/target/fn-custom.rs +++ b/tests/target/fn-custom.rs @@ -1,4 +1,4 @@ -// rustfmt-fn_args_layout: Compressed +// rustfmt-fn_params_layout: Compressed // Test some of the ways function signatures can be customised. // Test compressed layout of args. diff --git a/tests/target/fn_args_layout-vertical.rs b/tests/target/fn_args_layout-vertical.rs index da0ac981d872d..bfeca15c967ed 100644 --- a/tests/target/fn_args_layout-vertical.rs +++ b/tests/target/fn_args_layout-vertical.rs @@ -1,4 +1,4 @@ -// rustfmt-fn_args_layout: Vertical +// rustfmt-fn_params_layout: Vertical // Empty list should stay on one line. fn do_bar() -> u8 { diff --git a/tests/target/issue-4791/issue_4928.rs b/tests/target/issue-4791/issue_4928.rs index 588656b535fa1..29f6bda90631b 100644 --- a/tests/target/issue-4791/issue_4928.rs +++ b/tests/target/issue-4791/issue_4928.rs @@ -1,7 +1,7 @@ // rustfmt-brace_style: SameLineWhere // rustfmt-comment_width: 100 // rustfmt-edition: 2018 -// rustfmt-fn_args_layout: Compressed +// rustfmt-fn_params_layout: Compressed // rustfmt-hard_tabs: false // rustfmt-match_block_trailing_comma: true // rustfmt-max_width: 100 From dde28314da7fa634f89411fc974ce08ada1077a7 Mon Sep 17 00:00:00 2001 From: waynewaynetsai Date: Sat, 16 Jul 2022 12:13:19 +0800 Subject: [PATCH 11/69] docs: fix duplicated names example --- Configurations.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Configurations.md b/Configurations.md index 17eabd48759e3..eaff09431acea 100644 --- a/Configurations.md +++ b/Configurations.md @@ -589,7 +589,7 @@ doesn't get ignored when aligning. #### `0` (default): ```rust -enum Bar { +enum Foo { A = 0, Bb = 1, RandomLongVariantGoesHere = 10, From 85fdf8ecec5551e79dc5ac3a8babaf514a58ef86 Mon Sep 17 00:00:00 2001 From: Urgau Date: Sun, 17 Jul 2022 14:18:57 +0200 Subject: [PATCH 12/69] Remove useless conditional compilation - 2 --- src/test/mod.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/test/mod.rs b/src/test/mod.rs index 6b5bc2b30dd5a..cfad4a8ed0e3e 100644 --- a/src/test/mod.rs +++ b/src/test/mod.rs @@ -982,11 +982,7 @@ fn rustfmt() -> PathBuf { assert!( me.is_file() || me.with_extension("exe").is_file(), "{}", - if cfg!(release) { - "no rustfmt bin, try running `cargo build --release` before testing" - } else { - "no rustfmt bin, try running `cargo build` before testing" - } + "no rustfmt bin, try running `cargo build` or `cargo build --release` before testing" ); me } From a7bf0090347d8523dd62c0508a4c8413cdba099a Mon Sep 17 00:00:00 2001 From: Jorge Martin Juarez <50276574+jmj0502@users.noreply.github.com> Date: Sun, 17 Jul 2022 21:39:25 -0400 Subject: [PATCH 13/69] Fix/comments inside trait generics gets duplicated (#5446) * Bugfix: Now slash/start comments aren't duplicated on trait parameters. * Removing unnecesary comment. * Improvements: Improving the BytePos offset. * Improvements: Improving the description of the test cases. --- src/items.rs | 6 +++++- tests/target/issue-5358.rs | 4 ++++ 2 files changed, 9 insertions(+), 1 deletion(-) create mode 100644 tests/target/issue-5358.rs diff --git a/src/items.rs b/src/items.rs index 6ab02e7f9239b..a76e88b77d484 100644 --- a/src/items.rs +++ b/src/items.rs @@ -1084,7 +1084,11 @@ pub(crate) fn format_trait( let item_snippet = context.snippet(item.span); if let Some(lo) = item_snippet.find('/') { // 1 = `{` - let comment_hi = body_lo - BytePos(1); + let comment_hi = if generics.params.len() > 0 { + generics.span.lo() - BytePos(1) + } else { + body_lo - BytePos(1) + }; let comment_lo = item.span.lo() + BytePos(lo as u32); if comment_lo < comment_hi { match recover_missing_comment_in_span( diff --git a/tests/target/issue-5358.rs b/tests/target/issue-5358.rs new file mode 100644 index 0000000000000..d4bf4909ad76f --- /dev/null +++ b/tests/target/issue-5358.rs @@ -0,0 +1,4 @@ +// Test /* comment */ inside trait generics does not get duplicated. +trait Test {} + +trait TestTwo {} From 05332b8c50c79c86b4715b764e4967016845273f Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Tue, 19 Jul 2022 11:48:49 -0400 Subject: [PATCH 14/69] Add test for issue 3033 Closes 3033 The issue is no longer reproducible. --- tests/target/issue_3033.rs | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 tests/target/issue_3033.rs diff --git a/tests/target/issue_3033.rs b/tests/target/issue_3033.rs new file mode 100644 index 0000000000000..e12249a6da6f3 --- /dev/null +++ b/tests/target/issue_3033.rs @@ -0,0 +1,2 @@ +use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServerBinding:: + BluetoothRemoteGATTServerMethods; From f2c31ba04db6bf07c140c86bfbe2cb16f1b83a8e Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Tue, 19 Jul 2022 00:37:32 -0400 Subject: [PATCH 15/69] Add tests for issue 2534 Closes 2534 The behavior described in the original issue can no longer be reproduced. The tests show that to be the case regardless of if `format_macro_matchers` is `true` or `false`. --- tests/target/issue-2534/format_macro_matchers_false.rs | 6 ++++++ tests/target/issue-2534/format_macro_matchers_true.rs | 6 ++++++ 2 files changed, 12 insertions(+) create mode 100644 tests/target/issue-2534/format_macro_matchers_false.rs create mode 100644 tests/target/issue-2534/format_macro_matchers_true.rs diff --git a/tests/target/issue-2534/format_macro_matchers_false.rs b/tests/target/issue-2534/format_macro_matchers_false.rs new file mode 100644 index 0000000000000..2038ed7f1d014 --- /dev/null +++ b/tests/target/issue-2534/format_macro_matchers_false.rs @@ -0,0 +1,6 @@ +// rustfmt-format_macro_matchers: false + +macro_rules! foo { + ($a:ident : $b:ty) => {}; + ($a:ident $b:ident $c:ident) => {}; +} diff --git a/tests/target/issue-2534/format_macro_matchers_true.rs b/tests/target/issue-2534/format_macro_matchers_true.rs new file mode 100644 index 0000000000000..01d939add4dc2 --- /dev/null +++ b/tests/target/issue-2534/format_macro_matchers_true.rs @@ -0,0 +1,6 @@ +// rustfmt-format_macro_matchers: true + +macro_rules! foo { + ($a:ident : $b:ty) => {}; + ($a:ident $b:ident $c:ident) => {}; +} From 4c78c738ba45c4ac4bab3bb74009712e00d307c7 Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Tue, 19 Jul 2022 18:47:03 -0400 Subject: [PATCH 16/69] Add tests for 3245 and 3561 Closes 3245 Closes 3561 These issues were originally linked in issue 3672 and as was mentioned in PR 3706, it's unclear which commit resolved the issue but the issue can no longer be reproduced. --- tests/source/issue_3245.rs | 4 ++++ tests/source/issue_3561.rs | 6 ++++++ tests/target/issue_3245.rs | 4 ++++ tests/target/issue_3561.rs | 7 +++++++ 4 files changed, 21 insertions(+) create mode 100644 tests/source/issue_3245.rs create mode 100644 tests/source/issue_3561.rs create mode 100644 tests/target/issue_3245.rs create mode 100644 tests/target/issue_3561.rs diff --git a/tests/source/issue_3245.rs b/tests/source/issue_3245.rs new file mode 100644 index 0000000000000..0279246ed6ac4 --- /dev/null +++ b/tests/source/issue_3245.rs @@ -0,0 +1,4 @@ +fn main() { + let x = 1; + ;let y = 3; +} diff --git a/tests/source/issue_3561.rs b/tests/source/issue_3561.rs new file mode 100644 index 0000000000000..8f6cd8f9fbce5 --- /dev/null +++ b/tests/source/issue_3561.rs @@ -0,0 +1,6 @@ +fn main() {;7 +} + +fn main() { + ;7 +} diff --git a/tests/target/issue_3245.rs b/tests/target/issue_3245.rs new file mode 100644 index 0000000000000..8f442f1181a59 --- /dev/null +++ b/tests/target/issue_3245.rs @@ -0,0 +1,4 @@ +fn main() { + let x = 1; + let y = 3; +} diff --git a/tests/target/issue_3561.rs b/tests/target/issue_3561.rs new file mode 100644 index 0000000000000..846a14d86a5ff --- /dev/null +++ b/tests/target/issue_3561.rs @@ -0,0 +1,7 @@ +fn main() { + 7 +} + +fn main() { + 7 +} From c19b14539b79d44f5f433ac189d70e07fb152354 Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Wed, 20 Jul 2022 09:15:51 -0400 Subject: [PATCH 17/69] test for issue 3164 Closes 3164 Show that when `error_on_line_overflow=true` is set in the rustfmt.toml that an error message is written to stderr. --- tests/cargo-fmt/main.rs | 19 +++++++++++++++++++ tests/cargo-fmt/source/issue_3164/Cargo.toml | 8 ++++++++ tests/cargo-fmt/source/issue_3164/src/main.rs | 13 +++++++++++++ tests/rustfmt/main.rs | 15 +++++++++++++++ 4 files changed, 55 insertions(+) create mode 100644 tests/cargo-fmt/source/issue_3164/Cargo.toml create mode 100644 tests/cargo-fmt/source/issue_3164/src/main.rs diff --git a/tests/cargo-fmt/main.rs b/tests/cargo-fmt/main.rs index 5aa4388518b8a..701c36fadeafa 100644 --- a/tests/cargo-fmt/main.rs +++ b/tests/cargo-fmt/main.rs @@ -98,3 +98,22 @@ fn cargo_fmt_out_of_line_test_modules() { assert!(stdout.contains(&format!("Diff in {}", path.display()))) } } + +#[rustfmt_only_ci_test] +#[test] +fn cargo_fmt_emits_error_on_line_overflow_true() { + // See also https://github.com/rust-lang/rustfmt/issues/3164 + let args = [ + "--check", + "--manifest-path", + "tests/cargo-fmt/source/issue_3164/Cargo.toml", + "--", + "--config", + "error_on_line_overflow=true", + ]; + + let (_stdout, stderr) = cargo_fmt(&args); + assert!(stderr.contains( + "line formatted, but exceeded maximum width (maximum: 100 (see `max_width` option)" + )) +} diff --git a/tests/cargo-fmt/source/issue_3164/Cargo.toml b/tests/cargo-fmt/source/issue_3164/Cargo.toml new file mode 100644 index 0000000000000..580ef7e6e24fe --- /dev/null +++ b/tests/cargo-fmt/source/issue_3164/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "issue_3164" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/tests/cargo-fmt/source/issue_3164/src/main.rs b/tests/cargo-fmt/source/issue_3164/src/main.rs new file mode 100644 index 0000000000000..9330107ac8dc7 --- /dev/null +++ b/tests/cargo-fmt/source/issue_3164/src/main.rs @@ -0,0 +1,13 @@ +#[allow(unused_macros)] +macro_rules! foo { + ($id:ident) => { + macro_rules! bar { + ($id2:tt) => { + #[cfg(any(target_feature = $id2, target_feature = $id2, target_feature = $id2, target_feature = $id2, target_feature = $id2))] + fn $id() {} + }; + } + }; +} + +fn main() {} diff --git a/tests/rustfmt/main.rs b/tests/rustfmt/main.rs index 636e3053e0f8e..7ff301e80195a 100644 --- a/tests/rustfmt/main.rs +++ b/tests/rustfmt/main.rs @@ -159,3 +159,18 @@ fn mod_resolution_error_path_attribute_does_not_exist() { // The path attribute points to a file that does not exist assert!(stderr.contains("does_not_exist.rs does not exist")); } + +#[test] +fn rustfmt_emits_error_on_line_overflow_true() { + // See also https://github.com/rust-lang/rustfmt/issues/3164 + let args = [ + "--config", + "error_on_line_overflow=true", + "tests/cargo-fmt/source/issue_3164/src/main.rs", + ]; + + let (_stdout, stderr) = rustfmt(&args); + assert!(stderr.contains( + "line formatted, but exceeded maximum width (maximum: 100 (see `max_width` option)" + )) +} From a451a39dec2bd5d7f0822eaa092e1423b42ea1d3 Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Wed, 20 Jul 2022 13:59:57 -0400 Subject: [PATCH 18/69] Add test for issue 4350 Closes 4350 Its unclear which commit resolved this, but the original issue is no longer reproducible. --- tests/target/issue_4350.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 tests/target/issue_4350.rs diff --git a/tests/target/issue_4350.rs b/tests/target/issue_4350.rs new file mode 100644 index 0000000000000..a94c5c32188d2 --- /dev/null +++ b/tests/target/issue_4350.rs @@ -0,0 +1,13 @@ +//rustfmt-format_macro_bodies: true + +macro_rules! mto_text_left { + ($buf:ident, $n:ident, $pos:ident, $state:ident) => {{ + let cursor = loop { + state = match iter.next() { + None if $pos == DP::Start => break last_char_idx($buf), + None /*some comment */ => break 0, + }; + }; + Ok(saturate_cursor($buf, cursor)) + }}; +} From ed77962d243f93e1690ac62f0b8d733383090240 Mon Sep 17 00:00:00 2001 From: Martin Juarez Date: Tue, 26 Jul 2022 12:21:22 -0400 Subject: [PATCH 19/69] Improvements: Adding tests for the issue-4643. --- tests/source/issue-4643.rs | 23 +++++++++++++++++++++++ tests/target/issue-4643.rs | 19 +++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 tests/source/issue-4643.rs create mode 100644 tests/target/issue-4643.rs diff --git a/tests/source/issue-4643.rs b/tests/source/issue-4643.rs new file mode 100644 index 0000000000000..382072d9004bf --- /dev/null +++ b/tests/source/issue-4643.rs @@ -0,0 +1,23 @@ +// output doesn't get corrupted when using comments within generic type parameters of a trait + +pub trait Something< + A, + // some comment + B, + C +> { + fn a(&self, x: A) -> i32; + fn b(&self, x: B) -> i32; + fn c(&self, x: C) -> i32; +} + +pub trait SomethingElse< + A, + /* some comment */ + B, + C +> { + fn a(&self, x: A) -> i32; + fn b(&self, x: B) -> i32; + fn c(&self, x: C) -> i32; +} diff --git a/tests/target/issue-4643.rs b/tests/target/issue-4643.rs new file mode 100644 index 0000000000000..ef99e4db382cb --- /dev/null +++ b/tests/target/issue-4643.rs @@ -0,0 +1,19 @@ +// output doesn't get corrupted when using comments within generic type parameters of a trait + +pub trait Something< + A, + // some comment + B, + C, +> +{ + fn a(&self, x: A) -> i32; + fn b(&self, x: B) -> i32; + fn c(&self, x: C) -> i32; +} + +pub trait SomethingElse { + fn a(&self, x: A) -> i32; + fn b(&self, x: B) -> i32; + fn c(&self, x: C) -> i32; +} From 7432422008f8be71df989e357d949072c77e9060 Mon Sep 17 00:00:00 2001 From: aizpurua23a <57321880+aizpurua23a@users.noreply.github.com> Date: Wed, 27 Jul 2022 18:59:29 +0200 Subject: [PATCH 20/69] Update Configurations.md to point to dirs 4.0 docs --- Configurations.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Configurations.md b/Configurations.md index eaff09431acea..e066553dc63f3 100644 --- a/Configurations.md +++ b/Configurations.md @@ -1,6 +1,6 @@ # Configuring Rustfmt -Rustfmt is designed to be very configurable. You can create a TOML file called `rustfmt.toml` or `.rustfmt.toml`, place it in the project or any other parent directory and it will apply the options in that file. If none of these directories contain such a file, both your home directory and a directory called `rustfmt` in your [global config directory](https://docs.rs/dirs/1.0.4/dirs/fn.config_dir.html) (e.g. `.config/rustfmt/`) are checked as well. +Rustfmt is designed to be very configurable. You can create a TOML file called `rustfmt.toml` or `.rustfmt.toml`, place it in the project or any other parent directory and it will apply the options in that file. If none of these directories contain such a file, both your home directory and a directory called `rustfmt` in your [global config directory](https://docs.rs/dirs/4.0.0/dirs/fn.config_dir.html) (e.g. `.config/rustfmt/`) are checked as well. A possible content of `rustfmt.toml` or `.rustfmt.toml` might look like this: From a7801aac272ce50da191af86bab988284de534be Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Mon, 25 Jul 2022 21:38:09 -0400 Subject: [PATCH 21/69] Add test for issue 3987 Closes 3987 It's unclear which commit resolved this issue, but it can no longer be reproduced. --- .../issue-3987/format_macro_bodies_true.rs | 26 +++++++++++++++++++ .../issue-3987/format_macro_bodies_false.rs | 26 +++++++++++++++++++ .../issue-3987/format_macro_bodies_true.rs | 21 +++++++++++++++ 3 files changed, 73 insertions(+) create mode 100644 tests/source/issue-3987/format_macro_bodies_true.rs create mode 100644 tests/target/issue-3987/format_macro_bodies_false.rs create mode 100644 tests/target/issue-3987/format_macro_bodies_true.rs diff --git a/tests/source/issue-3987/format_macro_bodies_true.rs b/tests/source/issue-3987/format_macro_bodies_true.rs new file mode 100644 index 0000000000000..9af114fbe574d --- /dev/null +++ b/tests/source/issue-3987/format_macro_bodies_true.rs @@ -0,0 +1,26 @@ +// rustfmt-format_macro_bodies: true + +// with comments +macro_rules! macros { + () => {{ + Struct { + field: ( + 42 + //comment 1 + 42 + //comment 2 + ), + }; + }}; +} + +// without comments +macro_rules! macros { + () => {{ + Struct { + field: ( + 42 + + 42 + ), + }; + }}; +} diff --git a/tests/target/issue-3987/format_macro_bodies_false.rs b/tests/target/issue-3987/format_macro_bodies_false.rs new file mode 100644 index 0000000000000..1352b762e4509 --- /dev/null +++ b/tests/target/issue-3987/format_macro_bodies_false.rs @@ -0,0 +1,26 @@ +// rustfmt-format_macro_bodies: false + +// with comments +macro_rules! macros { + () => {{ + Struct { + field: ( + 42 + //comment 1 + 42 + //comment 2 + ), + }; + }}; +} + +// without comments +macro_rules! macros { + () => {{ + Struct { + field: ( + 42 + + 42 + ), + }; + }}; +} diff --git a/tests/target/issue-3987/format_macro_bodies_true.rs b/tests/target/issue-3987/format_macro_bodies_true.rs new file mode 100644 index 0000000000000..88d57159c859f --- /dev/null +++ b/tests/target/issue-3987/format_macro_bodies_true.rs @@ -0,0 +1,21 @@ +// rustfmt-format_macro_bodies: true + +// with comments +macro_rules! macros { + () => {{ + Struct { + field: ( + 42 + //comment 1 + 42 + //comment 2 + ), + }; + }}; +} + +// without comments +macro_rules! macros { + () => {{ + Struct { field: (42 + 42) }; + }}; +} From af72f7a17f01a2d61490556e32c91c2d98416c9b Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Thu, 28 Jul 2022 10:31:04 +1000 Subject: [PATCH 22/69] Remove `TreeAndSpacing`. A `TokenStream` contains a `Lrc>`. But this is not quite right. `Spacing` makes sense for `TokenTree::Token`, but does not make sense for `TokenTree::Delimited`, because a `TokenTree::Delimited` cannot be joined with another `TokenTree`. This commit fixes this problem, by adding `Spacing` to `TokenTree::Token`, changing `TokenStream` to contain a `Lrc>`, and removing the `TreeAndSpacing` typedef. The commit removes these two impls: - `impl From for TokenStream` - `impl From for TreeAndSpacing` These were useful, but also resulted in code with many `.into()` calls that was hard to read, particularly for anyone not highly familiar with the relevant types. This commit makes some other changes to compensate: - `TokenTree::token()` becomes `TokenTree::token_{alone,joint}()`. - `TokenStream::token_{alone,joint}()` are added. - `TokenStream::delimited` is added. This results in things like this: ```rust TokenTree::token(token::Semi, stmt.span).into() ``` changing to this: ```rust TokenStream::token_alone(token::Semi, stmt.span) ``` This makes the type of the result, and its spacing, clearer. These changes also simplifies `Cursor` and `CursorRef`, because they no longer need to distinguish between `next` and `next_with_spacing`. --- src/macros.rs | 98 ++++++++++++++++++++++++++++++++------------------- 1 file changed, 61 insertions(+), 37 deletions(-) diff --git a/src/macros.rs b/src/macros.rs index f4b2bcf281577..3a641fab5d647 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -13,7 +13,7 @@ use std::collections::HashMap; use std::panic::{catch_unwind, AssertUnwindSafe}; use rustc_ast::token::{BinOpToken, Delimiter, Token, TokenKind}; -use rustc_ast::tokenstream::{Cursor, Spacing, TokenStream, TokenTree}; +use rustc_ast::tokenstream::{Cursor, TokenStream, TokenTree}; use rustc_ast::{ast, ptr}; use rustc_ast_pretty::pprust; use rustc_span::{ @@ -682,7 +682,7 @@ struct MacroArgParser { fn last_tok(tt: &TokenTree) -> Token { match *tt { - TokenTree::Token(ref t) => t.clone(), + TokenTree::Token(ref t, _) => t.clone(), TokenTree::Delimited(delim_span, delim, _) => Token { kind: TokenKind::CloseDelim(delim), span: delim_span.close, @@ -737,10 +737,13 @@ impl MacroArgParser { fn add_meta_variable(&mut self, iter: &mut Cursor) -> Option<()> { match iter.next() { - Some(TokenTree::Token(Token { - kind: TokenKind::Ident(name, _), - .. - })) => { + Some(TokenTree::Token( + Token { + kind: TokenKind::Ident(name, _), + .. + }, + _, + )) => { self.result.push(ParsedMacroArg { kind: MacroArgKind::MetaVariable(name, self.buf.clone()), }); @@ -777,21 +780,30 @@ impl MacroArgParser { } match tok { - TokenTree::Token(Token { - kind: TokenKind::BinOp(BinOpToken::Plus), - .. - }) - | TokenTree::Token(Token { - kind: TokenKind::Question, - .. - }) - | TokenTree::Token(Token { - kind: TokenKind::BinOp(BinOpToken::Star), - .. - }) => { + TokenTree::Token( + Token { + kind: TokenKind::BinOp(BinOpToken::Plus), + .. + }, + _, + ) + | TokenTree::Token( + Token { + kind: TokenKind::Question, + .. + }, + _, + ) + | TokenTree::Token( + Token { + kind: TokenKind::BinOp(BinOpToken::Star), + .. + }, + _, + ) => { break; } - TokenTree::Token(ref t) => { + TokenTree::Token(ref t, _) => { buffer.push_str(&pprust::token_to_string(t)); } _ => return None, @@ -859,10 +871,13 @@ impl MacroArgParser { while let Some(tok) = iter.next() { match tok { - TokenTree::Token(Token { - kind: TokenKind::Dollar, - span, - }) => { + TokenTree::Token( + Token { + kind: TokenKind::Dollar, + span, + }, + _, + ) => { // We always want to add a separator before meta variables. if !self.buf.is_empty() { self.add_separator(); @@ -875,13 +890,16 @@ impl MacroArgParser { span, }; } - TokenTree::Token(Token { - kind: TokenKind::Colon, - .. - }) if self.is_meta_var => { + TokenTree::Token( + Token { + kind: TokenKind::Colon, + .. + }, + _, + ) if self.is_meta_var => { self.add_meta_variable(&mut iter)?; } - TokenTree::Token(ref t) => self.update_buffer(t), + TokenTree::Token(ref t, _) => self.update_buffer(t), TokenTree::Delimited(_delimited_span, delimited, ref tts) => { if !self.buf.is_empty() { if next_space(&self.last_tok.kind) == SpaceState::Always { @@ -1123,12 +1141,15 @@ impl MacroParser { TokenTree::Token(..) => return None, TokenTree::Delimited(delimited_span, d, _) => (delimited_span.open.lo(), d), }; - let args = TokenStream::new(vec![(tok, Spacing::Joint)]); + let args = TokenStream::new(vec![tok]); match self.toks.next()? { - TokenTree::Token(Token { - kind: TokenKind::FatArrow, - .. - }) => {} + TokenTree::Token( + Token { + kind: TokenKind::FatArrow, + .. + }, + _, + ) => {} _ => return None, } let (mut hi, body, whole_body) = match self.toks.next()? { @@ -1147,10 +1168,13 @@ impl MacroParser { ) } }; - if let Some(TokenTree::Token(Token { - kind: TokenKind::Semi, - span, - })) = self.toks.look_ahead(0) + if let Some(TokenTree::Token( + Token { + kind: TokenKind::Semi, + span, + }, + _, + )) = self.toks.look_ahead(0) { hi = span.hi(); self.toks.next(); From 7cc126180f8340071741586c9b455b88b920b116 Mon Sep 17 00:00:00 2001 From: Tom Milligan Date: Wed, 20 Jul 2022 07:46:49 +0100 Subject: [PATCH 23/69] feat: nicer skip context for macro/attribute --- src/attr.rs | 4 ++-- src/macros.rs | 3 ++- src/skip.rs | 59 +++++++++++++++++++++++++++++++++----------------- src/visitor.rs | 4 ++-- 4 files changed, 45 insertions(+), 25 deletions(-) diff --git a/src/attr.rs b/src/attr.rs index 41ba9a847e67a..b1efaa21f2746 100644 --- a/src/attr.rs +++ b/src/attr.rs @@ -337,7 +337,7 @@ impl Rewrite for ast::Attribute { } else { let should_skip = self .ident() - .map(|s| context.skip_context.skip_attribute(s.name.as_str())) + .map(|s| context.skip_context.attributes.skip(s.name.as_str())) .unwrap_or(false); let prefix = attr_prefix(self); @@ -391,7 +391,7 @@ impl Rewrite for [ast::Attribute] { // Determine if the source text is annotated with `#[rustfmt::skip::attributes(derive)]` // or `#![rustfmt::skip::attributes(derive)]` - let skip_derives = context.skip_context.skip_attribute("derive"); + let skip_derives = context.skip_context.attributes.skip("derive"); // This is not just a simple map because we need to handle doc comments // (where we take as many doc comment attributes as possible) and possibly diff --git a/src/macros.rs b/src/macros.rs index e78ef1f806678..1ef5a095bf981 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -157,7 +157,8 @@ pub(crate) fn rewrite_macro( ) -> Option { let should_skip = context .skip_context - .skip_macro(context.snippet(mac.path.span)); + .macros + .skip(context.snippet(mac.path.span)); if should_skip { None } else { diff --git a/src/skip.rs b/src/skip.rs index 8b2fd7736ae51..4ebbee542a265 100644 --- a/src/skip.rs +++ b/src/skip.rs @@ -2,41 +2,60 @@ use rustc_ast::ast; use rustc_ast_pretty::pprust; +use std::collections::HashSet; -/// Take care of skip name stack. You can update it by attributes slice or -/// by other context. Query this context to know if you need skip a block. +/// Track which blocks of code are to be skipped when formatting. +/// +/// You can update it by: +/// +/// - attributes slice +/// - manually feeding values into the underlying contexts +/// +/// Query this context to know if you need skip a block. #[derive(Default, Clone)] pub(crate) struct SkipContext { - pub(crate) all_macros: bool, - macros: Vec, - attributes: Vec, + pub(crate) macros: SkipNameContext, + pub(crate) attributes: SkipNameContext, } impl SkipContext { pub(crate) fn update_with_attrs(&mut self, attrs: &[ast::Attribute]) { - self.macros.append(&mut get_skip_names("macros", attrs)); - self.attributes - .append(&mut get_skip_names("attributes", attrs)); + self.macros.append(get_skip_names("macros", attrs)); + self.attributes.append(get_skip_names("attributes", attrs)); } - pub(crate) fn update(&mut self, mut other: SkipContext) { - self.macros.append(&mut other.macros); - self.attributes.append(&mut other.attributes); + pub(crate) fn update(&mut self, other: SkipContext) { + let SkipContext { macros, attributes } = other; + self.macros.update(macros); + self.attributes.update(attributes); + } +} + +/// Track which names to skip. +/// +/// Query this context with a string to know whether to skip it. +#[derive(Default, Clone)] +pub(crate) struct SkipNameContext { + all: bool, + values: HashSet, +} + +impl SkipNameContext { + pub(crate) fn append(&mut self, values: Vec) { + self.values.extend(values); } - pub(crate) fn update_macros(&mut self, other: T) - where - T: IntoIterator, - { - self.macros.extend(other.into_iter()); + pub(crate) fn update(&mut self, other: Self) { + self.all = self.all || other.all; + self.values.extend(other.values); } - pub(crate) fn skip_macro(&self, name: &str) -> bool { - self.all_macros || self.macros.iter().any(|n| n == name) + pub(crate) fn skip(&self, name: &str) -> bool { + self.all || self.values.contains(name) } - pub(crate) fn skip_attribute(&self, name: &str) -> bool { - self.attributes.iter().any(|n| n == name) + pub(crate) fn set_all(&mut self, all: bool) { + self.all = all; } } diff --git a/src/visitor.rs b/src/visitor.rs index b93153de154a8..4b3ee7f76e185 100644 --- a/src/visitor.rs +++ b/src/visitor.rs @@ -775,10 +775,10 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { for macro_selector in config.skip_macro_invocations().0 { match macro_selector { MacroSelector::Name(name) => macro_names.push(name.to_string()), - MacroSelector::All => skip_context.all_macros = true, + MacroSelector::All => skip_context.macros.set_all(true), } } - skip_context.update_macros(macro_names); + skip_context.macros.append(macro_names); FmtVisitor { parent_context: None, parse_sess: parse_session, From 3fa81c6dbf72a83e4612d9490cdceade5eb2d2ae Mon Sep 17 00:00:00 2001 From: Tom Milligan Date: Wed, 20 Jul 2022 22:24:50 +0100 Subject: [PATCH 24/69] [review] use extend trait, enum for skip context --- src/skip.rs | 54 ++++++++++++++++++++++++++++++++++++-------------- src/visitor.rs | 4 ++-- 2 files changed, 41 insertions(+), 17 deletions(-) diff --git a/src/skip.rs b/src/skip.rs index 4ebbee542a265..59d6d84c96430 100644 --- a/src/skip.rs +++ b/src/skip.rs @@ -11,7 +11,7 @@ use std::collections::HashSet; /// - attributes slice /// - manually feeding values into the underlying contexts /// -/// Query this context to know if you need skip a block. +/// Query this context to know if you need to skip a block. #[derive(Default, Clone)] pub(crate) struct SkipContext { pub(crate) macros: SkipNameContext, @@ -20,8 +20,8 @@ pub(crate) struct SkipContext { impl SkipContext { pub(crate) fn update_with_attrs(&mut self, attrs: &[ast::Attribute]) { - self.macros.append(get_skip_names("macros", attrs)); - self.attributes.append(get_skip_names("attributes", attrs)); + self.macros.extend(get_skip_names("macros", attrs)); + self.attributes.extend(get_skip_names("attributes", attrs)); } pub(crate) fn update(&mut self, other: SkipContext) { @@ -34,28 +34,52 @@ impl SkipContext { /// Track which names to skip. /// /// Query this context with a string to know whether to skip it. -#[derive(Default, Clone)] -pub(crate) struct SkipNameContext { - all: bool, - values: HashSet, +#[derive(Clone)] +pub(crate) enum SkipNameContext { + All, + Values(HashSet), } -impl SkipNameContext { - pub(crate) fn append(&mut self, values: Vec) { - self.values.extend(values); +impl Default for SkipNameContext { + fn default() -> Self { + Self::Values(Default::default()) + } +} + +impl Extend for SkipNameContext { + fn extend>(&mut self, iter: T) { + match self { + Self::All => {} + Self::Values(values) => values.extend(iter), + } } +} +impl SkipNameContext { pub(crate) fn update(&mut self, other: Self) { - self.all = self.all || other.all; - self.values.extend(other.values); + match (self, other) { + // If we're already skipping everything, nothing more can be added + (Self::All, _) => {} + // If we want to skip all, set it + (this, Self::All) => { + *this = Self::All; + } + // If we have some new values to skip, add them + (Self::Values(existing_values), Self::Values(new_values)) => { + existing_values.extend(new_values) + } + } } pub(crate) fn skip(&self, name: &str) -> bool { - self.all || self.values.contains(name) + match self { + Self::All => true, + Self::Values(values) => values.contains(name), + } } - pub(crate) fn set_all(&mut self, all: bool) { - self.all = all; + pub(crate) fn skip_all(&mut self) { + *self = Self::All; } } diff --git a/src/visitor.rs b/src/visitor.rs index 4b3ee7f76e185..c0fc37eaaa899 100644 --- a/src/visitor.rs +++ b/src/visitor.rs @@ -775,10 +775,10 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { for macro_selector in config.skip_macro_invocations().0 { match macro_selector { MacroSelector::Name(name) => macro_names.push(name.to_string()), - MacroSelector::All => skip_context.macros.set_all(true), + MacroSelector::All => skip_context.macros.skip_all(), } } - skip_context.macros.append(macro_names); + skip_context.macros.extend(macro_names); FmtVisitor { parent_context: None, parse_sess: parse_session, From 23ef4b7ac476714886582865b39d396d615a3901 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Sun, 31 Jul 2022 13:53:37 -0500 Subject: [PATCH 25/69] refactor(chains): encapsulate shared code, prep for overflows --- src/chains.rs | 99 +++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 77 insertions(+), 22 deletions(-) diff --git a/src/chains.rs b/src/chains.rs index 5bccb22db4c17..a2976bbe92a5e 100644 --- a/src/chains.rs +++ b/src/chains.rs @@ -74,6 +74,60 @@ use crate::utils::{ rewrite_ident, trimmed_last_line_width, wrap_str, }; +/// Provides the original input contents from the span +/// of a chain element with trailing spaces trimmed. +fn format_overflow_style(span: Span, context: &RewriteContext<'_>) -> Option { + context.snippet_provider.span_to_snippet(span).map(|s| { + s.lines() + .map(|l| l.trim_end()) + .collect::>() + .join("\n") + }) +} + +fn format_chain_item( + item: &ChainItem, + context: &RewriteContext<'_>, + rewrite_shape: Shape, + allow_overflow: bool, +) -> Option { + if allow_overflow { + item.rewrite(context, rewrite_shape) + .or_else(|| format_overflow_style(item.span, context)) + } else { + item.rewrite(context, rewrite_shape) + } +} + +fn get_block_child_shape( + prev_ends_with_block: bool, + context: &RewriteContext<'_>, + shape: Shape, +) -> Shape { + if prev_ends_with_block { + shape.block_indent(0) + } else { + shape.block_indent(context.config.tab_spaces()) + } + .with_max_width(context.config) +} + +fn get_visual_style_child_shape( + context: &RewriteContext<'_>, + shape: Shape, + offset: usize, + parent_overflowing: bool, +) -> Option { + if !parent_overflowing { + shape + .with_max_width(context.config) + .offset_left(offset) + .map(|s| s.visual_indent(0)) + } else { + Some(shape.visual_indent(offset)) + } +} + pub(crate) fn rewrite_chain( expr: &ast::Expr, context: &RewriteContext<'_>, @@ -498,6 +552,8 @@ struct ChainFormatterShared<'a> { // The number of children in the chain. This is not equal to `self.children.len()` // because `self.children` will change size as we process the chain. child_count: usize, + // Whether elements are allowed to overflow past the max_width limit + allow_overflow: bool, } impl<'a> ChainFormatterShared<'a> { @@ -507,6 +563,8 @@ impl<'a> ChainFormatterShared<'a> { rewrites: Vec::with_capacity(chain.children.len() + 1), fits_single_line: false, child_count: chain.children.len(), + // TODO(calebcartwright) + allow_overflow: false, } } @@ -519,6 +577,14 @@ impl<'a> ChainFormatterShared<'a> { } } + fn format_children(&mut self, context: &RewriteContext<'_>, child_shape: Shape) -> Option<()> { + for item in &self.children[..self.children.len() - 1] { + let rewrite = format_chain_item(item, context, child_shape, self.allow_overflow)?; + self.rewrites.push(rewrite); + } + Some(()) + } + // Rewrite the last child. The last child of a chain requires special treatment. We need to // know whether 'overflowing' the last child make a better formatting: // @@ -731,22 +797,12 @@ impl<'a> ChainFormatter for ChainFormatterBlock<'a> { } fn child_shape(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { - Some( - if self.root_ends_with_block { - shape.block_indent(0) - } else { - shape.block_indent(context.config.tab_spaces()) - } - .with_max_width(context.config), - ) + let block_end = self.root_ends_with_block; + Some(get_block_child_shape(block_end, context, shape)) } fn format_children(&mut self, context: &RewriteContext<'_>, child_shape: Shape) -> Option<()> { - for item in &self.shared.children[..self.shared.children.len() - 1] { - let rewrite = item.rewrite(context, child_shape)?; - self.shared.rewrites.push(rewrite); - } - Some(()) + self.shared.format_children(context, child_shape) } fn format_last_child( @@ -828,18 +884,17 @@ impl<'a> ChainFormatter for ChainFormatterVisual<'a> { } fn child_shape(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { - shape - .with_max_width(context.config) - .offset_left(self.offset) - .map(|s| s.visual_indent(0)) + get_visual_style_child_shape( + context, + shape, + self.offset, + // TODO(calebcartwright): self.shared.permissibly_overflowing_parent, + false, + ) } fn format_children(&mut self, context: &RewriteContext<'_>, child_shape: Shape) -> Option<()> { - for item in &self.shared.children[..self.shared.children.len() - 1] { - let rewrite = item.rewrite(context, child_shape)?; - self.shared.rewrites.push(rewrite); - } - Some(()) + self.shared.format_children(context, child_shape) } fn format_last_child( From 662702eb54b12f16729d6559ce0478b00ef153a8 Mon Sep 17 00:00:00 2001 From: alexey semenyuk Date: Sun, 7 Aug 2022 02:53:03 +0300 Subject: [PATCH 26/69] Fix typos (#5486) * Fix typos * Fix typos --- CHANGELOG.md | 2 +- Processes.md | 2 +- src/bin/main.rs | 2 +- src/config/mod.rs | 2 +- src/imports.rs | 4 ++-- tests/mod-resolver/issue-5198/lib/c/d/explanation.txt | 2 +- tests/mod-resolver/issue-5198/lib/explanation.txt | 2 +- tests/source/cfg_if/detect/arch/x86.rs | 2 +- tests/source/enum.rs | 2 +- tests/source/tuple.rs | 2 +- .../wrap_comments_should_not_imply_format_doc_comments.rs | 2 +- tests/target/cfg_if/detect/arch/x86.rs | 2 +- tests/target/enum.rs | 2 +- tests/target/tuple.rs | 2 +- .../wrap_comments_should_not_imply_format_doc_comments.rs | 2 +- 15 files changed, 16 insertions(+), 16 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0c1893bf8c387..e9ce930dabc68 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -840,7 +840,7 @@ from formatting an attribute #3665 - Fix formatting of raw string literals #2983 - Handle chain with try operators with spaces #2986 - Use correct shape in Visual tuple rewriting #2987 -- Impove formatting of arguments with `visual_style = "Visual"` option #2988 +- Improve formatting of arguments with `visual_style = "Visual"` option #2988 - Change `print_diff` to output the correct line number 992b179 - Propagate errors about failing to rewrite a macro 6f318e3 - Handle formatting of long function signature #3010 diff --git a/Processes.md b/Processes.md index 9d86d52b122d8..334414702b159 100644 --- a/Processes.md +++ b/Processes.md @@ -2,7 +2,7 @@ This document outlines processes regarding management of rustfmt. # Stabilising an Option -In this Section, we describe how to stabilise an option of the rustfmt's configration. +In this Section, we describe how to stabilise an option of the rustfmt's configuration. ## Conditions diff --git a/src/bin/main.rs b/src/bin/main.rs index 8e871e61f2683..be64559e87745 100644 --- a/src/bin/main.rs +++ b/src/bin/main.rs @@ -136,7 +136,7 @@ fn make_opts() -> Options { "l", "files-with-diff", "Prints the names of mismatched files that were formatted. Prints the names of \ - files that would be formated when used with `--check` mode. ", + files that would be formatted when used with `--check` mode. ", ); opts.optmulti( "", diff --git a/src/config/mod.rs b/src/config/mod.rs index 5492519f3894a..4ec7e924bf621 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -182,7 +182,7 @@ create_config! { make_backup: bool, false, false, "Backup changed files"; print_misformatted_file_names: bool, false, true, "Prints the names of mismatched files that were formatted. Prints the names of \ - files that would be formated when used with `--check` mode. "; + files that would be formatted when used with `--check` mode. "; } #[derive(Error, Debug)] diff --git a/src/imports.rs b/src/imports.rs index 8d41c881589e5..140d8953abc90 100644 --- a/src/imports.rs +++ b/src/imports.rs @@ -251,8 +251,8 @@ fn flatten_use_trees( use_trees: Vec, import_granularity: ImportGranularity, ) -> Vec { - // Return non-sorted single occurance of the use-trees text string; - // order is by first occurance of the use-tree. + // Return non-sorted single occurrence of the use-trees text string; + // order is by first occurrence of the use-tree. use_trees .into_iter() .flat_map(|tree| tree.flatten(import_granularity)) diff --git a/tests/mod-resolver/issue-5198/lib/c/d/explanation.txt b/tests/mod-resolver/issue-5198/lib/c/d/explanation.txt index 92c9e3021431f..254102ebabdc2 100644 --- a/tests/mod-resolver/issue-5198/lib/c/d/explanation.txt +++ b/tests/mod-resolver/issue-5198/lib/c/d/explanation.txt @@ -9,7 +9,7 @@ The directory name './lib/c/d/' conflicts with the './lib/c/d.rs' file name. * mod g; Module resolution will fail if we look for './lib/c/d/e.rs' or './lib/c/d/e/mod.rs', -so we should fall back to looking for './lib/c/e.rs', which correctly finds the modlue, that +so we should fall back to looking for './lib/c/e.rs', which correctly finds the module, that rustfmt should format. './lib/c/d/f.rs' and './lib/c/d/g/mod.rs' exist at the default submodule paths so we should be able diff --git a/tests/mod-resolver/issue-5198/lib/explanation.txt b/tests/mod-resolver/issue-5198/lib/explanation.txt index d436a8076cd71..90464def8ebcc 100644 --- a/tests/mod-resolver/issue-5198/lib/explanation.txt +++ b/tests/mod-resolver/issue-5198/lib/explanation.txt @@ -9,7 +9,7 @@ The directory name './lib' conflicts with the './lib.rs' file name. * mod c; Module resolution will fail if we look for './lib/a.rs' or './lib/a/mod.rs', -so we should fall back to looking for './a.rs', which correctly finds the modlue that +so we should fall back to looking for './a.rs', which correctly finds the module that rustfmt should format. './lib/b.rs' and './lib/c/mod.rs' exist at the default submodule paths so we should be able diff --git a/tests/source/cfg_if/detect/arch/x86.rs b/tests/source/cfg_if/detect/arch/x86.rs index d26f4ee894fad..131cbb855f163 100644 --- a/tests/source/cfg_if/detect/arch/x86.rs +++ b/tests/source/cfg_if/detect/arch/x86.rs @@ -329,7 +329,7 @@ pub enum Feature { tbm, /// POPCNT (Population Count) popcnt, - /// FXSR (Floating-point context fast save and restor) + /// FXSR (Floating-point context fast save and restore) fxsr, /// XSAVE (Save Processor Extended States) xsave, diff --git a/tests/source/enum.rs b/tests/source/enum.rs index 0ed9651abe722..a7b9616929cb0 100644 --- a/tests/source/enum.rs +++ b/tests/source/enum.rs @@ -36,7 +36,7 @@ enum StructLikeVariants { Normal(u32, String, ), StructLike { x: i32, // Test comment // Pre-comment - #[Attr50] y: SomeType, // Aanother Comment + #[Attr50] y: SomeType, // Another Comment }, SL { a: A } } diff --git a/tests/source/tuple.rs b/tests/source/tuple.rs index 9a0f979fbca38..5189a7454f3a7 100644 --- a/tests/source/tuple.rs +++ b/tests/source/tuple.rs @@ -1,4 +1,4 @@ -// Test tuple litterals +// Test tuple literals fn foo() { let a = (a, a, a, a, a); diff --git a/tests/source/wrap_comments_should_not_imply_format_doc_comments.rs b/tests/source/wrap_comments_should_not_imply_format_doc_comments.rs index 78b3ce146f289..56064e4a4cccf 100644 --- a/tests/source/wrap_comments_should_not_imply_format_doc_comments.rs +++ b/tests/source/wrap_comments_should_not_imply_format_doc_comments.rs @@ -11,6 +11,6 @@ /// fn foo() {} -/// A long commment for wrapping +/// A long comment for wrapping /// This is a long long long long long long long long long long long long long long long long long long long long sentence. fn bar() {} diff --git a/tests/target/cfg_if/detect/arch/x86.rs b/tests/target/cfg_if/detect/arch/x86.rs index 02d5eed1c2923..47210cae2aaa0 100644 --- a/tests/target/cfg_if/detect/arch/x86.rs +++ b/tests/target/cfg_if/detect/arch/x86.rs @@ -314,7 +314,7 @@ pub enum Feature { tbm, /// POPCNT (Population Count) popcnt, - /// FXSR (Floating-point context fast save and restor) + /// FXSR (Floating-point context fast save and restore) fxsr, /// XSAVE (Save Processor Extended States) xsave, diff --git a/tests/target/enum.rs b/tests/target/enum.rs index 9a25126b44ecb..70fc8ab376ccd 100644 --- a/tests/target/enum.rs +++ b/tests/target/enum.rs @@ -43,7 +43,7 @@ enum StructLikeVariants { x: i32, // Test comment // Pre-comment #[Attr50] - y: SomeType, // Aanother Comment + y: SomeType, // Another Comment }, SL { a: A, diff --git a/tests/target/tuple.rs b/tests/target/tuple.rs index 68bb2f3bc2850..24fcf8cfd7cf3 100644 --- a/tests/target/tuple.rs +++ b/tests/target/tuple.rs @@ -1,4 +1,4 @@ -// Test tuple litterals +// Test tuple literals fn foo() { let a = (a, a, a, a, a); diff --git a/tests/target/wrap_comments_should_not_imply_format_doc_comments.rs b/tests/target/wrap_comments_should_not_imply_format_doc_comments.rs index d61d4d7c216a3..6ccecc7e0bbe6 100644 --- a/tests/target/wrap_comments_should_not_imply_format_doc_comments.rs +++ b/tests/target/wrap_comments_should_not_imply_format_doc_comments.rs @@ -10,7 +10,7 @@ /// ``` fn foo() {} -/// A long commment for wrapping +/// A long comment for wrapping /// This is a long long long long long long long long long long long long long /// long long long long long long long sentence. fn bar() {} From 5a1ef3c7bc1f81f4a21da493f8e352d7316c7351 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Sat, 6 Aug 2022 19:48:55 -0500 Subject: [PATCH 27/69] chore: bump toolchain --- rust-toolchain | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust-toolchain b/rust-toolchain index 2640a9e0ecc28..f8ed76d2e6f9e 100644 --- a/rust-toolchain +++ b/rust-toolchain @@ -1,3 +1,3 @@ [toolchain] -channel = "nightly-2022-06-21" +channel = "nightly-2022-08-06" components = ["rustc-dev"] From 437de8d17fc39231cc8424069579855a94e8c245 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Sat, 6 Aug 2022 19:59:52 -0500 Subject: [PATCH 28/69] chore: disable unreachable pub lint on config items --- src/config/mod.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/config/mod.rs b/src/config/mod.rs index 4ec7e924bf621..1fc6d033541c6 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -20,9 +20,11 @@ pub use crate::config::options::*; #[macro_use] pub(crate) mod config_type; #[macro_use] +#[allow(unreachable_pub)] pub(crate) mod options; pub(crate) mod file_lines; +#[allow(unreachable_pub)] pub(crate) mod lists; pub(crate) mod macro_names; From c78ef92add17c545c387bee12428d3dd51d90003 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Sat, 6 Aug 2022 20:29:46 -0500 Subject: [PATCH 29/69] chore: fix another config unreachable-pub --- src/config/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/config/mod.rs b/src/config/mod.rs index 1fc6d033541c6..14f27f3f8b692 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -422,7 +422,7 @@ mod test { use rustfmt_config_proc_macro::config_type; #[config_type] - pub enum PartiallyUnstableOption { + pub(crate) enum PartiallyUnstableOption { V1, V2, #[unstable_variant] From a67d909627b7ec93e315bfe1c66895904055c75c Mon Sep 17 00:00:00 2001 From: alex-semenyuk Date: Mon, 8 Aug 2022 15:23:41 +0300 Subject: [PATCH 30/69] Fix some clippy issues --- src/cargo-fmt/main.rs | 12 +++++------- src/cargo-fmt/test/mod.rs | 4 ++-- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/src/cargo-fmt/main.rs b/src/cargo-fmt/main.rs index 9031d29b45f7f..2b714b68df00e 100644 --- a/src/cargo-fmt/main.rs +++ b/src/cargo-fmt/main.rs @@ -198,12 +198,10 @@ fn convert_message_format_to_rustfmt_args( Ok(()) } "human" => Ok(()), - _ => { - return Err(format!( - "invalid --message-format value: {}. Allowed values are: short|json|human", - message_format - )); - } + _ => Err(format!( + "invalid --message-format value: {}. Allowed values are: short|json|human", + message_format + )), } } @@ -215,7 +213,7 @@ fn print_usage_to_stderr(reason: &str) { .expect("failed to write to stderr"); } -#[derive(Debug, Clone, Copy, PartialEq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Verbosity { Verbose, Normal, diff --git a/src/cargo-fmt/test/mod.rs b/src/cargo-fmt/test/mod.rs index 56e52fbabb68b..696326e4f9406 100644 --- a/src/cargo-fmt/test/mod.rs +++ b/src/cargo-fmt/test/mod.rs @@ -70,9 +70,9 @@ fn mandatory_separator() { .is_err() ); assert!( - !Opts::command() + Opts::command() .try_get_matches_from(&["test", "--", "--emit"]) - .is_err() + .is_ok() ); } From ea017d7f84e218c4a8048d2ecd9d63bbda014209 Mon Sep 17 00:00:00 2001 From: David Bar-On <61089727+davidBar-On@users.noreply.github.com> Date: Tue, 9 Aug 2022 16:30:49 +0300 Subject: [PATCH 31/69] Backport PR #4730 (#5390) * Backport PR #4730 that fix issue #4689 * Test files for each Verion One and Two * Simplify per review comment - use defer and matches! * Changes per reviewer comments for reducing indentations --- src/types.rs | 43 +++++++++- tests/source/issue-4689/one.rs | 149 ++++++++++++++++++++++++++++++++ tests/source/issue-4689/two.rs | 149 ++++++++++++++++++++++++++++++++ tests/target/issue-4689/one.rs | 150 ++++++++++++++++++++++++++++++++ tests/target/issue-4689/two.rs | 152 +++++++++++++++++++++++++++++++++ 5 files changed, 639 insertions(+), 4 deletions(-) create mode 100644 tests/source/issue-4689/one.rs create mode 100644 tests/source/issue-4689/two.rs create mode 100644 tests/target/issue-4689/one.rs create mode 100644 tests/target/issue-4689/two.rs diff --git a/src/types.rs b/src/types.rs index 2627886db109d..25ad587ba856b 100644 --- a/src/types.rs +++ b/src/types.rs @@ -941,6 +941,28 @@ fn join_bounds_inner( ast::GenericBound::Trait(..) => last_line_extendable(s), }; + // Whether a GenericBound item is a PathSegment segment that includes internal array + // that contains more than one item + let is_item_with_multi_items_array = |item: &ast::GenericBound| match item { + ast::GenericBound::Trait(ref poly_trait_ref, ..) => { + let segments = &poly_trait_ref.trait_ref.path.segments; + if segments.len() > 1 { + true + } else { + if let Some(args_in) = &segments[0].args { + matches!( + args_in.deref(), + ast::GenericArgs::AngleBracketed(bracket_args) + if bracket_args.args.len() > 1 + ) + } else { + false + } + } + } + _ => false, + }; + let result = items.iter().enumerate().try_fold( (String::new(), None, false), |(strs, prev_trailing_span, prev_extendable), (i, item)| { @@ -1035,10 +1057,23 @@ fn join_bounds_inner( }, )?; - if !force_newline - && items.len() > 1 - && (result.0.contains('\n') || result.0.len() > shape.width) - { + // Whether retry the function with forced newline is needed: + // Only if result is not already multiline and did not exceed line width, + // and either there is more than one item; + // or the single item is of type `Trait`, + // and any of the internal arrays contains more than one item; + let retry_with_force_newline = + if force_newline || (!result.0.contains('\n') && result.0.len() <= shape.width) { + false + } else { + if items.len() > 1 { + true + } else { + is_item_with_multi_items_array(&items[0]) + } + }; + + if retry_with_force_newline { join_bounds_inner(context, shape, items, need_indent, true) } else { Some(result.0) diff --git a/tests/source/issue-4689/one.rs b/tests/source/issue-4689/one.rs new file mode 100644 index 0000000000000..d048eb10fb15c --- /dev/null +++ b/tests/source/issue-4689/one.rs @@ -0,0 +1,149 @@ +// rustfmt-version: One + +// Based on the issue description +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, +> + fmt::Write +{ +// +} +pub trait PrettyPrinter<'tcx>: +Printer< +'tcx, +Error = fmt::Error, +Path = Self, +Region = Self, +Type = Self, +DynExistential = Self, +Const = Self, +> + fmt::Write1 + fmt::Write2 +{ +// +} +pub trait PrettyPrinter<'tcx>: +fmt::Write + Printer< +'tcx, +Error = fmt::Error, +Path = Self, +Region = Self, +Type = Self, +DynExistential = Self, +Const = Self, +> +{ +// +} +pub trait PrettyPrinter<'tcx>: +fmt::Write + Printer1< +'tcx, +Error = fmt::Error, +Path = Self, +Region = Self, +Type = Self, +DynExistential = Self, +Const = Self, +> + Printer2< +'tcx, +Error = fmt::Error, +Path = Self, +Region = Self, +Type = Self, +DynExistential = Self, +Const = Self, +> +{ +// +} + +// Some test cases to ensure other cases formatting were not changed +fn f() -> Box< +FnMut() -> Thing< +WithType = LongItemName, +Error = LONGLONGLONGLONGLONGONGEvenLongerErrorNameLongerLonger, +>, +> { +} +fn f() -> Box< +FnMut() -> Thing< +WithType = LongItemName, +Error = LONGLONGLONGLONGLONGONGEvenLongerErrorNameLongerLonger, +> + fmt::Write1 ++ fmt::Write2, +> { +} + +fn foo(foo2: F) +where +F: Fn( +// this comment is deleted +) +{ +} +fn foo(foo2: F) +where +F: Fn( +// this comment is deleted +) + fmt::Write +{ +} + +fn elaborate_bounds(mut mk_cand: F) +where +F: for<> FnMut( +&mut ProbeContext<>, +ty::PolyTraitRefffffffffffffffffffffffffffffffff<>, +tyyyyyyyyyyyyyyyyyyyyy::AssociatedItem, +), +{ +} +fn elaborate_bounds(mut mk_cand: F) +where +F: for<> FnMut( +&mut ProbeContext<>, +ty::PolyTraitRefffffffffffffffffffffffffffffffff<>, +tyyyyyyyyyyyyyyyyyyyyy::AssociatedItem, +) + fmt::Write, +{ +} + +fn build_sorted_static_get_entry_names( +mut entries: entryyyyyyyy, +) -> ( +impl Fn( +AlphabeticalTraversal, +Seconddddddddddddddddddddddddddddddddddd +) -> Parammmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm ++ Sendddddddddddddddddddddddddddddddddddddddddddd +) { +} + +pub trait SomeTrait: +Cloneeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee ++ Eqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq +{ +} + +trait B = where +for<'b> &'b Self: Send ++ Cloneeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee ++ Copyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy; diff --git a/tests/source/issue-4689/two.rs b/tests/source/issue-4689/two.rs new file mode 100644 index 0000000000000..ea7feda825d46 --- /dev/null +++ b/tests/source/issue-4689/two.rs @@ -0,0 +1,149 @@ +// rustfmt-version: Two + +// Based on the issue description +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, +> + fmt::Write +{ +// +} +pub trait PrettyPrinter<'tcx>: +Printer< +'tcx, +Error = fmt::Error, +Path = Self, +Region = Self, +Type = Self, +DynExistential = Self, +Const = Self, +> + fmt::Write1 + fmt::Write2 +{ +// +} +pub trait PrettyPrinter<'tcx>: +fmt::Write + Printer< +'tcx, +Error = fmt::Error, +Path = Self, +Region = Self, +Type = Self, +DynExistential = Self, +Const = Self, +> +{ +// +} +pub trait PrettyPrinter<'tcx>: +fmt::Write + Printer1< +'tcx, +Error = fmt::Error, +Path = Self, +Region = Self, +Type = Self, +DynExistential = Self, +Const = Self, +> + Printer2< +'tcx, +Error = fmt::Error, +Path = Self, +Region = Self, +Type = Self, +DynExistential = Self, +Const = Self, +> +{ +// +} + +// Some test cases to ensure other cases formatting were not changed +fn f() -> Box< +FnMut() -> Thing< +WithType = LongItemName, +Error = LONGLONGLONGLONGLONGONGEvenLongerErrorNameLongerLonger, +>, +> { +} +fn f() -> Box< +FnMut() -> Thing< +WithType = LongItemName, +Error = LONGLONGLONGLONGLONGONGEvenLongerErrorNameLongerLonger, +> + fmt::Write1 ++ fmt::Write2, +> { +} + +fn foo(foo2: F) +where +F: Fn( +// this comment is deleted +) +{ +} +fn foo(foo2: F) +where +F: Fn( +// this comment is deleted +) + fmt::Write +{ +} + +fn elaborate_bounds(mut mk_cand: F) +where +F: for<> FnMut( +&mut ProbeContext<>, +ty::PolyTraitRefffffffffffffffffffffffffffffffff<>, +tyyyyyyyyyyyyyyyyyyyyy::AssociatedItem, +), +{ +} +fn elaborate_bounds(mut mk_cand: F) +where +F: for<> FnMut( +&mut ProbeContext<>, +ty::PolyTraitRefffffffffffffffffffffffffffffffff<>, +tyyyyyyyyyyyyyyyyyyyyy::AssociatedItem, +) + fmt::Write, +{ +} + +fn build_sorted_static_get_entry_names( +mut entries: entryyyyyyyy, +) -> ( +impl Fn( +AlphabeticalTraversal, +Seconddddddddddddddddddddddddddddddddddd +) -> Parammmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm ++ Sendddddddddddddddddddddddddddddddddddddddddddd +) { +} + +pub trait SomeTrait: +Cloneeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee ++ Eqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq +{ +} + +trait B = where +for<'b> &'b Self: Send ++ Cloneeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee ++ Copyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy; diff --git a/tests/target/issue-4689/one.rs b/tests/target/issue-4689/one.rs new file mode 100644 index 0000000000000..df1a507bc1da9 --- /dev/null +++ b/tests/target/issue-4689/one.rs @@ -0,0 +1,150 @@ +// rustfmt-version: One + +// Based on the issue description +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, + > + fmt::Write +{ + // +} +pub trait PrettyPrinter<'tcx>: + Printer< + 'tcx, + Error = fmt::Error, + Path = Self, + Region = Self, + Type = Self, + DynExistential = Self, + Const = Self, + > + fmt::Write1 + + fmt::Write2 +{ + // +} +pub trait PrettyPrinter<'tcx>: + fmt::Write + + Printer< + 'tcx, + Error = fmt::Error, + Path = Self, + Region = Self, + Type = Self, + DynExistential = Self, + Const = Self, + > +{ + // +} +pub trait PrettyPrinter<'tcx>: + fmt::Write + + Printer1< + 'tcx, + Error = fmt::Error, + Path = Self, + Region = Self, + Type = Self, + DynExistential = Self, + Const = Self, + > + Printer2< + 'tcx, + Error = fmt::Error, + Path = Self, + Region = Self, + Type = Self, + DynExistential = Self, + Const = Self, + > +{ + // +} + +// Some test cases to ensure other cases formatting were not changed +fn f() -> Box< + FnMut() -> Thing< + WithType = LongItemName, + Error = LONGLONGLONGLONGLONGONGEvenLongerErrorNameLongerLonger, + >, +> { +} +fn f() -> Box< + FnMut() -> Thing< + WithType = LongItemName, + Error = LONGLONGLONGLONGLONGONGEvenLongerErrorNameLongerLonger, + > + fmt::Write1 + + fmt::Write2, +> { +} + +fn foo(foo2: F) +where + F: Fn( + // this comment is deleted + ), +{ +} +fn foo(foo2: F) +where + F: Fn( + // this comment is deleted + ) + fmt::Write, +{ +} + +fn elaborate_bounds(mut mk_cand: F) +where + F: FnMut( + &mut ProbeContext, + ty::PolyTraitRefffffffffffffffffffffffffffffffff, + tyyyyyyyyyyyyyyyyyyyyy::AssociatedItem, + ), +{ +} +fn elaborate_bounds(mut mk_cand: F) +where + F: FnMut( + &mut ProbeContext, + ty::PolyTraitRefffffffffffffffffffffffffffffffff, + tyyyyyyyyyyyyyyyyyyyyy::AssociatedItem, + ) + fmt::Write, +{ +} + +fn build_sorted_static_get_entry_names( + mut entries: entryyyyyyyy, +) -> (impl Fn( + AlphabeticalTraversal, + Seconddddddddddddddddddddddddddddddddddd, +) -> Parammmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm + + Sendddddddddddddddddddddddddddddddddddddddddddd) { +} + +pub trait SomeTrait: + Cloneeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee + + Eqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq +{ +} + +trait B = where + for<'b> &'b Self: Send + + Cloneeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee + + Copyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy; diff --git a/tests/target/issue-4689/two.rs b/tests/target/issue-4689/two.rs new file mode 100644 index 0000000000000..e3b5cd22810ba --- /dev/null +++ b/tests/target/issue-4689/two.rs @@ -0,0 +1,152 @@ +// rustfmt-version: Two + +// Based on the issue description +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, + > + fmt::Write +{ + // +} +pub trait PrettyPrinter<'tcx>: + Printer< + 'tcx, + Error = fmt::Error, + Path = Self, + Region = Self, + Type = Self, + DynExistential = Self, + Const = Self, + > + fmt::Write1 + + fmt::Write2 +{ + // +} +pub trait PrettyPrinter<'tcx>: + fmt::Write + + Printer< + 'tcx, + Error = fmt::Error, + Path = Self, + Region = Self, + Type = Self, + DynExistential = Self, + Const = Self, + > +{ + // +} +pub trait PrettyPrinter<'tcx>: + fmt::Write + + Printer1< + 'tcx, + Error = fmt::Error, + Path = Self, + Region = Self, + Type = Self, + DynExistential = Self, + Const = Self, + > + Printer2< + 'tcx, + Error = fmt::Error, + Path = Self, + Region = Self, + Type = Self, + DynExistential = Self, + Const = Self, + > +{ + // +} + +// Some test cases to ensure other cases formatting were not changed +fn f() -> Box< + FnMut() -> Thing< + WithType = LongItemName, + Error = LONGLONGLONGLONGLONGONGEvenLongerErrorNameLongerLonger, + >, +> { +} +fn f() -> Box< + FnMut() -> Thing< + WithType = LongItemName, + Error = LONGLONGLONGLONGLONGONGEvenLongerErrorNameLongerLonger, + > + fmt::Write1 + + fmt::Write2, +> { +} + +fn foo(foo2: F) +where + F: Fn( + // this comment is deleted + ), +{ +} +fn foo(foo2: F) +where + F: Fn( + // this comment is deleted + ) + fmt::Write, +{ +} + +fn elaborate_bounds(mut mk_cand: F) +where + F: FnMut( + &mut ProbeContext, + ty::PolyTraitRefffffffffffffffffffffffffffffffff, + tyyyyyyyyyyyyyyyyyyyyy::AssociatedItem, + ), +{ +} +fn elaborate_bounds(mut mk_cand: F) +where + F: FnMut( + &mut ProbeContext, + ty::PolyTraitRefffffffffffffffffffffffffffffffff, + tyyyyyyyyyyyyyyyyyyyyy::AssociatedItem, + ) + fmt::Write, +{ +} + +fn build_sorted_static_get_entry_names( + mut entries: entryyyyyyyy, +) -> ( + impl Fn( + AlphabeticalTraversal, + Seconddddddddddddddddddddddddddddddddddd, + ) -> Parammmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm + + Sendddddddddddddddddddddddddddddddddddddddddddd +) { +} + +pub trait SomeTrait: + Cloneeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee + + Eqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq +{ +} + +trait B = where + for<'b> &'b Self: Send + + Cloneeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee + + Copyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy; From 76be14b5cadd56e18af721c830c5592621b19cb7 Mon Sep 17 00:00:00 2001 From: Camille GILLOT Date: Sun, 7 Aug 2022 15:21:11 +0200 Subject: [PATCH 32/69] Do not consider method call receiver as an argument in AST. --- src/chains.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/chains.rs b/src/chains.rs index e26e24ec55ad6..fcc02eca42987 100644 --- a/src/chains.rs +++ b/src/chains.rs @@ -145,7 +145,7 @@ impl ChainItemKind { fn from_ast(context: &RewriteContext<'_>, expr: &ast::Expr) -> (ChainItemKind, Span) { let (kind, span) = match expr.kind { - ast::ExprKind::MethodCall(ref segment, ref expressions, _) => { + ast::ExprKind::MethodCall(ref segment, ref receiver, ref expressions, _) => { let types = if let Some(ref generic_args) = segment.args { if let ast::GenericArgs::AngleBracketed(ref data) = **generic_args { data.args @@ -163,7 +163,7 @@ impl ChainItemKind { } else { vec![] }; - let span = mk_sp(expressions[0].span.hi(), expr.span.hi()); + let span = mk_sp(receiver.span.hi(), expr.span.hi()); let kind = ChainItemKind::MethodCall(segment.clone(), types, expressions.clone()); (kind, span) } @@ -253,7 +253,7 @@ impl ChainItem { format!("::<{}>", type_list.join(", ")) }; let callee_str = format!(".{}{}", rewrite_ident(context, method_name), type_str); - rewrite_call(context, &callee_str, &args[1..], span, shape) + rewrite_call(context, &callee_str, &args, span, shape) } } @@ -400,8 +400,8 @@ impl Chain { // is a try! macro, we'll convert it to shorthand when the option is set. fn pop_expr_chain(expr: &ast::Expr, context: &RewriteContext<'_>) -> Option { match expr.kind { - ast::ExprKind::MethodCall(_, ref expressions, _) => { - Some(Self::convert_try(&expressions[0], context)) + ast::ExprKind::MethodCall(_, ref receiver, _, _) => { + Some(Self::convert_try(&receiver, context)) } ast::ExprKind::Field(ref subexpr, _) | ast::ExprKind::Try(ref subexpr) From 949da529d7a0b348376f67e77676a8722ad21899 Mon Sep 17 00:00:00 2001 From: Yacin Tmimi Date: Mon, 1 Aug 2022 00:29:32 -0400 Subject: [PATCH 33/69] Add GitHub Action to test master rustfmt formatting vs a feature branch This new action is intended to help us maintainers determine when feature branches cause breaking formatting changes by running rustfmt (master) and the feature branch on various rust repositories. Over time I expect the list of checked projects to increase. With this action in place we can more easily test that a new feature or bug fix doesn't introduce breaking changes. Although this action needs to be manually triggered right now, we might consider adding it to our CI runs in the future. --- .github/workflows/check_diff.yml | 33 +++++ ci/check_diff.sh | 199 +++++++++++++++++++++++++++++++ 2 files changed, 232 insertions(+) create mode 100644 .github/workflows/check_diff.yml create mode 100755 ci/check_diff.sh diff --git a/.github/workflows/check_diff.yml b/.github/workflows/check_diff.yml new file mode 100644 index 0000000000000..8bfb5834519cd --- /dev/null +++ b/.github/workflows/check_diff.yml @@ -0,0 +1,33 @@ +name: Diff Check +on: + workflow_dispatch: + inputs: + clone_url: + description: 'Git url of a rustfmt fork to compare against the latest master rustfmt' + required: true + branch_name: + description: 'Name of the feature branch on the forked repo' + required: true + commit_hash: + description: 'Optional commit hash from the feature branch' + required: false + rustfmt_configs: + description: 'Optional comma separated list of rustfmt config options to pass when running the feature branch' + required: false + +jobs: + diff_check: + runs-on: ubuntu-latest + + steps: + - name: checkout + uses: actions/checkout@v3 + + - name: install rustup + run: | + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs > rustup-init.sh + sh rustup-init.sh -y --default-toolchain none + rustup target add x86_64-unknown-linux-gnu + + - name: check diff + run: bash ${GITHUB_WORKSPACE}/ci/check_diff.sh ${{ github.event.inputs.clone_url }} ${{ github.event.inputs.branch_name }} ${{ github.event.inputs.commit_hash }} ${{ github.event.inputs.rustfmt_configs }} diff --git a/ci/check_diff.sh b/ci/check_diff.sh new file mode 100755 index 0000000000000..062c2dd8673ab --- /dev/null +++ b/ci/check_diff.sh @@ -0,0 +1,199 @@ +#!/bin/bash + +function print_usage() { + echo "usage check_diff REMOTE_REPO FEATURE_BRANCH [COMMIT_HASH] [OPTIONAL_RUSTFMT_CONFIGS]" +} + +if [ $# -le 1 ]; then + print_usage + exit 1 +fi + +REMOTE_REPO=$1 +FEATURE_BRANCH=$2 +OPTIONAL_COMMIT_HASH=$3 +OPTIONAL_RUSTFMT_CONFIGS=$4 + +# OUTPUT array used to collect all the status of running diffs on various repos +STATUSES=() + +# Clone a git repository and cd into it. +# +# Parameters: +# $1: git clone url +# $2: directory where the repo should be cloned +function clone_repo() { + GIT_TERMINAL_PROMPT=0 git clone --quiet $1 --depth 1 $2 && cd $2 +} + +# Initialize Git submoduels for the repo. +# +# Parameters +# $1: list of directories to initialize +function init_submodules() { + git submodule update --init $1 +} + +# Run rusfmt with the --check flag to see if a diff is produced. +# +# Parameters: +# $1: Path to a rustfmt binary +# $2: Output file path for the diff +# $3: Any additional configuration options to pass to rustfmt +# +# Globlas: +# $OPTIONAL_RUSTFMT_CONFIGS: Optional configs passed to the script from $4 +function create_diff() { + local config; + if [ -z "$3" ]; then + config="--config=error_on_line_overflow=false,error_on_unformatted=false" + else + config="--config=error_on_line_overflow=false,error_on_unformatted=false,$OPTIONAL_RUSTFMT_CONFIGS" + fi + + for i in `find . | grep "\.rs$"` + do + $1 --unstable-features --skip-children --check --color=always $config $i >> $2 2>/dev/null + done +} + +# Run the master rustfmt binary and the feature branch binary in the current directory and compare the diffs +# +# Parameters +# $1: Name of the repository (used for logging) +# +# Globlas: +# $RUSFMT_BIN: Path to the rustfmt master binary. Created when running `compile_rustfmt` +# $FEATURE_BIN: Path to the rustfmt feature binary. Created when running `compile_rustfmt` +# $OPTIONAL_RUSTFMT_CONFIGS: Optional configs passed to the script from $4 +function check_diff() { + echo "running rustfmt (master) on $1" + create_diff $RUSFMT_BIN rustfmt_diff.txt + + echo "running rustfmt (feature) on $1" + create_diff $FEATURE_BIN feature_diff.txt $OPTIONAL_RUSTFMT_CONFIGS + + echo "checking diff" + local diff; + # we don't add color to the diff since we added color when running rustfmt --check. + # tail -n + 6 removes the git diff header info + # cut -c 2- removes the leading diff characters("+","-"," ") from running git diff. + # Again, the diff output we care about was already added when we ran rustfmt --check + diff=$( + git --no-pager diff --color=never \ + --unified=0 --no-index rustfmt_diff.txt feature_diff.txt 2>&1 | tail -n +6 | cut -c 2- + ) + + if [ -z "$diff" ]; then + echo "no diff detected between rustfmt and the feture branch" + return 0 + else + echo "$diff" + return 1 + fi +} + +# Compiles and produces two rustfmt binaries. +# One for the current master, and another for the feature branch +# +# Parameters: +# $1: Directory where rustfmt will be cloned +# +# Globlas: +# $REMOTE_REPO: Clone URL to the rustfmt fork that we want to test +# $FEATURE_BRANCH: Name of the feature branch +# $OPTIONAL_COMMIT_HASH: Optional commit hash that will be checked out if provided +function compile_rustfmt() { + RUSTFMT_REPO="https://github.com/rust-lang/rustfmt.git" + clone_repo $RUSTFMT_REPO $1 + git remote add feature $REMOTE_REPO + git fetch feature $FEATURE_BRANCH + + cargo build --release --bin rustfmt && cp target/release/rustfmt $1/rustfmt + if [ -z "$OPTIONAL_COMMIT_HASH" ]; then + git switch $FEATURE_BRANCH + else + git switch $OPTIONAL_COMMIT_HASH --detach + fi + cargo build --release --bin rustfmt && cp target/release/rustfmt $1/feature_rustfmt + RUSFMT_BIN=$1/rustfmt + FEATURE_BIN=$1/feature_rustfmt +} + +# Check the diff for running rustfmt and the feature branch on all the .rs files in the repo. +# +# Parameters +# $1: Clone URL for the repo +# $2: Name of the repo (mostly used for logging) +# $3: Path to any submodules that should be initialized +function check_repo() { + WORKDIR=$(pwd) + REPO_URL=$1 + REPO_NAME=$2 + SUBMODULES=$3 + + local tmp_dir; + tmp_dir=$(mktemp -d -t $REPO_NAME-XXXXXXXX) + clone_repo $REPO_URL $tmp_dir + + if [ ! -z "$SUBMODULES" ]; then + init_submodules $SUBMODULES + fi + + check_diff $REPO_NAME + # append the status of running `check_diff` to the STATUSES array + STATUSES+=($?) + + echo "removing tmp_dir $tmp_dir" + rm -rf $tmp_dir + cd $WORKDIR +} + +function main() { + tmp_dir=$(mktemp -d -t rustfmt-XXXXXXXX) + echo Created tmp_dir $tmp_dir + + compile_rustfmt $tmp_dir + + # run checks + check_repo "https://github.com/rust-lang/rust.git" rust-lang-rust + check_repo "https://github.com/rust-lang/cargo.git" cargo + check_repo "https://github.com/rust-lang/miri.git" miri + check_repo "https://github.com/rust-lang/rust-analyzer.git" rust-analyzer + check_repo "https://github.com/bitflags/bitflags.git" bitflags + check_repo "https://github.com/rust-lang/log.git" log + check_repo "https://github.com/rust-lang/mdBook.git" mdBook + check_repo "https://github.com/rust-lang/packed_simd.git" packed_simd + check_repo "https://github.com/rust-lang/rust-semverver.git" check_repo + check_repo "https://github.com/Stebalien/tempfile.git" tempfile + check_repo "https://github.com/rust-lang/futures-rs.git" futures-rs + check_repo "https://github.com/dtolnay/anyhow.git" anyhow + check_repo "https://github.com/dtolnay/thiserror.git" thiserror + check_repo "https://github.com/dtolnay/syn.git" syn + check_repo "https://github.com/serde-rs/serde.git" serde + check_repo "https://github.com/rust-lang/rustlings.git" rustlings + check_repo "https://github.com/rust-lang/rustup.git" rustup + check_repo "https://github.com/SergioBenitez/Rocket.git" Rocket + check_repo "https://github.com/rustls/rustls.git" rustls + check_repo "https://github.com/rust-lang/rust-bindgen.git" rust-bindgen + check_repo "https://github.com/hyperium/hyper.git" hyper + check_repo "https://github.com/actix/actix.git" actix + check_repo "https://github.com/denoland/deno.git" denoland_deno + + # cleanup temp dir + echo removing tmp_dir $tmp_dir + rm -rf $tmp_dir + + # figure out the exit code + for status in ${STATUSES[@]} + do + if [ $status -eq 1 ]; then + echo "formatting diff found 💔" + return 1 + fi + done + + echo "no diff found 😊" +} + +main From edb616df3372e75bb501b871906901b834821106 Mon Sep 17 00:00:00 2001 From: David Wood Date: Wed, 10 Aug 2022 17:30:47 +0100 Subject: [PATCH 34/69] errors: move translation logic into module Just moving code around so that triagebot can ping relevant parties when translation logic is modified. Signed-off-by: David Wood --- src/parse/session.rs | 52 ++++++++++++++++++++++++++++---------------- 1 file changed, 33 insertions(+), 19 deletions(-) diff --git a/src/parse/session.rs b/src/parse/session.rs index 23db542191036..6efeee98fea6c 100644 --- a/src/parse/session.rs +++ b/src/parse/session.rs @@ -3,6 +3,7 @@ use std::sync::atomic::{AtomicBool, Ordering}; use rustc_data_structures::sync::{Lrc, Send}; use rustc_errors::emitter::{Emitter, EmitterWriter}; +use rustc_errors::translation::Translate; use rustc_errors::{ColorConfig, Diagnostic, Handler, Level as DiagnosticLevel}; use rustc_session::parse::ParseSess as RawParseSess; use rustc_span::{ @@ -28,19 +29,24 @@ pub(crate) struct ParseSess { /// Emitter which discards every error. struct SilentEmitter; -impl Emitter for SilentEmitter { - fn source_map(&self) -> Option<&Lrc> { - None - } - fn emit_diagnostic(&mut self, _db: &Diagnostic) {} +impl Translate for SilentEmitter { fn fluent_bundle(&self) -> Option<&Lrc> { None } + fn fallback_fluent_bundle(&self) -> &rustc_errors::FluentBundle { panic!("silent emitter attempted to translate a diagnostic"); } } +impl Emitter for SilentEmitter { + fn source_map(&self) -> Option<&Lrc> { + None + } + + fn emit_diagnostic(&mut self, _db: &Diagnostic) {} +} + fn silent_emitter() -> Box { Box::new(SilentEmitter {}) } @@ -62,10 +68,21 @@ impl SilentOnIgnoredFilesEmitter { } } +impl Translate for SilentOnIgnoredFilesEmitter { + fn fluent_bundle(&self) -> Option<&Lrc> { + self.emitter.fluent_bundle() + } + + fn fallback_fluent_bundle(&self) -> &rustc_errors::FluentBundle { + self.emitter.fallback_fluent_bundle() + } +} + impl Emitter for SilentOnIgnoredFilesEmitter { fn source_map(&self) -> Option<&Lrc> { None } + fn emit_diagnostic(&mut self, db: &Diagnostic) { if db.level() == DiagnosticLevel::Fatal { return self.handle_non_ignoreable_error(db); @@ -88,14 +105,6 @@ impl Emitter for SilentOnIgnoredFilesEmitter { } self.handle_non_ignoreable_error(db); } - - fn fluent_bundle(&self) -> Option<&Lrc> { - self.emitter.fluent_bundle() - } - - fn fallback_fluent_bundle(&self) -> &rustc_errors::FluentBundle { - self.emitter.fallback_fluent_bundle() - } } fn default_handler( @@ -340,19 +349,24 @@ mod tests { num_emitted_errors: Lrc, } + impl Translate for TestEmitter { + fn fluent_bundle(&self) -> Option<&Lrc> { + None + } + + fn fallback_fluent_bundle(&self) -> &rustc_errors::FluentBundle { + panic!("test emitter attempted to translate a diagnostic"); + } + } + impl Emitter for TestEmitter { fn source_map(&self) -> Option<&Lrc> { None } + fn emit_diagnostic(&mut self, _db: &Diagnostic) { self.num_emitted_errors.fetch_add(1, Ordering::Release); } - fn fluent_bundle(&self) -> Option<&Lrc> { - None - } - fn fallback_fluent_bundle(&self) -> &rustc_errors::FluentBundle { - panic!("test emitter attempted to translate a diagnostic"); - } } fn build_diagnostic(level: DiagnosticLevel, span: Option) -> Diagnostic { From e97825ed5ef3975ff6b138e16147802979df4ef3 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Thu, 11 Aug 2022 21:06:11 +1000 Subject: [PATCH 35/69] Shrink `ast::Attribute`. --- src/skip.rs | 4 ++-- src/visitor.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/skip.rs b/src/skip.rs index 0fdc097efc23f..032922d421df7 100644 --- a/src/skip.rs +++ b/src/skip.rs @@ -58,8 +58,8 @@ fn get_skip_names(kind: &str, attrs: &[ast::Attribute]) -> Vec { for attr in attrs { // rustc_ast::ast::Path is implemented partialEq // but it is designed for segments.len() == 1 - if let ast::AttrKind::Normal(attr_item, _) = &attr.kind { - if pprust::path_to_string(&attr_item.path) != path { + if let ast::AttrKind::Normal(normal) = &attr.kind { + if pprust::path_to_string(&normal.item.path) != path { continue; } } diff --git a/src/visitor.rs b/src/visitor.rs index 9a0e0752c12f5..7bb745eeb8b9b 100644 --- a/src/visitor.rs +++ b/src/visitor.rs @@ -811,8 +811,8 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { ); } else { match &attr.kind { - ast::AttrKind::Normal(ref attribute_item, _) - if self.is_unknown_rustfmt_attr(&attribute_item.path.segments) => + ast::AttrKind::Normal(ref normal) + if self.is_unknown_rustfmt_attr(&normal.item.path.segments) => { let file_name = self.parse_sess.span_to_filename(attr.span); self.report.append( From e5b5f56d4329159961095bdaca3f608fc097f930 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Mon, 1 Aug 2022 16:46:08 +1000 Subject: [PATCH 36/69] Rename some things related to literals. - Rename `ast::Lit::token` as `ast::Lit::token_lit`, because its type is `token::Lit`, which is not a token. (This has been confusing me for a long time.) reasonable because we have an `ast::token::Lit` inside an `ast::Lit`. - Rename `LitKind::{from,to}_lit_token` as `LitKind::{from,to}_token_lit`, to match the above change and `token::Lit`. --- src/expr.rs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/expr.rs b/src/expr.rs index a7b73ba78c59e..3105882e2d308 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -79,7 +79,7 @@ pub(crate) fn format_expr( if let Some(expr_rw) = rewrite_literal(context, l, shape) { Some(expr_rw) } else { - if let LitKind::StrRaw(_) = l.token.kind { + if let LitKind::StrRaw(_) = l.token_lit.kind { Some(context.snippet(l.span).trim().into()) } else { None @@ -1226,7 +1226,7 @@ fn rewrite_string_lit(context: &RewriteContext<'_>, span: Span, shape: Shape) -> fn rewrite_int_lit(context: &RewriteContext<'_>, lit: &ast::Lit, shape: Shape) -> Option { let span = lit.span; - let symbol = lit.token.symbol.as_str(); + let symbol = lit.token_lit.symbol.as_str(); if let Some(symbol_stripped) = symbol.strip_prefix("0x") { let hex_lit = match context.config.hex_literal_case() { @@ -1239,7 +1239,9 @@ fn rewrite_int_lit(context: &RewriteContext<'_>, lit: &ast::Lit, shape: Shape) - format!( "0x{}{}", hex_lit, - lit.token.suffix.map_or(String::new(), |s| s.to_string()) + lit.token_lit + .suffix + .map_or(String::new(), |s| s.to_string()) ), context.config.max_width(), shape, From 38659ec6ad5f341cf8eb3139725bf695872c6de7 Mon Sep 17 00:00:00 2001 From: A-Walrus <58790821+A-Walrus@users.noreply.github.com> Date: Fri, 19 Aug 2022 02:44:29 +0300 Subject: [PATCH 37/69] Unicode comment align (#5505) * Fix comment alignment with unicode Also added tests for this behaviour * Simplify tests * Improve tests --- src/lists.rs | 16 ++-- tests/source/comments_unicode.rs | 140 +++++++++++++++++++++++++++++++ tests/target/comments_unicode.rs | 140 +++++++++++++++++++++++++++++++ 3 files changed, 288 insertions(+), 8 deletions(-) create mode 100644 tests/source/comments_unicode.rs create mode 100644 tests/target/comments_unicode.rs diff --git a/src/lists.rs b/src/lists.rs index e87850507824f..a878e6cf9b2fc 100644 --- a/src/lists.rs +++ b/src/lists.rs @@ -297,9 +297,9 @@ where } else { inner_item.as_ref() }; - let mut item_last_line_width = item_last_line.len() + item_sep_len; + let mut item_last_line_width = unicode_str_width(item_last_line) + item_sep_len; if item_last_line.starts_with(&**indent_str) { - item_last_line_width -= indent_str.len(); + item_last_line_width -= unicode_str_width(indent_str); } if !item.is_substantial() { @@ -449,7 +449,7 @@ where } else if starts_with_newline(comment) { false } else { - comment.trim().contains('\n') || comment.trim().len() > width + comment.trim().contains('\n') || unicode_str_width(comment.trim()) > width }; rewrite_comment( @@ -465,7 +465,7 @@ where if !starts_with_newline(comment) { if formatting.align_comments { let mut comment_alignment = - post_comment_alignment(item_max_width, inner_item.len()); + post_comment_alignment(item_max_width, unicode_str_width(inner_item)); if first_line_width(&formatted_comment) + last_line_width(&result) + comment_alignment @@ -475,7 +475,7 @@ where item_max_width = None; formatted_comment = rewrite_post_comment(&mut item_max_width)?; comment_alignment = - post_comment_alignment(item_max_width, inner_item.len()); + post_comment_alignment(item_max_width, unicode_str_width(inner_item)); } for _ in 0..=comment_alignment { result.push(' '); @@ -533,7 +533,7 @@ where let mut first = true; for item in items.clone().into_iter().skip(i) { let item = item.as_ref(); - let inner_item_width = item.inner_as_ref().len(); + let inner_item_width = unicode_str_width(item.inner_as_ref()); if !first && (item.is_different_group() || item.post_comment.is_none() @@ -552,8 +552,8 @@ where max_width } -fn post_comment_alignment(item_max_width: Option, inner_item_len: usize) -> usize { - item_max_width.unwrap_or(0).saturating_sub(inner_item_len) +fn post_comment_alignment(item_max_width: Option, inner_item_width: usize) -> usize { + item_max_width.unwrap_or(0).saturating_sub(inner_item_width) } pub(crate) struct ListItems<'a, I, F1, F2, F3> diff --git a/tests/source/comments_unicode.rs b/tests/source/comments_unicode.rs new file mode 100644 index 0000000000000..e65a245ba9343 --- /dev/null +++ b/tests/source/comments_unicode.rs @@ -0,0 +1,140 @@ +impl Default for WhitespaceCharacters { + fn default() -> Self { + Self { + space: '·', // U+00B7 + nbsp: '⍽', // U+237D + tab: '→', // U+2192 + newline: '⏎', // U+23CE + } + } +} + +const RAINBOWS: &[&str] = &[ + "rаinЬοѡ", // hue: 0 + "raіnЬοw", // hue: 2 + "rаіɴЬow", // hue: 2 + "raіɴЬoѡ", // hue: 8 + "ʀainЬow", // hue: 8 + "ʀaіɴboѡ", // hue: 8 + "ʀаіnbοw", // hue: 11 + "rainЬoѡ", // hue: 14 + "raіɴbow", // hue: 14 + "rаiɴЬow", // hue: 20 + "raіnЬow", // hue: 26 + "ʀaiɴbοw", // hue: 32 + "raіɴboѡ", // hue: 35 + "rаiɴbow", // hue: 35 + "rаіnbοw", // hue: 38 + "rаinЬow", // hue: 47 + "ʀaіnboѡ", // hue: 47 + "ʀaіnЬoѡ", // hue: 47 + "ʀаіɴbοw", // hue: 53 + "ʀaіnЬοѡ", // hue: 57 + "raiɴЬoѡ", // hue: 68 + "ʀainbοѡ", // hue: 68 + "ʀаinboѡ", // hue: 68 + "ʀаiɴbοw", // hue: 68 + "ʀаіnbow", // hue: 68 + "rаіnЬοѡ", // hue: 69 + "ʀainЬοw", // hue: 71 + "raiɴbow", // hue: 73 + "raіnЬoѡ", // hue: 74 + "rаіɴbοw", // hue: 77 + "raіnЬοѡ", // hue: 81 + "raiɴЬow", // hue: 83 + "ʀainbοw", // hue: 83 + "ʀаinbow", // hue: 83 + "ʀаiɴbοѡ", // hue: 83 + "ʀаіnboѡ", // hue: 83 + "ʀаіɴЬοѡ", // hue: 84 + "rainЬow", // hue: 85 + "ʀаiɴЬοw", // hue: 86 + "ʀаіnbοѡ", // hue: 89 + "ʀаіnЬοw", // hue: 92 + "rаiɴbοw", // hue: 95 + "ʀаіɴbοѡ", // hue: 98 + "ʀаiɴЬοѡ", // hue: 99 + "raіnbοw", // hue: 101 + "ʀаіɴЬοw", // hue: 101 + "ʀaiɴboѡ", // hue: 104 + "ʀаinbοѡ", // hue: 104 + "rаiɴbοѡ", // hue: 107 + "ʀаinЬοw", // hue: 107 + "rаiɴЬοw", // hue: 110 + "rаіnboѡ", // hue: 110 + "rаіnbοѡ", // hue: 113 + "ʀainЬοѡ", // hue: 114 + "rаіnЬοw", // hue: 116 + "ʀaіɴЬow", // hue: 116 + "rаinbοw", // hue: 122 + "ʀаіɴboѡ", // hue: 125 + "rаinbοѡ", // hue: 131 + "rainbow", // hue: 134 + "rаinЬοw", // hue: 134 + "ʀаiɴboѡ", // hue: 140 + "rainЬοѡ", // hue: 141 + "raіɴЬow", // hue: 143 + "ʀainЬoѡ", // hue: 143 + "ʀaіɴbow", // hue: 143 + "ʀainbow", // hue: 148 + "rаіɴboѡ", // hue: 149 + "ʀainboѡ", // hue: 155 + "ʀaіnbow", // hue: 155 + "ʀaіnЬow", // hue: 155 + "raiɴbοw", // hue: 158 + "ʀаiɴЬoѡ", // hue: 158 + "rainbοw", // hue: 160 + "rаinbow", // hue: 160 + "ʀaіɴbοѡ", // hue: 164 + "ʀаiɴbow", // hue: 164 + "ʀаіnЬoѡ", // hue: 164 + "ʀaiɴЬοѡ", // hue: 165 + "rаiɴboѡ", // hue: 167 + "ʀaіɴЬοw", // hue: 167 + "ʀaіɴЬοѡ", // hue: 171 + "raіnboѡ", // hue: 173 + "ʀаіɴЬoѡ", // hue: 173 + "rаіɴbοѡ", // hue: 176 + "ʀаinЬow", // hue: 176 + "rаiɴЬοѡ", // hue: 177 + "rаіɴЬοw", // hue: 179 + "ʀаinЬoѡ", // hue: 179 + "ʀаіɴbow", // hue: 179 + "rаiɴЬoѡ", // hue: 182 + "raіɴbοѡ", // hue: 188 + "rаіnЬoѡ", // hue: 188 + "raiɴЬοѡ", // hue: 189 + "raіɴЬοw", // hue: 191 + "ʀaіɴbοw", // hue: 191 + "ʀаіnЬow", // hue: 191 + "rainbοѡ", // hue: 194 + "rаinboѡ", // hue: 194 + "rаіnbow", // hue: 194 + "rainЬοw", // hue: 197 + "rаinЬoѡ", // hue: 206 + "rаіɴbow", // hue: 206 + "rаіɴЬοѡ", // hue: 210 + "ʀaiɴЬow", // hue: 212 + "raіɴbοw", // hue: 218 + "rаіnЬow", // hue: 218 + "ʀaiɴbοѡ", // hue: 221 + "ʀaiɴЬοw", // hue: 224 + "ʀaіnbοѡ", // hue: 227 + "raiɴboѡ", // hue: 230 + "ʀaіnbοw", // hue: 230 + "ʀaіnЬοw", // hue: 230 + "ʀаinЬοѡ", // hue: 231 + "rainboѡ", // hue: 232 + "raіnbow", // hue: 232 + "ʀаіɴЬow", // hue: 233 + "ʀaіɴЬoѡ", // hue: 239 + "ʀаіnЬοѡ", // hue: 246 + "raiɴbοѡ", // hue: 248 + "ʀаiɴЬow", // hue: 248 + "raіɴЬοѡ", // hue: 249 + "raiɴЬοw", // hue: 251 + "rаіɴЬoѡ", // hue: 251 + "ʀaiɴbow", // hue: 251 + "ʀаinbοw", // hue: 251 + "raіnbοѡ", // hue: 254 +]; diff --git a/tests/target/comments_unicode.rs b/tests/target/comments_unicode.rs new file mode 100644 index 0000000000000..3e1b6b0a28fe4 --- /dev/null +++ b/tests/target/comments_unicode.rs @@ -0,0 +1,140 @@ +impl Default for WhitespaceCharacters { + fn default() -> Self { + Self { + space: '·', // U+00B7 + nbsp: '⍽', // U+237D + tab: '→', // U+2192 + newline: '⏎', // U+23CE + } + } +} + +const RAINBOWS: &[&str] = &[ + "rаinЬοѡ", // hue: 0 + "raіnЬοw", // hue: 2 + "rаіɴЬow", // hue: 2 + "raіɴЬoѡ", // hue: 8 + "ʀainЬow", // hue: 8 + "ʀaіɴboѡ", // hue: 8 + "ʀаіnbοw", // hue: 11 + "rainЬoѡ", // hue: 14 + "raіɴbow", // hue: 14 + "rаiɴЬow", // hue: 20 + "raіnЬow", // hue: 26 + "ʀaiɴbοw", // hue: 32 + "raіɴboѡ", // hue: 35 + "rаiɴbow", // hue: 35 + "rаіnbοw", // hue: 38 + "rаinЬow", // hue: 47 + "ʀaіnboѡ", // hue: 47 + "ʀaіnЬoѡ", // hue: 47 + "ʀаіɴbοw", // hue: 53 + "ʀaіnЬοѡ", // hue: 57 + "raiɴЬoѡ", // hue: 68 + "ʀainbοѡ", // hue: 68 + "ʀаinboѡ", // hue: 68 + "ʀаiɴbοw", // hue: 68 + "ʀаіnbow", // hue: 68 + "rаіnЬοѡ", // hue: 69 + "ʀainЬοw", // hue: 71 + "raiɴbow", // hue: 73 + "raіnЬoѡ", // hue: 74 + "rаіɴbοw", // hue: 77 + "raіnЬοѡ", // hue: 81 + "raiɴЬow", // hue: 83 + "ʀainbοw", // hue: 83 + "ʀаinbow", // hue: 83 + "ʀаiɴbοѡ", // hue: 83 + "ʀаіnboѡ", // hue: 83 + "ʀаіɴЬοѡ", // hue: 84 + "rainЬow", // hue: 85 + "ʀаiɴЬοw", // hue: 86 + "ʀаіnbοѡ", // hue: 89 + "ʀаіnЬοw", // hue: 92 + "rаiɴbοw", // hue: 95 + "ʀаіɴbοѡ", // hue: 98 + "ʀаiɴЬοѡ", // hue: 99 + "raіnbοw", // hue: 101 + "ʀаіɴЬοw", // hue: 101 + "ʀaiɴboѡ", // hue: 104 + "ʀаinbοѡ", // hue: 104 + "rаiɴbοѡ", // hue: 107 + "ʀаinЬοw", // hue: 107 + "rаiɴЬοw", // hue: 110 + "rаіnboѡ", // hue: 110 + "rаіnbοѡ", // hue: 113 + "ʀainЬοѡ", // hue: 114 + "rаіnЬοw", // hue: 116 + "ʀaіɴЬow", // hue: 116 + "rаinbοw", // hue: 122 + "ʀаіɴboѡ", // hue: 125 + "rаinbοѡ", // hue: 131 + "rainbow", // hue: 134 + "rаinЬοw", // hue: 134 + "ʀаiɴboѡ", // hue: 140 + "rainЬοѡ", // hue: 141 + "raіɴЬow", // hue: 143 + "ʀainЬoѡ", // hue: 143 + "ʀaіɴbow", // hue: 143 + "ʀainbow", // hue: 148 + "rаіɴboѡ", // hue: 149 + "ʀainboѡ", // hue: 155 + "ʀaіnbow", // hue: 155 + "ʀaіnЬow", // hue: 155 + "raiɴbοw", // hue: 158 + "ʀаiɴЬoѡ", // hue: 158 + "rainbοw", // hue: 160 + "rаinbow", // hue: 160 + "ʀaіɴbοѡ", // hue: 164 + "ʀаiɴbow", // hue: 164 + "ʀаіnЬoѡ", // hue: 164 + "ʀaiɴЬοѡ", // hue: 165 + "rаiɴboѡ", // hue: 167 + "ʀaіɴЬοw", // hue: 167 + "ʀaіɴЬοѡ", // hue: 171 + "raіnboѡ", // hue: 173 + "ʀаіɴЬoѡ", // hue: 173 + "rаіɴbοѡ", // hue: 176 + "ʀаinЬow", // hue: 176 + "rаiɴЬοѡ", // hue: 177 + "rаіɴЬοw", // hue: 179 + "ʀаinЬoѡ", // hue: 179 + "ʀаіɴbow", // hue: 179 + "rаiɴЬoѡ", // hue: 182 + "raіɴbοѡ", // hue: 188 + "rаіnЬoѡ", // hue: 188 + "raiɴЬοѡ", // hue: 189 + "raіɴЬοw", // hue: 191 + "ʀaіɴbοw", // hue: 191 + "ʀаіnЬow", // hue: 191 + "rainbοѡ", // hue: 194 + "rаinboѡ", // hue: 194 + "rаіnbow", // hue: 194 + "rainЬοw", // hue: 197 + "rаinЬoѡ", // hue: 206 + "rаіɴbow", // hue: 206 + "rаіɴЬοѡ", // hue: 210 + "ʀaiɴЬow", // hue: 212 + "raіɴbοw", // hue: 218 + "rаіnЬow", // hue: 218 + "ʀaiɴbοѡ", // hue: 221 + "ʀaiɴЬοw", // hue: 224 + "ʀaіnbοѡ", // hue: 227 + "raiɴboѡ", // hue: 230 + "ʀaіnbοw", // hue: 230 + "ʀaіnЬοw", // hue: 230 + "ʀаinЬοѡ", // hue: 231 + "rainboѡ", // hue: 232 + "raіnbow", // hue: 232 + "ʀаіɴЬow", // hue: 233 + "ʀaіɴЬoѡ", // hue: 239 + "ʀаіnЬοѡ", // hue: 246 + "raiɴbοѡ", // hue: 248 + "ʀаiɴЬow", // hue: 248 + "raіɴЬοѡ", // hue: 249 + "raiɴЬοw", // hue: 251 + "rаіɴЬoѡ", // hue: 251 + "ʀaiɴbow", // hue: 251 + "ʀаinbοw", // hue: 251 + "raіnbοѡ", // hue: 254 +]; From 05a0dfe8cd4db51a08d11ab24cc1586c833e2df1 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Wed, 17 Aug 2022 12:34:33 +1000 Subject: [PATCH 38/69] Use `AttrVec` in more places. In some places we use `Vec` and some places we use `ThinVec` (a.k.a. `AttrVec`). This results in various points where we have to convert between `Vec` and `ThinVec`. This commit changes the places that use `Vec` to use `AttrVec`. A lot of this is mechanical and boring, but there are some interesting parts: - It adds a few new methods to `ThinVec`. - It implements `MapInPlace` for `ThinVec`, and introduces a macro to avoid the repetition of this trait for `Vec`, `SmallVec`, and `ThinVec`. Overall, it makes the code a little nicer, and has little effect on performance. But it is a precursor to removing `rustc_data_structures::thin_vec::ThinVec` and replacing it with `thin_vec::ThinVec`, which is implemented more efficiently. --- src/attr.rs | 5 +---- src/imports.rs | 4 ++-- src/modules.rs | 8 ++++---- src/parse/parser.rs | 2 +- 4 files changed, 8 insertions(+), 11 deletions(-) diff --git a/src/attr.rs b/src/attr.rs index 41ba9a847e67a..f5c1ee5fdd121 100644 --- a/src/attr.rs +++ b/src/attr.rs @@ -49,10 +49,7 @@ pub(crate) fn get_span_without_attrs(stmt: &ast::Stmt) -> Span { } /// Returns attributes that are within `outer_span`. -pub(crate) fn filter_inline_attrs( - attrs: &[ast::Attribute], - outer_span: Span, -) -> Vec { +pub(crate) fn filter_inline_attrs(attrs: &[ast::Attribute], outer_span: Span) -> ast::AttrVec { attrs .iter() .filter(|a| outer_span.lo() <= a.span.lo() && a.span.hi() <= outer_span.hi()) diff --git a/src/imports.rs b/src/imports.rs index 8d41c881589e5..b6530c69243ed 100644 --- a/src/imports.rs +++ b/src/imports.rs @@ -116,7 +116,7 @@ pub(crate) struct UseTree { // Additional fields for top level use items. // Should we have another struct for top-level use items rather than reusing this? visibility: Option, - attrs: Option>, + attrs: Option, } impl PartialEq for UseTree { @@ -417,7 +417,7 @@ impl UseTree { list_item: Option, visibility: Option, opt_lo: Option, - attrs: Option>, + attrs: Option, ) -> UseTree { let span = if let Some(lo) = opt_lo { mk_sp(lo, a.span.hi()) diff --git a/src/modules.rs b/src/modules.rs index 81da724329f02..7a0d1736c59a6 100644 --- a/src/modules.rs +++ b/src/modules.rs @@ -26,7 +26,7 @@ type FileModMap<'ast> = BTreeMap>; pub(crate) struct Module<'a> { ast_mod_kind: Option>, pub(crate) items: Cow<'a, Vec>>, - inner_attr: Vec, + inner_attr: ast::AttrVec, pub(crate) span: Span, } @@ -35,7 +35,7 @@ impl<'a> Module<'a> { mod_span: Span, ast_mod_kind: Option>, mod_items: Cow<'a, Vec>>, - mod_attrs: Cow<'a, Vec>, + mod_attrs: Cow<'a, ast::AttrVec>, ) -> Self { let inner_attr = mod_attrs .iter() @@ -158,7 +158,7 @@ impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> { module_item.item.span, Some(Cow::Owned(sub_mod_kind.clone())), Cow::Owned(vec![]), - Cow::Owned(vec![]), + Cow::Owned(ast::AttrVec::new()), ), )?; } @@ -185,7 +185,7 @@ impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> { span, Some(Cow::Owned(sub_mod_kind.clone())), Cow::Owned(vec![]), - Cow::Owned(vec![]), + Cow::Owned(ast::AttrVec::new()), ), )?; } diff --git a/src/parse/parser.rs b/src/parse/parser.rs index 268c72649a65a..e0bd065518b3d 100644 --- a/src/parse/parser.rs +++ b/src/parse/parser.rs @@ -109,7 +109,7 @@ impl<'a> Parser<'a> { sess: &'a ParseSess, path: &Path, span: Span, - ) -> Result<(Vec, Vec>, Span), ParserError> { + ) -> Result<(ast::AttrVec, Vec>, Span), ParserError> { let result = catch_unwind(AssertUnwindSafe(|| { let mut parser = new_parser_from_file(sess.inner(), path, Some(span)); match parser.parse_mod(&TokenKind::Eof) { From 7852b8808b1691f956d8928b3f9ca140cf93feb8 Mon Sep 17 00:00:00 2001 From: Joshua Nelson Date: Thu, 14 Jul 2022 08:30:38 -0500 Subject: [PATCH 39/69] Stabilize `#![feature(label_break_value)]` # Stabilization proposal The feature was implemented in https://github.com/rust-lang/rust/pull/50045 by est31 and has been in nightly since 2018-05-16 (over 4 years now). There are [no open issues][issue-label] other than the tracking issue. There is a strong consensus that `break` is the right keyword and we should not use `return`. There have been several concerns raised about this feature on the tracking issue (other than the one about tests, which has been fixed, and an interaction with try blocks, which has been fixed). 1. nrc's original comment about cost-benefit analysis: https://github.com/rust-lang/rust/issues/48594#issuecomment-422235234 2. joshtriplett's comments about seeing use cases: https://github.com/rust-lang/rust/issues/48594#issuecomment-422281176 3. withoutboats's comments that Rust does not need more control flow constructs: https://github.com/rust-lang/rust/issues/48594#issuecomment-450050630 Many different examples of code that's simpler using this feature have been provided: - A lexer by rpjohnst which must repeat code without label-break-value: https://github.com/rust-lang/rust/issues/48594#issuecomment-422502014 - A snippet by SergioBenitez which avoids using a new function and adding several new return points to a function: https://github.com/rust-lang/rust/issues/48594#issuecomment-427628251. This particular case would also work if `try` blocks were stabilized (at the cost of making the code harder to optimize). - Several examples by JohnBSmith: https://github.com/rust-lang/rust/issues/48594#issuecomment-434651395 - Several examples by Centril: https://github.com/rust-lang/rust/issues/48594#issuecomment-440154733 - An example by petrochenkov where this is used in the compiler itself to avoid duplicating error checking code: https://github.com/rust-lang/rust/issues/48594#issuecomment-443557569 - Amanieu recently provided another example related to complex conditions, where try blocks would not have helped: https://github.com/rust-lang/rust/issues/48594#issuecomment-1184213006 Additionally, petrochenkov notes that this is strictly more powerful than labelled loops due to macros which accidentally exit a loop instead of being consumed by the macro matchers: https://github.com/rust-lang/rust/issues/48594#issuecomment-450246249 nrc later resolved their concern, mostly because of the aforementioned macro problems. joshtriplett suggested that macros could be able to generate IR directly (https://github.com/rust-lang/rust/issues/48594#issuecomment-451685983) but there are no open RFCs, and the design space seems rather speculative. joshtriplett later resolved his concerns, due to a symmetry between this feature and existing labelled break: https://github.com/rust-lang/rust/issues/48594#issuecomment-632960804 withoutboats has regrettably left the language team. joshtriplett later posted that the lang team would consider starting an FCP given a stabilization report: https://github.com/rust-lang/rust/issues/48594#issuecomment-1111269353 [issue-label]: https://github.com/rust-lang/rust/issues?q=is%3Aissue+is%3Aopen+label%3AF-label_break_value+ ## Report + Feature gate: - https://github.com/rust-lang/rust/blob/d695a497bbf4b20d2580b75075faa80230d41667/src/test/ui/feature-gates/feature-gate-label_break_value.rs + Diagnostics: - https://github.com/rust-lang/rust/blob/6b2d3d5f3cd1e553d87b5496632132565b6779d3/compiler/rustc_parse/src/parser/diagnostics.rs#L2629 - https://github.com/rust-lang/rust/blob/f65bf0b2bb1a99f73095c01a118f3c37d3ee614c/compiler/rustc_resolve/src/diagnostics.rs#L749 - https://github.com/rust-lang/rust/blob/f65bf0b2bb1a99f73095c01a118f3c37d3ee614c/compiler/rustc_resolve/src/diagnostics.rs#L1001 - https://github.com/rust-lang/rust/blob/111df9e6eda1d752233482c1309d00d20a4bbf98/compiler/rustc_passes/src/loops.rs#L254 - https://github.com/rust-lang/rust/blob/d695a497bbf4b20d2580b75075faa80230d41667/compiler/rustc_parse/src/parser/expr.rs#L2079 - https://github.com/rust-lang/rust/blob/d695a497bbf4b20d2580b75075faa80230d41667/compiler/rustc_parse/src/parser/expr.rs#L1569 + Tests: - https://github.com/rust-lang/rust/blob/master/src/test/ui/label/label_break_value_continue.rs - https://github.com/rust-lang/rust/blob/master/src/test/ui/label/label_break_value_unlabeled_break.rs - https://github.com/rust-lang/rust/blob/master/src/test/ui/label/label_break_value_illegal_uses.rs - https://github.com/rust-lang/rust/blob/master/src/test/ui/lint/unused_labels.rs - https://github.com/rust-lang/rust/blob/master/src/test/ui/run-pass/for-loop-while/label_break_value.rs ## Interactions with other features Labels follow the hygiene of local variables. label-break-value is permitted within `try` blocks: ```rust let _: Result<(), ()> = try { 'foo: { Err(())?; break 'foo; } }; ``` label-break-value is disallowed within closures, generators, and async blocks: ```rust 'a: { || break 'a //~^ ERROR use of unreachable label `'a` //~| ERROR `break` inside of a closure } ``` label-break-value is disallowed on [_BlockExpression_]; it can only occur as a [_LoopExpression_]: ```rust fn labeled_match() { match false 'b: { //~ ERROR block label not supported here _ => {} } } macro_rules! m { ($b:block) => { 'lab: $b; //~ ERROR cannot use a `block` macro fragment here unsafe $b; //~ ERROR cannot use a `block` macro fragment here |x: u8| -> () $b; //~ ERROR cannot use a `block` macro fragment here } } fn foo() { m!({}); } ``` [_BlockExpression_]: https://doc.rust-lang.org/nightly/reference/expressions/block-expr.html [_LoopExpression_]: https://doc.rust-lang.org/nightly/reference/expressions/loop-expr.html --- tests/source/issue-3217.rs | 2 -- tests/target/issue-3217.rs | 2 -- 2 files changed, 4 deletions(-) diff --git a/tests/source/issue-3217.rs b/tests/source/issue-3217.rs index 176c702002a28..e68ca2c5907fc 100644 --- a/tests/source/issue-3217.rs +++ b/tests/source/issue-3217.rs @@ -1,5 +1,3 @@ -#![feature(label_break_value)] - fn main() { let mut res = 0; 's_39: { if res == 0i32 { println!("Hello, world!"); } } diff --git a/tests/target/issue-3217.rs b/tests/target/issue-3217.rs index 5121320a0975b..403bf4c340a4e 100644 --- a/tests/target/issue-3217.rs +++ b/tests/target/issue-3217.rs @@ -1,5 +1,3 @@ -#![feature(label_break_value)] - fn main() { let mut res = 0; 's_39: { From ddda7bbe5dfc3884857a90efe9dfd4dfc3eb85e1 Mon Sep 17 00:00:00 2001 From: Eric Huss Date: Sat, 20 Aug 2022 21:19:43 -0700 Subject: [PATCH 40/69] Sunset RLS --- Processes.md | 4 ---- README.md | 2 +- atom.md | 4 ++-- 3 files changed, 3 insertions(+), 7 deletions(-) diff --git a/Processes.md b/Processes.md index 9d86d52b122d8..f763b5714ce2c 100644 --- a/Processes.md +++ b/Processes.md @@ -51,7 +51,3 @@ git tag -s v1.2.3 -m "Release 1.2.3" `cargo publish` ## 5. Create a PR to rust-lang/rust to update the rustfmt submodule - -Note that if you are updating `rustc-ap-*` crates, then you need to update **every** submodules in the rust-lang/rust repository that depend on the crates to use the same version of those. - -As of 2019/05, there are two such crates: `rls` and `racer` (`racer` depends on `rustc-ap-syntax` and `rls` depends on `racer`, and `rls` is one of submodules of the rust-lang/rust repository). diff --git a/README.md b/README.md index b3a968f0c043e..0f9652aecf9c2 100644 --- a/README.md +++ b/README.md @@ -135,7 +135,7 @@ completed without error (whether or not changes were made). * [Emacs](https://github.com/rust-lang/rust-mode) * [Sublime Text 3](https://packagecontrol.io/packages/RustFmt) * [Atom](atom.md) -* Visual Studio Code using [vscode-rust](https://github.com/editor-rs/vscode-rust), [vsc-rustfmt](https://github.com/Connorcpu/vsc-rustfmt) or [rls_vscode](https://github.com/jonathandturner/rls_vscode) through RLS. +* [Visual Studio Code](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer) * [IntelliJ or CLion](intellij.md) diff --git a/atom.md b/atom.md index f77ac1490721d..c7e3a991a5f03 100644 --- a/atom.md +++ b/atom.md @@ -1,8 +1,8 @@ # Running Rustfmt from Atom -## RLS +## rust-analyzer -Rustfmt is included with the Rust Language Server, itself provided by [ide-rust](https://atom.io/packages/ide-rust). +Rustfmt can be utilized from [rust-analyzer](https://rust-analyzer.github.io/) which is provided by [ide-rust](https://atom.io/packages/ide-rust). `apm install ide-rust` From 748b031056f109b0e2e58ab1e2f0189b83c32f3e Mon Sep 17 00:00:00 2001 From: Jack Huey <31162821+jackh726@users.noreply.github.com> Date: Wed, 4 May 2022 10:22:19 -0400 Subject: [PATCH 41/69] Stabilize GATs --- tests/source/issue_4257.rs | 3 --- tests/source/issue_4911.rs | 1 - tests/source/issue_4943.rs | 2 -- tests/target/issue_4257.rs | 3 --- tests/target/issue_4911.rs | 1 - tests/target/issue_4943.rs | 2 -- 6 files changed, 12 deletions(-) diff --git a/tests/source/issue_4257.rs b/tests/source/issue_4257.rs index 2b887fadb621c..9482512efca0a 100644 --- a/tests/source/issue_4257.rs +++ b/tests/source/issue_4257.rs @@ -1,6 +1,3 @@ -#![feature(generic_associated_types)] -#![allow(incomplete_features)] - trait Trait { type Type<'a> where T: 'a; fn foo(x: &T) -> Self::Type<'_>; diff --git a/tests/source/issue_4911.rs b/tests/source/issue_4911.rs index 21ef6c6c491ac..c254db7b509cc 100644 --- a/tests/source/issue_4911.rs +++ b/tests/source/issue_4911.rs @@ -1,4 +1,3 @@ -#![feature(generic_associated_types)] #![feature(min_type_alias_impl_trait)] impl SomeTrait for SomeType { diff --git a/tests/source/issue_4943.rs b/tests/source/issue_4943.rs index 0793b7b4fe1cc..307d9a4a1aba1 100644 --- a/tests/source/issue_4943.rs +++ b/tests/source/issue_4943.rs @@ -1,5 +1,3 @@ -#![feature(generic_associated_types)] - impl SomeStruct { fn process(v: T) -> ::R where Self: GAT = T> diff --git a/tests/target/issue_4257.rs b/tests/target/issue_4257.rs index 1ebaaf2b60018..309a66c8dc3cc 100644 --- a/tests/target/issue_4257.rs +++ b/tests/target/issue_4257.rs @@ -1,6 +1,3 @@ -#![feature(generic_associated_types)] -#![allow(incomplete_features)] - trait Trait { type Type<'a> where diff --git a/tests/target/issue_4911.rs b/tests/target/issue_4911.rs index 890a62267ce64..0f64aa7f766fd 100644 --- a/tests/target/issue_4911.rs +++ b/tests/target/issue_4911.rs @@ -1,4 +1,3 @@ -#![feature(generic_associated_types)] #![feature(min_type_alias_impl_trait)] impl SomeTrait for SomeType { diff --git a/tests/target/issue_4943.rs b/tests/target/issue_4943.rs index 318f7ebed6e06..bc8f1a366da29 100644 --- a/tests/target/issue_4943.rs +++ b/tests/target/issue_4943.rs @@ -1,5 +1,3 @@ -#![feature(generic_associated_types)] - impl SomeStruct { fn process(v: T) -> ::R where From e40972ebf86040de884d5b5b54e3345af504c140 Mon Sep 17 00:00:00 2001 From: Cameron Steffen Date: Tue, 30 Aug 2022 17:39:36 -0500 Subject: [PATCH 42/69] rustfmt: BindingAnnotation change --- src/patterns.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/patterns.rs b/src/patterns.rs index 9b74b35f31413..e2fe92b28f23e 100644 --- a/src/patterns.rs +++ b/src/patterns.rs @@ -1,4 +1,6 @@ -use rustc_ast::ast::{self, BindingMode, Pat, PatField, PatKind, RangeEnd, RangeSyntax}; +use rustc_ast::ast::{ + self, BindingAnnotation, ByRef, Pat, PatField, PatKind, RangeEnd, RangeSyntax, +}; use rustc_ast::ptr; use rustc_span::{BytePos, Span}; @@ -99,10 +101,10 @@ impl Rewrite for Pat { write_list(&items, &fmt) } PatKind::Box(ref pat) => rewrite_unary_prefix(context, "box ", &**pat, shape), - PatKind::Ident(binding_mode, ident, ref sub_pat) => { - let (prefix, mutability) = match binding_mode { - BindingMode::ByRef(mutability) => ("ref", mutability), - BindingMode::ByValue(mutability) => ("", mutability), + PatKind::Ident(BindingAnnotation(by_ref, mutability), ident, ref sub_pat) => { + let prefix = match by_ref { + ByRef::Yes => "ref", + ByRef::No => "", }; let mut_infix = format_mutability(mutability).trim(); let id_str = rewrite_ident(context, ident); From ef91154250977b3b5d05448dafbca524a1168b47 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Mon, 19 Sep 2022 17:58:37 -0500 Subject: [PATCH 43/69] docs: expand behavior of imports_granularity re: groups (#5543) --- Configurations.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/Configurations.md b/Configurations.md index e066553dc63f3..400ad8c5d3bfe 100644 --- a/Configurations.md +++ b/Configurations.md @@ -1857,13 +1857,16 @@ pub enum Foo {} ## `imports_granularity` -How imports should be grouped into `use` statements. Imports will be merged or split to the configured level of granularity. +Controls how imports are structured in `use` statements. Imports will be merged or split to the configured level of granularity. + +Similar to other `import` related configuration options, this option operates within the bounds of user-defined groups of imports. See [`group_imports`](#group_imports) for more information on import groups. + +Note that rustfmt will not modify the granularity of imports containing comments if doing so could potentially lose or misplace said comments. - **Default value**: `Preserve` - **Possible values**: `Preserve`, `Crate`, `Module`, `Item`, `One` - **Stable**: No (tracking issue: [#4991](https://github.com/rust-lang/rustfmt/issues/4991)) -Note that rustfmt will not modify the granularity of imports containing comments if doing so could potentially lose or misplace said comments. #### `Preserve` (default): From d71413cbfae7a8c7fb7d2534f7240915161ce46a Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Mon, 10 Oct 2022 02:05:24 +0000 Subject: [PATCH 44/69] Rename AssocItemKind::TyAlias to AssocItemKind::Type --- src/items.rs | 12 ++++++------ src/visitor.rs | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/items.rs b/src/items.rs index 8f35068e35f04..a2a73f0a5fb3a 100644 --- a/src/items.rs +++ b/src/items.rs @@ -594,7 +594,7 @@ impl<'a> FmtVisitor<'a> { let both_type = |l: &TyOpt, r: &TyOpt| is_type(l) && is_type(r); let both_opaque = |l: &TyOpt, r: &TyOpt| is_opaque(l) && is_opaque(r); let need_empty_line = |a: &ast::AssocItemKind, b: &ast::AssocItemKind| match (a, b) { - (TyAlias(lty), TyAlias(rty)) + (Type(lty), Type(rty)) if both_type(<y.ty, &rty.ty) || both_opaque(<y.ty, &rty.ty) => { false @@ -612,7 +612,7 @@ impl<'a> FmtVisitor<'a> { } buffer.sort_by(|(_, a), (_, b)| match (&a.kind, &b.kind) { - (TyAlias(lty), TyAlias(rty)) + (Type(lty), Type(rty)) if both_type(<y.ty, &rty.ty) || both_opaque(<y.ty, &rty.ty) => { a.ident.as_str().cmp(b.ident.as_str()) @@ -621,10 +621,10 @@ impl<'a> FmtVisitor<'a> { a.ident.as_str().cmp(b.ident.as_str()) } (Fn(..), Fn(..)) => a.span.lo().cmp(&b.span.lo()), - (TyAlias(ty), _) if is_type(&ty.ty) => Ordering::Less, - (_, TyAlias(ty)) if is_type(&ty.ty) => Ordering::Greater, - (TyAlias(..), _) => Ordering::Less, - (_, TyAlias(..)) => Ordering::Greater, + (Type(ty), _) if is_type(&ty.ty) => Ordering::Less, + (_, Type(ty)) if is_type(&ty.ty) => Ordering::Greater, + (Type(..), _) => Ordering::Less, + (_, Type(..)) => Ordering::Greater, (Const(..), _) => Ordering::Less, (_, Const(..)) => Ordering::Greater, (MacCall(..), _) => Ordering::Less, diff --git a/src/visitor.rs b/src/visitor.rs index 7bb745eeb8b9b..9c3cc7820d299 100644 --- a/src/visitor.rs +++ b/src/visitor.rs @@ -660,7 +660,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { self.push_rewrite(ai.span, rewrite); } } - (ast::AssocItemKind::TyAlias(ref ty_alias), _) => { + (ast::AssocItemKind::Type(ref ty_alias), _) => { self.visit_ty_alias_kind(ty_alias, visitor_kind, ai.span); } (ast::AssocItemKind::MacCall(ref mac), _) => { From 7cc303fbf62f6a058064fc07026231a8a5ee533f Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Mon, 10 Oct 2022 18:29:17 +0200 Subject: [PATCH 45/69] Fix unclosed HTML tag in rustfmt doc --- src/config/config_type.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/config/config_type.rs b/src/config/config_type.rs index e37ed798cb559..c5e61658ad1ed 100644 --- a/src/config/config_type.rs +++ b/src/config/config_type.rs @@ -4,7 +4,7 @@ use crate::config::options::{IgnoreList, WidthHeuristics}; /// Trait for types that can be used in `Config`. pub(crate) trait ConfigType: Sized { /// Returns hint text for use in `Config::print_docs()`. For enum types, this is a - /// pipe-separated list of variants; for other types it returns "". + /// pipe-separated list of variants; for other types it returns ``. fn doc_hint() -> String; } From 657dcf21d8e13265513451f354511a53ea2c3b04 Mon Sep 17 00:00:00 2001 From: mejrs <> Date: Wed, 19 Oct 2022 00:08:20 +0200 Subject: [PATCH 46/69] Implement -Ztrack-diagnostics --- src/parse/session.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/parse/session.rs b/src/parse/session.rs index 6efeee98fea6c..6bfec79cd7030 100644 --- a/src/parse/session.rs +++ b/src/parse/session.rs @@ -134,6 +134,7 @@ fn default_handler( false, None, false, + false, )) }; Handler::with_emitter( From eb07a5ea417f4fb54cbfaa0a74992208c0435bad Mon Sep 17 00:00:00 2001 From: Yuki Okushi Date: Mon, 24 Oct 2022 20:13:47 +0900 Subject: [PATCH 47/69] Remove `failure` integration test Signed-off-by: Yuki Okushi --- .github/workflows/integration.yml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index 4d8899b434bbe..314ce0e84c61b 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -27,7 +27,6 @@ jobs: tempdir, futures-rs, rust-clippy, - failure, ] include: # Allowed Failures @@ -63,9 +62,6 @@ jobs: # Original comment was: temporal build failure due to breaking changes in the nightly compiler - integration: rust-semverver allow-failure: true - # Can be moved back to include section after https://github.com/rust-lang-nursery/failure/pull/298 is merged - - integration: failure - allow-failure: true steps: - name: checkout From ad9fb89c3009282a55582f1c478d215d0c6005b0 Mon Sep 17 00:00:00 2001 From: Yuki Okushi Date: Mon, 24 Oct 2022 20:21:44 +0900 Subject: [PATCH 48/69] Update Git repo URLs Signed-off-by: Yuki Okushi --- ci/integration.sh | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/ci/integration.sh b/ci/integration.sh index 562d5d70c70ba..19d502bc5c7bd 100755 --- a/ci/integration.sh +++ b/ci/integration.sh @@ -91,14 +91,28 @@ case ${INTEGRATION} in cd - ;; crater) - git clone --depth=1 https://github.com/rust-lang-nursery/${INTEGRATION}.git + git clone --depth=1 https://github.com/rust-lang/${INTEGRATION}.git cd ${INTEGRATION} show_head check_fmt_with_lib_tests cd - ;; + bitflags) + git clone --depth=1 https://github.com/bitflags/${INTEGRATION}.git + cd ${INTEGRATION} + show_head + check_fmt_with_all_tests + cd - + ;; + error-chain | tempdir) + git clone --depth=1 https://github.com/rust-lang-deprecated/${INTEGRATION}.git + cd ${INTEGRATION} + show_head + check_fmt_with_all_tests + cd - + ;; *) - git clone --depth=1 https://github.com/rust-lang-nursery/${INTEGRATION}.git + git clone --depth=1 https://github.com/rust-lang/${INTEGRATION}.git cd ${INTEGRATION} show_head check_fmt_with_all_tests From ee2bed96d60fd7e46b1fb868f6a8f27e3a8058d0 Mon Sep 17 00:00:00 2001 From: Alex Touchet Date: Sat, 5 Nov 2022 21:39:56 -0700 Subject: [PATCH 49/69] Fix spacing --- Configurations.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Configurations.md b/Configurations.md index 400ad8c5d3bfe..49e7e4e64892a 100644 --- a/Configurations.md +++ b/Configurations.md @@ -425,7 +425,7 @@ fn example() { ## `comment_width` -Maximum length of comments. No effect unless`wrap_comments = true`. +Maximum length of comments. No effect unless `wrap_comments = true`. - **Default value**: `80` - **Possible values**: any positive integer From 660e53512f1c25f03f6cf34fb620a7c0ed11d120 Mon Sep 17 00:00:00 2001 From: clubby789 Date: Mon, 31 Oct 2022 18:30:09 +0000 Subject: [PATCH 50/69] Introduce `ExprKind::IncludedBytes` --- src/expr.rs | 1 + src/utils.rs | 1 + 2 files changed, 2 insertions(+) diff --git a/src/expr.rs b/src/expr.rs index 3105882e2d308..7750df0fff3af 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -399,6 +399,7 @@ pub(crate) fn format_expr( } } ast::ExprKind::Underscore => Some("_".to_owned()), + ast::ExprKind::IncludedBytes(..) => unreachable!(), ast::ExprKind::Err => None, }; diff --git a/src/utils.rs b/src/utils.rs index cd852855602e8..c47b3b314dd4b 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -496,6 +496,7 @@ pub(crate) fn is_block_expr(context: &RewriteContext<'_>, expr: &ast::Expr, repr | ast::ExprKind::Continue(..) | ast::ExprKind::Err | ast::ExprKind::Field(..) + | ast::ExprKind::IncludedBytes(..) | ast::ExprKind::InlineAsm(..) | ast::ExprKind::Let(..) | ast::ExprKind::Path(..) From 826fb78bebc757acf138e86bd755e1d81c1d08bc Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Mon, 10 Oct 2022 13:40:56 +1100 Subject: [PATCH 51/69] Use `token::Lit` in `ast::ExprKind::Lit`. Instead of `ast::Lit`. Literal lowering now happens at two different times. Expression literals are lowered when HIR is crated. Attribute literals are lowered during parsing. This commit changes the language very slightly. Some programs that used to not compile now will compile. This is because some invalid literals that are removed by `cfg` or attribute macros will no longer trigger errors. See this comment for more details: https://github.com/rust-lang/rust/pull/102944#issuecomment-1277476773 --- src/attr.rs | 6 ++++-- src/expr.rs | 41 ++++++++++++++++++++++------------------- 2 files changed, 26 insertions(+), 21 deletions(-) diff --git a/src/attr.rs b/src/attr.rs index f5c1ee5fdd121..ccc2fd0d5f589 100644 --- a/src/attr.rs +++ b/src/attr.rs @@ -260,7 +260,9 @@ impl Rewrite for ast::NestedMetaItem { fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { match self { ast::NestedMetaItem::MetaItem(ref meta_item) => meta_item.rewrite(context, shape), - ast::NestedMetaItem::Literal(ref l) => rewrite_literal(context, l, shape), + ast::NestedMetaItem::Literal(ref l) => { + rewrite_literal(context, l.token_lit, l.span, shape) + } } } } @@ -318,7 +320,7 @@ impl Rewrite for ast::MetaItem { // we might be better off ignoring the fact that the attribute // is longer than the max width and continue on formatting. // See #2479 for example. - let value = rewrite_literal(context, literal, lit_shape) + let value = rewrite_literal(context, literal.token_lit, literal.span, lit_shape) .unwrap_or_else(|| context.snippet(literal.span).to_owned()); format!("{} = {}", path, value) } diff --git a/src/expr.rs b/src/expr.rs index 7750df0fff3af..b4f1a178dbf44 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -3,7 +3,7 @@ use std::cmp::min; use itertools::Itertools; use rustc_ast::token::{Delimiter, LitKind}; -use rustc_ast::{ast, ptr}; +use rustc_ast::{ast, ptr, token}; use rustc_span::{BytePos, Span}; use crate::chains::rewrite_chain; @@ -75,12 +75,12 @@ pub(crate) fn format_expr( choose_separator_tactic(context, expr.span), None, ), - ast::ExprKind::Lit(ref l) => { - if let Some(expr_rw) = rewrite_literal(context, l, shape) { + ast::ExprKind::Lit(token_lit) => { + if let Some(expr_rw) = rewrite_literal(context, token_lit, expr.span, shape) { Some(expr_rw) } else { - if let LitKind::StrRaw(_) = l.token_lit.kind { - Some(context.snippet(l.span).trim().into()) + if let LitKind::StrRaw(_) = token_lit.kind { + Some(context.snippet(expr.span).trim().into()) } else { None } @@ -274,9 +274,9 @@ pub(crate) fn format_expr( fn needs_space_before_range(context: &RewriteContext<'_>, lhs: &ast::Expr) -> bool { match lhs.kind { - ast::ExprKind::Lit(ref lit) => match lit.kind { - ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) => { - context.snippet(lit.span).ends_with('.') + ast::ExprKind::Lit(token_lit) => match token_lit.kind { + token::LitKind::Float if token_lit.suffix.is_none() => { + context.snippet(lhs.span).ends_with('.') } _ => false, }, @@ -1185,14 +1185,15 @@ pub(crate) fn is_unsafe_block(block: &ast::Block) -> bool { pub(crate) fn rewrite_literal( context: &RewriteContext<'_>, - l: &ast::Lit, + token_lit: token::Lit, + span: Span, shape: Shape, ) -> Option { - match l.kind { - ast::LitKind::Str(_, ast::StrStyle::Cooked) => rewrite_string_lit(context, l.span, shape), - ast::LitKind::Int(..) => rewrite_int_lit(context, l, shape), + match token_lit.kind { + token::LitKind::Str => rewrite_string_lit(context, span, shape), + token::LitKind::Integer => rewrite_int_lit(context, token_lit, span, shape), _ => wrap_str( - context.snippet(l.span).to_owned(), + context.snippet(span).to_owned(), context.config.max_width(), shape, ), @@ -1225,9 +1226,13 @@ fn rewrite_string_lit(context: &RewriteContext<'_>, span: Span, shape: Shape) -> ) } -fn rewrite_int_lit(context: &RewriteContext<'_>, lit: &ast::Lit, shape: Shape) -> Option { - let span = lit.span; - let symbol = lit.token_lit.symbol.as_str(); +fn rewrite_int_lit( + context: &RewriteContext<'_>, + token_lit: token::Lit, + span: Span, + shape: Shape, +) -> Option { + let symbol = token_lit.symbol.as_str(); if let Some(symbol_stripped) = symbol.strip_prefix("0x") { let hex_lit = match context.config.hex_literal_case() { @@ -1240,9 +1245,7 @@ fn rewrite_int_lit(context: &RewriteContext<'_>, lit: &ast::Lit, shape: Shape) - format!( "0x{}{}", hex_lit, - lit.token_lit - .suffix - .map_or(String::new(), |s| s.to_string()) + token_lit.suffix.map_or(String::new(), |s| s.to_string()) ), context.config.max_width(), shape, From 4a4addc5980e95e4f7883f2d56aedcd08626ba73 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Thu, 8 Sep 2022 10:52:51 +1000 Subject: [PATCH 52/69] Box `ExprKind::{Closure,MethodCall}`, and `QSelf` in expressions, types, and patterns. --- src/attr.rs | 6 +++--- src/chains.rs | 12 +++++------- src/closures.rs | 30 +++++++++++++++++++----------- src/expr.rs | 26 +++++++++++++------------- src/patterns.rs | 9 ++++----- src/types.rs | 8 ++++---- src/utils.rs | 2 +- 7 files changed, 49 insertions(+), 44 deletions(-) diff --git a/src/attr.rs b/src/attr.rs index ccc2fd0d5f589..23f55db773e6c 100644 --- a/src/attr.rs +++ b/src/attr.rs @@ -290,10 +290,10 @@ impl Rewrite for ast::MetaItem { fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { Some(match self.kind { ast::MetaItemKind::Word => { - rewrite_path(context, PathContext::Type, None, &self.path, shape)? + rewrite_path(context, PathContext::Type, &None, &self.path, shape)? } ast::MetaItemKind::List(ref list) => { - let path = rewrite_path(context, PathContext::Type, None, &self.path, shape)?; + let path = rewrite_path(context, PathContext::Type, &None, &self.path, shape)?; let has_trailing_comma = crate::expr::span_ends_with_comma(context, self.span); overflow::rewrite_with_parens( context, @@ -311,7 +311,7 @@ impl Rewrite for ast::MetaItem { )? } ast::MetaItemKind::NameValue(ref literal) => { - let path = rewrite_path(context, PathContext::Type, None, &self.path, shape)?; + let path = rewrite_path(context, PathContext::Type, &None, &self.path, shape)?; // 3 = ` = ` let lit_shape = shape.shrink_left(path.len() + 3)?; // `rewrite_literal` returns `None` when `literal` exceeds max diff --git a/src/chains.rs b/src/chains.rs index fcc02eca42987..a1a73cf4bd570 100644 --- a/src/chains.rs +++ b/src/chains.rs @@ -145,8 +145,8 @@ impl ChainItemKind { fn from_ast(context: &RewriteContext<'_>, expr: &ast::Expr) -> (ChainItemKind, Span) { let (kind, span) = match expr.kind { - ast::ExprKind::MethodCall(ref segment, ref receiver, ref expressions, _) => { - let types = if let Some(ref generic_args) = segment.args { + ast::ExprKind::MethodCall(ref call) => { + let types = if let Some(ref generic_args) = call.seg.args { if let ast::GenericArgs::AngleBracketed(ref data) = **generic_args { data.args .iter() @@ -163,8 +163,8 @@ impl ChainItemKind { } else { vec![] }; - let span = mk_sp(receiver.span.hi(), expr.span.hi()); - let kind = ChainItemKind::MethodCall(segment.clone(), types, expressions.clone()); + let span = mk_sp(call.receiver.span.hi(), expr.span.hi()); + let kind = ChainItemKind::MethodCall(call.seg.clone(), types, call.args.clone()); (kind, span) } ast::ExprKind::Field(ref nested, field) => { @@ -400,9 +400,7 @@ impl Chain { // is a try! macro, we'll convert it to shorthand when the option is set. fn pop_expr_chain(expr: &ast::Expr, context: &RewriteContext<'_>) -> Option { match expr.kind { - ast::ExprKind::MethodCall(_, ref receiver, _, _) => { - Some(Self::convert_try(&receiver, context)) - } + ast::ExprKind::MethodCall(ref call) => Some(Self::convert_try(&call.receiver, context)), ast::ExprKind::Field(ref subexpr, _) | ast::ExprKind::Try(ref subexpr) | ast::ExprKind::Await(ref subexpr) => Some(Self::convert_try(subexpr, context)), diff --git a/src/closures.rs b/src/closures.rs index 88a6bebb68c84..423c3a997f53d 100644 --- a/src/closures.rs +++ b/src/closures.rs @@ -326,16 +326,16 @@ pub(crate) fn rewrite_last_closure( expr: &ast::Expr, shape: Shape, ) -> Option { - if let ast::ExprKind::Closure( - ref binder, - capture, - ref is_async, - movability, - ref fn_decl, - ref body, - _, - ) = expr.kind - { + if let ast::ExprKind::Closure(ref closure) = expr.kind { + let ast::Closure { + ref binder, + capture_clause, + ref asyncness, + movability, + ref fn_decl, + ref body, + fn_decl_span: _, + } = **closure; let body = match body.kind { ast::ExprKind::Block(ref block, _) if !is_unsafe_block(block) @@ -347,7 +347,15 @@ pub(crate) fn rewrite_last_closure( _ => body, }; let (prefix, extra_offset) = rewrite_closure_fn_decl( - binder, capture, is_async, movability, fn_decl, body, expr.span, context, shape, + binder, + capture_clause, + asyncness, + movability, + fn_decl, + body, + expr.span, + context, + shape, )?; // If the closure goes multi line before its body, do not overflow the closure. if prefix.contains('\n') { diff --git a/src/expr.rs b/src/expr.rs index b4f1a178dbf44..aba1c484bf1dd 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -116,7 +116,7 @@ pub(crate) fn format_expr( rewrite_struct_lit( context, path, - qself.as_ref(), + qself, fields, rest, &expr.attrs, @@ -169,7 +169,7 @@ pub(crate) fn format_expr( rewrite_match(context, cond, arms, shape, expr.span, &expr.attrs) } ast::ExprKind::Path(ref qself, ref path) => { - rewrite_path(context, PathContext::Expr, qself.as_ref(), path, shape) + rewrite_path(context, PathContext::Expr, qself, path, shape) } ast::ExprKind::Assign(ref lhs, ref rhs, _) => { rewrite_assignment(context, lhs, rhs, None, shape) @@ -203,16 +203,16 @@ pub(crate) fn format_expr( Some("yield".to_string()) } } - ast::ExprKind::Closure( - ref binder, - capture, - ref is_async, - movability, - ref fn_decl, - ref body, - _, - ) => closures::rewrite_closure( - binder, capture, is_async, movability, fn_decl, body, expr.span, context, shape, + ast::ExprKind::Closure(ref cl) => closures::rewrite_closure( + &cl.binder, + cl.capture_clause, + &cl.asyncness, + cl.movability, + &cl.fn_decl, + &cl.body, + expr.span, + context, + shape, ), ast::ExprKind::Try(..) | ast::ExprKind::Field(..) @@ -1537,7 +1537,7 @@ fn struct_lit_can_be_aligned(fields: &[ast::ExprField], has_base: bool) -> bool fn rewrite_struct_lit<'a>( context: &RewriteContext<'_>, path: &ast::Path, - qself: Option<&ast::QSelf>, + qself: &Option>, fields: &'a [ast::ExprField], struct_rest: &ast::StructRest, attrs: &[ast::Attribute], diff --git a/src/patterns.rs b/src/patterns.rs index e2fe92b28f23e..3f335172590ec 100644 --- a/src/patterns.rs +++ b/src/patterns.rs @@ -227,11 +227,10 @@ impl Rewrite for Pat { } PatKind::Tuple(ref items) => rewrite_tuple_pat(items, None, self.span, context, shape), PatKind::Path(ref q_self, ref path) => { - rewrite_path(context, PathContext::Expr, q_self.as_ref(), path, shape) + rewrite_path(context, PathContext::Expr, q_self, path, shape) } PatKind::TupleStruct(ref q_self, ref path, ref pat_vec) => { - let path_str = - rewrite_path(context, PathContext::Expr, q_self.as_ref(), path, shape)?; + let path_str = rewrite_path(context, PathContext::Expr, q_self, path, shape)?; rewrite_tuple_pat(pat_vec, Some(path_str), self.span, context, shape) } PatKind::Lit(ref expr) => expr.rewrite(context, shape), @@ -271,7 +270,7 @@ impl Rewrite for Pat { } fn rewrite_struct_pat( - qself: &Option, + qself: &Option>, path: &ast::Path, fields: &[ast::PatField], ellipsis: bool, @@ -281,7 +280,7 @@ fn rewrite_struct_pat( ) -> Option { // 2 = ` {` let path_shape = shape.sub_width(2)?; - let path_str = rewrite_path(context, PathContext::Expr, qself.as_ref(), path, path_shape)?; + let path_str = rewrite_path(context, PathContext::Expr, qself, path, path_shape)?; if fields.is_empty() && !ellipsis { return Some(format!("{} {{}}", path_str)); diff --git a/src/types.rs b/src/types.rs index 2627886db109d..d5177a2057b8a 100644 --- a/src/types.rs +++ b/src/types.rs @@ -38,11 +38,11 @@ pub(crate) enum PathContext { pub(crate) fn rewrite_path( context: &RewriteContext<'_>, path_context: PathContext, - qself: Option<&ast::QSelf>, + qself: &Option>, path: &ast::Path, shape: Shape, ) -> Option { - let skip_count = qself.map_or(0, |x| x.position); + let skip_count = qself.as_ref().map_or(0, |x| x.position); let mut result = if path.is_global() && qself.is_none() && path_context != PathContext::Import { "::".to_owned() @@ -655,7 +655,7 @@ impl Rewrite for ast::PolyTraitRef { impl Rewrite for ast::TraitRef { fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { - rewrite_path(context, PathContext::Type, None, &self.path, shape) + rewrite_path(context, PathContext::Type, &None, &self.path, shape) } } @@ -800,7 +800,7 @@ impl Rewrite for ast::Ty { rewrite_tuple(context, items.iter(), self.span, shape, items.len() == 1) } ast::TyKind::Path(ref q_self, ref path) => { - rewrite_path(context, PathContext::Type, q_self.as_ref(), path, shape) + rewrite_path(context, PathContext::Type, q_self, path, shape) } ast::TyKind::Array(ref ty, ref repeats) => rewrite_pair( &**ty, diff --git a/src/utils.rs b/src/utils.rs index c47b3b314dd4b..136a2c7fce24a 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -479,9 +479,9 @@ pub(crate) fn is_block_expr(context: &RewriteContext<'_>, expr: &ast::Expr, repr | ast::ExprKind::Binary(_, _, ref expr) | ast::ExprKind::Index(_, ref expr) | ast::ExprKind::Unary(_, ref expr) - | ast::ExprKind::Closure(_, _, _, _, _, ref expr, _) | ast::ExprKind::Try(ref expr) | ast::ExprKind::Yield(Some(ref expr)) => is_block_expr(context, expr, repr), + ast::ExprKind::Closure(ref closure) => is_block_expr(context, &closure.body, repr), // This can only be a string lit ast::ExprKind::Lit(_) => { repr.contains('\n') && trimmed_last_line_width(repr) <= context.config.tab_spaces() From 1343ffd564fbaed96e800a125e3d2b43de09beea Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Fri, 18 Nov 2022 11:24:21 +1100 Subject: [PATCH 53/69] Split `MacArgs` in two. `MacArgs` is an enum with three variants: `Empty`, `Delimited`, and `Eq`. It's used in two ways: - For representing attribute macro arguments (e.g. in `AttrItem`), where all three variants are used. - For representing function-like macros (e.g. in `MacCall` and `MacroDef`), where only the `Delimited` variant is used. In other words, `MacArgs` is used in two quite different places due to them having partial overlap. I find this makes the code hard to read. It also leads to various unreachable code paths, and allows invalid values (such as accidentally using `MacArgs::Empty` in a `MacCall`). This commit splits `MacArgs` in two: - `DelimArgs` is a new struct just for the "delimited arguments" case. It is now used in `MacCall` and `MacroDef`. - `AttrArgs` is a renaming of the old `MacArgs` enum for the attribute macro case. Its `Delimited` variant now contains a `DelimArgs`. Various other related things are renamed as well. These changes make the code clearer, avoids several unreachable paths, and disallows the invalid values. --- src/expr.rs | 2 +- src/macros.rs | 6 +++--- src/parse/macros/asm.rs | 2 +- src/parse/macros/cfg_if.rs | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/expr.rs b/src/expr.rs index aba1c484bf1dd..d5611082f0103 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -1341,7 +1341,7 @@ pub(crate) fn can_be_overflowed_expr( } ast::ExprKind::MacCall(ref mac) => { match ( - rustc_ast::ast::MacDelimiter::from_token(mac.args.delim().unwrap()), + rustc_ast::ast::MacDelimiter::from_token(mac.args.delim.to_token()), context.config.overflow_delimited_expr(), ) { (Some(ast::MacDelimiter::Bracket), true) diff --git a/src/macros.rs b/src/macros.rs index 3a641fab5d647..df94938803788 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -208,7 +208,7 @@ fn rewrite_macro_inner( original_style }; - let ts = mac.args.inner_tokens(); + let ts = mac.args.tokens.clone(); let has_comment = contains_comment(context.snippet(mac.span())); if ts.is_empty() && !has_comment { return match style { @@ -392,7 +392,7 @@ pub(crate) fn rewrite_macro_def( return snippet; } - let ts = def.body.inner_tokens(); + let ts = def.body.tokens.clone(); let mut parser = MacroParser::new(ts.into_trees()); let parsed_def = match parser.parse() { Some(def) => def, @@ -1087,7 +1087,7 @@ pub(crate) fn convert_try_mac( ) -> Option { let path = &pprust::path_to_string(&mac.path); if path == "try" || path == "r#try" { - let ts = mac.args.inner_tokens(); + let ts = mac.args.tokens.clone(); Some(ast::Expr { id: ast::NodeId::root(), // dummy value diff --git a/src/parse/macros/asm.rs b/src/parse/macros/asm.rs index cc9fb5072ce1e..01edfab36547c 100644 --- a/src/parse/macros/asm.rs +++ b/src/parse/macros/asm.rs @@ -5,7 +5,7 @@ use crate::rewrite::RewriteContext; #[allow(dead_code)] pub(crate) fn parse_asm(context: &RewriteContext<'_>, mac: &ast::MacCall) -> Option { - let ts = mac.args.inner_tokens(); + let ts = mac.args.tokens.clone(); let mut parser = super::build_parser(context, ts); parse_asm_args(&mut parser, context.parse_sess.inner(), mac.span(), false).ok() } diff --git a/src/parse/macros/cfg_if.rs b/src/parse/macros/cfg_if.rs index 09b3e32df312d..ace1a76b3fe7d 100644 --- a/src/parse/macros/cfg_if.rs +++ b/src/parse/macros/cfg_if.rs @@ -23,7 +23,7 @@ fn parse_cfg_if_inner<'a>( sess: &'a ParseSess, mac: &'a ast::MacCall, ) -> Result, &'static str> { - let ts = mac.args.inner_tokens(); + let ts = mac.args.tokens.clone(); let mut parser = build_stream_parser(sess.inner(), ts); let mut items = vec![]; From 3d44530eb081d6ffb45124bb25feb2738f6f09ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Thu, 3 Nov 2022 14:22:35 -0700 Subject: [PATCH 54/69] Fix rustfmt --- src/expr.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/expr.rs b/src/expr.rs index d5611082f0103..414e767690bd0 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -660,7 +660,7 @@ fn to_control_flow(expr: &ast::Expr, expr_type: ExprType) -> Option { Some(ControlFlow::new_for(pat, cond, block, label, expr.span)) } - ast::ExprKind::Loop(ref block, label) => { + ast::ExprKind::Loop(ref block, label, _) => { Some(ControlFlow::new_loop(block, label, expr.span)) } ast::ExprKind::While(ref cond, ref block, label) => { From cdff11ce94a6d70873920a4347de41adc5763d03 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Wed, 23 Nov 2022 15:39:42 +1100 Subject: [PATCH 55/69] Rename `ast::Lit` as `ast::MetaItemLit`. --- src/attr.rs | 11 ++++++++--- src/modules/visitor.rs | 12 ++++++++---- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/src/attr.rs b/src/attr.rs index 23f55db773e6c..8cba2a850e5bc 100644 --- a/src/attr.rs +++ b/src/attr.rs @@ -527,14 +527,19 @@ pub(crate) trait MetaVisitor<'ast> { fn visit_meta_word(&mut self, _meta_item: &'ast ast::MetaItem) {} - fn visit_meta_name_value(&mut self, _meta_item: &'ast ast::MetaItem, _lit: &'ast ast::Lit) {} + fn visit_meta_name_value( + &mut self, + _meta_item: &'ast ast::MetaItem, + _lit: &'ast ast::MetaItemLit, + ) { + } fn visit_nested_meta_item(&mut self, nm: &'ast ast::NestedMetaItem) { match nm { ast::NestedMetaItem::MetaItem(ref meta_item) => self.visit_meta_item(meta_item), - ast::NestedMetaItem::Literal(ref lit) => self.visit_literal(lit), + ast::NestedMetaItem::Literal(ref lit) => self.visit_meta_item_lit(lit), } } - fn visit_literal(&mut self, _lit: &'ast ast::Lit) {} + fn visit_meta_item_lit(&mut self, _lit: &'ast ast::MetaItemLit) {} } diff --git a/src/modules/visitor.rs b/src/modules/visitor.rs index ea67977c17a2b..48431693332a6 100644 --- a/src/modules/visitor.rs +++ b/src/modules/visitor.rs @@ -84,15 +84,19 @@ impl PathVisitor { } impl<'ast> MetaVisitor<'ast> for PathVisitor { - fn visit_meta_name_value(&mut self, meta_item: &'ast ast::MetaItem, lit: &'ast ast::Lit) { + fn visit_meta_name_value( + &mut self, + meta_item: &'ast ast::MetaItem, + lit: &'ast ast::MetaItemLit, + ) { if meta_item.has_name(Symbol::intern("path")) && lit.kind.is_str() { - self.paths.push(lit_to_str(lit)); + self.paths.push(meta_item_lit_to_str(lit)); } } } #[cfg(not(windows))] -fn lit_to_str(lit: &ast::Lit) -> String { +fn meta_item_lit_to_str(lit: &ast::MetaItemLit) -> String { match lit.kind { ast::LitKind::Str(symbol, ..) => symbol.to_string(), _ => unreachable!(), @@ -100,7 +104,7 @@ fn lit_to_str(lit: &ast::Lit) -> String { } #[cfg(windows)] -fn lit_to_str(lit: &ast::Lit) -> String { +fn meta_item_lit_to_str(lit: &ast::MetaItemLit) -> String { match lit.kind { ast::LitKind::Str(symbol, ..) => symbol.as_str().replace("/", "\\"), _ => unreachable!(), From c7e4abd44469d20fad3033608d7ece501609ed34 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Thu, 24 Nov 2022 15:00:09 +1100 Subject: [PATCH 56/69] Rename `NestedMetaItem::[Ll]iteral` as `NestedMetaItem::[Ll]it`. We already use a mix of `Literal` and `Lit`. The latter is better because it is shorter without causing any ambiguity. --- src/attr.rs | 6 ++---- src/overflow.rs | 4 ++-- src/utils.rs | 2 +- 3 files changed, 5 insertions(+), 7 deletions(-) diff --git a/src/attr.rs b/src/attr.rs index 8cba2a850e5bc..2ac703b957b86 100644 --- a/src/attr.rs +++ b/src/attr.rs @@ -260,9 +260,7 @@ impl Rewrite for ast::NestedMetaItem { fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { match self { ast::NestedMetaItem::MetaItem(ref meta_item) => meta_item.rewrite(context, shape), - ast::NestedMetaItem::Literal(ref l) => { - rewrite_literal(context, l.token_lit, l.span, shape) - } + ast::NestedMetaItem::Lit(ref l) => rewrite_literal(context, l.token_lit, l.span, shape), } } } @@ -537,7 +535,7 @@ pub(crate) trait MetaVisitor<'ast> { fn visit_nested_meta_item(&mut self, nm: &'ast ast::NestedMetaItem) { match nm { ast::NestedMetaItem::MetaItem(ref meta_item) => self.visit_meta_item(meta_item), - ast::NestedMetaItem::Literal(ref lit) => self.visit_meta_item_lit(lit), + ast::NestedMetaItem::Lit(ref lit) => self.visit_meta_item_lit(lit), } } diff --git a/src/overflow.rs b/src/overflow.rs index 6bf8cd0c70be0..af0b95430a197 100644 --- a/src/overflow.rs +++ b/src/overflow.rs @@ -125,7 +125,7 @@ impl<'a> OverflowableItem<'a> { OverflowableItem::MacroArg(MacroArg::Keyword(..)) => true, OverflowableItem::MacroArg(MacroArg::Expr(expr)) => is_simple_expr(expr), OverflowableItem::NestedMetaItem(nested_meta_item) => match nested_meta_item { - ast::NestedMetaItem::Literal(..) => true, + ast::NestedMetaItem::Lit(..) => true, ast::NestedMetaItem::MetaItem(ref meta_item) => { matches!(meta_item.kind, ast::MetaItemKind::Word) } @@ -169,7 +169,7 @@ impl<'a> OverflowableItem<'a> { }, OverflowableItem::NestedMetaItem(nested_meta_item) if len == 1 => { match nested_meta_item { - ast::NestedMetaItem::Literal(..) => false, + ast::NestedMetaItem::Lit(..) => false, ast::NestedMetaItem::MetaItem(..) => true, } } diff --git a/src/utils.rs b/src/utils.rs index 136a2c7fce24a..3e884419f1a32 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -263,7 +263,7 @@ fn is_skip(meta_item: &MetaItem) -> bool { fn is_skip_nested(meta_item: &NestedMetaItem) -> bool { match meta_item { NestedMetaItem::MetaItem(ref mi) => is_skip(mi), - NestedMetaItem::Literal(_) => false, + NestedMetaItem::Lit(_) => false, } } From 749c816faec774e7e7cae8ebad01d7ca0464b541 Mon Sep 17 00:00:00 2001 From: Sarthak Singh Date: Wed, 9 Nov 2022 20:39:28 +0530 Subject: [PATCH 57/69] Keep track of the start of the argument block of a closure --- src/closures.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/closures.rs b/src/closures.rs index 423c3a997f53d..244d4427c5623 100644 --- a/src/closures.rs +++ b/src/closures.rs @@ -335,6 +335,7 @@ pub(crate) fn rewrite_last_closure( ref fn_decl, ref body, fn_decl_span: _, + fn_arg_span: _, } = **closure; let body = match body.kind { ast::ExprKind::Block(ref block, _) From 46f0b38eb5f4965bd3230ceeba4a3ed7d0e5f68e Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Thu, 1 Dec 2022 18:51:20 +0300 Subject: [PATCH 58/69] rustc_ast_lowering: Stop lowering imports into multiple items Lower them into a single item with multiple resolutions instead. This also allows to remove additional `NodId`s and `DefId`s related to those additional items. --- src/imports.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/imports.rs b/src/imports.rs index b6530c69243ed..d9dc8d004aff4 100644 --- a/src/imports.rs +++ b/src/imports.rs @@ -490,7 +490,7 @@ impl UseTree { ); result.path.push(UseSegment { kind, version }); } - UseTreeKind::Simple(ref rename, ..) => { + UseTreeKind::Simple(ref rename) => { // If the path has leading double colons and is composed of only 2 segments, then we // bypass the call to path_to_imported_ident which would get only the ident and // lose the path root, e.g., `that` in `::that`. From c91dd22870d40315c3e0e5b45077516286e918fd Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Tue, 29 Nov 2022 13:36:00 +1100 Subject: [PATCH 59/69] Remove `token::Lit` from `ast::MetaItemLit`. `token::Lit` contains a `kind` field that indicates what kind of literal it is. `ast::MetaItemLit` currently wraps a `token::Lit` but also has its own `kind` field. This means that `ast::MetaItemLit` encodes the literal kind in two different ways. This commit changes `ast::MetaItemLit` so it no longer wraps `token::Lit`. It now contains the `symbol` and `suffix` fields from `token::Lit`, but not the `kind` field, eliminating the redundancy. --- src/attr.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/attr.rs b/src/attr.rs index 2ac703b957b86..c503eeeb9b3b9 100644 --- a/src/attr.rs +++ b/src/attr.rs @@ -260,7 +260,9 @@ impl Rewrite for ast::NestedMetaItem { fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option { match self { ast::NestedMetaItem::MetaItem(ref meta_item) => meta_item.rewrite(context, shape), - ast::NestedMetaItem::Lit(ref l) => rewrite_literal(context, l.token_lit, l.span, shape), + ast::NestedMetaItem::Lit(ref l) => { + rewrite_literal(context, l.as_token_lit(), l.span, shape) + } } } } @@ -308,18 +310,18 @@ impl Rewrite for ast::MetaItem { }), )? } - ast::MetaItemKind::NameValue(ref literal) => { + ast::MetaItemKind::NameValue(ref lit) => { let path = rewrite_path(context, PathContext::Type, &None, &self.path, shape)?; // 3 = ` = ` let lit_shape = shape.shrink_left(path.len() + 3)?; - // `rewrite_literal` returns `None` when `literal` exceeds max + // `rewrite_literal` returns `None` when `lit` exceeds max // width. Since a literal is basically unformattable unless it // is a string literal (and only if `format_strings` is set), // we might be better off ignoring the fact that the attribute // is longer than the max width and continue on formatting. // See #2479 for example. - let value = rewrite_literal(context, literal.token_lit, literal.span, lit_shape) - .unwrap_or_else(|| context.snippet(literal.span).to_owned()); + let value = rewrite_literal(context, lit.as_token_lit(), lit.span, lit_shape) + .unwrap_or_else(|| context.snippet(lit.span).to_owned()); format!("{} = {}", path, value) } }) From ac8eaa1ba7a5e6887b45bbd84d9a583fac6e39c9 Mon Sep 17 00:00:00 2001 From: Nilstrieb <48135649+Nilstrieb@users.noreply.github.com> Date: Wed, 28 Dec 2022 18:06:11 +0100 Subject: [PATCH 60/69] Rename `Rptr` to `Ref` in AST and HIR The name makes a lot more sense, and `ty::TyKind` calls it `Ref` already as well. --- src/types.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/types.rs b/src/types.rs index d5177a2057b8a..c1991e8d2c808 100644 --- a/src/types.rs +++ b/src/types.rs @@ -688,7 +688,7 @@ impl Rewrite for ast::Ty { rewrite_unary_prefix(context, prefix, &*mt.ty, shape) } - ast::TyKind::Rptr(ref lifetime, ref mt) => { + ast::TyKind::Ref(ref lifetime, ref mt) => { let mut_str = format_mutability(mt.mutbl); let mut_len = mut_str.len(); let mut result = String::with_capacity(128); @@ -1059,7 +1059,7 @@ pub(crate) fn can_be_overflowed_type( ) -> bool { match ty.kind { ast::TyKind::Tup(..) => context.use_block_indent() && len == 1, - ast::TyKind::Rptr(_, ref mutty) | ast::TyKind::Ptr(ref mutty) => { + ast::TyKind::Ref(_, ref mutty) | ast::TyKind::Ptr(ref mutty) => { can_be_overflowed_type(context, &*mutty.ty, len) } _ => false, From d7fa2ee3e6eae1a7fe4526249ce61caaa3d448d4 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Mon, 12 Dec 2022 19:37:28 +0000 Subject: [PATCH 61/69] Add missing extern crate rustc_driver --- src/lib.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 1d1ef525f23fa..0c27bcacfb83c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -24,6 +24,11 @@ extern crate rustc_parse; extern crate rustc_session; extern crate rustc_span; +// Necessary to pull in object code as the rest of the rustc crates are shipped only as rmeta +// files. +#[allow(unused_extern_crates)] +extern crate rustc_driver; + use std::cell::RefCell; use std::collections::HashMap; use std::fmt; From 664c60a18eb594ef22a31b7fa3a0dfb367cdd442 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Thu, 5 Jan 2023 21:29:36 +0000 Subject: [PATCH 62/69] Detect closures assigned to binding in block Fix #58497. --- tests/target/issue_4110.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/target/issue_4110.rs b/tests/target/issue_4110.rs index 4a58c3946e12d..d3734e90b7ffa 100644 --- a/tests/target/issue_4110.rs +++ b/tests/target/issue_4110.rs @@ -20,6 +20,7 @@ fn bindings() { category, span, &format!("`{}`", name), + "function", ), ( ref name, From 8c8aa3873f1c7177d532a6093da5e9836611ed4c Mon Sep 17 00:00:00 2001 From: Albert Larsan <74931857+albertlarsan68@users.noreply.github.com> Date: Thu, 5 Jan 2023 09:45:44 +0100 Subject: [PATCH 63/69] Change `src/test` to `tests` in source files, fix tidy and tests --- tests/source/issue-2445.rs | 4 ++-- tests/target/issue-2445.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/source/issue-2445.rs b/tests/source/issue-2445.rs index 84ce6e647b83c..deef429dbee08 100644 --- a/tests/source/issue-2445.rs +++ b/tests/source/issue-2445.rs @@ -1,6 +1,6 @@ test!(RunPassPretty { // comment - path: "src/test/run-pass/pretty", + path: "tests/run-pass/pretty", mode: "pretty", suite: "run-pass", default: false, @@ -9,7 +9,7 @@ test!(RunPassPretty { test!(RunPassPretty { // comment - path: "src/test/run-pass/pretty", + path: "tests/run-pass/pretty", mode: "pretty", suite: "run-pass", default: false, diff --git a/tests/target/issue-2445.rs b/tests/target/issue-2445.rs index 1bc7752fd1619..463c5d4957686 100644 --- a/tests/target/issue-2445.rs +++ b/tests/target/issue-2445.rs @@ -1,6 +1,6 @@ test!(RunPassPretty { // comment - path: "src/test/run-pass/pretty", + path: "tests/run-pass/pretty", mode: "pretty", suite: "run-pass", default: false, @@ -9,7 +9,7 @@ test!(RunPassPretty { test!(RunPassPretty { // comment - path: "src/test/run-pass/pretty", + path: "tests/run-pass/pretty", mode: "pretty", suite: "run-pass", default: false, From 19c2286d5c0fe45765cb6bd182b32722173b0942 Mon Sep 17 00:00:00 2001 From: Deadbeef Date: Tue, 20 Dec 2022 16:15:55 +0000 Subject: [PATCH 64/69] parse const closures --- src/closures.rs | 19 ++++++++++++++++--- src/expr.rs | 1 + 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/src/closures.rs b/src/closures.rs index 244d4427c5623..8fd0fcf8f5c2c 100644 --- a/src/closures.rs +++ b/src/closures.rs @@ -26,6 +26,7 @@ use crate::utils::{last_line_width, left_most_sub_expr, stmt_expr, NodeIdExt}; pub(crate) fn rewrite_closure( binder: &ast::ClosureBinder, + constness: ast::Const, capture: ast::CaptureBy, is_async: &ast::Async, movability: ast::Movability, @@ -38,7 +39,7 @@ pub(crate) fn rewrite_closure( debug!("rewrite_closure {:?}", body); let (prefix, extra_offset) = rewrite_closure_fn_decl( - binder, capture, is_async, movability, fn_decl, body, span, context, shape, + binder, constness, capture, is_async, movability, fn_decl, body, span, context, shape, )?; // 1 = space between `|...|` and body. let body_shape = shape.offset_left(extra_offset)?; @@ -230,6 +231,7 @@ fn rewrite_closure_block( // Return type is (prefix, extra_offset) fn rewrite_closure_fn_decl( binder: &ast::ClosureBinder, + constness: ast::Const, capture: ast::CaptureBy, asyncness: &ast::Async, movability: ast::Movability, @@ -250,6 +252,12 @@ fn rewrite_closure_fn_decl( ast::ClosureBinder::NotPresent => "".to_owned(), }; + let const_ = if matches!(constness, ast::Const::Yes(_)) { + "const " + } else { + "" + }; + let immovable = if movability == ast::Movability::Static { "static " } else { @@ -264,7 +272,7 @@ fn rewrite_closure_fn_decl( // 4 = "|| {".len(), which is overconservative when the closure consists of // a single expression. let nested_shape = shape - .shrink_left(binder.len() + immovable.len() + is_async.len() + mover.len())? + .shrink_left(binder.len() + const_.len() + immovable.len() + is_async.len() + mover.len())? .sub_width(4)?; // 1 = | @@ -302,7 +310,10 @@ fn rewrite_closure_fn_decl( .tactic(tactic) .preserve_newline(true); let list_str = write_list(&item_vec, &fmt)?; - let mut prefix = format!("{}{}{}{}|{}|", binder, immovable, is_async, mover, list_str); + let mut prefix = format!( + "{}{}{}{}{}|{}|", + binder, const_, immovable, is_async, mover, list_str + ); if !ret_str.is_empty() { if prefix.contains('\n') { @@ -329,6 +340,7 @@ pub(crate) fn rewrite_last_closure( if let ast::ExprKind::Closure(ref closure) = expr.kind { let ast::Closure { ref binder, + constness, capture_clause, ref asyncness, movability, @@ -349,6 +361,7 @@ pub(crate) fn rewrite_last_closure( }; let (prefix, extra_offset) = rewrite_closure_fn_decl( binder, + constness, capture_clause, asyncness, movability, diff --git a/src/expr.rs b/src/expr.rs index 414e767690bd0..868ff045ab78b 100644 --- a/src/expr.rs +++ b/src/expr.rs @@ -205,6 +205,7 @@ pub(crate) fn format_expr( } ast::ExprKind::Closure(ref cl) => closures::rewrite_closure( &cl.binder, + cl.constness, cl.capture_clause, &cl.asyncness, cl.movability, From aae222c974a982e878f279b95bd1a9d0166ff229 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Mon, 23 Jan 2023 10:54:05 -0600 Subject: [PATCH 65/69] fix: correct span for structs with const generics --- src/items.rs | 2 +- tests/target/issue_5668.rs | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) create mode 100644 tests/target/issue_5668.rs diff --git a/src/items.rs b/src/items.rs index 755a41f6bf0cd..063a6428a08f7 100644 --- a/src/items.rs +++ b/src/items.rs @@ -1245,7 +1245,7 @@ fn format_unit_struct( ) -> Option { let header_str = format_header(context, p.prefix, p.ident, p.vis, offset); let generics_str = if let Some(generics) = p.generics { - let hi = context.snippet_provider.span_before(p.span, ";"); + let hi = context.snippet_provider.span_before_last(p.span, ";"); format_generics( context, generics, diff --git a/tests/target/issue_5668.rs b/tests/target/issue_5668.rs new file mode 100644 index 0000000000000..bbd9a530b81c0 --- /dev/null +++ b/tests/target/issue_5668.rs @@ -0,0 +1,8 @@ +type Foo = impl Send; +struct Struct< + const C: usize = { + let _: Foo = (); + //~^ ERROR: mismatched types + 0 + }, +>; From 18dd0757dbef84611fc0f1f522b15913248b8541 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Mon, 23 Jan 2023 21:44:03 -0600 Subject: [PATCH 66/69] chore: bump toolchain --- rust-toolchain | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/rust-toolchain b/rust-toolchain index f8ed76d2e6f9e..22283b3d62002 100644 --- a/rust-toolchain +++ b/rust-toolchain @@ -1,3 +1,3 @@ [toolchain] -channel = "nightly-2022-08-06" -components = ["rustc-dev"] +channel = "nightly-2023-01-24" +components = ["llvm-tools", "rustc-dev"] From 5139b14620832d08a436ad85c1bef4037c36395b Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Tue, 24 Jan 2023 11:13:54 -0600 Subject: [PATCH 67/69] fix: version gate changes for multiline single generic bound --- src/types.rs | 23 ++++++++++++----------- tests/target/issue-4689/one.rs | 16 ++++++++-------- 2 files changed, 20 insertions(+), 19 deletions(-) diff --git a/src/types.rs b/src/types.rs index 2cae549810751..01e2fb6e61e15 100644 --- a/src/types.rs +++ b/src/types.rs @@ -1057,21 +1057,22 @@ fn join_bounds_inner( }, )?; - // Whether retry the function with forced newline is needed: + // Whether to retry with a forced newline: // Only if result is not already multiline and did not exceed line width, // and either there is more than one item; // or the single item is of type `Trait`, // and any of the internal arrays contains more than one item; - let retry_with_force_newline = - if force_newline || (!result.0.contains('\n') && result.0.len() <= shape.width) { - false - } else { - if items.len() > 1 { - true - } else { - is_item_with_multi_items_array(&items[0]) - } - }; + let retry_with_force_newline = match context.config.version() { + Version::One => { + !force_newline + && items.len() > 1 + && (result.0.contains('\n') || result.0.len() > shape.width) + } + Version::Two if force_newline => false, + Version::Two if (!result.0.contains('\n') && result.0.len() <= shape.width) => false, + Version::Two if items.len() > 1 => true, + Version::Two => is_item_with_multi_items_array(&items[0]), + }; if retry_with_force_newline { join_bounds_inner(context, shape, items, need_indent, true) diff --git a/tests/target/issue-4689/one.rs b/tests/target/issue-4689/one.rs index df1a507bc1da9..7735e34f3b5ed 100644 --- a/tests/target/issue-4689/one.rs +++ b/tests/target/issue-4689/one.rs @@ -3,14 +3,14 @@ // Based on the issue description pub trait PrettyPrinter<'tcx>: Printer< - 'tcx, - Error = fmt::Error, - Path = Self, - Region = Self, - Type = Self, - DynExistential = Self, - Const = Self, - > + 'tcx, + Error = fmt::Error, + Path = Self, + Region = Self, + Type = Self, + DynExistential = Self, + Const = Self, +> { // } From 1d8491b120223272b13451fc81265aa64f7f4d5b Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Tue, 24 Jan 2023 13:08:52 -0600 Subject: [PATCH 68/69] chore: prep v1.5.2 release --- CHANGELOG.md | 26 ++++++++++++++++++++++++++ Cargo.lock | 2 +- Cargo.toml | 2 +- 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e9ce930dabc68..60f961fa12ac8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,32 @@ ## [Unreleased] +## [1.5.2] 2023-01-24 + +### Fixed + +- Resolve issue when comments are found within const generic defaults in unit structs [#5668](https://github.com/rust-lang/rustfmt/issues/5668) +- Resolve issue when block comments are found within trait generics [#5358](https://github.com/rust-lang/rustfmt/issues/5358) +- Correctly handle alignment of comments containing unicode characters [#5504](https://github.com/rust-lang/rustfmt/issues/5504) +- Properly indent a single generic bound that requires being written across multiple lines [#4689](https://github.com/rust-lang/rustfmt/issues/4689) (n.b. this change is version gated and will only appear when the `version` configuration option is set to `Two`) + +### Changed + +- Renamed `fn_args_layout` configuration option to `fn_params_layout` [#4149](https://github.com/rust-lang/rustfmt/issues/4149). Note that `fn_args_layout` has only been soft deprecated: `fn_args_layout` will continue to work without issue, but rustfmt will display a warning to encourage users to switch to the new name + +### Added + +- New configuration option (`skip_macro_invocations`)[https://rust-lang.github.io/rustfmt/?version=master&search=#skip_macro_invocations] [#5347](https://github.com/rust-lang/rustfmt/pull/5347) that can be used to globally define a single enumerated list of macro calls that rustfmt should skip formatting. rustfmt [currently also supports this via a custom tool attribute](https://github.com/rust-lang/rustfmt#tips), however, these cannot be used in all contexts because [custom inner attributes are unstable](https://github.com/rust-lang/rust/issues/54726) + +### Misc + +- rustfmt now internally supports the ability to have both stable and unstable variants of a configuration option [#5378](https://github.com/rust-lang/rustfmt/issues/5378). This ability will allow the rustfmt team to make certain configuration options available on stable toolchains more quickly because we no longer have to wait for _every_ variant to be stable-ready before stabilizing _any_ variant. + +### Install/Download Options +- **rustup (nightly)** - nightly-2023-01-24 +- **GitHub Release Binaries** - [Release v1.5.2](https://github.com/rust-lang/rustfmt/releases/tag/v1.5.2) +- **Build from source** - [Tag v1.5.2](https://github.com/rust-lang/rustfmt/tree/v1.5.2), see instructions for how to [install rustfmt from source][install-from-source] + ## [1.5.1] 2022-06-24 **N.B** A bug was introduced in v1.5.0/nightly-2022-06-15 which modified formatting. If you happened to run rustfmt over your code with one of those ~10 nightlies it's possible you may have seen formatting changes, and you may see additional changes after this fix since that bug has now been reverted. diff --git a/Cargo.lock b/Cargo.lock index e51755289706c..24166d51c51fa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -485,7 +485,7 @@ dependencies = [ [[package]] name = "rustfmt-nightly" -version = "1.5.1" +version = "1.5.2" dependencies = [ "annotate-snippets", "anyhow", diff --git a/Cargo.toml b/Cargo.toml index 7438335eaa78f..87ce59d0217e8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "rustfmt-nightly" -version = "1.5.1" +version = "1.5.2" description = "Tool to find and fix Rust formatting issues" repository = "https://github.com/rust-lang/rustfmt" readme = "README.md" From 6bf1a87fcd45dbde0d8c69099a3ab74197bd2fc8 Mon Sep 17 00:00:00 2001 From: Caleb Cartwright Date: Tue, 24 Jan 2023 14:21:14 -0600 Subject: [PATCH 69/69] update rustfmt subtree version in lockfile --- Cargo.lock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8e1a3c57f0314..65571b1472f00 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4926,7 +4926,7 @@ dependencies = [ [[package]] name = "rustfmt-config_proc_macro" -version = "0.2.0" +version = "0.3.0" dependencies = [ "proc-macro2", "quote", @@ -4936,7 +4936,7 @@ dependencies = [ [[package]] name = "rustfmt-nightly" -version = "1.5.1" +version = "1.5.2" dependencies = [ "annotate-snippets", "anyhow",