From b31922cbec08ba96c71c1f84d6b909b019d8f762 Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Tue, 15 Sep 2026 08:55:04 +0200 Subject: [PATCH 01/56] feat(tree-sitter-compact): add declaration-level Compact grammar Adds a Cargo workspace and a tree-sitter grammar that resolves every Compact declaration to a named node while leaving bodies, parameter lists and expressions opaque. The grammar exists to feed a doc-comment linter, so precision stops at the declaration boundary and the full expression grammar is out of scope. * grammar: fourteen declaration kinds with `name` fields, recursive module bodies, three comment kinds as extras, structured type expressions so nested generic arguments resolve. * binding: native Rust binding, generated parser committed, CI fails when regeneration changes it. * tests: tree-sitter corpus plus a Rust corpus test that rejects any ERROR or MISSING node over the upstream formatter fixtures, the in-repo Compact sources, and an optional external tree. --- .github/workflows/rust.yml | 46 + Cargo.lock | 216 + Cargo.toml | 17 + biome.json | 1 + crates/tree-sitter-compact/Cargo.toml | 34 + crates/tree-sitter-compact/README.md | 88 + .../bindings/rust/build.rs | 19 + .../tree-sitter-compact/bindings/rust/lib.rs | 34 + crates/tree-sitter-compact/grammar.js | 256 + crates/tree-sitter-compact/package.json | 16 + .../queries/highlights.scm | 42 + crates/tree-sitter-compact/src/grammar.json | 1380 ++++ .../tree-sitter-compact/src/node-types.json | 913 +++ crates/tree-sitter-compact/src/parser.c | 7042 +++++++++++++++++ .../src/tree_sitter/alloc.h | 54 + .../src/tree_sitter/array.h | 291 + .../src/tree_sitter/parser.h | 286 + .../test/corpus/circuits-and-constructors.txt | 152 + .../test/corpus/comments.txt | 134 + .../test/corpus/imports.txt | 141 + .../test/corpus/modules-and-exports.txt | 116 + .../test/corpus/pragma-and-include.txt | 37 + .../test/corpus/structs-enums-contracts.txt | 105 + .../test/corpus/types-ledger-witness.txt | 149 + .../test/fixtures/upstream/NOTICE | 17 + .../upstream/already_formatted.compact | 26 + .../test/fixtures/upstream/example_1.compact | 34 + .../test/fixtures/upstream/example_10.compact | 62 + .../test/fixtures/upstream/example_11.compact | 32 + .../test/fixtures/upstream/example_12.compact | 36 + .../test/fixtures/upstream/example_13.compact | 185 + .../test/fixtures/upstream/example_2.compact | 40 + .../test/fixtures/upstream/example_3.compact | 41 + .../test/fixtures/upstream/example_4.compact | 32 + .../test/fixtures/upstream/example_5.compact | 34 + .../test/fixtures/upstream/example_6.compact | 31 + .../test/fixtures/upstream/example_7.compact | 32 + .../test/fixtures/upstream/example_8.compact | 43 + .../test/fixtures/upstream/example_9.compact | 34 + crates/tree-sitter-compact/tests/corpus.rs | 214 + crates/tree-sitter-compact/tree-sitter.json | 37 + rust-toolchain.toml | 3 + 42 files changed, 12502 insertions(+) create mode 100644 .github/workflows/rust.yml create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 crates/tree-sitter-compact/Cargo.toml create mode 100644 crates/tree-sitter-compact/README.md create mode 100644 crates/tree-sitter-compact/bindings/rust/build.rs create mode 100644 crates/tree-sitter-compact/bindings/rust/lib.rs create mode 100644 crates/tree-sitter-compact/grammar.js create mode 100644 crates/tree-sitter-compact/package.json create mode 100644 crates/tree-sitter-compact/queries/highlights.scm create mode 100644 crates/tree-sitter-compact/src/grammar.json create mode 100644 crates/tree-sitter-compact/src/node-types.json create mode 100644 crates/tree-sitter-compact/src/parser.c create mode 100644 crates/tree-sitter-compact/src/tree_sitter/alloc.h create mode 100644 crates/tree-sitter-compact/src/tree_sitter/array.h create mode 100644 crates/tree-sitter-compact/src/tree_sitter/parser.h create mode 100644 crates/tree-sitter-compact/test/corpus/circuits-and-constructors.txt create mode 100644 crates/tree-sitter-compact/test/corpus/comments.txt create mode 100644 crates/tree-sitter-compact/test/corpus/imports.txt create mode 100644 crates/tree-sitter-compact/test/corpus/modules-and-exports.txt create mode 100644 crates/tree-sitter-compact/test/corpus/pragma-and-include.txt create mode 100644 crates/tree-sitter-compact/test/corpus/structs-enums-contracts.txt create mode 100644 crates/tree-sitter-compact/test/corpus/types-ledger-witness.txt create mode 100644 crates/tree-sitter-compact/test/fixtures/upstream/NOTICE create mode 100644 crates/tree-sitter-compact/test/fixtures/upstream/already_formatted.compact create mode 100644 crates/tree-sitter-compact/test/fixtures/upstream/example_1.compact create mode 100644 crates/tree-sitter-compact/test/fixtures/upstream/example_10.compact create mode 100644 crates/tree-sitter-compact/test/fixtures/upstream/example_11.compact create mode 100644 crates/tree-sitter-compact/test/fixtures/upstream/example_12.compact create mode 100644 crates/tree-sitter-compact/test/fixtures/upstream/example_13.compact create mode 100644 crates/tree-sitter-compact/test/fixtures/upstream/example_2.compact create mode 100644 crates/tree-sitter-compact/test/fixtures/upstream/example_3.compact create mode 100644 crates/tree-sitter-compact/test/fixtures/upstream/example_4.compact create mode 100644 crates/tree-sitter-compact/test/fixtures/upstream/example_5.compact create mode 100644 crates/tree-sitter-compact/test/fixtures/upstream/example_6.compact create mode 100644 crates/tree-sitter-compact/test/fixtures/upstream/example_7.compact create mode 100644 crates/tree-sitter-compact/test/fixtures/upstream/example_8.compact create mode 100644 crates/tree-sitter-compact/test/fixtures/upstream/example_9.compact create mode 100644 crates/tree-sitter-compact/tests/corpus.rs create mode 100644 crates/tree-sitter-compact/tree-sitter.json create mode 100644 rust-toolchain.toml diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml new file mode 100644 index 00000000..2bc8283a --- /dev/null +++ b/.github/workflows/rust.yml @@ -0,0 +1,46 @@ +name: Rust + +on: + pull_request: + push: + branches: + - main + - beta + +jobs: + rust: + name: Run Rust Checks + runs-on: ubuntu-24.04 + + permissions: + contents: read + + steps: + - name: Harden Runner + uses: step-security/harden-runner@05e31511f85b41b11d1cf0ef85d0992719546e2c # v2.21.0 + with: + egress-policy: audit + + - name: Check out code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Install the pinned toolchain + run: | + rustup toolchain install 1.96 --profile minimal --component rustfmt --component clippy + rustup show active-toolchain + + - name: Check formatting + run: cargo fmt --all --check + + - name: Lint + run: cargo clippy --workspace --all-targets -- -D warnings + + - name: Test + run: cargo test --workspace + + - name: Check the generated parser is up to date + working-directory: crates/tree-sitter-compact + run: npx -y tree-sitter-cli@0.25.8 generate + + - name: Fail if regeneration changed the parser + run: git diff --exit-code -- crates/tree-sitter-compact/src diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 00000000..e78a9e5e --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,216 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "cc" +version = "1.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3eb0f42d6c360dc3f8a821f6bf2fdea7f72bfd36b3076eb0e6d1e9e0752fff4" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "find-msvc-tools" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e0f1c7c3a72c66fd80abe965175f7523475c0489a87d3ff9d6e8c87d87a9d2d" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "indexmap", + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b2231b7c3057d5e4ad0156fb3dc807d900806020c5ffa3ee6ff2c8c76fb8520" + +[[package]] +name = "syn" +version = "3.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12df2e0110f65b775f769bb17ef989067a1d931b2eb822bd4346631eeada89f9" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tree-sitter" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78f873475d258561b06f1c595d93308a7ed124d9977cb26b148c2084a4a3cc87" +dependencies = [ + "cc", + "regex", + "regex-syntax", + "serde_json", + "streaming-iterator", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-compact" +version = "0.1.0" +dependencies = [ + "cc", + "tree-sitter", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-language" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca0d1bf6fdd806e43ae5198f82f527056d359def39e54e67a0f478ac09dac081" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 00000000..af074357 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,17 @@ +[workspace] +resolver = "2" +members = ["crates/*"] + +[workspace.package] +edition = "2024" +license = "MIT" +repository = "https://github.com/OpenZeppelin/compact-tools" +rust-version = "1.96" + +[workspace.lints.clippy] +pedantic = { level = "warn", priority = -1 } + +[workspace.dependencies] +cc = "1" +tree-sitter = "0.25" +tree-sitter-language = "0.1" diff --git a/biome.json b/biome.json index 79dd4dbc..88b7ec77 100644 --- a/biome.json +++ b/biome.json @@ -13,6 +13,7 @@ "!**/tsconfig.base.json", "!**/tsconfig*.json", "!**/*.compact", + "!crates/tree-sitter-compact/src/**/*", "!**/artifacts/**/*", "!**/coverage/**/*", "!**/dist/**/*", diff --git a/crates/tree-sitter-compact/Cargo.toml b/crates/tree-sitter-compact/Cargo.toml new file mode 100644 index 00000000..3626181f --- /dev/null +++ b/crates/tree-sitter-compact/Cargo.toml @@ -0,0 +1,34 @@ +[package] +name = "tree-sitter-compact" +version = "0.1.0" +description = "Declaration-level Compact grammar for tree-sitter" +build = "bindings/rust/build.rs" +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +include = [ + "bindings/rust/*", + "grammar.js", + "queries/*", + "src/*", + "tree-sitter.json", + "LICENSE*", + "README.md", +] + +[lints] +workspace = true + +[lib] +path = "bindings/rust/lib.rs" + +[dependencies] +tree-sitter-language.workspace = true + +[build-dependencies] +cc.workspace = true + +[dev-dependencies] +tree-sitter.workspace = true diff --git a/crates/tree-sitter-compact/README.md b/crates/tree-sitter-compact/README.md new file mode 100644 index 00000000..287c198a --- /dev/null +++ b/crates/tree-sitter-compact/README.md @@ -0,0 +1,88 @@ +# tree-sitter-compact + +Declaration-level [tree-sitter](https://tree-sitter.github.io) grammar for the +Compact smart-contract language (Midnight), tracking language version 0.26. + +It exists to feed a doc-comment linter, so it resolves declarations precisely and +leaves everything else opaque. + +## What it covers + +- Every top-level and module-level declaration is a named node with a `name` + field: `pragma_declaration`, `include_declaration`, `import_declaration`, + `export_declaration`, `module_declaration`, `struct_declaration`, + `enum_declaration`, `contract_declaration`, `implements_declaration`, + `type_declaration`, `ledger_declaration`, `witness_declaration`, + `constructor_declaration`, `circuit_declaration`. +- `module_declaration` recurses: a `module_body` holds the same declarations. +- Comments are named nodes in `extras`: `line_comment`, `block_comment`, + `doc_comment`. +- Types are structured enough to walk: `type_expression`, `generic_arguments`, + `generic_parameters`, `generic_parameter`. +- All import forms: bare module, quoted path, generic arguments, `prefix`, and + the `{ a, b as c } from` selection. + +## What is opaque + +- Circuit and constructor bodies: `block` is a brace-balanced token run. Strings + and comments are lexed first, so braces inside them do not count. +- Struct, enum and external-contract bodies reuse the same `block`. +- Parameter lists: `parameter_list` is a paren-balanced run, so destructuring + patterns parse without a pattern grammar. +- Statements and expressions. There is no expression grammar and none is planned. +- Version expressions: `version_constraint` is one token that runs to the `;`. + +Angle brackets are balanced only inside `generic_arguments`, where a `>` always +closes a type-argument list. They are never balanced in opaque runs. + +## Modifiers + +`export`, `sealed`, `pure` and `new` stay anonymous keyword tokens directly under +the declaration node. A consumer tests for them by walking children and comparing +`node.kind()`: + +```rust +let exported = { + let mut cursor = declaration.walk(); + declaration + .children(&mut cursor) + .any(|child| child.kind() == "export") +}; +``` + +They are not fields, because a field would need a distinct name per modifier and +the linter only ever asks whether one is present. + +## Comment disambiguation + +`doc_comment` matches `/** … */` and outranks `block_comment` by lexical +precedence when both match the same span. `/**/` matches only `block_comment`, +since the doc pattern needs at least one `*` after the opener. + +## Regenerating the parser + +`src/parser.c`, `src/grammar.json`, `src/node-types.json` and `src/tree_sitter/*` +are generated and committed. After editing `grammar.js`: + +```sh +npx -y tree-sitter-cli@0.25.8 generate +``` + +CI regenerates and fails on any diff under `crates/tree-sitter-compact/src`. + +## Tests + +```sh +# Grammar corpus, run from this directory. +npx -y tree-sitter-cli@0.25.8 test + +# Rust bindings plus the fixture corpora. +cargo test --workspace + +# Add an external tree of .compact files. +COMPACT_CORPUS_DIR=/path/to/contracts cargo test --workspace -- --nocapture corpus +``` + +`tests/corpus.rs` asserts that no fixture produces an `ERROR` or `MISSING` node. +`test/fixtures/upstream/` holds the Compact formatter's own examples; see the +`NOTICE` beside them for provenance. diff --git a/crates/tree-sitter-compact/bindings/rust/build.rs b/crates/tree-sitter-compact/bindings/rust/build.rs new file mode 100644 index 00000000..c65afd8f --- /dev/null +++ b/crates/tree-sitter-compact/bindings/rust/build.rs @@ -0,0 +1,19 @@ +fn main() { + let src_dir = std::path::Path::new("src"); + + let mut config = cc::Build::new(); + config.std("c11").include(src_dir); + config.file(src_dir.join("parser.c")); + + // Generated code trips these on some compiler versions; they are not actionable here. + config.flag_if_supported("-Wno-unused-but-set-variable"); + config.flag_if_supported("-Wno-unused-parameter"); + config.flag_if_supported("-Wno-trigraphs"); + + config.compile("tree-sitter-compact"); + + println!("cargo:rerun-if-changed=src/parser.c"); + println!("cargo:rerun-if-changed=src/grammar.json"); + println!("cargo:rerun-if-changed=src/node-types.json"); + println!("cargo:rerun-if-changed=src/tree_sitter"); +} diff --git a/crates/tree-sitter-compact/bindings/rust/lib.rs b/crates/tree-sitter-compact/bindings/rust/lib.rs new file mode 100644 index 00000000..601c9741 --- /dev/null +++ b/crates/tree-sitter-compact/bindings/rust/lib.rs @@ -0,0 +1,34 @@ +//! Declaration-level tree-sitter grammar for Compact (Midnight). +//! +//! Declarations are named nodes with a `name` field; circuit and constructor +//! bodies, parameter lists and statements stay opaque brace-balanced runs. + +#![deny(unsafe_op_in_unsafe_fn)] + +use tree_sitter_language::LanguageFn; + +unsafe extern "C" { + fn tree_sitter_compact() -> *const (); +} + +/// The tree-sitter language for Compact. +// SAFETY: `tree_sitter_compact` is generated by tree-sitter-cli into `src/parser.c`, +// which `build.rs` links into this crate, and it returns a `'static` language pointer. +pub const LANGUAGE: LanguageFn = unsafe { LanguageFn::from_raw(tree_sitter_compact) }; + +/// The node-type metadata that tree-sitter-cli generated alongside the parser. +pub const NODE_TYPES: &str = include_str!("../../src/node-types.json"); + +/// The highlight query shipped with the grammar. +pub const HIGHLIGHTS_QUERY: &str = include_str!("../../queries/highlights.scm"); + +#[cfg(test)] +mod tests { + #[test] + fn language_loads_into_a_parser() { + let mut parser = tree_sitter::Parser::new(); + parser + .set_language(&super::LANGUAGE.into()) + .expect("the generated parser matches the tree-sitter ABI this crate builds against"); + } +} diff --git a/crates/tree-sitter-compact/grammar.js b/crates/tree-sitter-compact/grammar.js new file mode 100644 index 00000000..55c2d258 --- /dev/null +++ b/crates/tree-sitter-compact/grammar.js @@ -0,0 +1,256 @@ +/// +// @ts-check + +// Declaration-level grammar for Compact (Midnight), language version 0.26. +// Every top-level and module-level declaration is a named node carrying a `name` +// field; bodies, parameter lists and statements stay opaque brace-balanced runs. + +/** + * Comma-separated list with an optional trailing comma. + * @param {RuleOrLiteral} rule + */ +function commaSep(rule) { + return optional(seq(rule, repeat(seq(',', rule)), optional(','))); +} + +module.exports = grammar({ + name: 'compact', + + word: ($) => $.identifier, + + extras: ($) => [/\s/, $.doc_comment, $.block_comment, $.line_comment], + + rules: { + source_file: ($) => repeat($._declaration), + + _declaration: ($) => + choice( + $.pragma_declaration, + $.include_declaration, + $.import_declaration, + $.export_declaration, + $.module_declaration, + $.struct_declaration, + $.enum_declaration, + $.implements_declaration, + $.contract_declaration, + $.type_declaration, + $.ledger_declaration, + $.witness_declaration, + $.constructor_declaration, + $.circuit_declaration, + ), + + // pragma id version-expr ; + pragma_declaration: ($) => + seq('pragma', field('name', $.identifier), $.version_constraint, ';'), + + // Version expressions are not modelled; the run stops at the terminating `;`. + version_constraint: (_$) => token(/[^;{}\r\n]+/), + + // include "file" ; + include_declaration: ($) => seq('include', field('path', $.string), ';'), + + // import {sel} from? name gargs? prefix? ; + import_declaration: ($) => + seq( + 'import', + optional($.import_selection), + field('name', choice($.identifier, $.string)), + optional($.generic_arguments), + optional($.import_prefix), + ';', + ), + + import_selection: ($) => seq('{', commaSep($.import_element), '}', 'from'), + + import_element: ($) => + seq( + field('name', $.identifier), + optional(seq('as', field('alias', $.identifier))), + ), + + import_prefix: ($) => seq('prefix', field('prefix', $.identifier)), + + // export { id, ... } ;? + export_declaration: ($) => + seq('export', '{', commaSep($.identifier), '}', optional(';')), + + // export? module Name gparams? { declaration... } + module_declaration: ($) => + seq( + optional('export'), + 'module', + field('name', $.identifier), + optional($.generic_parameters), + field('body', $.module_body), + ), + + module_body: ($) => seq('{', repeat($._declaration), '}'), + + // export? struct Name gparams? { typed-id... } ;? + struct_declaration: ($) => + seq( + optional('export'), + 'struct', + field('name', $.identifier), + optional($.generic_parameters), + field('body', $.block), + optional(';'), + ), + + // export? enum Name { id, ... } ;? + enum_declaration: ($) => + seq( + optional('export'), + 'enum', + field('name', $.identifier), + field('body', $.block), + optional(';'), + ), + + // contract implements type ; + implements_declaration: ($) => + seq('contract', 'implements', field('type', $.type_expression), ';'), + + // export? contract Name { circuit-declaration... } ;? + contract_declaration: ($) => + seq( + optional('export'), + 'contract', + field('name', $.identifier), + field('body', $.block), + optional(';'), + ), + + // export? new? type Name gparams? = type ; + type_declaration: ($) => + seq( + optional('export'), + optional('new'), + 'type', + field('name', $.identifier), + optional($.generic_parameters), + '=', + field('value', $.type_expression), + ';', + ), + + // export? sealed? ledger id : type ; + ledger_declaration: ($) => + seq( + optional('export'), + optional('sealed'), + 'ledger', + field('name', $.identifier), + ':', + field('type', $.type_expression), + ';', + ), + + // export? witness id gparams? (params) : type ; + witness_declaration: ($) => + seq( + optional('export'), + 'witness', + field('name', $.identifier), + optional($.generic_parameters), + field('parameters', $.parameter_list), + ':', + field('type', $.type_expression), + ';', + ), + + // constructor (params) block + constructor_declaration: ($) => + seq( + 'constructor', + field('parameters', $.parameter_list), + field('body', $.block), + ), + + // export? pure? circuit name gparams? (params) : type block + circuit_declaration: ($) => + seq( + optional('export'), + optional('pure'), + 'circuit', + field('name', $.identifier), + optional($.generic_parameters), + field('parameters', $.parameter_list), + ':', + field('type', $.type_expression), + field('body', $.block), + ), + + // <#T, U,> + generic_parameters: ($) => seq('<', commaSep($.generic_parameter), '>'), + + generic_parameter: ($) => seq(optional('#'), field('name', $.identifier)), + + // Angle brackets nest only here, where a `>` always closes a type argument list. + generic_arguments: ($) => seq('<', repeat($._type_item), '>'), + + type_expression: ($) => repeat1($._type_item), + + _type_item: ($) => + choice( + $.identifier, + $.number, + $.string, + $.generic_arguments, + $._tuple_type, + ',', + ':', + '..', + ), + + _tuple_type: ($) => seq('[', repeat($._type_item), ']'), + + // Brace-balanced opaque run: circuit and constructor bodies, struct, enum and + // external-contract bodies, and destructuring patterns inside parameter lists. + block: ($) => seq('{', repeat($._opaque), '}'), + + parameter_list: ($) => seq('(', repeat($._opaque), ')'), + + _paren_group: ($) => seq('(', repeat($._opaque), ')'), + + _bracket_group: ($) => seq('[', repeat($._opaque), ']'), + + _opaque: ($) => + choice( + $.block, + $._paren_group, + $._bracket_group, + $.string, + $._opaque_token, + '/', + ), + + // Anything that is not a delimiter, a quote or a comment opener. + // biome-ignore lint/complexity/noUselessEscapeInRegex: tree-sitter's regex engine rejects an unescaped `[` in a class. + _opaque_token: (_$) => token(/[^\s(){}\[\]"'\/]+/), + + identifier: (_$) => /[A-Za-z_$][A-Za-z0-9_$]*/, + + number: (_$) => /[0-9]+/, + + // Double-quoted literals span lines; the Compact formatter emits them that way. + string: (_$) => + token( + choice( + seq('"', repeat(choice(/[^"\\]/, /\\(.|\r?\n)/)), '"'), + seq("'", repeat(choice(/[^'\\\r\n]/, /\\./)), "'"), + ), + ), + + // `/** ... */` outranks `/* ... */` at equal length; `/**/` matches only the latter. + doc_comment: (_$) => + token(prec(2, seq('/**', /[^*]*\*+([^/*][^*]*\*+)*/, '/'))), + + block_comment: (_$) => + token(prec(1, seq('/*', /[^*]*\*+([^/*][^*]*\*+)*/, '/'))), + + line_comment: (_$) => token(seq('//', /[^\r\n]*/)), + }, +}); diff --git a/crates/tree-sitter-compact/package.json b/crates/tree-sitter-compact/package.json new file mode 100644 index 00000000..7f85f180 --- /dev/null +++ b/crates/tree-sitter-compact/package.json @@ -0,0 +1,16 @@ +{ + "name": "tree-sitter-compact", + "version": "0.1.0", + "private": true, + "description": "Declaration-level Compact grammar for tree-sitter", + "license": "MIT", + "main": "grammar.js", + "tree-sitter": [ + { + "scope": "source.compact", + "file-types": [ + "compact" + ] + } + ] +} diff --git a/crates/tree-sitter-compact/queries/highlights.scm b/crates/tree-sitter-compact/queries/highlights.scm new file mode 100644 index 00000000..da7e44b2 --- /dev/null +++ b/crates/tree-sitter-compact/queries/highlights.scm @@ -0,0 +1,42 @@ +; Declaration names. +(pragma_declaration name: (identifier) @variable.builtin) +(module_declaration name: (identifier) @type) +(struct_declaration name: (identifier) @type) +(enum_declaration name: (identifier) @type) +(contract_declaration name: (identifier) @type) +(type_declaration name: (identifier) @type) +(circuit_declaration name: (identifier) @function) +(witness_declaration name: (identifier) @function) +(ledger_declaration name: (identifier) @property) +(generic_parameter name: (identifier) @type.parameter) + +; Keywords and modifiers. +[ + "pragma" + "include" + "import" + "export" + "from" + "as" + "prefix" + "module" + "struct" + "enum" + "contract" + "implements" + "type" + "new" + "sealed" + "ledger" + "witness" + "constructor" + "circuit" + "pure" +] @keyword + +(string) @string +(number) @number + +(line_comment) @comment +(block_comment) @comment +(doc_comment) @comment.documentation diff --git a/crates/tree-sitter-compact/src/grammar.json b/crates/tree-sitter-compact/src/grammar.json new file mode 100644 index 00000000..7bc3a421 --- /dev/null +++ b/crates/tree-sitter-compact/src/grammar.json @@ -0,0 +1,1380 @@ +{ + "$schema": "https://tree-sitter.github.io/tree-sitter/assets/schemas/grammar.schema.json", + "name": "compact", + "word": "identifier", + "rules": { + "source_file": { + "type": "REPEAT", + "content": { + "type": "SYMBOL", + "name": "_declaration" + } + }, + "_declaration": { + "type": "CHOICE", + "members": [ + { + "type": "SYMBOL", + "name": "pragma_declaration" + }, + { + "type": "SYMBOL", + "name": "include_declaration" + }, + { + "type": "SYMBOL", + "name": "import_declaration" + }, + { + "type": "SYMBOL", + "name": "export_declaration" + }, + { + "type": "SYMBOL", + "name": "module_declaration" + }, + { + "type": "SYMBOL", + "name": "struct_declaration" + }, + { + "type": "SYMBOL", + "name": "enum_declaration" + }, + { + "type": "SYMBOL", + "name": "implements_declaration" + }, + { + "type": "SYMBOL", + "name": "contract_declaration" + }, + { + "type": "SYMBOL", + "name": "type_declaration" + }, + { + "type": "SYMBOL", + "name": "ledger_declaration" + }, + { + "type": "SYMBOL", + "name": "witness_declaration" + }, + { + "type": "SYMBOL", + "name": "constructor_declaration" + }, + { + "type": "SYMBOL", + "name": "circuit_declaration" + } + ] + }, + "pragma_declaration": { + "type": "SEQ", + "members": [ + { + "type": "STRING", + "value": "pragma" + }, + { + "type": "FIELD", + "name": "name", + "content": { + "type": "SYMBOL", + "name": "identifier" + } + }, + { + "type": "SYMBOL", + "name": "version_constraint" + }, + { + "type": "STRING", + "value": ";" + } + ] + }, + "version_constraint": { + "type": "TOKEN", + "content": { + "type": "PATTERN", + "value": "[^;{}\\r\\n]+" + } + }, + "include_declaration": { + "type": "SEQ", + "members": [ + { + "type": "STRING", + "value": "include" + }, + { + "type": "FIELD", + "name": "path", + "content": { + "type": "SYMBOL", + "name": "string" + } + }, + { + "type": "STRING", + "value": ";" + } + ] + }, + "import_declaration": { + "type": "SEQ", + "members": [ + { + "type": "STRING", + "value": "import" + }, + { + "type": "CHOICE", + "members": [ + { + "type": "SYMBOL", + "name": "import_selection" + }, + { + "type": "BLANK" + } + ] + }, + { + "type": "FIELD", + "name": "name", + "content": { + "type": "CHOICE", + "members": [ + { + "type": "SYMBOL", + "name": "identifier" + }, + { + "type": "SYMBOL", + "name": "string" + } + ] + } + }, + { + "type": "CHOICE", + "members": [ + { + "type": "SYMBOL", + "name": "generic_arguments" + }, + { + "type": "BLANK" + } + ] + }, + { + "type": "CHOICE", + "members": [ + { + "type": "SYMBOL", + "name": "import_prefix" + }, + { + "type": "BLANK" + } + ] + }, + { + "type": "STRING", + "value": ";" + } + ] + }, + "import_selection": { + "type": "SEQ", + "members": [ + { + "type": "STRING", + "value": "{" + }, + { + "type": "CHOICE", + "members": [ + { + "type": "SEQ", + "members": [ + { + "type": "SYMBOL", + "name": "import_element" + }, + { + "type": "REPEAT", + "content": { + "type": "SEQ", + "members": [ + { + "type": "STRING", + "value": "," + }, + { + "type": "SYMBOL", + "name": "import_element" + } + ] + } + }, + { + "type": "CHOICE", + "members": [ + { + "type": "STRING", + "value": "," + }, + { + "type": "BLANK" + } + ] + } + ] + }, + { + "type": "BLANK" + } + ] + }, + { + "type": "STRING", + "value": "}" + }, + { + "type": "STRING", + "value": "from" + } + ] + }, + "import_element": { + "type": "SEQ", + "members": [ + { + "type": "FIELD", + "name": "name", + "content": { + "type": "SYMBOL", + "name": "identifier" + } + }, + { + "type": "CHOICE", + "members": [ + { + "type": "SEQ", + "members": [ + { + "type": "STRING", + "value": "as" + }, + { + "type": "FIELD", + "name": "alias", + "content": { + "type": "SYMBOL", + "name": "identifier" + } + } + ] + }, + { + "type": "BLANK" + } + ] + } + ] + }, + "import_prefix": { + "type": "SEQ", + "members": [ + { + "type": "STRING", + "value": "prefix" + }, + { + "type": "FIELD", + "name": "prefix", + "content": { + "type": "SYMBOL", + "name": "identifier" + } + } + ] + }, + "export_declaration": { + "type": "SEQ", + "members": [ + { + "type": "STRING", + "value": "export" + }, + { + "type": "STRING", + "value": "{" + }, + { + "type": "CHOICE", + "members": [ + { + "type": "SEQ", + "members": [ + { + "type": "SYMBOL", + "name": "identifier" + }, + { + "type": "REPEAT", + "content": { + "type": "SEQ", + "members": [ + { + "type": "STRING", + "value": "," + }, + { + "type": "SYMBOL", + "name": "identifier" + } + ] + } + }, + { + "type": "CHOICE", + "members": [ + { + "type": "STRING", + "value": "," + }, + { + "type": "BLANK" + } + ] + } + ] + }, + { + "type": "BLANK" + } + ] + }, + { + "type": "STRING", + "value": "}" + }, + { + "type": "CHOICE", + "members": [ + { + "type": "STRING", + "value": ";" + }, + { + "type": "BLANK" + } + ] + } + ] + }, + "module_declaration": { + "type": "SEQ", + "members": [ + { + "type": "CHOICE", + "members": [ + { + "type": "STRING", + "value": "export" + }, + { + "type": "BLANK" + } + ] + }, + { + "type": "STRING", + "value": "module" + }, + { + "type": "FIELD", + "name": "name", + "content": { + "type": "SYMBOL", + "name": "identifier" + } + }, + { + "type": "CHOICE", + "members": [ + { + "type": "SYMBOL", + "name": "generic_parameters" + }, + { + "type": "BLANK" + } + ] + }, + { + "type": "FIELD", + "name": "body", + "content": { + "type": "SYMBOL", + "name": "module_body" + } + } + ] + }, + "module_body": { + "type": "SEQ", + "members": [ + { + "type": "STRING", + "value": "{" + }, + { + "type": "REPEAT", + "content": { + "type": "SYMBOL", + "name": "_declaration" + } + }, + { + "type": "STRING", + "value": "}" + } + ] + }, + "struct_declaration": { + "type": "SEQ", + "members": [ + { + "type": "CHOICE", + "members": [ + { + "type": "STRING", + "value": "export" + }, + { + "type": "BLANK" + } + ] + }, + { + "type": "STRING", + "value": "struct" + }, + { + "type": "FIELD", + "name": "name", + "content": { + "type": "SYMBOL", + "name": "identifier" + } + }, + { + "type": "CHOICE", + "members": [ + { + "type": "SYMBOL", + "name": "generic_parameters" + }, + { + "type": "BLANK" + } + ] + }, + { + "type": "FIELD", + "name": "body", + "content": { + "type": "SYMBOL", + "name": "block" + } + }, + { + "type": "CHOICE", + "members": [ + { + "type": "STRING", + "value": ";" + }, + { + "type": "BLANK" + } + ] + } + ] + }, + "enum_declaration": { + "type": "SEQ", + "members": [ + { + "type": "CHOICE", + "members": [ + { + "type": "STRING", + "value": "export" + }, + { + "type": "BLANK" + } + ] + }, + { + "type": "STRING", + "value": "enum" + }, + { + "type": "FIELD", + "name": "name", + "content": { + "type": "SYMBOL", + "name": "identifier" + } + }, + { + "type": "FIELD", + "name": "body", + "content": { + "type": "SYMBOL", + "name": "block" + } + }, + { + "type": "CHOICE", + "members": [ + { + "type": "STRING", + "value": ";" + }, + { + "type": "BLANK" + } + ] + } + ] + }, + "implements_declaration": { + "type": "SEQ", + "members": [ + { + "type": "STRING", + "value": "contract" + }, + { + "type": "STRING", + "value": "implements" + }, + { + "type": "FIELD", + "name": "type", + "content": { + "type": "SYMBOL", + "name": "type_expression" + } + }, + { + "type": "STRING", + "value": ";" + } + ] + }, + "contract_declaration": { + "type": "SEQ", + "members": [ + { + "type": "CHOICE", + "members": [ + { + "type": "STRING", + "value": "export" + }, + { + "type": "BLANK" + } + ] + }, + { + "type": "STRING", + "value": "contract" + }, + { + "type": "FIELD", + "name": "name", + "content": { + "type": "SYMBOL", + "name": "identifier" + } + }, + { + "type": "FIELD", + "name": "body", + "content": { + "type": "SYMBOL", + "name": "block" + } + }, + { + "type": "CHOICE", + "members": [ + { + "type": "STRING", + "value": ";" + }, + { + "type": "BLANK" + } + ] + } + ] + }, + "type_declaration": { + "type": "SEQ", + "members": [ + { + "type": "CHOICE", + "members": [ + { + "type": "STRING", + "value": "export" + }, + { + "type": "BLANK" + } + ] + }, + { + "type": "CHOICE", + "members": [ + { + "type": "STRING", + "value": "new" + }, + { + "type": "BLANK" + } + ] + }, + { + "type": "STRING", + "value": "type" + }, + { + "type": "FIELD", + "name": "name", + "content": { + "type": "SYMBOL", + "name": "identifier" + } + }, + { + "type": "CHOICE", + "members": [ + { + "type": "SYMBOL", + "name": "generic_parameters" + }, + { + "type": "BLANK" + } + ] + }, + { + "type": "STRING", + "value": "=" + }, + { + "type": "FIELD", + "name": "value", + "content": { + "type": "SYMBOL", + "name": "type_expression" + } + }, + { + "type": "STRING", + "value": ";" + } + ] + }, + "ledger_declaration": { + "type": "SEQ", + "members": [ + { + "type": "CHOICE", + "members": [ + { + "type": "STRING", + "value": "export" + }, + { + "type": "BLANK" + } + ] + }, + { + "type": "CHOICE", + "members": [ + { + "type": "STRING", + "value": "sealed" + }, + { + "type": "BLANK" + } + ] + }, + { + "type": "STRING", + "value": "ledger" + }, + { + "type": "FIELD", + "name": "name", + "content": { + "type": "SYMBOL", + "name": "identifier" + } + }, + { + "type": "STRING", + "value": ":" + }, + { + "type": "FIELD", + "name": "type", + "content": { + "type": "SYMBOL", + "name": "type_expression" + } + }, + { + "type": "STRING", + "value": ";" + } + ] + }, + "witness_declaration": { + "type": "SEQ", + "members": [ + { + "type": "CHOICE", + "members": [ + { + "type": "STRING", + "value": "export" + }, + { + "type": "BLANK" + } + ] + }, + { + "type": "STRING", + "value": "witness" + }, + { + "type": "FIELD", + "name": "name", + "content": { + "type": "SYMBOL", + "name": "identifier" + } + }, + { + "type": "CHOICE", + "members": [ + { + "type": "SYMBOL", + "name": "generic_parameters" + }, + { + "type": "BLANK" + } + ] + }, + { + "type": "FIELD", + "name": "parameters", + "content": { + "type": "SYMBOL", + "name": "parameter_list" + } + }, + { + "type": "STRING", + "value": ":" + }, + { + "type": "FIELD", + "name": "type", + "content": { + "type": "SYMBOL", + "name": "type_expression" + } + }, + { + "type": "STRING", + "value": ";" + } + ] + }, + "constructor_declaration": { + "type": "SEQ", + "members": [ + { + "type": "STRING", + "value": "constructor" + }, + { + "type": "FIELD", + "name": "parameters", + "content": { + "type": "SYMBOL", + "name": "parameter_list" + } + }, + { + "type": "FIELD", + "name": "body", + "content": { + "type": "SYMBOL", + "name": "block" + } + } + ] + }, + "circuit_declaration": { + "type": "SEQ", + "members": [ + { + "type": "CHOICE", + "members": [ + { + "type": "STRING", + "value": "export" + }, + { + "type": "BLANK" + } + ] + }, + { + "type": "CHOICE", + "members": [ + { + "type": "STRING", + "value": "pure" + }, + { + "type": "BLANK" + } + ] + }, + { + "type": "STRING", + "value": "circuit" + }, + { + "type": "FIELD", + "name": "name", + "content": { + "type": "SYMBOL", + "name": "identifier" + } + }, + { + "type": "CHOICE", + "members": [ + { + "type": "SYMBOL", + "name": "generic_parameters" + }, + { + "type": "BLANK" + } + ] + }, + { + "type": "FIELD", + "name": "parameters", + "content": { + "type": "SYMBOL", + "name": "parameter_list" + } + }, + { + "type": "STRING", + "value": ":" + }, + { + "type": "FIELD", + "name": "type", + "content": { + "type": "SYMBOL", + "name": "type_expression" + } + }, + { + "type": "FIELD", + "name": "body", + "content": { + "type": "SYMBOL", + "name": "block" + } + } + ] + }, + "generic_parameters": { + "type": "SEQ", + "members": [ + { + "type": "STRING", + "value": "<" + }, + { + "type": "CHOICE", + "members": [ + { + "type": "SEQ", + "members": [ + { + "type": "SYMBOL", + "name": "generic_parameter" + }, + { + "type": "REPEAT", + "content": { + "type": "SEQ", + "members": [ + { + "type": "STRING", + "value": "," + }, + { + "type": "SYMBOL", + "name": "generic_parameter" + } + ] + } + }, + { + "type": "CHOICE", + "members": [ + { + "type": "STRING", + "value": "," + }, + { + "type": "BLANK" + } + ] + } + ] + }, + { + "type": "BLANK" + } + ] + }, + { + "type": "STRING", + "value": ">" + } + ] + }, + "generic_parameter": { + "type": "SEQ", + "members": [ + { + "type": "CHOICE", + "members": [ + { + "type": "STRING", + "value": "#" + }, + { + "type": "BLANK" + } + ] + }, + { + "type": "FIELD", + "name": "name", + "content": { + "type": "SYMBOL", + "name": "identifier" + } + } + ] + }, + "generic_arguments": { + "type": "SEQ", + "members": [ + { + "type": "STRING", + "value": "<" + }, + { + "type": "REPEAT", + "content": { + "type": "SYMBOL", + "name": "_type_item" + } + }, + { + "type": "STRING", + "value": ">" + } + ] + }, + "type_expression": { + "type": "REPEAT1", + "content": { + "type": "SYMBOL", + "name": "_type_item" + } + }, + "_type_item": { + "type": "CHOICE", + "members": [ + { + "type": "SYMBOL", + "name": "identifier" + }, + { + "type": "SYMBOL", + "name": "number" + }, + { + "type": "SYMBOL", + "name": "string" + }, + { + "type": "SYMBOL", + "name": "generic_arguments" + }, + { + "type": "SYMBOL", + "name": "_tuple_type" + }, + { + "type": "STRING", + "value": "," + }, + { + "type": "STRING", + "value": ":" + }, + { + "type": "STRING", + "value": ".." + } + ] + }, + "_tuple_type": { + "type": "SEQ", + "members": [ + { + "type": "STRING", + "value": "[" + }, + { + "type": "REPEAT", + "content": { + "type": "SYMBOL", + "name": "_type_item" + } + }, + { + "type": "STRING", + "value": "]" + } + ] + }, + "block": { + "type": "SEQ", + "members": [ + { + "type": "STRING", + "value": "{" + }, + { + "type": "REPEAT", + "content": { + "type": "SYMBOL", + "name": "_opaque" + } + }, + { + "type": "STRING", + "value": "}" + } + ] + }, + "parameter_list": { + "type": "SEQ", + "members": [ + { + "type": "STRING", + "value": "(" + }, + { + "type": "REPEAT", + "content": { + "type": "SYMBOL", + "name": "_opaque" + } + }, + { + "type": "STRING", + "value": ")" + } + ] + }, + "_paren_group": { + "type": "SEQ", + "members": [ + { + "type": "STRING", + "value": "(" + }, + { + "type": "REPEAT", + "content": { + "type": "SYMBOL", + "name": "_opaque" + } + }, + { + "type": "STRING", + "value": ")" + } + ] + }, + "_bracket_group": { + "type": "SEQ", + "members": [ + { + "type": "STRING", + "value": "[" + }, + { + "type": "REPEAT", + "content": { + "type": "SYMBOL", + "name": "_opaque" + } + }, + { + "type": "STRING", + "value": "]" + } + ] + }, + "_opaque": { + "type": "CHOICE", + "members": [ + { + "type": "SYMBOL", + "name": "block" + }, + { + "type": "SYMBOL", + "name": "_paren_group" + }, + { + "type": "SYMBOL", + "name": "_bracket_group" + }, + { + "type": "SYMBOL", + "name": "string" + }, + { + "type": "SYMBOL", + "name": "_opaque_token" + }, + { + "type": "STRING", + "value": "/" + } + ] + }, + "_opaque_token": { + "type": "TOKEN", + "content": { + "type": "PATTERN", + "value": "[^\\s(){}\\[\\]\"'\\/]+" + } + }, + "identifier": { + "type": "PATTERN", + "value": "[A-Za-z_$][A-Za-z0-9_$]*" + }, + "number": { + "type": "PATTERN", + "value": "[0-9]+" + }, + "string": { + "type": "TOKEN", + "content": { + "type": "CHOICE", + "members": [ + { + "type": "SEQ", + "members": [ + { + "type": "STRING", + "value": "\"" + }, + { + "type": "REPEAT", + "content": { + "type": "CHOICE", + "members": [ + { + "type": "PATTERN", + "value": "[^\"\\\\]" + }, + { + "type": "PATTERN", + "value": "\\\\(.|\\r?\\n)" + } + ] + } + }, + { + "type": "STRING", + "value": "\"" + } + ] + }, + { + "type": "SEQ", + "members": [ + { + "type": "STRING", + "value": "'" + }, + { + "type": "REPEAT", + "content": { + "type": "CHOICE", + "members": [ + { + "type": "PATTERN", + "value": "[^'\\\\\\r\\n]" + }, + { + "type": "PATTERN", + "value": "\\\\." + } + ] + } + }, + { + "type": "STRING", + "value": "'" + } + ] + } + ] + } + }, + "doc_comment": { + "type": "TOKEN", + "content": { + "type": "PREC", + "value": 2, + "content": { + "type": "SEQ", + "members": [ + { + "type": "STRING", + "value": "/**" + }, + { + "type": "PATTERN", + "value": "[^*]*\\*+([^/*][^*]*\\*+)*" + }, + { + "type": "STRING", + "value": "/" + } + ] + } + } + }, + "block_comment": { + "type": "TOKEN", + "content": { + "type": "PREC", + "value": 1, + "content": { + "type": "SEQ", + "members": [ + { + "type": "STRING", + "value": "/*" + }, + { + "type": "PATTERN", + "value": "[^*]*\\*+([^/*][^*]*\\*+)*" + }, + { + "type": "STRING", + "value": "/" + } + ] + } + } + }, + "line_comment": { + "type": "TOKEN", + "content": { + "type": "SEQ", + "members": [ + { + "type": "STRING", + "value": "//" + }, + { + "type": "PATTERN", + "value": "[^\\r\\n]*" + } + ] + } + } + }, + "extras": [ + { + "type": "PATTERN", + "value": "\\s" + }, + { + "type": "SYMBOL", + "name": "doc_comment" + }, + { + "type": "SYMBOL", + "name": "block_comment" + }, + { + "type": "SYMBOL", + "name": "line_comment" + } + ], + "conflicts": [], + "precedences": [], + "externals": [], + "inline": [], + "supertypes": [], + "reserved": {} +} \ No newline at end of file diff --git a/crates/tree-sitter-compact/src/node-types.json b/crates/tree-sitter-compact/src/node-types.json new file mode 100644 index 00000000..9c16e7d9 --- /dev/null +++ b/crates/tree-sitter-compact/src/node-types.json @@ -0,0 +1,913 @@ +[ + { + "type": "block", + "named": true, + "fields": {}, + "children": { + "multiple": true, + "required": false, + "types": [ + { + "type": "block", + "named": true + }, + { + "type": "string", + "named": true + } + ] + } + }, + { + "type": "circuit_declaration", + "named": true, + "fields": { + "body": { + "multiple": false, + "required": true, + "types": [ + { + "type": "block", + "named": true + } + ] + }, + "name": { + "multiple": false, + "required": true, + "types": [ + { + "type": "identifier", + "named": true + } + ] + }, + "parameters": { + "multiple": false, + "required": true, + "types": [ + { + "type": "parameter_list", + "named": true + } + ] + }, + "type": { + "multiple": false, + "required": true, + "types": [ + { + "type": "type_expression", + "named": true + } + ] + } + }, + "children": { + "multiple": false, + "required": false, + "types": [ + { + "type": "generic_parameters", + "named": true + } + ] + } + }, + { + "type": "constructor_declaration", + "named": true, + "fields": { + "body": { + "multiple": false, + "required": true, + "types": [ + { + "type": "block", + "named": true + } + ] + }, + "parameters": { + "multiple": false, + "required": true, + "types": [ + { + "type": "parameter_list", + "named": true + } + ] + } + } + }, + { + "type": "contract_declaration", + "named": true, + "fields": { + "body": { + "multiple": false, + "required": true, + "types": [ + { + "type": "block", + "named": true + } + ] + }, + "name": { + "multiple": false, + "required": true, + "types": [ + { + "type": "identifier", + "named": true + } + ] + } + } + }, + { + "type": "enum_declaration", + "named": true, + "fields": { + "body": { + "multiple": false, + "required": true, + "types": [ + { + "type": "block", + "named": true + } + ] + }, + "name": { + "multiple": false, + "required": true, + "types": [ + { + "type": "identifier", + "named": true + } + ] + } + } + }, + { + "type": "export_declaration", + "named": true, + "fields": {}, + "children": { + "multiple": true, + "required": false, + "types": [ + { + "type": "identifier", + "named": true + } + ] + } + }, + { + "type": "generic_arguments", + "named": true, + "fields": {}, + "children": { + "multiple": true, + "required": false, + "types": [ + { + "type": "generic_arguments", + "named": true + }, + { + "type": "identifier", + "named": true + }, + { + "type": "number", + "named": true + }, + { + "type": "string", + "named": true + } + ] + } + }, + { + "type": "generic_parameter", + "named": true, + "fields": { + "name": { + "multiple": false, + "required": true, + "types": [ + { + "type": "identifier", + "named": true + } + ] + } + } + }, + { + "type": "generic_parameters", + "named": true, + "fields": {}, + "children": { + "multiple": true, + "required": false, + "types": [ + { + "type": "generic_parameter", + "named": true + } + ] + } + }, + { + "type": "implements_declaration", + "named": true, + "fields": { + "type": { + "multiple": false, + "required": true, + "types": [ + { + "type": "type_expression", + "named": true + } + ] + } + } + }, + { + "type": "import_declaration", + "named": true, + "fields": { + "name": { + "multiple": false, + "required": true, + "types": [ + { + "type": "identifier", + "named": true + }, + { + "type": "string", + "named": true + } + ] + } + }, + "children": { + "multiple": true, + "required": false, + "types": [ + { + "type": "generic_arguments", + "named": true + }, + { + "type": "import_prefix", + "named": true + }, + { + "type": "import_selection", + "named": true + } + ] + } + }, + { + "type": "import_element", + "named": true, + "fields": { + "alias": { + "multiple": false, + "required": false, + "types": [ + { + "type": "identifier", + "named": true + } + ] + }, + "name": { + "multiple": false, + "required": true, + "types": [ + { + "type": "identifier", + "named": true + } + ] + } + } + }, + { + "type": "import_prefix", + "named": true, + "fields": { + "prefix": { + "multiple": false, + "required": true, + "types": [ + { + "type": "identifier", + "named": true + } + ] + } + } + }, + { + "type": "import_selection", + "named": true, + "fields": {}, + "children": { + "multiple": true, + "required": false, + "types": [ + { + "type": "import_element", + "named": true + } + ] + } + }, + { + "type": "include_declaration", + "named": true, + "fields": { + "path": { + "multiple": false, + "required": true, + "types": [ + { + "type": "string", + "named": true + } + ] + } + } + }, + { + "type": "ledger_declaration", + "named": true, + "fields": { + "name": { + "multiple": false, + "required": true, + "types": [ + { + "type": "identifier", + "named": true + } + ] + }, + "type": { + "multiple": false, + "required": true, + "types": [ + { + "type": "type_expression", + "named": true + } + ] + } + } + }, + { + "type": "module_body", + "named": true, + "fields": {}, + "children": { + "multiple": true, + "required": false, + "types": [ + { + "type": "circuit_declaration", + "named": true + }, + { + "type": "constructor_declaration", + "named": true + }, + { + "type": "contract_declaration", + "named": true + }, + { + "type": "enum_declaration", + "named": true + }, + { + "type": "export_declaration", + "named": true + }, + { + "type": "implements_declaration", + "named": true + }, + { + "type": "import_declaration", + "named": true + }, + { + "type": "include_declaration", + "named": true + }, + { + "type": "ledger_declaration", + "named": true + }, + { + "type": "module_declaration", + "named": true + }, + { + "type": "pragma_declaration", + "named": true + }, + { + "type": "struct_declaration", + "named": true + }, + { + "type": "type_declaration", + "named": true + }, + { + "type": "witness_declaration", + "named": true + } + ] + } + }, + { + "type": "module_declaration", + "named": true, + "fields": { + "body": { + "multiple": false, + "required": true, + "types": [ + { + "type": "module_body", + "named": true + } + ] + }, + "name": { + "multiple": false, + "required": true, + "types": [ + { + "type": "identifier", + "named": true + } + ] + } + }, + "children": { + "multiple": false, + "required": false, + "types": [ + { + "type": "generic_parameters", + "named": true + } + ] + } + }, + { + "type": "parameter_list", + "named": true, + "fields": {}, + "children": { + "multiple": true, + "required": false, + "types": [ + { + "type": "block", + "named": true + }, + { + "type": "string", + "named": true + } + ] + } + }, + { + "type": "pragma_declaration", + "named": true, + "fields": { + "name": { + "multiple": false, + "required": true, + "types": [ + { + "type": "identifier", + "named": true + } + ] + } + }, + "children": { + "multiple": false, + "required": true, + "types": [ + { + "type": "version_constraint", + "named": true + } + ] + } + }, + { + "type": "source_file", + "named": true, + "root": true, + "fields": {}, + "children": { + "multiple": true, + "required": false, + "types": [ + { + "type": "circuit_declaration", + "named": true + }, + { + "type": "constructor_declaration", + "named": true + }, + { + "type": "contract_declaration", + "named": true + }, + { + "type": "enum_declaration", + "named": true + }, + { + "type": "export_declaration", + "named": true + }, + { + "type": "implements_declaration", + "named": true + }, + { + "type": "import_declaration", + "named": true + }, + { + "type": "include_declaration", + "named": true + }, + { + "type": "ledger_declaration", + "named": true + }, + { + "type": "module_declaration", + "named": true + }, + { + "type": "pragma_declaration", + "named": true + }, + { + "type": "struct_declaration", + "named": true + }, + { + "type": "type_declaration", + "named": true + }, + { + "type": "witness_declaration", + "named": true + } + ] + } + }, + { + "type": "struct_declaration", + "named": true, + "fields": { + "body": { + "multiple": false, + "required": true, + "types": [ + { + "type": "block", + "named": true + } + ] + }, + "name": { + "multiple": false, + "required": true, + "types": [ + { + "type": "identifier", + "named": true + } + ] + } + }, + "children": { + "multiple": false, + "required": false, + "types": [ + { + "type": "generic_parameters", + "named": true + } + ] + } + }, + { + "type": "type_declaration", + "named": true, + "fields": { + "name": { + "multiple": false, + "required": true, + "types": [ + { + "type": "identifier", + "named": true + } + ] + }, + "value": { + "multiple": false, + "required": true, + "types": [ + { + "type": "type_expression", + "named": true + } + ] + } + }, + "children": { + "multiple": false, + "required": false, + "types": [ + { + "type": "generic_parameters", + "named": true + } + ] + } + }, + { + "type": "type_expression", + "named": true, + "fields": {}, + "children": { + "multiple": true, + "required": false, + "types": [ + { + "type": "generic_arguments", + "named": true + }, + { + "type": "identifier", + "named": true + }, + { + "type": "number", + "named": true + }, + { + "type": "string", + "named": true + } + ] + } + }, + { + "type": "witness_declaration", + "named": true, + "fields": { + "name": { + "multiple": false, + "required": true, + "types": [ + { + "type": "identifier", + "named": true + } + ] + }, + "parameters": { + "multiple": false, + "required": true, + "types": [ + { + "type": "parameter_list", + "named": true + } + ] + }, + "type": { + "multiple": false, + "required": true, + "types": [ + { + "type": "type_expression", + "named": true + } + ] + } + }, + "children": { + "multiple": false, + "required": false, + "types": [ + { + "type": "generic_parameters", + "named": true + } + ] + } + }, + { + "type": "#", + "named": false + }, + { + "type": "(", + "named": false + }, + { + "type": ")", + "named": false + }, + { + "type": ",", + "named": false + }, + { + "type": "..", + "named": false + }, + { + "type": "/", + "named": false + }, + { + "type": ":", + "named": false + }, + { + "type": ";", + "named": false + }, + { + "type": "<", + "named": false + }, + { + "type": "=", + "named": false + }, + { + "type": ">", + "named": false + }, + { + "type": "[", + "named": false + }, + { + "type": "]", + "named": false + }, + { + "type": "as", + "named": false + }, + { + "type": "block_comment", + "named": true, + "extra": true + }, + { + "type": "circuit", + "named": false + }, + { + "type": "constructor", + "named": false + }, + { + "type": "contract", + "named": false + }, + { + "type": "doc_comment", + "named": true, + "extra": true + }, + { + "type": "enum", + "named": false + }, + { + "type": "export", + "named": false + }, + { + "type": "from", + "named": false + }, + { + "type": "identifier", + "named": true + }, + { + "type": "implements", + "named": false + }, + { + "type": "import", + "named": false + }, + { + "type": "include", + "named": false + }, + { + "type": "ledger", + "named": false + }, + { + "type": "line_comment", + "named": true, + "extra": true + }, + { + "type": "module", + "named": false + }, + { + "type": "new", + "named": false + }, + { + "type": "number", + "named": true + }, + { + "type": "pragma", + "named": false + }, + { + "type": "prefix", + "named": false + }, + { + "type": "pure", + "named": false + }, + { + "type": "sealed", + "named": false + }, + { + "type": "string", + "named": true + }, + { + "type": "struct", + "named": false + }, + { + "type": "type", + "named": false + }, + { + "type": "version_constraint", + "named": true + }, + { + "type": "witness", + "named": false + }, + { + "type": "{", + "named": false + }, + { + "type": "}", + "named": false + } +] \ No newline at end of file diff --git a/crates/tree-sitter-compact/src/parser.c b/crates/tree-sitter-compact/src/parser.c new file mode 100644 index 00000000..3166d213 --- /dev/null +++ b/crates/tree-sitter-compact/src/parser.c @@ -0,0 +1,7042 @@ +/* Automatically @generated by tree-sitter v0.25.8 */ + +#include "tree_sitter/parser.h" + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic ignored "-Wmissing-field-initializers" +#endif + +#define LANGUAGE_VERSION 15 +#define STATE_COUNT 265 +#define LARGE_STATE_COUNT 2 +#define SYMBOL_COUNT 81 +#define ALIAS_COUNT 0 +#define TOKEN_COUNT 44 +#define EXTERNAL_TOKEN_COUNT 0 +#define FIELD_COUNT 8 +#define MAX_ALIAS_SEQUENCE_LENGTH 9 +#define MAX_RESERVED_WORD_SET_SIZE 0 +#define PRODUCTION_ID_COUNT 32 +#define SUPERTYPE_COUNT 0 + +enum ts_symbol_identifiers { + sym_identifier = 1, + anon_sym_pragma = 2, + anon_sym_SEMI = 3, + sym_version_constraint = 4, + anon_sym_include = 5, + anon_sym_import = 6, + anon_sym_LBRACE = 7, + anon_sym_COMMA = 8, + anon_sym_RBRACE = 9, + anon_sym_from = 10, + anon_sym_as = 11, + anon_sym_prefix = 12, + anon_sym_export = 13, + anon_sym_module = 14, + anon_sym_struct = 15, + anon_sym_enum = 16, + anon_sym_contract = 17, + anon_sym_implements = 18, + anon_sym_new = 19, + anon_sym_type = 20, + anon_sym_EQ = 21, + anon_sym_sealed = 22, + anon_sym_ledger = 23, + anon_sym_COLON = 24, + anon_sym_witness = 25, + anon_sym_constructor = 26, + anon_sym_pure = 27, + anon_sym_circuit = 28, + anon_sym_LT = 29, + anon_sym_GT = 30, + anon_sym_POUND = 31, + anon_sym_DOT_DOT = 32, + anon_sym_LBRACK = 33, + anon_sym_RBRACK = 34, + anon_sym_LPAREN = 35, + anon_sym_RPAREN = 36, + anon_sym_SLASH = 37, + sym__opaque_token = 38, + sym_number = 39, + sym_string = 40, + sym_doc_comment = 41, + sym_block_comment = 42, + sym_line_comment = 43, + sym_source_file = 44, + sym__declaration = 45, + sym_pragma_declaration = 46, + sym_include_declaration = 47, + sym_import_declaration = 48, + sym_import_selection = 49, + sym_import_element = 50, + sym_import_prefix = 51, + sym_export_declaration = 52, + sym_module_declaration = 53, + sym_module_body = 54, + sym_struct_declaration = 55, + sym_enum_declaration = 56, + sym_implements_declaration = 57, + sym_contract_declaration = 58, + sym_type_declaration = 59, + sym_ledger_declaration = 60, + sym_witness_declaration = 61, + sym_constructor_declaration = 62, + sym_circuit_declaration = 63, + sym_generic_parameters = 64, + sym_generic_parameter = 65, + sym_generic_arguments = 66, + sym_type_expression = 67, + sym__type_item = 68, + sym__tuple_type = 69, + sym_block = 70, + sym_parameter_list = 71, + sym__paren_group = 72, + sym__bracket_group = 73, + sym__opaque = 74, + aux_sym_source_file_repeat1 = 75, + aux_sym_import_selection_repeat1 = 76, + aux_sym_export_declaration_repeat1 = 77, + aux_sym_generic_parameters_repeat1 = 78, + aux_sym_generic_arguments_repeat1 = 79, + aux_sym_block_repeat1 = 80, +}; + +static const char * const ts_symbol_names[] = { + [ts_builtin_sym_end] = "end", + [sym_identifier] = "identifier", + [anon_sym_pragma] = "pragma", + [anon_sym_SEMI] = ";", + [sym_version_constraint] = "version_constraint", + [anon_sym_include] = "include", + [anon_sym_import] = "import", + [anon_sym_LBRACE] = "{", + [anon_sym_COMMA] = ",", + [anon_sym_RBRACE] = "}", + [anon_sym_from] = "from", + [anon_sym_as] = "as", + [anon_sym_prefix] = "prefix", + [anon_sym_export] = "export", + [anon_sym_module] = "module", + [anon_sym_struct] = "struct", + [anon_sym_enum] = "enum", + [anon_sym_contract] = "contract", + [anon_sym_implements] = "implements", + [anon_sym_new] = "new", + [anon_sym_type] = "type", + [anon_sym_EQ] = "=", + [anon_sym_sealed] = "sealed", + [anon_sym_ledger] = "ledger", + [anon_sym_COLON] = ":", + [anon_sym_witness] = "witness", + [anon_sym_constructor] = "constructor", + [anon_sym_pure] = "pure", + [anon_sym_circuit] = "circuit", + [anon_sym_LT] = "<", + [anon_sym_GT] = ">", + [anon_sym_POUND] = "#", + [anon_sym_DOT_DOT] = "..", + [anon_sym_LBRACK] = "[", + [anon_sym_RBRACK] = "]", + [anon_sym_LPAREN] = "(", + [anon_sym_RPAREN] = ")", + [anon_sym_SLASH] = "/", + [sym__opaque_token] = "_opaque_token", + [sym_number] = "number", + [sym_string] = "string", + [sym_doc_comment] = "doc_comment", + [sym_block_comment] = "block_comment", + [sym_line_comment] = "line_comment", + [sym_source_file] = "source_file", + [sym__declaration] = "_declaration", + [sym_pragma_declaration] = "pragma_declaration", + [sym_include_declaration] = "include_declaration", + [sym_import_declaration] = "import_declaration", + [sym_import_selection] = "import_selection", + [sym_import_element] = "import_element", + [sym_import_prefix] = "import_prefix", + [sym_export_declaration] = "export_declaration", + [sym_module_declaration] = "module_declaration", + [sym_module_body] = "module_body", + [sym_struct_declaration] = "struct_declaration", + [sym_enum_declaration] = "enum_declaration", + [sym_implements_declaration] = "implements_declaration", + [sym_contract_declaration] = "contract_declaration", + [sym_type_declaration] = "type_declaration", + [sym_ledger_declaration] = "ledger_declaration", + [sym_witness_declaration] = "witness_declaration", + [sym_constructor_declaration] = "constructor_declaration", + [sym_circuit_declaration] = "circuit_declaration", + [sym_generic_parameters] = "generic_parameters", + [sym_generic_parameter] = "generic_parameter", + [sym_generic_arguments] = "generic_arguments", + [sym_type_expression] = "type_expression", + [sym__type_item] = "_type_item", + [sym__tuple_type] = "_tuple_type", + [sym_block] = "block", + [sym_parameter_list] = "parameter_list", + [sym__paren_group] = "_paren_group", + [sym__bracket_group] = "_bracket_group", + [sym__opaque] = "_opaque", + [aux_sym_source_file_repeat1] = "source_file_repeat1", + [aux_sym_import_selection_repeat1] = "import_selection_repeat1", + [aux_sym_export_declaration_repeat1] = "export_declaration_repeat1", + [aux_sym_generic_parameters_repeat1] = "generic_parameters_repeat1", + [aux_sym_generic_arguments_repeat1] = "generic_arguments_repeat1", + [aux_sym_block_repeat1] = "block_repeat1", +}; + +static const TSSymbol ts_symbol_map[] = { + [ts_builtin_sym_end] = ts_builtin_sym_end, + [sym_identifier] = sym_identifier, + [anon_sym_pragma] = anon_sym_pragma, + [anon_sym_SEMI] = anon_sym_SEMI, + [sym_version_constraint] = sym_version_constraint, + [anon_sym_include] = anon_sym_include, + [anon_sym_import] = anon_sym_import, + [anon_sym_LBRACE] = anon_sym_LBRACE, + [anon_sym_COMMA] = anon_sym_COMMA, + [anon_sym_RBRACE] = anon_sym_RBRACE, + [anon_sym_from] = anon_sym_from, + [anon_sym_as] = anon_sym_as, + [anon_sym_prefix] = anon_sym_prefix, + [anon_sym_export] = anon_sym_export, + [anon_sym_module] = anon_sym_module, + [anon_sym_struct] = anon_sym_struct, + [anon_sym_enum] = anon_sym_enum, + [anon_sym_contract] = anon_sym_contract, + [anon_sym_implements] = anon_sym_implements, + [anon_sym_new] = anon_sym_new, + [anon_sym_type] = anon_sym_type, + [anon_sym_EQ] = anon_sym_EQ, + [anon_sym_sealed] = anon_sym_sealed, + [anon_sym_ledger] = anon_sym_ledger, + [anon_sym_COLON] = anon_sym_COLON, + [anon_sym_witness] = anon_sym_witness, + [anon_sym_constructor] = anon_sym_constructor, + [anon_sym_pure] = anon_sym_pure, + [anon_sym_circuit] = anon_sym_circuit, + [anon_sym_LT] = anon_sym_LT, + [anon_sym_GT] = anon_sym_GT, + [anon_sym_POUND] = anon_sym_POUND, + [anon_sym_DOT_DOT] = anon_sym_DOT_DOT, + [anon_sym_LBRACK] = anon_sym_LBRACK, + [anon_sym_RBRACK] = anon_sym_RBRACK, + [anon_sym_LPAREN] = anon_sym_LPAREN, + [anon_sym_RPAREN] = anon_sym_RPAREN, + [anon_sym_SLASH] = anon_sym_SLASH, + [sym__opaque_token] = sym__opaque_token, + [sym_number] = sym_number, + [sym_string] = sym_string, + [sym_doc_comment] = sym_doc_comment, + [sym_block_comment] = sym_block_comment, + [sym_line_comment] = sym_line_comment, + [sym_source_file] = sym_source_file, + [sym__declaration] = sym__declaration, + [sym_pragma_declaration] = sym_pragma_declaration, + [sym_include_declaration] = sym_include_declaration, + [sym_import_declaration] = sym_import_declaration, + [sym_import_selection] = sym_import_selection, + [sym_import_element] = sym_import_element, + [sym_import_prefix] = sym_import_prefix, + [sym_export_declaration] = sym_export_declaration, + [sym_module_declaration] = sym_module_declaration, + [sym_module_body] = sym_module_body, + [sym_struct_declaration] = sym_struct_declaration, + [sym_enum_declaration] = sym_enum_declaration, + [sym_implements_declaration] = sym_implements_declaration, + [sym_contract_declaration] = sym_contract_declaration, + [sym_type_declaration] = sym_type_declaration, + [sym_ledger_declaration] = sym_ledger_declaration, + [sym_witness_declaration] = sym_witness_declaration, + [sym_constructor_declaration] = sym_constructor_declaration, + [sym_circuit_declaration] = sym_circuit_declaration, + [sym_generic_parameters] = sym_generic_parameters, + [sym_generic_parameter] = sym_generic_parameter, + [sym_generic_arguments] = sym_generic_arguments, + [sym_type_expression] = sym_type_expression, + [sym__type_item] = sym__type_item, + [sym__tuple_type] = sym__tuple_type, + [sym_block] = sym_block, + [sym_parameter_list] = sym_parameter_list, + [sym__paren_group] = sym__paren_group, + [sym__bracket_group] = sym__bracket_group, + [sym__opaque] = sym__opaque, + [aux_sym_source_file_repeat1] = aux_sym_source_file_repeat1, + [aux_sym_import_selection_repeat1] = aux_sym_import_selection_repeat1, + [aux_sym_export_declaration_repeat1] = aux_sym_export_declaration_repeat1, + [aux_sym_generic_parameters_repeat1] = aux_sym_generic_parameters_repeat1, + [aux_sym_generic_arguments_repeat1] = aux_sym_generic_arguments_repeat1, + [aux_sym_block_repeat1] = aux_sym_block_repeat1, +}; + +static const TSSymbolMetadata ts_symbol_metadata[] = { + [ts_builtin_sym_end] = { + .visible = false, + .named = true, + }, + [sym_identifier] = { + .visible = true, + .named = true, + }, + [anon_sym_pragma] = { + .visible = true, + .named = false, + }, + [anon_sym_SEMI] = { + .visible = true, + .named = false, + }, + [sym_version_constraint] = { + .visible = true, + .named = true, + }, + [anon_sym_include] = { + .visible = true, + .named = false, + }, + [anon_sym_import] = { + .visible = true, + .named = false, + }, + [anon_sym_LBRACE] = { + .visible = true, + .named = false, + }, + [anon_sym_COMMA] = { + .visible = true, + .named = false, + }, + [anon_sym_RBRACE] = { + .visible = true, + .named = false, + }, + [anon_sym_from] = { + .visible = true, + .named = false, + }, + [anon_sym_as] = { + .visible = true, + .named = false, + }, + [anon_sym_prefix] = { + .visible = true, + .named = false, + }, + [anon_sym_export] = { + .visible = true, + .named = false, + }, + [anon_sym_module] = { + .visible = true, + .named = false, + }, + [anon_sym_struct] = { + .visible = true, + .named = false, + }, + [anon_sym_enum] = { + .visible = true, + .named = false, + }, + [anon_sym_contract] = { + .visible = true, + .named = false, + }, + [anon_sym_implements] = { + .visible = true, + .named = false, + }, + [anon_sym_new] = { + .visible = true, + .named = false, + }, + [anon_sym_type] = { + .visible = true, + .named = false, + }, + [anon_sym_EQ] = { + .visible = true, + .named = false, + }, + [anon_sym_sealed] = { + .visible = true, + .named = false, + }, + [anon_sym_ledger] = { + .visible = true, + .named = false, + }, + [anon_sym_COLON] = { + .visible = true, + .named = false, + }, + [anon_sym_witness] = { + .visible = true, + .named = false, + }, + [anon_sym_constructor] = { + .visible = true, + .named = false, + }, + [anon_sym_pure] = { + .visible = true, + .named = false, + }, + [anon_sym_circuit] = { + .visible = true, + .named = false, + }, + [anon_sym_LT] = { + .visible = true, + .named = false, + }, + [anon_sym_GT] = { + .visible = true, + .named = false, + }, + [anon_sym_POUND] = { + .visible = true, + .named = false, + }, + [anon_sym_DOT_DOT] = { + .visible = true, + .named = false, + }, + [anon_sym_LBRACK] = { + .visible = true, + .named = false, + }, + [anon_sym_RBRACK] = { + .visible = true, + .named = false, + }, + [anon_sym_LPAREN] = { + .visible = true, + .named = false, + }, + [anon_sym_RPAREN] = { + .visible = true, + .named = false, + }, + [anon_sym_SLASH] = { + .visible = true, + .named = false, + }, + [sym__opaque_token] = { + .visible = false, + .named = true, + }, + [sym_number] = { + .visible = true, + .named = true, + }, + [sym_string] = { + .visible = true, + .named = true, + }, + [sym_doc_comment] = { + .visible = true, + .named = true, + }, + [sym_block_comment] = { + .visible = true, + .named = true, + }, + [sym_line_comment] = { + .visible = true, + .named = true, + }, + [sym_source_file] = { + .visible = true, + .named = true, + }, + [sym__declaration] = { + .visible = false, + .named = true, + }, + [sym_pragma_declaration] = { + .visible = true, + .named = true, + }, + [sym_include_declaration] = { + .visible = true, + .named = true, + }, + [sym_import_declaration] = { + .visible = true, + .named = true, + }, + [sym_import_selection] = { + .visible = true, + .named = true, + }, + [sym_import_element] = { + .visible = true, + .named = true, + }, + [sym_import_prefix] = { + .visible = true, + .named = true, + }, + [sym_export_declaration] = { + .visible = true, + .named = true, + }, + [sym_module_declaration] = { + .visible = true, + .named = true, + }, + [sym_module_body] = { + .visible = true, + .named = true, + }, + [sym_struct_declaration] = { + .visible = true, + .named = true, + }, + [sym_enum_declaration] = { + .visible = true, + .named = true, + }, + [sym_implements_declaration] = { + .visible = true, + .named = true, + }, + [sym_contract_declaration] = { + .visible = true, + .named = true, + }, + [sym_type_declaration] = { + .visible = true, + .named = true, + }, + [sym_ledger_declaration] = { + .visible = true, + .named = true, + }, + [sym_witness_declaration] = { + .visible = true, + .named = true, + }, + [sym_constructor_declaration] = { + .visible = true, + .named = true, + }, + [sym_circuit_declaration] = { + .visible = true, + .named = true, + }, + [sym_generic_parameters] = { + .visible = true, + .named = true, + }, + [sym_generic_parameter] = { + .visible = true, + .named = true, + }, + [sym_generic_arguments] = { + .visible = true, + .named = true, + }, + [sym_type_expression] = { + .visible = true, + .named = true, + }, + [sym__type_item] = { + .visible = false, + .named = true, + }, + [sym__tuple_type] = { + .visible = false, + .named = true, + }, + [sym_block] = { + .visible = true, + .named = true, + }, + [sym_parameter_list] = { + .visible = true, + .named = true, + }, + [sym__paren_group] = { + .visible = false, + .named = true, + }, + [sym__bracket_group] = { + .visible = false, + .named = true, + }, + [sym__opaque] = { + .visible = false, + .named = true, + }, + [aux_sym_source_file_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym_import_selection_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym_export_declaration_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym_generic_parameters_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym_generic_arguments_repeat1] = { + .visible = false, + .named = false, + }, + [aux_sym_block_repeat1] = { + .visible = false, + .named = false, + }, +}; + +enum ts_field_identifiers { + field_alias = 1, + field_body = 2, + field_name = 3, + field_parameters = 4, + field_path = 5, + field_prefix = 6, + field_type = 7, + field_value = 8, +}; + +static const char * const ts_field_names[] = { + [0] = NULL, + [field_alias] = "alias", + [field_body] = "body", + [field_name] = "name", + [field_parameters] = "parameters", + [field_path] = "path", + [field_prefix] = "prefix", + [field_type] = "type", + [field_value] = "value", +}; + +static const TSMapSlice ts_field_map_slices[PRODUCTION_ID_COUNT] = { + [1] = {.index = 0, .length = 1}, + [2] = {.index = 1, .length = 1}, + [3] = {.index = 2, .length = 1}, + [4] = {.index = 3, .length = 2}, + [5] = {.index = 5, .length = 2}, + [6] = {.index = 7, .length = 1}, + [7] = {.index = 8, .length = 1}, + [8] = {.index = 9, .length = 2}, + [9] = {.index = 11, .length = 2}, + [10] = {.index = 13, .length = 1}, + [11] = {.index = 14, .length = 2}, + [12] = {.index = 16, .length = 2}, + [13] = {.index = 18, .length = 2}, + [14] = {.index = 20, .length = 2}, + [15] = {.index = 22, .length = 2}, + [16] = {.index = 24, .length = 2}, + [17] = {.index = 26, .length = 2}, + [18] = {.index = 28, .length = 3}, + [19] = {.index = 31, .length = 4}, + [20] = {.index = 35, .length = 2}, + [21] = {.index = 37, .length = 2}, + [22] = {.index = 39, .length = 2}, + [23] = {.index = 41, .length = 3}, + [24] = {.index = 44, .length = 4}, + [25] = {.index = 48, .length = 3}, + [26] = {.index = 51, .length = 4}, + [27] = {.index = 55, .length = 2}, + [28] = {.index = 57, .length = 3}, + [29] = {.index = 60, .length = 4}, + [30] = {.index = 64, .length = 4}, + [31] = {.index = 68, .length = 4}, +}; + +static const TSFieldMapEntry ts_field_map_entries[] = { + [0] = + {field_path, 1}, + [1] = + {field_name, 0}, + [2] = + {field_name, 1}, + [3] = + {field_body, 2}, + {field_name, 1}, + [5] = + {field_body, 2}, + {field_parameters, 1}, + [7] = + {field_prefix, 1}, + [8] = + {field_name, 2}, + [9] = + {field_body, 3}, + {field_name, 2}, + [11] = + {field_body, 3}, + {field_name, 1}, + [13] = + {field_type, 2}, + [14] = + {field_alias, 2}, + {field_name, 0}, + [16] = + {field_body, 4}, + {field_name, 2}, + [18] = + {field_name, 1}, + {field_value, 3}, + [20] = + {field_name, 1}, + {field_type, 3}, + [22] = + {field_name, 2}, + {field_value, 4}, + [24] = + {field_name, 2}, + {field_type, 4}, + [26] = + {field_name, 1}, + {field_value, 4}, + [28] = + {field_name, 1}, + {field_parameters, 2}, + {field_type, 4}, + [31] = + {field_body, 5}, + {field_name, 1}, + {field_parameters, 2}, + {field_type, 4}, + [35] = + {field_name, 3}, + {field_value, 5}, + [37] = + {field_name, 2}, + {field_value, 5}, + [39] = + {field_name, 3}, + {field_type, 5}, + [41] = + {field_name, 2}, + {field_parameters, 3}, + {field_type, 5}, + [44] = + {field_body, 6}, + {field_name, 2}, + {field_parameters, 3}, + {field_type, 5}, + [48] = + {field_name, 1}, + {field_parameters, 3}, + {field_type, 5}, + [51] = + {field_body, 6}, + {field_name, 1}, + {field_parameters, 3}, + {field_type, 5}, + [55] = + {field_name, 3}, + {field_value, 6}, + [57] = + {field_name, 2}, + {field_parameters, 4}, + {field_type, 6}, + [60] = + {field_body, 7}, + {field_name, 3}, + {field_parameters, 4}, + {field_type, 6}, + [64] = + {field_body, 7}, + {field_name, 2}, + {field_parameters, 4}, + {field_type, 6}, + [68] = + {field_body, 8}, + {field_name, 3}, + {field_parameters, 5}, + {field_type, 7}, +}; + +static const TSSymbol ts_alias_sequences[PRODUCTION_ID_COUNT][MAX_ALIAS_SEQUENCE_LENGTH] = { + [0] = {0}, +}; + +static const uint16_t ts_non_terminal_alias_map[] = { + 0, +}; + +static const TSStateId ts_primary_state_ids[STATE_COUNT] = { + [0] = 0, + [1] = 1, + [2] = 2, + [3] = 3, + [4] = 4, + [5] = 5, + [6] = 6, + [7] = 7, + [8] = 8, + [9] = 9, + [10] = 10, + [11] = 11, + [12] = 12, + [13] = 13, + [14] = 14, + [15] = 15, + [16] = 16, + [17] = 17, + [18] = 18, + [19] = 19, + [20] = 20, + [21] = 21, + [22] = 22, + [23] = 23, + [24] = 24, + [25] = 25, + [26] = 26, + [27] = 27, + [28] = 28, + [29] = 29, + [30] = 30, + [31] = 31, + [32] = 32, + [33] = 33, + [34] = 34, + [35] = 35, + [36] = 36, + [37] = 37, + [38] = 38, + [39] = 39, + [40] = 40, + [41] = 41, + [42] = 42, + [43] = 43, + [44] = 44, + [45] = 45, + [46] = 46, + [47] = 47, + [48] = 48, + [49] = 49, + [50] = 50, + [51] = 51, + [52] = 52, + [53] = 53, + [54] = 54, + [55] = 55, + [56] = 56, + [57] = 57, + [58] = 58, + [59] = 59, + [60] = 60, + [61] = 61, + [62] = 62, + [63] = 63, + [64] = 64, + [65] = 65, + [66] = 66, + [67] = 67, + [68] = 68, + [69] = 69, + [70] = 70, + [71] = 71, + [72] = 72, + [73] = 73, + [74] = 74, + [75] = 75, + [76] = 76, + [77] = 77, + [78] = 78, + [79] = 79, + [80] = 80, + [81] = 81, + [82] = 82, + [83] = 83, + [84] = 84, + [85] = 85, + [86] = 86, + [87] = 87, + [88] = 88, + [89] = 89, + [90] = 90, + [91] = 91, + [92] = 92, + [93] = 93, + [94] = 94, + [95] = 95, + [96] = 96, + [97] = 97, + [98] = 96, + [99] = 99, + [100] = 100, + [101] = 101, + [102] = 102, + [103] = 103, + [104] = 104, + [105] = 105, + [106] = 106, + [107] = 107, + [108] = 100, + [109] = 109, + [110] = 110, + [111] = 111, + [112] = 112, + [113] = 15, + [114] = 18, + [115] = 115, + [116] = 116, + [117] = 117, + [118] = 118, + [119] = 119, + [120] = 120, + [121] = 121, + [122] = 122, + [123] = 123, + [124] = 124, + [125] = 125, + [126] = 126, + [127] = 127, + [128] = 128, + [129] = 129, + [130] = 130, + [131] = 131, + [132] = 132, + [133] = 133, + [134] = 134, + [135] = 135, + [136] = 136, + [137] = 137, + [138] = 138, + [139] = 139, + [140] = 140, + [141] = 141, + [142] = 142, + [143] = 143, + [144] = 144, + [145] = 145, + [146] = 146, + [147] = 147, + [148] = 148, + [149] = 149, + [150] = 150, + [151] = 151, + [152] = 152, + [153] = 153, + [154] = 154, + [155] = 155, + [156] = 156, + [157] = 157, + [158] = 158, + [159] = 159, + [160] = 160, + [161] = 161, + [162] = 162, + [163] = 163, + [164] = 164, + [165] = 165, + [166] = 166, + [167] = 167, + [168] = 168, + [169] = 169, + [170] = 170, + [171] = 171, + [172] = 172, + [173] = 173, + [174] = 174, + [175] = 175, + [176] = 176, + [177] = 177, + [178] = 178, + [179] = 179, + [180] = 180, + [181] = 181, + [182] = 182, + [183] = 183, + [184] = 184, + [185] = 185, + [186] = 186, + [187] = 187, + [188] = 188, + [189] = 189, + [190] = 190, + [191] = 191, + [192] = 192, + [193] = 193, + [194] = 194, + [195] = 195, + [196] = 196, + [197] = 197, + [198] = 198, + [199] = 199, + [200] = 200, + [201] = 201, + [202] = 202, + [203] = 203, + [204] = 204, + [205] = 205, + [206] = 206, + [207] = 207, + [208] = 208, + [209] = 209, + [210] = 210, + [211] = 211, + [212] = 212, + [213] = 213, + [214] = 214, + [215] = 215, + [216] = 216, + [217] = 217, + [218] = 218, + [219] = 219, + [220] = 220, + [221] = 221, + [222] = 222, + [223] = 223, + [224] = 224, + [225] = 225, + [226] = 226, + [227] = 227, + [228] = 228, + [229] = 229, + [230] = 230, + [231] = 231, + [232] = 232, + [233] = 233, + [234] = 234, + [235] = 235, + [236] = 236, + [237] = 237, + [238] = 238, + [239] = 239, + [240] = 240, + [241] = 241, + [242] = 242, + [243] = 243, + [244] = 244, + [245] = 245, + [246] = 246, + [247] = 247, + [248] = 248, + [249] = 249, + [250] = 250, + [251] = 251, + [252] = 252, + [253] = 253, + [254] = 254, + [255] = 255, + [256] = 256, + [257] = 257, + [258] = 258, + [259] = 259, + [260] = 260, + [261] = 261, + [262] = 262, + [263] = 263, + [264] = 264, +}; + +static const TSCharacterRange sym__opaque_token_character_set_1[] = { + {0, 0x08}, {0x0e, 0x1f}, {'!', '!'}, {'#', '&'}, {'*', '.'}, {'0', 'Z'}, {'\\', '\\'}, {'^', 'z'}, + {'|', '|'}, {'~', 0x10ffff}, +}; + +static bool ts_lex(TSLexer *lexer, TSStateId state) { + START_LEXER(); + eof = lexer->eof(lexer); + switch (state) { + case 0: + if (eof) ADVANCE(14); + ADVANCE_MAP( + '"', 3, + '#', 33, + '\'', 4, + '(', 37, + ')', 38, + ',', 27, + '.', 11, + '/', 39, + ':', 30, + ';', 15, + '<', 31, + '=', 29, + '>', 32, + '[', 35, + ']', 36, + '{', 26, + '}', 28, + ); + if (('\t' <= lookahead && lookahead <= '\r') || + lookahead == ' ') SKIP(0); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(42); + if (lookahead == '$' || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(41); + END_STATE(); + case 1: + if (lookahead == '\r') ADVANCE(3); + if (lookahead != 0) ADVANCE(3); + END_STATE(); + case 2: + ADVANCE_MAP( + '"', 3, + '\'', 4, + '(', 37, + ')', 38, + '/', 39, + '[', 35, + ']', 36, + '{', 26, + '}', 28, + ); + if (('\t' <= lookahead && lookahead <= '\r') || + lookahead == ' ') SKIP(2); + if (lookahead != 0) ADVANCE(40); + END_STATE(); + case 3: + if (lookahead == '"') ADVANCE(43); + if (lookahead == '\\') ADVANCE(1); + if (lookahead != 0) ADVANCE(3); + END_STATE(); + case 4: + if (lookahead == '\'') ADVANCE(43); + if (lookahead == '\\') ADVANCE(13); + if (lookahead != 0 && + lookahead != '\n' && + lookahead != '\r') ADVANCE(4); + END_STATE(); + case 5: + if (lookahead == '*') ADVANCE(6); + if (lookahead != 0) ADVANCE(10); + END_STATE(); + case 6: + if (lookahead == '*') ADVANCE(7); + if (lookahead == '/') ADVANCE(46); + if (lookahead != 0) ADVANCE(8); + END_STATE(); + case 7: + if (lookahead == '*') ADVANCE(7); + if (lookahead == '/') ADVANCE(44); + if (lookahead != 0) ADVANCE(8); + END_STATE(); + case 8: + if (lookahead == '*') ADVANCE(7); + if (lookahead != 0) ADVANCE(8); + END_STATE(); + case 9: + if (lookahead == '*') ADVANCE(9); + if (lookahead == '/') ADVANCE(45); + if (lookahead != 0) ADVANCE(10); + END_STATE(); + case 10: + if (lookahead == '*') ADVANCE(9); + if (lookahead != 0) ADVANCE(10); + END_STATE(); + case 11: + if (lookahead == '.') ADVANCE(34); + END_STATE(); + case 12: + if (lookahead == '/') ADVANCE(16); + if (lookahead == '\n' || + lookahead == '\r') SKIP(12); + if (('\t' <= lookahead && lookahead <= '\f') || + lookahead == ' ') ADVANCE(23); + if (lookahead != 0 && + lookahead != ';' && + lookahead != '{' && + lookahead != '}') ADVANCE(25); + END_STATE(); + case 13: + if (lookahead != 0 && + lookahead != '\n') ADVANCE(4); + END_STATE(); + case 14: + ACCEPT_TOKEN(ts_builtin_sym_end); + END_STATE(); + case 15: + ACCEPT_TOKEN(anon_sym_SEMI); + END_STATE(); + case 16: + ACCEPT_TOKEN(sym_version_constraint); + if (lookahead == '*') ADVANCE(17); + if (lookahead == '/') ADVANCE(24); + if (lookahead != 0 && + lookahead != '\n' && + lookahead != '\r' && + lookahead != ';' && + lookahead != '{' && + lookahead != '}') ADVANCE(25); + END_STATE(); + case 17: + ACCEPT_TOKEN(sym_version_constraint); + if (lookahead == '*') ADVANCE(19); + if (lookahead == '\n' || + lookahead == '\r' || + lookahead == ';' || + lookahead == '{' || + lookahead == '}') ADVANCE(10); + if (lookahead != 0) ADVANCE(22); + END_STATE(); + case 18: + ACCEPT_TOKEN(sym_version_constraint); + if (lookahead == '*') ADVANCE(18); + if (lookahead == '/') ADVANCE(44); + if (lookahead == '\n' || + lookahead == '\r' || + lookahead == ';' || + lookahead == '{' || + lookahead == '}') ADVANCE(8); + if (lookahead != 0) ADVANCE(20); + END_STATE(); + case 19: + ACCEPT_TOKEN(sym_version_constraint); + if (lookahead == '*') ADVANCE(18); + if (lookahead == '/') ADVANCE(47); + if (lookahead == '\n' || + lookahead == '\r' || + lookahead == ';' || + lookahead == '{' || + lookahead == '}') ADVANCE(8); + if (lookahead != 0) ADVANCE(20); + END_STATE(); + case 20: + ACCEPT_TOKEN(sym_version_constraint); + if (lookahead == '*') ADVANCE(18); + if (lookahead == '\n' || + lookahead == '\r' || + lookahead == ';' || + lookahead == '{' || + lookahead == '}') ADVANCE(8); + if (lookahead != 0) ADVANCE(20); + END_STATE(); + case 21: + ACCEPT_TOKEN(sym_version_constraint); + if (lookahead == '*') ADVANCE(21); + if (lookahead == '/') ADVANCE(45); + if (lookahead == '\n' || + lookahead == '\r' || + lookahead == ';' || + lookahead == '{' || + lookahead == '}') ADVANCE(10); + if (lookahead != 0) ADVANCE(22); + END_STATE(); + case 22: + ACCEPT_TOKEN(sym_version_constraint); + if (lookahead == '*') ADVANCE(21); + if (lookahead == '\n' || + lookahead == '\r' || + lookahead == ';' || + lookahead == '{' || + lookahead == '}') ADVANCE(10); + if (lookahead != 0) ADVANCE(22); + END_STATE(); + case 23: + ACCEPT_TOKEN(sym_version_constraint); + if (lookahead == '/') ADVANCE(16); + if (lookahead == '\t' || + lookahead == 0x0b || + lookahead == '\f' || + lookahead == ' ') ADVANCE(23); + if (lookahead != 0 && + (lookahead < '\t' || '\r' < lookahead) && + lookahead != ';' && + lookahead != '{' && + lookahead != '}') ADVANCE(25); + END_STATE(); + case 24: + ACCEPT_TOKEN(sym_version_constraint); + if (lookahead == ';' || + lookahead == '{' || + lookahead == '}') ADVANCE(48); + if (lookahead != 0 && + lookahead != '\n' && + lookahead != '\r') ADVANCE(24); + END_STATE(); + case 25: + ACCEPT_TOKEN(sym_version_constraint); + if (lookahead != 0 && + lookahead != '\n' && + lookahead != '\r' && + lookahead != ';' && + lookahead != '{' && + lookahead != '}') ADVANCE(25); + END_STATE(); + case 26: + ACCEPT_TOKEN(anon_sym_LBRACE); + END_STATE(); + case 27: + ACCEPT_TOKEN(anon_sym_COMMA); + END_STATE(); + case 28: + ACCEPT_TOKEN(anon_sym_RBRACE); + END_STATE(); + case 29: + ACCEPT_TOKEN(anon_sym_EQ); + END_STATE(); + case 30: + ACCEPT_TOKEN(anon_sym_COLON); + END_STATE(); + case 31: + ACCEPT_TOKEN(anon_sym_LT); + END_STATE(); + case 32: + ACCEPT_TOKEN(anon_sym_GT); + END_STATE(); + case 33: + ACCEPT_TOKEN(anon_sym_POUND); + END_STATE(); + case 34: + ACCEPT_TOKEN(anon_sym_DOT_DOT); + END_STATE(); + case 35: + ACCEPT_TOKEN(anon_sym_LBRACK); + END_STATE(); + case 36: + ACCEPT_TOKEN(anon_sym_RBRACK); + END_STATE(); + case 37: + ACCEPT_TOKEN(anon_sym_LPAREN); + END_STATE(); + case 38: + ACCEPT_TOKEN(anon_sym_RPAREN); + END_STATE(); + case 39: + ACCEPT_TOKEN(anon_sym_SLASH); + if (lookahead == '*') ADVANCE(5); + if (lookahead == '/') ADVANCE(48); + END_STATE(); + case 40: + ACCEPT_TOKEN(sym__opaque_token); + if ((!eof && set_contains(sym__opaque_token_character_set_1, 10, lookahead))) ADVANCE(40); + END_STATE(); + case 41: + ACCEPT_TOKEN(sym_identifier); + if (lookahead == '$' || + ('0' <= lookahead && lookahead <= '9') || + ('A' <= lookahead && lookahead <= 'Z') || + lookahead == '_' || + ('a' <= lookahead && lookahead <= 'z')) ADVANCE(41); + END_STATE(); + case 42: + ACCEPT_TOKEN(sym_number); + if (('0' <= lookahead && lookahead <= '9')) ADVANCE(42); + END_STATE(); + case 43: + ACCEPT_TOKEN(sym_string); + END_STATE(); + case 44: + ACCEPT_TOKEN(sym_doc_comment); + END_STATE(); + case 45: + ACCEPT_TOKEN(sym_block_comment); + END_STATE(); + case 46: + ACCEPT_TOKEN(sym_block_comment); + if (lookahead == '*') ADVANCE(7); + if (lookahead != 0) ADVANCE(8); + END_STATE(); + case 47: + ACCEPT_TOKEN(sym_block_comment); + if (lookahead == '*') ADVANCE(18); + if (lookahead == '\n' || + lookahead == '\r' || + lookahead == ';' || + lookahead == '{' || + lookahead == '}') ADVANCE(8); + if (lookahead != 0) ADVANCE(20); + END_STATE(); + case 48: + ACCEPT_TOKEN(sym_line_comment); + if (lookahead != 0 && + lookahead != '\n' && + lookahead != '\r') ADVANCE(48); + END_STATE(); + default: + return false; + } +} + +static bool ts_lex_keywords(TSLexer *lexer, TSStateId state) { + START_LEXER(); + eof = lexer->eof(lexer); + switch (state) { + case 0: + ADVANCE_MAP( + 'a', 1, + 'c', 2, + 'e', 3, + 'f', 4, + 'i', 5, + 'l', 6, + 'm', 7, + 'n', 8, + 'p', 9, + 's', 10, + 't', 11, + 'w', 12, + ); + if (('\t' <= lookahead && lookahead <= '\r') || + lookahead == ' ') SKIP(0); + END_STATE(); + case 1: + if (lookahead == 's') ADVANCE(13); + END_STATE(); + case 2: + if (lookahead == 'i') ADVANCE(14); + if (lookahead == 'o') ADVANCE(15); + END_STATE(); + case 3: + if (lookahead == 'n') ADVANCE(16); + if (lookahead == 'x') ADVANCE(17); + END_STATE(); + case 4: + if (lookahead == 'r') ADVANCE(18); + END_STATE(); + case 5: + if (lookahead == 'm') ADVANCE(19); + if (lookahead == 'n') ADVANCE(20); + END_STATE(); + case 6: + if (lookahead == 'e') ADVANCE(21); + END_STATE(); + case 7: + if (lookahead == 'o') ADVANCE(22); + END_STATE(); + case 8: + if (lookahead == 'e') ADVANCE(23); + END_STATE(); + case 9: + if (lookahead == 'r') ADVANCE(24); + if (lookahead == 'u') ADVANCE(25); + END_STATE(); + case 10: + if (lookahead == 'e') ADVANCE(26); + if (lookahead == 't') ADVANCE(27); + END_STATE(); + case 11: + if (lookahead == 'y') ADVANCE(28); + END_STATE(); + case 12: + if (lookahead == 'i') ADVANCE(29); + END_STATE(); + case 13: + ACCEPT_TOKEN(anon_sym_as); + END_STATE(); + case 14: + if (lookahead == 'r') ADVANCE(30); + END_STATE(); + case 15: + if (lookahead == 'n') ADVANCE(31); + END_STATE(); + case 16: + if (lookahead == 'u') ADVANCE(32); + END_STATE(); + case 17: + if (lookahead == 'p') ADVANCE(33); + END_STATE(); + case 18: + if (lookahead == 'o') ADVANCE(34); + END_STATE(); + case 19: + if (lookahead == 'p') ADVANCE(35); + END_STATE(); + case 20: + if (lookahead == 'c') ADVANCE(36); + END_STATE(); + case 21: + if (lookahead == 'd') ADVANCE(37); + END_STATE(); + case 22: + if (lookahead == 'd') ADVANCE(38); + END_STATE(); + case 23: + if (lookahead == 'w') ADVANCE(39); + END_STATE(); + case 24: + if (lookahead == 'a') ADVANCE(40); + if (lookahead == 'e') ADVANCE(41); + END_STATE(); + case 25: + if (lookahead == 'r') ADVANCE(42); + END_STATE(); + case 26: + if (lookahead == 'a') ADVANCE(43); + END_STATE(); + case 27: + if (lookahead == 'r') ADVANCE(44); + END_STATE(); + case 28: + if (lookahead == 'p') ADVANCE(45); + END_STATE(); + case 29: + if (lookahead == 't') ADVANCE(46); + END_STATE(); + case 30: + if (lookahead == 'c') ADVANCE(47); + END_STATE(); + case 31: + if (lookahead == 's') ADVANCE(48); + if (lookahead == 't') ADVANCE(49); + END_STATE(); + case 32: + if (lookahead == 'm') ADVANCE(50); + END_STATE(); + case 33: + if (lookahead == 'o') ADVANCE(51); + END_STATE(); + case 34: + if (lookahead == 'm') ADVANCE(52); + END_STATE(); + case 35: + if (lookahead == 'l') ADVANCE(53); + if (lookahead == 'o') ADVANCE(54); + END_STATE(); + case 36: + if (lookahead == 'l') ADVANCE(55); + END_STATE(); + case 37: + if (lookahead == 'g') ADVANCE(56); + END_STATE(); + case 38: + if (lookahead == 'u') ADVANCE(57); + END_STATE(); + case 39: + ACCEPT_TOKEN(anon_sym_new); + END_STATE(); + case 40: + if (lookahead == 'g') ADVANCE(58); + END_STATE(); + case 41: + if (lookahead == 'f') ADVANCE(59); + END_STATE(); + case 42: + if (lookahead == 'e') ADVANCE(60); + END_STATE(); + case 43: + if (lookahead == 'l') ADVANCE(61); + END_STATE(); + case 44: + if (lookahead == 'u') ADVANCE(62); + END_STATE(); + case 45: + if (lookahead == 'e') ADVANCE(63); + END_STATE(); + case 46: + if (lookahead == 'n') ADVANCE(64); + END_STATE(); + case 47: + if (lookahead == 'u') ADVANCE(65); + END_STATE(); + case 48: + if (lookahead == 't') ADVANCE(66); + END_STATE(); + case 49: + if (lookahead == 'r') ADVANCE(67); + END_STATE(); + case 50: + ACCEPT_TOKEN(anon_sym_enum); + END_STATE(); + case 51: + if (lookahead == 'r') ADVANCE(68); + END_STATE(); + case 52: + ACCEPT_TOKEN(anon_sym_from); + END_STATE(); + case 53: + if (lookahead == 'e') ADVANCE(69); + END_STATE(); + case 54: + if (lookahead == 'r') ADVANCE(70); + END_STATE(); + case 55: + if (lookahead == 'u') ADVANCE(71); + END_STATE(); + case 56: + if (lookahead == 'e') ADVANCE(72); + END_STATE(); + case 57: + if (lookahead == 'l') ADVANCE(73); + END_STATE(); + case 58: + if (lookahead == 'm') ADVANCE(74); + END_STATE(); + case 59: + if (lookahead == 'i') ADVANCE(75); + END_STATE(); + case 60: + ACCEPT_TOKEN(anon_sym_pure); + END_STATE(); + case 61: + if (lookahead == 'e') ADVANCE(76); + END_STATE(); + case 62: + if (lookahead == 'c') ADVANCE(77); + END_STATE(); + case 63: + ACCEPT_TOKEN(anon_sym_type); + END_STATE(); + case 64: + if (lookahead == 'e') ADVANCE(78); + END_STATE(); + case 65: + if (lookahead == 'i') ADVANCE(79); + END_STATE(); + case 66: + if (lookahead == 'r') ADVANCE(80); + END_STATE(); + case 67: + if (lookahead == 'a') ADVANCE(81); + END_STATE(); + case 68: + if (lookahead == 't') ADVANCE(82); + END_STATE(); + case 69: + if (lookahead == 'm') ADVANCE(83); + END_STATE(); + case 70: + if (lookahead == 't') ADVANCE(84); + END_STATE(); + case 71: + if (lookahead == 'd') ADVANCE(85); + END_STATE(); + case 72: + if (lookahead == 'r') ADVANCE(86); + END_STATE(); + case 73: + if (lookahead == 'e') ADVANCE(87); + END_STATE(); + case 74: + if (lookahead == 'a') ADVANCE(88); + END_STATE(); + case 75: + if (lookahead == 'x') ADVANCE(89); + END_STATE(); + case 76: + if (lookahead == 'd') ADVANCE(90); + END_STATE(); + case 77: + if (lookahead == 't') ADVANCE(91); + END_STATE(); + case 78: + if (lookahead == 's') ADVANCE(92); + END_STATE(); + case 79: + if (lookahead == 't') ADVANCE(93); + END_STATE(); + case 80: + if (lookahead == 'u') ADVANCE(94); + END_STATE(); + case 81: + if (lookahead == 'c') ADVANCE(95); + END_STATE(); + case 82: + ACCEPT_TOKEN(anon_sym_export); + END_STATE(); + case 83: + if (lookahead == 'e') ADVANCE(96); + END_STATE(); + case 84: + ACCEPT_TOKEN(anon_sym_import); + END_STATE(); + case 85: + if (lookahead == 'e') ADVANCE(97); + END_STATE(); + case 86: + ACCEPT_TOKEN(anon_sym_ledger); + END_STATE(); + case 87: + ACCEPT_TOKEN(anon_sym_module); + END_STATE(); + case 88: + ACCEPT_TOKEN(anon_sym_pragma); + END_STATE(); + case 89: + ACCEPT_TOKEN(anon_sym_prefix); + END_STATE(); + case 90: + ACCEPT_TOKEN(anon_sym_sealed); + END_STATE(); + case 91: + ACCEPT_TOKEN(anon_sym_struct); + END_STATE(); + case 92: + if (lookahead == 's') ADVANCE(98); + END_STATE(); + case 93: + ACCEPT_TOKEN(anon_sym_circuit); + END_STATE(); + case 94: + if (lookahead == 'c') ADVANCE(99); + END_STATE(); + case 95: + if (lookahead == 't') ADVANCE(100); + END_STATE(); + case 96: + if (lookahead == 'n') ADVANCE(101); + END_STATE(); + case 97: + ACCEPT_TOKEN(anon_sym_include); + END_STATE(); + case 98: + ACCEPT_TOKEN(anon_sym_witness); + END_STATE(); + case 99: + if (lookahead == 't') ADVANCE(102); + END_STATE(); + case 100: + ACCEPT_TOKEN(anon_sym_contract); + END_STATE(); + case 101: + if (lookahead == 't') ADVANCE(103); + END_STATE(); + case 102: + if (lookahead == 'o') ADVANCE(104); + END_STATE(); + case 103: + if (lookahead == 's') ADVANCE(105); + END_STATE(); + case 104: + if (lookahead == 'r') ADVANCE(106); + END_STATE(); + case 105: + ACCEPT_TOKEN(anon_sym_implements); + END_STATE(); + case 106: + ACCEPT_TOKEN(anon_sym_constructor); + END_STATE(); + default: + return false; + } +} + +static const TSLexerMode ts_lex_modes[STATE_COUNT] = { + [0] = {.lex_state = 0}, + [1] = {.lex_state = 0}, + [2] = {.lex_state = 0}, + [3] = {.lex_state = 0}, + [4] = {.lex_state = 0}, + [5] = {.lex_state = 0}, + [6] = {.lex_state = 0}, + [7] = {.lex_state = 0}, + [8] = {.lex_state = 0}, + [9] = {.lex_state = 0}, + [10] = {.lex_state = 0}, + [11] = {.lex_state = 0}, + [12] = {.lex_state = 0}, + [13] = {.lex_state = 0}, + [14] = {.lex_state = 0}, + [15] = {.lex_state = 0}, + [16] = {.lex_state = 0}, + [17] = {.lex_state = 0}, + [18] = {.lex_state = 0}, + [19] = {.lex_state = 0}, + [20] = {.lex_state = 0}, + [21] = {.lex_state = 0}, + [22] = {.lex_state = 0}, + [23] = {.lex_state = 0}, + [24] = {.lex_state = 0}, + [25] = {.lex_state = 0}, + [26] = {.lex_state = 0}, + [27] = {.lex_state = 0}, + [28] = {.lex_state = 0}, + [29] = {.lex_state = 0}, + [30] = {.lex_state = 0}, + [31] = {.lex_state = 0}, + [32] = {.lex_state = 0}, + [33] = {.lex_state = 0}, + [34] = {.lex_state = 0}, + [35] = {.lex_state = 0}, + [36] = {.lex_state = 0}, + [37] = {.lex_state = 0}, + [38] = {.lex_state = 0}, + [39] = {.lex_state = 0}, + [40] = {.lex_state = 0}, + [41] = {.lex_state = 0}, + [42] = {.lex_state = 0}, + [43] = {.lex_state = 0}, + [44] = {.lex_state = 0}, + [45] = {.lex_state = 0}, + [46] = {.lex_state = 0}, + [47] = {.lex_state = 0}, + [48] = {.lex_state = 0}, + [49] = {.lex_state = 0}, + [50] = {.lex_state = 0}, + [51] = {.lex_state = 0}, + [52] = {.lex_state = 0}, + [53] = {.lex_state = 0}, + [54] = {.lex_state = 0}, + [55] = {.lex_state = 0}, + [56] = {.lex_state = 0}, + [57] = {.lex_state = 0}, + [58] = {.lex_state = 0}, + [59] = {.lex_state = 0}, + [60] = {.lex_state = 0}, + [61] = {.lex_state = 0}, + [62] = {.lex_state = 0}, + [63] = {.lex_state = 0}, + [64] = {.lex_state = 0}, + [65] = {.lex_state = 0}, + [66] = {.lex_state = 0}, + [67] = {.lex_state = 0}, + [68] = {.lex_state = 2}, + [69] = {.lex_state = 0}, + [70] = {.lex_state = 0}, + [71] = {.lex_state = 0}, + [72] = {.lex_state = 0}, + [73] = {.lex_state = 0}, + [74] = {.lex_state = 0}, + [75] = {.lex_state = 0}, + [76] = {.lex_state = 0}, + [77] = {.lex_state = 0}, + [78] = {.lex_state = 0}, + [79] = {.lex_state = 0}, + [80] = {.lex_state = 0}, + [81] = {.lex_state = 0}, + [82] = {.lex_state = 0}, + [83] = {.lex_state = 0}, + [84] = {.lex_state = 0}, + [85] = {.lex_state = 0}, + [86] = {.lex_state = 0}, + [87] = {.lex_state = 0}, + [88] = {.lex_state = 0}, + [89] = {.lex_state = 0}, + [90] = {.lex_state = 0}, + [91] = {.lex_state = 0}, + [92] = {.lex_state = 0}, + [93] = {.lex_state = 0}, + [94] = {.lex_state = 0}, + [95] = {.lex_state = 0}, + [96] = {.lex_state = 2}, + [97] = {.lex_state = 2}, + [98] = {.lex_state = 2}, + [99] = {.lex_state = 0}, + [100] = {.lex_state = 2}, + [101] = {.lex_state = 2}, + [102] = {.lex_state = 0}, + [103] = {.lex_state = 2}, + [104] = {.lex_state = 2}, + [105] = {.lex_state = 0}, + [106] = {.lex_state = 2}, + [107] = {.lex_state = 2}, + [108] = {.lex_state = 2}, + [109] = {.lex_state = 2}, + [110] = {.lex_state = 2}, + [111] = {.lex_state = 2}, + [112] = {.lex_state = 2}, + [113] = {.lex_state = 2}, + [114] = {.lex_state = 2}, + [115] = {.lex_state = 0}, + [116] = {.lex_state = 0}, + [117] = {.lex_state = 0}, + [118] = {.lex_state = 0}, + [119] = {.lex_state = 0}, + [120] = {.lex_state = 0}, + [121] = {.lex_state = 0}, + [122] = {.lex_state = 0}, + [123] = {.lex_state = 0}, + [124] = {.lex_state = 0}, + [125] = {.lex_state = 0}, + [126] = {.lex_state = 0}, + [127] = {.lex_state = 0}, + [128] = {.lex_state = 0}, + [129] = {.lex_state = 0}, + [130] = {.lex_state = 0}, + [131] = {.lex_state = 0}, + [132] = {.lex_state = 0}, + [133] = {.lex_state = 0}, + [134] = {.lex_state = 0}, + [135] = {.lex_state = 0}, + [136] = {.lex_state = 0}, + [137] = {.lex_state = 0}, + [138] = {.lex_state = 0}, + [139] = {.lex_state = 0}, + [140] = {.lex_state = 0}, + [141] = {.lex_state = 0}, + [142] = {.lex_state = 0}, + [143] = {.lex_state = 0}, + [144] = {.lex_state = 0}, + [145] = {.lex_state = 0}, + [146] = {.lex_state = 0}, + [147] = {.lex_state = 0}, + [148] = {.lex_state = 0}, + [149] = {.lex_state = 0}, + [150] = {.lex_state = 0}, + [151] = {.lex_state = 0}, + [152] = {.lex_state = 0}, + [153] = {.lex_state = 0}, + [154] = {.lex_state = 0}, + [155] = {.lex_state = 0}, + [156] = {.lex_state = 0}, + [157] = {.lex_state = 0}, + [158] = {.lex_state = 0}, + [159] = {.lex_state = 0}, + [160] = {.lex_state = 0}, + [161] = {.lex_state = 0}, + [162] = {.lex_state = 0}, + [163] = {.lex_state = 0}, + [164] = {.lex_state = 0}, + [165] = {.lex_state = 0}, + [166] = {.lex_state = 0}, + [167] = {.lex_state = 0}, + [168] = {.lex_state = 0}, + [169] = {.lex_state = 0}, + [170] = {.lex_state = 0}, + [171] = {.lex_state = 0}, + [172] = {.lex_state = 0}, + [173] = {.lex_state = 0}, + [174] = {.lex_state = 0}, + [175] = {.lex_state = 0}, + [176] = {.lex_state = 0}, + [177] = {.lex_state = 0}, + [178] = {.lex_state = 0}, + [179] = {.lex_state = 0}, + [180] = {.lex_state = 0}, + [181] = {.lex_state = 0}, + [182] = {.lex_state = 0}, + [183] = {.lex_state = 0}, + [184] = {.lex_state = 0}, + [185] = {.lex_state = 0}, + [186] = {.lex_state = 0}, + [187] = {.lex_state = 0}, + [188] = {.lex_state = 0}, + [189] = {.lex_state = 0}, + [190] = {.lex_state = 0}, + [191] = {.lex_state = 0}, + [192] = {.lex_state = 0}, + [193] = {.lex_state = 0}, + [194] = {.lex_state = 0}, + [195] = {.lex_state = 0}, + [196] = {.lex_state = 0}, + [197] = {.lex_state = 0}, + [198] = {.lex_state = 0}, + [199] = {.lex_state = 0}, + [200] = {.lex_state = 0}, + [201] = {.lex_state = 0}, + [202] = {.lex_state = 0}, + [203] = {.lex_state = 0}, + [204] = {.lex_state = 0}, + [205] = {.lex_state = 0}, + [206] = {.lex_state = 0}, + [207] = {.lex_state = 0}, + [208] = {.lex_state = 0}, + [209] = {.lex_state = 0}, + [210] = {.lex_state = 0}, + [211] = {.lex_state = 0}, + [212] = {.lex_state = 0}, + [213] = {.lex_state = 0}, + [214] = {.lex_state = 0}, + [215] = {.lex_state = 0}, + [216] = {.lex_state = 0}, + [217] = {.lex_state = 0}, + [218] = {.lex_state = 0}, + [219] = {.lex_state = 0}, + [220] = {.lex_state = 0}, + [221] = {.lex_state = 0}, + [222] = {.lex_state = 0}, + [223] = {.lex_state = 0}, + [224] = {.lex_state = 0}, + [225] = {.lex_state = 0}, + [226] = {.lex_state = 12}, + [227] = {.lex_state = 0}, + [228] = {.lex_state = 0}, + [229] = {.lex_state = 0}, + [230] = {.lex_state = 0}, + [231] = {.lex_state = 0}, + [232] = {.lex_state = 0}, + [233] = {.lex_state = 0}, + [234] = {.lex_state = 0}, + [235] = {.lex_state = 0}, + [236] = {.lex_state = 0}, + [237] = {.lex_state = 0}, + [238] = {.lex_state = 0}, + [239] = {.lex_state = 0}, + [240] = {.lex_state = 0}, + [241] = {.lex_state = 0}, + [242] = {.lex_state = 0}, + [243] = {.lex_state = 0}, + [244] = {.lex_state = 0}, + [245] = {.lex_state = 0}, + [246] = {.lex_state = 0}, + [247] = {.lex_state = 0}, + [248] = {.lex_state = 0}, + [249] = {.lex_state = 0}, + [250] = {.lex_state = 0}, + [251] = {.lex_state = 0}, + [252] = {.lex_state = 0}, + [253] = {.lex_state = 0}, + [254] = {.lex_state = 0}, + [255] = {.lex_state = 0}, + [256] = {.lex_state = 0}, + [257] = {.lex_state = 0}, + [258] = {.lex_state = 0}, + [259] = {.lex_state = 0}, + [260] = {.lex_state = 0}, + [261] = {.lex_state = 0}, + [262] = {.lex_state = 0}, + [263] = {.lex_state = 0}, + [264] = {.lex_state = 0}, +}; + +static const uint16_t ts_parse_table[LARGE_STATE_COUNT][SYMBOL_COUNT] = { + [STATE(0)] = { + [ts_builtin_sym_end] = ACTIONS(1), + [sym_identifier] = ACTIONS(1), + [anon_sym_pragma] = ACTIONS(1), + [anon_sym_SEMI] = ACTIONS(1), + [anon_sym_include] = ACTIONS(1), + [anon_sym_import] = ACTIONS(1), + [anon_sym_LBRACE] = ACTIONS(1), + [anon_sym_COMMA] = ACTIONS(1), + [anon_sym_RBRACE] = ACTIONS(1), + [anon_sym_from] = ACTIONS(1), + [anon_sym_as] = ACTIONS(1), + [anon_sym_prefix] = ACTIONS(1), + [anon_sym_export] = ACTIONS(1), + [anon_sym_module] = ACTIONS(1), + [anon_sym_struct] = ACTIONS(1), + [anon_sym_enum] = ACTIONS(1), + [anon_sym_contract] = ACTIONS(1), + [anon_sym_implements] = ACTIONS(1), + [anon_sym_new] = ACTIONS(1), + [anon_sym_type] = ACTIONS(1), + [anon_sym_EQ] = ACTIONS(1), + [anon_sym_sealed] = ACTIONS(1), + [anon_sym_ledger] = ACTIONS(1), + [anon_sym_COLON] = ACTIONS(1), + [anon_sym_witness] = ACTIONS(1), + [anon_sym_constructor] = ACTIONS(1), + [anon_sym_pure] = ACTIONS(1), + [anon_sym_circuit] = ACTIONS(1), + [anon_sym_LT] = ACTIONS(1), + [anon_sym_GT] = ACTIONS(1), + [anon_sym_POUND] = ACTIONS(1), + [anon_sym_DOT_DOT] = ACTIONS(1), + [anon_sym_LBRACK] = ACTIONS(1), + [anon_sym_RBRACK] = ACTIONS(1), + [anon_sym_LPAREN] = ACTIONS(1), + [anon_sym_RPAREN] = ACTIONS(1), + [anon_sym_SLASH] = ACTIONS(1), + [sym_number] = ACTIONS(1), + [sym_string] = ACTIONS(1), + [sym_doc_comment] = ACTIONS(3), + [sym_block_comment] = ACTIONS(5), + [sym_line_comment] = ACTIONS(3), + }, + [STATE(1)] = { + [sym_source_file] = STATE(207), + [sym__declaration] = STATE(3), + [sym_pragma_declaration] = STATE(3), + [sym_include_declaration] = STATE(3), + [sym_import_declaration] = STATE(3), + [sym_export_declaration] = STATE(3), + [sym_module_declaration] = STATE(3), + [sym_struct_declaration] = STATE(3), + [sym_enum_declaration] = STATE(3), + [sym_implements_declaration] = STATE(3), + [sym_contract_declaration] = STATE(3), + [sym_type_declaration] = STATE(3), + [sym_ledger_declaration] = STATE(3), + [sym_witness_declaration] = STATE(3), + [sym_constructor_declaration] = STATE(3), + [sym_circuit_declaration] = STATE(3), + [aux_sym_source_file_repeat1] = STATE(3), + [ts_builtin_sym_end] = ACTIONS(7), + [anon_sym_pragma] = ACTIONS(9), + [anon_sym_include] = ACTIONS(11), + [anon_sym_import] = ACTIONS(13), + [anon_sym_export] = ACTIONS(15), + [anon_sym_module] = ACTIONS(17), + [anon_sym_struct] = ACTIONS(19), + [anon_sym_enum] = ACTIONS(21), + [anon_sym_contract] = ACTIONS(23), + [anon_sym_new] = ACTIONS(25), + [anon_sym_type] = ACTIONS(27), + [anon_sym_sealed] = ACTIONS(29), + [anon_sym_ledger] = ACTIONS(31), + [anon_sym_witness] = ACTIONS(33), + [anon_sym_constructor] = ACTIONS(35), + [anon_sym_pure] = ACTIONS(37), + [anon_sym_circuit] = ACTIONS(39), + [sym_doc_comment] = ACTIONS(3), + [sym_block_comment] = ACTIONS(5), + [sym_line_comment] = ACTIONS(3), + }, +}; + +static const uint16_t ts_small_parse_table[] = { + [0] = 20, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(43), 1, + anon_sym_pragma, + ACTIONS(46), 1, + anon_sym_include, + ACTIONS(49), 1, + anon_sym_import, + ACTIONS(52), 1, + anon_sym_export, + ACTIONS(55), 1, + anon_sym_module, + ACTIONS(58), 1, + anon_sym_struct, + ACTIONS(61), 1, + anon_sym_enum, + ACTIONS(64), 1, + anon_sym_contract, + ACTIONS(67), 1, + anon_sym_new, + ACTIONS(70), 1, + anon_sym_type, + ACTIONS(73), 1, + anon_sym_sealed, + ACTIONS(76), 1, + anon_sym_ledger, + ACTIONS(79), 1, + anon_sym_witness, + ACTIONS(82), 1, + anon_sym_constructor, + ACTIONS(85), 1, + anon_sym_pure, + ACTIONS(88), 1, + anon_sym_circuit, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(41), 2, + ts_builtin_sym_end, + anon_sym_RBRACE, + STATE(2), 16, + sym__declaration, + sym_pragma_declaration, + sym_include_declaration, + sym_import_declaration, + sym_export_declaration, + sym_module_declaration, + sym_struct_declaration, + sym_enum_declaration, + sym_implements_declaration, + sym_contract_declaration, + sym_type_declaration, + sym_ledger_declaration, + sym_witness_declaration, + sym_constructor_declaration, + sym_circuit_declaration, + aux_sym_source_file_repeat1, + [78] = 20, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(9), 1, + anon_sym_pragma, + ACTIONS(11), 1, + anon_sym_include, + ACTIONS(13), 1, + anon_sym_import, + ACTIONS(15), 1, + anon_sym_export, + ACTIONS(17), 1, + anon_sym_module, + ACTIONS(19), 1, + anon_sym_struct, + ACTIONS(21), 1, + anon_sym_enum, + ACTIONS(23), 1, + anon_sym_contract, + ACTIONS(25), 1, + anon_sym_new, + ACTIONS(27), 1, + anon_sym_type, + ACTIONS(29), 1, + anon_sym_sealed, + ACTIONS(31), 1, + anon_sym_ledger, + ACTIONS(33), 1, + anon_sym_witness, + ACTIONS(35), 1, + anon_sym_constructor, + ACTIONS(37), 1, + anon_sym_pure, + ACTIONS(39), 1, + anon_sym_circuit, + ACTIONS(91), 1, + ts_builtin_sym_end, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + STATE(2), 16, + sym__declaration, + sym_pragma_declaration, + sym_include_declaration, + sym_import_declaration, + sym_export_declaration, + sym_module_declaration, + sym_struct_declaration, + sym_enum_declaration, + sym_implements_declaration, + sym_contract_declaration, + sym_type_declaration, + sym_ledger_declaration, + sym_witness_declaration, + sym_constructor_declaration, + sym_circuit_declaration, + aux_sym_source_file_repeat1, + [155] = 20, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(9), 1, + anon_sym_pragma, + ACTIONS(11), 1, + anon_sym_include, + ACTIONS(13), 1, + anon_sym_import, + ACTIONS(15), 1, + anon_sym_export, + ACTIONS(17), 1, + anon_sym_module, + ACTIONS(19), 1, + anon_sym_struct, + ACTIONS(21), 1, + anon_sym_enum, + ACTIONS(23), 1, + anon_sym_contract, + ACTIONS(25), 1, + anon_sym_new, + ACTIONS(27), 1, + anon_sym_type, + ACTIONS(29), 1, + anon_sym_sealed, + ACTIONS(31), 1, + anon_sym_ledger, + ACTIONS(33), 1, + anon_sym_witness, + ACTIONS(35), 1, + anon_sym_constructor, + ACTIONS(37), 1, + anon_sym_pure, + ACTIONS(39), 1, + anon_sym_circuit, + ACTIONS(93), 1, + anon_sym_RBRACE, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + STATE(5), 16, + sym__declaration, + sym_pragma_declaration, + sym_include_declaration, + sym_import_declaration, + sym_export_declaration, + sym_module_declaration, + sym_struct_declaration, + sym_enum_declaration, + sym_implements_declaration, + sym_contract_declaration, + sym_type_declaration, + sym_ledger_declaration, + sym_witness_declaration, + sym_constructor_declaration, + sym_circuit_declaration, + aux_sym_source_file_repeat1, + [232] = 20, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(9), 1, + anon_sym_pragma, + ACTIONS(11), 1, + anon_sym_include, + ACTIONS(13), 1, + anon_sym_import, + ACTIONS(15), 1, + anon_sym_export, + ACTIONS(17), 1, + anon_sym_module, + ACTIONS(19), 1, + anon_sym_struct, + ACTIONS(21), 1, + anon_sym_enum, + ACTIONS(23), 1, + anon_sym_contract, + ACTIONS(25), 1, + anon_sym_new, + ACTIONS(27), 1, + anon_sym_type, + ACTIONS(29), 1, + anon_sym_sealed, + ACTIONS(31), 1, + anon_sym_ledger, + ACTIONS(33), 1, + anon_sym_witness, + ACTIONS(35), 1, + anon_sym_constructor, + ACTIONS(37), 1, + anon_sym_pure, + ACTIONS(39), 1, + anon_sym_circuit, + ACTIONS(95), 1, + anon_sym_RBRACE, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + STATE(2), 16, + sym__declaration, + sym_pragma_declaration, + sym_include_declaration, + sym_import_declaration, + sym_export_declaration, + sym_module_declaration, + sym_struct_declaration, + sym_enum_declaration, + sym_implements_declaration, + sym_contract_declaration, + sym_type_declaration, + sym_ledger_declaration, + sym_witness_declaration, + sym_constructor_declaration, + sym_circuit_declaration, + aux_sym_source_file_repeat1, + [309] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(99), 1, + anon_sym_SEMI, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(97), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [340] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(103), 1, + anon_sym_SEMI, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(101), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [371] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(107), 1, + anon_sym_SEMI, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(105), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [402] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(111), 1, + anon_sym_SEMI, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(109), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [433] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(115), 1, + anon_sym_SEMI, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(113), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [464] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(119), 1, + anon_sym_SEMI, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(117), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [495] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(123), 1, + anon_sym_SEMI, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(121), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [526] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(127), 1, + anon_sym_SEMI, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(125), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [557] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(131), 1, + anon_sym_SEMI, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(129), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [588] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(133), 19, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_SEMI, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [617] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(137), 1, + anon_sym_SEMI, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(135), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [648] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(141), 1, + anon_sym_SEMI, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(139), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [679] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(143), 19, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_SEMI, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [708] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(147), 1, + anon_sym_SEMI, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(145), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [739] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(149), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [767] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(151), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [795] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(153), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [823] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(155), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [851] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(157), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [879] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(159), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [907] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(161), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [935] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(163), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [963] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(165), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [991] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(167), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1019] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(169), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1047] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(171), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1075] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(173), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1103] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(113), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1131] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(135), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1159] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(175), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1187] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(177), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1215] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(179), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1243] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(181), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1271] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(183), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1299] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(185), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1327] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(187), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1355] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(189), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1383] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(191), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1411] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(193), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1439] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(195), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1467] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(145), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1495] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(197), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1523] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(199), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1551] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(201), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1579] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(203), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1607] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(205), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1635] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(207), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1663] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(209), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1691] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(211), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1719] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(213), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1747] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(215), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1775] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(217), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1803] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(219), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1831] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(221), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1859] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(223), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1887] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(225), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1915] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(227), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1943] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(229), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1971] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(231), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [1999] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(233), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [2027] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(235), 18, + ts_builtin_sym_end, + anon_sym_pragma, + anon_sym_include, + anon_sym_import, + anon_sym_RBRACE, + anon_sym_export, + anon_sym_module, + anon_sym_struct, + anon_sym_enum, + anon_sym_contract, + anon_sym_new, + anon_sym_type, + anon_sym_sealed, + anon_sym_ledger, + anon_sym_witness, + anon_sym_constructor, + anon_sym_pure, + anon_sym_circuit, + [2055] = 7, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(242), 1, + anon_sym_LT, + ACTIONS(245), 1, + anon_sym_LBRACK, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(240), 4, + anon_sym_SEMI, + anon_sym_LBRACE, + anon_sym_GT, + anon_sym_RBRACK, + STATE(67), 4, + sym_generic_arguments, + sym__type_item, + sym__tuple_type, + aux_sym_generic_arguments_repeat1, + ACTIONS(237), 6, + anon_sym_COMMA, + anon_sym_COLON, + anon_sym_DOT_DOT, + sym_identifier, + sym_number, + sym_string, + [2089] = 9, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(248), 1, + anon_sym_LBRACE, + ACTIONS(253), 1, + anon_sym_LBRACK, + ACTIONS(256), 1, + anon_sym_LPAREN, + ACTIONS(259), 1, + anon_sym_SLASH, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(262), 2, + sym__opaque_token, + sym_string, + ACTIONS(251), 3, + anon_sym_RBRACE, + anon_sym_RBRACK, + anon_sym_RPAREN, + STATE(68), 5, + sym_block, + sym__paren_group, + sym__bracket_group, + sym__opaque, + aux_sym_block_repeat1, + [2125] = 7, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(269), 1, + anon_sym_LT, + ACTIONS(271), 1, + anon_sym_LBRACK, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(267), 2, + anon_sym_SEMI, + anon_sym_LBRACE, + STATE(67), 4, + sym_generic_arguments, + sym__type_item, + sym__tuple_type, + aux_sym_generic_arguments_repeat1, + ACTIONS(265), 6, + anon_sym_COMMA, + anon_sym_COLON, + anon_sym_DOT_DOT, + sym_identifier, + sym_number, + sym_string, + [2157] = 7, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(269), 1, + anon_sym_LT, + ACTIONS(271), 1, + anon_sym_LBRACK, + STATE(163), 1, + sym_type_expression, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + STATE(69), 4, + sym_generic_arguments, + sym__type_item, + sym__tuple_type, + aux_sym_generic_arguments_repeat1, + ACTIONS(273), 6, + anon_sym_COMMA, + anon_sym_COLON, + anon_sym_DOT_DOT, + sym_identifier, + sym_number, + sym_string, + [2188] = 7, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(269), 1, + anon_sym_LT, + ACTIONS(271), 1, + anon_sym_LBRACK, + STATE(187), 1, + sym_type_expression, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + STATE(69), 4, + sym_generic_arguments, + sym__type_item, + sym__tuple_type, + aux_sym_generic_arguments_repeat1, + ACTIONS(273), 6, + anon_sym_COMMA, + anon_sym_COLON, + anon_sym_DOT_DOT, + sym_identifier, + sym_number, + sym_string, + [2219] = 7, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(269), 1, + anon_sym_LT, + ACTIONS(271), 1, + anon_sym_LBRACK, + ACTIONS(277), 1, + anon_sym_RBRACK, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + STATE(79), 4, + sym_generic_arguments, + sym__type_item, + sym__tuple_type, + aux_sym_generic_arguments_repeat1, + ACTIONS(275), 6, + anon_sym_COMMA, + anon_sym_COLON, + anon_sym_DOT_DOT, + sym_identifier, + sym_number, + sym_string, + [2250] = 7, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(269), 1, + anon_sym_LT, + ACTIONS(271), 1, + anon_sym_LBRACK, + STATE(223), 1, + sym_type_expression, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + STATE(69), 4, + sym_generic_arguments, + sym__type_item, + sym__tuple_type, + aux_sym_generic_arguments_repeat1, + ACTIONS(273), 6, + anon_sym_COMMA, + anon_sym_COLON, + anon_sym_DOT_DOT, + sym_identifier, + sym_number, + sym_string, + [2281] = 7, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(269), 1, + anon_sym_LT, + ACTIONS(271), 1, + anon_sym_LBRACK, + STATE(229), 1, + sym_type_expression, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + STATE(69), 4, + sym_generic_arguments, + sym__type_item, + sym__tuple_type, + aux_sym_generic_arguments_repeat1, + ACTIONS(273), 6, + anon_sym_COMMA, + anon_sym_COLON, + anon_sym_DOT_DOT, + sym_identifier, + sym_number, + sym_string, + [2312] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(279), 2, + anon_sym_prefix, + sym_identifier, + ACTIONS(281), 11, + anon_sym_SEMI, + anon_sym_LBRACE, + anon_sym_COMMA, + anon_sym_COLON, + anon_sym_LT, + anon_sym_GT, + anon_sym_DOT_DOT, + anon_sym_LBRACK, + anon_sym_RBRACK, + sym_number, + sym_string, + [2337] = 7, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(269), 1, + anon_sym_LT, + ACTIONS(271), 1, + anon_sym_LBRACK, + ACTIONS(283), 1, + anon_sym_GT, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + STATE(67), 4, + sym_generic_arguments, + sym__type_item, + sym__tuple_type, + aux_sym_generic_arguments_repeat1, + ACTIONS(265), 6, + anon_sym_COMMA, + anon_sym_COLON, + anon_sym_DOT_DOT, + sym_identifier, + sym_number, + sym_string, + [2368] = 7, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(269), 1, + anon_sym_LT, + ACTIONS(271), 1, + anon_sym_LBRACK, + STATE(247), 1, + sym_type_expression, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + STATE(69), 4, + sym_generic_arguments, + sym__type_item, + sym__tuple_type, + aux_sym_generic_arguments_repeat1, + ACTIONS(273), 6, + anon_sym_COMMA, + anon_sym_COLON, + anon_sym_DOT_DOT, + sym_identifier, + sym_number, + sym_string, + [2399] = 7, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(269), 1, + anon_sym_LT, + ACTIONS(271), 1, + anon_sym_LBRACK, + STATE(252), 1, + sym_type_expression, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + STATE(69), 4, + sym_generic_arguments, + sym__type_item, + sym__tuple_type, + aux_sym_generic_arguments_repeat1, + ACTIONS(273), 6, + anon_sym_COMMA, + anon_sym_COLON, + anon_sym_DOT_DOT, + sym_identifier, + sym_number, + sym_string, + [2430] = 7, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(269), 1, + anon_sym_LT, + ACTIONS(271), 1, + anon_sym_LBRACK, + ACTIONS(285), 1, + anon_sym_RBRACK, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + STATE(67), 4, + sym_generic_arguments, + sym__type_item, + sym__tuple_type, + aux_sym_generic_arguments_repeat1, + ACTIONS(265), 6, + anon_sym_COMMA, + anon_sym_COLON, + anon_sym_DOT_DOT, + sym_identifier, + sym_number, + sym_string, + [2461] = 7, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(269), 1, + anon_sym_LT, + ACTIONS(271), 1, + anon_sym_LBRACK, + STATE(201), 1, + sym_type_expression, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + STATE(69), 4, + sym_generic_arguments, + sym__type_item, + sym__tuple_type, + aux_sym_generic_arguments_repeat1, + ACTIONS(273), 6, + anon_sym_COMMA, + anon_sym_COLON, + anon_sym_DOT_DOT, + sym_identifier, + sym_number, + sym_string, + [2492] = 7, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(269), 1, + anon_sym_LT, + ACTIONS(271), 1, + anon_sym_LBRACK, + STATE(204), 1, + sym_type_expression, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + STATE(69), 4, + sym_generic_arguments, + sym__type_item, + sym__tuple_type, + aux_sym_generic_arguments_repeat1, + ACTIONS(273), 6, + anon_sym_COMMA, + anon_sym_COLON, + anon_sym_DOT_DOT, + sym_identifier, + sym_number, + sym_string, + [2523] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(287), 2, + anon_sym_prefix, + sym_identifier, + ACTIONS(289), 11, + anon_sym_SEMI, + anon_sym_LBRACE, + anon_sym_COMMA, + anon_sym_COLON, + anon_sym_LT, + anon_sym_GT, + anon_sym_DOT_DOT, + anon_sym_LBRACK, + anon_sym_RBRACK, + sym_number, + sym_string, + [2548] = 7, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(269), 1, + anon_sym_LT, + ACTIONS(271), 1, + anon_sym_LBRACK, + STATE(232), 1, + sym_type_expression, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + STATE(69), 4, + sym_generic_arguments, + sym__type_item, + sym__tuple_type, + aux_sym_generic_arguments_repeat1, + ACTIONS(273), 6, + anon_sym_COMMA, + anon_sym_COLON, + anon_sym_DOT_DOT, + sym_identifier, + sym_number, + sym_string, + [2579] = 7, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(269), 1, + anon_sym_LT, + ACTIONS(271), 1, + anon_sym_LBRACK, + STATE(220), 1, + sym_type_expression, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + STATE(69), 4, + sym_generic_arguments, + sym__type_item, + sym__tuple_type, + aux_sym_generic_arguments_repeat1, + ACTIONS(273), 6, + anon_sym_COMMA, + anon_sym_COLON, + anon_sym_DOT_DOT, + sym_identifier, + sym_number, + sym_string, + [2610] = 7, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(269), 1, + anon_sym_LT, + ACTIONS(271), 1, + anon_sym_LBRACK, + STATE(221), 1, + sym_type_expression, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + STATE(69), 4, + sym_generic_arguments, + sym__type_item, + sym__tuple_type, + aux_sym_generic_arguments_repeat1, + ACTIONS(273), 6, + anon_sym_COMMA, + anon_sym_COLON, + anon_sym_DOT_DOT, + sym_identifier, + sym_number, + sym_string, + [2641] = 7, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(269), 1, + anon_sym_LT, + ACTIONS(271), 1, + anon_sym_LBRACK, + STATE(224), 1, + sym_type_expression, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + STATE(69), 4, + sym_generic_arguments, + sym__type_item, + sym__tuple_type, + aux_sym_generic_arguments_repeat1, + ACTIONS(273), 6, + anon_sym_COMMA, + anon_sym_COLON, + anon_sym_DOT_DOT, + sym_identifier, + sym_number, + sym_string, + [2672] = 7, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(269), 1, + anon_sym_LT, + ACTIONS(271), 1, + anon_sym_LBRACK, + STATE(171), 1, + sym_type_expression, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + STATE(69), 4, + sym_generic_arguments, + sym__type_item, + sym__tuple_type, + aux_sym_generic_arguments_repeat1, + ACTIONS(273), 6, + anon_sym_COMMA, + anon_sym_COLON, + anon_sym_DOT_DOT, + sym_identifier, + sym_number, + sym_string, + [2703] = 7, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(269), 1, + anon_sym_LT, + ACTIONS(271), 1, + anon_sym_LBRACK, + STATE(234), 1, + sym_type_expression, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + STATE(69), 4, + sym_generic_arguments, + sym__type_item, + sym__tuple_type, + aux_sym_generic_arguments_repeat1, + ACTIONS(273), 6, + anon_sym_COMMA, + anon_sym_COLON, + anon_sym_DOT_DOT, + sym_identifier, + sym_number, + sym_string, + [2734] = 7, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(269), 1, + anon_sym_LT, + ACTIONS(271), 1, + anon_sym_LBRACK, + STATE(177), 1, + sym_type_expression, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + STATE(69), 4, + sym_generic_arguments, + sym__type_item, + sym__tuple_type, + aux_sym_generic_arguments_repeat1, + ACTIONS(273), 6, + anon_sym_COMMA, + anon_sym_COLON, + anon_sym_DOT_DOT, + sym_identifier, + sym_number, + sym_string, + [2765] = 7, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(269), 1, + anon_sym_LT, + ACTIONS(271), 1, + anon_sym_LBRACK, + STATE(241), 1, + sym_type_expression, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + STATE(69), 4, + sym_generic_arguments, + sym__type_item, + sym__tuple_type, + aux_sym_generic_arguments_repeat1, + ACTIONS(273), 6, + anon_sym_COMMA, + anon_sym_COLON, + anon_sym_DOT_DOT, + sym_identifier, + sym_number, + sym_string, + [2796] = 7, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(269), 1, + anon_sym_LT, + ACTIONS(271), 1, + anon_sym_LBRACK, + STATE(244), 1, + sym_type_expression, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + STATE(69), 4, + sym_generic_arguments, + sym__type_item, + sym__tuple_type, + aux_sym_generic_arguments_repeat1, + ACTIONS(273), 6, + anon_sym_COMMA, + anon_sym_COLON, + anon_sym_DOT_DOT, + sym_identifier, + sym_number, + sym_string, + [2827] = 7, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(269), 1, + anon_sym_LT, + ACTIONS(271), 1, + anon_sym_LBRACK, + STATE(181), 1, + sym_type_expression, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + STATE(69), 4, + sym_generic_arguments, + sym__type_item, + sym__tuple_type, + aux_sym_generic_arguments_repeat1, + ACTIONS(273), 6, + anon_sym_COMMA, + anon_sym_COLON, + anon_sym_DOT_DOT, + sym_identifier, + sym_number, + sym_string, + [2858] = 7, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(269), 1, + anon_sym_LT, + ACTIONS(271), 1, + anon_sym_LBRACK, + STATE(182), 1, + sym_type_expression, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + STATE(69), 4, + sym_generic_arguments, + sym__type_item, + sym__tuple_type, + aux_sym_generic_arguments_repeat1, + ACTIONS(273), 6, + anon_sym_COMMA, + anon_sym_COLON, + anon_sym_DOT_DOT, + sym_identifier, + sym_number, + sym_string, + [2889] = 7, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(269), 1, + anon_sym_LT, + ACTIONS(271), 1, + anon_sym_LBRACK, + ACTIONS(293), 1, + anon_sym_GT, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + STATE(76), 4, + sym_generic_arguments, + sym__type_item, + sym__tuple_type, + aux_sym_generic_arguments_repeat1, + ACTIONS(291), 6, + anon_sym_COMMA, + anon_sym_COLON, + anon_sym_DOT_DOT, + sym_identifier, + sym_number, + sym_string, + [2920] = 7, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(269), 1, + anon_sym_LT, + ACTIONS(271), 1, + anon_sym_LBRACK, + STATE(217), 1, + sym_type_expression, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + STATE(69), 4, + sym_generic_arguments, + sym__type_item, + sym__tuple_type, + aux_sym_generic_arguments_repeat1, + ACTIONS(273), 6, + anon_sym_COMMA, + anon_sym_COLON, + anon_sym_DOT_DOT, + sym_identifier, + sym_number, + sym_string, + [2951] = 9, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(295), 1, + anon_sym_LBRACE, + ACTIONS(297), 1, + anon_sym_RBRACE, + ACTIONS(299), 1, + anon_sym_LBRACK, + ACTIONS(301), 1, + anon_sym_LPAREN, + ACTIONS(303), 1, + anon_sym_SLASH, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(305), 2, + sym__opaque_token, + sym_string, + STATE(68), 5, + sym_block, + sym__paren_group, + sym__bracket_group, + sym__opaque, + aux_sym_block_repeat1, + [2985] = 9, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(295), 1, + anon_sym_LBRACE, + ACTIONS(299), 1, + anon_sym_LBRACK, + ACTIONS(301), 1, + anon_sym_LPAREN, + ACTIONS(307), 1, + anon_sym_RBRACK, + ACTIONS(309), 1, + anon_sym_SLASH, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(311), 2, + sym__opaque_token, + sym_string, + STATE(104), 5, + sym_block, + sym__paren_group, + sym__bracket_group, + sym__opaque, + aux_sym_block_repeat1, + [3019] = 9, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(295), 1, + anon_sym_LBRACE, + ACTIONS(299), 1, + anon_sym_LBRACK, + ACTIONS(301), 1, + anon_sym_LPAREN, + ACTIONS(303), 1, + anon_sym_SLASH, + ACTIONS(313), 1, + anon_sym_RBRACE, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(305), 2, + sym__opaque_token, + sym_string, + STATE(68), 5, + sym_block, + sym__paren_group, + sym__bracket_group, + sym__opaque, + aux_sym_block_repeat1, + [3053] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(315), 12, + anon_sym_SEMI, + anon_sym_LBRACE, + anon_sym_COMMA, + anon_sym_COLON, + anon_sym_LT, + anon_sym_GT, + anon_sym_DOT_DOT, + anon_sym_LBRACK, + anon_sym_RBRACK, + sym_identifier, + sym_number, + sym_string, + [3075] = 9, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(295), 1, + anon_sym_LBRACE, + ACTIONS(299), 1, + anon_sym_LBRACK, + ACTIONS(301), 1, + anon_sym_LPAREN, + ACTIONS(317), 1, + anon_sym_RBRACE, + ACTIONS(319), 1, + anon_sym_SLASH, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(321), 2, + sym__opaque_token, + sym_string, + STATE(98), 5, + sym_block, + sym__paren_group, + sym__bracket_group, + sym__opaque, + aux_sym_block_repeat1, + [3109] = 9, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(295), 1, + anon_sym_LBRACE, + ACTIONS(299), 1, + anon_sym_LBRACK, + ACTIONS(301), 1, + anon_sym_LPAREN, + ACTIONS(323), 1, + anon_sym_RPAREN, + ACTIONS(325), 1, + anon_sym_SLASH, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(327), 2, + sym__opaque_token, + sym_string, + STATE(106), 5, + sym_block, + sym__paren_group, + sym__bracket_group, + sym__opaque, + aux_sym_block_repeat1, + [3143] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(329), 12, + anon_sym_SEMI, + anon_sym_LBRACE, + anon_sym_COMMA, + anon_sym_COLON, + anon_sym_LT, + anon_sym_GT, + anon_sym_DOT_DOT, + anon_sym_LBRACK, + anon_sym_RBRACK, + sym_identifier, + sym_number, + sym_string, + [3165] = 9, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(295), 1, + anon_sym_LBRACE, + ACTIONS(299), 1, + anon_sym_LBRACK, + ACTIONS(301), 1, + anon_sym_LPAREN, + ACTIONS(331), 1, + anon_sym_RPAREN, + ACTIONS(333), 1, + anon_sym_SLASH, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(335), 2, + sym__opaque_token, + sym_string, + STATE(107), 5, + sym_block, + sym__paren_group, + sym__bracket_group, + sym__opaque, + aux_sym_block_repeat1, + [3199] = 9, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(295), 1, + anon_sym_LBRACE, + ACTIONS(299), 1, + anon_sym_LBRACK, + ACTIONS(301), 1, + anon_sym_LPAREN, + ACTIONS(303), 1, + anon_sym_SLASH, + ACTIONS(337), 1, + anon_sym_RBRACK, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(305), 2, + sym__opaque_token, + sym_string, + STATE(68), 5, + sym_block, + sym__paren_group, + sym__bracket_group, + sym__opaque, + aux_sym_block_repeat1, + [3233] = 14, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(339), 1, + anon_sym_LBRACE, + ACTIONS(341), 1, + anon_sym_module, + ACTIONS(343), 1, + anon_sym_struct, + ACTIONS(345), 1, + anon_sym_enum, + ACTIONS(347), 1, + anon_sym_contract, + ACTIONS(349), 1, + anon_sym_new, + ACTIONS(351), 1, + anon_sym_type, + ACTIONS(353), 1, + anon_sym_sealed, + ACTIONS(355), 1, + anon_sym_ledger, + ACTIONS(357), 1, + anon_sym_witness, + ACTIONS(359), 1, + anon_sym_pure, + ACTIONS(361), 1, + anon_sym_circuit, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [3277] = 9, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(295), 1, + anon_sym_LBRACE, + ACTIONS(299), 1, + anon_sym_LBRACK, + ACTIONS(301), 1, + anon_sym_LPAREN, + ACTIONS(303), 1, + anon_sym_SLASH, + ACTIONS(363), 1, + anon_sym_RPAREN, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(305), 2, + sym__opaque_token, + sym_string, + STATE(68), 5, + sym_block, + sym__paren_group, + sym__bracket_group, + sym__opaque, + aux_sym_block_repeat1, + [3311] = 9, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(295), 1, + anon_sym_LBRACE, + ACTIONS(299), 1, + anon_sym_LBRACK, + ACTIONS(301), 1, + anon_sym_LPAREN, + ACTIONS(303), 1, + anon_sym_SLASH, + ACTIONS(365), 1, + anon_sym_RPAREN, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(305), 2, + sym__opaque_token, + sym_string, + STATE(68), 5, + sym_block, + sym__paren_group, + sym__bracket_group, + sym__opaque, + aux_sym_block_repeat1, + [3345] = 9, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(295), 1, + anon_sym_LBRACE, + ACTIONS(299), 1, + anon_sym_LBRACK, + ACTIONS(301), 1, + anon_sym_LPAREN, + ACTIONS(367), 1, + anon_sym_RBRACE, + ACTIONS(369), 1, + anon_sym_SLASH, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(371), 2, + sym__opaque_token, + sym_string, + STATE(96), 5, + sym_block, + sym__paren_group, + sym__bracket_group, + sym__opaque, + aux_sym_block_repeat1, + [3379] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(375), 1, + anon_sym_SLASH, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(373), 8, + anon_sym_LBRACE, + anon_sym_RBRACE, + anon_sym_LBRACK, + anon_sym_RBRACK, + anon_sym_LPAREN, + anon_sym_RPAREN, + sym__opaque_token, + sym_string, + [3400] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(379), 1, + anon_sym_SLASH, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(377), 8, + anon_sym_LBRACE, + anon_sym_RBRACE, + anon_sym_LBRACK, + anon_sym_RBRACK, + anon_sym_LPAREN, + anon_sym_RPAREN, + sym__opaque_token, + sym_string, + [3421] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(383), 1, + anon_sym_SLASH, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(381), 8, + anon_sym_LBRACE, + anon_sym_RBRACE, + anon_sym_LBRACK, + anon_sym_RBRACK, + anon_sym_LPAREN, + anon_sym_RPAREN, + sym__opaque_token, + sym_string, + [3442] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(387), 1, + anon_sym_SLASH, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(385), 8, + anon_sym_LBRACE, + anon_sym_RBRACE, + anon_sym_LBRACK, + anon_sym_RBRACK, + anon_sym_LPAREN, + anon_sym_RPAREN, + sym__opaque_token, + sym_string, + [3463] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(389), 1, + anon_sym_SLASH, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(133), 8, + anon_sym_LBRACE, + anon_sym_RBRACE, + anon_sym_LBRACK, + anon_sym_RBRACK, + anon_sym_LPAREN, + anon_sym_RPAREN, + sym__opaque_token, + sym_string, + [3484] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(391), 1, + anon_sym_SLASH, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(143), 8, + anon_sym_LBRACE, + anon_sym_RBRACE, + anon_sym_LBRACK, + anon_sym_RBRACK, + anon_sym_LPAREN, + anon_sym_RPAREN, + sym__opaque_token, + sym_string, + [3505] = 7, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(269), 1, + anon_sym_LT, + ACTIONS(393), 1, + anon_sym_SEMI, + ACTIONS(395), 1, + anon_sym_prefix, + STATE(148), 1, + sym_generic_arguments, + STATE(237), 1, + sym_import_prefix, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [3528] = 7, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(269), 1, + anon_sym_LT, + ACTIONS(395), 1, + anon_sym_prefix, + ACTIONS(397), 1, + anon_sym_SEMI, + STATE(140), 1, + sym_generic_arguments, + STATE(200), 1, + sym_import_prefix, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [3551] = 6, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(399), 1, + anon_sym_LBRACE, + ACTIONS(401), 1, + anon_sym_LT, + STATE(11), 1, + sym_block, + STATE(170), 1, + sym_generic_parameters, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [3571] = 6, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(399), 1, + anon_sym_LBRACE, + ACTIONS(401), 1, + anon_sym_LT, + STATE(7), 1, + sym_block, + STATE(168), 1, + sym_generic_parameters, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [3591] = 6, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(403), 1, + sym_identifier, + ACTIONS(405), 1, + anon_sym_GT, + ACTIONS(407), 1, + anon_sym_POUND, + STATE(173), 1, + sym_generic_parameter, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [3611] = 5, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(411), 1, + anon_sym_LBRACE, + STATE(158), 1, + sym_import_selection, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(409), 2, + sym_identifier, + sym_string, + [3629] = 6, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(401), 1, + anon_sym_LT, + ACTIONS(413), 1, + anon_sym_LPAREN, + STATE(159), 1, + sym_generic_parameters, + STATE(211), 1, + sym_parameter_list, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [3649] = 6, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(401), 1, + anon_sym_LT, + ACTIONS(415), 1, + anon_sym_LBRACE, + STATE(41), 1, + sym_module_body, + STATE(191), 1, + sym_generic_parameters, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [3669] = 6, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(401), 1, + anon_sym_LT, + ACTIONS(415), 1, + anon_sym_LBRACE, + STATE(42), 1, + sym_module_body, + STATE(189), 1, + sym_generic_parameters, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [3689] = 6, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(403), 1, + sym_identifier, + ACTIONS(407), 1, + anon_sym_POUND, + ACTIONS(417), 1, + anon_sym_GT, + STATE(132), 1, + sym_generic_parameter, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [3709] = 6, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(401), 1, + anon_sym_LT, + ACTIONS(413), 1, + anon_sym_LPAREN, + STATE(188), 1, + sym_generic_parameters, + STATE(260), 1, + sym_parameter_list, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [3729] = 6, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(401), 1, + anon_sym_LT, + ACTIONS(413), 1, + anon_sym_LPAREN, + STATE(180), 1, + sym_generic_parameters, + STATE(203), 1, + sym_parameter_list, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [3749] = 6, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(403), 1, + sym_identifier, + ACTIONS(407), 1, + anon_sym_POUND, + ACTIONS(419), 1, + anon_sym_GT, + STATE(173), 1, + sym_generic_parameter, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [3769] = 6, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(401), 1, + anon_sym_LT, + ACTIONS(413), 1, + anon_sym_LPAREN, + STATE(155), 1, + sym_generic_parameters, + STATE(259), 1, + sym_parameter_list, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [3789] = 6, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(401), 1, + anon_sym_LT, + ACTIONS(413), 1, + anon_sym_LPAREN, + STATE(190), 1, + sym_generic_parameters, + STATE(263), 1, + sym_parameter_list, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [3809] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(421), 3, + anon_sym_LBRACE, + anon_sym_EQ, + anon_sym_LPAREN, + [3822] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(423), 3, + anon_sym_LBRACE, + anon_sym_EQ, + anon_sym_LPAREN, + [3835] = 5, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(425), 1, + anon_sym_COMMA, + ACTIONS(427), 1, + anon_sym_GT, + STATE(139), 1, + aux_sym_generic_parameters_repeat1, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [3852] = 5, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(429), 1, + sym_identifier, + ACTIONS(431), 1, + anon_sym_RBRACE, + STATE(167), 1, + sym_import_element, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [3869] = 5, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(433), 1, + anon_sym_COMMA, + ACTIONS(436), 1, + anon_sym_RBRACE, + STATE(134), 1, + aux_sym_import_selection_repeat1, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [3886] = 5, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(438), 1, + anon_sym_COMMA, + ACTIONS(441), 1, + anon_sym_RBRACE, + STATE(135), 1, + aux_sym_export_declaration_repeat1, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [3903] = 5, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(401), 1, + anon_sym_LT, + ACTIONS(443), 1, + anon_sym_EQ, + STATE(250), 1, + sym_generic_parameters, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [3920] = 5, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(429), 1, + sym_identifier, + ACTIONS(445), 1, + anon_sym_RBRACE, + STATE(167), 1, + sym_import_element, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [3937] = 5, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(445), 1, + anon_sym_RBRACE, + ACTIONS(447), 1, + anon_sym_COMMA, + STATE(134), 1, + aux_sym_import_selection_repeat1, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [3954] = 5, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(419), 1, + anon_sym_GT, + ACTIONS(449), 1, + anon_sym_COMMA, + STATE(146), 1, + aux_sym_generic_parameters_repeat1, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [3971] = 5, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(395), 1, + anon_sym_prefix, + ACTIONS(451), 1, + anon_sym_SEMI, + STATE(219), 1, + sym_import_prefix, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [3988] = 5, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(453), 1, + anon_sym_COMMA, + ACTIONS(455), 1, + anon_sym_RBRACE, + STATE(135), 1, + aux_sym_export_declaration_repeat1, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4005] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(459), 1, + anon_sym_as, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(457), 2, + anon_sym_COMMA, + anon_sym_RBRACE, + [4020] = 5, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(461), 1, + anon_sym_COMMA, + ACTIONS(463), 1, + anon_sym_RBRACE, + STATE(138), 1, + aux_sym_import_selection_repeat1, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4037] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(465), 3, + anon_sym_LBRACE, + anon_sym_EQ, + anon_sym_LPAREN, + [4050] = 5, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(429), 1, + sym_identifier, + ACTIONS(467), 1, + anon_sym_RBRACE, + STATE(143), 1, + sym_import_element, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4067] = 5, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(469), 1, + anon_sym_COMMA, + ACTIONS(472), 1, + anon_sym_GT, + STATE(146), 1, + aux_sym_generic_parameters_repeat1, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4084] = 5, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(401), 1, + anon_sym_LT, + ACTIONS(474), 1, + anon_sym_EQ, + STATE(243), 1, + sym_generic_parameters, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4101] = 5, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(395), 1, + anon_sym_prefix, + ACTIONS(476), 1, + anon_sym_SEMI, + STATE(197), 1, + sym_import_prefix, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4118] = 5, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(478), 1, + anon_sym_COMMA, + ACTIONS(480), 1, + anon_sym_RBRACE, + STATE(141), 1, + aux_sym_export_declaration_repeat1, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4135] = 5, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(403), 1, + sym_identifier, + ACTIONS(407), 1, + anon_sym_POUND, + STATE(173), 1, + sym_generic_parameter, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4152] = 5, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(401), 1, + anon_sym_LT, + ACTIONS(482), 1, + anon_sym_EQ, + STATE(245), 1, + sym_generic_parameters, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4169] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(484), 3, + anon_sym_LBRACE, + anon_sym_EQ, + anon_sym_LPAREN, + [4182] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(486), 2, + sym_identifier, + sym_string, + [4194] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(488), 2, + anon_sym_LBRACE, + anon_sym_COLON, + [4206] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(413), 1, + anon_sym_LPAREN, + STATE(225), 1, + sym_parameter_list, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4220] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(490), 2, + anon_sym_COMMA, + anon_sym_GT, + [4232] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(413), 1, + anon_sym_LPAREN, + STATE(160), 1, + sym_parameter_list, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4246] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(492), 2, + sym_identifier, + sym_string, + [4258] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(413), 1, + anon_sym_LPAREN, + STATE(194), 1, + sym_parameter_list, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4272] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(399), 1, + anon_sym_LBRACE, + STATE(22), 1, + sym_block, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4286] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(494), 2, + anon_sym_LBRACE, + anon_sym_COLON, + [4298] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(455), 1, + anon_sym_RBRACE, + ACTIONS(496), 1, + sym_identifier, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4312] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(399), 1, + anon_sym_LBRACE, + STATE(53), 1, + sym_block, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4326] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(498), 2, + sym_identifier, + sym_string, + [4338] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(429), 1, + sym_identifier, + STATE(167), 1, + sym_import_element, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4352] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(500), 2, + anon_sym_COMMA, + anon_sym_RBRACE, + [4364] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(436), 2, + anon_sym_COMMA, + anon_sym_RBRACE, + [4376] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(399), 1, + anon_sym_LBRACE, + STATE(14), 1, + sym_block, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4390] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(502), 1, + sym_identifier, + ACTIONS(504), 1, + anon_sym_implements, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4404] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(399), 1, + anon_sym_LBRACE, + STATE(17), 1, + sym_block, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4418] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(399), 1, + anon_sym_LBRACE, + STATE(58), 1, + sym_block, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4432] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(506), 2, + anon_sym_COMMA, + anon_sym_GT, + [4444] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(472), 2, + anon_sym_COMMA, + anon_sym_GT, + [4456] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(508), 1, + sym_identifier, + ACTIONS(510), 1, + anon_sym_RBRACE, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4470] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(441), 2, + anon_sym_COMMA, + anon_sym_RBRACE, + [4482] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(512), 2, + sym_identifier, + sym_string, + [4494] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(399), 1, + anon_sym_LBRACE, + STATE(60), 1, + sym_block, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4508] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + ACTIONS(514), 2, + sym_identifier, + sym_string, + [4520] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(496), 1, + sym_identifier, + ACTIONS(516), 1, + anon_sym_RBRACE, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4534] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(413), 1, + anon_sym_LPAREN, + STATE(230), 1, + sym_parameter_list, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4548] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(399), 1, + anon_sym_LBRACE, + STATE(63), 1, + sym_block, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4562] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(399), 1, + anon_sym_LBRACE, + STATE(64), 1, + sym_block, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4576] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(399), 1, + anon_sym_LBRACE, + STATE(8), 1, + sym_block, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4590] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(399), 1, + anon_sym_LBRACE, + STATE(12), 1, + sym_block, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4604] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(399), 1, + anon_sym_LBRACE, + STATE(13), 1, + sym_block, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4618] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(399), 1, + anon_sym_LBRACE, + STATE(9), 1, + sym_block, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4632] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(399), 1, + anon_sym_LBRACE, + STATE(65), 1, + sym_block, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4646] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(413), 1, + anon_sym_LPAREN, + STATE(253), 1, + sym_parameter_list, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4660] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(415), 1, + anon_sym_LBRACE, + STATE(23), 1, + sym_module_body, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4674] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(413), 1, + anon_sym_LPAREN, + STATE(261), 1, + sym_parameter_list, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4688] = 4, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(415), 1, + anon_sym_LBRACE, + STATE(35), 1, + sym_module_body, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4702] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(518), 1, + sym_identifier, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4713] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(520), 1, + sym_identifier, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4724] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(522), 1, + anon_sym_COLON, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4735] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(524), 1, + sym_identifier, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4746] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(526), 1, + sym_identifier, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4757] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(528), 1, + anon_sym_SEMI, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4768] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(530), 1, + anon_sym_from, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4779] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(361), 1, + anon_sym_circuit, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4790] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(451), 1, + anon_sym_SEMI, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4801] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(532), 1, + anon_sym_SEMI, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4812] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(534), 1, + sym_string, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4823] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(536), 1, + anon_sym_COLON, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4834] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(538), 1, + anon_sym_SEMI, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4845] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(540), 1, + sym_identifier, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4856] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(542), 1, + anon_sym_type, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4867] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(544), 1, + ts_builtin_sym_end, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4878] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(546), 1, + sym_identifier, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4889] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(548), 1, + anon_sym_ledger, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4900] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(550), 1, + anon_sym_from, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4911] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(552), 1, + anon_sym_COLON, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4922] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(554), 1, + anon_sym_SEMI, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4933] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(556), 1, + anon_sym_circuit, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4944] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(558), 1, + anon_sym_from, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4955] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(496), 1, + sym_identifier, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4966] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(560), 1, + sym_identifier, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4977] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(562), 1, + anon_sym_SEMI, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4988] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(564), 1, + sym_identifier, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [4999] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(566), 1, + anon_sym_SEMI, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5010] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(568), 1, + anon_sym_SEMI, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5021] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(570), 1, + anon_sym_SEMI, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5032] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(572), 1, + sym_identifier, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5043] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(574), 1, + anon_sym_SEMI, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5054] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(576), 1, + anon_sym_SEMI, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5065] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(578), 1, + anon_sym_COLON, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5076] = 2, + ACTIONS(580), 1, + sym_version_constraint, + ACTIONS(5), 3, + sym_doc_comment, + sym_block_comment, + sym_line_comment, + [5085] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(582), 1, + anon_sym_SEMI, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5096] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(584), 1, + sym_identifier, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5107] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(586), 1, + anon_sym_SEMI, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5118] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(588), 1, + anon_sym_COLON, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5129] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(590), 1, + sym_identifier, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5140] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(592), 1, + anon_sym_SEMI, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5151] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(594), 1, + sym_identifier, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5162] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(596), 1, + anon_sym_SEMI, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5173] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(598), 1, + sym_identifier, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5184] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(351), 1, + anon_sym_type, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5195] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(476), 1, + anon_sym_SEMI, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5206] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(600), 1, + anon_sym_COLON, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5217] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(602), 1, + sym_identifier, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5228] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(604), 1, + sym_identifier, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5239] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(606), 1, + anon_sym_SEMI, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5250] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(608), 1, + sym_identifier, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5261] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(610), 1, + anon_sym_EQ, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5272] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(612), 1, + anon_sym_SEMI, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5283] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(614), 1, + anon_sym_EQ, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5294] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(616), 1, + anon_sym_COLON, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5305] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(618), 1, + anon_sym_SEMI, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5316] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(620), 1, + anon_sym_from, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5327] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(355), 1, + anon_sym_ledger, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5338] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(622), 1, + anon_sym_EQ, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5349] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(624), 1, + sym_identifier, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5360] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(626), 1, + anon_sym_SEMI, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5371] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(628), 1, + anon_sym_COLON, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5382] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(630), 1, + sym_identifier, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5393] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(632), 1, + anon_sym_SEMI, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5404] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(634), 1, + sym_identifier, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5415] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(636), 1, + sym_identifier, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5426] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(638), 1, + anon_sym_COLON, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5437] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(640), 1, + anon_sym_COLON, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5448] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(642), 1, + anon_sym_COLON, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5459] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(644), 1, + anon_sym_COLON, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5470] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(646), 1, + sym_identifier, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5481] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(648), 1, + anon_sym_COLON, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, + [5492] = 3, + ACTIONS(5), 1, + sym_block_comment, + ACTIONS(650), 1, + sym_identifier, + ACTIONS(3), 2, + sym_doc_comment, + sym_line_comment, +}; + +static const uint32_t ts_small_parse_table_map[] = { + [SMALL_STATE(2)] = 0, + [SMALL_STATE(3)] = 78, + [SMALL_STATE(4)] = 155, + [SMALL_STATE(5)] = 232, + [SMALL_STATE(6)] = 309, + [SMALL_STATE(7)] = 340, + [SMALL_STATE(8)] = 371, + [SMALL_STATE(9)] = 402, + [SMALL_STATE(10)] = 433, + [SMALL_STATE(11)] = 464, + [SMALL_STATE(12)] = 495, + [SMALL_STATE(13)] = 526, + [SMALL_STATE(14)] = 557, + [SMALL_STATE(15)] = 588, + [SMALL_STATE(16)] = 617, + [SMALL_STATE(17)] = 648, + [SMALL_STATE(18)] = 679, + [SMALL_STATE(19)] = 708, + [SMALL_STATE(20)] = 739, + [SMALL_STATE(21)] = 767, + [SMALL_STATE(22)] = 795, + [SMALL_STATE(23)] = 823, + [SMALL_STATE(24)] = 851, + [SMALL_STATE(25)] = 879, + [SMALL_STATE(26)] = 907, + [SMALL_STATE(27)] = 935, + [SMALL_STATE(28)] = 963, + [SMALL_STATE(29)] = 991, + [SMALL_STATE(30)] = 1019, + [SMALL_STATE(31)] = 1047, + [SMALL_STATE(32)] = 1075, + [SMALL_STATE(33)] = 1103, + [SMALL_STATE(34)] = 1131, + [SMALL_STATE(35)] = 1159, + [SMALL_STATE(36)] = 1187, + [SMALL_STATE(37)] = 1215, + [SMALL_STATE(38)] = 1243, + [SMALL_STATE(39)] = 1271, + [SMALL_STATE(40)] = 1299, + [SMALL_STATE(41)] = 1327, + [SMALL_STATE(42)] = 1355, + [SMALL_STATE(43)] = 1383, + [SMALL_STATE(44)] = 1411, + [SMALL_STATE(45)] = 1439, + [SMALL_STATE(46)] = 1467, + [SMALL_STATE(47)] = 1495, + [SMALL_STATE(48)] = 1523, + [SMALL_STATE(49)] = 1551, + [SMALL_STATE(50)] = 1579, + [SMALL_STATE(51)] = 1607, + [SMALL_STATE(52)] = 1635, + [SMALL_STATE(53)] = 1663, + [SMALL_STATE(54)] = 1691, + [SMALL_STATE(55)] = 1719, + [SMALL_STATE(56)] = 1747, + [SMALL_STATE(57)] = 1775, + [SMALL_STATE(58)] = 1803, + [SMALL_STATE(59)] = 1831, + [SMALL_STATE(60)] = 1859, + [SMALL_STATE(61)] = 1887, + [SMALL_STATE(62)] = 1915, + [SMALL_STATE(63)] = 1943, + [SMALL_STATE(64)] = 1971, + [SMALL_STATE(65)] = 1999, + [SMALL_STATE(66)] = 2027, + [SMALL_STATE(67)] = 2055, + [SMALL_STATE(68)] = 2089, + [SMALL_STATE(69)] = 2125, + [SMALL_STATE(70)] = 2157, + [SMALL_STATE(71)] = 2188, + [SMALL_STATE(72)] = 2219, + [SMALL_STATE(73)] = 2250, + [SMALL_STATE(74)] = 2281, + [SMALL_STATE(75)] = 2312, + [SMALL_STATE(76)] = 2337, + [SMALL_STATE(77)] = 2368, + [SMALL_STATE(78)] = 2399, + [SMALL_STATE(79)] = 2430, + [SMALL_STATE(80)] = 2461, + [SMALL_STATE(81)] = 2492, + [SMALL_STATE(82)] = 2523, + [SMALL_STATE(83)] = 2548, + [SMALL_STATE(84)] = 2579, + [SMALL_STATE(85)] = 2610, + [SMALL_STATE(86)] = 2641, + [SMALL_STATE(87)] = 2672, + [SMALL_STATE(88)] = 2703, + [SMALL_STATE(89)] = 2734, + [SMALL_STATE(90)] = 2765, + [SMALL_STATE(91)] = 2796, + [SMALL_STATE(92)] = 2827, + [SMALL_STATE(93)] = 2858, + [SMALL_STATE(94)] = 2889, + [SMALL_STATE(95)] = 2920, + [SMALL_STATE(96)] = 2951, + [SMALL_STATE(97)] = 2985, + [SMALL_STATE(98)] = 3019, + [SMALL_STATE(99)] = 3053, + [SMALL_STATE(100)] = 3075, + [SMALL_STATE(101)] = 3109, + [SMALL_STATE(102)] = 3143, + [SMALL_STATE(103)] = 3165, + [SMALL_STATE(104)] = 3199, + [SMALL_STATE(105)] = 3233, + [SMALL_STATE(106)] = 3277, + [SMALL_STATE(107)] = 3311, + [SMALL_STATE(108)] = 3345, + [SMALL_STATE(109)] = 3379, + [SMALL_STATE(110)] = 3400, + [SMALL_STATE(111)] = 3421, + [SMALL_STATE(112)] = 3442, + [SMALL_STATE(113)] = 3463, + [SMALL_STATE(114)] = 3484, + [SMALL_STATE(115)] = 3505, + [SMALL_STATE(116)] = 3528, + [SMALL_STATE(117)] = 3551, + [SMALL_STATE(118)] = 3571, + [SMALL_STATE(119)] = 3591, + [SMALL_STATE(120)] = 3611, + [SMALL_STATE(121)] = 3629, + [SMALL_STATE(122)] = 3649, + [SMALL_STATE(123)] = 3669, + [SMALL_STATE(124)] = 3689, + [SMALL_STATE(125)] = 3709, + [SMALL_STATE(126)] = 3729, + [SMALL_STATE(127)] = 3749, + [SMALL_STATE(128)] = 3769, + [SMALL_STATE(129)] = 3789, + [SMALL_STATE(130)] = 3809, + [SMALL_STATE(131)] = 3822, + [SMALL_STATE(132)] = 3835, + [SMALL_STATE(133)] = 3852, + [SMALL_STATE(134)] = 3869, + [SMALL_STATE(135)] = 3886, + [SMALL_STATE(136)] = 3903, + [SMALL_STATE(137)] = 3920, + [SMALL_STATE(138)] = 3937, + [SMALL_STATE(139)] = 3954, + [SMALL_STATE(140)] = 3971, + [SMALL_STATE(141)] = 3988, + [SMALL_STATE(142)] = 4005, + [SMALL_STATE(143)] = 4020, + [SMALL_STATE(144)] = 4037, + [SMALL_STATE(145)] = 4050, + [SMALL_STATE(146)] = 4067, + [SMALL_STATE(147)] = 4084, + [SMALL_STATE(148)] = 4101, + [SMALL_STATE(149)] = 4118, + [SMALL_STATE(150)] = 4135, + [SMALL_STATE(151)] = 4152, + [SMALL_STATE(152)] = 4169, + [SMALL_STATE(153)] = 4182, + [SMALL_STATE(154)] = 4194, + [SMALL_STATE(155)] = 4206, + [SMALL_STATE(156)] = 4220, + [SMALL_STATE(157)] = 4232, + [SMALL_STATE(158)] = 4246, + [SMALL_STATE(159)] = 4258, + [SMALL_STATE(160)] = 4272, + [SMALL_STATE(161)] = 4286, + [SMALL_STATE(162)] = 4298, + [SMALL_STATE(163)] = 4312, + [SMALL_STATE(164)] = 4326, + [SMALL_STATE(165)] = 4338, + [SMALL_STATE(166)] = 4352, + [SMALL_STATE(167)] = 4364, + [SMALL_STATE(168)] = 4376, + [SMALL_STATE(169)] = 4390, + [SMALL_STATE(170)] = 4404, + [SMALL_STATE(171)] = 4418, + [SMALL_STATE(172)] = 4432, + [SMALL_STATE(173)] = 4444, + [SMALL_STATE(174)] = 4456, + [SMALL_STATE(175)] = 4470, + [SMALL_STATE(176)] = 4482, + [SMALL_STATE(177)] = 4494, + [SMALL_STATE(178)] = 4508, + [SMALL_STATE(179)] = 4520, + [SMALL_STATE(180)] = 4534, + [SMALL_STATE(181)] = 4548, + [SMALL_STATE(182)] = 4562, + [SMALL_STATE(183)] = 4576, + [SMALL_STATE(184)] = 4590, + [SMALL_STATE(185)] = 4604, + [SMALL_STATE(186)] = 4618, + [SMALL_STATE(187)] = 4632, + [SMALL_STATE(188)] = 4646, + [SMALL_STATE(189)] = 4660, + [SMALL_STATE(190)] = 4674, + [SMALL_STATE(191)] = 4688, + [SMALL_STATE(192)] = 4702, + [SMALL_STATE(193)] = 4713, + [SMALL_STATE(194)] = 4724, + [SMALL_STATE(195)] = 4735, + [SMALL_STATE(196)] = 4746, + [SMALL_STATE(197)] = 4757, + [SMALL_STATE(198)] = 4768, + [SMALL_STATE(199)] = 4779, + [SMALL_STATE(200)] = 4790, + [SMALL_STATE(201)] = 4801, + [SMALL_STATE(202)] = 4812, + [SMALL_STATE(203)] = 4823, + [SMALL_STATE(204)] = 4834, + [SMALL_STATE(205)] = 4845, + [SMALL_STATE(206)] = 4856, + [SMALL_STATE(207)] = 4867, + [SMALL_STATE(208)] = 4878, + [SMALL_STATE(209)] = 4889, + [SMALL_STATE(210)] = 4900, + [SMALL_STATE(211)] = 4911, + [SMALL_STATE(212)] = 4922, + [SMALL_STATE(213)] = 4933, + [SMALL_STATE(214)] = 4944, + [SMALL_STATE(215)] = 4955, + [SMALL_STATE(216)] = 4966, + [SMALL_STATE(217)] = 4977, + [SMALL_STATE(218)] = 4988, + [SMALL_STATE(219)] = 4999, + [SMALL_STATE(220)] = 5010, + [SMALL_STATE(221)] = 5021, + [SMALL_STATE(222)] = 5032, + [SMALL_STATE(223)] = 5043, + [SMALL_STATE(224)] = 5054, + [SMALL_STATE(225)] = 5065, + [SMALL_STATE(226)] = 5076, + [SMALL_STATE(227)] = 5085, + [SMALL_STATE(228)] = 5096, + [SMALL_STATE(229)] = 5107, + [SMALL_STATE(230)] = 5118, + [SMALL_STATE(231)] = 5129, + [SMALL_STATE(232)] = 5140, + [SMALL_STATE(233)] = 5151, + [SMALL_STATE(234)] = 5162, + [SMALL_STATE(235)] = 5173, + [SMALL_STATE(236)] = 5184, + [SMALL_STATE(237)] = 5195, + [SMALL_STATE(238)] = 5206, + [SMALL_STATE(239)] = 5217, + [SMALL_STATE(240)] = 5228, + [SMALL_STATE(241)] = 5239, + [SMALL_STATE(242)] = 5250, + [SMALL_STATE(243)] = 5261, + [SMALL_STATE(244)] = 5272, + [SMALL_STATE(245)] = 5283, + [SMALL_STATE(246)] = 5294, + [SMALL_STATE(247)] = 5305, + [SMALL_STATE(248)] = 5316, + [SMALL_STATE(249)] = 5327, + [SMALL_STATE(250)] = 5338, + [SMALL_STATE(251)] = 5349, + [SMALL_STATE(252)] = 5360, + [SMALL_STATE(253)] = 5371, + [SMALL_STATE(254)] = 5382, + [SMALL_STATE(255)] = 5393, + [SMALL_STATE(256)] = 5404, + [SMALL_STATE(257)] = 5415, + [SMALL_STATE(258)] = 5426, + [SMALL_STATE(259)] = 5437, + [SMALL_STATE(260)] = 5448, + [SMALL_STATE(261)] = 5459, + [SMALL_STATE(262)] = 5470, + [SMALL_STATE(263)] = 5481, + [SMALL_STATE(264)] = 5492, +}; + +static const TSParseActionEntry ts_parse_actions[] = { + [0] = {.entry = {.count = 0, .reusable = false}}, + [1] = {.entry = {.count = 1, .reusable = false}}, RECOVER(), + [3] = {.entry = {.count = 1, .reusable = true}}, SHIFT_EXTRA(), + [5] = {.entry = {.count = 1, .reusable = false}}, SHIFT_EXTRA(), + [7] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_source_file, 0, 0, 0), + [9] = {.entry = {.count = 1, .reusable = true}}, SHIFT(218), + [11] = {.entry = {.count = 1, .reusable = true}}, SHIFT(202), + [13] = {.entry = {.count = 1, .reusable = true}}, SHIFT(120), + [15] = {.entry = {.count = 1, .reusable = true}}, SHIFT(105), + [17] = {.entry = {.count = 1, .reusable = true}}, SHIFT(242), + [19] = {.entry = {.count = 1, .reusable = true}}, SHIFT(231), + [21] = {.entry = {.count = 1, .reusable = true}}, SHIFT(262), + [23] = {.entry = {.count = 1, .reusable = true}}, SHIFT(169), + [25] = {.entry = {.count = 1, .reusable = true}}, SHIFT(236), + [27] = {.entry = {.count = 1, .reusable = true}}, SHIFT(240), + [29] = {.entry = {.count = 1, .reusable = true}}, SHIFT(249), + [31] = {.entry = {.count = 1, .reusable = true}}, SHIFT(239), + [33] = {.entry = {.count = 1, .reusable = true}}, SHIFT(222), + [35] = {.entry = {.count = 1, .reusable = true}}, SHIFT(157), + [37] = {.entry = {.count = 1, .reusable = true}}, SHIFT(199), + [39] = {.entry = {.count = 1, .reusable = true}}, SHIFT(205), + [41] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym_source_file_repeat1, 2, 0, 0), + [43] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_source_file_repeat1, 2, 0, 0), SHIFT_REPEAT(218), + [46] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_source_file_repeat1, 2, 0, 0), SHIFT_REPEAT(202), + [49] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_source_file_repeat1, 2, 0, 0), SHIFT_REPEAT(120), + [52] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_source_file_repeat1, 2, 0, 0), SHIFT_REPEAT(105), + [55] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_source_file_repeat1, 2, 0, 0), SHIFT_REPEAT(242), + [58] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_source_file_repeat1, 2, 0, 0), SHIFT_REPEAT(231), + [61] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_source_file_repeat1, 2, 0, 0), SHIFT_REPEAT(262), + [64] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_source_file_repeat1, 2, 0, 0), SHIFT_REPEAT(169), + [67] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_source_file_repeat1, 2, 0, 0), SHIFT_REPEAT(236), + [70] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_source_file_repeat1, 2, 0, 0), SHIFT_REPEAT(240), + [73] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_source_file_repeat1, 2, 0, 0), SHIFT_REPEAT(249), + [76] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_source_file_repeat1, 2, 0, 0), SHIFT_REPEAT(239), + [79] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_source_file_repeat1, 2, 0, 0), SHIFT_REPEAT(222), + [82] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_source_file_repeat1, 2, 0, 0), SHIFT_REPEAT(157), + [85] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_source_file_repeat1, 2, 0, 0), SHIFT_REPEAT(199), + [88] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_source_file_repeat1, 2, 0, 0), SHIFT_REPEAT(205), + [91] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_source_file, 1, 0, 0), + [93] = {.entry = {.count = 1, .reusable = true}}, SHIFT(21), + [95] = {.entry = {.count = 1, .reusable = true}}, SHIFT(40), + [97] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_export_declaration, 3, 0, 0), + [99] = {.entry = {.count = 1, .reusable = true}}, SHIFT(33), + [101] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_struct_declaration, 3, 0, 4), + [103] = {.entry = {.count = 1, .reusable = true}}, SHIFT(26), + [105] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_enum_declaration, 3, 0, 4), + [107] = {.entry = {.count = 1, .reusable = true}}, SHIFT(27), + [109] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_contract_declaration, 3, 0, 4), + [111] = {.entry = {.count = 1, .reusable = true}}, SHIFT(29), + [113] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_export_declaration, 4, 0, 0), + [115] = {.entry = {.count = 1, .reusable = true}}, SHIFT(34), + [117] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_struct_declaration, 4, 0, 8), + [119] = {.entry = {.count = 1, .reusable = true}}, SHIFT(37), + [121] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_enum_declaration, 4, 0, 8), + [123] = {.entry = {.count = 1, .reusable = true}}, SHIFT(38), + [125] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_contract_declaration, 4, 0, 8), + [127] = {.entry = {.count = 1, .reusable = true}}, SHIFT(39), + [129] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_struct_declaration, 4, 0, 9), + [131] = {.entry = {.count = 1, .reusable = true}}, SHIFT(66), + [133] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_block, 2, 0, 0), + [135] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_export_declaration, 5, 0, 0), + [137] = {.entry = {.count = 1, .reusable = true}}, SHIFT(46), + [139] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_struct_declaration, 5, 0, 12), + [141] = {.entry = {.count = 1, .reusable = true}}, SHIFT(48), + [143] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_block, 3, 0, 0), + [145] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_export_declaration, 6, 0, 0), + [147] = {.entry = {.count = 1, .reusable = true}}, SHIFT(54), + [149] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_ledger_declaration, 7, 0, 22), + [151] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_module_body, 2, 0, 0), + [153] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_constructor_declaration, 3, 0, 5), + [155] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_module_declaration, 4, 0, 9), + [157] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_pragma_declaration, 4, 0, 3), + [159] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_import_declaration, 4, 0, 3), + [161] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_struct_declaration, 4, 0, 4), + [163] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_enum_declaration, 4, 0, 4), + [165] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_implements_declaration, 4, 0, 10), + [167] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_contract_declaration, 4, 0, 4), + [169] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_import_declaration, 4, 0, 7), + [171] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_import_declaration, 5, 0, 3), + [173] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_import_declaration, 5, 0, 7), + [175] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_module_declaration, 5, 0, 12), + [177] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_include_declaration, 3, 0, 1), + [179] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_struct_declaration, 5, 0, 8), + [181] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_enum_declaration, 5, 0, 8), + [183] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_contract_declaration, 5, 0, 8), + [185] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_module_body, 3, 0, 0), + [187] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_module_declaration, 4, 0, 8), + [189] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_module_declaration, 3, 0, 4), + [191] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_type_declaration, 5, 0, 13), + [193] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_ledger_declaration, 5, 0, 14), + [195] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_import_declaration, 6, 0, 7), + [197] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_import_declaration, 3, 0, 3), + [199] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_struct_declaration, 6, 0, 12), + [201] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_type_declaration, 6, 0, 15), + [203] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_ledger_declaration, 6, 0, 16), + [205] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_type_declaration, 6, 0, 17), + [207] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_witness_declaration, 6, 0, 18), + [209] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_circuit_declaration, 6, 0, 19), + [211] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_export_declaration, 7, 0, 0), + [213] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_type_declaration, 7, 0, 20), + [215] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_type_declaration, 7, 0, 21), + [217] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_witness_declaration, 7, 0, 23), + [219] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_circuit_declaration, 7, 0, 24), + [221] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_witness_declaration, 7, 0, 25), + [223] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_circuit_declaration, 7, 0, 26), + [225] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_type_declaration, 8, 0, 27), + [227] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_witness_declaration, 8, 0, 28), + [229] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_circuit_declaration, 8, 0, 29), + [231] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_circuit_declaration, 8, 0, 30), + [233] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_circuit_declaration, 9, 0, 31), + [235] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_struct_declaration, 5, 0, 9), + [237] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_generic_arguments_repeat1, 2, 0, 0), SHIFT_REPEAT(67), + [240] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym_generic_arguments_repeat1, 2, 0, 0), + [242] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_generic_arguments_repeat1, 2, 0, 0), SHIFT_REPEAT(94), + [245] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_generic_arguments_repeat1, 2, 0, 0), SHIFT_REPEAT(72), + [248] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_block_repeat1, 2, 0, 0), SHIFT_REPEAT(108), + [251] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym_block_repeat1, 2, 0, 0), + [253] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_block_repeat1, 2, 0, 0), SHIFT_REPEAT(97), + [256] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_block_repeat1, 2, 0, 0), SHIFT_REPEAT(103), + [259] = {.entry = {.count = 2, .reusable = false}}, REDUCE(aux_sym_block_repeat1, 2, 0, 0), SHIFT_REPEAT(68), + [262] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_block_repeat1, 2, 0, 0), SHIFT_REPEAT(68), + [265] = {.entry = {.count = 1, .reusable = true}}, SHIFT(67), + [267] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_type_expression, 1, 0, 0), + [269] = {.entry = {.count = 1, .reusable = true}}, SHIFT(94), + [271] = {.entry = {.count = 1, .reusable = true}}, SHIFT(72), + [273] = {.entry = {.count = 1, .reusable = true}}, SHIFT(69), + [275] = {.entry = {.count = 1, .reusable = true}}, SHIFT(79), + [277] = {.entry = {.count = 1, .reusable = true}}, SHIFT(99), + [279] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_generic_arguments, 2, 0, 0), + [281] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_generic_arguments, 2, 0, 0), + [283] = {.entry = {.count = 1, .reusable = true}}, SHIFT(82), + [285] = {.entry = {.count = 1, .reusable = true}}, SHIFT(102), + [287] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_generic_arguments, 3, 0, 0), + [289] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_generic_arguments, 3, 0, 0), + [291] = {.entry = {.count = 1, .reusable = true}}, SHIFT(76), + [293] = {.entry = {.count = 1, .reusable = true}}, SHIFT(75), + [295] = {.entry = {.count = 1, .reusable = true}}, SHIFT(108), + [297] = {.entry = {.count = 1, .reusable = true}}, SHIFT(114), + [299] = {.entry = {.count = 1, .reusable = true}}, SHIFT(97), + [301] = {.entry = {.count = 1, .reusable = true}}, SHIFT(103), + [303] = {.entry = {.count = 1, .reusable = false}}, SHIFT(68), + [305] = {.entry = {.count = 1, .reusable = true}}, SHIFT(68), + [307] = {.entry = {.count = 1, .reusable = true}}, SHIFT(112), + [309] = {.entry = {.count = 1, .reusable = false}}, SHIFT(104), + [311] = {.entry = {.count = 1, .reusable = true}}, SHIFT(104), + [313] = {.entry = {.count = 1, .reusable = true}}, SHIFT(18), + [315] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__tuple_type, 2, 0, 0), + [317] = {.entry = {.count = 1, .reusable = true}}, SHIFT(15), + [319] = {.entry = {.count = 1, .reusable = false}}, SHIFT(98), + [321] = {.entry = {.count = 1, .reusable = true}}, SHIFT(98), + [323] = {.entry = {.count = 1, .reusable = true}}, SHIFT(154), + [325] = {.entry = {.count = 1, .reusable = false}}, SHIFT(106), + [327] = {.entry = {.count = 1, .reusable = true}}, SHIFT(106), + [329] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__tuple_type, 3, 0, 0), + [331] = {.entry = {.count = 1, .reusable = true}}, SHIFT(111), + [333] = {.entry = {.count = 1, .reusable = false}}, SHIFT(107), + [335] = {.entry = {.count = 1, .reusable = true}}, SHIFT(107), + [337] = {.entry = {.count = 1, .reusable = true}}, SHIFT(109), + [339] = {.entry = {.count = 1, .reusable = true}}, SHIFT(174), + [341] = {.entry = {.count = 1, .reusable = true}}, SHIFT(228), + [343] = {.entry = {.count = 1, .reusable = true}}, SHIFT(235), + [345] = {.entry = {.count = 1, .reusable = true}}, SHIFT(251), + [347] = {.entry = {.count = 1, .reusable = true}}, SHIFT(256), + [349] = {.entry = {.count = 1, .reusable = true}}, SHIFT(206), + [351] = {.entry = {.count = 1, .reusable = true}}, SHIFT(208), + [353] = {.entry = {.count = 1, .reusable = true}}, SHIFT(209), + [355] = {.entry = {.count = 1, .reusable = true}}, SHIFT(193), + [357] = {.entry = {.count = 1, .reusable = true}}, SHIFT(195), + [359] = {.entry = {.count = 1, .reusable = true}}, SHIFT(213), + [361] = {.entry = {.count = 1, .reusable = true}}, SHIFT(216), + [363] = {.entry = {.count = 1, .reusable = true}}, SHIFT(161), + [365] = {.entry = {.count = 1, .reusable = true}}, SHIFT(110), + [367] = {.entry = {.count = 1, .reusable = true}}, SHIFT(113), + [369] = {.entry = {.count = 1, .reusable = false}}, SHIFT(96), + [371] = {.entry = {.count = 1, .reusable = true}}, SHIFT(96), + [373] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__bracket_group, 3, 0, 0), + [375] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym__bracket_group, 3, 0, 0), + [377] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__paren_group, 3, 0, 0), + [379] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym__paren_group, 3, 0, 0), + [381] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__paren_group, 2, 0, 0), + [383] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym__paren_group, 2, 0, 0), + [385] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym__bracket_group, 2, 0, 0), + [387] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym__bracket_group, 2, 0, 0), + [389] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_block, 2, 0, 0), + [391] = {.entry = {.count = 1, .reusable = false}}, REDUCE(sym_block, 3, 0, 0), + [393] = {.entry = {.count = 1, .reusable = true}}, SHIFT(47), + [395] = {.entry = {.count = 1, .reusable = true}}, SHIFT(233), + [397] = {.entry = {.count = 1, .reusable = true}}, SHIFT(30), + [399] = {.entry = {.count = 1, .reusable = true}}, SHIFT(100), + [401] = {.entry = {.count = 1, .reusable = true}}, SHIFT(124), + [403] = {.entry = {.count = 1, .reusable = true}}, SHIFT(172), + [405] = {.entry = {.count = 1, .reusable = true}}, SHIFT(130), + [407] = {.entry = {.count = 1, .reusable = true}}, SHIFT(196), + [409] = {.entry = {.count = 1, .reusable = true}}, SHIFT(115), + [411] = {.entry = {.count = 1, .reusable = true}}, SHIFT(145), + [413] = {.entry = {.count = 1, .reusable = true}}, SHIFT(101), + [415] = {.entry = {.count = 1, .reusable = true}}, SHIFT(4), + [417] = {.entry = {.count = 1, .reusable = true}}, SHIFT(131), + [419] = {.entry = {.count = 1, .reusable = true}}, SHIFT(144), + [421] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_generic_parameters, 5, 0, 0), + [423] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_generic_parameters, 2, 0, 0), + [425] = {.entry = {.count = 1, .reusable = true}}, SHIFT(127), + [427] = {.entry = {.count = 1, .reusable = true}}, SHIFT(152), + [429] = {.entry = {.count = 1, .reusable = true}}, SHIFT(142), + [431] = {.entry = {.count = 1, .reusable = true}}, SHIFT(210), + [433] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_import_selection_repeat1, 2, 0, 0), SHIFT_REPEAT(165), + [436] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym_import_selection_repeat1, 2, 0, 0), + [438] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_export_declaration_repeat1, 2, 0, 0), SHIFT_REPEAT(215), + [441] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym_export_declaration_repeat1, 2, 0, 0), + [443] = {.entry = {.count = 1, .reusable = true}}, SHIFT(73), + [445] = {.entry = {.count = 1, .reusable = true}}, SHIFT(198), + [447] = {.entry = {.count = 1, .reusable = true}}, SHIFT(133), + [449] = {.entry = {.count = 1, .reusable = true}}, SHIFT(119), + [451] = {.entry = {.count = 1, .reusable = true}}, SHIFT(32), + [453] = {.entry = {.count = 1, .reusable = true}}, SHIFT(179), + [455] = {.entry = {.count = 1, .reusable = true}}, SHIFT(16), + [457] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_import_element, 1, 0, 2), + [459] = {.entry = {.count = 1, .reusable = true}}, SHIFT(264), + [461] = {.entry = {.count = 1, .reusable = true}}, SHIFT(137), + [463] = {.entry = {.count = 1, .reusable = true}}, SHIFT(248), + [465] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_generic_parameters, 4, 0, 0), + [467] = {.entry = {.count = 1, .reusable = true}}, SHIFT(214), + [469] = {.entry = {.count = 2, .reusable = true}}, REDUCE(aux_sym_generic_parameters_repeat1, 2, 0, 0), SHIFT_REPEAT(150), + [472] = {.entry = {.count = 1, .reusable = true}}, REDUCE(aux_sym_generic_parameters_repeat1, 2, 0, 0), + [474] = {.entry = {.count = 1, .reusable = true}}, SHIFT(95), + [476] = {.entry = {.count = 1, .reusable = true}}, SHIFT(25), + [478] = {.entry = {.count = 1, .reusable = true}}, SHIFT(162), + [480] = {.entry = {.count = 1, .reusable = true}}, SHIFT(10), + [482] = {.entry = {.count = 1, .reusable = true}}, SHIFT(77), + [484] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_generic_parameters, 3, 0, 0), + [486] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_import_selection, 4, 0, 0), + [488] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_parameter_list, 2, 0, 0), + [490] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_generic_parameter, 2, 0, 3), + [492] = {.entry = {.count = 1, .reusable = true}}, SHIFT(116), + [494] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_parameter_list, 3, 0, 0), + [496] = {.entry = {.count = 1, .reusable = true}}, SHIFT(175), + [498] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_import_selection, 5, 0, 0), + [500] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_import_element, 3, 0, 11), + [502] = {.entry = {.count = 1, .reusable = false}}, SHIFT(186), + [504] = {.entry = {.count = 1, .reusable = false}}, SHIFT(83), + [506] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_generic_parameter, 1, 0, 2), + [508] = {.entry = {.count = 1, .reusable = true}}, SHIFT(149), + [510] = {.entry = {.count = 1, .reusable = true}}, SHIFT(6), + [512] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_import_selection, 3, 0, 0), + [514] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_import_selection, 6, 0, 0), + [516] = {.entry = {.count = 1, .reusable = true}}, SHIFT(19), + [518] = {.entry = {.count = 1, .reusable = true}}, SHIFT(128), + [520] = {.entry = {.count = 1, .reusable = true}}, SHIFT(258), + [522] = {.entry = {.count = 1, .reusable = true}}, SHIFT(89), + [524] = {.entry = {.count = 1, .reusable = true}}, SHIFT(125), + [526] = {.entry = {.count = 1, .reusable = true}}, SHIFT(156), + [528] = {.entry = {.count = 1, .reusable = true}}, SHIFT(31), + [530] = {.entry = {.count = 1, .reusable = true}}, SHIFT(164), + [532] = {.entry = {.count = 1, .reusable = true}}, SHIFT(51), + [534] = {.entry = {.count = 1, .reusable = true}}, SHIFT(227), + [536] = {.entry = {.count = 1, .reusable = true}}, SHIFT(81), + [538] = {.entry = {.count = 1, .reusable = true}}, SHIFT(52), + [540] = {.entry = {.count = 1, .reusable = true}}, SHIFT(121), + [542] = {.entry = {.count = 1, .reusable = true}}, SHIFT(254), + [544] = {.entry = {.count = 1, .reusable = true}}, ACCEPT_INPUT(), + [546] = {.entry = {.count = 1, .reusable = true}}, SHIFT(151), + [548] = {.entry = {.count = 1, .reusable = true}}, SHIFT(257), + [550] = {.entry = {.count = 1, .reusable = true}}, SHIFT(178), + [552] = {.entry = {.count = 1, .reusable = true}}, SHIFT(70), + [554] = {.entry = {.count = 1, .reusable = true}}, SHIFT(24), + [556] = {.entry = {.count = 1, .reusable = true}}, SHIFT(192), + [558] = {.entry = {.count = 1, .reusable = true}}, SHIFT(176), + [560] = {.entry = {.count = 1, .reusable = true}}, SHIFT(129), + [562] = {.entry = {.count = 1, .reusable = true}}, SHIFT(55), + [564] = {.entry = {.count = 1, .reusable = true}}, SHIFT(226), + [566] = {.entry = {.count = 1, .reusable = true}}, SHIFT(45), + [568] = {.entry = {.count = 1, .reusable = true}}, SHIFT(56), + [570] = {.entry = {.count = 1, .reusable = true}}, SHIFT(20), + [572] = {.entry = {.count = 1, .reusable = true}}, SHIFT(126), + [574] = {.entry = {.count = 1, .reusable = true}}, SHIFT(43), + [576] = {.entry = {.count = 1, .reusable = true}}, SHIFT(57), + [578] = {.entry = {.count = 1, .reusable = true}}, SHIFT(71), + [580] = {.entry = {.count = 1, .reusable = false}}, SHIFT(212), + [582] = {.entry = {.count = 1, .reusable = true}}, SHIFT(36), + [584] = {.entry = {.count = 1, .reusable = true}}, SHIFT(122), + [586] = {.entry = {.count = 1, .reusable = true}}, SHIFT(44), + [588] = {.entry = {.count = 1, .reusable = true}}, SHIFT(88), + [590] = {.entry = {.count = 1, .reusable = true}}, SHIFT(118), + [592] = {.entry = {.count = 1, .reusable = true}}, SHIFT(28), + [594] = {.entry = {.count = 1, .reusable = true}}, SHIFT(255), + [596] = {.entry = {.count = 1, .reusable = true}}, SHIFT(59), + [598] = {.entry = {.count = 1, .reusable = true}}, SHIFT(117), + [600] = {.entry = {.count = 1, .reusable = true}}, SHIFT(74), + [602] = {.entry = {.count = 1, .reusable = true}}, SHIFT(238), + [604] = {.entry = {.count = 1, .reusable = true}}, SHIFT(136), + [606] = {.entry = {.count = 1, .reusable = true}}, SHIFT(61), + [608] = {.entry = {.count = 1, .reusable = true}}, SHIFT(123), + [610] = {.entry = {.count = 1, .reusable = true}}, SHIFT(90), + [612] = {.entry = {.count = 1, .reusable = true}}, SHIFT(62), + [614] = {.entry = {.count = 1, .reusable = true}}, SHIFT(84), + [616] = {.entry = {.count = 1, .reusable = true}}, SHIFT(85), + [618] = {.entry = {.count = 1, .reusable = true}}, SHIFT(49), + [620] = {.entry = {.count = 1, .reusable = true}}, SHIFT(153), + [622] = {.entry = {.count = 1, .reusable = true}}, SHIFT(80), + [624] = {.entry = {.count = 1, .reusable = true}}, SHIFT(184), + [626] = {.entry = {.count = 1, .reusable = true}}, SHIFT(50), + [628] = {.entry = {.count = 1, .reusable = true}}, SHIFT(91), + [630] = {.entry = {.count = 1, .reusable = true}}, SHIFT(147), + [632] = {.entry = {.count = 1, .reusable = true}}, REDUCE(sym_import_prefix, 2, 0, 6), + [634] = {.entry = {.count = 1, .reusable = true}}, SHIFT(185), + [636] = {.entry = {.count = 1, .reusable = true}}, SHIFT(246), + [638] = {.entry = {.count = 1, .reusable = true}}, SHIFT(78), + [640] = {.entry = {.count = 1, .reusable = true}}, SHIFT(92), + [642] = {.entry = {.count = 1, .reusable = true}}, SHIFT(86), + [644] = {.entry = {.count = 1, .reusable = true}}, SHIFT(93), + [646] = {.entry = {.count = 1, .reusable = true}}, SHIFT(183), + [648] = {.entry = {.count = 1, .reusable = true}}, SHIFT(87), + [650] = {.entry = {.count = 1, .reusable = true}}, SHIFT(166), +}; + +#ifdef __cplusplus +extern "C" { +#endif +#ifdef TREE_SITTER_HIDE_SYMBOLS +#define TS_PUBLIC +#elif defined(_WIN32) +#define TS_PUBLIC __declspec(dllexport) +#else +#define TS_PUBLIC __attribute__((visibility("default"))) +#endif + +TS_PUBLIC const TSLanguage *tree_sitter_compact(void) { + static const TSLanguage language = { + .abi_version = LANGUAGE_VERSION, + .symbol_count = SYMBOL_COUNT, + .alias_count = ALIAS_COUNT, + .token_count = TOKEN_COUNT, + .external_token_count = EXTERNAL_TOKEN_COUNT, + .state_count = STATE_COUNT, + .large_state_count = LARGE_STATE_COUNT, + .production_id_count = PRODUCTION_ID_COUNT, + .supertype_count = SUPERTYPE_COUNT, + .field_count = FIELD_COUNT, + .max_alias_sequence_length = MAX_ALIAS_SEQUENCE_LENGTH, + .parse_table = &ts_parse_table[0][0], + .small_parse_table = ts_small_parse_table, + .small_parse_table_map = ts_small_parse_table_map, + .parse_actions = ts_parse_actions, + .symbol_names = ts_symbol_names, + .field_names = ts_field_names, + .field_map_slices = ts_field_map_slices, + .field_map_entries = ts_field_map_entries, + .symbol_metadata = ts_symbol_metadata, + .public_symbol_map = ts_symbol_map, + .alias_map = ts_non_terminal_alias_map, + .alias_sequences = &ts_alias_sequences[0][0], + .lex_modes = (const void*)ts_lex_modes, + .lex_fn = ts_lex, + .keyword_lex_fn = ts_lex_keywords, + .keyword_capture_token = sym_identifier, + .primary_state_ids = ts_primary_state_ids, + .name = "compact", + .max_reserved_word_set_size = 0, + .metadata = { + .major_version = 0, + .minor_version = 1, + .patch_version = 0, + }, + }; + return &language; +} +#ifdef __cplusplus +} +#endif diff --git a/crates/tree-sitter-compact/src/tree_sitter/alloc.h b/crates/tree-sitter-compact/src/tree_sitter/alloc.h new file mode 100644 index 00000000..1abdd120 --- /dev/null +++ b/crates/tree-sitter-compact/src/tree_sitter/alloc.h @@ -0,0 +1,54 @@ +#ifndef TREE_SITTER_ALLOC_H_ +#define TREE_SITTER_ALLOC_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include + +// Allow clients to override allocation functions +#ifdef TREE_SITTER_REUSE_ALLOCATOR + +extern void *(*ts_current_malloc)(size_t size); +extern void *(*ts_current_calloc)(size_t count, size_t size); +extern void *(*ts_current_realloc)(void *ptr, size_t size); +extern void (*ts_current_free)(void *ptr); + +#ifndef ts_malloc +#define ts_malloc ts_current_malloc +#endif +#ifndef ts_calloc +#define ts_calloc ts_current_calloc +#endif +#ifndef ts_realloc +#define ts_realloc ts_current_realloc +#endif +#ifndef ts_free +#define ts_free ts_current_free +#endif + +#else + +#ifndef ts_malloc +#define ts_malloc malloc +#endif +#ifndef ts_calloc +#define ts_calloc calloc +#endif +#ifndef ts_realloc +#define ts_realloc realloc +#endif +#ifndef ts_free +#define ts_free free +#endif + +#endif + +#ifdef __cplusplus +} +#endif + +#endif // TREE_SITTER_ALLOC_H_ diff --git a/crates/tree-sitter-compact/src/tree_sitter/array.h b/crates/tree-sitter-compact/src/tree_sitter/array.h new file mode 100644 index 00000000..a17a574f --- /dev/null +++ b/crates/tree-sitter-compact/src/tree_sitter/array.h @@ -0,0 +1,291 @@ +#ifndef TREE_SITTER_ARRAY_H_ +#define TREE_SITTER_ARRAY_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "./alloc.h" + +#include +#include +#include +#include +#include + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4101) +#elif defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wunused-variable" +#endif + +#define Array(T) \ + struct { \ + T *contents; \ + uint32_t size; \ + uint32_t capacity; \ + } + +/// Initialize an array. +#define array_init(self) \ + ((self)->size = 0, (self)->capacity = 0, (self)->contents = NULL) + +/// Create an empty array. +#define array_new() \ + { NULL, 0, 0 } + +/// Get a pointer to the element at a given `index` in the array. +#define array_get(self, _index) \ + (assert((uint32_t)(_index) < (self)->size), &(self)->contents[_index]) + +/// Get a pointer to the first element in the array. +#define array_front(self) array_get(self, 0) + +/// Get a pointer to the last element in the array. +#define array_back(self) array_get(self, (self)->size - 1) + +/// Clear the array, setting its size to zero. Note that this does not free any +/// memory allocated for the array's contents. +#define array_clear(self) ((self)->size = 0) + +/// Reserve `new_capacity` elements of space in the array. If `new_capacity` is +/// less than the array's current capacity, this function has no effect. +#define array_reserve(self, new_capacity) \ + _array__reserve((Array *)(self), array_elem_size(self), new_capacity) + +/// Free any memory allocated for this array. Note that this does not free any +/// memory allocated for the array's contents. +#define array_delete(self) _array__delete((Array *)(self)) + +/// Push a new `element` onto the end of the array. +#define array_push(self, element) \ + (_array__grow((Array *)(self), 1, array_elem_size(self)), \ + (self)->contents[(self)->size++] = (element)) + +/// Increase the array's size by `count` elements. +/// New elements are zero-initialized. +#define array_grow_by(self, count) \ + do { \ + if ((count) == 0) break; \ + _array__grow((Array *)(self), count, array_elem_size(self)); \ + memset((self)->contents + (self)->size, 0, (count) * array_elem_size(self)); \ + (self)->size += (count); \ + } while (0) + +/// Append all elements from one array to the end of another. +#define array_push_all(self, other) \ + array_extend((self), (other)->size, (other)->contents) + +/// Append `count` elements to the end of the array, reading their values from the +/// `contents` pointer. +#define array_extend(self, count, contents) \ + _array__splice( \ + (Array *)(self), array_elem_size(self), (self)->size, \ + 0, count, contents \ + ) + +/// Remove `old_count` elements from the array starting at the given `index`. At +/// the same index, insert `new_count` new elements, reading their values from the +/// `new_contents` pointer. +#define array_splice(self, _index, old_count, new_count, new_contents) \ + _array__splice( \ + (Array *)(self), array_elem_size(self), _index, \ + old_count, new_count, new_contents \ + ) + +/// Insert one `element` into the array at the given `index`. +#define array_insert(self, _index, element) \ + _array__splice((Array *)(self), array_elem_size(self), _index, 0, 1, &(element)) + +/// Remove one element from the array at the given `index`. +#define array_erase(self, _index) \ + _array__erase((Array *)(self), array_elem_size(self), _index) + +/// Pop the last element off the array, returning the element by value. +#define array_pop(self) ((self)->contents[--(self)->size]) + +/// Assign the contents of one array to another, reallocating if necessary. +#define array_assign(self, other) \ + _array__assign((Array *)(self), (const Array *)(other), array_elem_size(self)) + +/// Swap one array with another +#define array_swap(self, other) \ + _array__swap((Array *)(self), (Array *)(other)) + +/// Get the size of the array contents +#define array_elem_size(self) (sizeof *(self)->contents) + +/// Search a sorted array for a given `needle` value, using the given `compare` +/// callback to determine the order. +/// +/// If an existing element is found to be equal to `needle`, then the `index` +/// out-parameter is set to the existing value's index, and the `exists` +/// out-parameter is set to true. Otherwise, `index` is set to an index where +/// `needle` should be inserted in order to preserve the sorting, and `exists` +/// is set to false. +#define array_search_sorted_with(self, compare, needle, _index, _exists) \ + _array__search_sorted(self, 0, compare, , needle, _index, _exists) + +/// Search a sorted array for a given `needle` value, using integer comparisons +/// of a given struct field (specified with a leading dot) to determine the order. +/// +/// See also `array_search_sorted_with`. +#define array_search_sorted_by(self, field, needle, _index, _exists) \ + _array__search_sorted(self, 0, _compare_int, field, needle, _index, _exists) + +/// Insert a given `value` into a sorted array, using the given `compare` +/// callback to determine the order. +#define array_insert_sorted_with(self, compare, value) \ + do { \ + unsigned _index, _exists; \ + array_search_sorted_with(self, compare, &(value), &_index, &_exists); \ + if (!_exists) array_insert(self, _index, value); \ + } while (0) + +/// Insert a given `value` into a sorted array, using integer comparisons of +/// a given struct field (specified with a leading dot) to determine the order. +/// +/// See also `array_search_sorted_by`. +#define array_insert_sorted_by(self, field, value) \ + do { \ + unsigned _index, _exists; \ + array_search_sorted_by(self, field, (value) field, &_index, &_exists); \ + if (!_exists) array_insert(self, _index, value); \ + } while (0) + +// Private + +typedef Array(void) Array; + +/// This is not what you're looking for, see `array_delete`. +static inline void _array__delete(Array *self) { + if (self->contents) { + ts_free(self->contents); + self->contents = NULL; + self->size = 0; + self->capacity = 0; + } +} + +/// This is not what you're looking for, see `array_erase`. +static inline void _array__erase(Array *self, size_t element_size, + uint32_t index) { + assert(index < self->size); + char *contents = (char *)self->contents; + memmove(contents + index * element_size, contents + (index + 1) * element_size, + (self->size - index - 1) * element_size); + self->size--; +} + +/// This is not what you're looking for, see `array_reserve`. +static inline void _array__reserve(Array *self, size_t element_size, uint32_t new_capacity) { + if (new_capacity > self->capacity) { + if (self->contents) { + self->contents = ts_realloc(self->contents, new_capacity * element_size); + } else { + self->contents = ts_malloc(new_capacity * element_size); + } + self->capacity = new_capacity; + } +} + +/// This is not what you're looking for, see `array_assign`. +static inline void _array__assign(Array *self, const Array *other, size_t element_size) { + _array__reserve(self, element_size, other->size); + self->size = other->size; + memcpy(self->contents, other->contents, self->size * element_size); +} + +/// This is not what you're looking for, see `array_swap`. +static inline void _array__swap(Array *self, Array *other) { + Array swap = *other; + *other = *self; + *self = swap; +} + +/// This is not what you're looking for, see `array_push` or `array_grow_by`. +static inline void _array__grow(Array *self, uint32_t count, size_t element_size) { + uint32_t new_size = self->size + count; + if (new_size > self->capacity) { + uint32_t new_capacity = self->capacity * 2; + if (new_capacity < 8) new_capacity = 8; + if (new_capacity < new_size) new_capacity = new_size; + _array__reserve(self, element_size, new_capacity); + } +} + +/// This is not what you're looking for, see `array_splice`. +static inline void _array__splice(Array *self, size_t element_size, + uint32_t index, uint32_t old_count, + uint32_t new_count, const void *elements) { + uint32_t new_size = self->size + new_count - old_count; + uint32_t old_end = index + old_count; + uint32_t new_end = index + new_count; + assert(old_end <= self->size); + + _array__reserve(self, element_size, new_size); + + char *contents = (char *)self->contents; + if (self->size > old_end) { + memmove( + contents + new_end * element_size, + contents + old_end * element_size, + (self->size - old_end) * element_size + ); + } + if (new_count > 0) { + if (elements) { + memcpy( + (contents + index * element_size), + elements, + new_count * element_size + ); + } else { + memset( + (contents + index * element_size), + 0, + new_count * element_size + ); + } + } + self->size += new_count - old_count; +} + +/// A binary search routine, based on Rust's `std::slice::binary_search_by`. +/// This is not what you're looking for, see `array_search_sorted_with` or `array_search_sorted_by`. +#define _array__search_sorted(self, start, compare, suffix, needle, _index, _exists) \ + do { \ + *(_index) = start; \ + *(_exists) = false; \ + uint32_t size = (self)->size - *(_index); \ + if (size == 0) break; \ + int comparison; \ + while (size > 1) { \ + uint32_t half_size = size / 2; \ + uint32_t mid_index = *(_index) + half_size; \ + comparison = compare(&((self)->contents[mid_index] suffix), (needle)); \ + if (comparison <= 0) *(_index) = mid_index; \ + size -= half_size; \ + } \ + comparison = compare(&((self)->contents[*(_index)] suffix), (needle)); \ + if (comparison == 0) *(_exists) = true; \ + else if (comparison < 0) *(_index) += 1; \ + } while (0) + +/// Helper macro for the `_sorted_by` routines below. This takes the left (existing) +/// parameter by reference in order to work with the generic sorting function above. +#define _compare_int(a, b) ((int)*(a) - (int)(b)) + +#ifdef _MSC_VER +#pragma warning(pop) +#elif defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#endif + +#ifdef __cplusplus +} +#endif + +#endif // TREE_SITTER_ARRAY_H_ diff --git a/crates/tree-sitter-compact/src/tree_sitter/parser.h b/crates/tree-sitter-compact/src/tree_sitter/parser.h new file mode 100644 index 00000000..858107de --- /dev/null +++ b/crates/tree-sitter-compact/src/tree_sitter/parser.h @@ -0,0 +1,286 @@ +#ifndef TREE_SITTER_PARSER_H_ +#define TREE_SITTER_PARSER_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include + +#define ts_builtin_sym_error ((TSSymbol)-1) +#define ts_builtin_sym_end 0 +#define TREE_SITTER_SERIALIZATION_BUFFER_SIZE 1024 + +#ifndef TREE_SITTER_API_H_ +typedef uint16_t TSStateId; +typedef uint16_t TSSymbol; +typedef uint16_t TSFieldId; +typedef struct TSLanguage TSLanguage; +typedef struct TSLanguageMetadata { + uint8_t major_version; + uint8_t minor_version; + uint8_t patch_version; +} TSLanguageMetadata; +#endif + +typedef struct { + TSFieldId field_id; + uint8_t child_index; + bool inherited; +} TSFieldMapEntry; + +// Used to index the field and supertype maps. +typedef struct { + uint16_t index; + uint16_t length; +} TSMapSlice; + +typedef struct { + bool visible; + bool named; + bool supertype; +} TSSymbolMetadata; + +typedef struct TSLexer TSLexer; + +struct TSLexer { + int32_t lookahead; + TSSymbol result_symbol; + void (*advance)(TSLexer *, bool); + void (*mark_end)(TSLexer *); + uint32_t (*get_column)(TSLexer *); + bool (*is_at_included_range_start)(const TSLexer *); + bool (*eof)(const TSLexer *); + void (*log)(const TSLexer *, const char *, ...); +}; + +typedef enum { + TSParseActionTypeShift, + TSParseActionTypeReduce, + TSParseActionTypeAccept, + TSParseActionTypeRecover, +} TSParseActionType; + +typedef union { + struct { + uint8_t type; + TSStateId state; + bool extra; + bool repetition; + } shift; + struct { + uint8_t type; + uint8_t child_count; + TSSymbol symbol; + int16_t dynamic_precedence; + uint16_t production_id; + } reduce; + uint8_t type; +} TSParseAction; + +typedef struct { + uint16_t lex_state; + uint16_t external_lex_state; +} TSLexMode; + +typedef struct { + uint16_t lex_state; + uint16_t external_lex_state; + uint16_t reserved_word_set_id; +} TSLexerMode; + +typedef union { + TSParseAction action; + struct { + uint8_t count; + bool reusable; + } entry; +} TSParseActionEntry; + +typedef struct { + int32_t start; + int32_t end; +} TSCharacterRange; + +struct TSLanguage { + uint32_t abi_version; + uint32_t symbol_count; + uint32_t alias_count; + uint32_t token_count; + uint32_t external_token_count; + uint32_t state_count; + uint32_t large_state_count; + uint32_t production_id_count; + uint32_t field_count; + uint16_t max_alias_sequence_length; + const uint16_t *parse_table; + const uint16_t *small_parse_table; + const uint32_t *small_parse_table_map; + const TSParseActionEntry *parse_actions; + const char * const *symbol_names; + const char * const *field_names; + const TSMapSlice *field_map_slices; + const TSFieldMapEntry *field_map_entries; + const TSSymbolMetadata *symbol_metadata; + const TSSymbol *public_symbol_map; + const uint16_t *alias_map; + const TSSymbol *alias_sequences; + const TSLexerMode *lex_modes; + bool (*lex_fn)(TSLexer *, TSStateId); + bool (*keyword_lex_fn)(TSLexer *, TSStateId); + TSSymbol keyword_capture_token; + struct { + const bool *states; + const TSSymbol *symbol_map; + void *(*create)(void); + void (*destroy)(void *); + bool (*scan)(void *, TSLexer *, const bool *symbol_whitelist); + unsigned (*serialize)(void *, char *); + void (*deserialize)(void *, const char *, unsigned); + } external_scanner; + const TSStateId *primary_state_ids; + const char *name; + const TSSymbol *reserved_words; + uint16_t max_reserved_word_set_size; + uint32_t supertype_count; + const TSSymbol *supertype_symbols; + const TSMapSlice *supertype_map_slices; + const TSSymbol *supertype_map_entries; + TSLanguageMetadata metadata; +}; + +static inline bool set_contains(const TSCharacterRange *ranges, uint32_t len, int32_t lookahead) { + uint32_t index = 0; + uint32_t size = len - index; + while (size > 1) { + uint32_t half_size = size / 2; + uint32_t mid_index = index + half_size; + const TSCharacterRange *range = &ranges[mid_index]; + if (lookahead >= range->start && lookahead <= range->end) { + return true; + } else if (lookahead > range->end) { + index = mid_index; + } + size -= half_size; + } + const TSCharacterRange *range = &ranges[index]; + return (lookahead >= range->start && lookahead <= range->end); +} + +/* + * Lexer Macros + */ + +#ifdef _MSC_VER +#define UNUSED __pragma(warning(suppress : 4101)) +#else +#define UNUSED __attribute__((unused)) +#endif + +#define START_LEXER() \ + bool result = false; \ + bool skip = false; \ + UNUSED \ + bool eof = false; \ + int32_t lookahead; \ + goto start; \ + next_state: \ + lexer->advance(lexer, skip); \ + start: \ + skip = false; \ + lookahead = lexer->lookahead; + +#define ADVANCE(state_value) \ + { \ + state = state_value; \ + goto next_state; \ + } + +#define ADVANCE_MAP(...) \ + { \ + static const uint16_t map[] = { __VA_ARGS__ }; \ + for (uint32_t i = 0; i < sizeof(map) / sizeof(map[0]); i += 2) { \ + if (map[i] == lookahead) { \ + state = map[i + 1]; \ + goto next_state; \ + } \ + } \ + } + +#define SKIP(state_value) \ + { \ + skip = true; \ + state = state_value; \ + goto next_state; \ + } + +#define ACCEPT_TOKEN(symbol_value) \ + result = true; \ + lexer->result_symbol = symbol_value; \ + lexer->mark_end(lexer); + +#define END_STATE() return result; + +/* + * Parse Table Macros + */ + +#define SMALL_STATE(id) ((id) - LARGE_STATE_COUNT) + +#define STATE(id) id + +#define ACTIONS(id) id + +#define SHIFT(state_value) \ + {{ \ + .shift = { \ + .type = TSParseActionTypeShift, \ + .state = (state_value) \ + } \ + }} + +#define SHIFT_REPEAT(state_value) \ + {{ \ + .shift = { \ + .type = TSParseActionTypeShift, \ + .state = (state_value), \ + .repetition = true \ + } \ + }} + +#define SHIFT_EXTRA() \ + {{ \ + .shift = { \ + .type = TSParseActionTypeShift, \ + .extra = true \ + } \ + }} + +#define REDUCE(symbol_name, children, precedence, prod_id) \ + {{ \ + .reduce = { \ + .type = TSParseActionTypeReduce, \ + .symbol = symbol_name, \ + .child_count = children, \ + .dynamic_precedence = precedence, \ + .production_id = prod_id \ + }, \ + }} + +#define RECOVER() \ + {{ \ + .type = TSParseActionTypeRecover \ + }} + +#define ACCEPT_INPUT() \ + {{ \ + .type = TSParseActionTypeAccept \ + }} + +#ifdef __cplusplus +} +#endif + +#endif // TREE_SITTER_PARSER_H_ diff --git a/crates/tree-sitter-compact/test/corpus/circuits-and-constructors.txt b/crates/tree-sitter-compact/test/corpus/circuits-and-constructors.txt new file mode 100644 index 00000000..0290bca4 --- /dev/null +++ b/crates/tree-sitter-compact/test/corpus/circuits-and-constructors.txt @@ -0,0 +1,152 @@ +================================================================================ +plain circuit +================================================================================ + +circuit assertInitialized(): [] { + assert(_isInitialized, "not initialized"); +} + +-------------------------------------------------------------------------------- + +(source_file + (circuit_declaration + name: (identifier) + parameters: (parameter_list) + type: (type_expression) + body: (block + (string)))) + +================================================================================ +exported circuit +================================================================================ + +export circuit owner(): Either, ContractAddress> { + return _owner; +} + +-------------------------------------------------------------------------------- + +(source_file + (circuit_declaration + name: (identifier) + parameters: (parameter_list) + type: (type_expression + (identifier) + (generic_arguments + (identifier) + (generic_arguments + (number)) + (identifier))) + body: (block))) + +================================================================================ +exported pure circuit +================================================================================ + +export pure circuit add(a: Uint<32>, b: Uint<32>): Uint<64> { + return a + b; +} + +-------------------------------------------------------------------------------- + +(source_file + (circuit_declaration + name: (identifier) + parameters: (parameter_list) + type: (type_expression + (identifier) + (generic_arguments + (number))) + body: (block))) + +================================================================================ +pure circuit +================================================================================ + +pure circuit half(x: Field): Field { + return x; +} + +-------------------------------------------------------------------------------- + +(source_file + (circuit_declaration + name: (identifier) + parameters: (parameter_list) + type: (type_expression + (identifier)) + body: (block))) + +================================================================================ +generic circuit +================================================================================ + +export circuit pick<#T, U>(a: T, b: U): T { + return a; +} + +-------------------------------------------------------------------------------- + +(source_file + (circuit_declaration + name: (identifier) + (generic_parameters + (generic_parameter + name: (identifier)) + (generic_parameter + name: (identifier))) + parameters: (parameter_list) + type: (type_expression + (identifier)) + body: (block))) + +================================================================================ +circuit with a destructuring parameter +================================================================================ + +circuit unpack({ left, right }: Pair): [] { + return []; +} + +-------------------------------------------------------------------------------- + +(source_file + (circuit_declaration + name: (identifier) + parameters: (parameter_list + (block)) + type: (type_expression) + body: (block))) + +================================================================================ +circuit body with braces inside a string +================================================================================ + +circuit shout(): [] { + assert(false, "} not a brace {"); +} + +-------------------------------------------------------------------------------- + +(source_file + (circuit_declaration + name: (identifier) + parameters: (parameter_list) + type: (type_expression) + body: (block + (string)))) + +================================================================================ +constructor +================================================================================ + +constructor(initialOwner: Either, ContractAddress>) { + Ownable_initialize(initialOwner); +} + +-------------------------------------------------------------------------------- + +(source_file + (constructor_declaration + (parameter_list) + (block))) diff --git a/crates/tree-sitter-compact/test/corpus/comments.txt b/crates/tree-sitter-compact/test/corpus/comments.txt new file mode 100644 index 00000000..edeb5583 --- /dev/null +++ b/crates/tree-sitter-compact/test/corpus/comments.txt @@ -0,0 +1,134 @@ +================================================================================ +line comment +================================================================================ + +// a note +ledger _x: Field; + +-------------------------------------------------------------------------------- + +(source_file + (line_comment) + (ledger_declaration + name: (identifier) + type: (type_expression + (identifier)))) + +================================================================================ +block comment +================================================================================ + +/* a note */ +ledger _x: Field; + +-------------------------------------------------------------------------------- + +(source_file + (block_comment) + (ledger_declaration + name: (identifier) + type: (type_expression + (identifier)))) + +================================================================================ +empty block comment +================================================================================ + +/**/ +ledger _x: Field; + +-------------------------------------------------------------------------------- + +(source_file + (block_comment) + (ledger_declaration + name: (identifier) + type: (type_expression + (identifier)))) + +================================================================================ +doc comment +================================================================================ + +/** @description A flag. */ +ledger _x: Boolean; + +-------------------------------------------------------------------------------- + +(source_file + (doc_comment) + (ledger_declaration + name: (identifier) + type: (type_expression + (identifier)))) + +================================================================================ +doc comment before an exported circuit +================================================================================ + +/** + * @description Returns the owner. + * @circuitInfo k=7, rows=76 + */ +export circuit owner(): Bytes<32> { + return _owner; +} + +-------------------------------------------------------------------------------- + +(source_file + (doc_comment) + (circuit_declaration + name: (identifier) + parameters: (parameter_list) + type: (type_expression + (identifier) + (generic_arguments + (number))) + body: (block))) + +================================================================================ +doc comment before an exported module +================================================================================ + +/** @module Ownable */ +export module Ownable { + /** @description A flag. */ + export ledger _isInitialized: Boolean; +} + +-------------------------------------------------------------------------------- + +(source_file + (doc_comment) + (module_declaration + name: (identifier) + body: (module_body + (doc_comment) + (ledger_declaration + name: (identifier) + type: (type_expression + (identifier)))))) + +================================================================================ +comments inside a circuit body +================================================================================ + +circuit noop(): [] { + // a line + /* a block */ + /** a doc */ + return []; +} + +-------------------------------------------------------------------------------- + +(source_file + (circuit_declaration + name: (identifier) + parameters: (parameter_list) + type: (type_expression) + body: (block + (line_comment) + (block_comment) + (doc_comment)))) diff --git a/crates/tree-sitter-compact/test/corpus/imports.txt b/crates/tree-sitter-compact/test/corpus/imports.txt new file mode 100644 index 00000000..b8bef8a3 --- /dev/null +++ b/crates/tree-sitter-compact/test/corpus/imports.txt @@ -0,0 +1,141 @@ +================================================================================ +bare module import +================================================================================ + +import CompactStandardLibrary; + +-------------------------------------------------------------------------------- + +(source_file + (import_declaration + name: (identifier))) + +================================================================================ +path import +================================================================================ + +import "./Foo"; + +-------------------------------------------------------------------------------- + +(source_file + (import_declaration + name: (string))) + +================================================================================ +module import with prefix +================================================================================ + +import Foo prefix Foo_; + +-------------------------------------------------------------------------------- + +(source_file + (import_declaration + name: (identifier) + (import_prefix + prefix: (identifier)))) + +================================================================================ +path import with prefix +================================================================================ + +import "./Foo" prefix F_; + +-------------------------------------------------------------------------------- + +(source_file + (import_declaration + name: (string) + (import_prefix + prefix: (identifier)))) + +================================================================================ +import with generic arguments +================================================================================ + +import Foo prefix X_; + +-------------------------------------------------------------------------------- + +(source_file + (import_declaration + name: (identifier) + (generic_arguments + (identifier) + (identifier)) + (import_prefix + prefix: (identifier)))) + +================================================================================ +path import with nested generic arguments +================================================================================ + +import "../../Signer"> prefix Signer_; + +-------------------------------------------------------------------------------- + +(source_file + (import_declaration + name: (string) + (generic_arguments + (identifier) + (generic_arguments + (identifier) + (identifier))) + (import_prefix + prefix: (identifier)))) + +================================================================================ +import selection +================================================================================ + +import { _name, _symbol } from "./Core"; + +-------------------------------------------------------------------------------- + +(source_file + (import_declaration + (import_selection + (import_element + (identifier)) + (import_element + (identifier))) + (string))) + +================================================================================ +import selection with alias and prefix +================================================================================ + +import { selfAsRecipient, UINT128_MAX as MAX } from "../utils/Utils" prefix Utils_; + +-------------------------------------------------------------------------------- + +(source_file + (import_declaration + (import_selection + (import_element + (identifier)) + (import_element + (identifier) + (identifier))) + (string) + (import_prefix + (identifier)))) + +================================================================================ +import selection from a bare module +================================================================================ + +import { ZswapCoinPublicKey, Either } from CompactStandardLibrary; + +-------------------------------------------------------------------------------- + +(source_file + (import_declaration + (import_selection + (import_element + (identifier)) + (import_element + (identifier))) + (identifier))) diff --git a/crates/tree-sitter-compact/test/corpus/modules-and-exports.txt b/crates/tree-sitter-compact/test/corpus/modules-and-exports.txt new file mode 100644 index 00000000..29eebea3 --- /dev/null +++ b/crates/tree-sitter-compact/test/corpus/modules-and-exports.txt @@ -0,0 +1,116 @@ +================================================================================ +module with declarations in its body +================================================================================ + +module Ownable { + import CompactStandardLibrary; + export ledger _owner: Bytes<32>; +} + +-------------------------------------------------------------------------------- + +(source_file + (module_declaration + name: (identifier) + body: (module_body + (import_declaration + name: (identifier)) + (ledger_declaration + name: (identifier) + type: (type_expression + (identifier) + (generic_arguments + (number))))))) + +================================================================================ +exported generic module +================================================================================ + +export module Signer { + export circuit check(x: T): Boolean { return true; } +} + +-------------------------------------------------------------------------------- + +(source_file + (module_declaration + name: (identifier) + (generic_parameters + (generic_parameter + name: (identifier))) + body: (module_body + (circuit_declaration + name: (identifier) + parameters: (parameter_list) + type: (type_expression + (identifier)) + body: (block))))) + +================================================================================ +nested modules +================================================================================ + +module Outer { + module Inner { + export ledger _flag: Boolean; + } +} + +-------------------------------------------------------------------------------- + +(source_file + (module_declaration + name: (identifier) + body: (module_body + (module_declaration + name: (identifier) + body: (module_body + (ledger_declaration + name: (identifier) + type: (type_expression + (identifier)))))))) + +================================================================================ +export list +================================================================================ + +export { A, B }; + +-------------------------------------------------------------------------------- + +(source_file + (export_declaration + (identifier) + (identifier))) + +================================================================================ +export list without a trailing semicolon +================================================================================ + +export { A, B, } + +-------------------------------------------------------------------------------- + +(source_file + (export_declaration + (identifier) + (identifier))) + +================================================================================ +export list inside a module +================================================================================ + +module M { + export { _name, _symbol, _decimals }; +} + +-------------------------------------------------------------------------------- + +(source_file + (module_declaration + name: (identifier) + body: (module_body + (export_declaration + (identifier) + (identifier) + (identifier))))) diff --git a/crates/tree-sitter-compact/test/corpus/pragma-and-include.txt b/crates/tree-sitter-compact/test/corpus/pragma-and-include.txt new file mode 100644 index 00000000..47ec3557 --- /dev/null +++ b/crates/tree-sitter-compact/test/corpus/pragma-and-include.txt @@ -0,0 +1,37 @@ +================================================================================ +pragma with a lower bound +================================================================================ + +pragma language_version >= 0.23.0; + +-------------------------------------------------------------------------------- + +(source_file + (pragma_declaration + name: (identifier) + (version_constraint))) + +================================================================================ +pragma with alternative versions +================================================================================ + +pragma language_version 0.16 || 0.17; + +-------------------------------------------------------------------------------- + +(source_file + (pragma_declaration + name: (identifier) + (version_constraint))) + +================================================================================ +include +================================================================================ + +include "./shared"; + +-------------------------------------------------------------------------------- + +(source_file + (include_declaration + path: (string))) diff --git a/crates/tree-sitter-compact/test/corpus/structs-enums-contracts.txt b/crates/tree-sitter-compact/test/corpus/structs-enums-contracts.txt new file mode 100644 index 00000000..50a79183 --- /dev/null +++ b/crates/tree-sitter-compact/test/corpus/structs-enums-contracts.txt @@ -0,0 +1,105 @@ +================================================================================ +struct +================================================================================ + +struct Val { + a: Field; + b: Boolean; +} + +-------------------------------------------------------------------------------- + +(source_file + (struct_declaration + name: (identifier) + body: (block))) + +================================================================================ +exported struct with a trailing semicolon +================================================================================ + +export struct Ciphertext { + c1: CurvePoint, + c2: CurvePoint, +}; + +-------------------------------------------------------------------------------- + +(source_file + (struct_declaration + name: (identifier) + body: (block))) + +================================================================================ +generic struct +================================================================================ + +export struct Box { + value: T; +} + +-------------------------------------------------------------------------------- + +(source_file + (struct_declaration + name: (identifier) + (generic_parameters + (generic_parameter + name: (identifier))) + body: (block))) + +================================================================================ +enum +================================================================================ + +enum Color { red, white, blue } + +-------------------------------------------------------------------------------- + +(source_file + (enum_declaration + name: (identifier) + body: (block))) + +================================================================================ +exported enum with a trailing semicolon +================================================================================ + +export enum ProposalStatus { Pending, Approved, Rejected, }; + +-------------------------------------------------------------------------------- + +(source_file + (enum_declaration + name: (identifier) + body: (block))) + +================================================================================ +external contract declaration +================================================================================ + +export contract Token { + circuit balanceOf(owner: Bytes<32>): Uint<128>; + pure circuit name(): Opaque<"string">; +}; + +-------------------------------------------------------------------------------- + +(source_file + (contract_declaration + name: (identifier) + body: (block + (string)))) + +================================================================================ +contract implements +================================================================================ + +contract implements Token; + +-------------------------------------------------------------------------------- + +(source_file + (implements_declaration + (type_expression + (identifier)))) diff --git a/crates/tree-sitter-compact/test/corpus/types-ledger-witness.txt b/crates/tree-sitter-compact/test/corpus/types-ledger-witness.txt new file mode 100644 index 00000000..67c6b33f --- /dev/null +++ b/crates/tree-sitter-compact/test/corpus/types-ledger-witness.txt @@ -0,0 +1,149 @@ +================================================================================ +ledger field +================================================================================ + +ledger _counter: Counter; + +-------------------------------------------------------------------------------- + +(source_file + (ledger_declaration + name: (identifier) + type: (type_expression + (identifier)))) + +================================================================================ +exported ledger field +================================================================================ + +export ledger _owner: Either, ContractAddress>; + +-------------------------------------------------------------------------------- + +(source_file + (ledger_declaration + name: (identifier) + type: (type_expression + (identifier) + (generic_arguments + (identifier) + (generic_arguments + (number)) + (identifier))))) + +================================================================================ +exported sealed ledger field +================================================================================ + +export sealed ledger _domain: Bytes<32>; + +-------------------------------------------------------------------------------- + +(source_file + (ledger_declaration + name: (identifier) + type: (type_expression + (identifier) + (generic_arguments + (number))))) + +================================================================================ +ledger field with a tuple type +================================================================================ + +ledger _pair: [Field, Boolean]; + +-------------------------------------------------------------------------------- + +(source_file + (ledger_declaration + name: (identifier) + type: (type_expression + (identifier) + (identifier)))) + +================================================================================ +witness +================================================================================ + +witness wit_CallerSK(): Bytes<32>; + +-------------------------------------------------------------------------------- + +(source_file + (witness_declaration + name: (identifier) + parameters: (parameter_list) + type: (type_expression + (identifier) + (generic_arguments + (number))))) + +================================================================================ +exported witness with parameters +================================================================================ + +export witness wit_balance(ct: ElGamal_Ciphertext): Uint<128>; + +-------------------------------------------------------------------------------- + +(source_file + (witness_declaration + name: (identifier) + parameters: (parameter_list) + type: (type_expression + (identifier) + (generic_arguments + (number))))) + +================================================================================ +type alias +================================================================================ + +type Hash = Bytes<32>; + +-------------------------------------------------------------------------------- + +(source_file + (type_declaration + name: (identifier) + value: (type_expression + (identifier) + (generic_arguments + (number))))) + +================================================================================ +exported new type alias +================================================================================ + +export new type AccountIdentifier = Bytes<32>; + +-------------------------------------------------------------------------------- + +(source_file + (type_declaration + name: (identifier) + value: (type_expression + (identifier) + (generic_arguments + (number))))) + +================================================================================ +generic type alias +================================================================================ + +export type Pair = [A, B]; + +-------------------------------------------------------------------------------- + +(source_file + (type_declaration + name: (identifier) + (generic_parameters + (generic_parameter + name: (identifier)) + (generic_parameter + name: (identifier))) + value: (type_expression + (identifier) + (identifier)))) diff --git a/crates/tree-sitter-compact/test/fixtures/upstream/NOTICE b/crates/tree-sitter-compact/test/fixtures/upstream/NOTICE new file mode 100644 index 00000000..9352fb85 --- /dev/null +++ b/crates/tree-sitter-compact/test/fixtures/upstream/NOTICE @@ -0,0 +1,17 @@ +The `.compact` files in this directory are copied verbatim from the Compact +compiler repository and are used here only as parser fixtures. + +Source: https://github.com/LFDT-Minokawa/compact +Path: examples/formatter/output/ +Commit: c47230cc8c3e743634166d9b84698ac2b238c418 +License: Apache-2.0 +Copyright: Copyright (C) 2025 Midnight Foundation + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +these files except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed +under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, either express or implied. See the License for the +specific language governing permissions and limitations under the License. diff --git a/crates/tree-sitter-compact/test/fixtures/upstream/already_formatted.compact b/crates/tree-sitter-compact/test/fixtures/upstream/already_formatted.compact new file mode 100644 index 00000000..800fb64a --- /dev/null +++ b/crates/tree-sitter-compact/test/fixtures/upstream/already_formatted.compact @@ -0,0 +1,26 @@ +// This file is part of Compact. +// Copyright (C) 2025 Midnight Foundation +// SPDX-License-Identifier: Apache-2.0 +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import CompactStandardLibrary; + +export ledger round: Counter; + +export circuit increment(): [] { + round.increment(1); +} + +export circuit decrement(): [] { + round.decrement(1); +} diff --git a/crates/tree-sitter-compact/test/fixtures/upstream/example_1.compact b/crates/tree-sitter-compact/test/fixtures/upstream/example_1.compact new file mode 100644 index 00000000..bae9c5b4 --- /dev/null +++ b/crates/tree-sitter-compact/test/fixtures/upstream/example_1.compact @@ -0,0 +1,34 @@ +// This file is part of Compact. +// Copyright (C) 2025 Midnight Foundation +// SPDX-License-Identifier: Apache-2.0 +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import CompactStandardLibrary; + +export circuit method(): [] { + const p = 1; + const z = 2; + const x = 3; +} + +constructor() { + const p: Field = 1; + + const z: Boolean = true; + + const y = default; + + const f = default> as Field; +} + +witness method_2(): Boolean; diff --git a/crates/tree-sitter-compact/test/fixtures/upstream/example_10.compact b/crates/tree-sitter-compact/test/fixtures/upstream/example_10.compact new file mode 100644 index 00000000..e6274dae --- /dev/null +++ b/crates/tree-sitter-compact/test/fixtures/upstream/example_10.compact @@ -0,0 +1,62 @@ +// This file is part of Compact. +// Copyright (C) 2025 Midnight Foundation +// SPDX-License-Identifier: Apache-2.0 +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import CompactStandardLibrary; + +export ledger c: Counter; + +export circuit decrement(amount: Uint<16>): [] { + return c.decrement(amount); +} + +export circuit increment(amount: Uint<16>): [] { + for (const f of 1..10) { + c.increment(1); + } + return c.increment(amount); +} + +export circuit reset_to_default(): [] { + assert(1 < 2, "hoho"); + return c.reset_to_default(); +} + +export circuit read(): Uint<64> { + if (1 == 2) + + { + return c.read(); + } + return c.read(); +} + +struct Val { + x: Field, + y: Boolean, + f: Field, + + x: Opaque<"string">, + + d: Vector<1, Boolean>, +} + +enum french { + a, + bm, + c, + d, +} + +export { Maybe }; diff --git a/crates/tree-sitter-compact/test/fixtures/upstream/example_11.compact b/crates/tree-sitter-compact/test/fixtures/upstream/example_11.compact new file mode 100644 index 00000000..062f535c --- /dev/null +++ b/crates/tree-sitter-compact/test/fixtures/upstream/example_11.compact @@ -0,0 +1,32 @@ +// This file is part of Compact. +// Copyright (C) 2025 Midnight Foundation +// SPDX-License-Identifier: Apache-2.0 +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +struct mariusz { + x: Field, + y: Field, + z: Field, +} + +export circuit bob(a: Field, x: Field,): [Uint<32>, Uint<32>,] { + return [1, 2,]; +} + +constructor() { + + const p = [1, 1, 1, 1, 1, 1, 1, 1, 1,]; + const f = mariusz { 1, 2, 3, }; + const g = [bob(1, 2,), bob(1, 2,), bob(1, 2,),]; + const phil = [1, 2, 3, [1, 2, 3,],]; +} diff --git a/crates/tree-sitter-compact/test/fixtures/upstream/example_12.compact b/crates/tree-sitter-compact/test/fixtures/upstream/example_12.compact new file mode 100644 index 00000000..7d1f0d3e --- /dev/null +++ b/crates/tree-sitter-compact/test/fixtures/upstream/example_12.compact @@ -0,0 +1,36 @@ +// This file is part of Compact. +// Copyright (C) 2025 Midnight Foundation +// SPDX-License-Identifier: Apache-2.0 +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +struct var9a { + a: Field, + b: Field +} + +struct var9b { + a: var9a, + b: var9a +} + +struct var9c { + a: var9b, + b: var9b +} + +export circuit test9(): [] { + const p = var9c { a: var9b { a: var9a { 1, 2 }, b: var9a { 1, 2 } }, + b: var9b { a: var9a { 1, 2 }, b: var9a { 1, 2 }, } }, + x = 1, + y = p.a.a.a + p.b.b.b; +} diff --git a/crates/tree-sitter-compact/test/fixtures/upstream/example_13.compact b/crates/tree-sitter-compact/test/fixtures/upstream/example_13.compact new file mode 100644 index 00000000..34734d94 --- /dev/null +++ b/crates/tree-sitter-compact/test/fixtures/upstream/example_13.compact @@ -0,0 +1,185 @@ +// This file is part of Compact. +// Copyright (C) 2025 Midnight Foundation +// SPDX-License-Identifier: Apache-2.0 +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import CompactStandardLibrary; + +export ledger total_operations: Counter; + +export ledger last_calculated_result: Field; + +export ledger operation_category_code: Uint<8>; + +export ledger result_value: Field; + +export ledger multiplier: Field; + +export ledger op_multiplier: Field; + +witness get_user_calculation_parameters_from_external_validation_source( + user_identifier_hash: Field, + initial_amount_value: Uint<64>, + scaling_factor_multiplier: Uint<64>, + offset_adjustment_value: Uint<64> + ): Uint<64>; + +witness retrieve_transaction_validation_context_and_authorization_flags( + transaction_reference_id: Field, + sender_account_identifier: Field, + receiver_account_identifier: Field, + operation_type_code: Uint<8> + ): [Boolean, Uint<64>]; + +circuit perform_complex_arithmetic_calculation_with_multiple_inputs( + base_calculation_value: Uint<64>, + primary_scaling_factor: Uint<64>, + secondary_offset_amount: Uint<64>, + final_adjustment_modifier: Uint<64> + ): Uint<64> { + return ((base_calculation_value * primary_scaling_factor) + secondary_offset_amount) + + final_adjustment_modifier; +} + +export circuit execute_tiered_bonus_calculation_based_on_user_metrics( + user_account_balance: Uint<64>, + transaction_total_amount: Uint<64>, + accumulated_loyalty_points: Uint<64>, + account_age_in_months: Uint<64> + ): Uint<64> { + const base = transaction_total_amount * 10 as Uint<64>; + const loyalty = accumulated_loyalty_points * 2 as Uint<64>; + const age = account_age_in_months * 3 as Uint<64>; + return (base + loyalty) + age; +} + +export circuit test_multiline_call_expressions(input_value: Uint<64>): Uint<64> { + const result_from_arithmetic = + perform_complex_arithmetic_calculation_with_multiple_inputs( + input_value, + 10 as Uint<64>, + 5 as Uint<64>, + 2 as Uint<64> + ); + const bonus_calculation_result = + execute_tiered_bonus_calculation_based_on_user_metrics( + input_value * 2 as Uint<64>, + input_value + 100 as Uint<64>, + 50 as Uint<64>, + 12 as Uint<64> + ); + return result_from_arithmetic + bonus_calculation_result; +} + +export circuit test_anonymous_circuit_in_fold(values: Vector<4, Uint<64>>): Uint<64> { + const sum_result = + fold((accumulator_running_total: Uint<64>, current_element_value: Uint<64>): Uint<64> => { + const intermediate_calculation = accumulator_running_total + current_element_value; + return intermediate_calculation; + }, + 0 as Uint<64>, + values); + return sum_result; +} + +export circuit test_complex_anonymous_circuit(input_vector: Vector<4, Uint<64>>): Uint<64> { + const transformed = + fold((running_accumulator_total: Uint<64>, vector_element_value: Uint<64>): Uint<64> => { + const doubled_value = vector_element_value * 2 as Uint<64>; + const with_bonus_added = doubled_value + 10 as Uint<64>; + return running_accumulator_total + with_bonus_added; + }, + 0 as Uint<64>, + input_vector); + return transformed; +} + +export circuit test_map_anonymous(input: Vector<4, Uint<64>>): Vector<4, Uint<64>> { + const result = map((element_value: Uint<64>): Uint<64> => { + const step_one = element_value * 3 as Uint<64>; + const step_two = step_one + 7 as Uint<64>; + return step_two; + }, + input); + return result; +} + +export circuit test_if_else_chain(operation_code: Uint<8>): Uint<64> { + result_value = 0 as Field; + if (operation_code == (0 as Uint<8>)) { + result_value = 100 as Field; + } else if (operation_code == (1 as Uint<8>)) { + result_value = 200 as Field; + } else if (operation_code == (2 as Uint<8>)) { + result_value = 300 as Field; + } else if (operation_code == (3 as Uint<8>)) { + result_value = 400 as Field; + } else if (operation_code == (4 as Uint<8>)) { + result_value = 500 as Field; + } else { + result_value = 0 as Field; + } + return result_value as Uint<64>; +} + +export circuit test_complex_if_else(category: Uint<8>, amount: Uint<64>): Uint<64> { + multiplier = 100 as Field; + if (category == (0 as Uint<8>)) { + multiplier = 100 as Field; + } else if (category == (1 as Uint<8>)) { + multiplier = 110 as Field; + } else if (category == (2 as Uint<8>)) { + multiplier = 125 as Field; + } else if (category == (3 as Uint<8>)) { + multiplier = 150 as Field; + } else if (category == (4 as Uint<8>)) { + multiplier = 200 as Field; + } else { + multiplier = 100 as Field; + } + return (amount * (multiplier as Uint<64>)); +} + +export circuit test_all_scenarios_combined( + op_type: Uint<8>, + base_amount: Uint<64>, + test_values: Vector<4, Uint<64>> + ): Uint<64> { + total_operations.increment(1 as Uint<16>); + const arithmetic_result = + perform_complex_arithmetic_calculation_with_multiple_inputs( + base_amount, + 2 as Uint<64>, + 10 as Uint<64>, + 5 as Uint<64> + ); + const vector_sum = + fold((acc: Uint<64>, val: Uint<64>): Uint<64> => { + return acc + val; + }, + 0 as Uint<64>, + test_values); + op_multiplier = 1 as Field; + if (op_type == (0 as Uint<8>)) { + op_multiplier = 1 as Field; + } else if (op_type == (1 as Uint<8>)) { + op_multiplier = 2 as Field; + } else if (op_type == (2 as Uint<8>)) { + op_multiplier = 3 as Field; + } else { + op_multiplier = 1 as Field; + } + last_calculated_result = ((arithmetic_result + vector_sum) * (op_multiplier as Uint<64>)) as Field; + operation_category_code = op_type; + return last_calculated_result as Uint<64>; +} diff --git a/crates/tree-sitter-compact/test/fixtures/upstream/example_2.compact b/crates/tree-sitter-compact/test/fixtures/upstream/example_2.compact new file mode 100644 index 00000000..364c3f28 --- /dev/null +++ b/crates/tree-sitter-compact/test/fixtures/upstream/example_2.compact @@ -0,0 +1,40 @@ +// This file is part of Compact. +// Copyright (C) 2025 Midnight Foundation +// SPDX-License-Identifier: Apache-2.0 +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import CompactStandardLibrary; + +export circuit method_3(): [] { + const p = 1; + const z = 2; + + if (p > z) { + assert(1 > 2, "troll"); + if (p > z) { + assert(1 > 2, "troll"); + if (p > z) { + assert(1 > 2, "troll"); + if (p > z) { + assert(1 > 2, "troll"); + if (p > z) { + assert(1 > 2, "troll"); + if (p > z) { + assert(1 > 2, "troll"); + } + } + } + } + } + } +} diff --git a/crates/tree-sitter-compact/test/fixtures/upstream/example_3.compact b/crates/tree-sitter-compact/test/fixtures/upstream/example_3.compact new file mode 100644 index 00000000..7f806e4e --- /dev/null +++ b/crates/tree-sitter-compact/test/fixtures/upstream/example_3.compact @@ -0,0 +1,41 @@ +// This file is part of Compact. +// Copyright (C) 2025 Midnight Foundation +// SPDX-License-Identifier: Apache-2.0 +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import CompactStandardLibrary; + +pragma language_version >= 0.15; + +export circuit method_4(): [] { + for (const i of 1..10) { + + assert(1 > 2, "troll"); + for (const i of 1..10) { + + assert(1 > 2, "troll"); + for (const i of 1..10) { + + assert(1 > 2, "troll"); + for (const i of 1..10) { + + assert(1 > 2, "troll"); + + } + + } + + } + + } +} diff --git a/crates/tree-sitter-compact/test/fixtures/upstream/example_4.compact b/crates/tree-sitter-compact/test/fixtures/upstream/example_4.compact new file mode 100644 index 00000000..716061bb --- /dev/null +++ b/crates/tree-sitter-compact/test/fixtures/upstream/example_4.compact @@ -0,0 +1,32 @@ +// This file is part of Compact. +// Copyright (C) 2025 Midnight Foundation +// SPDX-License-Identifier: Apache-2.0 +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import CompactStandardLibrary; + +export ledger test: Map; + +export ledger test2: Map; + +export circuit ronan(): [] { + return []; +} + +witness caroline(): Field; + +export circuit Grendel(x: Field, y: Field, z: Field, d: Uint<32>): Field + + { + return x + y + z; +} diff --git a/crates/tree-sitter-compact/test/fixtures/upstream/example_5.compact b/crates/tree-sitter-compact/test/fixtures/upstream/example_5.compact new file mode 100644 index 00000000..881f9b2c --- /dev/null +++ b/crates/tree-sitter-compact/test/fixtures/upstream/example_5.compact @@ -0,0 +1,34 @@ +// This file is part of Compact. +// Copyright (C) 2025 Midnight Foundation +// SPDX-License-Identifier: Apache-2.0 +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import CompactStandardLibrary; + +constructor(x: Field, y: Field, z: Field) { + const p = x + y + z; +} + +export circuit test(): Field { + assert(1 > 2, "hello world"); +} + +export circuit test2(): [] { + + const g = default>; +} + +export circuit test3(): Boolean { + const p = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,]; + return []; +} diff --git a/crates/tree-sitter-compact/test/fixtures/upstream/example_6.compact b/crates/tree-sitter-compact/test/fixtures/upstream/example_6.compact new file mode 100644 index 00000000..67d4ac45 --- /dev/null +++ b/crates/tree-sitter-compact/test/fixtures/upstream/example_6.compact @@ -0,0 +1,31 @@ +// This file is part of Compact. +// Copyright (C) 2025 Midnight Foundation +// SPDX-License-Identifier: Apache-2.0 +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import CompactStandardLibrary; + +constructor() { + const p = default; + const z = 1; +} + +export circuit test(): [] { + return []; +} + +witness barbara(): Boolean; + +witness arnold(x: Float): Boolean; + +export ledger counter: Counter; diff --git a/crates/tree-sitter-compact/test/fixtures/upstream/example_7.compact b/crates/tree-sitter-compact/test/fixtures/upstream/example_7.compact new file mode 100644 index 00000000..ea7282d9 --- /dev/null +++ b/crates/tree-sitter-compact/test/fixtures/upstream/example_7.compact @@ -0,0 +1,32 @@ +// This file is part of Compact. +// Copyright (C) 2025 Midnight Foundation +// SPDX-License-Identifier: Apache-2.0 +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import CompactStandardLibrary; + +constructor() { + const f = 4; + const z = 2; + const p = f + z; +} + +export circuit randolph(x: Field, z: Field): Field { + return x + z; +} + +witness adam(x: Field, y: Uint<32>): Uint<16>; + +export ledger round: Counter; + +export ledger ariadna: Map; diff --git a/crates/tree-sitter-compact/test/fixtures/upstream/example_8.compact b/crates/tree-sitter-compact/test/fixtures/upstream/example_8.compact new file mode 100644 index 00000000..8280eb9b --- /dev/null +++ b/crates/tree-sitter-compact/test/fixtures/upstream/example_8.compact @@ -0,0 +1,43 @@ +// This file is part of Compact. +// Copyright (C) 2025 Midnight Foundation +// SPDX-License-Identifier: Apache-2.0 +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +pragma language_version > 0.14; + +export ledger counter: Counter; + +export circuit reynolds(): Field { + return default; +} + +constructor(x: Field, y: Field, z: Field) { + for (const x of 1..10) { + assert(i == i, "hello world"); + } + for (const y of 0..10) { + if (y == 1) { + assert(y == y, + " + gorgonzola" + ); + } + } + return []; +} + +export circuit burt(): [] { + + const y = 1; + +} diff --git a/crates/tree-sitter-compact/test/fixtures/upstream/example_9.compact b/crates/tree-sitter-compact/test/fixtures/upstream/example_9.compact new file mode 100644 index 00000000..a78e3194 --- /dev/null +++ b/crates/tree-sitter-compact/test/fixtures/upstream/example_9.compact @@ -0,0 +1,34 @@ +// This file is part of Compact. +// Copyright (C) 2025 Midnight Foundation +// SPDX-License-Identifier: Apache-2.0 +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import CompactStandardLibrary; + +export ledger c: Counter; + +export circuit decrement(amount: Uint<16>): [] { + return c.decrement(amount); +} + +export circuit increment(amount: Uint<16>): [] { + return c.increment(amount); +} + +export circuit reset_to_default(): [] { + return c.reset_to_default(); +} + +export circuit read(): Uint<64> { + return c.read(); +} diff --git a/crates/tree-sitter-compact/tests/corpus.rs b/crates/tree-sitter-compact/tests/corpus.rs new file mode 100644 index 00000000..ea033738 --- /dev/null +++ b/crates/tree-sitter-compact/tests/corpus.rs @@ -0,0 +1,214 @@ +//! Real Compact sources must parse with no `ERROR` and no `MISSING` node. + +use std::path::{Path, PathBuf}; + +use tree_sitter::{Node, Parser, Tree}; + +/// Directories that never hold first-party Compact sources. +const SKIPPED_DIRS: [&str; 5] = ["node_modules", "target", "dist", "build", ".git"]; + +fn parser() -> Parser { + let mut parser = Parser::new(); + parser + .set_language(&tree_sitter_compact::LANGUAGE.into()) + .expect("the generated parser matches the tree-sitter ABI this crate builds against"); + parser +} + +fn workspace_root() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("..") + .join("..") + .canonicalize() + .expect("the crate sits two levels below the workspace root") +} + +fn compact_files(dirs: &[PathBuf]) -> Vec { + let mut files = Vec::new(); + for dir in dirs { + collect_compact_files(dir, &mut files); + } + files.sort(); + files +} + +fn collect_compact_files(dir: &Path, out: &mut Vec) { + let entries = std::fs::read_dir(dir) + .unwrap_or_else(|error| panic!("corpus directory {} is readable: {error}", dir.display())); + + for entry in entries { + let entry = entry.expect("a directory entry read without error"); + let path = entry.path(); + let name = entry.file_name(); + + if path.is_dir() { + if !SKIPPED_DIRS.iter().any(|skipped| name == *skipped) { + collect_compact_files(&path, out); + } + } else if path + .extension() + .is_some_and(|extension| extension == "compact") + { + out.push(path); + } + } +} + +fn child_kinds(node: Node) -> Vec<&'static str> { + let mut cursor = node.walk(); + let mut kinds = Vec::new(); + for child in node.children(&mut cursor) { + kinds.push(child.kind()); + } + kinds +} + +struct Defect { + kind: String, + start: usize, + end: usize, + excerpt: String, +} + +fn excerpt(source: &str, start: usize) -> String { + let tail = &source[start..]; + let mut end = 0; + for (index, character) in tail.char_indices().take(120) { + end = index + character.len_utf8(); + } + tail[..end].replace('\n', "\\n") +} + +fn find_defect(node: Node, source: &str) -> Option { + if node.is_error() || node.is_missing() { + let start = node.start_byte(); + return Some(Defect { + kind: if node.is_missing() { + format!("MISSING {}", node.kind()) + } else { + node.kind().to_owned() + }, + start, + end: node.end_byte(), + excerpt: excerpt(source, start), + }); + } + + if !node.has_error() { + return None; + } + + let mut cursor = node.walk(); + for child in node.children(&mut cursor) { + if let Some(defect) = find_defect(child, source) { + return Some(defect); + } + } + None +} + +fn assert_parses_clean(parser: &mut Parser, files: &[PathBuf]) { + for path in files { + let source = std::fs::read_to_string(path) + .unwrap_or_else(|error| panic!("{} is readable UTF-8: {error}", path.display())); + let tree: Tree = parser + .parse(&source, None) + .unwrap_or_else(|| panic!("{} produced a parse tree", path.display())); + + if let Some(defect) = find_defect(tree.root_node(), &source) { + let Defect { + kind, + start, + end, + excerpt, + } = defect; + panic!( + "{}: {kind} at bytes {start}..{end}\n {excerpt}", + path.display() + ); + } + } +} + +#[test] +fn upstream_corpus_parses_without_defects() { + let files = + compact_files(&[Path::new(env!("CARGO_MANIFEST_DIR")).join("test/fixtures/upstream")]); + + assert!( + !files.is_empty(), + "the upstream fixture directory is populated" + ); + println!("upstream corpus: {} files", files.len()); + assert_parses_clean(&mut parser(), &files); +} + +#[test] +fn in_repo_corpus_parses_without_defects() { + let root = workspace_root(); + let files = compact_files(&[ + root.join("tests/integrations/fixtures"), + root.join("examples"), + root.join("packages/simulator/test/fixtures/sample-contracts"), + ]); + + assert!(!files.is_empty(), "the repository ships Compact sources"); + println!("in-repo corpus: {} files", files.len()); + assert_parses_clean(&mut parser(), &files); +} + +#[test] +fn external_corpus_parses_without_defects() { + let Ok(dir) = std::env::var("COMPACT_CORPUS_DIR") else { + println!("external corpus: COMPACT_CORPUS_DIR unset, nothing checked"); + return; + }; + + let files = compact_files(&[PathBuf::from(&dir)]); + + assert!( + !files.is_empty(), + "COMPACT_CORPUS_DIR holds Compact sources" + ); + println!("external corpus: {} files under {dir}", files.len()); + assert_parses_clean(&mut parser(), &files); +} + +#[test] +fn doc_commented_export_pure_circuit_exposes_name_and_modifiers() { + let source = "/** @description Adds two numbers. */\n\ + export pure circuit add(a: Uint<32>, b: Uint<32>): Uint<64> {\n\ + \x20 return a + b;\n\ + }\n"; + + let tree = parser() + .parse(source, None) + .expect("the snippet produced a parse tree"); + let root = tree.root_node(); + assert!(!root.has_error(), "the snippet parsed without defects"); + assert_eq!(child_kinds(root), ["doc_comment", "circuit_declaration"]); + + let circuit = root.child(1).expect("the circuit follows its doc comment"); + assert_eq!( + child_kinds(circuit), + [ + "export", + "pure", + "circuit", + "identifier", + "parameter_list", + ":", + "type_expression", + "block", + ] + ); + + let name = circuit + .child_by_field_name("name") + .expect("a circuit declaration carries a name field"); + assert_eq!( + name.utf8_text(source.as_bytes()) + .expect("the source is valid UTF-8"), + "add" + ); +} diff --git a/crates/tree-sitter-compact/tree-sitter.json b/crates/tree-sitter-compact/tree-sitter.json new file mode 100644 index 00000000..f3f86e58 --- /dev/null +++ b/crates/tree-sitter-compact/tree-sitter.json @@ -0,0 +1,37 @@ +{ + "grammars": [ + { + "name": "compact", + "camelcase": "Compact", + "scope": "source.compact", + "path": ".", + "file-types": ["compact"], + "highlights": ["queries/highlights.scm"], + "injection-regex": "^compact$" + } + ], + "metadata": { + "version": "0.1.0", + "license": "MIT", + "description": "Declaration-level Compact grammar for tree-sitter", + "authors": [ + { + "name": "OpenZeppelin" + } + ], + "links": { + "repository": "https://github.com/OpenZeppelin/compact-tools" + } + }, + "bindings": { + "c": true, + "go": false, + "java": false, + "kotlin": false, + "node": false, + "python": false, + "rust": true, + "swift": false, + "zig": false + } +} diff --git a/rust-toolchain.toml b/rust-toolchain.toml new file mode 100644 index 00000000..38faa687 --- /dev/null +++ b/rust-toolchain.toml @@ -0,0 +1,3 @@ +[toolchain] +channel = "1.96" +components = ["rustfmt", "clippy"] From 0d4991ba96c40c26d540bc2bb855d5f89ab7fe7a Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Tue, 15 Sep 2026 09:41:51 +0200 Subject: [PATCH 02/56] refactor(compact-tree-sitter): rename the grammar crate Every crate in this workspace is named compact-*, so the grammar crate follows suit instead of the tree-sitter- convention. The grammar name in tree-sitter.json and the generated C symbol stay `compact`; only the Cargo package and its directory move. --- .github/workflows/rust.yml | 4 ++-- Cargo.lock | 18 +++++++++--------- biome.json | 2 +- .../Cargo.toml | 2 +- .../README.md | 4 ++-- .../bindings/rust/build.rs | 2 +- .../bindings/rust/lib.rs | 0 .../grammar.js | 0 .../package.json | 2 +- .../queries/highlights.scm | 0 .../src/grammar.json | 0 .../src/node-types.json | 0 .../src/parser.c | 0 .../src/tree_sitter/alloc.h | 0 .../src/tree_sitter/array.h | 0 .../src/tree_sitter/parser.h | 0 .../test/corpus/circuits-and-constructors.txt | 0 .../test/corpus/comments.txt | 0 .../test/corpus/imports.txt | 0 .../test/corpus/modules-and-exports.txt | 0 .../test/corpus/pragma-and-include.txt | 0 .../test/corpus/structs-enums-contracts.txt | 0 .../test/corpus/types-ledger-witness.txt | 0 .../test/fixtures/upstream/NOTICE | 0 .../upstream/already_formatted.compact | 0 .../test/fixtures/upstream/example_1.compact | 0 .../test/fixtures/upstream/example_10.compact | 0 .../test/fixtures/upstream/example_11.compact | 0 .../test/fixtures/upstream/example_12.compact | 0 .../test/fixtures/upstream/example_13.compact | 0 .../test/fixtures/upstream/example_2.compact | 0 .../test/fixtures/upstream/example_3.compact | 0 .../test/fixtures/upstream/example_4.compact | 0 .../test/fixtures/upstream/example_5.compact | 0 .../test/fixtures/upstream/example_6.compact | 0 .../test/fixtures/upstream/example_7.compact | 0 .../test/fixtures/upstream/example_8.compact | 0 .../test/fixtures/upstream/example_9.compact | 0 .../tests/corpus.rs | 2 +- .../tree-sitter.json | 0 40 files changed, 18 insertions(+), 18 deletions(-) rename crates/{tree-sitter-compact => compact-tree-sitter}/Cargo.toml (95%) rename crates/{tree-sitter-compact => compact-tree-sitter}/README.md (97%) rename crates/{tree-sitter-compact => compact-tree-sitter}/bindings/rust/build.rs (93%) rename crates/{tree-sitter-compact => compact-tree-sitter}/bindings/rust/lib.rs (100%) rename crates/{tree-sitter-compact => compact-tree-sitter}/grammar.js (100%) rename crates/{tree-sitter-compact => compact-tree-sitter}/package.json (89%) rename crates/{tree-sitter-compact => compact-tree-sitter}/queries/highlights.scm (100%) rename crates/{tree-sitter-compact => compact-tree-sitter}/src/grammar.json (100%) rename crates/{tree-sitter-compact => compact-tree-sitter}/src/node-types.json (100%) rename crates/{tree-sitter-compact => compact-tree-sitter}/src/parser.c (100%) rename crates/{tree-sitter-compact => compact-tree-sitter}/src/tree_sitter/alloc.h (100%) rename crates/{tree-sitter-compact => compact-tree-sitter}/src/tree_sitter/array.h (100%) rename crates/{tree-sitter-compact => compact-tree-sitter}/src/tree_sitter/parser.h (100%) rename crates/{tree-sitter-compact => compact-tree-sitter}/test/corpus/circuits-and-constructors.txt (100%) rename crates/{tree-sitter-compact => compact-tree-sitter}/test/corpus/comments.txt (100%) rename crates/{tree-sitter-compact => compact-tree-sitter}/test/corpus/imports.txt (100%) rename crates/{tree-sitter-compact => compact-tree-sitter}/test/corpus/modules-and-exports.txt (100%) rename crates/{tree-sitter-compact => compact-tree-sitter}/test/corpus/pragma-and-include.txt (100%) rename crates/{tree-sitter-compact => compact-tree-sitter}/test/corpus/structs-enums-contracts.txt (100%) rename crates/{tree-sitter-compact => compact-tree-sitter}/test/corpus/types-ledger-witness.txt (100%) rename crates/{tree-sitter-compact => compact-tree-sitter}/test/fixtures/upstream/NOTICE (100%) rename crates/{tree-sitter-compact => compact-tree-sitter}/test/fixtures/upstream/already_formatted.compact (100%) rename crates/{tree-sitter-compact => compact-tree-sitter}/test/fixtures/upstream/example_1.compact (100%) rename crates/{tree-sitter-compact => compact-tree-sitter}/test/fixtures/upstream/example_10.compact (100%) rename crates/{tree-sitter-compact => compact-tree-sitter}/test/fixtures/upstream/example_11.compact (100%) rename crates/{tree-sitter-compact => compact-tree-sitter}/test/fixtures/upstream/example_12.compact (100%) rename crates/{tree-sitter-compact => compact-tree-sitter}/test/fixtures/upstream/example_13.compact (100%) rename crates/{tree-sitter-compact => compact-tree-sitter}/test/fixtures/upstream/example_2.compact (100%) rename crates/{tree-sitter-compact => compact-tree-sitter}/test/fixtures/upstream/example_3.compact (100%) rename crates/{tree-sitter-compact => compact-tree-sitter}/test/fixtures/upstream/example_4.compact (100%) rename crates/{tree-sitter-compact => compact-tree-sitter}/test/fixtures/upstream/example_5.compact (100%) rename crates/{tree-sitter-compact => compact-tree-sitter}/test/fixtures/upstream/example_6.compact (100%) rename crates/{tree-sitter-compact => compact-tree-sitter}/test/fixtures/upstream/example_7.compact (100%) rename crates/{tree-sitter-compact => compact-tree-sitter}/test/fixtures/upstream/example_8.compact (100%) rename crates/{tree-sitter-compact => compact-tree-sitter}/test/fixtures/upstream/example_9.compact (100%) rename crates/{tree-sitter-compact => compact-tree-sitter}/tests/corpus.rs (99%) rename crates/{tree-sitter-compact => compact-tree-sitter}/tree-sitter.json (100%) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 2bc8283a..a3f227ab 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -39,8 +39,8 @@ jobs: run: cargo test --workspace - name: Check the generated parser is up to date - working-directory: crates/tree-sitter-compact + working-directory: crates/compact-tree-sitter run: npx -y tree-sitter-cli@0.25.8 generate - name: Fail if regeneration changed the parser - run: git diff --exit-code -- crates/tree-sitter-compact/src + run: git diff --exit-code -- crates/compact-tree-sitter/src diff --git a/Cargo.lock b/Cargo.lock index e78a9e5e..f1a04064 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -21,6 +21,15 @@ dependencies = [ "shlex", ] +[[package]] +name = "compact-tree-sitter" +version = "0.1.0" +dependencies = [ + "cc", + "tree-sitter", + "tree-sitter-language", +] + [[package]] name = "equivalent" version = "1.0.2" @@ -188,15 +197,6 @@ dependencies = [ "tree-sitter-language", ] -[[package]] -name = "tree-sitter-compact" -version = "0.1.0" -dependencies = [ - "cc", - "tree-sitter", - "tree-sitter-language", -] - [[package]] name = "tree-sitter-language" version = "0.1.8" diff --git a/biome.json b/biome.json index 88b7ec77..045f84ca 100644 --- a/biome.json +++ b/biome.json @@ -13,7 +13,7 @@ "!**/tsconfig.base.json", "!**/tsconfig*.json", "!**/*.compact", - "!crates/tree-sitter-compact/src/**/*", + "!crates/compact-tree-sitter/src/**/*", "!**/artifacts/**/*", "!**/coverage/**/*", "!**/dist/**/*", diff --git a/crates/tree-sitter-compact/Cargo.toml b/crates/compact-tree-sitter/Cargo.toml similarity index 95% rename from crates/tree-sitter-compact/Cargo.toml rename to crates/compact-tree-sitter/Cargo.toml index 3626181f..8ae71a81 100644 --- a/crates/tree-sitter-compact/Cargo.toml +++ b/crates/compact-tree-sitter/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "tree-sitter-compact" +name = "compact-tree-sitter" version = "0.1.0" description = "Declaration-level Compact grammar for tree-sitter" build = "bindings/rust/build.rs" diff --git a/crates/tree-sitter-compact/README.md b/crates/compact-tree-sitter/README.md similarity index 97% rename from crates/tree-sitter-compact/README.md rename to crates/compact-tree-sitter/README.md index 287c198a..50f0d706 100644 --- a/crates/tree-sitter-compact/README.md +++ b/crates/compact-tree-sitter/README.md @@ -1,4 +1,4 @@ -# tree-sitter-compact +# compact-tree-sitter Declaration-level [tree-sitter](https://tree-sitter.github.io) grammar for the Compact smart-contract language (Midnight), tracking language version 0.26. @@ -68,7 +68,7 @@ are generated and committed. After editing `grammar.js`: npx -y tree-sitter-cli@0.25.8 generate ``` -CI regenerates and fails on any diff under `crates/tree-sitter-compact/src`. +CI regenerates and fails on any diff under `crates/compact-tree-sitter/src`. ## Tests diff --git a/crates/tree-sitter-compact/bindings/rust/build.rs b/crates/compact-tree-sitter/bindings/rust/build.rs similarity index 93% rename from crates/tree-sitter-compact/bindings/rust/build.rs rename to crates/compact-tree-sitter/bindings/rust/build.rs index c65afd8f..603d5b77 100644 --- a/crates/tree-sitter-compact/bindings/rust/build.rs +++ b/crates/compact-tree-sitter/bindings/rust/build.rs @@ -10,7 +10,7 @@ fn main() { config.flag_if_supported("-Wno-unused-parameter"); config.flag_if_supported("-Wno-trigraphs"); - config.compile("tree-sitter-compact"); + config.compile("compact-tree-sitter"); println!("cargo:rerun-if-changed=src/parser.c"); println!("cargo:rerun-if-changed=src/grammar.json"); diff --git a/crates/tree-sitter-compact/bindings/rust/lib.rs b/crates/compact-tree-sitter/bindings/rust/lib.rs similarity index 100% rename from crates/tree-sitter-compact/bindings/rust/lib.rs rename to crates/compact-tree-sitter/bindings/rust/lib.rs diff --git a/crates/tree-sitter-compact/grammar.js b/crates/compact-tree-sitter/grammar.js similarity index 100% rename from crates/tree-sitter-compact/grammar.js rename to crates/compact-tree-sitter/grammar.js diff --git a/crates/tree-sitter-compact/package.json b/crates/compact-tree-sitter/package.json similarity index 89% rename from crates/tree-sitter-compact/package.json rename to crates/compact-tree-sitter/package.json index 7f85f180..2760c2ce 100644 --- a/crates/tree-sitter-compact/package.json +++ b/crates/compact-tree-sitter/package.json @@ -1,5 +1,5 @@ { - "name": "tree-sitter-compact", + "name": "compact-tree-sitter", "version": "0.1.0", "private": true, "description": "Declaration-level Compact grammar for tree-sitter", diff --git a/crates/tree-sitter-compact/queries/highlights.scm b/crates/compact-tree-sitter/queries/highlights.scm similarity index 100% rename from crates/tree-sitter-compact/queries/highlights.scm rename to crates/compact-tree-sitter/queries/highlights.scm diff --git a/crates/tree-sitter-compact/src/grammar.json b/crates/compact-tree-sitter/src/grammar.json similarity index 100% rename from crates/tree-sitter-compact/src/grammar.json rename to crates/compact-tree-sitter/src/grammar.json diff --git a/crates/tree-sitter-compact/src/node-types.json b/crates/compact-tree-sitter/src/node-types.json similarity index 100% rename from crates/tree-sitter-compact/src/node-types.json rename to crates/compact-tree-sitter/src/node-types.json diff --git a/crates/tree-sitter-compact/src/parser.c b/crates/compact-tree-sitter/src/parser.c similarity index 100% rename from crates/tree-sitter-compact/src/parser.c rename to crates/compact-tree-sitter/src/parser.c diff --git a/crates/tree-sitter-compact/src/tree_sitter/alloc.h b/crates/compact-tree-sitter/src/tree_sitter/alloc.h similarity index 100% rename from crates/tree-sitter-compact/src/tree_sitter/alloc.h rename to crates/compact-tree-sitter/src/tree_sitter/alloc.h diff --git a/crates/tree-sitter-compact/src/tree_sitter/array.h b/crates/compact-tree-sitter/src/tree_sitter/array.h similarity index 100% rename from crates/tree-sitter-compact/src/tree_sitter/array.h rename to crates/compact-tree-sitter/src/tree_sitter/array.h diff --git a/crates/tree-sitter-compact/src/tree_sitter/parser.h b/crates/compact-tree-sitter/src/tree_sitter/parser.h similarity index 100% rename from crates/tree-sitter-compact/src/tree_sitter/parser.h rename to crates/compact-tree-sitter/src/tree_sitter/parser.h diff --git a/crates/tree-sitter-compact/test/corpus/circuits-and-constructors.txt b/crates/compact-tree-sitter/test/corpus/circuits-and-constructors.txt similarity index 100% rename from crates/tree-sitter-compact/test/corpus/circuits-and-constructors.txt rename to crates/compact-tree-sitter/test/corpus/circuits-and-constructors.txt diff --git a/crates/tree-sitter-compact/test/corpus/comments.txt b/crates/compact-tree-sitter/test/corpus/comments.txt similarity index 100% rename from crates/tree-sitter-compact/test/corpus/comments.txt rename to crates/compact-tree-sitter/test/corpus/comments.txt diff --git a/crates/tree-sitter-compact/test/corpus/imports.txt b/crates/compact-tree-sitter/test/corpus/imports.txt similarity index 100% rename from crates/tree-sitter-compact/test/corpus/imports.txt rename to crates/compact-tree-sitter/test/corpus/imports.txt diff --git a/crates/tree-sitter-compact/test/corpus/modules-and-exports.txt b/crates/compact-tree-sitter/test/corpus/modules-and-exports.txt similarity index 100% rename from crates/tree-sitter-compact/test/corpus/modules-and-exports.txt rename to crates/compact-tree-sitter/test/corpus/modules-and-exports.txt diff --git a/crates/tree-sitter-compact/test/corpus/pragma-and-include.txt b/crates/compact-tree-sitter/test/corpus/pragma-and-include.txt similarity index 100% rename from crates/tree-sitter-compact/test/corpus/pragma-and-include.txt rename to crates/compact-tree-sitter/test/corpus/pragma-and-include.txt diff --git a/crates/tree-sitter-compact/test/corpus/structs-enums-contracts.txt b/crates/compact-tree-sitter/test/corpus/structs-enums-contracts.txt similarity index 100% rename from crates/tree-sitter-compact/test/corpus/structs-enums-contracts.txt rename to crates/compact-tree-sitter/test/corpus/structs-enums-contracts.txt diff --git a/crates/tree-sitter-compact/test/corpus/types-ledger-witness.txt b/crates/compact-tree-sitter/test/corpus/types-ledger-witness.txt similarity index 100% rename from crates/tree-sitter-compact/test/corpus/types-ledger-witness.txt rename to crates/compact-tree-sitter/test/corpus/types-ledger-witness.txt diff --git a/crates/tree-sitter-compact/test/fixtures/upstream/NOTICE b/crates/compact-tree-sitter/test/fixtures/upstream/NOTICE similarity index 100% rename from crates/tree-sitter-compact/test/fixtures/upstream/NOTICE rename to crates/compact-tree-sitter/test/fixtures/upstream/NOTICE diff --git a/crates/tree-sitter-compact/test/fixtures/upstream/already_formatted.compact b/crates/compact-tree-sitter/test/fixtures/upstream/already_formatted.compact similarity index 100% rename from crates/tree-sitter-compact/test/fixtures/upstream/already_formatted.compact rename to crates/compact-tree-sitter/test/fixtures/upstream/already_formatted.compact diff --git a/crates/tree-sitter-compact/test/fixtures/upstream/example_1.compact b/crates/compact-tree-sitter/test/fixtures/upstream/example_1.compact similarity index 100% rename from crates/tree-sitter-compact/test/fixtures/upstream/example_1.compact rename to crates/compact-tree-sitter/test/fixtures/upstream/example_1.compact diff --git a/crates/tree-sitter-compact/test/fixtures/upstream/example_10.compact b/crates/compact-tree-sitter/test/fixtures/upstream/example_10.compact similarity index 100% rename from crates/tree-sitter-compact/test/fixtures/upstream/example_10.compact rename to crates/compact-tree-sitter/test/fixtures/upstream/example_10.compact diff --git a/crates/tree-sitter-compact/test/fixtures/upstream/example_11.compact b/crates/compact-tree-sitter/test/fixtures/upstream/example_11.compact similarity index 100% rename from crates/tree-sitter-compact/test/fixtures/upstream/example_11.compact rename to crates/compact-tree-sitter/test/fixtures/upstream/example_11.compact diff --git a/crates/tree-sitter-compact/test/fixtures/upstream/example_12.compact b/crates/compact-tree-sitter/test/fixtures/upstream/example_12.compact similarity index 100% rename from crates/tree-sitter-compact/test/fixtures/upstream/example_12.compact rename to crates/compact-tree-sitter/test/fixtures/upstream/example_12.compact diff --git a/crates/tree-sitter-compact/test/fixtures/upstream/example_13.compact b/crates/compact-tree-sitter/test/fixtures/upstream/example_13.compact similarity index 100% rename from crates/tree-sitter-compact/test/fixtures/upstream/example_13.compact rename to crates/compact-tree-sitter/test/fixtures/upstream/example_13.compact diff --git a/crates/tree-sitter-compact/test/fixtures/upstream/example_2.compact b/crates/compact-tree-sitter/test/fixtures/upstream/example_2.compact similarity index 100% rename from crates/tree-sitter-compact/test/fixtures/upstream/example_2.compact rename to crates/compact-tree-sitter/test/fixtures/upstream/example_2.compact diff --git a/crates/tree-sitter-compact/test/fixtures/upstream/example_3.compact b/crates/compact-tree-sitter/test/fixtures/upstream/example_3.compact similarity index 100% rename from crates/tree-sitter-compact/test/fixtures/upstream/example_3.compact rename to crates/compact-tree-sitter/test/fixtures/upstream/example_3.compact diff --git a/crates/tree-sitter-compact/test/fixtures/upstream/example_4.compact b/crates/compact-tree-sitter/test/fixtures/upstream/example_4.compact similarity index 100% rename from crates/tree-sitter-compact/test/fixtures/upstream/example_4.compact rename to crates/compact-tree-sitter/test/fixtures/upstream/example_4.compact diff --git a/crates/tree-sitter-compact/test/fixtures/upstream/example_5.compact b/crates/compact-tree-sitter/test/fixtures/upstream/example_5.compact similarity index 100% rename from crates/tree-sitter-compact/test/fixtures/upstream/example_5.compact rename to crates/compact-tree-sitter/test/fixtures/upstream/example_5.compact diff --git a/crates/tree-sitter-compact/test/fixtures/upstream/example_6.compact b/crates/compact-tree-sitter/test/fixtures/upstream/example_6.compact similarity index 100% rename from crates/tree-sitter-compact/test/fixtures/upstream/example_6.compact rename to crates/compact-tree-sitter/test/fixtures/upstream/example_6.compact diff --git a/crates/tree-sitter-compact/test/fixtures/upstream/example_7.compact b/crates/compact-tree-sitter/test/fixtures/upstream/example_7.compact similarity index 100% rename from crates/tree-sitter-compact/test/fixtures/upstream/example_7.compact rename to crates/compact-tree-sitter/test/fixtures/upstream/example_7.compact diff --git a/crates/tree-sitter-compact/test/fixtures/upstream/example_8.compact b/crates/compact-tree-sitter/test/fixtures/upstream/example_8.compact similarity index 100% rename from crates/tree-sitter-compact/test/fixtures/upstream/example_8.compact rename to crates/compact-tree-sitter/test/fixtures/upstream/example_8.compact diff --git a/crates/tree-sitter-compact/test/fixtures/upstream/example_9.compact b/crates/compact-tree-sitter/test/fixtures/upstream/example_9.compact similarity index 100% rename from crates/tree-sitter-compact/test/fixtures/upstream/example_9.compact rename to crates/compact-tree-sitter/test/fixtures/upstream/example_9.compact diff --git a/crates/tree-sitter-compact/tests/corpus.rs b/crates/compact-tree-sitter/tests/corpus.rs similarity index 99% rename from crates/tree-sitter-compact/tests/corpus.rs rename to crates/compact-tree-sitter/tests/corpus.rs index ea033738..7ff16ed6 100644 --- a/crates/tree-sitter-compact/tests/corpus.rs +++ b/crates/compact-tree-sitter/tests/corpus.rs @@ -10,7 +10,7 @@ const SKIPPED_DIRS: [&str; 5] = ["node_modules", "target", "dist", "build", ".gi fn parser() -> Parser { let mut parser = Parser::new(); parser - .set_language(&tree_sitter_compact::LANGUAGE.into()) + .set_language(&compact_tree_sitter::LANGUAGE.into()) .expect("the generated parser matches the tree-sitter ABI this crate builds against"); parser } diff --git a/crates/tree-sitter-compact/tree-sitter.json b/crates/compact-tree-sitter/tree-sitter.json similarity index 100% rename from crates/tree-sitter-compact/tree-sitter.json rename to crates/compact-tree-sitter/tree-sitter.json From ec5cb8a0e5d21cfe11d7a78870ce45b8e994d4ff Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Tue, 15 Sep 2026 09:43:29 +0200 Subject: [PATCH 03/56] feat(compact-lint): add the check command Adds the compact-lint CLI with one subcommand, check, that enforces per-declaration-kind doc-comment templates from compact-lint.toml and optionally runs compact format --check. Findings print one per line as path:line:col: rule: message on stdout; exit 1 on findings, 2 on any error. fix and fill-constraints come later and only add tables to the same toml. * doc: tags parsed into an ordered list with line and column, so a finding points at the @ of the offending tag. * rules: missing-doc, missing-tag, forbidden-tag, module-name, missing-constraints, constraints-format, constraints-placeholder (--strict), parse, format. Constraints apply to exported non-pure circuits only. * config: every field optional, unknown keys and tags without their @ rejected; an explicit --config is a preset anchored at the cwd. * tests: one fixture case per rule through the binary, plus unit tests per module. --- Cargo.lock | 365 +++++++++++++++ Cargo.toml | 10 + crates/compact-lint/Cargo.toml | 33 ++ crates/compact-lint/README.md | 128 ++++++ .../examples/compact-contracts.toml | 40 ++ crates/compact-lint/src/check.rs | 117 +++++ crates/compact-lint/src/config.rs | 305 +++++++++++++ crates/compact-lint/src/discover.rs | 114 +++++ crates/compact-lint/src/doc.rs | 211 +++++++++ crates/compact-lint/src/format.rs | 156 +++++++ crates/compact-lint/src/lib.rs | 16 + crates/compact-lint/src/main.rs | 114 +++++ crates/compact-lint/src/model.rs | 177 ++++++++ crates/compact-lint/src/report.rs | 142 ++++++ crates/compact-lint/src/rules.rs | 415 ++++++++++++++++++ crates/compact-lint/tests/check.rs | 172 ++++++++ .../tests/fixtures/clean/Clean.compact | 56 +++ .../tests/fixtures/clean/compact-lint.toml | 27 ++ .../tests/fixtures/clean/expected.txt | 0 .../constraints-format/Malformed.compact | 17 + .../constraints-format/compact-lint.toml | 27 ++ .../fixtures/constraints-format/expected.txt | 2 + .../constraints-placeholder/Unfilled.compact | 11 + .../constraints-placeholder/compact-lint.toml | 27 ++ .../constraints-placeholder/expected.txt | 1 + .../fixtures/forbidden-tag/Returns.compact | 18 + .../fixtures/forbidden-tag/compact-lint.toml | 27 ++ .../tests/fixtures/forbidden-tag/expected.txt | 2 + .../missing-constraints/Unmeasured.compact | 17 + .../missing-constraints/compact-lint.toml | 27 ++ .../fixtures/missing-constraints/expected.txt | 1 + .../tests/fixtures/missing-doc/Gaps.compact | 20 + .../fixtures/missing-doc/compact-lint.toml | 27 ++ .../tests/fixtures/missing-doc/expected.txt | 3 + .../fixtures/missing-tag/Untagged.compact | 10 + .../fixtures/missing-tag/compact-lint.toml | 27 ++ .../tests/fixtures/missing-tag/expected.txt | 2 + .../fixtures/module-name/Renamed.compact | 6 + .../fixtures/module-name/compact-lint.toml | 27 ++ .../tests/fixtures/module-name/expected.txt | 1 + .../tests/fixtures/parse/Broken.compact | 3 + .../tests/fixtures/parse/compact-lint.toml | 2 + .../tests/fixtures/parse/expected.txt | 1 + 43 files changed, 2904 insertions(+) create mode 100644 crates/compact-lint/Cargo.toml create mode 100644 crates/compact-lint/README.md create mode 100644 crates/compact-lint/examples/compact-contracts.toml create mode 100644 crates/compact-lint/src/check.rs create mode 100644 crates/compact-lint/src/config.rs create mode 100644 crates/compact-lint/src/discover.rs create mode 100644 crates/compact-lint/src/doc.rs create mode 100644 crates/compact-lint/src/format.rs create mode 100644 crates/compact-lint/src/lib.rs create mode 100644 crates/compact-lint/src/main.rs create mode 100644 crates/compact-lint/src/model.rs create mode 100644 crates/compact-lint/src/report.rs create mode 100644 crates/compact-lint/src/rules.rs create mode 100644 crates/compact-lint/tests/check.rs create mode 100644 crates/compact-lint/tests/fixtures/clean/Clean.compact create mode 100644 crates/compact-lint/tests/fixtures/clean/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/clean/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/constraints-format/Malformed.compact create mode 100644 crates/compact-lint/tests/fixtures/constraints-format/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/constraints-format/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/constraints-placeholder/Unfilled.compact create mode 100644 crates/compact-lint/tests/fixtures/constraints-placeholder/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/constraints-placeholder/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/forbidden-tag/Returns.compact create mode 100644 crates/compact-lint/tests/fixtures/forbidden-tag/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/forbidden-tag/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/missing-constraints/Unmeasured.compact create mode 100644 crates/compact-lint/tests/fixtures/missing-constraints/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/missing-constraints/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/missing-doc/Gaps.compact create mode 100644 crates/compact-lint/tests/fixtures/missing-doc/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/missing-doc/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/missing-tag/Untagged.compact create mode 100644 crates/compact-lint/tests/fixtures/missing-tag/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/missing-tag/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/module-name/Renamed.compact create mode 100644 crates/compact-lint/tests/fixtures/module-name/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/module-name/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/parse/Broken.compact create mode 100644 crates/compact-lint/tests/fixtures/parse/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/parse/expected.txt diff --git a/Cargo.lock b/Cargo.lock index f1a04064..80f353a8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11,6 +11,88 @@ dependencies = [ "memchr", ] +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "assert_cmd" +version = "2.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2aa3a22042e45de04255c7bf3626e239f450200fd0493c1e382263544b20aea6" +dependencies = [ + "anstyle", + "bstr", + "libc", + "predicates", + "predicates-core", + "predicates-tree", + "wait-timeout", +] + +[[package]] +name = "bstr" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f" +dependencies = [ + "memchr", + "regex-automata", + "serde_core", +] + [[package]] name = "cc" version = "1.4.6" @@ -21,6 +103,68 @@ dependencies = [ "shlex", ] +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "compact-lint" +version = "0.1.0" +dependencies = [ + "anyhow", + "assert_cmd", + "clap", + "compact-tree-sitter", + "globset", + "serde", + "thiserror", + "toml", + "tree-sitter", + "walkdir", +] + [[package]] name = "compact-tree-sitter" version = "0.1.0" @@ -30,6 +174,12 @@ dependencies = [ "tree-sitter-language", ] +[[package]] +name = "difflib" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8" + [[package]] name = "equivalent" version = "1.0.2" @@ -42,12 +192,31 @@ version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e0f1c7c3a72c66fd80abe965175f7523475c0489a87d3ff9d6e8c87d87a9d2d" +[[package]] +name = "globset" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07c34a9410465b45bd9787443bc7370f37735bad04b0f0cd57ff1a3186c98988" +dependencies = [ + "aho-corasick", + "bstr", + "log", + "regex-automata", + "regex-syntax", +] + [[package]] name = "hashbrown" version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + [[package]] name = "indexmap" version = "2.14.2" @@ -58,18 +227,69 @@ dependencies = [ "hashbrown", ] +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + [[package]] name = "itoa" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + [[package]] name = "memchr" version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "predicates" +version = "3.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ada8f2932f28a27ee7b70dd6c1c39ea0675c55a36879ab92f3a715eaa1e63cfe" +dependencies = [ + "anstyle", + "difflib", + "predicates-core", +] + +[[package]] +name = "predicates-core" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cad38746f3166b4031b1a0d39ad9f954dd291e7854fcc0eed52ee41a0b50d144" + +[[package]] +name = "predicates-tree" +version = "1.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0de1b847b39c8131db0467e9df1ff60e6d0562ab8e9a16e568ad0fdb372e2f2" +dependencies = [ + "predicates-core", + "termtree", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -117,6 +337,15 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + [[package]] name = "serde" version = "1.0.229" @@ -124,6 +353,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" dependencies = [ "serde_core", + "serde_derive", ] [[package]] @@ -160,6 +390,15 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_spanned" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" +dependencies = [ + "serde_core", +] + [[package]] name = "shlex" version = "2.0.1" @@ -172,6 +411,12 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b2231b7c3057d5e4ad0156fb3dc807d900806020c5ffa3ee6ff2c8c76fb8520" +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + [[package]] name = "syn" version = "3.0.5" @@ -183,6 +428,71 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "termtree" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683" + +[[package]] +name = "thiserror" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "toml" +version = "1.1.6+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "920602543f0911ab71da12c50d59701da54c196d1a2bf5cb4b75667f137a406a" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2" + [[package]] name = "tree-sitter" version = "0.25.10" @@ -209,6 +519,61 @@ version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "wait-timeout" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" +dependencies = [ + "libc", +] + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" + [[package]] name = "zmij" version = "1.0.23" diff --git a/Cargo.toml b/Cargo.toml index af074357..5e096be2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,16 @@ rust-version = "1.96" pedantic = { level = "warn", priority = -1 } [workspace.dependencies] +anyhow = "1.0" cc = "1" +clap = { version = "4.6", features = ["derive", "env"] } +globset = "0.4" +serde = { version = "1.0", features = ["derive"] } +thiserror = "2.0" +toml = "1.1" tree-sitter = "0.25" +compact-tree-sitter = { version = "0.1.0", path = "crates/compact-tree-sitter" } tree-sitter-language = "0.1" +walkdir = "2.5" + +assert_cmd = "2.2" diff --git a/crates/compact-lint/Cargo.toml b/crates/compact-lint/Cargo.toml new file mode 100644 index 00000000..09834756 --- /dev/null +++ b/crates/compact-lint/Cargo.toml @@ -0,0 +1,33 @@ +[package] +name = "compact-lint" +version = "0.1.0" +description = "Doc-comment linter for Compact sources" +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[lints] +workspace = true + +[lib] +name = "compact_lint" +path = "src/lib.rs" + +[[bin]] +name = "compact-lint" +path = "src/main.rs" + +[dependencies] +anyhow.workspace = true +clap.workspace = true +globset.workspace = true +serde.workspace = true +thiserror.workspace = true +toml.workspace = true +tree-sitter.workspace = true +compact-tree-sitter.workspace = true +walkdir.workspace = true + +[dev-dependencies] +assert_cmd.workspace = true diff --git a/crates/compact-lint/README.md b/crates/compact-lint/README.md new file mode 100644 index 00000000..28bd6284 --- /dev/null +++ b/crates/compact-lint/README.md @@ -0,0 +1,128 @@ +# compact-lint + +Doc-comment linter for Compact sources. It parses `.compact` files with +[`compact-tree-sitter`](../compact-tree-sitter), matches every declaration against the +per-kind template in `compact-lint.toml`, and prints one finding per line. + +## Usage + +```sh +compact-lint check [PATHS]... [--config ] [--strict] [--no-format] [--compact-bin ] +``` + +- `PATHS` β€” files or directories, walked recursively for `.compact`. Skipped while + walking: `node_modules`, `target`, `dist`, `build`, `.git`. +- No `PATHS` β€” the config's `include` globs are used instead. +- `--config ` β€” use this config instead of searching upward for + `compact-lint.toml`. +- `--strict` β€” turn `k=?` / `rows=?` placeholders into findings. Use it on release + branches. +- `--no-format` β€” skip the `compact format --check` pass. Required where the `compact` + binary is unavailable, CI included. +- `--compact-bin ` β€” path to the `compact` binary. Also settable with + `COMPACT_LINT_COMPACT_BIN`; the flag wins. + +Findings go to stdout, one per line, in `path:line:col: rule: message` form (the +rustc / eslint shape, so editors and `grep` both read it). The `N findings in M files` +summary goes to stderr, where `M` is the number of files checked. + +## Exit codes + +- `0` β€” no findings. +- `1` β€” findings. +- `2` β€” usage, config, IO or parser error. + +## Rules + +| Rule | Meaning | +| --- | --- | +| `missing-doc` | The declaration needs docs per `kinds..docs` and has no doc comment attached. | +| `missing-tag` | A tag listed in `kinds..tags` is absent from the doc comment. | +| `forbidden-tag` | A tag listed in `tags.forbid` is present. | +| `module-name` | `@module ` does not name the module it documents. | +| `missing-constraints` | An exported non-pure circuit has no constraints tag. | +| `constraints-format` | The constraints value is not `k=, rows=`. | +| `constraints-placeholder` | `--strict` only: the constraints value still holds a `?`. | +| `parse` | The file holds a syntax defect; the first one is reported and the doc rules are skipped for that file. | +| `format` | `compact format --check` reported the file. | + +Rule detail: + +- **Attachment.** A doc comment counts as attached only when it is the declaration's + immediately preceding *named* sibling. A `//` or `/* */` comment between the two + breaks the attachment and the declaration reads as undocumented. +- **Export.** "Exported" means the declaration carries the `export` token itself. A + non-exported circuit inside an exported module is not exported. +- **Constraints.** The rule applies to exported non-pure circuits only, and that is + fixed, not configurable. A missing doc comment reports as `missing-doc`, not + `missing-constraints`. +- **`module-name`.** The documented name is the first word of the `@module` value, + without its generic arguments or trailing punctuation, so `@module Signer` matches + `module Signer` and `@module Utils.` matches `module Utils`. +- **`forbidden-tag`.** It fires on any doc comment attached to a checked declaration, + including declarations whose docs are optional. + +## Config + +`compact-lint.toml`, searched for upward from the current directory. Every field is +optional; unknown fields are rejected. A config found by walking upward anchors the +`include` globs at its own directory; a config named with `--config` is a shareable +preset, so the globs stay anchored at the current directory. + +```toml +version = 1 +include = ["contracts/src/**/*.compact"] +exclude = ["**/test/mocks/**", "**/archive/**"] + +[constraints] +tag = "@constraints" + +[tags] +forbid = ["@return"] + +[kinds.module] +docs = "exported" +tags = ["@module", "@description"] +``` + +Defaults when no config file is found: + +| Key | Default | +| --- | --- | +| `version` | `1`, the only version this build accepts | +| `include` | `["**/*.compact"]` | +| `exclude` | `[]` | +| `constraints.tag` | `"@constraints"` | +| `tags.forbid` | `[]` | +| `kinds..docs` | `"exported"` | +| `kinds..tags` | `[]` | + +- `kinds` takes one table per kind: `module`, `circuit`, `ledger`, `witness`, + `constructor`, `struct`, `enum`, `contract`, `type`. `pragma`, `import`, `include`, + `export { … }` and `contract implements` are never checked. +- `docs` is `"all"`, `"exported"` or `"none"`. +- `constructor` carries no `export` token, so `"exported"` means "never" for it. Use + `"all"` or `"none"` there. +- `exclude` filters files found by walking a directory. A file named on the command + line is always checked. + +`examples/compact-contracts.toml` is the config for OpenZeppelin/compact-contracts. + +## Doc-comment model + +- `/**`, `*/` and the leading ` * ` gutter are stripped. +- A tag line's first non-blank token is `@` followed by one or more ASCII letters. +- A tag's value is the rest of its line plus every following line until the next tag or + a blank line. +- Repeated tags are kept in source order; `@param` normally repeats. +- `@param {Type} name - text` is not parsed further. + +## Tests + +```sh +cargo test --workspace +``` + +`tests/fixtures//` holds one case per rule plus a clean case: a +`compact-lint.toml`, the `.compact` sources, and `expected.txt`, the exact stdout with +paths relative to the case directory. diff --git a/crates/compact-lint/examples/compact-contracts.toml b/crates/compact-lint/examples/compact-contracts.toml new file mode 100644 index 00000000..402186d0 --- /dev/null +++ b/crates/compact-lint/examples/compact-contracts.toml @@ -0,0 +1,40 @@ +# compact-lint config for OpenZeppelin/compact-contracts. +# Copy it to the repository root as compact-lint.toml. + +version = 1 +include = ["contracts/src/**/*.compact"] +exclude = ["**/test/mocks/**", "**/archive/**"] + +# `@constraints` is the default; set `tag` to point the rule at another annotation. +[constraints] +tag = "@constraints" + +[tags] +forbid = ["@return"] + +[kinds.module] +docs = "exported" +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] + +[kinds.ledger] +tags = ["@description"] + +[kinds.witness] +docs = "all" +tags = ["@description"] + +[kinds.struct] +tags = ["@description"] + +[kinds.enum] +tags = ["@description"] + +[kinds.constructor] +docs = "none" + +[kinds.contract] + +[kinds.type] diff --git a/crates/compact-lint/src/check.rs b/crates/compact-lint/src/check.rs new file mode 100644 index 00000000..2f2d2a88 --- /dev/null +++ b/crates/compact-lint/src/check.rs @@ -0,0 +1,117 @@ +//! The `check` subcommand: resolve config, collect files, run the rules. + +use std::ffi::OsString; +use std::path::{Path, PathBuf}; + +use thiserror::Error; + +use crate::config::{Config, ConfigError, discover as discover_config}; +use crate::discover::{self, DiscoverError}; +use crate::format::{self, FormatError}; +use crate::report::Finding; +use crate::rules::{LintError, Linter}; + +#[derive(Debug, Error)] +pub enum CheckError { + #[error(transparent)] + Config(#[from] ConfigError), + #[error(transparent)] + Discover(#[from] DiscoverError), + #[error(transparent)] + Lint(#[from] LintError), + #[error(transparent)] + Format(#[from] FormatError), + #[error("cannot read {path}")] + Read { + path: PathBuf, + #[source] + source: std::io::Error, + }, +} + +/// Everything the `check` subcommand needs, already resolved from flags and env. +pub struct Options { + pub paths: Vec, + pub config_path: Option, + pub strict: bool, + pub no_format: bool, + pub compact_bin: OsString, +} + +/// The findings, plus how many files produced them. +pub struct Outcome { + pub findings: Vec, + pub files_checked: usize, +} + +impl Outcome { + #[must_use] + pub fn summary(&self) -> String { + format!( + "{} findings in {} files", + self.findings.len(), + self.files_checked + ) + } +} + +/// Runs the subcommand with `cwd` as the working directory. +/// # Errors +/// Returns an error when the config, the file walk, the parser or the formatter fails. +pub fn run(options: &Options, cwd: &Path) -> Result { + let (config, config_path, base) = resolve_config(options, cwd)?; + let source = config_path.as_deref().unwrap_or(Path::new("")); + + let exclude = config.exclude_set(source)?; + let files = if options.paths.is_empty() { + let include = config.include_set(source)?; + discover::from_globs(&base, &include, &exclude)? + } else { + discover::from_paths(&options.paths, &base, &exclude)? + }; + let files: Vec = files.iter().map(|path| display_path(path, cwd)).collect(); + + let mut linter = Linter::new()?; + let mut findings = Vec::new(); + for path in &files { + let text = std::fs::read_to_string(path).map_err(|source| CheckError::Read { + path: path.clone(), + source, + })?; + findings.extend(linter.check(path, &text, &config, options.strict)?); + } + + if !options.no_format { + findings.extend(format::check(&options.compact_bin, &files)?); + } + + findings.sort_by(|left, right| left.sort_key().cmp(&right.sort_key())); + Ok(Outcome { + findings, + files_checked: files.len(), + }) +} + +/// An explicit `--config` is a shareable preset, so glob discovery stays anchored at +/// `cwd`; a config found by walking upward anchors discovery at its own directory. +fn resolve_config( + options: &Options, + cwd: &Path, +) -> Result<(Config, Option, PathBuf), ConfigError> { + if let Some(path) = options.config_path.as_deref() { + return Ok((Config::load(path)?, Some(path.to_owned()), cwd.to_owned())); + } + + match discover_config(cwd) { + Some(path) => { + let base = path.parent().unwrap_or(cwd).to_owned(); + Ok((Config::load(&path)?, Some(path), base)) + } + None => Ok((Config::default(), None, cwd.to_owned())), + } +} + +/// Paths under the working directory print relative to it; anything else prints as is. +fn display_path(path: &Path, cwd: &Path) -> PathBuf { + path.strip_prefix(cwd).unwrap_or(path).to_owned() +} diff --git a/crates/compact-lint/src/config.rs b/crates/compact-lint/src/config.rs new file mode 100644 index 00000000..0d7ae2ba --- /dev/null +++ b/crates/compact-lint/src/config.rs @@ -0,0 +1,305 @@ +//! `compact-lint.toml`: discovery, parsing, and the built-in defaults. + +use std::path::{Path, PathBuf}; + +use globset::{Glob, GlobSet, GlobSetBuilder}; +use serde::Deserialize; +use thiserror::Error; + +use crate::doc::Tag; +use crate::model::DeclKind; + +/// The config file name searched for upward from the current directory. +pub const CONFIG_FILE_NAME: &str = "compact-lint.toml"; + +/// The only schema version this build understands. +pub const SUPPORTED_VERSION: u32 = 1; + +#[derive(Debug, Error)] +pub enum ConfigError { + #[error("cannot read config {path}")] + Read { + path: PathBuf, + #[source] + source: std::io::Error, + }, + #[error("cannot parse config {path}")] + Parse { + path: PathBuf, + #[source] + source: toml::de::Error, + }, + #[error( + "config {path} is version {found}, but this build understands version {SUPPORTED_VERSION}" + )] + Version { path: PathBuf, found: u32 }, + #[error( + "config {path} lists tag {tag:?}; tags are spelled with their `@`, like `@description`" + )] + Tag { path: PathBuf, tag: String }, + #[error("config {path} has an invalid glob {pattern:?}")] + Glob { + path: PathBuf, + pattern: String, + #[source] + source: globset::Error, + }, +} + +/// How much of a kind needs documenting. +#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "lowercase")] +pub enum DocsPolicy { + /// Every declaration of the kind. + All, + /// Only declarations carrying the `export` token. + #[default] + Exported, + /// The kind is not checked for docs. + None, +} + +/// Per-kind requirements. +#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields, default)] +pub struct KindConfig { + pub docs: DocsPolicy, + pub tags: Vec, +} + +/// One table per checked declaration kind. +#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields, default)] +pub struct KindsConfig { + pub module: KindConfig, + pub circuit: KindConfig, + pub ledger: KindConfig, + pub witness: KindConfig, + pub constructor: KindConfig, + #[serde(rename = "struct")] + pub struct_: KindConfig, + #[serde(rename = "enum")] + pub enum_: KindConfig, + pub contract: KindConfig, + #[serde(rename = "type")] + pub type_: KindConfig, +} + +impl KindsConfig { + #[must_use] + pub fn get(&self, kind: DeclKind) -> &KindConfig { + match kind { + DeclKind::Module => &self.module, + DeclKind::Circuit => &self.circuit, + DeclKind::Ledger => &self.ledger, + DeclKind::Witness => &self.witness, + DeclKind::Constructor => &self.constructor, + DeclKind::Struct => &self.struct_, + DeclKind::Enum => &self.enum_, + DeclKind::Contract => &self.contract, + DeclKind::Type => &self.type_, + } + } +} + +/// The circuit constraints annotation. +#[derive(Clone, Debug, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields, default)] +pub struct ConstraintsConfig { + pub tag: Tag, +} + +impl Default for ConstraintsConfig { + fn default() -> Self { + Self { + tag: Tag::new("@constraints"), + } + } +} + +/// Tags no doc comment may carry. +#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields, default)] +pub struct TagsConfig { + pub forbid: Vec, +} + +/// A parsed `compact-lint.toml`, or the built-in defaults when no file was found. +#[derive(Clone, Debug, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields, default)] +pub struct Config { + pub version: u32, + pub include: Vec, + pub exclude: Vec, + pub constraints: ConstraintsConfig, + pub tags: TagsConfig, + pub kinds: KindsConfig, +} + +impl Default for Config { + fn default() -> Self { + Self { + version: SUPPORTED_VERSION, + include: vec!["**/*.compact".to_owned()], + exclude: Vec::new(), + constraints: ConstraintsConfig::default(), + tags: TagsConfig::default(), + kinds: KindsConfig::default(), + } + } +} + +impl Config { + /// Parses a config file and rejects a version this build does not implement. + /// # Errors + /// Returns an error when the file is unreadable, malformed, or a future version. + pub fn load(path: &Path) -> Result { + let text = std::fs::read_to_string(path).map_err(|source| ConfigError::Read { + path: path.to_owned(), + source, + })?; + + let config: Self = toml::from_str(&text).map_err(|source| ConfigError::Parse { + path: path.to_owned(), + source, + })?; + + if config.version != SUPPORTED_VERSION { + return Err(ConfigError::Version { + path: path.to_owned(), + found: config.version, + }); + } + + if let Some(tag) = config.tags().find(|tag| !tag.is_well_formed()) { + return Err(ConfigError::Tag { + path: path.to_owned(), + tag: tag.to_string(), + }); + } + + Ok(config) + } + + /// Every tag the config mentions: required per kind, forbidden, and the constraints tag. + fn tags(&self) -> impl Iterator { + let per_kind = [ + &self.kinds.module, + &self.kinds.circuit, + &self.kinds.ledger, + &self.kinds.witness, + &self.kinds.constructor, + &self.kinds.struct_, + &self.kinds.enum_, + &self.kinds.contract, + &self.kinds.type_, + ] + .into_iter() + .flat_map(|kind| kind.tags.iter()); + + per_kind + .chain(self.tags.forbid.iter()) + .chain(std::iter::once(&self.constraints.tag)) + } + + /// Compiles the `include` globs. + /// # Errors + /// Returns an error when a pattern is not a valid glob. + pub fn include_set(&self, path: &Path) -> Result { + glob_set(&self.include, path) + } + + /// Compiles the `exclude` globs; an empty set matches nothing. + /// # Errors + /// Returns an error when a pattern is not a valid glob. + pub fn exclude_set(&self, path: &Path) -> Result { + glob_set(&self.exclude, path) + } +} + +fn glob_set(patterns: &[String], path: &Path) -> Result { + let mut builder = GlobSetBuilder::new(); + for pattern in patterns { + let glob = Glob::new(pattern).map_err(|source| ConfigError::Glob { + path: path.to_owned(), + pattern: pattern.clone(), + source, + })?; + builder.add(glob); + } + builder.build().map_err(|source| ConfigError::Glob { + path: path.to_owned(), + pattern: String::new(), + source, + }) +} + +/// Walks up from `start` looking for `compact-lint.toml`. +#[must_use] +pub fn discover(start: &Path) -> Option { + for directory in start.ancestors() { + let candidate = directory.join(CONFIG_FILE_NAME); + if candidate.is_file() { + return Some(candidate); + } + } + None +} + +#[cfg(test)] +mod tests { + use super::{Config, DocsPolicy, SUPPORTED_VERSION}; + use crate::doc::Tag; + use crate::model::DeclKind; + + #[test] + fn defaults_require_docs_on_exported_declarations_only() { + let config = Config::default(); + + assert_eq!(config.version, SUPPORTED_VERSION); + assert_eq!(config.constraints.tag, Tag::new("@constraints")); + for kind in [DeclKind::Module, DeclKind::Circuit, DeclKind::Type] { + assert_eq!(config.kinds.get(kind).docs, DocsPolicy::Exported); + assert!(config.kinds.get(kind).tags.is_empty()); + } + } + + #[test] + fn omitted_tables_fall_back_to_defaults() { + let config: Config = toml::from_str("version = 1\n[kinds.witness]\ndocs = \"all\"\n") + .expect("the snippet is valid config"); + + assert_eq!(config.kinds.witness.docs, DocsPolicy::All); + assert_eq!(config.kinds.circuit.docs, DocsPolicy::Exported); + assert_eq!(config.include, ["**/*.compact"]); + } + + #[test] + fn an_unknown_key_is_rejected() { + let error = toml::from_str::("verison = 1\n").expect_err("the key is misspelled"); + + assert!(error.to_string().contains("verison"), "{error}"); + } + + #[test] + fn a_tag_without_its_at_sign_is_rejected() { + let dir = std::env::temp_dir().join(format!("compact-lint-config-{}", std::process::id())); + std::fs::create_dir_all(&dir).expect("the temp dir is writable"); + let path = dir.join("compact-lint.toml"); + std::fs::write(&path, "[kinds.circuit]\ntags = [\"description\"]\n") + .expect("the config is writable"); + + let error = Config::load(&path).expect_err("the tag lacks its @"); + + assert!(error.to_string().contains("\"description\""), "{error}"); + std::fs::remove_dir_all(&dir).expect("the temp dir is removable"); + } + + #[test] + fn an_unknown_kind_is_rejected() { + let error = + toml::from_str::("[kinds.circiut]\n").expect_err("the kind is misspelled"); + + assert!(error.to_string().contains("circiut"), "{error}"); + } +} diff --git a/crates/compact-lint/src/discover.rs b/crates/compact-lint/src/discover.rs new file mode 100644 index 00000000..f647c9f1 --- /dev/null +++ b/crates/compact-lint/src/discover.rs @@ -0,0 +1,114 @@ +//! Turning CLI paths and config globs into the list of files to check. + +use std::path::{Path, PathBuf}; + +use globset::GlobSet; +use thiserror::Error; +use walkdir::WalkDir; + +/// Directories that never hold first-party Compact sources. +const SKIPPED_DIRS: [&str; 5] = ["node_modules", "target", "dist", "build", ".git"]; + +const COMPACT_EXTENSION: &str = "compact"; + +#[derive(Debug, Error)] +pub enum DiscoverError { + #[error("cannot walk {path}")] + Walk { + path: PathBuf, + #[source] + source: walkdir::Error, + }, + #[error("path {0} does not exist")] + Missing(PathBuf), +} + +/// Collects the `.compact` files under the given paths. +/// +/// A path named on the command line is always checked, even when `exclude` matches +/// it; files found by walking a directory are filtered by `exclude`. +/// # Errors +/// Returns an error when a path does not exist or a directory cannot be walked. +pub fn from_paths( + paths: &[PathBuf], + base: &Path, + exclude: &GlobSet, +) -> Result, DiscoverError> { + let mut files = Vec::new(); + + for path in paths { + if path.is_file() { + files.push(path.clone()); + } else if path.is_dir() { + walk(path, base, exclude, None, &mut files)?; + } else { + return Err(DiscoverError::Missing(path.clone())); + } + } + + Ok(sorted(files)) +} + +/// Collects the `.compact` files under `base` that `include` matches and `exclude` does not. +/// # Errors +/// Returns an error when `base` cannot be walked. +pub fn from_globs( + base: &Path, + include: &GlobSet, + exclude: &GlobSet, +) -> Result, DiscoverError> { + let mut files = Vec::new(); + walk(base, base, exclude, Some(include), &mut files)?; + Ok(sorted(files)) +} + +fn walk( + root: &Path, + base: &Path, + exclude: &GlobSet, + include: Option<&GlobSet>, + out: &mut Vec, +) -> Result<(), DiscoverError> { + let walker = WalkDir::new(root) + .follow_links(false) + .into_iter() + .filter_entry(|entry| entry.depth() == 0 || !is_skipped_dir(entry.file_name())); + + for entry in walker { + let entry = entry.map_err(|source| DiscoverError::Walk { + path: root.to_owned(), + source, + })?; + + if !entry.file_type().is_file() { + continue; + } + + let path = entry.path(); + if path + .extension() + .is_none_or(|extension| extension != COMPACT_EXTENSION) + { + continue; + } + + let relative = path.strip_prefix(base).unwrap_or(path); + if include.is_some_and(|set| !set.is_match(relative)) || exclude.is_match(relative) { + continue; + } + + out.push(path.to_owned()); + } + + Ok(()) +} + +fn is_skipped_dir(name: &std::ffi::OsStr) -> bool { + SKIPPED_DIRS.iter().any(|skipped| name == *skipped) +} + +fn sorted(mut files: Vec) -> Vec { + files.sort(); + files.dedup(); + files +} diff --git a/crates/compact-lint/src/doc.rs b/crates/compact-lint/src/doc.rs new file mode 100644 index 00000000..685007f1 --- /dev/null +++ b/crates/compact-lint/src/doc.rs @@ -0,0 +1,211 @@ +//! Parsing of `/** … */` doc comments into an ordered tag list. + +use std::fmt; + +use serde::Deserialize; + +/// A doc-comment tag name, stored with its leading `@` (`@description`). +#[derive(Clone, Debug, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[serde(transparent)] +pub struct Tag(String); + +impl Tag { + pub fn new(name: impl Into) -> Self { + Self(name.into()) + } + + #[must_use] + pub fn as_str(&self) -> &str { + &self.0 + } + + /// `@` followed by at least one ASCII letter, the same shape the parser recognises. + #[must_use] + pub fn is_well_formed(&self) -> bool { + self.0.strip_prefix('@').is_some_and(|name| { + !name.is_empty() && name.bytes().all(|byte| byte.is_ascii_alphabetic()) + }) + } +} + +impl fmt::Display for Tag { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(&self.0) + } +} + +/// One tag occurrence: its name, its value, and where it sits inside the comment. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct TagOccurrence { + pub tag: Tag, + pub value: String, + /// 0-based line index inside the doc comment, counted from the `/**` line. + pub line_offset: usize, + /// 0-based byte offset of the `@` in its line; on the first line, counted after `/**`. + pub column_offset: usize, +} + +/// A parsed doc comment. Repeated tags (`@param`) are kept in source order. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct DocComment { + tags: Vec, +} + +impl DocComment { + /// Parses the raw `/** … */` text, stripping the delimiters and the ` * ` gutter. + #[must_use] + pub fn parse(raw: &str) -> Self { + let opened = raw.strip_prefix("/**").unwrap_or(raw); + let inner = opened.strip_suffix("*/").unwrap_or(opened); + + let mut tags: Vec = Vec::new(); + let mut open: Option = None; + + for (line_offset, line) in inner.lines().enumerate() { + let content = strip_gutter(line).trim(); + + if content.is_empty() { + open = None; + continue; + } + + if let Some((tag, value)) = split_tag(content) { + tags.push(TagOccurrence { + tag, + value: value.to_owned(), + line_offset, + column_offset: line.find('@').unwrap_or(0), + }); + open = Some(tags.len() - 1); + continue; + } + + // A non-blank, non-tag line continues the tag above it. + if let Some(index) = open + && let Some(occurrence) = tags.get_mut(index) + { + if !occurrence.value.is_empty() { + occurrence.value.push('\n'); + } + occurrence.value.push_str(content); + } + } + + Self { tags } + } + + /// Every tag occurrence, in source order. + #[must_use] + pub fn tags(&self) -> &[TagOccurrence] { + &self.tags + } + + #[must_use] + pub fn has(&self, tag: &Tag) -> bool { + self.tags.iter().any(|occurrence| &occurrence.tag == tag) + } + + /// The first occurrence of `tag`, which is the one every rule reads. + #[must_use] + pub fn first(&self, tag: &Tag) -> Option<&TagOccurrence> { + self.tags.iter().find(|occurrence| &occurrence.tag == tag) + } + + /// The value of the first occurrence of `tag`. + #[must_use] + pub fn value(&self, tag: &Tag) -> Option<&str> { + self.first(tag).map(|occurrence| occurrence.value.as_str()) + } +} + +/// Removes the leading whitespace, one `*`, and one following space from a comment line. +fn strip_gutter(line: &str) -> &str { + let trimmed = line.trim_start(); + match trimmed.strip_prefix('*') { + Some(rest) => rest.strip_prefix(' ').unwrap_or(rest), + None => trimmed, + } +} + +/// A tag line starts with `@` followed by at least one ASCII letter. +fn split_tag(content: &str) -> Option<(Tag, &str)> { + let rest = content.strip_prefix('@')?; + let name_len = rest + .find(|character: char| !character.is_ascii_alphabetic()) + .unwrap_or(rest.len()); + if name_len == 0 { + return None; + } + + let (name, value) = rest.split_at(name_len); + Some((Tag::new(format!("@{name}")), value.trim())) +} + +#[cfg(test)] +mod tests { + use super::{DocComment, Tag}; + + #[test] + fn gutter_and_delimiters_are_stripped() { + let doc = DocComment::parse("/**\n * @description Adds two numbers.\n */"); + + assert_eq!(doc.tags().len(), 1); + assert_eq!(doc.tags()[0].tag, Tag::new("@description")); + assert_eq!(doc.tags()[0].value, "Adds two numbers."); + assert_eq!(doc.tags()[0].line_offset, 1); + assert_eq!(doc.tags()[0].column_offset, 3); + } + + #[test] + fn a_blank_line_ends_a_value() { + let doc = DocComment::parse("/**\n * @notice first\n *\n * loose prose\n */"); + + assert_eq!(doc.value(&Tag::new("@notice")), Some("first")); + } + + #[test] + fn a_non_tag_line_continues_the_tag_above_it() { + let doc = DocComment::parse("/**\n * @notice first\n * second\n */"); + + assert_eq!(doc.value(&Tag::new("@notice")), Some("first\nsecond")); + } + + #[test] + fn repeated_tags_keep_source_order() { + let doc = DocComment::parse( + "/**\n * @param {Uint<8>} a - left\n * @param {Uint<8>} b - right\n */", + ); + + let params: Vec<&str> = doc + .tags() + .iter() + .filter(|occurrence| occurrence.tag == Tag::new("@param")) + .map(|occurrence| occurrence.value.as_str()) + .collect(); + assert_eq!(params, ["{Uint<8>} a - left", "{Uint<8>} b - right"]); + } + + #[test] + fn return_and_returns_are_distinct_tags() { + let doc = DocComment::parse("/**\n * @returns The sum.\n */"); + + assert!(doc.has(&Tag::new("@returns"))); + assert!(!doc.has(&Tag::new("@return"))); + } + + #[test] + fn an_at_sign_without_letters_is_not_a_tag() { + let doc = DocComment::parse("/**\n * @1234 not a tag\n * mail@example.com\n */"); + + assert!(doc.tags().is_empty()); + } + + #[test] + fn a_single_line_comment_parses() { + let doc = DocComment::parse("/** @description One liner. */"); + + assert_eq!(doc.value(&Tag::new("@description")), Some("One liner.")); + assert_eq!(doc.tags()[0].line_offset, 0); + assert_eq!(doc.tags()[0].column_offset, 1); + } +} diff --git a/crates/compact-lint/src/format.rs b/crates/compact-lint/src/format.rs new file mode 100644 index 00000000..d3a0c46a --- /dev/null +++ b/crates/compact-lint/src/format.rs @@ -0,0 +1,156 @@ +//! The optional `compact format --check` pass. + +use std::ffi::OsStr; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use thiserror::Error; + +use crate::report::{Finding, Position, RuleId}; + +/// Environment override for the `compact` binary; the `--compact-bin` flag wins over it. +pub const COMPACT_BIN_ENV: &str = "COMPACT_LINT_COMPACT_BIN"; + +/// The default binary name, resolved through `PATH`. +pub const DEFAULT_COMPACT_BIN: &str = "compact"; + +pub const MESSAGE: &str = "not formatted; run `compact format`"; + +#[derive(Debug, Error)] +pub enum FormatError { + #[error("cannot run `{binary}`; pass --no-format to skip the format check")] + BinaryMissing { binary: String }, + #[error("cannot run `{binary}`")] + Spawn { + binary: String, + #[source] + source: std::io::Error, + }, +} + +/// Runs `compact format --check` once over every file and maps its report to findings. +/// +/// The formatter writes one `:` line per unformatted file to stderr, followed by +/// an indented diff. An output that holds no such line yields one finding on the first +/// checked file carrying the formatter's own first line. +/// # Errors +/// Returns an error when the `compact` binary is missing or cannot be spawned. +pub fn check(binary: &OsStr, files: &[PathBuf]) -> Result, FormatError> { + if files.is_empty() { + return Ok(Vec::new()); + } + + let output = Command::new(binary) + .arg("format") + .arg("--check") + .args(files) + .output() + .map_err(|source| { + let binary = binary.to_string_lossy().into_owned(); + if source.kind() == std::io::ErrorKind::NotFound { + FormatError::BinaryMissing { binary } + } else { + FormatError::Spawn { binary, source } + } + })?; + + if output.status.success() { + return Ok(Vec::new()); + } + + let stderr = String::from_utf8_lossy(&output.stderr); + let stdout = String::from_utf8_lossy(&output.stdout); + let reported: Vec<&str> = reported_paths(&stderr) + .chain(reported_paths(&stdout)) + .collect(); + + if reported.is_empty() { + let raw = first_line(&stderr) + .or_else(|| first_line(&stdout)) + .unwrap_or("compact format --check failed"); + return Ok(vec![Finding::new( + files[0].clone(), + Position::file_start(), + RuleId::FORMAT, + raw.to_owned(), + )]); + } + + Ok(reported + .into_iter() + .map(|path| { + Finding::new( + resolve(path, files), + Position::file_start(), + RuleId::FORMAT, + MESSAGE.to_owned(), + ) + }) + .collect()) +} + +/// Unformatted files are announced as a flush-left `:` line. +fn reported_paths(output: &str) -> impl Iterator { + output.lines().filter_map(|line| { + let path = line.strip_suffix(':')?; + (!path.is_empty() && !path.starts_with(char::is_whitespace) && path.ends_with(".compact")) + .then_some(path) + }) +} + +/// Prefers the path spelling the caller passed in, so output stays consistent. +/// Matching is by whole path components, so `Token.compact` never claims `NativeToken.compact`. +fn resolve(reported: &str, files: &[PathBuf]) -> PathBuf { + let reported = Path::new(reported); + files + .iter() + .find(|file| reported.ends_with(file) || file.ends_with(reported)) + .cloned() + .unwrap_or_else(|| reported.to_owned()) +} + +fn first_line(output: &str) -> Option<&str> { + output.lines().map(str::trim).find(|line| !line.is_empty()) +} + +#[cfg(test)] +mod tests { + use super::{reported_paths, resolve}; + use std::path::PathBuf; + + const SAMPLE: &str = "/tmp/bad.compact:\n 18 | export ledger round: Counter;\n- 21 | - round.increment(1);\n+ 21 | + round.increment(1);\n\nError: formatting failed\n"; + + #[test] + fn flush_left_path_lines_become_findings() { + let paths: Vec<&str> = reported_paths(SAMPLE).collect(); + + assert_eq!(paths, ["/tmp/bad.compact"]); + } + + #[test] + fn indented_diff_lines_are_not_paths() { + let paths: Vec<&str> = reported_paths(" a.compact:\n\ttrailing:\n").collect(); + + assert!(paths.is_empty()); + } + + #[test] + fn an_absolute_report_maps_back_to_the_relative_path_passed_in() { + let files = [PathBuf::from("contracts/src/Token.compact")]; + + assert_eq!( + resolve("/work/contracts/src/Token.compact", &files), + PathBuf::from("contracts/src/Token.compact") + ); + } + + #[test] + fn a_shorter_file_name_with_the_same_suffix_is_not_a_match() { + let files = [PathBuf::from("Token.compact")]; + + assert_eq!( + resolve("/work/NativeToken.compact", &files), + PathBuf::from("/work/NativeToken.compact") + ); + } +} diff --git a/crates/compact-lint/src/lib.rs b/crates/compact-lint/src/lib.rs new file mode 100644 index 00000000..fdaf6e9d --- /dev/null +++ b/crates/compact-lint/src/lib.rs @@ -0,0 +1,16 @@ +//! Doc-comment linter for Compact sources. +//! +//! The crate parses `.compact` files with the bundled tree-sitter grammar, matches each +//! declaration against the per-kind doc-comment template in `compact-lint.toml`, and +//! reports one [`report::Finding`] per violation. + +#![forbid(unsafe_code)] + +pub mod check; +pub mod config; +pub mod discover; +pub mod doc; +pub mod format; +pub mod model; +pub mod report; +pub mod rules; diff --git a/crates/compact-lint/src/main.rs b/crates/compact-lint/src/main.rs new file mode 100644 index 00000000..dc4d3640 --- /dev/null +++ b/crates/compact-lint/src/main.rs @@ -0,0 +1,114 @@ +//! `compact-lint` command line entry point. + +#![forbid(unsafe_code)] + +use std::ffi::OsString; +use std::io::Write; +use std::path::PathBuf; +use std::process::ExitCode; + +use anyhow::{Context, Result}; +use clap::{Parser, Subcommand}; + +use compact_lint::check::{self, Options, Outcome}; +use compact_lint::format::{COMPACT_BIN_ENV, DEFAULT_COMPACT_BIN}; + +/// Exit code for a run that produced findings. +const EXIT_FINDINGS: u8 = 1; + +/// Exit code for a usage, config, IO or parser error. +const EXIT_ERROR: u8 = 2; + +#[derive(Debug, Parser)] +#[command( + name = "compact-lint", + version, + about = "Doc-comment linter for Compact sources" +)] +struct Cli { + #[command(subcommand)] + command: Command, +} + +#[derive(Debug, Subcommand)] +enum Command { + /// Check doc comments against the per-kind templates in compact-lint.toml. + Check(CheckArgs), +} + +#[derive(Debug, clap::Args)] +struct CheckArgs { + /// Files or directories to check; defaults to the config's include globs. + paths: Vec, + + /// Config file to use instead of searching upward for compact-lint.toml. + #[arg(long, value_name = "FILE")] + config: Option, + + /// Report `k=?` / `rows=?` placeholders in the constraints tag. + #[arg(long)] + strict: bool, + + /// Skip the `compact format --check` pass. + #[arg(long)] + no_format: bool, + + /// Path to the `compact` binary. + #[arg(long, value_name = "PATH", env = COMPACT_BIN_ENV)] + compact_bin: Option, +} + +fn main() -> ExitCode { + match run() { + Ok(code) => code, + Err(error) => { + report_error(&error); + ExitCode::from(EXIT_ERROR) + } + } +} + +fn run() -> Result { + let cli = Cli::parse(); + let Command::Check(args) = cli.command; + + let cwd = std::env::current_dir().context("reading the current directory")?; + let options = Options { + paths: args.paths, + config_path: args.config, + strict: args.strict, + no_format: args.no_format, + compact_bin: args + .compact_bin + .unwrap_or_else(|| OsString::from(DEFAULT_COMPACT_BIN)), + }; + + let outcome = check::run(&options, &cwd).context("running the check")?; + emit(&outcome).context("writing the report")?; + + Ok(if outcome.findings.is_empty() { + ExitCode::SUCCESS + } else { + ExitCode::from(EXIT_FINDINGS) + }) +} + +fn emit(outcome: &Outcome) -> std::io::Result<()> { + let stdout = std::io::stdout(); + let mut out = stdout.lock(); + for finding in &outcome.findings { + writeln!(out, "{finding}")?; + } + out.flush()?; + + eprintln!("{}", outcome.summary()); + Ok(()) +} + +/// Prints the error and every source under it, one cause per line. +fn report_error(error: &anyhow::Error) { + eprintln!("compact-lint: {error}"); + for cause in error.chain().skip(1) { + eprintln!(" caused by: {cause}"); + } +} diff --git a/crates/compact-lint/src/model.rs b/crates/compact-lint/src/model.rs new file mode 100644 index 00000000..968eee81 --- /dev/null +++ b/crates/compact-lint/src/model.rs @@ -0,0 +1,177 @@ +//! Declarations the linter checks, lifted out of the tree-sitter tree. + +use std::fmt; + +use tree_sitter::Node; + +use crate::doc::{DocComment, TagOccurrence}; +use crate::report::Position; + +/// The declaration kinds the linter has rules for. +/// +/// `pragma`, `include`, `import`, `export { … }` and `contract implements` are +/// never checked, so they have no variant here. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum DeclKind { + Module, + Circuit, + Ledger, + Witness, + Constructor, + Struct, + Enum, + Contract, + Type, +} + +impl DeclKind { + /// Maps a tree-sitter node kind, returning `None` for unchecked declarations. + #[must_use] + pub fn from_node_kind(node_kind: &str) -> Option { + match node_kind { + "module_declaration" => Some(Self::Module), + "circuit_declaration" => Some(Self::Circuit), + "ledger_declaration" => Some(Self::Ledger), + "witness_declaration" => Some(Self::Witness), + "constructor_declaration" => Some(Self::Constructor), + "struct_declaration" => Some(Self::Struct), + "enum_declaration" => Some(Self::Enum), + "contract_declaration" => Some(Self::Contract), + "type_declaration" => Some(Self::Type), + _ => None, + } + } + + /// The name used in config keys and messages. + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::Module => "module", + Self::Circuit => "circuit", + Self::Ledger => "ledger", + Self::Witness => "witness", + Self::Constructor => "constructor", + Self::Struct => "struct", + Self::Enum => "enum", + Self::Contract => "contract", + Self::Type => "type", + } + } +} + +impl fmt::Display for DeclKind { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(self.as_str()) + } +} + +/// One declaration with the facts the rules need. +#[derive(Clone, Debug)] +pub struct Declaration { + pub kind: DeclKind, + /// The `name` field; `constructor` has none. + pub name: Option, + /// The declaration carries the `export` token itself; nesting never grants it. + pub exported: bool, + pub pure: bool, + pub position: Position, + /// The doc comment immediately preceding the declaration, if one attaches. + pub doc: Option, +} + +/// A doc comment bound to a declaration, with the source line it starts on. +#[derive(Clone, Debug)] +pub struct AttachedDoc { + pub comment: DocComment, + /// 0-based row of the `/**` line, for turning a tag's offset into a position. + pub start_row: usize, + pub start_column: usize, +} + +impl AttachedDoc { + /// The position of a tag's `@`; a first-line offset is counted after the `/**`. + #[must_use] + pub const fn tag_position(&self, occurrence: &TagOccurrence) -> Position { + let column = if occurrence.line_offset == 0 { + self.start_column + "/**".len() + occurrence.column_offset + } else { + occurrence.column_offset + }; + Position::from_zero_based(self.start_row + occurrence.line_offset, column) + } +} + +/// Collects every checked declaration, descending into module bodies. +#[must_use] +pub fn declarations(root: Node<'_>, source: &str) -> Vec { + let mut found = Vec::new(); + collect(root, source, &mut found); + found +} + +fn collect(parent: Node<'_>, source: &str, out: &mut Vec) { + let mut cursor = parent.walk(); + for node in parent.named_children(&mut cursor) { + let Some(kind) = DeclKind::from_node_kind(node.kind()) else { + continue; + }; + + out.push(declaration(kind, node, source)); + + // Only modules nest; every other body is an opaque token run. + if kind == DeclKind::Module + && let Some(body) = node.child_by_field_name("body") + { + collect(body, source, out); + } + } +} + +fn declaration(kind: DeclKind, node: Node<'_>, source: &str) -> Declaration { + let mut cursor = node.walk(); + let mut exported = false; + let mut pure = false; + for child in node.children(&mut cursor) { + match child.kind() { + "export" => exported = true, + "pure" => pure = true, + _ => {} + } + } + + let name = node + .child_by_field_name("name") + .and_then(|name| text(name, source)) + .map(str::to_owned); + + let start = node.start_position(); + + Declaration { + kind, + name, + exported, + pure, + position: Position::from_zero_based(start.row, start.column), + doc: attached_doc(node, source), + } +} + +/// A doc comment attaches only as the immediately preceding named sibling; a line +/// or block comment in between breaks the attachment. +fn attached_doc(node: Node<'_>, source: &str) -> Option { + let previous = node.prev_named_sibling()?; + if previous.kind() != "doc_comment" { + return None; + } + + let start = previous.start_position(); + Some(AttachedDoc { + comment: DocComment::parse(text(previous, source)?), + start_row: start.row, + start_column: start.column, + }) +} + +fn text<'a>(node: Node<'_>, source: &'a str) -> Option<&'a str> { + source.get(node.start_byte()..node.end_byte()) +} diff --git a/crates/compact-lint/src/report.rs b/crates/compact-lint/src/report.rs new file mode 100644 index 00000000..b2d9f172 --- /dev/null +++ b/crates/compact-lint/src/report.rs @@ -0,0 +1,142 @@ +//! Findings and the one-line `path:line:col: rule: message` rendering. + +use std::fmt; +use std::path::{Path, PathBuf}; + +/// A lint rule's stable identifier, as printed in the output and matched by CI greps. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct RuleId(&'static str); + +impl RuleId { + pub const MISSING_DOC: Self = Self("missing-doc"); + pub const MISSING_TAG: Self = Self("missing-tag"); + pub const FORBIDDEN_TAG: Self = Self("forbidden-tag"); + pub const MODULE_NAME: Self = Self("module-name"); + pub const MISSING_CONSTRAINTS: Self = Self("missing-constraints"); + pub const CONSTRAINTS_FORMAT: Self = Self("constraints-format"); + pub const CONSTRAINTS_PLACEHOLDER: Self = Self("constraints-placeholder"); + pub const PARSE: Self = Self("parse"); + pub const FORMAT: Self = Self("format"); + + /// Every rule this build can emit, in the order the README lists them. + pub const ALL: [Self; 9] = [ + Self::MISSING_DOC, + Self::MISSING_TAG, + Self::FORBIDDEN_TAG, + Self::MODULE_NAME, + Self::MISSING_CONSTRAINTS, + Self::CONSTRAINTS_FORMAT, + Self::CONSTRAINTS_PLACEHOLDER, + Self::PARSE, + Self::FORMAT, + ]; + + #[must_use] + pub const fn as_str(self) -> &'static str { + self.0 + } +} + +impl fmt::Display for RuleId { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(self.0) + } +} + +/// A 1-based source position; column 1 is the first byte of a line. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct Position { + pub line: usize, + pub column: usize, +} + +impl Position { + /// Converts a tree-sitter 0-based row/column pair. + #[must_use] + pub const fn from_zero_based(row: usize, column: usize) -> Self { + Self { + line: row + 1, + column: column + 1, + } + } + + /// The start of a file, used by whole-file findings. + #[must_use] + pub const fn file_start() -> Self { + Self { line: 1, column: 1 } + } +} + +/// One lint violation at one source position. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Finding { + pub path: PathBuf, + pub position: Position, + pub rule: RuleId, + pub message: String, +} + +impl Finding { + pub fn new( + path: impl Into, + position: Position, + rule: RuleId, + message: String, + ) -> Self { + Self { + path: path.into(), + position, + rule, + message, + } + } + + /// Sorts findings by file, then position, then rule, so output is stable across runs. + #[must_use] + pub fn sort_key(&self) -> (&Path, Position, RuleId) { + (self.path.as_path(), self.position, self.rule) + } +} + +impl fmt::Display for Finding { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + formatter, + "{}:{}:{}: {}: {}", + self.path.display(), + self.position.line, + self.position.column, + self.rule, + self.message + ) + } +} + +#[cfg(test)] +mod tests { + use super::{Finding, Position, RuleId}; + + #[test] + fn finding_renders_as_path_line_col_rule_message() { + let finding = Finding::new( + "contracts/src/access/Ownable.compact", + Position::from_zero_based(41, 0), + RuleId::MISSING_DOC, + "circuit `assertOnlyOwner` has no doc comment".to_owned(), + ); + + assert_eq!( + finding.to_string(), + "contracts/src/access/Ownable.compact:42:1: missing-doc: circuit `assertOnlyOwner` has no doc comment" + ); + } + + #[test] + fn rule_ids_are_unique() { + let mut ids: Vec<&str> = RuleId::ALL.iter().map(|rule| rule.as_str()).collect(); + ids.sort_unstable(); + let count = ids.len(); + ids.dedup(); + assert_eq!(ids.len(), count); + } +} diff --git a/crates/compact-lint/src/rules.rs b/crates/compact-lint/src/rules.rs new file mode 100644 index 00000000..9bc0bf7a --- /dev/null +++ b/crates/compact-lint/src/rules.rs @@ -0,0 +1,415 @@ +//! The doc-comment rules, run over one parsed file at a time. + +use std::path::{Path, PathBuf}; + +use thiserror::Error; +use tree_sitter::{Node, Parser}; + +use crate::config::{Config, DocsPolicy}; +use crate::doc::Tag; +use crate::model::{DeclKind, Declaration, declarations}; +use crate::report::{Finding, Position, RuleId}; + +#[derive(Debug, Error)] +pub enum LintError { + #[error("the bundled Compact grammar does not match the linked tree-sitter ABI")] + Language(#[source] tree_sitter::LanguageError), + #[error("tree-sitter returned no parse tree for {0}")] + NoTree(PathBuf), +} + +/// A reusable parser plus the rules that run over its trees. +pub struct Linter { + parser: Parser, +} + +impl Linter { + /// # Errors + /// Returns an error when the bundled grammar does not match the linked ABI. + pub fn new() -> Result { + let mut parser = Parser::new(); + parser + .set_language(&compact_tree_sitter::LANGUAGE.into()) + .map_err(LintError::Language)?; + Ok(Self { parser }) + } + + /// Checks one file. `display` is the path printed in findings. + /// + /// A tree holding an `ERROR` or `MISSING` node yields a single `parse` finding and + /// no doc findings, because declarations around the defect are not trustworthy. + /// # Errors + /// Returns an error when tree-sitter produces no tree for `source`. + pub fn check( + &mut self, + display: &Path, + source: &str, + config: &Config, + strict: bool, + ) -> Result, LintError> { + let tree = self + .parser + .parse(source, None) + .ok_or_else(|| LintError::NoTree(display.to_owned()))?; + let root = tree.root_node(); + + if let Some(defect) = first_defect(root) { + return Ok(vec![defect.finding(display)]); + } + + let mut findings = Vec::new(); + for declaration in declarations(root, source) { + check_declaration(&declaration, display, config, strict, &mut findings); + } + findings.sort_by(|left, right| left.sort_key().cmp(&right.sort_key())); + Ok(findings) + } +} + +struct Defect { + position: Position, + kind: String, + missing: bool, +} + +impl Defect { + fn finding(&self, display: &Path) -> Finding { + let message = if self.missing { + format!("parse error: missing {}", self.kind) + } else { + format!("parse error: unexpected {}", self.kind) + }; + Finding::new(display, self.position, RuleId::PARSE, message) + } +} + +/// The first `ERROR` or `MISSING` node in document order. +fn first_defect(node: Node<'_>) -> Option { + if node.is_error() || node.is_missing() { + let start = node.start_position(); + return Some(Defect { + position: Position::from_zero_based(start.row, start.column), + kind: node.kind().to_owned(), + missing: node.is_missing(), + }); + } + + if !node.has_error() { + return None; + } + + let mut cursor = node.walk(); + node.children(&mut cursor).find_map(first_defect) +} + +fn check_declaration( + declaration: &Declaration, + display: &Path, + config: &Config, + strict: bool, + findings: &mut Vec, +) { + let kind_config = config.kinds.get(declaration.kind); + let requires_docs = match kind_config.docs { + DocsPolicy::All => true, + DocsPolicy::Exported => declaration.exported, + DocsPolicy::None => false, + }; + + let Some(attached) = declaration.doc.as_ref() else { + if requires_docs { + findings.push(Finding::new( + display, + declaration.position, + RuleId::MISSING_DOC, + format!("{} has no doc comment", subject(declaration)), + )); + } + return; + }; + + // A forbidden tag is a finding wherever it appears, documented or not. + for forbidden in &config.tags.forbid { + for occurrence in attached.comment.tags() { + if &occurrence.tag == forbidden { + findings.push(Finding::new( + display, + attached.tag_position(occurrence), + RuleId::FORBIDDEN_TAG, + format!("forbidden tag {forbidden}"), + )); + } + } + } + + if declaration.kind == DeclKind::Module { + check_module_name(declaration, display, findings); + } + + if !requires_docs { + return; + } + + for required in &kind_config.tags { + if !attached.comment.has(required) { + findings.push(Finding::new( + display, + declaration.position, + RuleId::MISSING_TAG, + format!("{} doc comment has no {required}", subject(declaration)), + )); + } + } + + check_constraints(declaration, display, config, strict, findings); +} + +/// `@module ` must name the module it documents. +fn check_module_name(declaration: &Declaration, display: &Path, findings: &mut Vec) { + let tag = Tag::new("@module"); + let (Some(attached), Some(name)) = (declaration.doc.as_ref(), declaration.name.as_deref()) + else { + return; + }; + let Some(occurrence) = attached.comment.first(&tag) else { + return; + }; + + let documented = module_name(&occurrence.value); + if documented != name { + findings.push(Finding::new( + display, + attached.tag_position(occurrence), + RuleId::MODULE_NAME, + format!("@module names `{documented}`, but the module is `{name}`"), + )); + } +} + +/// The documented name is the first word, without generic arguments or trailing punctuation. +fn module_name(value: &str) -> &str { + let first = value.split_whitespace().next().unwrap_or_default(); + let without_generics = first.split('<').next().unwrap_or(first); + without_generics.trim_end_matches(['.', ',', ':', ';']) +} + +/// Exported non-pure circuits carry the constraints annotation. +fn check_constraints( + declaration: &Declaration, + display: &Path, + config: &Config, + strict: bool, + findings: &mut Vec, +) { + if declaration.kind != DeclKind::Circuit || !declaration.exported || declaration.pure { + return; + } + let Some(attached) = declaration.doc.as_ref() else { + return; + }; + let tag = &config.constraints.tag; + + let Some(occurrence) = attached.comment.first(tag) else { + findings.push(Finding::new( + display, + declaration.position, + RuleId::MISSING_CONSTRAINTS, + format!("{} doc comment has no {tag}", subject(declaration)), + )); + return; + }; + + // The annotation is one line; anything below it is prose, not part of the value. + let value = occurrence.value.lines().next().unwrap_or_default().trim(); + let position = attached.tag_position(occurrence); + + let Some(placeholders) = parse_constraints(value) else { + findings.push(Finding::new( + display, + position, + RuleId::CONSTRAINTS_FORMAT, + format!("{tag} value `{value}` is not `k=, rows=`"), + )); + return; + }; + + if strict && placeholders { + findings.push(Finding::new( + display, + position, + RuleId::CONSTRAINTS_PLACEHOLDER, + format!("{tag} value `{value}` still holds a placeholder"), + )); + } +} + +/// Matches `k=,*rows=`; returns whether either field is a `?` placeholder. +fn parse_constraints(value: &str) -> Option { + let rest = value.strip_prefix("k=")?; + let (k, rest) = rest.split_once(',')?; + let rows = rest.trim_start().strip_prefix("rows=")?; + + let k_placeholder = is_placeholder(k)?; + let rows_placeholder = is_placeholder(rows)?; + Some(k_placeholder || rows_placeholder) +} + +/// A constraints field is either a decimal count or a `?` placeholder. +fn is_placeholder(field: &str) -> Option { + match field { + "?" => Some(true), + digits if !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit()) => { + Some(false) + } + _ => None, + } +} + +/// The kind plus the backquoted name, or a bare kind when the declaration has no name. +fn subject(declaration: &Declaration) -> String { + match declaration.name.as_deref() { + Some(name) => format!("{} `{name}`", declaration.kind), + None => declaration.kind.to_string(), + } +} + +#[cfg(test)] +mod tests { + use super::{Linter, module_name, parse_constraints}; + use crate::config::{Config, DocsPolicy}; + use crate::doc::Tag; + use std::path::Path; + + fn findings(source: &str, config: &Config, strict: bool) -> Vec { + Linter::new() + .expect("the bundled grammar loads") + .check(Path::new("a.compact"), source, config, strict) + .expect("the source produced a tree") + .iter() + .map(ToString::to_string) + .collect() + } + + fn circuit_config() -> Config { + let mut config = Config::default(); + config.kinds.circuit.tags = vec![Tag::new("@description")]; + config + } + + #[test] + fn a_non_exported_circuit_inside_an_exported_module_needs_no_docs() { + let source = "/** @description M. */\nexport module M {\n circuit helper(): [] { }\n}\n"; + + assert!(findings(source, &Config::default(), false).is_empty()); + } + + #[test] + fn an_exported_module_without_a_doc_comment_is_reported() { + let source = "export module M {\n}\n"; + + assert_eq!( + findings(source, &Config::default(), false), + ["a.compact:1:1: missing-doc: module `M` has no doc comment"] + ); + } + + #[test] + fn a_line_comment_between_the_doc_and_the_declaration_breaks_attachment() { + let source = "/** @description M. */\n// a note\nexport module M {\n}\n"; + + assert_eq!( + findings(source, &Config::default(), false), + ["a.compact:3:1: missing-doc: module `M` has no doc comment"] + ); + } + + #[test] + fn a_pure_exported_circuit_needs_no_constraints() { + let source = "/** @description Adds. */\nexport pure circuit add(a: Uint<8>): Uint<8> { return a; }\n"; + + assert!(findings(source, &circuit_config(), false).is_empty()); + } + + #[test] + fn an_exported_circuit_without_constraints_is_reported() { + let source = + "/** @description Bumps. */\nexport circuit bump(): [] { count.increment(1); }\n"; + + assert_eq!( + findings(source, &circuit_config(), false), + ["a.compact:2:1: missing-constraints: circuit `bump` doc comment has no @constraints"] + ); + } + + #[test] + fn a_placeholder_is_a_finding_only_under_strict() { + let source = "/**\n * @description Bumps.\n * @constraints k=?, rows=?\n */\nexport circuit bump(): [] { }\n"; + let config = circuit_config(); + + assert!(findings(source, &config, false).is_empty()); + assert_eq!( + findings(source, &config, true), + [ + "a.compact:3:4: constraints-placeholder: @constraints value `k=?, rows=?` still holds a placeholder" + ] + ); + } + + #[test] + fn a_forbidden_tag_is_reported_even_where_docs_are_optional() { + let source = "/**\n * @return nothing\n */\ncircuit hidden(): [] { }\n"; + let mut config = Config::default(); + config.tags.forbid = vec![Tag::new("@return")]; + + assert_eq!( + findings(source, &config, false), + ["a.compact:2:4: forbidden-tag: forbidden tag @return"] + ); + } + + #[test] + fn a_witness_under_docs_all_is_checked_without_export() { + let source = "witness wit_secret(): Bytes<32>;\n"; + let mut config = Config::default(); + config.kinds.witness.docs = DocsPolicy::All; + + assert_eq!( + findings(source, &config, false), + ["a.compact:1:1: missing-doc: witness `wit_secret` has no doc comment"] + ); + } + + #[test] + fn a_parse_defect_suppresses_the_doc_rules() { + let source = "export module M {\nexport circuit\n"; + + let reported = findings(source, &Config::default(), false); + assert_eq!(reported.len(), 1, "{reported:?}"); + assert!(reported[0].contains("parse error"), "{reported:?}"); + } + + #[test] + fn the_constraints_tag_is_configurable() { + let source = "/**\n * @description Bumps.\n * @circuitInfo k=6, rows=28\n */\nexport circuit bump(): [] { }\n"; + let mut config = circuit_config(); + config.constraints.tag = Tag::new("@circuitInfo"); + + assert!(findings(source, &config, false).is_empty()); + } + + #[test] + fn constraints_accept_flexible_spacing_after_the_comma() { + assert_eq!(parse_constraints("k=10, rows=626"), Some(false)); + assert_eq!(parse_constraints("k=10,rows=626"), Some(false)); + assert_eq!(parse_constraints("k=?, rows=626"), Some(true)); + assert_eq!(parse_constraints("k=10, rows=626 (approx)"), None); + assert_eq!(parse_constraints("rows=626, k=10"), None); + } + + #[test] + fn a_documented_module_name_drops_generics_and_trailing_punctuation() { + assert_eq!(module_name("Signer"), "Signer"); + assert_eq!(module_name("Utils."), "Utils"); + assert_eq!(module_name("ShieldedToken (archived)"), "ShieldedToken"); + } +} diff --git a/crates/compact-lint/tests/check.rs b/crates/compact-lint/tests/check.rs new file mode 100644 index 00000000..452c09dc --- /dev/null +++ b/crates/compact-lint/tests/check.rs @@ -0,0 +1,172 @@ +//! `compact-lint check` end to end, one fixture case per rule. +//! +//! Every case runs with `--no-format`, because CI has no `compact` binary. + +use std::path::PathBuf; +use std::process::Command; + +use assert_cmd::prelude::*; + +/// Exit code for a run that produced findings. +const EXIT_FINDINGS: i32 = 1; + +/// Exit code for a usage, config, IO or parser error. +const EXIT_ERROR: i32 = 2; + +fn case(name: &str) -> PathBuf { + // The child reports its working directory resolved, so the expectation must be too. + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures") + .join(name) + .canonicalize() + .expect("the fixture case exists") +} + +fn binary() -> Command { + Command::cargo_bin("compact-lint").expect("the binary is built alongside this test") +} + +fn expected(name: &str) -> String { + std::fs::read_to_string(case(name).join("expected.txt")).expect("the case has an expectation") +} + +/// Runs `check` inside a case directory and returns its exit code and stdout. +fn run(name: &str, extra: &[&str]) -> (i32, String) { + let output = binary() + .current_dir(case(name)) + .args(["check", "--no-format"]) + .args(extra) + .output() + .expect("the binary ran"); + + ( + output.status.code().expect("the binary was not signalled"), + String::from_utf8(output.stdout).expect("the report is UTF-8"), + ) +} + +fn assert_case(name: &str, extra: &[&str], code: i32) { + let (actual_code, stdout) = run(name, extra); + + assert_eq!(stdout, expected(name), "stdout for case {name}"); + assert_eq!(actual_code, code, "exit code for case {name}"); +} + +#[test] +fn a_fully_documented_module_reports_nothing() { + assert_case("clean", &[], 0); +} + +#[test] +fn undocumented_declarations_and_detached_docs_report_missing_doc() { + assert_case("missing-doc", &[], EXIT_FINDINGS); +} + +#[test] +fn a_doc_comment_without_a_required_tag_reports_missing_tag() { + assert_case("missing-tag", &[], EXIT_FINDINGS); +} + +#[test] +fn a_forbidden_tag_reports_wherever_it_appears() { + assert_case("forbidden-tag", &[], EXIT_FINDINGS); +} + +#[test] +fn a_module_tag_naming_another_module_reports_module_name() { + assert_case("module-name", &[], EXIT_FINDINGS); +} + +#[test] +fn an_unannotated_exported_circuit_reports_missing_constraints() { + assert_case("missing-constraints", &[], EXIT_FINDINGS); +} + +#[test] +fn a_malformed_constraints_value_reports_constraints_format() { + assert_case("constraints-format", &[], EXIT_FINDINGS); +} + +#[test] +fn a_placeholder_reports_only_under_strict() { + let (code, stdout) = run("constraints-placeholder", &[]); + assert_eq!(stdout, ""); + assert_eq!(code, 0); + + assert_case("constraints-placeholder", &["--strict"], EXIT_FINDINGS); +} + +#[test] +fn a_broken_file_reports_parse_instead_of_crashing() { + assert_case("parse", &[], EXIT_FINDINGS); +} + +#[test] +fn an_explicit_path_replaces_the_include_globs() { + let output = binary() + .current_dir(case("missing-doc")) + .args(["check", "--no-format", "Gaps.compact"]) + .output() + .expect("the binary ran"); + + assert_eq!( + String::from_utf8(output.stdout).expect("the report is UTF-8"), + expected("missing-doc") + ); +} + +#[test] +fn an_explicit_config_anchors_discovery_at_the_working_directory() { + let config = case("clean").join("compact-lint.toml"); + let output = binary() + .current_dir(case("missing-doc")) + .args(["check", "--no-format", "--config"]) + .arg(&config) + .output() + .expect("the binary ran"); + + assert_eq!( + String::from_utf8(output.stdout).expect("the report is UTF-8"), + expected("missing-doc") + ); +} + +#[test] +fn a_missing_compact_binary_exits_two_and_names_the_escape_hatch() { + let output = binary() + .current_dir(case("clean")) + .args(["check", "--compact-bin", "compact-lint-no-such-binary"]) + .output() + .expect("the binary ran"); + + let stderr = String::from_utf8(output.stderr).expect("the error is UTF-8"); + assert_eq!(output.status.code(), Some(EXIT_ERROR), "{stderr}"); + assert!(stderr.contains("--no-format"), "{stderr}"); +} + +#[test] +fn an_unreadable_config_exits_two() { + let output = binary() + .current_dir(case("clean")) + .args(["check", "--no-format", "--config", "compact-lint.toml.nope"]) + .output() + .expect("the binary ran"); + + assert_eq!(output.status.code(), Some(EXIT_ERROR)); +} + +#[test] +fn the_summary_goes_to_stderr_and_the_findings_to_stdout() { + let output = binary() + .current_dir(case("module-name")) + .args(["check", "--no-format"]) + .output() + .expect("the binary ran"); + + let stderr = String::from_utf8(output.stderr).expect("the summary is UTF-8"); + assert_eq!(stderr.trim_end(), "1 findings in 1 files"); + assert!( + String::from_utf8_lossy(&output.stdout).contains("module-name"), + "the rule id belongs on stdout" + ); +} diff --git a/crates/compact-lint/tests/fixtures/clean/Clean.compact b/crates/compact-lint/tests/fixtures/clean/Clean.compact new file mode 100644 index 00000000..030f7857 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/clean/Clean.compact @@ -0,0 +1,56 @@ +pragma language_version >= 0.23.0; + +/** + * @module Clean + * @description A module that satisfies every rule. + */ +export module Clean { + import CompactStandardLibrary; + + /** + * @description Whether the module is initialized. + */ + export ledger _isInitialized: Boolean; + + /** + * @description The caller's secret key. + */ + witness wit_Secret(): Bytes<32>; + + /** + * @description A single counter reading. + */ + export struct Reading { + value: Uint<64> + } + + /** + * @description The directions a counter moves in. + */ + export enum Direction { + Up, + Down + } + + constructor() { + _isInitialized = false; + } + + /** + * @description Doubles its argument. + * @param {Uint<8>} value - The value to double. + * @returns {Uint<16>} The doubled value. + */ + export pure circuit double(value: Uint<8>): Uint<16> { + return value as Uint<16> * 2; + } + + /** + * @description Marks the module initialized. + * @constraints k=10, rows=626 + * @returns {[]} Empty tuple. + */ + export circuit initialize(): [] { + _isInitialized = true; + } +} diff --git a/crates/compact-lint/tests/fixtures/clean/compact-lint.toml b/crates/compact-lint/tests/fixtures/clean/compact-lint.toml new file mode 100644 index 00000000..0813e24c --- /dev/null +++ b/crates/compact-lint/tests/fixtures/clean/compact-lint.toml @@ -0,0 +1,27 @@ +version = 1 +include = ["**/*.compact"] + +[tags] +forbid = ["@return"] + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] + +[kinds.ledger] +tags = ["@description"] + +[kinds.witness] +docs = "all" +tags = ["@description"] + +[kinds.struct] +tags = ["@description"] + +[kinds.enum] +tags = ["@description"] + +[kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/clean/expected.txt b/crates/compact-lint/tests/fixtures/clean/expected.txt new file mode 100644 index 00000000..e69de29b diff --git a/crates/compact-lint/tests/fixtures/constraints-format/Malformed.compact b/crates/compact-lint/tests/fixtures/constraints-format/Malformed.compact new file mode 100644 index 00000000..9e2365ae --- /dev/null +++ b/crates/compact-lint/tests/fixtures/constraints-format/Malformed.compact @@ -0,0 +1,17 @@ +/** + * @module Malformed + * @description A module whose annotations do not parse. + */ +export module Malformed { + /** + * @description The comma is missing. + * @constraints k=10 rows=626 + */ + export circuit first(): [] { } + + /** + * @description The fields are the wrong way round. + * @constraints rows=626, k=10 + */ + export circuit second(): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/constraints-format/compact-lint.toml b/crates/compact-lint/tests/fixtures/constraints-format/compact-lint.toml new file mode 100644 index 00000000..0813e24c --- /dev/null +++ b/crates/compact-lint/tests/fixtures/constraints-format/compact-lint.toml @@ -0,0 +1,27 @@ +version = 1 +include = ["**/*.compact"] + +[tags] +forbid = ["@return"] + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] + +[kinds.ledger] +tags = ["@description"] + +[kinds.witness] +docs = "all" +tags = ["@description"] + +[kinds.struct] +tags = ["@description"] + +[kinds.enum] +tags = ["@description"] + +[kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/constraints-format/expected.txt b/crates/compact-lint/tests/fixtures/constraints-format/expected.txt new file mode 100644 index 00000000..a1b1ac88 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/constraints-format/expected.txt @@ -0,0 +1,2 @@ +Malformed.compact:8:6: constraints-format: @constraints value `k=10 rows=626` is not `k=, rows=` +Malformed.compact:14:6: constraints-format: @constraints value `rows=626, k=10` is not `k=, rows=` diff --git a/crates/compact-lint/tests/fixtures/constraints-placeholder/Unfilled.compact b/crates/compact-lint/tests/fixtures/constraints-placeholder/Unfilled.compact new file mode 100644 index 00000000..4b12883c --- /dev/null +++ b/crates/compact-lint/tests/fixtures/constraints-placeholder/Unfilled.compact @@ -0,0 +1,11 @@ +/** + * @module Unfilled + * @description A module whose annotation is still a placeholder. + */ +export module Unfilled { + /** + * @description Not measured yet. + * @constraints k=?, rows=? + */ + export circuit run(): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/constraints-placeholder/compact-lint.toml b/crates/compact-lint/tests/fixtures/constraints-placeholder/compact-lint.toml new file mode 100644 index 00000000..0813e24c --- /dev/null +++ b/crates/compact-lint/tests/fixtures/constraints-placeholder/compact-lint.toml @@ -0,0 +1,27 @@ +version = 1 +include = ["**/*.compact"] + +[tags] +forbid = ["@return"] + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] + +[kinds.ledger] +tags = ["@description"] + +[kinds.witness] +docs = "all" +tags = ["@description"] + +[kinds.struct] +tags = ["@description"] + +[kinds.enum] +tags = ["@description"] + +[kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/constraints-placeholder/expected.txt b/crates/compact-lint/tests/fixtures/constraints-placeholder/expected.txt new file mode 100644 index 00000000..ba3214ef --- /dev/null +++ b/crates/compact-lint/tests/fixtures/constraints-placeholder/expected.txt @@ -0,0 +1 @@ +Unfilled.compact:8:6: constraints-placeholder: @constraints value `k=?, rows=?` still holds a placeholder diff --git a/crates/compact-lint/tests/fixtures/forbidden-tag/Returns.compact b/crates/compact-lint/tests/fixtures/forbidden-tag/Returns.compact new file mode 100644 index 00000000..61836afc --- /dev/null +++ b/crates/compact-lint/tests/fixtures/forbidden-tag/Returns.compact @@ -0,0 +1,18 @@ +/** + * @module Returns + * @description A module that still uses the old return tag. + */ +export module Returns { + /** + * @description Does nothing. + * @constraints k=6, rows=28 + * @return {[]} - Empty tuple. + */ + export circuit run(): [] { } + + /** + * @description Not exported, so its docs are optional, but the tag is not. + * @return {[]} - Empty tuple. + */ + circuit helper(): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/forbidden-tag/compact-lint.toml b/crates/compact-lint/tests/fixtures/forbidden-tag/compact-lint.toml new file mode 100644 index 00000000..0813e24c --- /dev/null +++ b/crates/compact-lint/tests/fixtures/forbidden-tag/compact-lint.toml @@ -0,0 +1,27 @@ +version = 1 +include = ["**/*.compact"] + +[tags] +forbid = ["@return"] + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] + +[kinds.ledger] +tags = ["@description"] + +[kinds.witness] +docs = "all" +tags = ["@description"] + +[kinds.struct] +tags = ["@description"] + +[kinds.enum] +tags = ["@description"] + +[kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/forbidden-tag/expected.txt b/crates/compact-lint/tests/fixtures/forbidden-tag/expected.txt new file mode 100644 index 00000000..0edaa79e --- /dev/null +++ b/crates/compact-lint/tests/fixtures/forbidden-tag/expected.txt @@ -0,0 +1,2 @@ +Returns.compact:9:6: forbidden-tag: forbidden tag @return +Returns.compact:15:6: forbidden-tag: forbidden tag @return diff --git a/crates/compact-lint/tests/fixtures/missing-constraints/Unmeasured.compact b/crates/compact-lint/tests/fixtures/missing-constraints/Unmeasured.compact new file mode 100644 index 00000000..f8e0a628 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/missing-constraints/Unmeasured.compact @@ -0,0 +1,17 @@ +/** + * @module Unmeasured + * @description A module whose exported circuit is unmeasured. + */ +export module Unmeasured { + /** + * @description Writes to the ledger without an annotation. + */ + export circuit run(): [] { } + + /** + * @description Pure circuits are never annotated. + */ + export pure circuit double(value: Uint<8>): Uint<16> { + return value as Uint<16> * 2; + } +} diff --git a/crates/compact-lint/tests/fixtures/missing-constraints/compact-lint.toml b/crates/compact-lint/tests/fixtures/missing-constraints/compact-lint.toml new file mode 100644 index 00000000..0813e24c --- /dev/null +++ b/crates/compact-lint/tests/fixtures/missing-constraints/compact-lint.toml @@ -0,0 +1,27 @@ +version = 1 +include = ["**/*.compact"] + +[tags] +forbid = ["@return"] + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] + +[kinds.ledger] +tags = ["@description"] + +[kinds.witness] +docs = "all" +tags = ["@description"] + +[kinds.struct] +tags = ["@description"] + +[kinds.enum] +tags = ["@description"] + +[kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/missing-constraints/expected.txt b/crates/compact-lint/tests/fixtures/missing-constraints/expected.txt new file mode 100644 index 00000000..18ec6884 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/missing-constraints/expected.txt @@ -0,0 +1 @@ +Unmeasured.compact:9:3: missing-constraints: circuit `run` doc comment has no @constraints diff --git a/crates/compact-lint/tests/fixtures/missing-doc/Gaps.compact b/crates/compact-lint/tests/fixtures/missing-doc/Gaps.compact new file mode 100644 index 00000000..13a4d3e9 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/missing-doc/Gaps.compact @@ -0,0 +1,20 @@ +/** + * @module Gaps + * @description A module whose members are undocumented. + */ +export module Gaps { + export ledger _owner: Bytes<32>; + + export enum Kind { + One + } + + /** + * @description Detached by the line comment below it. + * @constraints k=6, rows=28 + */ + // The comment that breaks the attachment. + export circuit run(): [] { + _owner = default>; + } +} diff --git a/crates/compact-lint/tests/fixtures/missing-doc/compact-lint.toml b/crates/compact-lint/tests/fixtures/missing-doc/compact-lint.toml new file mode 100644 index 00000000..0813e24c --- /dev/null +++ b/crates/compact-lint/tests/fixtures/missing-doc/compact-lint.toml @@ -0,0 +1,27 @@ +version = 1 +include = ["**/*.compact"] + +[tags] +forbid = ["@return"] + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] + +[kinds.ledger] +tags = ["@description"] + +[kinds.witness] +docs = "all" +tags = ["@description"] + +[kinds.struct] +tags = ["@description"] + +[kinds.enum] +tags = ["@description"] + +[kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/missing-doc/expected.txt b/crates/compact-lint/tests/fixtures/missing-doc/expected.txt new file mode 100644 index 00000000..b3649c78 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/missing-doc/expected.txt @@ -0,0 +1,3 @@ +Gaps.compact:6:3: missing-doc: ledger `_owner` has no doc comment +Gaps.compact:8:3: missing-doc: enum `Kind` has no doc comment +Gaps.compact:17:3: missing-doc: circuit `run` has no doc comment diff --git a/crates/compact-lint/tests/fixtures/missing-tag/Untagged.compact b/crates/compact-lint/tests/fixtures/missing-tag/Untagged.compact new file mode 100644 index 00000000..98d81164 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/missing-tag/Untagged.compact @@ -0,0 +1,10 @@ +/** + * @module Untagged + */ +export module Untagged { + /** + * The module has no @description, and neither has this circuit. + * @constraints k=6, rows=28 + */ + export circuit run(): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/missing-tag/compact-lint.toml b/crates/compact-lint/tests/fixtures/missing-tag/compact-lint.toml new file mode 100644 index 00000000..0813e24c --- /dev/null +++ b/crates/compact-lint/tests/fixtures/missing-tag/compact-lint.toml @@ -0,0 +1,27 @@ +version = 1 +include = ["**/*.compact"] + +[tags] +forbid = ["@return"] + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] + +[kinds.ledger] +tags = ["@description"] + +[kinds.witness] +docs = "all" +tags = ["@description"] + +[kinds.struct] +tags = ["@description"] + +[kinds.enum] +tags = ["@description"] + +[kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/missing-tag/expected.txt b/crates/compact-lint/tests/fixtures/missing-tag/expected.txt new file mode 100644 index 00000000..9fb4a3b1 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/missing-tag/expected.txt @@ -0,0 +1,2 @@ +Untagged.compact:4:1: missing-tag: module `Untagged` doc comment has no @description +Untagged.compact:9:3: missing-tag: circuit `run` doc comment has no @description diff --git a/crates/compact-lint/tests/fixtures/module-name/Renamed.compact b/crates/compact-lint/tests/fixtures/module-name/Renamed.compact new file mode 100644 index 00000000..8ea00b64 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/module-name/Renamed.compact @@ -0,0 +1,6 @@ +/** + * @module Stale + * @description The tag still names the module's old name. + */ +export module Renamed { +} diff --git a/crates/compact-lint/tests/fixtures/module-name/compact-lint.toml b/crates/compact-lint/tests/fixtures/module-name/compact-lint.toml new file mode 100644 index 00000000..0813e24c --- /dev/null +++ b/crates/compact-lint/tests/fixtures/module-name/compact-lint.toml @@ -0,0 +1,27 @@ +version = 1 +include = ["**/*.compact"] + +[tags] +forbid = ["@return"] + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] + +[kinds.ledger] +tags = ["@description"] + +[kinds.witness] +docs = "all" +tags = ["@description"] + +[kinds.struct] +tags = ["@description"] + +[kinds.enum] +tags = ["@description"] + +[kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/module-name/expected.txt b/crates/compact-lint/tests/fixtures/module-name/expected.txt new file mode 100644 index 00000000..6d31a1ce --- /dev/null +++ b/crates/compact-lint/tests/fixtures/module-name/expected.txt @@ -0,0 +1 @@ +Renamed.compact:2:4: module-name: @module names `Stale`, but the module is `Renamed` diff --git a/crates/compact-lint/tests/fixtures/parse/Broken.compact b/crates/compact-lint/tests/fixtures/parse/Broken.compact new file mode 100644 index 00000000..c21593b4 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/parse/Broken.compact @@ -0,0 +1,3 @@ +export module Broken { + export circuit +} diff --git a/crates/compact-lint/tests/fixtures/parse/compact-lint.toml b/crates/compact-lint/tests/fixtures/parse/compact-lint.toml new file mode 100644 index 00000000..56ee774e --- /dev/null +++ b/crates/compact-lint/tests/fixtures/parse/compact-lint.toml @@ -0,0 +1,2 @@ +version = 1 +include = ["**/*.compact"] diff --git a/crates/compact-lint/tests/fixtures/parse/expected.txt b/crates/compact-lint/tests/fixtures/parse/expected.txt new file mode 100644 index 00000000..b50d9d70 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/parse/expected.txt @@ -0,0 +1 @@ +Broken.compact:2:3: parse: parse error: unexpected ERROR From a8ac6560535ced886a40b2acb80c13ea2dd5e0e8 Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Tue, 15 Sep 2026 10:15:01 +0200 Subject: [PATCH 04/56] feat(compact-lint): add the fix command Adds fix, which rewrites doc comments so a following check is clean for every rule it covers and a second fix is a no-op. Detection now yields a structured Issue that check renders as a Finding and fix renders as an Edit, so the two subcommands cannot disagree. * fix: doc skeletons above undocumented declarations, missing tags in config order (a missing @description adopts prose that opens the body), the constraints placeholder after the description block, tag renames from the new [tags] rename map, and @module name repairs. Edits on one comment merge into a single replacement; files are rewritten atomically with their line ending and permissions kept. * target: config and path resolution shared by check and fix. * config: [fix] placeholder and [tags] rename, both validated. * tests: one before/after fixture per rule through the binary, run on a temp copy and followed by check and a second fix. --- Cargo.lock | 84 +++ Cargo.toml | 1 + crates/compact-lint/Cargo.toml | 1 + crates/compact-lint/README.md | 66 +- .../examples/compact-contracts.toml | 1 + crates/compact-lint/src/check.rs | 53 +- crates/compact-lint/src/config.rs | 67 +- crates/compact-lint/src/edit.rs | 570 ++++++++++++++++++ crates/compact-lint/src/fix.rs | 377 ++++++++++++ crates/compact-lint/src/lib.rs | 6 +- crates/compact-lint/src/main.rs | 74 ++- crates/compact-lint/src/model.rs | 7 + crates/compact-lint/src/rules.rs | 306 +++++++--- crates/compact-lint/src/target.rs | 65 ++ crates/compact-lint/tests/fix.rs | 223 +++++++ .../fix-constraints/after/Unmeasured.compact | 37 ++ .../fix-constraints/before/Unmeasured.compact | 31 + .../fix-constraints/compact-lint.toml | 13 + .../fixtures/fix-constraints/expected.txt | 3 + .../fixtures/fix-crlf/after/Windows.compact | 19 + .../fixtures/fix-crlf/before/Windows.compact | 13 + .../tests/fixtures/fix-crlf/compact-lint.toml | 18 + .../tests/fixtures/fix-crlf/expected.txt | 3 + .../fix-missing-tag/after/Untagged.compact | 25 + .../fix-missing-tag/before/Untagged.compact | 18 + .../fix-missing-tag/compact-lint.toml | 14 + .../fixtures/fix-missing-tag/expected.txt | 5 + .../fix-module-name/after/Renamed.compact | 12 + .../fix-module-name/before/Renamed.compact | 12 + .../fix-module-name/compact-lint.toml | 8 + .../fixtures/fix-module-name/expected.txt | 2 + .../fixtures/fix-rename/after/Returns.compact | 19 + .../fix-rename/before/Returns.compact | 19 + .../fixtures/fix-rename/compact-lint.toml | 15 + .../tests/fixtures/fix-rename/expected.txt | 2 + .../fixtures/fix-skeleton/after/Bare.compact | 59 ++ .../fixtures/fix-skeleton/before/Bare.compact | 32 + .../fixtures/fix-skeleton/compact-lint.toml | 31 + .../tests/fixtures/fix-skeleton/expected.txt | 8 + .../fix-unfixable/after/Malformed.compact | 12 + .../fix-unfixable/before/Malformed.compact | 12 + .../fixtures/fix-unfixable/compact-lint.toml | 15 + .../tests/fixtures/fix-unfixable/expected.txt | 0 43 files changed, 2224 insertions(+), 134 deletions(-) create mode 100644 crates/compact-lint/src/edit.rs create mode 100644 crates/compact-lint/src/fix.rs create mode 100644 crates/compact-lint/src/target.rs create mode 100644 crates/compact-lint/tests/fix.rs create mode 100644 crates/compact-lint/tests/fixtures/fix-constraints/after/Unmeasured.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-constraints/before/Unmeasured.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-constraints/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/fix-constraints/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/fix-crlf/after/Windows.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-crlf/before/Windows.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-crlf/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/fix-crlf/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/fix-missing-tag/after/Untagged.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-missing-tag/before/Untagged.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-missing-tag/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/fix-missing-tag/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/fix-module-name/after/Renamed.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-module-name/before/Renamed.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-module-name/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/fix-module-name/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/fix-rename/after/Returns.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-rename/before/Returns.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-rename/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/fix-rename/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/fix-skeleton/after/Bare.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-skeleton/before/Bare.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-skeleton/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/fix-skeleton/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/fix-unfixable/after/Malformed.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-unfixable/before/Malformed.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-unfixable/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/fix-unfixable/expected.txt diff --git a/Cargo.lock b/Cargo.lock index 80f353a8..7246e944 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -82,6 +82,12 @@ dependencies = [ "wait-timeout", ] +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + [[package]] name = "bstr" version = "1.13.1" @@ -103,6 +109,12 @@ dependencies = [ "shlex", ] +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + [[package]] name = "clap" version = "4.6.7" @@ -159,6 +171,7 @@ dependencies = [ "compact-tree-sitter", "globset", "serde", + "tempfile", "thiserror", "toml", "tree-sitter", @@ -186,12 +199,39 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + [[package]] name = "find-msvc-tools" version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e0f1c7c3a72c66fd80abe965175f7523475c0489a87d3ff9d6e8c87d87a9d2d" +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + [[package]] name = "globset" version = "0.4.20" @@ -245,6 +285,12 @@ version = "0.2.189" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + [[package]] name = "log" version = "0.4.34" @@ -257,6 +303,12 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + [[package]] name = "once_cell_polyfill" version = "1.70.2" @@ -308,6 +360,12 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + [[package]] name = "regex" version = "1.13.1" @@ -337,6 +395,19 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + [[package]] name = "same-file" version = "1.0.6" @@ -428,6 +499,19 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys", +] + [[package]] name = "termtree" version = "0.5.1" diff --git a/Cargo.toml b/Cargo.toml index 5e096be2..753653f2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -25,3 +25,4 @@ tree-sitter-language = "0.1" walkdir = "2.5" assert_cmd = "2.2" +tempfile = "3.27" diff --git a/crates/compact-lint/Cargo.toml b/crates/compact-lint/Cargo.toml index 09834756..384ce97f 100644 --- a/crates/compact-lint/Cargo.toml +++ b/crates/compact-lint/Cargo.toml @@ -31,3 +31,4 @@ walkdir.workspace = true [dev-dependencies] assert_cmd.workspace = true +tempfile.workspace = true diff --git a/crates/compact-lint/README.md b/crates/compact-lint/README.md index 28bd6284..0c4f3b2e 100644 --- a/crates/compact-lint/README.md +++ b/crates/compact-lint/README.md @@ -2,12 +2,14 @@ Doc-comment linter for Compact sources. It parses `.compact` files with [`compact-tree-sitter`](../compact-tree-sitter), matches every declaration against the -per-kind template in `compact-lint.toml`, and prints one finding per line. +per-kind template in `compact-lint.toml`, and prints one finding per line. `fix` +rewrites the comments the repairable rules report. ## Usage ```sh compact-lint check [PATHS]... [--config ] [--strict] [--no-format] [--compact-bin ] +compact-lint fix [PATHS]... [--config ] [--dry-run] ``` - `PATHS` β€” files or directories, walked recursively for `.compact`. Skipped while @@ -32,6 +34,52 @@ summary goes to stderr, where `M` is the number of files checked. - `1` β€” findings. - `2` β€” usage, config, IO or parser error. +## Fix + +`fix` rewrites `.compact` files so a following `check` is clean for every rule it +covers. It runs the same detection pass as `check`, so the two never disagree. + +```sh +compact-lint fix [PATHS]... [--config ] [--dry-run] +``` + +- `PATHS` and `--config` resolve exactly as they do for `check`. +- `--dry-run` β€” report the edits and write nothing. Exit `1` when there are edits, so + CI gates on it the way it gates on `cargo fmt --check`. + +Edits go to stdout, one per line, in `path:line:col: fix: ` form. The +`N edits in M files` summary goes to stderr, where `M` is the number of files changed. + +Exit codes: + +- `0` β€” the files were written, including when there was nothing to do. +- `1` β€” `--dry-run` only: edits would be made. +- `2` β€” usage, config, IO or parser error. + +What each rule's fix does: + +| Rule | Fix | +| --- | --- | +| `missing-doc` | Inserts a doc skeleton above the declaration, indented to it. Body lines come from `kinds..tags` in config order; `@module` takes the declaration's name, every other tag takes `fix.placeholder`. Exported non-pure circuits also get the constraints line. A kind with neither gets a single placeholder line. | +| `missing-tag` | Inserts each missing tag after the block of the last tag that precedes it in `kinds..tags`, else at the top of the body. A missing `@description` adopts untagged prose that opens the body instead of writing a placeholder. A `/** … */` one-liner expands to the multi-line form first. | +| `missing-constraints` | Inserts ` k=?, rows=?` after the `@description` block, with a blank ` *` line before it and, where prose follows, one after. Without a `@description` it opens the body. | +| `forbidden-tag` | Renames the tag in place, and only where `tags.rename` maps it. | +| `module-name` | Replaces the first word of the `@module` value with the module's name, keeping what follows. | + +Not fixed: + +- `constraints-format` β€” a human wrote a measurement the rule cannot parse; guessing at + it would lose the value. +- `constraints-placeholder` β€” filling `k=?` needs a real measurement. +- `parse` β€” the file does not parse, so no rewrite is trustworthy. +- `format` β€” that is `compact format`'s job. +- A forbidden tag with no `tags.rename` entry stays a `check` finding. + +Existing lines are never reordered or reflowed. Edits are computed against the original +text and applied from the highest offset down; several edits on one comment merge into a +single replacement of it. Files are rewritten through a sibling `.tmp` file and renamed +into place, keeping the file's line ending and its trailing newline, or lack of one. + ## Rules | Rule | Meaning | @@ -79,6 +127,10 @@ tag = "@constraints" [tags] forbid = ["@return"] +rename = { "@return" = "@returns" } + +[fix] +placeholder = "TODO" [kinds.module] docs = "exported" @@ -94,6 +146,8 @@ Defaults when no config file is found: | `exclude` | `[]` | | `constraints.tag` | `"@constraints"` | | `tags.forbid` | `[]` | +| `tags.rename` | `{}` | +| `fix.placeholder` | `"TODO"` | | `kinds..docs` | `"exported"` | | `kinds..tags` | `[]` | @@ -105,6 +159,10 @@ Defaults when no config file is found: `"all"` or `"none"` there. - `exclude` filters files found by walking a directory. A file named on the command line is always checked. +- `tags.rename` maps a forbidden tag to the tag `fix` writes in its place. Both spellings + are validated like every other tag. An unmapped forbidden tag is reported, never + rewritten. +- `fix.placeholder` is the text `fix` writes where it has no value of its own. `examples/compact-contracts.toml` is the config for OpenZeppelin/compact-contracts. @@ -123,6 +181,10 @@ Defaults when no config file is found: cargo test --workspace ``` -`tests/fixtures//` holds one case per rule plus a clean case: a +`tests/fixtures//` holds one `check` case per rule plus a clean case: a `compact-lint.toml`, the `.compact` sources, and `expected.txt`, the exact stdout with paths relative to the case directory. + +`tests/fixtures/fix-/` holds one `fix` case per rule: a `compact-lint.toml`, +`before/`, `after/` and `expected.txt`. The run copies `before/` into a temporary +directory, so the fixtures are never rewritten in place. diff --git a/crates/compact-lint/examples/compact-contracts.toml b/crates/compact-lint/examples/compact-contracts.toml index 402186d0..d20c3a93 100644 --- a/crates/compact-lint/examples/compact-contracts.toml +++ b/crates/compact-lint/examples/compact-contracts.toml @@ -11,6 +11,7 @@ tag = "@constraints" [tags] forbid = ["@return"] +rename = { "@return" = "@returns" } [kinds.module] docs = "exported" diff --git a/crates/compact-lint/src/check.rs b/crates/compact-lint/src/check.rs index 2f2d2a88..7fbc195f 100644 --- a/crates/compact-lint/src/check.rs +++ b/crates/compact-lint/src/check.rs @@ -1,22 +1,19 @@ -//! The `check` subcommand: resolve config, collect files, run the rules. +//! The `check` subcommand: resolve the target, run the rules, add the format pass. use std::ffi::OsString; use std::path::{Path, PathBuf}; use thiserror::Error; -use crate::config::{Config, ConfigError, discover as discover_config}; -use crate::discover::{self, DiscoverError}; use crate::format::{self, FormatError}; use crate::report::Finding; use crate::rules::{LintError, Linter}; +use crate::target::{self, TargetError}; #[derive(Debug, Error)] pub enum CheckError { #[error(transparent)] - Config(#[from] ConfigError), - #[error(transparent)] - Discover(#[from] DiscoverError), + Target(#[from] TargetError), #[error(transparent)] Lint(#[from] LintError), #[error(transparent)] @@ -59,59 +56,25 @@ impl Outcome { /// # Errors /// Returns an error when the config, the file walk, the parser or the formatter fails. pub fn run(options: &Options, cwd: &Path) -> Result { - let (config, config_path, base) = resolve_config(options, cwd)?; - let source = config_path.as_deref().unwrap_or(Path::new("")); - - let exclude = config.exclude_set(source)?; - let files = if options.paths.is_empty() { - let include = config.include_set(source)?; - discover::from_globs(&base, &include, &exclude)? - } else { - discover::from_paths(&options.paths, &base, &exclude)? - }; - let files: Vec = files.iter().map(|path| display_path(path, cwd)).collect(); + let target = target::resolve(&options.paths, options.config_path.as_deref(), cwd)?; let mut linter = Linter::new()?; let mut findings = Vec::new(); - for path in &files { + for path in &target.files { let text = std::fs::read_to_string(path).map_err(|source| CheckError::Read { path: path.clone(), source, })?; - findings.extend(linter.check(path, &text, &config, options.strict)?); + findings.extend(linter.check(path, &text, &target.config, options.strict)?); } if !options.no_format { - findings.extend(format::check(&options.compact_bin, &files)?); + findings.extend(format::check(&options.compact_bin, &target.files)?); } findings.sort_by(|left, right| left.sort_key().cmp(&right.sort_key())); Ok(Outcome { findings, - files_checked: files.len(), + files_checked: target.files.len(), }) } - -/// An explicit `--config` is a shareable preset, so glob discovery stays anchored at -/// `cwd`; a config found by walking upward anchors discovery at its own directory. -fn resolve_config( - options: &Options, - cwd: &Path, -) -> Result<(Config, Option, PathBuf), ConfigError> { - if let Some(path) = options.config_path.as_deref() { - return Ok((Config::load(path)?, Some(path.to_owned()), cwd.to_owned())); - } - - match discover_config(cwd) { - Some(path) => { - let base = path.parent().unwrap_or(cwd).to_owned(); - Ok((Config::load(&path)?, Some(path), base)) - } - None => Ok((Config::default(), None, cwd.to_owned())), - } -} - -/// Paths under the working directory print relative to it; anything else prints as is. -fn display_path(path: &Path, cwd: &Path) -> PathBuf { - path.strip_prefix(cwd).unwrap_or(path).to_owned() -} diff --git a/crates/compact-lint/src/config.rs b/crates/compact-lint/src/config.rs index 0d7ae2ba..002c6d13 100644 --- a/crates/compact-lint/src/config.rs +++ b/crates/compact-lint/src/config.rs @@ -1,5 +1,6 @@ //! `compact-lint.toml`: discovery, parsing, and the built-in defaults. +use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use globset::{Glob, GlobSet, GlobSetBuilder}; @@ -117,11 +118,28 @@ impl Default for ConstraintsConfig { } } -/// Tags no doc comment may carry. +/// Tags no doc comment may carry, and the replacements `fix` writes for them. #[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq)] #[serde(deny_unknown_fields, default)] pub struct TagsConfig { pub forbid: Vec, + /// Forbidden tag to its replacement; an unmapped forbidden tag stays a finding. + pub rename: BTreeMap, +} + +/// What `fix` writes where it has no value to write. +#[derive(Clone, Debug, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields, default)] +pub struct FixConfig { + pub placeholder: String, +} + +impl Default for FixConfig { + fn default() -> Self { + Self { + placeholder: "TODO".to_owned(), + } + } } /// A parsed `compact-lint.toml`, or the built-in defaults when no file was found. @@ -133,6 +151,7 @@ pub struct Config { pub exclude: Vec, pub constraints: ConstraintsConfig, pub tags: TagsConfig, + pub fix: FixConfig, pub kinds: KindsConfig, } @@ -144,6 +163,7 @@ impl Default for Config { exclude: Vec::new(), constraints: ConstraintsConfig::default(), tags: TagsConfig::default(), + fix: FixConfig::default(), kinds: KindsConfig::default(), } } @@ -199,9 +219,17 @@ impl Config { per_kind .chain(self.tags.forbid.iter()) + .chain(self.tags.rename.keys()) + .chain(self.tags.rename.values()) .chain(std::iter::once(&self.constraints.tag)) } + /// The replacement `fix` writes for a forbidden tag, when the config names one. + #[must_use] + pub fn rename_of(&self, tag: &Tag) -> Option<&Tag> { + self.tags.rename.get(tag) + } + /// Compiles the `include` globs. /// # Errors /// Returns an error when a pattern is not a valid glob. @@ -295,6 +323,43 @@ mod tests { std::fs::remove_dir_all(&dir).expect("the temp dir is removable"); } + #[test] + fn a_rename_maps_a_forbidden_tag_to_its_replacement() { + let config: Config = toml::from_str( + "[tags]\nforbid = [\"@return\"]\nrename = { \"@return\" = \"@returns\" }\n", + ) + .expect("the snippet is valid config"); + + assert_eq!( + config.rename_of(&Tag::new("@return")), + Some(&Tag::new("@returns")) + ); + assert_eq!(config.rename_of(&Tag::new("@notice")), None); + } + + #[test] + fn a_rename_target_without_its_at_sign_is_rejected() { + let dir = std::env::temp_dir().join(format!("compact-lint-rename-{}", std::process::id())); + std::fs::create_dir_all(&dir).expect("the temp dir is writable"); + let path = dir.join("compact-lint.toml"); + std::fs::write(&path, "[tags]\nrename = { \"@return\" = \"returns\" }\n") + .expect("the config is writable"); + + let error = Config::load(&path).expect_err("the replacement lacks its @"); + + assert!(error.to_string().contains("\"returns\""), "{error}"); + std::fs::remove_dir_all(&dir).expect("the temp dir is removable"); + } + + #[test] + fn the_fix_placeholder_defaults_to_todo() { + assert_eq!(Config::default().fix.placeholder, "TODO"); + + let config: Config = toml::from_str("[fix]\nplaceholder = \"FIXME\"\n") + .expect("the snippet is valid config"); + assert_eq!(config.fix.placeholder, "FIXME"); + } + #[test] fn an_unknown_kind_is_rejected() { let error = diff --git a/crates/compact-lint/src/edit.rs b/crates/compact-lint/src/edit.rs new file mode 100644 index 00000000..281d859a --- /dev/null +++ b/crates/compact-lint/src/edit.rs @@ -0,0 +1,570 @@ +//! Byte-range edits and the doc-comment rewriting `fix` applies. +//! +//! Every edit is computed against the original text. They are applied from the highest +//! offset down, so positions never shift, and edits that target the same doc comment are +//! merged into one replacement of that comment. + +use std::ops::Range; + +use crate::report::Position; + +/// One repair, carrying the line `fix` prints for it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Edit { + pub position: Position, + pub message: String, + pub kind: EditKind, +} + +/// What an edit rewrites. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum EditKind { + /// Text inserted at a byte offset, used for a whole doc-comment skeleton. + Insert { offset: usize, text: String }, + /// One rewrite of the doc comment spanning `range`. + Doc { + range: Range, + /// Column the `/**` starts on, the indentation of every line the op writes. + indent: usize, + op: DocOp, + }, +} + +/// One change to the lines of a doc comment. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum DocOp { + /// A `@tag value` line added after the last of `after` present, else at the top of the body. + InsertTag { + line: String, + /// Tags that precede this one in config order. + after: Vec, + /// Untagged prose opening the body becomes this tag's value instead of the placeholder. + adopts_prose: bool, + }, + /// A `@tag k=?, rows=?` line added after the `@description` block. + InsertConstraints(String), + /// The tag name on one line replaced in place. + RenameTag { + /// 0-based line index inside the original comment. + line: usize, + from: String, + to: String, + }, + /// The first word of `@module`'s value replaced with the module's name. + SetModuleName { + /// 0-based line index inside the original comment. + line: usize, + name: String, + }, +} + +/// The line ending the file already uses, taken from its first line. +#[must_use] +pub fn newline_of(source: &str) -> &'static str { + match source.find('\n') { + Some(index) if index > 0 && source.as_bytes()[index - 1] == b'\r' => "\r\n", + _ => "\n", + } +} + +/// Rewrites `source` with every edit, merging the edits that share a doc comment. +#[must_use] +pub fn apply(source: &str, edits: &[Edit], newline: &str) -> String { + let mut replacements: Vec<(Range, String)> = Vec::new(); + let mut docs: Vec<(Range, usize, Vec<&DocOp>)> = Vec::new(); + + for edit in edits { + match &edit.kind { + EditKind::Insert { offset, text } => { + replacements.push((*offset..*offset, text.clone())); + } + EditKind::Doc { range, indent, op } => { + match docs.iter_mut().find(|(known, _, _)| known == range) { + Some((_, _, ops)) => ops.push(op), + None => docs.push((range.clone(), *indent, vec![op])), + } + } + } + } + + for (range, indent, ops) in docs { + let original = source.get(range.clone()).unwrap_or_default(); + replacements.push((range, render_doc(original, indent, newline, &ops))); + } + + replacements.sort_by_key(|(range, _)| std::cmp::Reverse(range.start)); + + let mut out = source.to_owned(); + for (range, text) in replacements { + if range.end <= out.len() { + out.replace_range(range, &text); + } + } + out +} + +/// Applies every op to one doc comment and renders it back with `newline`. +#[must_use] +fn render_doc(doc: &str, indent: usize, newline: &str, ops: &[&DocOp]) -> String { + let mut lines: Vec = doc + .split('\n') + .map(|line| line.strip_suffix('\r').unwrap_or(line).to_owned()) + .collect(); + + let margin = " ".repeat(indent); + let gutter = format!("{margin} * "); + + // An insertion needs a body, so a `/** … */` one-liner expands first. + let expands = lines.len() == 1 + && ops + .iter() + .any(|op| matches!(op, DocOp::InsertTag { .. } | DocOp::InsertConstraints(_))); + let shift = usize::from(expands); + if expands { + lines = expand(&lines[0], &margin, &gutter); + } + + // In-place ops address the original lines, so they run before any insertion moves + // them; tags precede the constraints line, which anchors itself on `@description`. + for op in ops { + match op { + DocOp::RenameTag { line, from, to } => { + if let Some(target) = lines.get_mut(line + shift) + && let Some(renamed) = rename_tag(target, from, to) + { + *target = renamed; + } + } + DocOp::SetModuleName { line, name } => { + if let Some(target) = lines.get_mut(line + shift) + && let Some(renamed) = set_module_name(target, name) + { + *target = renamed; + } + } + _ => {} + } + } + + for op in ops { + if let DocOp::InsertTag { + line, + after, + adopts_prose, + } = op + { + insert_tag(&mut lines, &gutter, line, after, *adopts_prose); + } + } + + for op in ops { + if let DocOp::InsertConstraints(body) = op { + insert_constraints(&mut lines, &margin, &gutter, body); + } + } + + lines.join(newline) +} + +/// Splits `/** text */` into the three-line form, keeping the comment's indentation. +fn expand(single: &str, margin: &str, gutter: &str) -> Vec { + let inner = single + .strip_prefix("/**") + .and_then(|rest| rest.strip_suffix("*/")) + .unwrap_or(single) + .trim(); + + vec![ + "/**".to_owned(), + format!("{gutter}{inner}"), + format!("{margin} */"), + ] +} + +/// A tag line lands after the block of the last tag in `after` that is present, else at +/// the top of the body. With `adopts_prose`, untagged prose opening the body takes the +/// tag instead of a new line going in. +fn insert_tag( + lines: &mut Vec, + gutter: &str, + line: &str, + after: &[String], + adopts_prose: bool, +) { + let closer = lines.len().saturating_sub(1); + + if adopts_prose + && let Some(first) = (1..closer).find(|index| !is_blank(&lines[*index])) + && !starts_tag(content(&lines[first])) + && let Some((tag, _)) = line.split_once(' ') + { + lines[first] = format!("{gutter}{tag} {}", content(&lines[first])); + return; + } + + let at = tag_block_end(lines, closer, after).map_or(1.min(closer), |end| end + 1); + lines.insert(at, format!("{gutter}{line}")); +} + +/// The constraints line follows the `@description` block, or opens the body without one. +fn insert_constraints(lines: &mut Vec, margin: &str, gutter: &str, body: &str) { + let closer = lines.len().saturating_sub(1); + let blank = format!("{margin} *"); + + let at = match description_end(lines, closer) { + Some(end) => { + lines.insert(end + 1, blank.clone()); + end + 2 + } + None => 1.min(closer), + }; + + lines.insert(at, format!("{gutter}{body}")); + + let follows = at + 1; + if follows < lines.len() && follows != lines.len() - 1 && !is_blank(&lines[follows]) { + lines.insert(follows, blank); + } +} + +/// The last line of the `@description` block: its tag line plus every continuation. +fn description_end(lines: &[String], closer: usize) -> Option { + tag_block_end(lines, closer, &["@description".to_owned()]) +} + +/// The last line of the block opened by the last occurrence of any tag in `tags`. +fn tag_block_end(lines: &[String], closer: usize, tags: &[String]) -> Option { + let start = (1..closer).rev().find(|index| { + let text = content(&lines[*index]); + tags.iter().any(|tag| { + text.strip_prefix(tag.as_str()) + .is_some_and(|rest| rest.is_empty() || rest.starts_with(char::is_whitespace)) + }) + })?; + + let mut end = start; + while end + 1 < closer { + let next = content(&lines[end + 1]); + if next.is_empty() || starts_tag(next) { + break; + } + end += 1; + } + Some(end) +} + +/// A comment line without its indentation, its `*` and the space after it. +fn content(line: &str) -> &str { + let trimmed = line.trim_start(); + match trimmed.strip_prefix('*') { + Some(rest) => rest.trim(), + None => trimmed.trim(), + } +} + +fn is_blank(line: &str) -> bool { + content(line).is_empty() +} + +fn starts_tag(content: &str) -> bool { + content + .strip_prefix('@') + .is_some_and(|rest| rest.starts_with(|character: char| character.is_ascii_alphabetic())) +} + +/// Replaces the first whole-word occurrence of `from`, so `@return` never claims `@returns`. +fn rename_tag(line: &str, from: &str, to: &str) -> Option { + let bytes = line.as_bytes(); + let mut search = 0; + while let Some(offset) = line.get(search..)?.find(from) { + let start = search + offset; + let end = start + from.len(); + let before_is_word = start > 0 && bytes[start - 1].is_ascii_alphanumeric(); + let after_is_word = bytes.get(end).is_some_and(u8::is_ascii_alphabetic); + if !before_is_word && !after_is_word { + return Some(format!("{}{to}{}", &line[..start], &line[end..])); + } + search = end; + } + None +} + +/// Replaces the first word after `@module`, keeping whatever follows it. +fn set_module_name(line: &str, name: &str) -> Option { + let tag = "@module"; + let start = line.find(tag)?; + let after = start + tag.len(); + let rest = line.get(after..)?; + + let spaces = rest.len() - rest.trim_start().len(); + let value = rest.trim_start(); + let word = value + .find(char::is_whitespace) + .map_or(value.len(), |index| index); + + if value.is_empty() { + return Some(format!("{line} {name}")); + } + Some(format!( + "{}{}{name}{}", + &line[..after], + &rest[..spaces], + &value[word..] + )) +} + +#[cfg(test)] +mod tests { + use super::{ + DocOp, Edit, EditKind, apply, newline_of, rename_tag, render_doc, set_module_name, + }; + use crate::report::Position; + + fn doc_edit(range: std::ops::Range, indent: usize, op: DocOp) -> Edit { + Edit { + position: Position::file_start(), + message: String::new(), + kind: EditKind::Doc { range, indent, op }, + } + } + + fn tag(line: &str, after: &[&str]) -> DocOp { + DocOp::InsertTag { + line: line.to_owned(), + after: after.iter().map(ToString::to_string).collect(), + adopts_prose: line.starts_with("@description"), + } + } + + fn rendered(doc: &str, indent: usize, ops: &[DocOp]) -> String { + let borrowed: Vec<&DocOp> = ops.iter().collect(); + render_doc(doc, indent, "\n", &borrowed) + } + + #[test] + fn a_tag_goes_in_at_the_top_of_the_body() { + let doc = "/**\n * @constraints k=6, rows=28\n */"; + + assert_eq!( + rendered(doc, 2, &[tag("@description TODO", &[])]), + "/**\n * @description TODO\n * @constraints k=6, rows=28\n */" + ); + } + + #[test] + fn several_tags_keep_the_order_they_were_produced_in() { + let doc = "/**\n * @notice loose\n */"; + let ops = [ + tag("@module Ownable", &[]), + tag("@description TODO", &["@module"]), + ]; + + assert_eq!( + rendered(doc, 0, &ops), + "/**\n * @module Ownable\n * @description TODO\n * @notice loose\n */" + ); + } + + #[test] + fn a_tag_lands_after_the_tags_that_precede_it_in_config_order() { + let doc = "/**\n * @module Ownable\n * spanning two lines\n *\n * @notice loose\n */"; + + assert_eq!( + rendered(doc, 0, &[tag("@description TODO", &["@module"])]), + "/**\n * @module Ownable\n * spanning two lines\n * @description TODO\n *\n * @notice loose\n */" + ); + } + + #[test] + fn a_description_adopts_the_prose_that_opens_the_body() { + let doc = "/**\n * Approved accounts.\n * @param {T} a - A.\n */"; + + assert_eq!( + rendered(doc, 0, &[tag("@description TODO", &[])]), + "/**\n * @description Approved accounts.\n * @param {T} a - A.\n */" + ); + assert_eq!( + rendered( + "/** Approved accounts. */", + 2, + &[tag("@description TODO", &[])] + ), + "/**\n * @description Approved accounts.\n */" + ); + } + + #[test] + fn a_single_line_doc_expands_before_a_tag_goes_in() { + let doc = "/** @description Approved accounts. */"; + + assert_eq!( + rendered(doc, 2, &[tag("@module M", &[])]), + "/**\n * @module M\n * @description Approved accounts.\n */" + ); + } + + #[test] + fn constraints_follow_the_description_and_its_continuation_lines() { + let doc = "/**\n * @description Sends a coin\n * to the recipient.\n * @param {Coin} coin - The coin.\n */"; + + assert_eq!( + rendered( + doc, + 0, + &[DocOp::InsertConstraints( + "@constraints k=?, rows=?".to_owned() + )] + ), + "/**\n * @description Sends a coin\n * to the recipient.\n *\n * @constraints k=?, rows=?\n *\n * @param {Coin} coin - The coin.\n */" + ); + } + + #[test] + fn constraints_need_no_trailing_blank_before_the_closer() { + let doc = "/**\n * @description Bumps.\n */"; + + assert_eq!( + rendered( + doc, + 0, + &[DocOp::InsertConstraints( + "@constraints k=?, rows=?".to_owned() + )] + ), + "/**\n * @description Bumps.\n *\n * @constraints k=?, rows=?\n */" + ); + } + + #[test] + fn constraints_open_the_body_when_there_is_no_description() { + let doc = "/**\n * @notice loose prose.\n */"; + + assert_eq!( + rendered( + doc, + 0, + &[DocOp::InsertConstraints( + "@constraints k=?, rows=?".to_owned() + )] + ), + "/**\n * @constraints k=?, rows=?\n *\n * @notice loose prose.\n */" + ); + } + + #[test] + fn a_missing_description_and_missing_constraints_compose_on_one_comment() { + let doc = "/**\n * @param {Uint<8>} value - The value.\n */"; + let composed = "/**\n * @description TODO\n *\n * @constraints k=?, rows=?\n *\n * @param {Uint<8>} value - The value.\n */"; + let tag = tag("@description TODO", &[]); + let constraints = DocOp::InsertConstraints("@constraints k=?, rows=?".to_owned()); + + assert_eq!( + rendered(doc, 0, &[tag.clone(), constraints.clone()]), + composed + ); + // The rule that reports first must not decide where the annotation lands. + assert_eq!(rendered(doc, 0, &[constraints, tag]), composed); + } + + #[test] + fn two_edits_on_one_comment_merge_into_a_single_replacement() { + let source = "/**\n * @return nothing\n */\nexport circuit run(): [] { }\n"; + let edits = [ + doc_edit( + 0..26, + 0, + DocOp::RenameTag { + line: 1, + from: "@return".to_owned(), + to: "@returns".to_owned(), + }, + ), + doc_edit(0..26, 0, tag("@description TODO", &[])), + ]; + + assert_eq!( + apply(source, &edits, "\n"), + "/**\n * @description TODO\n * @returns nothing\n */\nexport circuit run(): [] { }\n" + ); + } + + #[test] + fn an_insertion_and_a_later_comment_edit_both_land() { + let source = + "export ledger a: Uint<8>;\n/**\n * @return x\n */\nexport circuit run(): [] { }\n"; + let edits = [ + Edit { + position: Position::file_start(), + message: String::new(), + kind: EditKind::Insert { + offset: 0, + text: "/**\n * TODO\n */\n".to_owned(), + }, + }, + doc_edit( + 26..45, + 0, + DocOp::RenameTag { + line: 1, + from: "@return".to_owned(), + to: "@returns".to_owned(), + }, + ), + ]; + + assert_eq!( + apply(source, &edits, "\n"), + "/**\n * TODO\n */\nexport ledger a: Uint<8>;\n/**\n * @returns x\n */\nexport circuit run(): [] { }\n" + ); + } + + #[test] + fn a_rename_leaves_the_rest_of_the_line_alone() { + assert_eq!( + rename_tag(" * @return {[]} - Empty tuple.", "@return", "@returns"), + Some(" * @returns {[]} - Empty tuple.".to_owned()) + ); + } + + #[test] + fn a_rename_does_not_match_a_longer_tag() { + assert_eq!(rename_tag(" * @returns x", "@return", "@returns"), None); + } + + #[test] + fn a_module_rewrite_keeps_what_follows_the_name() { + assert_eq!( + set_module_name(" * @module Stale (archived)", "Renamed"), + Some(" * @module Renamed (archived)".to_owned()) + ); + assert_eq!( + set_module_name(" * @module Stale", "Renamed"), + Some(" * @module Renamed".to_owned()) + ); + } + + #[test] + fn crlf_sources_keep_their_line_ending() { + let source = "/**\r\n * @description Bumps.\r\n */\r\n"; + let edits = [doc_edit( + 0..32, + 0, + DocOp::InsertConstraints("@constraints k=?, rows=?".to_owned()), + )]; + + assert_eq!(newline_of(source), "\r\n"); + assert_eq!( + apply(source, &edits, newline_of(source)), + "/**\r\n * @description Bumps.\r\n *\r\n * @constraints k=?, rows=?\r\n */\r\n" + ); + } + + #[test] + fn a_file_without_a_trailing_newline_keeps_it_missing() { + let source = "/**\n * @description Bumps.\n */"; + let edits = [doc_edit(0..30, 0, tag("@module M", &[]))]; + + let out = apply(source, &edits, "\n"); + assert!(!out.ends_with('\n'), "{out:?}"); + } +} diff --git a/crates/compact-lint/src/fix.rs b/crates/compact-lint/src/fix.rs new file mode 100644 index 00000000..88e42bd7 --- /dev/null +++ b/crates/compact-lint/src/fix.rs @@ -0,0 +1,377 @@ +//! The `fix` subcommand: turn the fixable issues into edits and rewrite the files. + +use std::path::{Path, PathBuf}; + +use thiserror::Error; + +use crate::config::Config; +use crate::doc::Tag; +use crate::edit::{DocOp, Edit, EditKind, apply, newline_of}; +use crate::model::DeclKind; +use crate::report::Position; +use crate::rules::{Issue, LintError, Linter}; +use crate::target::{self, TargetError}; + +/// The value written into an inserted constraints annotation. +const UNMEASURED: &str = "k=?, rows=?"; + +/// The tag whose value is the declaration's own name. +const MODULE_TAG: &str = "@module"; + +/// The tag that adopts untagged prose opening a doc comment. +const DESCRIPTION_TAG: &str = "@description"; + +#[derive(Debug, Error)] +pub enum FixError { + #[error(transparent)] + Target(#[from] TargetError), + #[error(transparent)] + Lint(#[from] LintError), + #[error("cannot read {path}")] + Read { + path: PathBuf, + #[source] + source: std::io::Error, + }, + #[error("cannot write {path}")] + Write { + path: PathBuf, + #[source] + source: std::io::Error, + }, +} + +/// Everything the `fix` subcommand needs, already resolved from flags. +pub struct Options { + pub paths: Vec, + pub config_path: Option, + pub dry_run: bool, +} + +/// The edits one file took. +pub struct FileEdits { + pub path: PathBuf, + pub edits: Vec, +} + +/// Every file the run changed, in the order they were visited. +pub struct Outcome { + pub files: Vec, +} + +impl Outcome { + #[must_use] + pub fn edits(&self) -> usize { + self.files.iter().map(|file| file.edits.len()).sum() + } + + #[must_use] + pub fn summary(&self) -> String { + format!("{} edits in {} files", self.edits(), self.files.len()) + } +} + +/// Runs the subcommand with `cwd` as the working directory. +/// # Errors +/// Returns an error when the config, the file walk, the parser or a write fails. +pub fn run(options: &Options, cwd: &Path) -> Result { + let target = target::resolve(&options.paths, options.config_path.as_deref(), cwd)?; + + let mut linter = Linter::new()?; + let mut files = Vec::new(); + + for path in &target.files { + let source = std::fs::read_to_string(path).map_err(|source| FixError::Read { + path: path.clone(), + source, + })?; + + let newline = newline_of(&source); + let edits: Vec = linter + .issues(path, &source, &target.config, false)? + .iter() + .filter_map(|issue| edit_for(issue, &target.config, newline)) + .collect(); + + if edits.is_empty() { + continue; + } + + if !options.dry_run { + write_atomically(path, &apply(&source, &edits, newline))?; + } + files.push(FileEdits { + path: path.clone(), + edits, + }); + } + + Ok(Outcome { files }) +} + +/// The repair for one issue, or `None` where the rule has no safe fix. +/// +/// `constraints-format` and `constraints-placeholder` need a measurement a rewrite +/// cannot invent, and `parse` and `format` are not doc-comment issues at all. +#[must_use] +pub fn edit_for(issue: &Issue, config: &Config, newline: &str) -> Option { + match issue { + Issue::MissingDoc { + position, + subject, + kind, + name, + offset, + indent, + constraints, + } => Some(Edit { + position: *position, + message: format!("inserted doc skeleton for {subject}"), + kind: EditKind::Insert { + offset: *offset, + text: skeleton( + *kind, + name.as_deref(), + *constraints, + config, + *indent, + newline, + ), + }, + }), + + Issue::MissingTag { + position, + kind, + tag, + name, + doc, + .. + } => Some(Edit { + position: *position, + message: format!("inserted {tag}"), + kind: EditKind::Doc { + range: doc.range.clone(), + indent: doc.indent, + op: missing_tag_op(*kind, tag, name.as_deref(), config), + }, + }), + + Issue::MissingConstraints { + position, tag, doc, .. + } => Some(Edit { + position: *position, + message: format!("inserted {tag} {UNMEASURED}"), + kind: EditKind::Doc { + range: doc.range.clone(), + indent: doc.indent, + op: DocOp::InsertConstraints(format!("{tag} {UNMEASURED}")), + }, + }), + + Issue::ForbiddenTag { + position, + tag, + line_offset, + doc, + } => { + let replacement = config.rename_of(tag)?; + Some(Edit { + position: *position, + message: format!("renamed {tag} to {replacement}"), + kind: EditKind::Doc { + range: doc.range.clone(), + indent: doc.indent, + op: DocOp::RenameTag { + line: *line_offset, + from: tag.to_string(), + to: replacement.to_string(), + }, + }, + }) + } + + Issue::ModuleName { + position, + name, + line_offset, + doc, + .. + } => Some(Edit { + position: *position, + message: format!("set {MODULE_TAG} to `{name}`"), + kind: EditKind::Doc { + range: doc.range.clone(), + indent: doc.indent, + op: DocOp::SetModuleName { + line: *line_offset, + name: name.clone(), + }, + }, + }), + + Issue::Parse { .. } + | Issue::ConstraintsFormat { .. } + | Issue::ConstraintsPlaceholder { .. } => None, + } +} + +/// The tag line lands after the tags that precede it in config order; `@description` +/// adopts prose that opens the body. +fn missing_tag_op(kind: DeclKind, tag: &Tag, name: Option<&str>, config: &Config) -> DocOp { + DocOp::InsertTag { + line: tag_line(tag, name, config), + after: config + .kinds + .get(kind) + .tags + .iter() + .take_while(|required| *required != tag) + .map(ToString::to_string) + .collect(), + adopts_prose: tag.as_str() == DESCRIPTION_TAG, + } +} + +/// `@module` takes the declaration's own name; every other tag takes the placeholder. +fn tag_line(tag: &Tag, name: Option<&str>, config: &Config) -> String { + match name { + Some(name) if tag.as_str() == MODULE_TAG => format!("{tag} {name}"), + _ => format!("{tag} {}", config.fix.placeholder), + } +} + +/// The doc comment `fix` writes above an undocumented declaration. +/// +/// Body lines come from `kinds..tags` in config order, then the constraints +/// annotation where the declaration takes one. +fn skeleton( + kind: DeclKind, + name: Option<&str>, + constraints: bool, + config: &Config, + indent: usize, + newline: &str, +) -> String { + let mut body: Vec = config + .kinds + .get(kind) + .tags + .iter() + .map(|tag| tag_line(tag, name, config)) + .collect(); + + if constraints { + if !body.is_empty() { + body.push(String::new()); + } + body.push(format!("{} {UNMEASURED}", config.constraints.tag)); + } + if body.is_empty() { + body.push(config.fix.placeholder.clone()); + } + + let margin = " ".repeat(indent); + let mut lines = vec!["/**".to_owned()]; + for line in body { + if line.is_empty() { + lines.push(format!("{margin} *")); + } else { + lines.push(format!("{margin} * {line}")); + } + } + lines.push(format!("{margin} */")); + + // The declaration follows on its own line, back at its original indentation. + format!("{}{newline}{margin}", lines.join(newline)) +} + +/// Writes through a sibling temporary file, so a failed write never truncates the source. +fn write_atomically(path: &Path, text: &str) -> Result<(), FixError> { + let temporary = path.with_extension("compact.tmp"); + + std::fs::write(&temporary, text).map_err(|source| FixError::Write { + path: temporary.clone(), + source, + })?; + let permissions = std::fs::metadata(path) + .map_err(|source| FixError::Read { + path: path.to_owned(), + source, + })? + .permissions(); + std::fs::set_permissions(&temporary, permissions).map_err(|source| FixError::Write { + path: temporary.clone(), + source, + })?; + std::fs::rename(&temporary, path).map_err(|source| FixError::Write { + path: path.to_owned(), + source, + }) +} + +/// The line `fix` prints for one edit. +#[must_use] +pub fn line(path: &Path, position: Position, message: &str) -> String { + format!( + "{}:{}:{}: fix: {message}", + path.display(), + position.line, + position.column + ) +} + +#[cfg(test)] +mod tests { + use super::skeleton; + use crate::config::Config; + use crate::doc::Tag; + use crate::model::DeclKind; + + fn config() -> Config { + let mut config = Config::default(); + config.kinds.module.tags = vec![Tag::new("@module"), Tag::new("@description")]; + config.kinds.circuit.tags = vec![Tag::new("@description")]; + config + } + + #[test] + fn a_module_skeleton_names_the_module() { + assert_eq!( + skeleton(DeclKind::Module, Some("Ownable"), false, &config(), 0, "\n"), + "/**\n * @module Ownable\n * @description TODO\n */\n" + ); + } + + #[test] + fn an_exported_circuit_skeleton_carries_the_constraints_line() { + assert_eq!( + skeleton(DeclKind::Circuit, Some("run"), true, &config(), 2, "\n"), + "/**\n * @description TODO\n *\n * @constraints k=?, rows=?\n */\n " + ); + } + + #[test] + fn a_pure_circuit_skeleton_stops_at_the_tag_lines() { + assert_eq!( + skeleton(DeclKind::Circuit, Some("double"), false, &config(), 2, "\n"), + "/**\n * @description TODO\n */\n " + ); + } + + #[test] + fn a_kind_with_no_required_tags_still_gets_a_placeholder_body() { + assert_eq!( + skeleton(DeclKind::Type, Some("RoleId"), false, &config(), 2, "\n"), + "/**\n * TODO\n */\n " + ); + } + + #[test] + fn a_crlf_skeleton_uses_the_file_line_ending() { + assert_eq!( + skeleton(DeclKind::Type, None, false, &config(), 0, "\r\n"), + "/**\r\n * TODO\r\n */\r\n" + ); + } +} diff --git a/crates/compact-lint/src/lib.rs b/crates/compact-lint/src/lib.rs index fdaf6e9d..2eb94bb3 100644 --- a/crates/compact-lint/src/lib.rs +++ b/crates/compact-lint/src/lib.rs @@ -2,7 +2,8 @@ //! //! The crate parses `.compact` files with the bundled tree-sitter grammar, matches each //! declaration against the per-kind doc-comment template in `compact-lint.toml`, and -//! reports one [`report::Finding`] per violation. +//! yields one [`rules::Issue`] per violation. `check` renders an issue as a +//! [`report::Finding`]; `fix` renders the repairable ones as an [`edit::Edit`]. #![forbid(unsafe_code)] @@ -10,7 +11,10 @@ pub mod check; pub mod config; pub mod discover; pub mod doc; +pub mod edit; +pub mod fix; pub mod format; pub mod model; pub mod report; pub mod rules; +pub mod target; diff --git a/crates/compact-lint/src/main.rs b/crates/compact-lint/src/main.rs index dc4d3640..e47c785d 100644 --- a/crates/compact-lint/src/main.rs +++ b/crates/compact-lint/src/main.rs @@ -10,10 +10,11 @@ use std::process::ExitCode; use anyhow::{Context, Result}; use clap::{Parser, Subcommand}; -use compact_lint::check::{self, Options, Outcome}; +use compact_lint::check::{self, Outcome}; +use compact_lint::fix; use compact_lint::format::{COMPACT_BIN_ENV, DEFAULT_COMPACT_BIN}; -/// Exit code for a run that produced findings. +/// Exit code for a run that produced findings, or a `--dry-run` that would edit. const EXIT_FINDINGS: u8 = 1; /// Exit code for a usage, config, IO or parser error. @@ -34,6 +35,8 @@ struct Cli { enum Command { /// Check doc comments against the per-kind templates in compact-lint.toml. Check(CheckArgs), + /// Rewrite doc comments so the rules `fix` covers stop reporting. + Fix(FixArgs), } #[derive(Debug, clap::Args)] @@ -58,6 +61,20 @@ struct CheckArgs { compact_bin: Option, } +#[derive(Debug, clap::Args)] +struct FixArgs { + /// Files or directories to fix; defaults to the config's include globs. + paths: Vec, + + /// Config file to use instead of searching upward for compact-lint.toml. + #[arg(long, value_name = "FILE")] + config: Option, + + /// Report the edits without writing them; exits 1 when there are any. + #[arg(long)] + dry_run: bool, +} + fn main() -> ExitCode { match run() { Ok(code) => code, @@ -70,10 +87,16 @@ fn main() -> ExitCode { fn run() -> Result { let cli = Cli::parse(); - let Command::Check(args) = cli.command; - let cwd = std::env::current_dir().context("reading the current directory")?; - let options = Options { + + match cli.command { + Command::Check(args) => run_check(args, &cwd), + Command::Fix(args) => run_fix(args, &cwd), + } +} + +fn run_check(args: CheckArgs, cwd: &std::path::Path) -> Result { + let options = check::Options { paths: args.paths, config_path: args.config, strict: args.strict, @@ -83,8 +106,8 @@ fn run() -> Result { .unwrap_or_else(|| OsString::from(DEFAULT_COMPACT_BIN)), }; - let outcome = check::run(&options, &cwd).context("running the check")?; - emit(&outcome).context("writing the report")?; + let outcome = check::run(&options, cwd).context("running the check")?; + emit_findings(&outcome).context("writing the report")?; Ok(if outcome.findings.is_empty() { ExitCode::SUCCESS @@ -93,7 +116,24 @@ fn run() -> Result { }) } -fn emit(outcome: &Outcome) -> std::io::Result<()> { +fn run_fix(args: FixArgs, cwd: &std::path::Path) -> Result { + let options = fix::Options { + paths: args.paths, + config_path: args.config, + dry_run: args.dry_run, + }; + + let outcome = fix::run(&options, cwd).context("running the fix")?; + emit_edits(&outcome).context("writing the report")?; + + Ok(if options.dry_run && outcome.edits() > 0 { + ExitCode::from(EXIT_FINDINGS) + } else { + ExitCode::SUCCESS + }) +} + +fn emit_findings(outcome: &Outcome) -> std::io::Result<()> { let stdout = std::io::stdout(); let mut out = stdout.lock(); for finding in &outcome.findings { @@ -105,6 +145,24 @@ fn emit(outcome: &Outcome) -> std::io::Result<()> { Ok(()) } +fn emit_edits(outcome: &fix::Outcome) -> std::io::Result<()> { + let stdout = std::io::stdout(); + let mut out = stdout.lock(); + for file in &outcome.files { + for edit in &file.edits { + writeln!( + out, + "{}", + fix::line(&file.path, edit.position, &edit.message) + )?; + } + } + out.flush()?; + + eprintln!("{}", outcome.summary()); + Ok(()) +} + /// Prints the error and every source under it, one cause per line. fn report_error(error: &anyhow::Error) { eprintln!("compact-lint: {error}"); diff --git a/crates/compact-lint/src/model.rs b/crates/compact-lint/src/model.rs index 968eee81..5634f9cd 100644 --- a/crates/compact-lint/src/model.rs +++ b/crates/compact-lint/src/model.rs @@ -1,6 +1,7 @@ //! Declarations the linter checks, lifted out of the tree-sitter tree. use std::fmt; +use std::ops::Range; use tree_sitter::Node; @@ -75,6 +76,8 @@ pub struct Declaration { pub exported: bool, pub pure: bool, pub position: Position, + /// Byte offset of the declaration's first token, where `fix` inserts a skeleton. + pub offset: usize, /// The doc comment immediately preceding the declaration, if one attaches. pub doc: Option, } @@ -86,6 +89,8 @@ pub struct AttachedDoc { /// 0-based row of the `/**` line, for turning a tag's offset into a position. pub start_row: usize, pub start_column: usize, + /// Byte range of the `/** … */` node, the span `fix` rewrites. + pub range: Range, } impl AttachedDoc { @@ -152,6 +157,7 @@ fn declaration(kind: DeclKind, node: Node<'_>, source: &str) -> Declaration { exported, pure, position: Position::from_zero_based(start.row, start.column), + offset: node.start_byte(), doc: attached_doc(node, source), } } @@ -169,6 +175,7 @@ fn attached_doc(node: Node<'_>, source: &str) -> Option { comment: DocComment::parse(text(previous, source)?), start_row: start.row, start_column: start.column, + range: previous.start_byte()..previous.end_byte(), }) } diff --git a/crates/compact-lint/src/rules.rs b/crates/compact-lint/src/rules.rs index 9bc0bf7a..eb723ddd 100644 --- a/crates/compact-lint/src/rules.rs +++ b/crates/compact-lint/src/rules.rs @@ -1,5 +1,9 @@ //! The doc-comment rules, run over one parsed file at a time. +//! +//! Detection yields [`Issue`]s. `check` renders them as [`Finding`]s and `fix` renders +//! the fixable ones as edits, so both subcommands read the same detection pass. +use std::ops::Range; use std::path::{Path, PathBuf}; use thiserror::Error; @@ -18,6 +22,142 @@ pub enum LintError { NoTree(PathBuf), } +/// Where a doc comment sits in the file, for the rules that rewrite one. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct DocRef { + /// Byte range of the `/** … */` node. + pub range: Range, + /// Column the `/**` starts on, reused as the rewritten comment's indentation. + pub indent: usize, +} + +/// One rule violation, carrying what `check` prints and what `fix` needs to repair it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Issue { + Parse { + position: Position, + node_kind: String, + missing: bool, + }, + MissingDoc { + position: Position, + subject: String, + kind: DeclKind, + name: Option, + /// Byte offset of the declaration's first token. + offset: usize, + /// The declaration's start column, reused as the skeleton's indentation. + indent: usize, + /// The declaration also carries the constraints annotation. + constraints: bool, + }, + MissingTag { + position: Position, + subject: String, + kind: DeclKind, + tag: Tag, + /// The declaration's name, which `@module` takes as its value. + name: Option, + doc: DocRef, + }, + ForbiddenTag { + position: Position, + tag: Tag, + /// 0-based line index of the tag inside the doc comment. + line_offset: usize, + doc: DocRef, + }, + ModuleName { + position: Position, + documented: String, + name: String, + /// 0-based line index of `@module` inside the doc comment. + line_offset: usize, + doc: DocRef, + }, + MissingConstraints { + position: Position, + subject: String, + tag: Tag, + doc: DocRef, + }, + ConstraintsFormat { + position: Position, + tag: Tag, + value: String, + }, + ConstraintsPlaceholder { + position: Position, + tag: Tag, + value: String, + }, +} + +impl Issue { + #[must_use] + pub const fn position(&self) -> Position { + match self { + Self::Parse { position, .. } + | Self::MissingDoc { position, .. } + | Self::MissingTag { position, .. } + | Self::ForbiddenTag { position, .. } + | Self::ModuleName { position, .. } + | Self::MissingConstraints { position, .. } + | Self::ConstraintsFormat { position, .. } + | Self::ConstraintsPlaceholder { position, .. } => *position, + } + } + + #[must_use] + pub const fn rule(&self) -> RuleId { + match self { + Self::Parse { .. } => RuleId::PARSE, + Self::MissingDoc { .. } => RuleId::MISSING_DOC, + Self::MissingTag { .. } => RuleId::MISSING_TAG, + Self::ForbiddenTag { .. } => RuleId::FORBIDDEN_TAG, + Self::ModuleName { .. } => RuleId::MODULE_NAME, + Self::MissingConstraints { .. } => RuleId::MISSING_CONSTRAINTS, + Self::ConstraintsFormat { .. } => RuleId::CONSTRAINTS_FORMAT, + Self::ConstraintsPlaceholder { .. } => RuleId::CONSTRAINTS_PLACEHOLDER, + } + } + + #[must_use] + pub fn message(&self) -> String { + match self { + Self::Parse { + node_kind, missing, .. + } => { + if *missing { + format!("parse error: missing {node_kind}") + } else { + format!("parse error: unexpected {node_kind}") + } + } + Self::MissingDoc { subject, .. } => format!("{subject} has no doc comment"), + Self::MissingTag { subject, tag, .. } + | Self::MissingConstraints { subject, tag, .. } => { + format!("{subject} doc comment has no {tag}") + } + Self::ForbiddenTag { tag, .. } => format!("forbidden tag {tag}"), + Self::ModuleName { + documented, name, .. + } => format!("@module names `{documented}`, but the module is `{name}`"), + Self::ConstraintsFormat { tag, value, .. } => { + format!("{tag} value `{value}` is not `k=, rows=`") + } + Self::ConstraintsPlaceholder { tag, value, .. } => { + format!("{tag} value `{value}` still holds a placeholder") + } + } + } + + #[must_use] + pub fn finding(&self, display: &Path) -> Finding { + Finding::new(display, self.position(), self.rule(), self.message()) + } +} + /// A reusable parser plus the rules that run over its trees. pub struct Linter { parser: Parser, @@ -34,19 +174,19 @@ impl Linter { Ok(Self { parser }) } - /// Checks one file. `display` is the path printed in findings. + /// Runs every rule over one file, in source order. /// - /// A tree holding an `ERROR` or `MISSING` node yields a single `parse` finding and - /// no doc findings, because declarations around the defect are not trustworthy. + /// A tree holding an `ERROR` or `MISSING` node yields a single `parse` issue and no + /// doc issues, because declarations around the defect are not trustworthy. /// # Errors /// Returns an error when tree-sitter produces no tree for `source`. - pub fn check( + pub fn issues( &mut self, display: &Path, source: &str, config: &Config, strict: bool, - ) -> Result, LintError> { + ) -> Result, LintError> { let tree = self .parser .parse(source, None) @@ -54,42 +194,42 @@ impl Linter { let root = tree.root_node(); if let Some(defect) = first_defect(root) { - return Ok(vec![defect.finding(display)]); + return Ok(vec![defect]); } - let mut findings = Vec::new(); + let mut issues = Vec::new(); for declaration in declarations(root, source) { - check_declaration(&declaration, display, config, strict, &mut findings); + check_declaration(&declaration, config, strict, &mut issues); } - findings.sort_by(|left, right| left.sort_key().cmp(&right.sort_key())); - Ok(findings) + issues.sort_by_key(|issue| (issue.position(), issue.rule())); + Ok(issues) } -} - -struct Defect { - position: Position, - kind: String, - missing: bool, -} -impl Defect { - fn finding(&self, display: &Path) -> Finding { - let message = if self.missing { - format!("parse error: missing {}", self.kind) - } else { - format!("parse error: unexpected {}", self.kind) - }; - Finding::new(display, self.position, RuleId::PARSE, message) + /// Checks one file. `display` is the path printed in findings. + /// # Errors + /// Returns an error when tree-sitter produces no tree for `source`. + pub fn check( + &mut self, + display: &Path, + source: &str, + config: &Config, + strict: bool, + ) -> Result, LintError> { + Ok(self + .issues(display, source, config, strict)? + .iter() + .map(|issue| issue.finding(display)) + .collect()) } } /// The first `ERROR` or `MISSING` node in document order. -fn first_defect(node: Node<'_>) -> Option { +fn first_defect(node: Node<'_>) -> Option { if node.is_error() || node.is_missing() { let start = node.start_position(); - return Some(Defect { + return Some(Issue::Parse { position: Position::from_zero_based(start.row, start.column), - kind: node.kind().to_owned(), + node_kind: node.kind().to_owned(), missing: node.is_missing(), }); } @@ -104,10 +244,9 @@ fn first_defect(node: Node<'_>) -> Option { fn check_declaration( declaration: &Declaration, - display: &Path, config: &Config, strict: bool, - findings: &mut Vec, + issues: &mut Vec, ) { let kind_config = config.kinds.get(declaration.kind); let requires_docs = match kind_config.docs { @@ -118,32 +257,40 @@ fn check_declaration( let Some(attached) = declaration.doc.as_ref() else { if requires_docs { - findings.push(Finding::new( - display, - declaration.position, - RuleId::MISSING_DOC, - format!("{} has no doc comment", subject(declaration)), - )); + issues.push(Issue::MissingDoc { + position: declaration.position, + subject: subject(declaration), + kind: declaration.kind, + name: declaration.name.clone(), + offset: declaration.offset, + indent: declaration.position.column - 1, + constraints: takes_constraints(declaration), + }); } return; }; - // A forbidden tag is a finding wherever it appears, documented or not. + let doc = DocRef { + range: attached.range.clone(), + indent: attached.start_column, + }; + + // A forbidden tag is an issue wherever it appears, documented or not. for forbidden in &config.tags.forbid { for occurrence in attached.comment.tags() { if &occurrence.tag == forbidden { - findings.push(Finding::new( - display, - attached.tag_position(occurrence), - RuleId::FORBIDDEN_TAG, - format!("forbidden tag {forbidden}"), - )); + issues.push(Issue::ForbiddenTag { + position: attached.tag_position(occurrence), + tag: forbidden.clone(), + line_offset: occurrence.line_offset, + doc: doc.clone(), + }); } } } if declaration.kind == DeclKind::Module { - check_module_name(declaration, display, findings); + check_module_name(declaration, &doc, issues); } if !requires_docs { @@ -152,20 +299,22 @@ fn check_declaration( for required in &kind_config.tags { if !attached.comment.has(required) { - findings.push(Finding::new( - display, - declaration.position, - RuleId::MISSING_TAG, - format!("{} doc comment has no {required}", subject(declaration)), - )); + issues.push(Issue::MissingTag { + position: declaration.position, + subject: subject(declaration), + kind: declaration.kind, + tag: required.clone(), + name: declaration.name.clone(), + doc: doc.clone(), + }); } } - check_constraints(declaration, display, config, strict, findings); + check_constraints(declaration, &doc, config, strict, issues); } /// `@module ` must name the module it documents. -fn check_module_name(declaration: &Declaration, display: &Path, findings: &mut Vec) { +fn check_module_name(declaration: &Declaration, doc: &DocRef, issues: &mut Vec) { let tag = Tag::new("@module"); let (Some(attached), Some(name)) = (declaration.doc.as_ref(), declaration.name.as_deref()) else { @@ -177,12 +326,13 @@ fn check_module_name(declaration: &Declaration, display: &Path, findings: &mut V let documented = module_name(&occurrence.value); if documented != name { - findings.push(Finding::new( - display, - attached.tag_position(occurrence), - RuleId::MODULE_NAME, - format!("@module names `{documented}`, but the module is `{name}`"), - )); + issues.push(Issue::ModuleName { + position: attached.tag_position(occurrence), + documented: documented.to_owned(), + name: name.to_owned(), + line_offset: occurrence.line_offset, + doc: doc.clone(), + }); } } @@ -194,14 +344,18 @@ fn module_name(value: &str) -> &str { } /// Exported non-pure circuits carry the constraints annotation. +const fn takes_constraints(declaration: &Declaration) -> bool { + matches!(declaration.kind, DeclKind::Circuit) && declaration.exported && !declaration.pure +} + fn check_constraints( declaration: &Declaration, - display: &Path, + doc: &DocRef, config: &Config, strict: bool, - findings: &mut Vec, + issues: &mut Vec, ) { - if declaration.kind != DeclKind::Circuit || !declaration.exported || declaration.pure { + if !takes_constraints(declaration) { return; } let Some(attached) = declaration.doc.as_ref() else { @@ -210,12 +364,12 @@ fn check_constraints( let tag = &config.constraints.tag; let Some(occurrence) = attached.comment.first(tag) else { - findings.push(Finding::new( - display, - declaration.position, - RuleId::MISSING_CONSTRAINTS, - format!("{} doc comment has no {tag}", subject(declaration)), - )); + issues.push(Issue::MissingConstraints { + position: declaration.position, + subject: subject(declaration), + tag: tag.clone(), + doc: doc.clone(), + }); return; }; @@ -224,22 +378,20 @@ fn check_constraints( let position = attached.tag_position(occurrence); let Some(placeholders) = parse_constraints(value) else { - findings.push(Finding::new( - display, + issues.push(Issue::ConstraintsFormat { position, - RuleId::CONSTRAINTS_FORMAT, - format!("{tag} value `{value}` is not `k=, rows=`"), - )); + tag: tag.clone(), + value: value.to_owned(), + }); return; }; if strict && placeholders { - findings.push(Finding::new( - display, + issues.push(Issue::ConstraintsPlaceholder { position, - RuleId::CONSTRAINTS_PLACEHOLDER, - format!("{tag} value `{value}` still holds a placeholder"), - )); + tag: tag.clone(), + value: value.to_owned(), + }); } } diff --git a/crates/compact-lint/src/target.rs b/crates/compact-lint/src/target.rs new file mode 100644 index 00000000..aaa5e16b --- /dev/null +++ b/crates/compact-lint/src/target.rs @@ -0,0 +1,65 @@ +//! What a subcommand runs over: the resolved config plus the file list. + +use std::path::{Path, PathBuf}; + +use thiserror::Error; + +use crate::config::{Config, ConfigError, discover as discover_config}; +use crate::discover::{self, DiscoverError}; + +#[derive(Debug, Error)] +pub enum TargetError { + #[error(transparent)] + Config(#[from] ConfigError), + #[error(transparent)] + Discover(#[from] DiscoverError), +} + +/// The config and the files it selects, shared by `check` and `fix`. +pub struct Target { + pub config: Config, + pub files: Vec, +} + +/// Resolves the config and the file list for one run. +/// +/// An explicit `config_path` is a shareable preset, so glob discovery stays anchored at +/// `cwd`; a config found by walking upward anchors discovery at its own directory. +/// # Errors +/// Returns an error when the config is unreadable or a path cannot be walked. +pub fn resolve( + paths: &[PathBuf], + config_path: Option<&Path>, + cwd: &Path, +) -> Result { + let (config, source, base) = match config_path { + Some(path) => (Config::load(path)?, path.to_owned(), cwd.to_owned()), + None => match discover_config(cwd) { + Some(path) => { + let base = path.parent().unwrap_or(cwd).to_owned(); + (Config::load(&path)?, path, base) + } + None => ( + Config::default(), + PathBuf::from(""), + cwd.to_owned(), + ), + }, + }; + + let exclude = config.exclude_set(&source)?; + let files = if paths.is_empty() { + let include = config.include_set(&source)?; + discover::from_globs(&base, &include, &exclude)? + } else { + discover::from_paths(paths, &base, &exclude)? + }; + + let files = files.iter().map(|path| display_path(path, cwd)).collect(); + Ok(Target { config, files }) +} + +/// Paths under the working directory print relative to it; anything else prints as is. +fn display_path(path: &Path, cwd: &Path) -> PathBuf { + path.strip_prefix(cwd).unwrap_or(path).to_owned() +} diff --git a/crates/compact-lint/tests/fix.rs b/crates/compact-lint/tests/fix.rs new file mode 100644 index 00000000..fae2b524 --- /dev/null +++ b/crates/compact-lint/tests/fix.rs @@ -0,0 +1,223 @@ +//! `compact-lint fix` end to end, one fixture case per rule. +//! +//! A case holds `compact-lint.toml`, `before/`, `after/` and `expected.txt`. The run +//! works on a copy of `before/`, so the fixtures themselves are never rewritten. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use assert_cmd::prelude::*; +use tempfile::TempDir; + +/// Exit code for a `--dry-run` that would edit. +const EXIT_EDITS: i32 = 1; + +fn case(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures") + .join(format!("fix-{name}")) + .canonicalize() + .expect("the fixture case exists") +} + +fn binary() -> Command { + Command::cargo_bin("compact-lint").expect("the binary is built alongside this test") +} + +/// Copies the case's config and `before/` tree into a fresh temporary directory. +fn work(name: &str) -> TempDir { + let directory = TempDir::new().expect("a temporary directory is available"); + let root = case(name); + + std::fs::copy( + root.join("compact-lint.toml"), + directory.path().join("compact-lint.toml"), + ) + .expect("the case has a config"); + copy_tree(&root.join("before"), directory.path()); + + directory +} + +fn copy_tree(from: &Path, to: &Path) { + for entry in std::fs::read_dir(from).expect("the tree is readable") { + let entry = entry.expect("the entry is readable"); + let target = to.join(entry.file_name()); + if entry.path().is_dir() { + std::fs::create_dir_all(&target).expect("the target is writable"); + copy_tree(&entry.path(), &target); + } else { + std::fs::copy(entry.path(), &target).expect("the file is copyable"); + } + } +} + +/// Every `.compact` file under `root`, keyed by its path relative to it. +fn sources(root: &Path) -> BTreeMap> { + let mut found = BTreeMap::new(); + collect(root, root, &mut found); + found +} + +fn collect(root: &Path, directory: &Path, out: &mut BTreeMap>) { + for entry in std::fs::read_dir(directory).expect("the tree is readable") { + let entry = entry.expect("the entry is readable"); + let path = entry.path(); + if path.is_dir() { + collect(root, &path, out); + } else if path + .extension() + .is_some_and(|extension| extension == "compact") + { + let relative = path.strip_prefix(root).expect("the path is under the root"); + out.insert( + relative.to_owned(), + std::fs::read(&path).expect("the source is readable"), + ); + } + } +} + +fn expected(name: &str) -> String { + std::fs::read_to_string(case(name).join("expected.txt")).expect("the case has an expectation") +} + +/// Runs a subcommand inside `directory` and returns its exit code and stdout. +fn run(directory: &Path, args: &[&str]) -> (i32, String) { + let output = binary() + .current_dir(directory) + .args(args) + .output() + .expect("the binary ran"); + + ( + output.status.code().expect("the binary was not signalled"), + String::from_utf8(output.stdout).expect("the report is UTF-8"), + ) +} + +/// The whole contract of a fixable case: it fixes, it lands, it settles, it previews. +fn assert_case(name: &str) { + let directory = work(name); + let root = directory.path(); + + let (code, stdout) = run(root, &["fix"]); + assert_eq!(stdout, expected(name), "stdout for case {name}"); + assert_eq!(code, 0, "exit code for case {name}"); + assert_eq!( + sources(root), + sources(&case(name).join("after")), + "rewritten sources for case {name}" + ); + + let (code, stdout) = run(root, &["check", "--no-format"]); + assert_eq!(stdout, "", "check is clean after fixing case {name}"); + assert_eq!(code, 0, "check exit code after fixing case {name}"); + + let (code, stdout) = run(root, &["fix"]); + assert_eq!(stdout, "", "a second fix on case {name} edits nothing"); + assert_eq!(code, 0, "second fix exit code for case {name}"); + + let preview = work(name); + let before = sources(preview.path()); + let (code, stdout) = run(preview.path(), &["fix", "--dry-run"]); + assert_eq!(stdout, expected(name), "dry-run stdout for case {name}"); + assert_eq!(code, EXIT_EDITS, "dry-run exit code for case {name}"); + assert_eq!( + sources(preview.path()), + before, + "dry-run wrote to case {name}" + ); +} + +#[test] +fn undocumented_declarations_of_every_kind_take_a_skeleton() { + assert_case("skeleton"); +} + +#[test] +fn a_required_tag_goes_into_the_comment_that_lacks_it() { + assert_case("missing-tag"); +} + +#[test] +fn the_constraints_annotation_follows_the_description_block() { + assert_case("constraints"); +} + +#[test] +fn a_forbidden_tag_with_a_replacement_is_renamed_in_place() { + assert_case("rename"); +} + +#[test] +fn a_stale_module_tag_takes_the_module_name() { + assert_case("module-name"); +} + +#[test] +fn a_crlf_source_keeps_its_line_endings() { + assert_case("crlf"); +} + +#[test] +fn nothing_fixable_writes_nothing_and_exits_zero() { + let directory = work("unfixable"); + let root = directory.path(); + let before = sources(root); + + let (code, stdout) = run(root, &["fix"]); + assert_eq!(stdout, ""); + assert_eq!(code, 0); + assert_eq!(sources(root), before); + + let (code, stdout) = run(root, &["fix", "--dry-run"]); + assert_eq!(stdout, ""); + assert_eq!(code, 0); +} + +#[test] +fn the_summary_goes_to_stderr_and_the_edits_to_stdout() { + let directory = work("rename"); + let output = binary() + .current_dir(directory.path()) + .arg("fix") + .output() + .expect("the binary ran"); + + let stderr = String::from_utf8(output.stderr).expect("the summary is UTF-8"); + assert_eq!(stderr.trim_end(), "2 edits in 1 files"); + assert!( + String::from_utf8_lossy(&output.stdout).contains(": fix: "), + "the edits belong on stdout" + ); +} + +#[test] +fn an_explicit_config_replaces_the_one_beside_the_sources() { + let directory = work("rename"); + std::fs::remove_file(directory.path().join("compact-lint.toml")) + .expect("the copied config is removable"); + + let config = case("rename").join("compact-lint.toml"); + let output = binary() + .current_dir(directory.path()) + .args(["fix", "--config"]) + .arg(&config) + .output() + .expect("the binary ran"); + + assert_eq!( + String::from_utf8(output.stdout).expect("the report is UTF-8"), + expected("rename") + ); +} + +#[test] +fn a_missing_path_exits_two() { + let directory = work("rename"); + let (code, _) = run(directory.path(), &["fix", "Nope.compact"]); + + assert_eq!(code, 2); +} diff --git a/crates/compact-lint/tests/fixtures/fix-constraints/after/Unmeasured.compact b/crates/compact-lint/tests/fixtures/fix-constraints/after/Unmeasured.compact new file mode 100644 index 00000000..6c55524f --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-constraints/after/Unmeasured.compact @@ -0,0 +1,37 @@ +/** + * @module Unmeasured + * @description A module whose exported circuits are unmeasured. + */ +export module Unmeasured { + /** + * @description Bumps the counter. + * + * @constraints k=?, rows=? + */ + export circuit bump(): [] { } + + /** + * @description Sends a coin + * to the recipient named below. + * + * @constraints k=?, rows=? + * + * @param {Bytes<32>} to - The recipient. + * @returns {[]} Empty tuple. + */ + export circuit send(to: Bytes<32>): [] { } + + /** + * @constraints k=?, rows=? + * + * @notice The annotation goes to the top, since there is no description. + */ + export circuit run(): [] { } + + /** + * @description Pure circuits are never annotated. + */ + export pure circuit double(value: Uint<8>): Uint<16> { + return value as Uint<16> * 2; + } +} diff --git a/crates/compact-lint/tests/fixtures/fix-constraints/before/Unmeasured.compact b/crates/compact-lint/tests/fixtures/fix-constraints/before/Unmeasured.compact new file mode 100644 index 00000000..ea9ffde3 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-constraints/before/Unmeasured.compact @@ -0,0 +1,31 @@ +/** + * @module Unmeasured + * @description A module whose exported circuits are unmeasured. + */ +export module Unmeasured { + /** + * @description Bumps the counter. + */ + export circuit bump(): [] { } + + /** + * @description Sends a coin + * to the recipient named below. + * + * @param {Bytes<32>} to - The recipient. + * @returns {[]} Empty tuple. + */ + export circuit send(to: Bytes<32>): [] { } + + /** + * @notice The annotation goes to the top, since there is no description. + */ + export circuit run(): [] { } + + /** + * @description Pure circuits are never annotated. + */ + export pure circuit double(value: Uint<8>): Uint<16> { + return value as Uint<16> * 2; + } +} diff --git a/crates/compact-lint/tests/fixtures/fix-constraints/compact-lint.toml b/crates/compact-lint/tests/fixtures/fix-constraints/compact-lint.toml new file mode 100644 index 00000000..832f4ee6 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-constraints/compact-lint.toml @@ -0,0 +1,13 @@ +version = 1 +include = ["**/*.compact"] + +[constraints] +tag = "@constraints" + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] + +[kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/fix-constraints/expected.txt b/crates/compact-lint/tests/fixtures/fix-constraints/expected.txt new file mode 100644 index 00000000..9b498237 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-constraints/expected.txt @@ -0,0 +1,3 @@ +Unmeasured.compact:9:3: fix: inserted @constraints k=?, rows=? +Unmeasured.compact:18:3: fix: inserted @constraints k=?, rows=? +Unmeasured.compact:23:3: fix: inserted @constraints k=?, rows=? diff --git a/crates/compact-lint/tests/fixtures/fix-crlf/after/Windows.compact b/crates/compact-lint/tests/fixtures/fix-crlf/after/Windows.compact new file mode 100644 index 00000000..d1f31182 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-crlf/after/Windows.compact @@ -0,0 +1,19 @@ +/** + * @module Windows + * @description A module written with Windows line endings. + */ +export module Windows { + /** + * @description TODO + */ + export ledger _count: Counter; + + /** + * @description Bumps the counter. + * + * @constraints k=?, rows=? + * + * @returns {[]} - Empty tuple. + */ + export circuit bump(): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/fix-crlf/before/Windows.compact b/crates/compact-lint/tests/fixtures/fix-crlf/before/Windows.compact new file mode 100644 index 00000000..2ba98604 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-crlf/before/Windows.compact @@ -0,0 +1,13 @@ +/** + * @module Windows + * @description A module written with Windows line endings. + */ +export module Windows { + export ledger _count: Counter; + + /** + * @description Bumps the counter. + * @return {[]} - Empty tuple. + */ + export circuit bump(): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/fix-crlf/compact-lint.toml b/crates/compact-lint/tests/fixtures/fix-crlf/compact-lint.toml new file mode 100644 index 00000000..5e3068c1 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-crlf/compact-lint.toml @@ -0,0 +1,18 @@ +version = 1 +include = ["**/*.compact"] + +[tags] +forbid = ["@return"] +rename = { "@return" = "@returns" } + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] + +[kinds.ledger] +tags = ["@description"] + +[kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/fix-crlf/expected.txt b/crates/compact-lint/tests/fixtures/fix-crlf/expected.txt new file mode 100644 index 00000000..994f2b4d --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-crlf/expected.txt @@ -0,0 +1,3 @@ +Windows.compact:6:3: fix: inserted doc skeleton for ledger `_count` +Windows.compact:10:6: fix: renamed @return to @returns +Windows.compact:12:3: fix: inserted @constraints k=?, rows=? diff --git a/crates/compact-lint/tests/fixtures/fix-missing-tag/after/Untagged.compact b/crates/compact-lint/tests/fixtures/fix-missing-tag/after/Untagged.compact new file mode 100644 index 00000000..5f112dec --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-missing-tag/after/Untagged.compact @@ -0,0 +1,25 @@ +/** + * @module Untagged + * @description TODO + */ +export module Untagged { + /** + * @description Approved accounts. Absent means not allowed. + */ + export ledger _allowed: Set>; + + /** + * @description The circuit has no description either. + * @constraints k=6, rows=28 + */ + export circuit run(): [] { } + + /** + * @description TODO + * + * @constraints k=?, rows=? + * + * @param {Uint<8>} value - The value to store. + */ + export circuit store(value: Uint<8>): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/fix-missing-tag/before/Untagged.compact b/crates/compact-lint/tests/fixtures/fix-missing-tag/before/Untagged.compact new file mode 100644 index 00000000..49ef079e --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-missing-tag/before/Untagged.compact @@ -0,0 +1,18 @@ +/** + * @module Untagged + */ +export module Untagged { + /** Approved accounts. Absent means not allowed. */ + export ledger _allowed: Set>; + + /** + * The circuit has no description either. + * @constraints k=6, rows=28 + */ + export circuit run(): [] { } + + /** + * @param {Uint<8>} value - The value to store. + */ + export circuit store(value: Uint<8>): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/fix-missing-tag/compact-lint.toml b/crates/compact-lint/tests/fixtures/fix-missing-tag/compact-lint.toml new file mode 100644 index 00000000..3af7b212 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-missing-tag/compact-lint.toml @@ -0,0 +1,14 @@ +version = 1 +include = ["**/*.compact"] + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] + +[kinds.ledger] +tags = ["@description"] + +[kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/fix-missing-tag/expected.txt b/crates/compact-lint/tests/fixtures/fix-missing-tag/expected.txt new file mode 100644 index 00000000..a33b4e22 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-missing-tag/expected.txt @@ -0,0 +1,5 @@ +Untagged.compact:4:1: fix: inserted @description +Untagged.compact:6:3: fix: inserted @description +Untagged.compact:12:3: fix: inserted @description +Untagged.compact:17:3: fix: inserted @constraints k=?, rows=? +Untagged.compact:17:3: fix: inserted @description diff --git a/crates/compact-lint/tests/fixtures/fix-module-name/after/Renamed.compact b/crates/compact-lint/tests/fixtures/fix-module-name/after/Renamed.compact new file mode 100644 index 00000000..4e467b1c --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-module-name/after/Renamed.compact @@ -0,0 +1,12 @@ +/** + * @module Renamed (archived) + * @description The tag still names the module's old name. + */ +export module Renamed { + /** + * @module Nested + * @description The inner tag names nothing that exists. + */ + export module Nested { + } +} diff --git a/crates/compact-lint/tests/fixtures/fix-module-name/before/Renamed.compact b/crates/compact-lint/tests/fixtures/fix-module-name/before/Renamed.compact new file mode 100644 index 00000000..2ac33623 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-module-name/before/Renamed.compact @@ -0,0 +1,12 @@ +/** + * @module Stale (archived) + * @description The tag still names the module's old name. + */ +export module Renamed { + /** + * @module Inner. + * @description The inner tag names nothing that exists. + */ + export module Nested { + } +} diff --git a/crates/compact-lint/tests/fixtures/fix-module-name/compact-lint.toml b/crates/compact-lint/tests/fixtures/fix-module-name/compact-lint.toml new file mode 100644 index 00000000..d404f250 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-module-name/compact-lint.toml @@ -0,0 +1,8 @@ +version = 1 +include = ["**/*.compact"] + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/fix-module-name/expected.txt b/crates/compact-lint/tests/fixtures/fix-module-name/expected.txt new file mode 100644 index 00000000..5e9811ac --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-module-name/expected.txt @@ -0,0 +1,2 @@ +Renamed.compact:2:4: fix: set @module to `Renamed` +Renamed.compact:7:6: fix: set @module to `Nested` diff --git a/crates/compact-lint/tests/fixtures/fix-rename/after/Returns.compact b/crates/compact-lint/tests/fixtures/fix-rename/after/Returns.compact new file mode 100644 index 00000000..21cbe5dc --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-rename/after/Returns.compact @@ -0,0 +1,19 @@ +/** + * @module Returns + * @description A module that still uses the old return tag. + */ +export module Returns { + /** + * @description Does nothing. + * @constraints k=6, rows=28 + * @returns {[]} - Empty tuple. + */ + export circuit run(): [] { } + + /** + * @description Not exported, so its docs are optional, but the tag is not. + * @returns {[]} - Empty tuple. + * @returns {[]} - The new spelling is left alone. + */ + circuit helper(): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/fix-rename/before/Returns.compact b/crates/compact-lint/tests/fixtures/fix-rename/before/Returns.compact new file mode 100644 index 00000000..8c8fc7a5 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-rename/before/Returns.compact @@ -0,0 +1,19 @@ +/** + * @module Returns + * @description A module that still uses the old return tag. + */ +export module Returns { + /** + * @description Does nothing. + * @constraints k=6, rows=28 + * @return {[]} - Empty tuple. + */ + export circuit run(): [] { } + + /** + * @description Not exported, so its docs are optional, but the tag is not. + * @return {[]} - Empty tuple. + * @returns {[]} - The new spelling is left alone. + */ + circuit helper(): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/fix-rename/compact-lint.toml b/crates/compact-lint/tests/fixtures/fix-rename/compact-lint.toml new file mode 100644 index 00000000..ad6ecc55 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-rename/compact-lint.toml @@ -0,0 +1,15 @@ +version = 1 +include = ["**/*.compact"] + +[tags] +forbid = ["@return"] +rename = { "@return" = "@returns" } + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] + +[kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/fix-rename/expected.txt b/crates/compact-lint/tests/fixtures/fix-rename/expected.txt new file mode 100644 index 00000000..50c5c2ad --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-rename/expected.txt @@ -0,0 +1,2 @@ +Returns.compact:9:6: fix: renamed @return to @returns +Returns.compact:15:6: fix: renamed @return to @returns diff --git a/crates/compact-lint/tests/fixtures/fix-skeleton/after/Bare.compact b/crates/compact-lint/tests/fixtures/fix-skeleton/after/Bare.compact new file mode 100644 index 00000000..77abb211 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-skeleton/after/Bare.compact @@ -0,0 +1,59 @@ +pragma language_version >= 0.23.0; + +/** + * @module Bare + * @description TODO + */ +export module Bare { + import CompactStandardLibrary; + + /** + * @description TODO + */ + export ledger _count: Counter; + + /** + * @description TODO + */ + witness wit_Secret(): Bytes<32>; + + /** + * @description TODO + */ + export struct Reading { + value: Uint<64> + } + + /** + * @description TODO + */ + export enum Direction { + Up, + Down + } + + /** + * TODO + */ + export type Alias = Bytes<32>; + + constructor() { + _count.resetToDefault(); + } + + /** + * @description TODO + */ + export pure circuit double(value: Uint<8>): Uint<16> { + return value as Uint<16> * 2; + } + + /** + * @description TODO + * + * @constraints k=?, rows=? + */ + export circuit bump(): [] { + _count.increment(1); + } +} diff --git a/crates/compact-lint/tests/fixtures/fix-skeleton/before/Bare.compact b/crates/compact-lint/tests/fixtures/fix-skeleton/before/Bare.compact new file mode 100644 index 00000000..9a88c836 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-skeleton/before/Bare.compact @@ -0,0 +1,32 @@ +pragma language_version >= 0.23.0; + +export module Bare { + import CompactStandardLibrary; + + export ledger _count: Counter; + + witness wit_Secret(): Bytes<32>; + + export struct Reading { + value: Uint<64> + } + + export enum Direction { + Up, + Down + } + + export type Alias = Bytes<32>; + + constructor() { + _count.resetToDefault(); + } + + export pure circuit double(value: Uint<8>): Uint<16> { + return value as Uint<16> * 2; + } + + export circuit bump(): [] { + _count.increment(1); + } +} diff --git a/crates/compact-lint/tests/fixtures/fix-skeleton/compact-lint.toml b/crates/compact-lint/tests/fixtures/fix-skeleton/compact-lint.toml new file mode 100644 index 00000000..5fd3408d --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-skeleton/compact-lint.toml @@ -0,0 +1,31 @@ +version = 1 +include = ["**/*.compact"] + +[fix] +placeholder = "TODO" + +[tags] +forbid = ["@return"] +rename = { "@return" = "@returns" } + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] + +[kinds.ledger] +tags = ["@description"] + +[kinds.witness] +docs = "all" +tags = ["@description"] + +[kinds.struct] +tags = ["@description"] + +[kinds.enum] +tags = ["@description"] + +[kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/fix-skeleton/expected.txt b/crates/compact-lint/tests/fixtures/fix-skeleton/expected.txt new file mode 100644 index 00000000..8dadb68e --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-skeleton/expected.txt @@ -0,0 +1,8 @@ +Bare.compact:3:1: fix: inserted doc skeleton for module `Bare` +Bare.compact:6:3: fix: inserted doc skeleton for ledger `_count` +Bare.compact:8:3: fix: inserted doc skeleton for witness `wit_Secret` +Bare.compact:10:3: fix: inserted doc skeleton for struct `Reading` +Bare.compact:14:3: fix: inserted doc skeleton for enum `Direction` +Bare.compact:19:3: fix: inserted doc skeleton for type `Alias` +Bare.compact:25:3: fix: inserted doc skeleton for circuit `double` +Bare.compact:29:3: fix: inserted doc skeleton for circuit `bump` diff --git a/crates/compact-lint/tests/fixtures/fix-unfixable/after/Malformed.compact b/crates/compact-lint/tests/fixtures/fix-unfixable/after/Malformed.compact new file mode 100644 index 00000000..d7039c83 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-unfixable/after/Malformed.compact @@ -0,0 +1,12 @@ +/** + * @module Malformed + * @description A module whose annotations a rewrite cannot repair. + */ +export module Malformed { + /** + * @description The comma is missing, and nothing can guess the measurement. + * @constraints k=10 rows=626 + * @throws {Error} The forbidden tag has no replacement. + */ + export circuit first(): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/fix-unfixable/before/Malformed.compact b/crates/compact-lint/tests/fixtures/fix-unfixable/before/Malformed.compact new file mode 100644 index 00000000..d7039c83 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-unfixable/before/Malformed.compact @@ -0,0 +1,12 @@ +/** + * @module Malformed + * @description A module whose annotations a rewrite cannot repair. + */ +export module Malformed { + /** + * @description The comma is missing, and nothing can guess the measurement. + * @constraints k=10 rows=626 + * @throws {Error} The forbidden tag has no replacement. + */ + export circuit first(): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/fix-unfixable/compact-lint.toml b/crates/compact-lint/tests/fixtures/fix-unfixable/compact-lint.toml new file mode 100644 index 00000000..9bb3ab8f --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-unfixable/compact-lint.toml @@ -0,0 +1,15 @@ +version = 1 +include = ["**/*.compact"] + +# `@throws` is forbidden but has no replacement, so `fix` leaves it where it is. +[tags] +forbid = ["@throws"] + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] + +[kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/fix-unfixable/expected.txt b/crates/compact-lint/tests/fixtures/fix-unfixable/expected.txt new file mode 100644 index 00000000..e69de29b From 25b4943ebf492371618a715babcdba66d5133cdf Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Tue, 15 Sep 2026 11:04:12 +0200 Subject: [PATCH 05/56] feat(compact-lint): add the fill-constraints command Adds fill-constraints, which measures every circuit that already carries the constraints tag and writes k and rows into it. The values exist only on the compiler terminal output, so each measurement source compiles once under a pty and the progress lines are parsed. A library module is measured through the mock contract that exports its circuit names; presets compile themselves. * measure: portable-pty compile, escape and redraw cleanup, proof filter from contract-info.json, and the .circuit-info.json cache in the shape the TypeScript builder writes so both tools share it. * source: overrides, then self globs, then mock templates. * fill: rewrite only the tag value; unmeasured circuits stay as they are and exit 1; --no-compile reads the cache; --dry-run writes nothing, the cache included. * tests: a fake compact script drives the pty path in CI; a captured transcript pins the parser. --- Cargo.lock | 171 ++++- Cargo.toml | 4 +- crates/compact-lint/Cargo.toml | 4 +- crates/compact-lint/README.md | 120 +++- .../examples/compact-contracts.toml | 3 + crates/compact-lint/src/config.rs | 72 ++- crates/compact-lint/src/edit.rs | 126 ++++ crates/compact-lint/src/fill.rs | 297 +++++++++ crates/compact-lint/src/fix.rs | 34 +- crates/compact-lint/src/lib.rs | 5 + crates/compact-lint/src/main.rs | 79 ++- crates/compact-lint/src/measure.rs | 602 ++++++++++++++++++ crates/compact-lint/src/rules.rs | 73 ++- crates/compact-lint/src/source.rs | 249 ++++++++ crates/compact-lint/src/target.rs | 10 +- crates/compact-lint/tests/fill.rs | 289 +++++++++ .../after/src/access/Ownable.compact | 33 + .../src/access/test/mocks/MockOwnable.compact | 6 + .../before/src/access/Ownable.compact | 33 + .../src/access/test/mocks/MockOwnable.compact | 6 + .../fixtures/fill-basic/compact-lint.toml | 8 + .../tests/fixtures/fill-basic/expected.txt | 3 + .../before/src/broken/Broken.compact | 12 + .../src/broken/test/mocks/MockBroken.compact | 6 + .../fill-compiler-fails/compact-lint.toml | 8 + .../fixtures/fill-fake-compact/bin/compact | 70 ++ .../after/src/orphan/Orphan.compact | 12 + .../before/src/orphan/Orphan.compact | 12 + .../fill-missing-source/compact-lint.toml | 7 + .../fixtures/fill-missing-source/expected.txt | 1 + .../after/src/access/Ownable.compact | 12 + .../src/access/test/mocks/MockOwnable.compact | 6 + .../before/src/access/Ownable.compact | 12 + .../src/access/test/mocks/MockOwnable.compact | 6 + .../fill-no-compile/compact-lint.toml | 8 + .../fixtures/fill-no-compile/expected.txt | 1 + .../after/src/utils/Utils.compact | 12 + .../utils/test/mocks/MockUtilities.compact | 6 + .../before/src/utils/Utils.compact | 12 + .../utils/test/mocks/MockUtilities.compact | 6 + .../fixtures/fill-override/compact-lint.toml | 11 + .../tests/fixtures/fill-override/expected.txt | 1 + .../after/src/multisig/presets/Vault.compact | 19 + .../before/src/multisig/presets/Vault.compact | 19 + .../fixtures/fill-self/compact-lint.toml | 10 + .../tests/fixtures/fill-self/expected.txt | 2 + .../tests/fixtures/fill-transcript/pty.txt | 19 + 47 files changed, 2471 insertions(+), 46 deletions(-) create mode 100644 crates/compact-lint/src/fill.rs create mode 100644 crates/compact-lint/src/measure.rs create mode 100644 crates/compact-lint/src/source.rs create mode 100644 crates/compact-lint/tests/fill.rs create mode 100644 crates/compact-lint/tests/fixtures/fill-basic/after/src/access/Ownable.compact create mode 100644 crates/compact-lint/tests/fixtures/fill-basic/after/src/access/test/mocks/MockOwnable.compact create mode 100644 crates/compact-lint/tests/fixtures/fill-basic/before/src/access/Ownable.compact create mode 100644 crates/compact-lint/tests/fixtures/fill-basic/before/src/access/test/mocks/MockOwnable.compact create mode 100644 crates/compact-lint/tests/fixtures/fill-basic/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/fill-basic/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/fill-compiler-fails/before/src/broken/Broken.compact create mode 100644 crates/compact-lint/tests/fixtures/fill-compiler-fails/before/src/broken/test/mocks/MockBroken.compact create mode 100644 crates/compact-lint/tests/fixtures/fill-compiler-fails/compact-lint.toml create mode 100755 crates/compact-lint/tests/fixtures/fill-fake-compact/bin/compact create mode 100644 crates/compact-lint/tests/fixtures/fill-missing-source/after/src/orphan/Orphan.compact create mode 100644 crates/compact-lint/tests/fixtures/fill-missing-source/before/src/orphan/Orphan.compact create mode 100644 crates/compact-lint/tests/fixtures/fill-missing-source/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/fill-missing-source/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/fill-no-compile/after/src/access/Ownable.compact create mode 100644 crates/compact-lint/tests/fixtures/fill-no-compile/after/src/access/test/mocks/MockOwnable.compact create mode 100644 crates/compact-lint/tests/fixtures/fill-no-compile/before/src/access/Ownable.compact create mode 100644 crates/compact-lint/tests/fixtures/fill-no-compile/before/src/access/test/mocks/MockOwnable.compact create mode 100644 crates/compact-lint/tests/fixtures/fill-no-compile/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/fill-no-compile/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/fill-override/after/src/utils/Utils.compact create mode 100644 crates/compact-lint/tests/fixtures/fill-override/after/src/utils/test/mocks/MockUtilities.compact create mode 100644 crates/compact-lint/tests/fixtures/fill-override/before/src/utils/Utils.compact create mode 100644 crates/compact-lint/tests/fixtures/fill-override/before/src/utils/test/mocks/MockUtilities.compact create mode 100644 crates/compact-lint/tests/fixtures/fill-override/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/fill-override/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/fill-self/after/src/multisig/presets/Vault.compact create mode 100644 crates/compact-lint/tests/fixtures/fill-self/before/src/multisig/presets/Vault.compact create mode 100644 crates/compact-lint/tests/fixtures/fill-self/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/fill-self/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/fill-transcript/pty.txt diff --git a/Cargo.lock b/Cargo.lock index 7246e944..778d546a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -82,6 +82,12 @@ dependencies = [ "wait-timeout", ] +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + [[package]] name = "bitflags" version = "2.13.2" @@ -115,6 +121,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +[[package]] +name = "cfg_aliases" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e" + [[package]] name = "clap" version = "4.6.7" @@ -146,7 +158,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn", + "syn 3.0.5", ] [[package]] @@ -170,9 +182,11 @@ dependencies = [ "clap", "compact-tree-sitter", "globset", + "portable-pty", "serde", + "serde_json", "tempfile", - "thiserror", + "thiserror 2.0.20", "toml", "tree-sitter", "walkdir", @@ -193,6 +207,12 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8" +[[package]] +name = "downcast-rs" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" + [[package]] name = "equivalent" version = "1.0.2" @@ -215,6 +235,17 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "filedescriptor" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e40758ed24c9b2eeb76c35fb0aebc66c626084edd827e07e1552279814c6682d" +dependencies = [ + "libc", + "thiserror 1.0.69", + "winapi", +] + [[package]] name = "find-msvc-tools" version = "0.1.12" @@ -279,6 +310,12 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + [[package]] name = "libc" version = "0.2.189" @@ -303,6 +340,18 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "nix" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab2156c4fce2f8df6c499cc1c763e4394b7482525bf2a9701c9d79d215f519e4" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -315,6 +364,27 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +[[package]] +name = "portable-pty" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4a596a2b3d2752d94f51fac2d4a96737b8705dddd311a32b9af47211f08671e" +dependencies = [ + "anyhow", + "bitflags 1.3.2", + "downcast-rs", + "filedescriptor", + "lazy_static", + "libc", + "log", + "nix", + "serial2", + "shared_library", + "shell-words", + "winapi", + "winreg", +] + [[package]] name = "predicates" version = "3.1.4" @@ -401,7 +471,7 @@ version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" dependencies = [ - "bitflags", + "bitflags 2.13.2", "errno", "libc", "linux-raw-sys", @@ -444,7 +514,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.5", ] [[package]] @@ -470,6 +540,33 @@ dependencies = [ "serde_core", ] +[[package]] +name = "serial2" +version = "0.2.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b16809bc35793b19ce4e0c53924bc0dce3937f15487997cfdaed936004180730" +dependencies = [ + "cfg-if", + "libc", + "windows-sys", +] + +[[package]] +name = "shared_library" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a9e7e0f2bfae24d8a5b5a66c5b257a83c7412304311512a0c054cd5e619da11" +dependencies = [ + "lazy_static", + "libc", +] + +[[package]] +name = "shell-words" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc6fe69c597f9c37bfeeeeeb33da3530379845f10be461a66d16d03eca2ded77" + [[package]] name = "shlex" version = "2.0.1" @@ -488,6 +585,17 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "syn" version = "3.0.5" @@ -518,13 +626,33 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683" +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + [[package]] name = "thiserror" version = "2.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" dependencies = [ - "thiserror-impl", + "thiserror-impl 2.0.20", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] @@ -535,7 +663,7 @@ checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.5", ] [[package]] @@ -628,6 +756,22 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + [[package]] name = "winapi-util" version = "0.1.11" @@ -637,6 +781,12 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + [[package]] name = "windows-link" version = "0.2.1" @@ -658,6 +808,15 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +[[package]] +name = "winreg" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d" +dependencies = [ + "winapi", +] + [[package]] name = "zmij" version = "1.0.23" diff --git a/Cargo.toml b/Cargo.toml index 753653f2..3e63a37e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,13 +16,15 @@ anyhow = "1.0" cc = "1" clap = { version = "4.6", features = ["derive", "env"] } globset = "0.4" +portable-pty = "0.9" serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" thiserror = "2.0" toml = "1.1" tree-sitter = "0.25" compact-tree-sitter = { version = "0.1.0", path = "crates/compact-tree-sitter" } tree-sitter-language = "0.1" +tempfile = "3.27" walkdir = "2.5" assert_cmd = "2.2" -tempfile = "3.27" diff --git a/crates/compact-lint/Cargo.toml b/crates/compact-lint/Cargo.toml index 384ce97f..014ed0b5 100644 --- a/crates/compact-lint/Cargo.toml +++ b/crates/compact-lint/Cargo.toml @@ -22,7 +22,10 @@ path = "src/main.rs" anyhow.workspace = true clap.workspace = true globset.workspace = true +portable-pty.workspace = true serde.workspace = true +serde_json.workspace = true +tempfile.workspace = true thiserror.workspace = true toml.workspace = true tree-sitter.workspace = true @@ -31,4 +34,3 @@ walkdir.workspace = true [dev-dependencies] assert_cmd.workspace = true -tempfile.workspace = true diff --git a/crates/compact-lint/README.md b/crates/compact-lint/README.md index 0c4f3b2e..d85a415a 100644 --- a/crates/compact-lint/README.md +++ b/crates/compact-lint/README.md @@ -3,13 +3,15 @@ Doc-comment linter for Compact sources. It parses `.compact` files with [`compact-tree-sitter`](../compact-tree-sitter), matches every declaration against the per-kind template in `compact-lint.toml`, and prints one finding per line. `fix` -rewrites the comments the repairable rules report. +rewrites the comments the repairable rules report. `fill-constraints` compiles the +contracts and writes the measured `k` and `rows` into the annotations. ## Usage ```sh compact-lint check [PATHS]... [--config ] [--strict] [--no-format] [--compact-bin ] compact-lint fix [PATHS]... [--config ] [--dry-run] +compact-lint fill-constraints [PATHS]... [--config ] [--dry-run] [--no-compile] [--compact-bin ] [--artifacts ] ``` - `PATHS` β€” files or directories, walked recursively for `.compact`. Skipped while @@ -80,6 +82,100 @@ text and applied from the highest offset down; several edits on one comment merg single replacement of it. Files are rewritten through a sibling `.tmp` file and renamed into place, keeping the file's line ending and its trailing newline, or lack of one. +## Fill constraints + +`fill-constraints` measures every circuit that already carries the constraints tag and +writes the value in, so `check --strict` is clean afterwards and a second run is a no-op. +`k` and `rows` reach only the compiler's terminal output, so each contract is compiled +under a pty and the progress lines are parsed. + +```sh +compact-lint fill-constraints [PATHS]... [--config ] [--dry-run] [--no-compile] [--compact-bin ] [--artifacts ] +``` + +- `PATHS` and `--config` resolve exactly as they do for `check`. +- `--dry-run` β€” report the changes and write nothing, the measurement cache included. +- `--no-compile` β€” read the `.circuit-info.json` caches instead of compiling. A source + with no cached entry is an error. +- `--compact-bin ` β€” path to the `compact` binary, as for `check`. Also settable + with `COMPACT_LINT_COMPACT_BIN`. +- `--artifacts ` β€” where the compiler writes. Without it a temporary directory is + used and removed at the end. + +Scope is the annotations that already exist: every exported non-pure circuit whose doc +comment carries `constraints.tag`, whatever its value. A circuit with no annotation is +`fix`'s job and is left alone here. A file holding a parse defect is skipped, so `check` +stays the place a syntax error is reported. + +Changes go to stdout, one per line: + +``` +contracts/src/access/Ownable.compact:59:6: fill: @constraints k=?, rows=? -> k=13, rows=4273 +``` + +The `N values filled in M files, U unmeasured` summary goes to stderr. `M` counts the +files that changed; `U` counts every tagged circuit left without a value, including the +ones in a file with no measurement source. + +### How a source is resolved + +A library module does not compile on its own, so its constraints are measured through the +mock contract that exports the same circuit names. For each file, in order: + +1. `constraints.overrides`, an exact path-to-path mapping. +2. `constraints.self`, globs for files that are contracts and compile themselves. +3. `constraints.sources`, templates expanded and tried until one exists. `{dir}` is the + file's directory, `{parent}` its parent, `{stem}` its name without the extension. + +Each distinct source is compiled once per run, whatever the number of files it measures. + +### The cache + +After a compile, the measurements are merged into `.circuit-info.json` beside the source, +keyed by the source's file name. It is the file the TypeScript builder in +`packages/builder` writes, in the same shape, so the two tools share it: + +```json +{ + "generatedAt": "2026-09-15T08:38:49.000Z", + "files": { + "MockOwnable.compact": [{ "name": "owner", "k": 7, "rows": 74 }] + } +} +``` + +Other files' entries are kept and `generatedAt` is refreshed. `--no-compile` reads this +file instead of running the compiler. + +### Unmeasured + +A tagged circuit is *unmeasured* when its source compiled but produced no measurement for +its name. That happens where the mock has no exported circuit of that name β€” `initialize` +is called from the mock's constructor, never exported β€” or where the compiler's +`contract-info.json` marks the circuit `proof: false`, which carries no constraints. The +value is left alone and the circuit is reported: + +``` +contracts/src/access/Ownable.compact:37:6: constraints-unmeasured: circuit `initialize` has no measurement in contracts/src/access/test/mocks/MockOwnable.compact +``` + +A file with no measurement source at all is reported once, with the candidates tried: + +``` +contracts/src/utils/Utils.compact:1:1: constraints-unmeasurable: no measurement source for contracts/src/utils/Utils.compact; tried contracts/src/utils/test/mocks/MockUtils.compact, contracts/src/test/mocks/MockUtils.compact +``` + +Exit codes: + +- `0` β€” every tagged circuit was measured, whether or not a value changed. +- `1` β€” at least one circuit is unmeasured or unmeasurable. +- `2` β€” usage, config, IO, compiler or missing-cache error. A failed compile prints the + source and the last 20 lines of the compiler's cleaned output; the raw pty stream is + never printed. + +Files are rewritten exactly as `fix` rewrites them: through a sibling `.tmp` file, keeping +the line ending, and only the annotation's own line changes. + ## Rules | Rule | Meaning | @@ -124,6 +220,12 @@ exclude = ["**/test/mocks/**", "**/archive/**"] [constraints] tag = "@constraints" +compiler = "0.34.0" +sources = ["{dir}/test/mocks/Mock{stem}.compact", "{parent}/test/mocks/Mock{stem}.compact"] +self = ["**/presets/**"] + +[constraints.overrides] +"contracts/src/utils/Utils.compact" = "contracts/src/utils/test/mocks/MockUtils.compact" [tags] forbid = ["@return"] @@ -145,6 +247,10 @@ Defaults when no config file is found: | `include` | `["**/*.compact"]` | | `exclude` | `[]` | | `constraints.tag` | `"@constraints"` | +| `constraints.compiler` | none, so `compact` picks its default toolchain | +| `constraints.sources` | `["{dir}/test/mocks/Mock{stem}.compact", "{parent}/test/mocks/Mock{stem}.compact"]` | +| `constraints.self` | `[]` | +| `constraints.overrides` | `{}` | | `tags.forbid` | `[]` | | `tags.rename` | `{}` | | `fix.placeholder` | `"TODO"` | @@ -163,6 +269,11 @@ Defaults when no config file is found: are validated like every other tag. An unmapped forbidden tag is reported, never rewritten. - `fix.placeholder` is the text `fix` writes where it has no value of its own. +- `constraints.compiler` is passed as `+` to `compact compile`. +- `constraints.sources` templates are tried in order; the first existing file wins. +- `constraints.self` marks files that compile themselves, so no mock is looked for. +- `constraints.overrides` keys and values are paths relative to the config's directory, + or to the current directory when the config came from `--config`. `examples/compact-contracts.toml` is the config for OpenZeppelin/compact-contracts. @@ -188,3 +299,10 @@ paths relative to the case directory. `tests/fixtures/fix-/` holds one `fix` case per rule: a `compact-lint.toml`, `before/`, `after/` and `expected.txt`. The run copies `before/` into a temporary directory, so the fixtures are never rewritten in place. + +`tests/fixtures/fill-/` holds the `fill-constraints` cases in the same shape. They +run against `tests/fixtures/fill-fake-compact/bin/compact`, a shell script that prints the +compiler's progress lines for a hard-coded table and writes a matching +`contract-info.json`, so the tests need no toolchain. It still runs through the pty, so +that path is covered too. `tests/fixtures/fill-transcript/pty.txt` is a captured +transcript of a real compile, for the parser's unit tests. diff --git a/crates/compact-lint/examples/compact-contracts.toml b/crates/compact-lint/examples/compact-contracts.toml index d20c3a93..ef9489eb 100644 --- a/crates/compact-lint/examples/compact-contracts.toml +++ b/crates/compact-lint/examples/compact-contracts.toml @@ -8,6 +8,9 @@ exclude = ["**/test/mocks/**", "**/archive/**"] # `@constraints` is the default; set `tag` to point the rule at another annotation. [constraints] tag = "@constraints" +# Presets are contracts, so fill-constraints compiles them directly. Everything else is +# measured through the mock beside it or in its parent, the default `sources` templates. +self = ["**/presets/**"] [tags] forbid = ["@return"] diff --git a/crates/compact-lint/src/config.rs b/crates/compact-lint/src/config.rs index 002c6d13..d633c480 100644 --- a/crates/compact-lint/src/config.rs +++ b/crates/compact-lint/src/config.rs @@ -103,17 +103,42 @@ impl KindsConfig { } } -/// The circuit constraints annotation. +/// Where `fill-constraints` looks for the contract that measures a file, tried in order. +/// +/// `{dir}` is the file's directory, `{parent}` its parent, `{stem}` its name without +/// the extension. +pub const DEFAULT_SOURCES: [&str; 2] = [ + "{dir}/test/mocks/Mock{stem}.compact", + "{parent}/test/mocks/Mock{stem}.compact", +]; + +/// The circuit constraints annotation, and how `fill-constraints` measures it. #[derive(Clone, Debug, Deserialize, PartialEq, Eq)] #[serde(deny_unknown_fields, default)] pub struct ConstraintsConfig { pub tag: Tag, + /// Toolchain version passed as `+`; none leaves `compact` on its default. + pub compiler: Option, + /// Measurement-source templates, first existing file wins. + pub sources: Vec, + /// Globs for files that are contracts and compile themselves. + #[serde(rename = "self")] + pub own: Vec, + /// File to its measurement source, both relative to the config's directory. + pub overrides: BTreeMap, } impl Default for ConstraintsConfig { fn default() -> Self { Self { tag: Tag::new("@constraints"), + compiler: None, + sources: DEFAULT_SOURCES + .iter() + .map(|&template| template.to_owned()) + .collect(), + own: Vec::new(), + overrides: BTreeMap::new(), } } } @@ -243,6 +268,13 @@ impl Config { pub fn exclude_set(&self, path: &Path) -> Result { glob_set(&self.exclude, path) } + + /// Compiles the `constraints.self` globs; an empty set matches nothing. + /// # Errors + /// Returns an error when a pattern is not a valid glob. + pub fn own_set(&self, path: &Path) -> Result { + glob_set(&self.constraints.own, path) + } } fn glob_set(patterns: &[String], path: &Path) -> Result { @@ -360,6 +392,44 @@ mod tests { assert_eq!(config.fix.placeholder, "FIXME"); } + #[test] + fn constraints_default_to_the_mock_templates_and_no_compiler_pin() { + let constraints = Config::default().constraints; + + assert_eq!(constraints.compiler, None); + assert_eq!(constraints.sources, super::DEFAULT_SOURCES); + assert!(constraints.own.is_empty()); + assert!(constraints.overrides.is_empty()); + } + + #[test] + fn a_constraints_table_keeps_the_templates_it_does_not_name() { + let config: Config = toml::from_str( + "[constraints]\ncompiler = \"0.34.0\"\nself = [\"**/presets/**\"]\n[constraints.overrides]\n\"a.compact\" = \"b.compact\"\n", + ) + .expect("the snippet is valid config"); + + assert_eq!(config.constraints.compiler.as_deref(), Some("0.34.0")); + assert_eq!(config.constraints.own, ["**/presets/**"]); + assert_eq!(config.constraints.sources, super::DEFAULT_SOURCES); + assert_eq!( + config + .constraints + .overrides + .get("a.compact") + .map(String::as_str), + Some("b.compact") + ); + } + + #[test] + fn an_unknown_constraints_key_is_rejected() { + let error = toml::from_str::("[constraints]\nsorces = []\n") + .expect_err("the key is misspelled"); + + assert!(error.to_string().contains("sorces"), "{error}"); + } + #[test] fn an_unknown_kind_is_rejected() { let error = diff --git a/crates/compact-lint/src/edit.rs b/crates/compact-lint/src/edit.rs index 281d859a..38a81397 100644 --- a/crates/compact-lint/src/edit.rs +++ b/crates/compact-lint/src/edit.rs @@ -5,6 +5,9 @@ //! merged into one replacement of that comment. use std::ops::Range; +use std::path::{Path, PathBuf}; + +use thiserror::Error; use crate::report::Position; @@ -56,6 +59,55 @@ pub enum DocOp { line: usize, name: String, }, + /// Everything after a tag on one line replaced with a new value. + SetTagValue { + /// 0-based line index inside the original comment. + line: usize, + tag: String, + value: String, + }, +} + +#[derive(Debug, Error)] +pub enum WriteError { + #[error("cannot read {path}")] + Read { + path: PathBuf, + #[source] + source: std::io::Error, + }, + #[error("cannot write {path}")] + Write { + path: PathBuf, + #[source] + source: std::io::Error, + }, +} + +/// Writes through a sibling temporary file, so a failed write never truncates the source. +/// # Errors +/// Returns an error when the temporary file, the source's mode, or the rename fails. +pub fn write_atomically(path: &Path, text: &str) -> Result<(), WriteError> { + let temporary = path.with_extension("compact.tmp"); + + std::fs::write(&temporary, text).map_err(|source| WriteError::Write { + path: temporary.clone(), + source, + })?; + let permissions = std::fs::metadata(path) + .map_err(|source| WriteError::Read { + path: path.to_owned(), + source, + })? + .permissions(); + std::fs::set_permissions(&temporary, permissions).map_err(|source| WriteError::Write { + path: temporary.clone(), + source, + })?; + std::fs::rename(&temporary, path).map_err(|source| WriteError::Write { + path: path.to_owned(), + source, + }) } /// The line ending the file already uses, taken from its first line. @@ -142,6 +194,13 @@ fn render_doc(doc: &str, indent: usize, newline: &str, ops: &[&DocOp]) -> String *target = renamed; } } + DocOp::SetTagValue { line, tag, value } => { + if let Some(target) = lines.get_mut(line + shift) + && let Some(rewritten) = set_tag_value(target, tag, value) + { + *target = rewritten; + } + } _ => {} } } @@ -289,6 +348,22 @@ fn rename_tag(line: &str, from: &str, to: &str) -> Option { None } +/// Replaces everything after the tag, keeping a one-line comment's closing delimiter. +fn set_tag_value(line: &str, tag: &str, value: &str) -> Option { + let start = line.find(tag)?; + let rest = line.get(start + tag.len()..)?; + if rest.starts_with(|character: char| character.is_ascii_alphabetic()) { + return None; + } + + let closer = if rest.trim_end().ends_with("*/") { + " */" + } else { + "" + }; + Some(format!("{}{tag} {value}{closer}", &line[..start])) +} + /// Replaces the first word after `@module`, keeping whatever follows it. fn set_module_name(line: &str, name: &str) -> Option { let tag = "@module"; @@ -317,6 +392,7 @@ fn set_module_name(line: &str, name: &str) -> Option { mod tests { use super::{ DocOp, Edit, EditKind, apply, newline_of, rename_tag, render_doc, set_module_name, + set_tag_value, }; use crate::report::Position; @@ -543,6 +619,56 @@ mod tests { ); } + #[test] + fn a_constraints_value_is_replaced_where_it_stands() { + let doc = "/**\n * @description Bumps.\n *\n * @constraints k=?, rows=?\n */"; + + assert_eq!( + rendered( + doc, + 0, + &[DocOp::SetTagValue { + line: 3, + tag: "@constraints".to_owned(), + value: "k=13, rows=4273".to_owned(), + }] + ), + "/**\n * @description Bumps.\n *\n * @constraints k=13, rows=4273\n */" + ); + } + + #[test] + fn a_value_rewrite_drops_what_trailed_the_old_one() { + assert_eq!( + set_tag_value( + " * @constraints k=1 rows=2 (stale)", + "@constraints", + "k=3, rows=4" + ), + Some(" * @constraints k=3, rows=4".to_owned()) + ); + assert_eq!( + set_tag_value(" * @constraintsX k=1", "@constraints", "k=3"), + None + ); + } + + #[test] + fn a_one_line_doc_keeps_its_closing_delimiter() { + assert_eq!( + rendered( + "/** @constraints k=?, rows=? */", + 2, + &[DocOp::SetTagValue { + line: 0, + tag: "@constraints".to_owned(), + value: "k=7, rows=74".to_owned(), + }] + ), + "/** @constraints k=7, rows=74 */" + ); + } + #[test] fn crlf_sources_keep_their_line_ending() { let source = "/**\r\n * @description Bumps.\r\n */\r\n"; diff --git a/crates/compact-lint/src/fill.rs b/crates/compact-lint/src/fill.rs new file mode 100644 index 00000000..5ee0dd6e --- /dev/null +++ b/crates/compact-lint/src/fill.rs @@ -0,0 +1,297 @@ +//! The `fill-constraints` subcommand: measure every tagged circuit and write the value in. +//! +//! Scope is the constraints annotations that already exist. A circuit with no annotation +//! is `fix`'s job, so this pass never adds one. + +use std::collections::BTreeMap; +use std::ffi::OsString; +use std::path::{Path, PathBuf}; + +use thiserror::Error; + +use crate::config::ConfigError; +use crate::edit::{DocOp, Edit, EditKind, WriteError, apply, newline_of, write_atomically}; +use crate::measure::{self, Compiler, Constraints, MeasureError}; +use crate::report::Position; +use crate::rules::{ConstraintSite, LintError, Linter}; +use crate::source::{Resolver, Source}; +use crate::target::{self, TargetError}; + +/// The rule name for a tagged circuit its source does not measure. +const UNMEASURED: &str = "constraints-unmeasured"; + +/// The rule name for a file with no measurement source at all. +const UNMEASURABLE: &str = "constraints-unmeasurable"; + +#[derive(Debug, Error)] +pub enum FillError { + #[error(transparent)] + Target(#[from] TargetError), + #[error(transparent)] + Config(#[from] ConfigError), + #[error(transparent)] + Lint(#[from] LintError), + #[error(transparent)] + Measure(#[from] MeasureError), + #[error(transparent)] + Write(#[from] WriteError), + #[error("cannot read {path}")] + Read { + path: PathBuf, + #[source] + source: std::io::Error, + }, +} + +/// Everything the subcommand needs, already resolved from flags and env. +pub struct Options { + pub paths: Vec, + pub config_path: Option, + pub dry_run: bool, + /// Read the `.circuit-info.json` caches instead of compiling. + pub no_compile: bool, + pub compact_bin: OsString, + /// Where the compiler writes; a run without one uses a temporary directory. + pub artifacts: PathBuf, +} + +/// The report lines and the counts behind the summary. +pub struct Outcome { + /// One line per change or gap, in file order. + pub lines: Vec, + pub filled: usize, + pub files: usize, + pub unmeasured: usize, +} + +impl Outcome { + #[must_use] + pub fn summary(&self) -> String { + format!( + "{} values filled in {} files, {} unmeasured", + self.filled, self.files, self.unmeasured + ) + } +} + +/// One file's annotations and the contract they are measured through. +struct Work { + path: PathBuf, + text: String, + sites: Vec, + source: Source, +} + +/// Runs the subcommand with `cwd` as the working directory. +/// # Errors +/// Returns an error when the config, the file walk, the parser, the compiler or a write +/// fails. +pub fn run(options: &Options, cwd: &Path) -> Result { + let target = target::resolve(&options.paths, options.config_path.as_deref(), cwd)?; + let resolver = Resolver::new(&target.config, &target.base, cwd)?; + let tag = target.config.constraints.tag.clone(); + + let mut linter = Linter::new()?; + let mut work = Vec::new(); + for path in &target.files { + let text = std::fs::read_to_string(path).map_err(|source| FillError::Read { + path: path.clone(), + source, + })?; + let sites = linter.constraint_sites(path, &text, &target.config)?; + if sites.is_empty() { + continue; + } + let source = resolver.resolve(path); + work.push(Work { + path: path.clone(), + text, + sites, + source, + }); + } + + let measured = measure_sources( + &work, + options, + target.config.constraints.compiler.as_ref(), + cwd, + )?; + + let mut outcome = Outcome { + lines: Vec::new(), + filled: 0, + files: 0, + unmeasured: 0, + }; + for file in &work { + fill_file(file, &measured, &tag, options, &mut outcome)?; + } + Ok(outcome) +} + +/// Compiles each distinct source once, or reads its cache under `--no-compile`. +fn measure_sources( + work: &[Work], + options: &Options, + version: Option<&String>, + cwd: &Path, +) -> Result>, FillError> { + let mut sources: Vec<&PathBuf> = work + .iter() + .filter_map(|file| match &file.source { + Source::Found(source) => Some(source), + Source::Missing(_) => None, + }) + .collect(); + sources.sort(); + sources.dedup(); + + let compiler = Compiler { + binary: options.compact_bin.clone(), + version: version.cloned(), + artifacts: options.artifacts.clone(), + cwd: cwd.to_owned(), + }; + + let mut measured = BTreeMap::new(); + for source in sources { + let list = if options.no_compile { + measure::read_cache(source)?.ok_or_else(|| MeasureError::CacheMiss { + path: measure::cache_path(source), + name: source.display().to_string(), + })? + } else { + let list = compiler.measure(source)?; + // A preview writes nothing, the cache included. + if !options.dry_run { + measure::write_cache(source, &list)?; + } + list + }; + + measured.insert( + source.clone(), + list.iter() + .map(|entry| (entry.name.clone(), entry.constraints())) + .collect(), + ); + } + Ok(measured) +} + +/// Rewrites one file's annotations and records what changed and what could not be measured. +fn fill_file( + file: &Work, + measured: &BTreeMap>, + tag: &crate::doc::Tag, + options: &Options, + outcome: &mut Outcome, +) -> Result<(), FillError> { + let source = match &file.source { + Source::Found(source) => source, + Source::Missing(tried) => { + outcome.lines.push(unmeasurable_line(&file.path, tried)); + outcome.unmeasured += file.sites.len(); + return Ok(()); + } + }; + let constraints = measured.get(source); + + let mut edits = Vec::new(); + for site in &file.sites { + let Some(measurement) = constraints.and_then(|found| found.get(&site.circuit)) else { + outcome + .lines + .push(unmeasured_line(&file.path, site, source)); + outcome.unmeasured += 1; + continue; + }; + + let value = measurement.value(); + if value == site.value { + continue; + } + + outcome.lines.push(format!( + "{}: fill: {tag} {} -> {value}", + at(&file.path, site.position), + site.value + )); + edits.push(Edit { + position: site.position, + message: String::new(), + kind: EditKind::Doc { + range: site.doc.range.clone(), + indent: site.doc.indent, + op: DocOp::SetTagValue { + line: site.line_offset, + tag: tag.to_string(), + value, + }, + }, + }); + } + + if edits.is_empty() { + return Ok(()); + } + + outcome.filled += edits.len(); + outcome.files += 1; + if !options.dry_run { + let newline = newline_of(&file.text); + write_atomically(&file.path, &apply(&file.text, &edits, newline))?; + } + Ok(()) +} + +fn unmeasured_line(path: &Path, site: &ConstraintSite, source: &Path) -> String { + format!( + "{}: {UNMEASURED}: circuit `{}` has no measurement in {}", + at(path, site.position), + site.circuit, + source.display() + ) +} + +fn unmeasurable_line(path: &Path, tried: &[PathBuf]) -> String { + let tried: Vec = tried + .iter() + .map(|path| path.display().to_string()) + .collect(); + format!( + "{}: {UNMEASURABLE}: no measurement source for {}; tried {}", + at(path, Position::file_start()), + path.display(), + if tried.is_empty() { + "nothing".to_owned() + } else { + tried.join(", ") + } + ) +} + +fn at(path: &Path, position: Position) -> String { + format!("{}:{}:{}", path.display(), position.line, position.column) +} + +#[cfg(test)] +mod tests { + use super::Outcome; + + #[test] + fn the_summary_counts_values_files_and_gaps() { + let outcome = Outcome { + lines: Vec::new(), + filled: 12, + files: 4, + unmeasured: 1, + }; + + assert_eq!( + outcome.summary(), + "12 values filled in 4 files, 1 unmeasured" + ); + } +} diff --git a/crates/compact-lint/src/fix.rs b/crates/compact-lint/src/fix.rs index 88e42bd7..20770e87 100644 --- a/crates/compact-lint/src/fix.rs +++ b/crates/compact-lint/src/fix.rs @@ -6,7 +6,7 @@ use thiserror::Error; use crate::config::Config; use crate::doc::Tag; -use crate::edit::{DocOp, Edit, EditKind, apply, newline_of}; +use crate::edit::{DocOp, Edit, EditKind, WriteError, apply, newline_of, write_atomically}; use crate::model::DeclKind; use crate::report::Position; use crate::rules::{Issue, LintError, Linter}; @@ -33,12 +33,8 @@ pub enum FixError { #[source] source: std::io::Error, }, - #[error("cannot write {path}")] - Write { - path: PathBuf, - #[source] - source: std::io::Error, - }, + #[error(transparent)] + Write(#[from] WriteError), } /// Everything the `fix` subcommand needs, already resolved from flags. @@ -286,30 +282,6 @@ fn skeleton( format!("{}{newline}{margin}", lines.join(newline)) } -/// Writes through a sibling temporary file, so a failed write never truncates the source. -fn write_atomically(path: &Path, text: &str) -> Result<(), FixError> { - let temporary = path.with_extension("compact.tmp"); - - std::fs::write(&temporary, text).map_err(|source| FixError::Write { - path: temporary.clone(), - source, - })?; - let permissions = std::fs::metadata(path) - .map_err(|source| FixError::Read { - path: path.to_owned(), - source, - })? - .permissions(); - std::fs::set_permissions(&temporary, permissions).map_err(|source| FixError::Write { - path: temporary.clone(), - source, - })?; - std::fs::rename(&temporary, path).map_err(|source| FixError::Write { - path: path.to_owned(), - source, - }) -} - /// The line `fix` prints for one edit. #[must_use] pub fn line(path: &Path, position: Position, message: &str) -> String { diff --git a/crates/compact-lint/src/lib.rs b/crates/compact-lint/src/lib.rs index 2eb94bb3..99ade4b5 100644 --- a/crates/compact-lint/src/lib.rs +++ b/crates/compact-lint/src/lib.rs @@ -4,6 +4,8 @@ //! declaration against the per-kind doc-comment template in `compact-lint.toml`, and //! yields one [`rules::Issue`] per violation. `check` renders an issue as a //! [`report::Finding`]; `fix` renders the repairable ones as an [`edit::Edit`]. +//! `fill-constraints` takes the other path: [`measure`] compiles a contract and +//! [`fill`] writes the measured values into the annotations that already exist. #![forbid(unsafe_code)] @@ -12,9 +14,12 @@ pub mod config; pub mod discover; pub mod doc; pub mod edit; +pub mod fill; pub mod fix; pub mod format; +pub mod measure; pub mod model; pub mod report; pub mod rules; +pub mod source; pub mod target; diff --git a/crates/compact-lint/src/main.rs b/crates/compact-lint/src/main.rs index e47c785d..b264b392 100644 --- a/crates/compact-lint/src/main.rs +++ b/crates/compact-lint/src/main.rs @@ -9,10 +9,11 @@ use std::process::ExitCode; use anyhow::{Context, Result}; use clap::{Parser, Subcommand}; +use tempfile::TempDir; use compact_lint::check::{self, Outcome}; -use compact_lint::fix; use compact_lint::format::{COMPACT_BIN_ENV, DEFAULT_COMPACT_BIN}; +use compact_lint::{fill, fix}; /// Exit code for a run that produced findings, or a `--dry-run` that would edit. const EXIT_FINDINGS: u8 = 1; @@ -37,6 +38,8 @@ enum Command { Check(CheckArgs), /// Rewrite doc comments so the rules `fix` covers stop reporting. Fix(FixArgs), + /// Measure every tagged circuit and write the values into its constraints tag. + FillConstraints(FillArgs), } #[derive(Debug, clap::Args)] @@ -75,6 +78,32 @@ struct FixArgs { dry_run: bool, } +#[derive(Debug, clap::Args)] +struct FillArgs { + /// Files or directories to fill; defaults to the config's include globs. + paths: Vec, + + /// Config file to use instead of searching upward for compact-lint.toml. + #[arg(long, value_name = "FILE")] + config: Option, + + /// Report the changes without writing them. + #[arg(long)] + dry_run: bool, + + /// Read the .circuit-info.json caches instead of compiling. + #[arg(long)] + no_compile: bool, + + /// Path to the `compact` binary. + #[arg(long, value_name = "PATH", env = COMPACT_BIN_ENV)] + compact_bin: Option, + + /// Directory the compiler writes to; kept after the run when given. + #[arg(long, value_name = "DIR")] + artifacts: Option, +} + fn main() -> ExitCode { match run() { Ok(code) => code, @@ -92,6 +121,7 @@ fn run() -> Result { match cli.command { Command::Check(args) => run_check(args, &cwd), Command::Fix(args) => run_fix(args, &cwd), + Command::FillConstraints(args) => run_fill(args, &cwd), } } @@ -133,6 +163,53 @@ fn run_fix(args: FixArgs, cwd: &std::path::Path) -> Result { }) } +fn run_fill(args: FillArgs, cwd: &std::path::Path) -> Result { + let (artifacts, temporary) = artifacts_dir(args.artifacts)?; + + let options = fill::Options { + paths: args.paths, + config_path: args.config, + dry_run: args.dry_run, + no_compile: args.no_compile, + compact_bin: args + .compact_bin + .unwrap_or_else(|| OsString::from(DEFAULT_COMPACT_BIN)), + artifacts, + }; + + let outcome = fill::run(&options, cwd).context("filling the constraints")?; + emit_lines(&outcome.lines, &outcome.summary()).context("writing the report")?; + + drop(temporary); + Ok(if outcome.unmeasured == 0 { + ExitCode::SUCCESS + } else { + ExitCode::from(EXIT_FINDINGS) + }) +} + +/// The artifacts directory, plus the temporary one to remove once the run ends. +fn artifacts_dir(given: Option) -> Result<(PathBuf, Option)> { + if let Some(path) = given { + return Ok((path, None)); + } + + let directory = tempfile::tempdir().context("creating the artifacts directory")?; + Ok((directory.path().to_owned(), Some(directory))) +} + +fn emit_lines(lines: &[String], summary: &str) -> std::io::Result<()> { + let stdout = std::io::stdout(); + let mut out = stdout.lock(); + for line in lines { + writeln!(out, "{line}")?; + } + out.flush()?; + + eprintln!("{summary}"); + Ok(()) +} + fn emit_findings(outcome: &Outcome) -> std::io::Result<()> { let stdout = std::io::stdout(); let mut out = stdout.lock(); diff --git a/crates/compact-lint/src/measure.rs b/crates/compact-lint/src/measure.rs new file mode 100644 index 00000000..954bc137 --- /dev/null +++ b/crates/compact-lint/src/measure.rs @@ -0,0 +1,602 @@ +//! Measuring a circuit's proving key size and row count with `compact compile`. +//! +//! `k` and `rows` reach only the compiler's terminal progress output, so the compile runs +//! under a pty and the transcript is parsed. Results are cached in the +//! `.circuit-info.json` file the TypeScript builder writes, in the same shape. + +use std::collections::BTreeMap; +use std::ffi::{OsStr, OsString}; +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use portable_pty::{CommandBuilder, PtySize, native_pty_system}; +use serde::{Deserialize, Serialize}; +use thiserror::Error; + +/// The measurement cache, written beside the compiled source. +pub const CACHE_FILE_NAME: &str = ".circuit-info.json"; + +/// The compiler's own report of the circuits it built, under the artifacts directory. +const CONTRACT_INFO_PATH: [&str; 2] = ["compiler", "contract-info.json"]; + +/// Compiler-output lines kept in a failure report. +const TAIL_LINES: usize = 20; + +/// Terminal geometry for the compile; a wide row keeps a progress line off the wrap. +const PTY_SIZE: PtySize = PtySize { + rows: 60, + cols: 200, + pixel_width: 0, + pixel_height: 0, +}; + +#[derive(Debug, Error)] +pub enum MeasureError { + #[error("cannot run `{binary}` under a pty")] + Spawn { + binary: String, + #[source] + source: Box, + }, + #[error("cannot read the compiler output for {file}")] + Transcript { + file: PathBuf, + #[source] + cause: std::io::Error, + }, + #[error("compiling {file} failed:\n{tail}")] + Compile { file: PathBuf, tail: String }, + #[error("cannot read {path}")] + Read { + path: PathBuf, + #[source] + source: std::io::Error, + }, + #[error("cannot write {path}")] + Write { + path: PathBuf, + #[source] + source: std::io::Error, + }, + #[error("cannot parse {path}")] + Parse { + path: PathBuf, + #[source] + source: serde_json::Error, + }, + #[error("{path} has no cached measurement for {name}; drop --no-compile to compile it")] + CacheMiss { path: PathBuf, name: String }, +} + +/// One circuit's measured constraints. +#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)] +pub struct Constraints { + pub k: u32, + pub rows: u32, +} + +impl Constraints { + /// The annotation value, the one spelling `check` accepts. + #[must_use] + pub fn value(self) -> String { + format!("k={}, rows={}", self.k, self.rows) + } +} + +/// One entry of the `.circuit-info.json` cache. +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] +pub struct Measurement { + pub name: String, + pub k: u32, + pub rows: u32, +} + +impl Measurement { + #[must_use] + pub const fn constraints(&self) -> Constraints { + Constraints { + k: self.k, + rows: self.rows, + } + } +} + +/// The `.circuit-info.json` shape, shared with the TypeScript builder. +#[derive(Clone, Debug, Default, Deserialize, Serialize)] +struct CircuitInfo { + #[serde(rename = "generatedAt")] + generated_at: String, + files: BTreeMap>, +} + +/// The compiler's circuit list; only `proof` circuits carry constraints. +#[derive(Debug, Deserialize)] +struct ContractInfo { + #[serde(default)] + circuits: Vec, +} + +#[derive(Debug, Deserialize)] +struct ContractCircuit { + name: String, + #[serde(default = "proves")] + proof: bool, +} + +/// An absent `proof` flag predates the field, when every circuit was proved. +const fn proves() -> bool { + true +} + +/// One `compact compile` invocation, reused for every source in a run. +pub struct Compiler { + pub binary: OsString, + /// Toolchain version passed as `+`. + pub version: Option, + /// Where each source's output directory is created. + pub artifacts: PathBuf, + /// The child's working directory, so a relative source path resolves as it reads. + pub cwd: PathBuf, +} + +impl Compiler { + /// Compiles one source and returns the circuits the compiler measured. + /// # Errors + /// Returns an error when the binary cannot run, the compile fails, or the + /// artifacts cannot be read. + pub fn measure(&self, source: &Path) -> Result, MeasureError> { + let stem = source + .file_stem() + .unwrap_or_else(|| OsStr::new("contract")) + .to_owned(); + let output = self.artifacts.join(&stem); + std::fs::create_dir_all(&output).map_err(|cause| MeasureError::Write { + path: output.clone(), + source: cause, + })?; + + let (status, raw) = self.spawn(source, &output)?; + let cleaned = clean(&raw); + if status != 0 { + return Err(MeasureError::Compile { + file: source.to_owned(), + tail: tail(&cleaned, TAIL_LINES), + }); + } + + let mut measured = parse(&cleaned); + if let Some(proved) = proved_circuits(&output)? { + measured.retain(|measurement| proved.contains(&measurement.name)); + } + Ok(measured) + } + + /// Runs the compile under a pty and returns its exit code and raw transcript. + fn spawn(&self, source: &Path, output: &Path) -> Result<(i32, String), MeasureError> { + let pty = native_pty_system(); + let pair = pty + .openpty(PTY_SIZE) + .map_err(|cause| self.spawn_error(cause))?; + + let mut command = CommandBuilder::new(&self.binary); + command.arg("compile"); + if let Some(version) = &self.version { + command.arg(format!("+{version}")); + } + command.arg(source); + command.arg(output); + command.env("TERM", "xterm-256color"); + command.cwd(&self.cwd); + + let mut child = pair + .slave + .spawn_command(command) + .map_err(|cause| self.spawn_error(cause))?; + drop(pair.slave); + + let mut reader = pair + .master + .try_clone_reader() + .map_err(|cause| self.spawn_error(cause))?; + let mut raw = Vec::new(); + reader + .read_to_end(&mut raw) + .map_err(|cause| MeasureError::Transcript { + file: source.to_owned(), + cause, + })?; + + let status = child.wait().map_err(|cause| MeasureError::Transcript { + file: source.to_owned(), + cause, + })?; + drop(pair.master); + + let code = i32::try_from(status.exit_code()).unwrap_or(i32::MAX); + Ok((code, String::from_utf8_lossy(&raw).into_owned())) + } + + fn spawn_error(&self, cause: anyhow::Error) -> MeasureError { + MeasureError::Spawn { + binary: self.binary.to_string_lossy().into_owned(), + source: cause.into(), + } + } +} + +/// The names of the circuits the compiler proved, or `None` without a contract report. +fn proved_circuits(output: &Path) -> Result>, MeasureError> { + let path = CONTRACT_INFO_PATH + .iter() + .fold(output.to_owned(), |path, segment| path.join(segment)); + if !path.is_file() { + return Ok(None); + } + + let text = std::fs::read_to_string(&path).map_err(|source| MeasureError::Read { + path: path.clone(), + source, + })?; + let info: ContractInfo = + serde_json::from_str(&text).map_err(|source| MeasureError::Parse { path, source })?; + + Ok(Some( + info.circuits + .into_iter() + .filter(|circuit| circuit.proof) + .map(|circuit| circuit.name) + .collect(), + )) +} + +/// Reads a source's entry from the cache beside it. +/// # Errors +/// Returns an error when the cache is unreadable or malformed. +pub fn read_cache(source: &Path) -> Result>, MeasureError> { + let path = cache_path(source); + if !path.is_file() { + return Ok(None); + } + + let info = load_cache(&path)?; + Ok(info.files.get(&file_key(source)).cloned()) +} + +/// Writes a source's entry into the cache beside it, keeping every other entry. +/// # Errors +/// Returns an error when the cache is unreadable, malformed or unwritable. +pub fn write_cache(source: &Path, measured: &[Measurement]) -> Result { + let path = cache_path(source); + let mut info = if path.is_file() { + load_cache(&path)? + } else { + CircuitInfo::default() + }; + + info.generated_at = timestamp(SystemTime::now()); + info.files.insert(file_key(source), measured.to_vec()); + + let mut text = serde_json::to_string_pretty(&info).map_err(|source| MeasureError::Parse { + path: path.clone(), + source, + })?; + text.push('\n'); + std::fs::write(&path, text).map_err(|source| MeasureError::Write { + path: path.clone(), + source, + })?; + Ok(path) +} + +fn load_cache(path: &Path) -> Result { + let text = std::fs::read_to_string(path).map_err(|source| MeasureError::Read { + path: path.to_owned(), + source, + })?; + serde_json::from_str(&text).map_err(|source| MeasureError::Parse { + path: path.to_owned(), + source, + }) +} + +/// The cache sits in the source's own directory. +#[must_use] +pub fn cache_path(source: &Path) -> PathBuf { + source + .parent() + .unwrap_or_else(|| Path::new(".")) + .join(CACHE_FILE_NAME) +} + +/// Entries are keyed by the source's file name, not its path. +fn file_key(source: &Path) -> String { + source + .file_name() + .unwrap_or_default() + .to_string_lossy() + .into_owned() +} + +/// Strips ANSI escapes, spinner frames and carriage-return redraws from pty output. +#[must_use] +pub fn clean(raw: &str) -> String { + let stripped = strip_escapes(raw); + let mut out = String::with_capacity(stripped.len()); + for (index, line) in stripped.split('\n').enumerate() { + if index > 0 { + out.push('\n'); + } + out.push_str(&clean_line(line)); + } + out +} + +/// The compiler redraws a line over itself, so only the text after the last `\r` is visible. +fn clean_line(line: &str) -> String { + let body = line.strip_suffix('\r').unwrap_or(line); + let visible = body.rsplit('\r').next().unwrap_or(body); + + let mut out = String::with_capacity(visible.len()); + let mut spaced = false; + for character in visible.chars() { + if is_spinner(character) { + continue; + } + if character.is_whitespace() { + spaced = true; + continue; + } + if spaced && !out.is_empty() { + out.push(' '); + } + spaced = false; + out.push(character); + } + out +} + +/// Braille frames and the tick / cross the compiler marks a finished circuit with. +fn is_spinner(character: char) -> bool { + matches!(character, '\u{2800}'..='\u{28ff}' | 'βœ“' | 'βœ”' | 'βœ—' | '✘') +} + +/// Drops CSI, OSC and character-set escape sequences, keeping the visible text. +fn strip_escapes(raw: &str) -> String { + let mut out = String::with_capacity(raw.len()); + let mut characters = raw.chars(); + + while let Some(character) = characters.next() { + if character != '\u{1b}' { + out.push(character); + continue; + } + match characters.next() { + // A CSI sequence runs to its first byte in the 0x40..0x7e range. + Some('[') => { + for parameter in characters.by_ref() { + if ('\u{40}'..='\u{7e}').contains(¶meter) { + break; + } + } + } + // An OSC sequence runs to a BEL or a string terminator. + Some(']') => { + let mut escaped = false; + for parameter in characters.by_ref() { + if parameter == '\u{7}' || (escaped && parameter == '\\') { + break; + } + escaped = parameter == '\u{1b}'; + } + } + Some('(' | ')') => { + characters.next(); + } + _ => {} + } + } + out +} + +/// Every measured circuit in a cleaned transcript; the last line for a name wins. +#[must_use] +pub fn parse(cleaned: &str) -> Vec { + let mut found: BTreeMap = BTreeMap::new(); + for line in cleaned.lines() { + if let Some(measurement) = parse_line(line) { + found.insert(measurement.name.clone(), measurement); + } + } + found.into_values().collect() +} + +/// Matches `circuit "" (k=, rows=)`, the compiler's per-circuit progress line. +fn parse_line(line: &str) -> Option { + let after = line.split_once("circuit ")?.1.trim_start(); + let (name, rest) = after.strip_prefix('"')?.split_once('"')?; + let fields = rest.trim_start().strip_prefix('(')?.split_once(')')?.0; + let (k, rows) = fields.split_once(',')?; + + Some(Measurement { + name: name.to_owned(), + k: field(k, "k")?, + rows: field(rows, "rows")?, + }) +} + +/// One `=` field of a progress line. +fn field(text: &str, name: &str) -> Option { + text.trim() + .strip_prefix(name)? + .trim_start() + .strip_prefix('=')? + .trim() + .parse() + .ok() +} + +/// The last `keep` non-blank lines of a cleaned transcript, with repeats dropped. +#[must_use] +pub fn tail(cleaned: &str, keep: usize) -> String { + let mut lines: Vec<&str> = Vec::new(); + for line in cleaned.lines().map(str::trim) { + if line.is_empty() || lines.last() == Some(&line) { + continue; + } + lines.push(line); + } + + let start = lines.len().saturating_sub(keep); + lines[start..].join("\n") +} + +/// An RFC 3339 UTC timestamp, the spelling the TypeScript builder writes. +fn timestamp(now: SystemTime) -> String { + let seconds = now + .duration_since(UNIX_EPOCH) + .map_or(0, |since| since.as_secs()); + let (days, rest) = (seconds / 86_400, seconds % 86_400); + let (year, month, day) = civil_date(i64::try_from(days).unwrap_or(0)); + + format!( + "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.000Z", + rest / 3600, + (rest % 3600) / 60, + rest % 60 + ) +} + +/// Days since the epoch to a civil date, by Howard Hinnant's `civil_from_days`. +fn civil_date(days: i64) -> (i64, i64, i64) { + let shifted = days + 719_468; + let era = shifted.div_euclid(146_097); + let day_of_era = shifted.rem_euclid(146_097); + let year_of_era = + (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365; + let year = year_of_era + era * 400; + let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100); + let shifted_month = (5 * day_of_year + 2) / 153; + + let day = day_of_year - (153 * shifted_month + 2) / 5 + 1; + let month = if shifted_month < 10 { + shifted_month + 3 + } else { + shifted_month - 9 + }; + (year + i64::from(month <= 2), month, day) +} + +#[cfg(test)] +mod tests { + use super::{ + CACHE_FILE_NAME, Measurement, civil_date, clean, parse, read_cache, tail, timestamp, + write_cache, + }; + use std::path::Path; + use std::time::{Duration, UNIX_EPOCH}; + + /// A pty transcript of `compact compile … MockOwnable.compact`, trimmed to two frames. + fn transcript() -> String { + std::fs::read_to_string( + Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/fill-transcript/pty.txt"), + ) + .expect("the captured transcript is readable") + } + + fn measurement(name: &str, k: u32, rows: u32) -> Measurement { + Measurement { + name: name.to_owned(), + k, + rows, + } + } + + #[test] + fn a_pty_transcript_yields_one_measurement_per_circuit() { + let measured = parse(&clean(&transcript())); + + assert_eq!( + measured, + [ + measurement("_transferOwnership", 10, 598), + measurement("_unsafeTransferOwnership", 13, 4868), + measurement("_unsafeUncheckedTransferOwnership", 10, 595), + measurement("assertOnlyOwner", 13, 4273), + measurement("owner", 7, 74), + measurement("renounceOwnership", 13, 4277), + measurement("transferOwnership", 13, 4871), + ] + ); + } + + #[test] + fn the_last_line_for_a_name_wins_over_the_partial_frames_above_it() { + let frames = " circuit \"owner\" (k=7)\n circuit \"owner\" (k=7, rows=9999)\n circuit \"owner\" (k=7, rows=74)\n"; + + assert_eq!(parse(frames), [measurement("owner", 7, 74)]); + } + + #[test] + fn escapes_and_redraws_leave_only_the_visible_text() { + let raw = "\u{1b}[2K circuit \"owner\" \u{1b}[32m|\u{1b}[0m \r\u{1b}[2K circuit \"owner\" (k=7, rows=74)\r\n"; + + assert_eq!(clean(raw), "circuit \"owner\" (k=7, rows=74)\n"); + } + + #[test] + fn a_line_without_both_fields_is_not_a_measurement() { + assert!(parse(" circuit \"owner\" (k=7)\n").is_empty()); + assert!(parse("Compiling 7 circuits:\n").is_empty()); + assert!(parse(" circuit \"owner\" (rows=74, k=7)\n").is_empty()); + } + + #[test] + fn a_failure_tail_keeps_the_last_distinct_lines() { + let cleaned = "one\none\ntwo\n\nthree\nfour\n"; + + assert_eq!(tail(cleaned, 2), "three\nfour"); + assert_eq!(tail(cleaned, 20), "one\ntwo\nthree\nfour"); + } + + #[test] + fn a_cache_write_keeps_the_entries_of_other_sources() { + let directory = tempfile::tempdir().expect("a temporary directory is available"); + let source = directory.path().join("MockOwnable.compact"); + std::fs::write( + directory.path().join(CACHE_FILE_NAME), + "{\n \"generatedAt\": \"2026-01-01T00:00:00.000Z\",\n \"files\": {\n \"Other.compact\": [{ \"name\": \"run\", \"k\": 3, \"rows\": 4 }]\n }\n}\n", + ) + .expect("the cache is writable"); + + let written = [measurement("owner", 7, 74)]; + write_cache(&source, &written).expect("the cache is writable"); + + assert_eq!( + read_cache(&source).expect("the cache is readable"), + Some(written.to_vec()) + ); + assert_eq!( + read_cache(&directory.path().join("Other.compact")).expect("the cache is readable"), + Some(vec![measurement("run", 3, 4)]) + ); + } + + #[test] + fn a_source_with_no_cache_entry_reads_as_absent() { + let directory = tempfile::tempdir().expect("a temporary directory is available"); + + assert_eq!( + read_cache(&directory.path().join("Gone.compact")).expect("the cache is readable"), + None + ); + } + + #[test] + fn a_timestamp_renders_as_utc_rfc_3339() { + let moment = UNIX_EPOCH + Duration::from_hours(490_896); + + assert_eq!(timestamp(moment), "2026-01-01T00:00:00.000Z"); + assert_eq!(civil_date(0), (1970, 1, 1)); + } +} diff --git a/crates/compact-lint/src/rules.rs b/crates/compact-lint/src/rules.rs index eb723ddd..889b302b 100644 --- a/crates/compact-lint/src/rules.rs +++ b/crates/compact-lint/src/rules.rs @@ -31,6 +31,23 @@ pub struct DocRef { pub indent: usize, } +/// A constraints annotation already present on an exported non-pure circuit. +/// +/// `check` only reports the annotations it faults; `fill-constraints` rewrites every one +/// of them, so it reads the sites directly. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ConstraintSite { + /// The circuit's name, which is the name its measurement carries. + pub circuit: String, + /// Position of the tag's `@`. + pub position: Position, + /// 0-based line index of the tag inside the doc comment. + pub line_offset: usize, + /// The annotation's value, first line only. + pub value: String, + pub doc: DocRef, +} + /// One rule violation, carrying what `check` prints and what `fix` needs to repair it. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Issue { @@ -205,6 +222,34 @@ impl Linter { Ok(issues) } + /// Every constraints annotation in one file, in source order. + /// + /// A file holding a parse defect yields none, because its declarations are not + /// trustworthy enough to rewrite. + /// # Errors + /// Returns an error when tree-sitter produces no tree for `source`. + pub fn constraint_sites( + &mut self, + display: &Path, + source: &str, + config: &Config, + ) -> Result, LintError> { + let tree = self + .parser + .parse(source, None) + .ok_or_else(|| LintError::NoTree(display.to_owned()))?; + let root = tree.root_node(); + + if first_defect(root).is_some() { + return Ok(Vec::new()); + } + + Ok(declarations(root, source) + .iter() + .filter_map(|declaration| constraint_site(declaration, &config.constraints.tag)) + .collect()) + } + /// Checks one file. `display` is the path printed in findings. /// # Errors /// Returns an error when tree-sitter produces no tree for `source`. @@ -348,6 +393,26 @@ const fn takes_constraints(declaration: &Declaration) -> bool { matches!(declaration.kind, DeclKind::Circuit) && declaration.exported && !declaration.pure } +/// The annotation on one declaration, where it is a named circuit that takes one. +fn constraint_site(declaration: &Declaration, tag: &Tag) -> Option { + if !takes_constraints(declaration) { + return None; + } + let attached = declaration.doc.as_ref()?; + let occurrence = attached.comment.first(tag)?; + + Some(ConstraintSite { + circuit: declaration.name.clone()?, + position: attached.tag_position(occurrence), + line_offset: occurrence.line_offset, + value: value_of(occurrence).to_owned(), + doc: DocRef { + range: attached.range.clone(), + indent: attached.start_column, + }, + }) +} + fn check_constraints( declaration: &Declaration, doc: &DocRef, @@ -373,8 +438,7 @@ fn check_constraints( return; }; - // The annotation is one line; anything below it is prose, not part of the value. - let value = occurrence.value.lines().next().unwrap_or_default().trim(); + let value = value_of(occurrence); let position = attached.tag_position(occurrence); let Some(placeholders) = parse_constraints(value) else { @@ -395,6 +459,11 @@ fn check_constraints( } } +/// The annotation is one line; anything below it is prose, not part of the value. +fn value_of(occurrence: &crate::doc::TagOccurrence) -> &str { + occurrence.value.lines().next().unwrap_or_default().trim() +} + /// Matches `k=,*rows=`; returns whether either field is a `?` placeholder. fn parse_constraints(value: &str) -> Option { let rest = value.strip_prefix("k=")?; diff --git a/crates/compact-lint/src/source.rs b/crates/compact-lint/src/source.rs new file mode 100644 index 00000000..2a5c3944 --- /dev/null +++ b/crates/compact-lint/src/source.rs @@ -0,0 +1,249 @@ +//! Which contract a file's circuits are measured through. +//! +//! A library module does not compile on its own, so its constraints are measured through +//! the mock contract that exports the same circuit names. + +use std::path::{Component, Path, PathBuf}; + +use crate::config::{Config, ConfigError}; + +/// Where a file's measurements come from. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Source { + /// The measurement source, which is the file itself for a contract. + Found(PathBuf), + /// No candidate exists, in the order they were tried. + Missing(Vec), +} + +/// The templates and globs, compiled once per run. +pub struct Resolver { + /// Directory the config's relative paths and globs are anchored at. + base: PathBuf, + cwd: PathBuf, + own: globset::GlobSet, + sources: Vec, + overrides: Vec<(PathBuf, PathBuf)>, +} + +impl Resolver { + /// # Errors + /// Returns an error when a `constraints.self` pattern is not a valid glob. + pub fn new(config: &Config, base: &Path, cwd: &Path) -> Result { + Ok(Self { + base: base.to_owned(), + cwd: cwd.to_owned(), + own: config.own_set(base)?, + sources: config.constraints.sources.clone(), + overrides: config + .constraints + .overrides + .iter() + .map(|(file, source)| (base.join(file), base.join(source))) + .collect(), + }) + } + + /// Resolves one file, trying overrides, then the `self` globs, then the templates. + #[must_use] + pub fn resolve(&self, file: &Path) -> Source { + let absolute = normalize(&self.absolute(file)); + let mut tried = Vec::new(); + + for (from, to) in &self.overrides { + if normalize(from) == absolute { + return self.first_existing(std::iter::once(self.shown(to)), &mut tried); + } + } + + let relative = absolute.strip_prefix(&self.base).unwrap_or(&absolute); + if self.own.is_match(relative) { + return Source::Found(file.to_owned()); + } + + self.first_existing(self.candidates(file), &mut tried) + } + + /// The templates expanded for one file, in config order. + fn candidates(&self, file: &Path) -> impl Iterator { + let directory = file.parent().unwrap_or(Path::new(".")).to_owned(); + let parent = directory.parent().map(Path::to_owned); + let stem = file + .file_stem() + .unwrap_or_default() + .to_string_lossy() + .into_owned(); + + self.sources + .clone() + .into_iter() + .filter_map(move |template| expand(&template, &directory, parent.as_deref(), &stem)) + } + + fn first_existing( + &self, + candidates: impl Iterator, + tried: &mut Vec, + ) -> Source { + for candidate in candidates { + if self.absolute(&candidate).is_file() { + return Source::Found(candidate); + } + tried.push(candidate); + } + Source::Missing(std::mem::take(tried)) + } + + /// Paths under the working directory print relative to it, as the file list does. + fn shown(&self, path: &Path) -> PathBuf { + path.strip_prefix(&self.cwd).unwrap_or(path).to_owned() + } + + fn absolute(&self, path: &Path) -> PathBuf { + if path.is_absolute() { + path.to_owned() + } else { + self.cwd.join(path) + } + } +} + +/// Fills a template's placeholders; a template needing `{parent}` at the root drops out. +fn expand(template: &str, directory: &Path, parent: Option<&Path>, stem: &str) -> Option { + let mut filled = template.replace("{stem}", stem); + + if filled.contains("{parent}") { + filled = filled.replace("{parent}", &display(parent?)); + } + if filled.contains("{dir}") { + filled = filled.replace("{dir}", &display(directory)); + } + Some(normalize(Path::new(&filled))) +} + +/// An empty directory renders as `.`, so a template never collapses into an absolute path. +fn display(path: &Path) -> String { + let text = path.to_string_lossy(); + if text.is_empty() { + ".".to_owned() + } else { + text.into_owned() + } +} + +/// Resolves `.` and `..` lexically, so two spellings of one path compare equal. +fn normalize(path: &Path) -> PathBuf { + let mut out = PathBuf::new(); + for component in path.components() { + match component { + Component::CurDir => {} + Component::ParentDir => { + out.pop(); + } + other => out.push(other), + } + } + out +} + +#[cfg(test)] +mod tests { + use super::{Resolver, Source}; + use crate::config::Config; + use std::path::{Path, PathBuf}; + + /// A tree with a module, its mock one level up, an extension and a preset. + fn tree() -> tempfile::TempDir { + let directory = tempfile::tempdir().expect("a temporary directory is available"); + for relative in [ + "src/access/Ownable.compact", + "src/access/test/mocks/MockOwnable.compact", + "src/token/extensions/Capped.compact", + "src/token/test/mocks/MockCapped.compact", + "src/multisig/presets/Vault.compact", + "src/utils/Utils.compact", + "src/utils/test/mocks/MockUtilities.compact", + "src/orphan/Orphan.compact", + ] { + let path = directory.path().join(relative); + std::fs::create_dir_all(path.parent().expect("the path has a directory")) + .expect("the tree is writable"); + std::fs::write(&path, "").expect("the source is writable"); + } + directory + } + + fn resolve(config: &Config, root: &Path, file: &str) -> Source { + Resolver::new(config, root, root) + .expect("the globs compile") + .resolve(Path::new(file)) + } + + #[test] + fn a_module_measures_through_the_mock_beside_it() { + let tree = tree(); + + assert_eq!( + resolve( + &Config::default(), + tree.path(), + "src/access/Ownable.compact" + ), + Source::Found(PathBuf::from("src/access/test/mocks/MockOwnable.compact")) + ); + } + + #[test] + fn an_extension_measures_through_the_mock_in_its_parent() { + let tree = tree(); + + assert_eq!( + resolve( + &Config::default(), + tree.path(), + "src/token/extensions/Capped.compact" + ), + Source::Found(PathBuf::from("src/token/test/mocks/MockCapped.compact")) + ); + } + + #[test] + fn a_preset_matching_a_self_glob_measures_through_itself() { + let tree = tree(); + let mut config = Config::default(); + config.constraints.own = vec!["**/presets/**".to_owned()]; + + assert_eq!( + resolve(&config, tree.path(), "src/multisig/presets/Vault.compact"), + Source::Found(PathBuf::from("src/multisig/presets/Vault.compact")) + ); + } + + #[test] + fn an_override_wins_over_the_templates() { + let tree = tree(); + let mut config = Config::default(); + config.constraints.overrides.insert( + "src/utils/Utils.compact".to_owned(), + "src/utils/test/mocks/MockUtilities.compact".to_owned(), + ); + + assert_eq!( + resolve(&config, tree.path(), "src/utils/Utils.compact"), + Source::Found(PathBuf::from("src/utils/test/mocks/MockUtilities.compact")) + ); + } + + #[test] + fn a_file_with_no_candidate_reports_the_paths_it_tried() { + let tree = tree(); + + assert_eq!( + resolve(&Config::default(), tree.path(), "src/orphan/Orphan.compact"), + Source::Missing(vec![ + PathBuf::from("src/orphan/test/mocks/MockOrphan.compact"), + PathBuf::from("src/test/mocks/MockOrphan.compact"), + ]) + ); + } +} diff --git a/crates/compact-lint/src/target.rs b/crates/compact-lint/src/target.rs index aaa5e16b..cae31a58 100644 --- a/crates/compact-lint/src/target.rs +++ b/crates/compact-lint/src/target.rs @@ -15,10 +15,12 @@ pub enum TargetError { Discover(#[from] DiscoverError), } -/// The config and the files it selects, shared by `check` and `fix`. +/// The config and the files it selects, shared by every subcommand. pub struct Target { pub config: Config, pub files: Vec, + /// Directory the config's own relative paths and globs are anchored at. + pub base: PathBuf, } /// Resolves the config and the file list for one run. @@ -56,7 +58,11 @@ pub fn resolve( }; let files = files.iter().map(|path| display_path(path, cwd)).collect(); - Ok(Target { config, files }) + Ok(Target { + config, + files, + base, + }) } /// Paths under the working directory print relative to it; anything else prints as is. diff --git a/crates/compact-lint/tests/fill.rs b/crates/compact-lint/tests/fill.rs new file mode 100644 index 00000000..8c8cbcba --- /dev/null +++ b/crates/compact-lint/tests/fill.rs @@ -0,0 +1,289 @@ +//! `compact-lint fill-constraints` end to end, against a fake `compact` binary. +//! +//! The fake at `tests/fixtures/fill-fake-compact/bin/compact` prints the compiler's +//! progress lines for a hard-coded table and writes a matching contract report, so the +//! pty path is exercised where the real toolchain is absent. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; + +use assert_cmd::prelude::*; +use tempfile::TempDir; + +/// Exit code for a run that left a tagged circuit unmeasured. +const EXIT_UNMEASURED: i32 = 1; + +/// Exit code for a config, IO or compiler error. +const EXIT_ERROR: i32 = 2; + +fn fixtures() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures") +} + +fn case(name: &str) -> PathBuf { + fixtures() + .join(format!("fill-{name}")) + .canonicalize() + .expect("the fixture case exists") +} + +fn fake_compact() -> PathBuf { + fixtures() + .join("fill-fake-compact/bin/compact") + .canonicalize() + .expect("the fake compiler exists") +} + +fn binary() -> Command { + Command::cargo_bin("compact-lint").expect("the binary is built alongside this test") +} + +/// Copies the case's config and `before/` tree into a fresh temporary directory. +fn work(name: &str) -> TempDir { + let directory = TempDir::new().expect("a temporary directory is available"); + let root = case(name); + + std::fs::copy( + root.join("compact-lint.toml"), + directory.path().join("compact-lint.toml"), + ) + .expect("the case has a config"); + copy_tree(&root.join("before"), directory.path()); + + directory +} + +fn copy_tree(from: &Path, to: &Path) { + for entry in std::fs::read_dir(from).expect("the tree is readable") { + let entry = entry.expect("the entry is readable"); + let target = to.join(entry.file_name()); + if entry.path().is_dir() { + std::fs::create_dir_all(&target).expect("the target is writable"); + copy_tree(&entry.path(), &target); + } else { + std::fs::copy(entry.path(), &target).expect("the file is copyable"); + } + } +} + +/// Every `.compact` file under `root`, keyed by its path relative to it. +fn sources(root: &Path) -> BTreeMap> { + let mut found = BTreeMap::new(); + collect(root, root, &mut found); + found +} + +fn collect(root: &Path, directory: &Path, out: &mut BTreeMap>) { + for entry in std::fs::read_dir(directory).expect("the tree is readable") { + let entry = entry.expect("the entry is readable"); + let path = entry.path(); + if path.is_dir() { + collect(root, &path, out); + } else if path + .extension() + .is_some_and(|extension| extension == "compact") + { + let relative = path.strip_prefix(root).expect("the path is under the root"); + out.insert( + relative.to_owned(), + std::fs::read(&path).expect("the source is readable"), + ); + } + } +} + +fn expected(name: &str) -> String { + std::fs::read_to_string(case(name).join("expected.txt")).expect("the case has an expectation") +} + +/// Runs `fill-constraints` inside `directory`, pointed at the fake compiler. +fn fill(directory: &Path, extra: &[&str]) -> Output { + binary() + .current_dir(directory) + .args(["fill-constraints", "--compact-bin"]) + .arg(fake_compact()) + .args(extra) + .output() + .expect("the binary ran") +} + +fn code_and_stdout(output: &Output) -> (i32, String) { + ( + output.status.code().expect("the binary was not signalled"), + String::from_utf8_lossy(&output.stdout).into_owned(), + ) +} + +/// Runs another subcommand inside `directory` and returns its exit code and stdout. +fn run(directory: &Path, args: &[&str]) -> (i32, String) { + let output = binary() + .current_dir(directory) + .args(args) + .output() + .expect("the binary ran"); + code_and_stdout(&output) +} + +/// The whole contract of a measurable case: it fills, it lands, it settles, it previews. +/// +/// `settled` is what a second run still reports, which is the unmeasured circuits. +fn assert_case(name: &str, extra: &[&str], exit: i32, settled: &str) { + let directory = work(name); + let root = directory.path(); + + let (code, stdout) = code_and_stdout(&fill(root, extra)); + assert_eq!(stdout, expected(name), "stdout for case {name}"); + assert_eq!(code, exit, "exit code for case {name}"); + assert_eq!( + sources(root), + sources(&case(name).join("after")), + "rewritten sources for case {name}" + ); + + let (code, stdout) = run(root, &["check", "--strict", "--no-format"]); + assert_eq!(stdout, "", "check is clean after filling case {name}"); + assert_eq!(code, 0, "check exit code after filling case {name}"); + + let (code, stdout) = code_and_stdout(&fill(root, extra)); + assert_eq!(stdout, settled, "a second run on case {name}"); + assert_eq!(code, exit, "second run exit code for case {name}"); + + let preview = work(name); + let before = sources(preview.path()); + let mut arguments = extra.to_vec(); + arguments.push("--dry-run"); + let (code, stdout) = code_and_stdout(&fill(preview.path(), &arguments)); + assert_eq!(stdout, expected(name), "dry-run stdout for case {name}"); + assert_eq!(code, exit, "dry-run exit code for case {name}"); + assert_eq!( + sources(preview.path()), + before, + "dry-run wrote to case {name}" + ); +} + +#[test] +fn placeholders_and_stale_values_take_the_measurement() { + let unmeasured = expected("basic") + .lines() + .filter(|line| line.contains("constraints-unmeasured")) + .collect::>() + .join("\n"); + + assert_case("basic", &[], EXIT_UNMEASURED, &format!("{unmeasured}\n")); +} + +#[test] +fn a_preset_matching_a_self_glob_compiles_itself() { + assert_case("self", &[], 0, ""); +} + +#[test] +fn an_override_names_the_contract_that_measures_a_file() { + assert_case("override", &[], 0, ""); +} + +#[test] +fn a_seeded_cache_fills_without_a_compiler() { + assert_case("no-compile", &["--no-compile"], 0, ""); +} + +#[test] +fn a_circuit_the_report_marks_unproved_stays_unmeasured() { + let directory = work("basic"); + let (_, stdout) = code_and_stdout(&fill(directory.path(), &[])); + + assert!( + stdout.contains("circuit `initialize` has no measurement"), + "{stdout}" + ); + assert!(!stdout.contains("k=5, rows=10"), "{stdout}"); +} + +#[test] +fn a_file_with_no_measurement_source_reports_once_and_exits_one() { + let directory = work("missing-source"); + let root = directory.path(); + let before = sources(root); + + let (code, stdout) = code_and_stdout(&fill(root, &[])); + + assert_eq!(stdout, expected("missing-source")); + assert_eq!(code, EXIT_UNMEASURED); + assert_eq!(sources(root), before); +} + +#[test] +fn a_failed_compile_exits_two_with_the_output_tail() { + let directory = work("compiler-fails"); + let output = fill(directory.path(), &[]); + let stderr = String::from_utf8_lossy(&output.stderr); + + assert_eq!(output.status.code(), Some(EXIT_ERROR)); + assert!(stderr.contains("MockBroken.compact"), "{stderr}"); + assert!(stderr.contains("type mismatch"), "{stderr}"); + assert!(!stderr.contains('\u{1b}'), "the raw pty stream leaked"); +} + +#[test] +fn a_missing_cache_entry_exits_two_and_names_the_flag() { + let directory = work("basic"); + let output = fill(directory.path(), &["--no-compile"]); + let stderr = String::from_utf8_lossy(&output.stderr); + + assert_eq!(output.status.code(), Some(EXIT_ERROR)); + assert!(stderr.contains(".circuit-info.json"), "{stderr}"); + assert!(stderr.contains("--no-compile"), "{stderr}"); +} + +#[test] +fn a_compile_writes_the_cache_the_builder_shares() { + let directory = work("override"); + fill(directory.path(), &[]); + + let cache = std::fs::read_to_string( + directory + .path() + .join("src/utils/test/mocks/.circuit-info.json"), + ) + .expect("the cache was written"); + + assert!(cache.contains("\"generatedAt\""), "{cache}"); + assert!(cache.contains("\"MockUtilities.compact\""), "{cache}"); + assert!(cache.contains("\"rows\": 310"), "{cache}"); +} + +#[test] +fn the_summary_goes_to_stderr_and_the_changes_to_stdout() { + let directory = work("basic"); + let output = fill(directory.path(), &[]); + + assert_eq!( + String::from_utf8_lossy(&output.stderr).trim_end(), + "2 values filled in 1 files, 1 unmeasured" + ); + assert!( + String::from_utf8_lossy(&output.stdout).contains(": fill: "), + "the changes belong on stdout" + ); +} + +#[test] +fn kept_artifacts_land_in_the_directory_the_flag_names() { + let directory = work("override"); + let artifacts = directory.path().join("artifacts"); + fill( + directory.path(), + &[ + "--artifacts", + artifacts.to_str().expect("the path is UTF-8"), + ], + ); + + assert!( + artifacts + .join("MockUtilities/compiler/contract-info.json") + .is_file() + ); +} diff --git a/crates/compact-lint/tests/fixtures/fill-basic/after/src/access/Ownable.compact b/crates/compact-lint/tests/fixtures/fill-basic/after/src/access/Ownable.compact new file mode 100644 index 00000000..ee555b2e --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-basic/after/src/access/Ownable.compact @@ -0,0 +1,33 @@ +/** + * @module Ownable + * @description Test fixture. + */ +export module Ownable { + /** + * @description Returns the owner. + * + * @constraints k=7, rows=74 + */ + export circuit owner(): [] { } + + /** + * @description Transfers ownership. + * + * @constraints k=13, rows=4871 + */ + export circuit transferOwnership(): [] { } + + /** + * @description Renounces ownership. + * + * @constraints k=13, rows=4277 + */ + export circuit renounceOwnership(): [] { } + + /** + * @description Sets the first owner. + * + * @constraints k=5, rows=10 + */ + export circuit initialize(): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/fill-basic/after/src/access/test/mocks/MockOwnable.compact b/crates/compact-lint/tests/fixtures/fill-basic/after/src/access/test/mocks/MockOwnable.compact new file mode 100644 index 00000000..bbb1510e --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-basic/after/src/access/test/mocks/MockOwnable.compact @@ -0,0 +1,6 @@ +/** + * @module MockStub + * @description Compiled by the fake compiler, never read by it. + */ +export module MockStub { +} diff --git a/crates/compact-lint/tests/fixtures/fill-basic/before/src/access/Ownable.compact b/crates/compact-lint/tests/fixtures/fill-basic/before/src/access/Ownable.compact new file mode 100644 index 00000000..d65ad1a5 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-basic/before/src/access/Ownable.compact @@ -0,0 +1,33 @@ +/** + * @module Ownable + * @description Test fixture. + */ +export module Ownable { + /** + * @description Returns the owner. + * + * @constraints k=?, rows=? + */ + export circuit owner(): [] { } + + /** + * @description Transfers ownership. + * + * @constraints k=9, rows=42 + */ + export circuit transferOwnership(): [] { } + + /** + * @description Renounces ownership. + * + * @constraints k=13, rows=4277 + */ + export circuit renounceOwnership(): [] { } + + /** + * @description Sets the first owner. + * + * @constraints k=5, rows=10 + */ + export circuit initialize(): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/fill-basic/before/src/access/test/mocks/MockOwnable.compact b/crates/compact-lint/tests/fixtures/fill-basic/before/src/access/test/mocks/MockOwnable.compact new file mode 100644 index 00000000..bbb1510e --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-basic/before/src/access/test/mocks/MockOwnable.compact @@ -0,0 +1,6 @@ +/** + * @module MockStub + * @description Compiled by the fake compiler, never read by it. + */ +export module MockStub { +} diff --git a/crates/compact-lint/tests/fixtures/fill-basic/compact-lint.toml b/crates/compact-lint/tests/fixtures/fill-basic/compact-lint.toml new file mode 100644 index 00000000..e5a81d85 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-basic/compact-lint.toml @@ -0,0 +1,8 @@ +version = 1 +exclude = ["**/test/mocks/**"] + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] diff --git a/crates/compact-lint/tests/fixtures/fill-basic/expected.txt b/crates/compact-lint/tests/fixtures/fill-basic/expected.txt new file mode 100644 index 00000000..a9bdabc9 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-basic/expected.txt @@ -0,0 +1,3 @@ +src/access/Ownable.compact:9:6: fill: @constraints k=?, rows=? -> k=7, rows=74 +src/access/Ownable.compact:16:6: fill: @constraints k=9, rows=42 -> k=13, rows=4871 +src/access/Ownable.compact:30:6: constraints-unmeasured: circuit `initialize` has no measurement in src/access/test/mocks/MockOwnable.compact diff --git a/crates/compact-lint/tests/fixtures/fill-compiler-fails/before/src/broken/Broken.compact b/crates/compact-lint/tests/fixtures/fill-compiler-fails/before/src/broken/Broken.compact new file mode 100644 index 00000000..ce4dfefe --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-compiler-fails/before/src/broken/Broken.compact @@ -0,0 +1,12 @@ +/** + * @module Broken + * @description Test fixture. + */ +export module Broken { + /** + * @description Runs. + * + * @constraints k=?, rows=? + */ + export circuit run(): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/fill-compiler-fails/before/src/broken/test/mocks/MockBroken.compact b/crates/compact-lint/tests/fixtures/fill-compiler-fails/before/src/broken/test/mocks/MockBroken.compact new file mode 100644 index 00000000..bbb1510e --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-compiler-fails/before/src/broken/test/mocks/MockBroken.compact @@ -0,0 +1,6 @@ +/** + * @module MockStub + * @description Compiled by the fake compiler, never read by it. + */ +export module MockStub { +} diff --git a/crates/compact-lint/tests/fixtures/fill-compiler-fails/compact-lint.toml b/crates/compact-lint/tests/fixtures/fill-compiler-fails/compact-lint.toml new file mode 100644 index 00000000..e5a81d85 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-compiler-fails/compact-lint.toml @@ -0,0 +1,8 @@ +version = 1 +exclude = ["**/test/mocks/**"] + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] diff --git a/crates/compact-lint/tests/fixtures/fill-fake-compact/bin/compact b/crates/compact-lint/tests/fixtures/fill-fake-compact/bin/compact new file mode 100755 index 00000000..b975fe04 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-fake-compact/bin/compact @@ -0,0 +1,70 @@ +#!/bin/sh +# Stand-in for `compact compile`, so the fill tests run where the toolchain is absent. +# It prints the progress lines the real compiler puts on its terminal and writes the +# matching contract report, for a table keyed by the source file name. + +set -e + +if [ "$1" != "compile" ]; then + echo "fake compact: unsupported command $*" >&2 + exit 64 +fi +shift + +case "$1" in + +*) shift ;; +esac + +source=$1 +output=$2 +name=$(basename "$source") + +# name k rows proof +case "$name" in + MockOwnable.compact) + table="owner 7 74 true +transferOwnership 13 4871 true +renounceOwnership 13 4277 true +initialize 5 10 false" + ;; + Vault.compact) + table="deposit 12 2048 true +withdraw 14 8192 true" + ;; + MockUtilities.compact) + table="hash 9 310 true" + ;; + MockBroken.compact) + echo "Compiling 1 circuits:" + echo "Exception in thread \"main\" java.lang.RuntimeException" + echo " Error: type mismatch at $source line 12" + echo " Error: compilation aborted" >&2 + exit 3 + ;; + *) + echo "fake compact: no table for $name" >&2 + exit 65 + ;; +esac + +count=$(echo "$table" | wc -l | tr -d ' ') +echo "Compiling $count circuits:" + +echo "$table" | while read -r circuit k rows proof; do + [ -n "$circuit" ] || continue + # The real compiler redraws the line, so the same circuit appears without rows first. + printf ' circuit "%s" (k=%s)\n' "$circuit" "$k" + printf ' circuit "%s" (k=%s, rows=%s)\n' "$circuit" "$k" "$rows" +done + +mkdir -p "$output/compiler" +{ + echo '{' + echo ' "compiler-version": "0.0.0-fake",' + echo ' "circuits": [' + echo "$table" | awk 'NF { if (n++) printf ",\n"; printf " { \"name\": \"%s\", \"pure\": false, \"proof\": %s }", $1, $4 } END { printf "\n" }' + echo ' ]' + echo '}' +} > "$output/compiler/contract-info.json" + +echo "Overall progress [====================] $count/$count" diff --git a/crates/compact-lint/tests/fixtures/fill-missing-source/after/src/orphan/Orphan.compact b/crates/compact-lint/tests/fixtures/fill-missing-source/after/src/orphan/Orphan.compact new file mode 100644 index 00000000..c2bc805d --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-missing-source/after/src/orphan/Orphan.compact @@ -0,0 +1,12 @@ +/** + * @module Orphan + * @description Test fixture. + */ +export module Orphan { + /** + * @description Runs. + * + * @constraints k=?, rows=? + */ + export circuit run(): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/fill-missing-source/before/src/orphan/Orphan.compact b/crates/compact-lint/tests/fixtures/fill-missing-source/before/src/orphan/Orphan.compact new file mode 100644 index 00000000..c2bc805d --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-missing-source/before/src/orphan/Orphan.compact @@ -0,0 +1,12 @@ +/** + * @module Orphan + * @description Test fixture. + */ +export module Orphan { + /** + * @description Runs. + * + * @constraints k=?, rows=? + */ + export circuit run(): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/fill-missing-source/compact-lint.toml b/crates/compact-lint/tests/fixtures/fill-missing-source/compact-lint.toml new file mode 100644 index 00000000..584076c2 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-missing-source/compact-lint.toml @@ -0,0 +1,7 @@ +version = 1 + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] diff --git a/crates/compact-lint/tests/fixtures/fill-missing-source/expected.txt b/crates/compact-lint/tests/fixtures/fill-missing-source/expected.txt new file mode 100644 index 00000000..1a91510b --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-missing-source/expected.txt @@ -0,0 +1 @@ +src/orphan/Orphan.compact:1:1: constraints-unmeasurable: no measurement source for src/orphan/Orphan.compact; tried src/orphan/test/mocks/MockOrphan.compact, src/test/mocks/MockOrphan.compact diff --git a/crates/compact-lint/tests/fixtures/fill-no-compile/after/src/access/Ownable.compact b/crates/compact-lint/tests/fixtures/fill-no-compile/after/src/access/Ownable.compact new file mode 100644 index 00000000..73ff33b1 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-no-compile/after/src/access/Ownable.compact @@ -0,0 +1,12 @@ +/** + * @module Ownable + * @description Test fixture. + */ +export module Ownable { + /** + * @description Returns the owner. + * + * @constraints k=7, rows=74 + */ + export circuit owner(): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/fill-no-compile/after/src/access/test/mocks/MockOwnable.compact b/crates/compact-lint/tests/fixtures/fill-no-compile/after/src/access/test/mocks/MockOwnable.compact new file mode 100644 index 00000000..bbb1510e --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-no-compile/after/src/access/test/mocks/MockOwnable.compact @@ -0,0 +1,6 @@ +/** + * @module MockStub + * @description Compiled by the fake compiler, never read by it. + */ +export module MockStub { +} diff --git a/crates/compact-lint/tests/fixtures/fill-no-compile/before/src/access/Ownable.compact b/crates/compact-lint/tests/fixtures/fill-no-compile/before/src/access/Ownable.compact new file mode 100644 index 00000000..ac40ca75 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-no-compile/before/src/access/Ownable.compact @@ -0,0 +1,12 @@ +/** + * @module Ownable + * @description Test fixture. + */ +export module Ownable { + /** + * @description Returns the owner. + * + * @constraints k=?, rows=? + */ + export circuit owner(): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/fill-no-compile/before/src/access/test/mocks/MockOwnable.compact b/crates/compact-lint/tests/fixtures/fill-no-compile/before/src/access/test/mocks/MockOwnable.compact new file mode 100644 index 00000000..bbb1510e --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-no-compile/before/src/access/test/mocks/MockOwnable.compact @@ -0,0 +1,6 @@ +/** + * @module MockStub + * @description Compiled by the fake compiler, never read by it. + */ +export module MockStub { +} diff --git a/crates/compact-lint/tests/fixtures/fill-no-compile/compact-lint.toml b/crates/compact-lint/tests/fixtures/fill-no-compile/compact-lint.toml new file mode 100644 index 00000000..e5a81d85 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-no-compile/compact-lint.toml @@ -0,0 +1,8 @@ +version = 1 +exclude = ["**/test/mocks/**"] + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] diff --git a/crates/compact-lint/tests/fixtures/fill-no-compile/expected.txt b/crates/compact-lint/tests/fixtures/fill-no-compile/expected.txt new file mode 100644 index 00000000..0e5a1e3f --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-no-compile/expected.txt @@ -0,0 +1 @@ +src/access/Ownable.compact:9:6: fill: @constraints k=?, rows=? -> k=7, rows=74 diff --git a/crates/compact-lint/tests/fixtures/fill-override/after/src/utils/Utils.compact b/crates/compact-lint/tests/fixtures/fill-override/after/src/utils/Utils.compact new file mode 100644 index 00000000..5e0f5238 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-override/after/src/utils/Utils.compact @@ -0,0 +1,12 @@ +/** + * @module Utils + * @description Test fixture. + */ +export module Utils { + /** + * @description Hashes a value. + * + * @constraints k=9, rows=310 + */ + export circuit hash(): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/fill-override/after/src/utils/test/mocks/MockUtilities.compact b/crates/compact-lint/tests/fixtures/fill-override/after/src/utils/test/mocks/MockUtilities.compact new file mode 100644 index 00000000..bbb1510e --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-override/after/src/utils/test/mocks/MockUtilities.compact @@ -0,0 +1,6 @@ +/** + * @module MockStub + * @description Compiled by the fake compiler, never read by it. + */ +export module MockStub { +} diff --git a/crates/compact-lint/tests/fixtures/fill-override/before/src/utils/Utils.compact b/crates/compact-lint/tests/fixtures/fill-override/before/src/utils/Utils.compact new file mode 100644 index 00000000..37b6b594 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-override/before/src/utils/Utils.compact @@ -0,0 +1,12 @@ +/** + * @module Utils + * @description Test fixture. + */ +export module Utils { + /** + * @description Hashes a value. + * + * @constraints k=?, rows=? + */ + export circuit hash(): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/fill-override/before/src/utils/test/mocks/MockUtilities.compact b/crates/compact-lint/tests/fixtures/fill-override/before/src/utils/test/mocks/MockUtilities.compact new file mode 100644 index 00000000..bbb1510e --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-override/before/src/utils/test/mocks/MockUtilities.compact @@ -0,0 +1,6 @@ +/** + * @module MockStub + * @description Compiled by the fake compiler, never read by it. + */ +export module MockStub { +} diff --git a/crates/compact-lint/tests/fixtures/fill-override/compact-lint.toml b/crates/compact-lint/tests/fixtures/fill-override/compact-lint.toml new file mode 100644 index 00000000..4f16f104 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-override/compact-lint.toml @@ -0,0 +1,11 @@ +version = 1 +exclude = ["**/test/mocks/**"] + +[constraints.overrides] +"src/utils/Utils.compact" = "src/utils/test/mocks/MockUtilities.compact" + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] diff --git a/crates/compact-lint/tests/fixtures/fill-override/expected.txt b/crates/compact-lint/tests/fixtures/fill-override/expected.txt new file mode 100644 index 00000000..f718af96 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-override/expected.txt @@ -0,0 +1 @@ +src/utils/Utils.compact:9:6: fill: @constraints k=?, rows=? -> k=9, rows=310 diff --git a/crates/compact-lint/tests/fixtures/fill-self/after/src/multisig/presets/Vault.compact b/crates/compact-lint/tests/fixtures/fill-self/after/src/multisig/presets/Vault.compact new file mode 100644 index 00000000..cec7bfe1 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-self/after/src/multisig/presets/Vault.compact @@ -0,0 +1,19 @@ +/** + * @module Vault + * @description Test fixture. + */ +export module Vault { + /** + * @description Deposits a coin. + * + * @constraints k=12, rows=2048 + */ + export circuit deposit(): [] { } + + /** + * @description Withdraws a coin. + * + * @constraints k=14, rows=8192 + */ + export circuit withdraw(): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/fill-self/before/src/multisig/presets/Vault.compact b/crates/compact-lint/tests/fixtures/fill-self/before/src/multisig/presets/Vault.compact new file mode 100644 index 00000000..e020fe16 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-self/before/src/multisig/presets/Vault.compact @@ -0,0 +1,19 @@ +/** + * @module Vault + * @description Test fixture. + */ +export module Vault { + /** + * @description Deposits a coin. + * + * @constraints k=?, rows=? + */ + export circuit deposit(): [] { } + + /** + * @description Withdraws a coin. + * + * @constraints k=?, rows=? + */ + export circuit withdraw(): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/fill-self/compact-lint.toml b/crates/compact-lint/tests/fixtures/fill-self/compact-lint.toml new file mode 100644 index 00000000..85451328 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-self/compact-lint.toml @@ -0,0 +1,10 @@ +version = 1 + +[constraints] +self = ["**/presets/**"] + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] diff --git a/crates/compact-lint/tests/fixtures/fill-self/expected.txt b/crates/compact-lint/tests/fixtures/fill-self/expected.txt new file mode 100644 index 00000000..88499e9a --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-self/expected.txt @@ -0,0 +1,2 @@ +src/multisig/presets/Vault.compact:9:6: fill: @constraints k=?, rows=? -> k=12, rows=2048 +src/multisig/presets/Vault.compact:16:6: fill: @constraints k=?, rows=? -> k=14, rows=8192 diff --git a/crates/compact-lint/tests/fixtures/fill-transcript/pty.txt b/crates/compact-lint/tests/fixtures/fill-transcript/pty.txt new file mode 100644 index 00000000..a52a733e --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-transcript/pty.txt @@ -0,0 +1,19 @@ +Compiling 7 circuits: + circuit "_transferOwnership" |  circuit "_transferOwnership" (k=10) |  circuit "_transferOwnership" (k=10, rows=598) |  circuit "_transferOwnership" (k=10, rows=598) | + circuit "_unsafeTransferOwnership" |    circuit "_transferOwnership" (k=10, rows=598) | + circuit "_unsafeTransferOwnership" (k=13) |    circuit "_transferOwnership" (k=10, rows=598) | + circuit "_unsafeTransferOwnership" (k=13, rows=4868) |    circuit "_transferOwnership" (k=10, rows=598) | + circuit "_unsafeTransferOwnership" (k=13, rows=4868) | + circuit "_unsafeUncheckedTransferOwnership" |    circuit "_unsafeUncheckedTransferOwnership" (k=10, rows=595)   + circuit "assertOnlyOwner" (k=13, rows=4273)   + circuit "owner" (k=7, rows=74)   + circuit "renounceOwnership" (k=13, rows=4277)   + circuit "transferOwnership" (k=13, rows=4871)   +Overall progress [====================] 7/7          circuit "_transferOwnership" (k=10, rows=598)   + circuit "_unsafeTransferOwnership" (k=13, rows=4868)   + circuit "_unsafeUncheckedTransferOwnership" (k=10, rows=595)   + circuit "assertOnlyOwner" (k=13, rows=4273)   + circuit "owner" (k=7, rows=74)   + circuit "renounceOwnership" (k=13, rows=4277)   + circuit "transferOwnership" (k=13, rows=4871)   +Overall progress [====================] 7/7 From 2ad67efb6b79188c38615cbe32dcd2d89c0ab0f0 Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Tue, 15 Sep 2026 11:06:54 +0200 Subject: [PATCH 06/56] test(compact-lint): track the seeded cache fixture The root .gitignore drops every .circuit-info.json, so the cache the fill-no-compile case reads never reached CI and the test failed there. --- .gitignore | 2 ++ .../before/src/access/test/mocks/.circuit-info.json | 12 ++++++++++++ 2 files changed, 14 insertions(+) create mode 100644 crates/compact-lint/tests/fixtures/fill-no-compile/before/src/access/test/mocks/.circuit-info.json diff --git a/.gitignore b/.gitignore index e2ebbac1..a66d7c3e 100644 --- a/.gitignore +++ b/.gitignore @@ -36,6 +36,8 @@ artifacts/ # compact-compiler's per-source circuit-info cache, written next to the # .compact sources it measures. .circuit-info.json +# Except the seeded cache the fill-constraints tests read. +!crates/compact-lint/tests/fixtures/**/.circuit-info.json midnight-level-db compactc diff --git a/crates/compact-lint/tests/fixtures/fill-no-compile/before/src/access/test/mocks/.circuit-info.json b/crates/compact-lint/tests/fixtures/fill-no-compile/before/src/access/test/mocks/.circuit-info.json new file mode 100644 index 00000000..0c0fa8e7 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-no-compile/before/src/access/test/mocks/.circuit-info.json @@ -0,0 +1,12 @@ +{ + "generatedAt": "2026-01-01T00:00:00.000Z", + "files": { + "MockOwnable.compact": [ + { + "name": "owner", + "k": 7, + "rows": 74 + } + ] + } +} From 80691d5128ed42476c08392738199ba8269983ce Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Tue, 15 Sep 2026 11:30:39 +0200 Subject: [PATCH 07/56] build(compact-lint): ship prebuilt binaries through npm Adds the @openzeppelin/compact-lint npm package, a Node bin that fetches the prebuilt compact-lint binary for the host from the GitHub release of the same version, verifies it against checksums.txt, caches it inside the package, and passes arguments and exit codes through. COMPACT_LINT_BINARY skips the download for source builds and air-gapped CI. * release.yml: compact-lint bumps package.json and the crate version together and refreshes Cargo.lock. * release-publish.yml: detection becomes its own job; a four-runner matrix builds the Linux and macOS binaries and the publish job creates the GitHub release with the assets before npm publish, so the package never points at a release that is not there yet. * Cargo.toml: stripped, thin-LTO release profile (3.3 MiB binary). * tests: target mapping, checksum verification, the download path against a local server, pass-through, and a guard that the npm and crate versions agree. --- .github/workflows/release-publish.yml | 175 +++++++++++++-- .github/workflows/release.yml | 40 ++++ .gitignore | 3 + Cargo.toml | 7 + README.md | 6 +- RELEASING.md | 40 +++- crates/compact-lint/README.md | 7 + packages/lint/CHANGELOG.md | 13 ++ packages/lint/LICENSE | 21 ++ packages/lint/README.md | 45 ++++ packages/lint/package.json | 43 ++++ packages/lint/src/binary.ts | 143 +++++++++++++ packages/lint/src/compactLint.ts | 52 +++++ packages/lint/test/binary.test.ts | 293 ++++++++++++++++++++++++++ packages/lint/test/version.test.ts | 22 ++ packages/lint/tsconfig.json | 21 ++ packages/lint/turbo.json | 11 + packages/lint/vitest.config.ts | 22 ++ yarn.lock | 13 ++ 19 files changed, 955 insertions(+), 22 deletions(-) create mode 100644 packages/lint/CHANGELOG.md create mode 100644 packages/lint/LICENSE create mode 100644 packages/lint/README.md create mode 100644 packages/lint/package.json create mode 100644 packages/lint/src/binary.ts create mode 100644 packages/lint/src/compactLint.ts create mode 100644 packages/lint/test/binary.test.ts create mode 100644 packages/lint/test/version.test.ts create mode 100644 packages/lint/tsconfig.json create mode 100644 packages/lint/turbo.json create mode 100644 packages/lint/vitest.config.ts diff --git a/.github/workflows/release-publish.yml b/.github/workflows/release-publish.yml index 09a30608..2e34bc08 100644 --- a/.github/workflows/release-publish.yml +++ b/.github/workflows/release-publish.yml @@ -19,30 +19,30 @@ on: - compact-builder - compact-cli - compact-deployer + - compact-lint - compact-simulator jobs: - publish: - name: Publish merged release + # Detection is its own job so the binary matrix and the publish both read the + # same answer. + detect: + name: Detect released package if: >- github.event_name == 'workflow_dispatch' || (github.event.pull_request.merged == true && contains(github.event.pull_request.labels.*.name, 'release')) runs-on: ubuntu-24.04 - environment: compact-npm-prod # Final approval gate before npm publish permissions: - contents: write # push the version tag - id-token: write # mint the npm OIDC credential and the provenance statement + contents: read - steps: - - name: Get github app token - uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0 - id: gh-app-token - with: - app-id: ${{ vars.GH_APP_ID }} - private-key: ${{ secrets.GH_APP_PRIVATE_KEY }} + outputs: + dir: ${{ steps.pkg.outputs.dir }} + name: ${{ steps.pkg.outputs.name }} + version: ${{ steps.pkg.outputs.version }} + dist_tag: ${{ steps.pkg.outputs.dist_tag }} + steps: # For pull_request runs: checkout the merge commit (deterministic view of # what was just merged). For manual dispatch: checkout the dispatched ref # (defaults to main but can be any branch β€” hotfix, release-prep, etc.). @@ -53,7 +53,6 @@ jobs: with: fetch-depth: 0 ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.merge_commit_sha || github.ref }} - token: ${{ steps.gh-app-token.outputs.token }} - name: Detect released package id: pkg @@ -69,6 +68,7 @@ jobs: compact-builder) DIR="builder" ;; compact-cli) DIR="cli" ;; compact-deployer) DIR="deployer" ;; + compact-lint) DIR="lint" ;; compact-simulator) DIR="simulator" ;; *) echo "::error::unknown package: $PKG" @@ -88,6 +88,7 @@ jobs: builder) PKG="compact-builder" ;; cli) PKG="compact-cli" ;; deployer) PKG="compact-deployer" ;; + lint) PKG="compact-lint" ;; simulator) PKG="compact-simulator" ;; *) echo "::error::unknown package directory: $DIR" @@ -135,6 +136,98 @@ jobs: echo "- Trigger: $EVENT" } >> $GITHUB_STEP_SUMMARY + # compact-lint ships a native binary per target, built on its own runner. The + # npm package downloads them, so they must reach the GitHub release first. + binaries: + name: Build compact-lint for ${{ matrix.target }} + needs: detect + if: needs.detect.outputs.name == 'compact-lint' + runs-on: ${{ matrix.runner }} + + permissions: + contents: read + + strategy: + fail-fast: false + matrix: + include: + - target: x86_64-unknown-linux-gnu + runner: ubuntu-24.04 + - target: aarch64-unknown-linux-gnu + runner: ubuntu-24.04-arm + - target: x86_64-apple-darwin + runner: macos-15-intel + - target: aarch64-apple-darwin + runner: macos-15 + + steps: + - name: Harden Runner + uses: step-security/harden-runner@05e31511f85b41b11d1cf0ef85d0992719546e2c # v2.21.0 + with: + egress-policy: audit + + - name: Check out target ref + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.merge_commit_sha || github.ref }} + + - name: Install the pinned toolchain + run: | + CHANNEL=$(grep -m1 '^channel' rust-toolchain.toml | cut -d'"' -f2) + rustup toolchain install "$CHANNEL" --profile minimal + rustup target add ${{ matrix.target }} + rustup show active-toolchain + + - name: Build + run: cargo build --release -p compact-lint --target ${{ matrix.target }} + + # Every target is built on its own native runner, so the binary runs here. + - name: Smoke test + run: target/${{ matrix.target }}/release/compact-lint --version + + - name: Stage the release asset + run: | + mkdir -p dist + cp target/${{ matrix.target }}/release/compact-lint dist/compact-lint-${{ matrix.target }} + + - name: Upload the release asset + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: compact-lint-${{ matrix.target }} + path: dist/compact-lint-${{ matrix.target }} + if-no-files-found: error + + publish: + name: Publish merged release + needs: [detect, binaries] + # `binaries` is skipped for every package but compact-lint, and a skipped + # dependency must not skip the publish. + if: >- + always() && + needs.detect.result == 'success' && + (needs.binaries.result == 'success' || needs.binaries.result == 'skipped') + runs-on: ubuntu-24.04 + environment: compact-npm-prod # Final approval gate before npm publish + + permissions: + contents: write # push the version tag and create the GitHub release + id-token: write # mint the npm OIDC credential and the provenance statement + + steps: + - name: Get github app token + uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0 + id: gh-app-token + with: + app-id: ${{ vars.GH_APP_ID }} + private-key: ${{ secrets.GH_APP_PRIVATE_KEY }} + + - name: Check out target ref + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 + ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.merge_commit_sha || github.ref }} + token: ${{ steps.gh-app-token.outputs.token }} + - name: Setup Node.js uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 with: @@ -148,11 +241,11 @@ jobs: run: yarn install --immutable - name: Build package - run: yarn build --filter=@openzeppelin/${{ steps.pkg.outputs.name }} + run: yarn build --filter=@openzeppelin/${{ needs.detect.outputs.name }} - name: Create and push tag env: - TAG: ${{ steps.pkg.outputs.name }}/v${{ steps.pkg.outputs.version }} + TAG: ${{ needs.detect.outputs.name }}/v${{ needs.detect.outputs.version }} run: | if git ls-remote --tags --exit-code origin "refs/tags/$TAG" >/dev/null; then echo "tag $TAG already on origin, leaving it in place" @@ -161,7 +254,55 @@ jobs: git push origin "$TAG" fi + - name: Download the release binaries + if: needs.detect.outputs.name == 'compact-lint' + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 + with: + path: dist + pattern: compact-lint-* + merge-multiple: true + + # Asset names only: the installed package looks each digest up by the name + # it downloads. + - name: Write the checksums + if: needs.detect.outputs.name == 'compact-lint' + working-directory: dist + run: | + sha256sum compact-lint-* > checksums.txt + cat checksums.txt + + # The npm package downloads these assets on first run, so the release has + # to carry them before the package reaches npm. + - name: Create the GitHub release + if: needs.detect.outputs.name == 'compact-lint' + env: + GH_TOKEN: ${{ steps.gh-app-token.outputs.token }} + TAG: ${{ needs.detect.outputs.name }}/v${{ needs.detect.outputs.version }} + VERSION: ${{ needs.detect.outputs.version }} + DIST_TAG: ${{ needs.detect.outputs.dist_tag }} + run: | + NOTES=$(awk -v v="$VERSION" ' + $0 ~ "^## " v "( |$)" { found = 1; next } + found && /^## / { exit } + found { print } + ' packages/lint/CHANGELOG.md) + if [[ -z "${NOTES//[[:space:]]/}" ]]; then + NOTES="$TAG" + fi + if gh release view "$TAG" >/dev/null 2>&1; then + gh release upload "$TAG" dist/* --clobber + else + ARGS=() + if [[ "$DIST_TAG" == "beta" ]]; then + ARGS+=(--prerelease) + fi + gh release create "$TAG" dist/* \ + --title "compact-lint v$VERSION" \ + --notes "$NOTES" \ + "${ARGS[@]}" + fi + - name: Publish to npm run: | - cd packages/${{ steps.pkg.outputs.dir }} - yarn npm publish --access public --provenance --tag ${{ steps.pkg.outputs.dist_tag }} + cd packages/${{ needs.detect.outputs.dir }} + yarn npm publish --access public --provenance --tag ${{ needs.detect.outputs.dist_tag }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 8ca63407..13360df6 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -11,6 +11,7 @@ on: - compact-builder - compact-cli - compact-deployer + - compact-lint - compact-simulator version_bump: description: "Version bump type (pre* strategies are beta-only)" @@ -89,6 +90,9 @@ jobs: "compact-deployer") echo "dir=deployer" >> $GITHUB_OUTPUT ;; + "compact-lint") + echo "dir=lint" >> $GITHUB_OUTPUT + ;; "compact-simulator") echo "dir=simulator" >> $GITHUB_OUTPUT ;; @@ -97,6 +101,15 @@ jobs: - name: Setup Environment uses: ./.github/actions/setup + # compact-lint's version lives in the crate too, and bumping it there + # rewrites Cargo.lock. + - name: Install the pinned toolchain + if: inputs.package == 'compact-lint' + run: | + CHANNEL=$(grep -m1 '^channel' rust-toolchain.toml | cut -d'"' -f2) + rustup toolchain install "$CHANNEL" --profile minimal + rustup show active-toolchain + - name: Run tests for package run: yarn test --filter=@openzeppelin/${{ inputs.package }} @@ -134,6 +147,20 @@ jobs: echo "- npm dist-tag: $DIST_TAG" } >> $GITHUB_STEP_SUMMARY + - name: Sync the crate version + if: inputs.package == 'compact-lint' + env: + NEW_VERSION: ${{ steps.version.outputs.new }} + run: | + sed -i "0,/^version = .*/s//version = \"$NEW_VERSION\"/" crates/compact-lint/Cargo.toml + # Resolving the workspace rewrites the crate's own Cargo.lock entry. + cargo metadata --format-version 1 > /tmp/cargo-metadata.json + ACTUAL=$(node -p "JSON.parse(require('fs').readFileSync('/tmp/cargo-metadata.json','utf8')).packages.find((p) => p.name === 'compact-lint').version") + if [[ "$ACTUAL" != "$NEW_VERSION" ]]; then + echo "::error::crates/compact-lint/Cargo.toml is at $ACTUAL, expected $NEW_VERSION" + exit 1 + fi + - name: Verify package contents run: | cd packages/${{ steps.pkg.outputs.dir }} @@ -156,6 +183,7 @@ jobs: fi - name: Commit version bump + if: inputs.package != 'compact-lint' uses: iarekylew00t/verified-bot-commit@42a042b0407248f3c0acac00c389e729e3476e86 # v2.3.5 with: message: "release: ${{ inputs.package }} v${{ steps.version.outputs.new }}" @@ -164,6 +192,18 @@ jobs: files: | packages/${{ steps.pkg.outputs.dir }}/package.json + - name: Commit version bump with the crate + if: inputs.package == 'compact-lint' + uses: iarekylew00t/verified-bot-commit@42a042b0407248f3c0acac00c389e729e3476e86 # v2.3.5 + with: + message: "release: ${{ inputs.package }} v${{ steps.version.outputs.new }}" + token: ${{ steps.gh-app-token.outputs.token }} + ref: ${{ steps.version.outputs.branch }} + files: | + packages/lint/package.json + crates/compact-lint/Cargo.toml + Cargo.lock + - name: Ensure release label exists env: GH_TOKEN: ${{ steps.gh-app-token.outputs.token }} diff --git a/.gitignore b/.gitignore index a66d7c3e..757ea362 100644 --- a/.gitignore +++ b/.gitignore @@ -66,6 +66,9 @@ vendor/ target/ .toolkit-cache/ +# compact-lint's release binary, cached inside the installed npm package. +packages/lint/.cache/ + coverage **/reports diff --git a/Cargo.toml b/Cargo.toml index 3e63a37e..a235a014 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,6 +8,13 @@ license = "MIT" repository = "https://github.com/OpenZeppelin/compact-tools" rust-version = "1.96" +# Release binaries ship as GitHub release assets, so size and speed both matter. +# Unwinding stays on: the error paths depend on it. +[profile.release] +strip = true +lto = "thin" +codegen-units = 1 + [workspace.lints.clippy] pedantic = { level = "warn", priority = -1 } diff --git a/README.md b/README.md index 4bbe406e..6ae796e2 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ Tools for compiling, building, testing, and deploying Compact smart contracts. T - [`packages/builder`](./packages/builder) β€” programmatic library that drives the Compact compiler + builder - [`packages/cli`](./packages/cli) β€” thin bin wrapper around the builder and deployer libraries (`compact-compiler`, `compact-builder`, `compact-deploy`) - [`packages/deployer`](./packages/deployer) β€” deployer library that submits a compiled contract to a Midnight network. Pins one Midnight stack: see [Supported stack](./packages/deployer/README.md#supported-stack) +- [`packages/lint`](./packages/lint) β€” bin wrapper around the [`compact-lint`](./crates/compact-lint) crate, the doc-comment linter for Compact sources - [`packages/simulator`](./packages/simulator) β€” TypeScript simulator to run and test Compact contracts locally See each package's README for usage, options, and examples. @@ -38,6 +39,9 @@ yarn add --dev @openzeppelin/compact-cli # Simulator β€” test Compact contracts locally yarn add --dev @openzeppelin/compact-simulator +# Linter β€” check doc comments in .compact sources +yarn add --dev @openzeppelin/compact-lint + # Deployer β€” deploy a compiled contract from TypeScript yarn add --dev @openzeppelin/compact-deployer ``` @@ -59,7 +63,7 @@ import { createSimulator } from '@openzeppelin/compact-simulator'; ## Requirements -- Node.js >= 22 for `packages/builder` and `packages/simulator`, >= 24 for `packages/cli` and `packages/deployer` +- Node.js >= 22 for `packages/builder` and `packages/simulator`, >= 24 for `packages/cli`, `packages/deployer` and `packages/lint` - Yarn 4 (Berry) - Turbo - Optional: Midnight Compact toolchain installed and available in `PATH` diff --git a/RELEASING.md b/RELEASING.md index a8ddbbe8..ed5e4965 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -49,7 +49,8 @@ release notes agree. - Create a git tag. - Publish the package to npm under the channel's dist-tag. 7. Once published, go to "Releases" and create a GitHub release using the - generated tag. Mark beta tags as prereleases. + generated tag. Mark beta tags as prereleases. `compact-lint` is the + exception: the workflow creates its release itself (see below). ## Graduating a beta to stable @@ -80,7 +81,7 @@ breaking change. After that, only `prerelease` moves the counter. Running ## First-release order -There's a one-step dependency chain across the four published packages: +There's a one-step dependency chain across the five published packages: ```text compact-cli (bin wrapper) @@ -88,6 +89,7 @@ compact-cli (bin wrapper) └─ depends on compact-deployer compact-builder (library) compact-deployer (library) +compact-lint (bin wrapper around the compact-lint crate) compact-simulator (library) ``` @@ -98,8 +100,38 @@ each dependent finds its deps already on npm: 1. `compact-builder` (no internal deps) 2. `compact-simulator` (no internal deps) 3. `compact-deployer` (no internal deps) -4. `compact-cli` (depends on `compact-builder` and `compact-deployer`; pull +4. `compact-lint` (no internal deps) +5. `compact-cli` (depends on `compact-builder` and `compact-deployer`; pull `main` first so both bump commits are present locally before triggering) -After the first release, the four packages version independently β€” bump any +After the first release, the five packages version independently β€” bump any one of them in isolation without re-publishing the others. + +## compact-lint + +`compact-lint` is a bin wrapper around the `compact-lint` crate, so its release +carries a native binary as well as an npm package. + +- The version lives in two files: `packages/lint/package.json` and + `crates/compact-lint/Cargo.toml`. The release workflow bumps the package, mirrors + the value into the crate, refreshes `Cargo.lock`, and commits all three. A unit + test in `packages/lint` fails when the two drift. +- The publish workflow builds four binaries before publishing, one per target, each + on its own runner: + + | Target | Runner | + | --- | --- | + | `x86_64-unknown-linux-gnu` | `ubuntu-24.04` | + | `aarch64-unknown-linux-gnu` | `ubuntu-24.04-arm` | + | `x86_64-apple-darwin` | `macos-15-intel` | + | `aarch64-apple-darwin` | `macos-15` | + +- It then creates the GitHub release `compact-lint/v` with the four assets + and a `checksums.txt`, and only then publishes to npm. The installed package + downloads its binary from that release, so the assets must be there first. For + every other package the GitHub release is still created by hand (step 7 above). +- Release notes come from the `## ` section of `packages/lint/CHANGELOG.md`, + falling back to the tag name. A `beta` dist-tag marks the release a prerelease. +- Before the first release, add `@openzeppelin/compact-lint` as a Trusted Publisher + on npmjs.org, naming this repo and `.github/workflows/release-publish.yml`. Every + new npm package needs this once, or the publish step cannot authenticate. diff --git a/crates/compact-lint/README.md b/crates/compact-lint/README.md index d85a415a..aa303996 100644 --- a/crates/compact-lint/README.md +++ b/crates/compact-lint/README.md @@ -6,6 +6,13 @@ per-kind template in `compact-lint.toml`, and prints one finding per line. `fix` rewrites the comments the repairable rules report. `fill-constraints` compiles the contracts and writes the measured `k` and `rows` into the annotations. +## Install + +- npm, no Rust toolchain needed: `yarn add -D @openzeppelin/compact-lint`, or + `npx @openzeppelin/compact-lint check`. The package downloads the release binary for + the host on first use. See [`packages/lint`](../../packages/lint). +- From source: `cargo install --path crates/compact-lint`. + ## Usage ```sh diff --git a/packages/lint/CHANGELOG.md b/packages/lint/CHANGELOG.md new file mode 100644 index 00000000..a6cdf5cf --- /dev/null +++ b/packages/lint/CHANGELOG.md @@ -0,0 +1,13 @@ +# Changelog + +All notable changes to `@openzeppelin/compact-lint` are documented in this +file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), +and this package adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## Unreleased + +### Added + +- `compact-lint` bin, a launcher that downloads the [`compact-lint`](../../crates/compact-lint) release binary for the host, verifies its SHA-256, and runs it diff --git a/packages/lint/LICENSE b/packages/lint/LICENSE new file mode 100644 index 00000000..e22ac902 --- /dev/null +++ b/packages/lint/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Zeppelin Group Ltd + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/lint/README.md b/packages/lint/README.md new file mode 100644 index 00000000..22f62d35 --- /dev/null +++ b/packages/lint/README.md @@ -0,0 +1,45 @@ +# @openzeppelin/compact-lint + +Bin wrapper around the [`compact-lint`](../../crates/compact-lint) Rust crate, the +doc-comment linter for Compact sources. The package itself is a thin launcher: it +resolves the native binary for the host and runs it with your arguments. + +## Install + +```bash +yarn add --dev @openzeppelin/compact-lint +``` + +```bash +npx @openzeppelin/compact-lint check +yarn compact-lint check contracts/src +yarn compact-lint fix --dry-run +``` + +Commands, flags, exit codes and `compact-lint.toml` are documented in the +[crate README](../../crates/compact-lint/README.md). + +## Where the binary comes from + +- Prebuilt binaries are attached to the `compact-lint/v` GitHub release, one + per target: `x86_64-unknown-linux-gnu`, `aarch64-unknown-linux-gnu`, + `x86_64-apple-darwin`, `aarch64-apple-darwin`. +- The first run downloads the one matching the host, checks its SHA-256 against the + release's `checksums.txt`, and caches it at `.cache/compact-lint--` + inside the installed package. Later runs print nothing and start it directly. +- Uninstalling the package removes the cache with it. +- No prebuilt binary for the host is a hard error: build the crate with + `cargo install --path crates/compact-lint` and point `COMPACT_LINT_BINARY` at it. + +## Environment + +| Variable | Effect | +| --- | --- | +| `COMPACT_LINT_BINARY` | Run this executable and skip the download. For local crate builds and air-gapped CI. | +| `COMPACT_LINT_DOWNLOAD_BASE` | Fetch the asset and `checksums.txt` from this base URL instead of the GitHub release. | +| `COMPACT_LINT_COMPACT_BIN` | Read by the linter itself: path to the `compact` binary. | + +## Requirements + +- Node.js >= 24 +- Linux or macOS, x86_64 or aarch64 diff --git a/packages/lint/package.json b/packages/lint/package.json new file mode 100644 index 00000000..d1451fa0 --- /dev/null +++ b/packages/lint/package.json @@ -0,0 +1,43 @@ +{ + "name": "@openzeppelin/compact-lint", + "description": "Doc-comment linter for Compact sources", + "version": "0.1.0", + "keywords": [ + "compact", + "lint", + "linter", + "doc-comments", + "midnight" + ], + "author": "OpenZeppelin Community ", + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/OpenZeppelin/compact-tools.git", + "directory": "packages/lint" + }, + "type": "module", + "files": [ + "dist", + "README.md", + "CHANGELOG.md", + "LICENSE" + ], + "engines": { + "node": ">=24" + }, + "bin": "dist/compactLint.js", + "scripts": { + "build": "tsc -p .", + "types": "tsc -p tsconfig.json --noEmit", + "test": "yarn vitest run", + "coverage": "yarn vitest run --coverage", + "clean": "git clean -fXd" + }, + "devDependencies": { + "@tsconfig/node24": "^24.0.3", + "@types/node": "26.1.2", + "typescript": "^6.0.3", + "vitest": "^4.1.9" + } +} diff --git a/packages/lint/src/binary.ts b/packages/lint/src/binary.ts new file mode 100644 index 00000000..02cbaa86 --- /dev/null +++ b/packages/lint/src/binary.ts @@ -0,0 +1,143 @@ +import { createHash, randomUUID } from 'node:crypto'; +import { + chmodSync, + existsSync, + mkdirSync, + renameSync, + writeFileSync, +} from 'node:fs'; +import { join } from 'node:path'; + +/** npm `platform-arch` pair to the Rust target triple the release assets are named after. */ +const TARGETS: Record = { + 'linux-x64': 'x86_64-unknown-linux-gnu', + 'linux-arm64': 'aarch64-unknown-linux-gnu', + 'darwin-x64': 'x86_64-apple-darwin', + 'darwin-arm64': 'aarch64-apple-darwin', +}; + +const RELEASE_BASE = + 'https://github.com/OpenZeppelin/compact-tools/releases/download'; + +/** A stalled release download fails instead of hanging the lint run. */ +const DOWNLOAD_TIMEOUT_MS = 120_000; + +/** Where the binary is fetched from and cached, and who is told about a download. */ +export interface ResolveOptions { + /** Root of the installed package; the cache lives under `.cache/` inside it. */ + packageDir: string; + version: string; + platform: string; + arch: string; + env: Record; + /** Called once, before the first download of a run. */ + notify: (message: string) => void; +} + +export function resolveTarget(platform: string, arch: string): string | null { + return TARGETS[`${platform}-${arch}`] ?? null; +} + +export function assetName(target: string): string { + return `compact-lint-${target}`; +} + +export function sha256(bytes: Uint8Array): string { + return createHash('sha256').update(bytes).digest('hex'); +} + +/** ` ` lines to an asset-keyed map; CRLF and the `*` binary marker are tolerated. */ +export function parseChecksums(text: string): Map { + const digests = new Map(); + for (const line of text.split('\n')) { + const entry = /^([0-9a-f]{64})\s+\*?(\S+)$/.exec(line.trim()); + if (entry) { + digests.set(entry[2], entry[1]); + } + } + return digests; +} + +export function expectedChecksum(text: string, asset: string): string { + const digest = parseChecksums(text).get(asset); + if (digest === undefined) { + throw new Error(`checksums.txt has no entry for ${asset}`); + } + return digest; +} + +/** + * Path to the `compact-lint` executable, downloading it into the package cache when missing. + * + * Messages carry no `compact-lint:` prefix; the bin adds it. + */ +export async function resolveBinary(options: ResolveOptions): Promise { + const override = options.env.COMPACT_LINT_BINARY; + if (override) { + return override; + } + + const target = resolveTarget(options.platform, options.arch); + if (target === null) { + throw new Error( + `no prebuilt binary for ${options.platform}-${options.arch}; build from source with cargo (crates/compact-lint) and set COMPACT_LINT_BINARY`, + ); + } + + const cacheDir = join(options.packageDir, '.cache'); + const cached = join(cacheDir, `compact-lint-${options.version}-${target}`); + if (existsSync(cached)) { + return cached; + } + + const asset = assetName(target); + const base = + options.env.COMPACT_LINT_DOWNLOAD_BASE ?? + `${RELEASE_BASE}/compact-lint/v${options.version}`; + options.notify(`downloading ${asset} (v${options.version})`); + + const [binary, checksums] = await Promise.all([ + fetchBytes(`${base}/${asset}`), + fetchText(`${base}/checksums.txt`), + ]); + + const expected = expectedChecksum(checksums, asset); + const actual = sha256(binary); + if (actual !== expected) { + throw new Error( + `checksum mismatch for ${asset}: expected ${expected}, got ${actual}; delete ${cached} and retry`, + ); + } + + // Staged under a unique name so concurrent runs never read a half-written file. + mkdirSync(cacheDir, { recursive: true }); + const staged = `${cached}.${randomUUID()}.tmp`; + writeFileSync(staged, binary); + chmodSync(staged, 0o755); + renameSync(staged, cached); + return cached; +} + +async function fetchOk(url: string): Promise { + let response: Response; + try { + response = await fetch(url, { + signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS), + }); + } catch (cause) { + const reason = cause instanceof Error ? cause.message : String(cause); + throw new Error(`download failed for ${url}: ${reason}`); + } + if (!response.ok) { + throw new Error(`download failed for ${url}: HTTP ${response.status}`); + } + return response; +} + +async function fetchBytes(url: string): Promise { + return new Uint8Array(await (await fetchOk(url)).arrayBuffer()); +} + +async function fetchText(url: string): Promise { + return (await fetchOk(url)).text(); +} diff --git a/packages/lint/src/compactLint.ts b/packages/lint/src/compactLint.ts new file mode 100644 index 00000000..a03ae709 --- /dev/null +++ b/packages/lint/src/compactLint.ts @@ -0,0 +1,52 @@ +#!/usr/bin/env node + +import { spawnSync } from 'node:child_process'; +import { readFileSync } from 'node:fs'; +import { constants } from 'node:os'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { resolveBinary } from './binary.ts'; + +// One level up from src/ and from dist/ alike, so both entry points find the manifest. +const packageDir = dirname(dirname(fileURLToPath(import.meta.url))); + +function packageVersion(): string { + const manifest = readFileSync(join(packageDir, 'package.json'), 'utf8'); + return (JSON.parse(manifest) as { version: string }).version; +} + +function fail(message: string): never { + process.stderr.write(`compact-lint: ${message}\n`); + process.exit(2); +} + +async function runLint(): Promise { + let binary: string; + try { + binary = await resolveBinary({ + packageDir, + version: packageVersion(), + platform: process.platform, + arch: process.arch, + env: process.env, + notify: (message) => process.stderr.write(`compact-lint: ${message}\n`), + }); + } catch (error) { + fail(error instanceof Error ? error.message : String(error)); + } + + // argv0 keeps the cache file name out of the linter's own usage output. + const result = spawnSync(binary, process.argv.slice(2), { + argv0: 'compact-lint', + stdio: 'inherit', + }); + if (result.error) { + fail(`cannot run ${binary}: ${result.error.message}`); + } + if (result.signal) { + process.exit(128 + (constants.signals[result.signal] ?? 0)); + } + process.exit(result.status ?? 0); +} + +await runLint(); diff --git a/packages/lint/test/binary.test.ts b/packages/lint/test/binary.test.ts new file mode 100644 index 00000000..c4673445 --- /dev/null +++ b/packages/lint/test/binary.test.ts @@ -0,0 +1,293 @@ +import { spawnSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { + chmodSync, + mkdtempSync, + rmSync, + statSync, + writeFileSync, +} from 'node:fs'; +import { createServer, type Server } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { + expectedChecksum, + parseChecksums, + resolveBinary, + resolveTarget, + sha256, +} from '../src/binary.ts'; + +const packageDir = dirname(dirname(fileURLToPath(import.meta.url))); +const FAKE_BINARY = '#!/bin/sh\necho fake-lint "$@"\n'; +const ASSET = 'compact-lint-x86_64-unknown-linux-gnu'; + +interface Origin { + base: string; + requests: string[]; + close: () => Promise; +} + +/** A release-shaped origin: one asset, one `checksums.txt`, every request path recorded. */ +async function startOrigin(files: Record): Promise { + const requests: string[] = []; + const server: Server = createServer((request, response) => { + const path = (request.url ?? '/').slice(1); + requests.push(path); + const body = files[path]; + if (body === undefined) { + response.writeHead(404).end('not found'); + return; + } + response.writeHead(200).end(body); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const { port } = server.address() as AddressInfo; + return { + base: `http://127.0.0.1:${port}`, + requests, + close: () => + new Promise((resolve, reject) => + server.close((error) => (error ? reject(error) : resolve())), + ), + }; +} + +function checksumsFor(asset: string, body: string): string { + const digest = createHash('sha256').update(body).digest('hex'); + return [ + `${'0'.repeat(64)} compact-lint-aarch64-apple-darwin`, + `${digest} ${asset}`, + `${'1'.repeat(64)} compact-lint-aarch64-unknown-linux-gnu`, + ].join('\n'); +} + +let install: string; +let notices: string[]; + +function options( + overrides: Partial[0]> = {}, +): Parameters[0] { + return { + packageDir: install, + version: '0.1.0', + platform: 'linux', + arch: 'x64', + env: {}, + notify: (message) => notices.push(message), + ...overrides, + }; +} + +beforeEach(() => { + install = mkdtempSync(join(tmpdir(), 'compact-lint-pkg-')); + notices = []; +}); + +afterEach(() => { + rmSync(install, { recursive: true, force: true }); +}); + +describe('resolveTarget', () => { + it('maps every supported platform and architecture to its rust target', () => { + expect(resolveTarget('linux', 'x64')).toBe('x86_64-unknown-linux-gnu'); + expect(resolveTarget('linux', 'arm64')).toBe('aarch64-unknown-linux-gnu'); + expect(resolveTarget('darwin', 'x64')).toBe('x86_64-apple-darwin'); + expect(resolveTarget('darwin', 'arm64')).toBe('aarch64-apple-darwin'); + }); + + it('returns null for a platform with no release asset', () => { + expect(resolveTarget('win32', 'x64')).toBeNull(); + expect(resolveTarget('linux', 'ia32')).toBeNull(); + }); +}); + +describe('parseChecksums', () => { + it('reads every entry of a multi-asset file', () => { + const digests = parseChecksums(checksumsFor(ASSET, FAKE_BINARY)); + expect(digests.size).toBe(3); + expect(digests.get(ASSET)).toBe(sha256(Buffer.from(FAKE_BINARY))); + }); + + it('reads entries written with CRLF line endings', () => { + const digests = parseChecksums( + checksumsFor(ASSET, FAKE_BINARY).replaceAll('\n', '\r\n'), + ); + expect(digests.get(ASSET)).toBe(sha256(Buffer.from(FAKE_BINARY))); + }); + + it('reads the entry of a file marked binary with an asterisk', () => { + const digests = parseChecksums(`${'a'.repeat(64)} *${ASSET}`); + expect(digests.get(ASSET)).toBe('a'.repeat(64)); + }); + + it('ignores blank lines and lines that hold no digest', () => { + const digests = parseChecksums('\n# a comment\nnot a checksum line\n'); + expect(digests.size).toBe(0); + }); + + it('rejects a file with no entry for the asset', () => { + expect(() => expectedChecksum('', ASSET)).toThrow( + `checksums.txt has no entry for ${ASSET}`, + ); + }); +}); + +describe('resolveBinary', () => { + it('reports a platform with no release asset', async () => { + await expect( + resolveBinary(options({ platform: 'win32', arch: 'x64' })), + ).rejects.toThrow( + 'no prebuilt binary for win32-x64; build from source with cargo (crates/compact-lint) and set COMPACT_LINT_BINARY', + ); + }); + + it('returns COMPACT_LINT_BINARY without contacting the origin', async () => { + const origin = await startOrigin({}); + try { + const binary = await resolveBinary( + options({ + env: { + COMPACT_LINT_BINARY: '/opt/compact-lint', + COMPACT_LINT_DOWNLOAD_BASE: origin.base, + }, + }), + ); + expect(binary).toBe('/opt/compact-lint'); + expect(origin.requests).toStrictEqual([]); + expect(notices).toStrictEqual([]); + } finally { + await origin.close(); + } + }); + + it('downloads, verifies and caches the release asset', async () => { + const origin = await startOrigin({ + [ASSET]: FAKE_BINARY, + 'checksums.txt': checksumsFor(ASSET, FAKE_BINARY), + }); + try { + const binary = await resolveBinary( + options({ env: { COMPACT_LINT_DOWNLOAD_BASE: origin.base } }), + ); + expect(binary).toBe( + join(install, '.cache', 'compact-lint-0.1.0-x86_64-unknown-linux-gnu'), + ); + expect(statSync(binary).mode & 0o777).toBe(0o755); + expect(spawnSync(binary, ['check'], { encoding: 'utf8' }).stdout).toBe( + 'fake-lint check\n', + ); + expect(origin.requests.toSorted()).toStrictEqual([ + 'checksums.txt', + ASSET, + ]); + expect(notices).toStrictEqual([ + 'downloading compact-lint-x86_64-unknown-linux-gnu (v0.1.0)', + ]); + } finally { + await origin.close(); + } + }); + + it('serves a second run from the cache', async () => { + const origin = await startOrigin({ + [ASSET]: FAKE_BINARY, + 'checksums.txt': checksumsFor(ASSET, FAKE_BINARY), + }); + try { + const first = await resolveBinary( + options({ env: { COMPACT_LINT_DOWNLOAD_BASE: origin.base } }), + ); + const second = await resolveBinary( + options({ env: { COMPACT_LINT_DOWNLOAD_BASE: origin.base } }), + ); + expect(second).toBe(first); + expect(origin.requests).toHaveLength(2); + expect(notices).toHaveLength(1); + } finally { + await origin.close(); + } + }); + + it('rejects an asset whose digest does not match checksums.txt', async () => { + const origin = await startOrigin({ + [ASSET]: FAKE_BINARY, + 'checksums.txt': checksumsFor(ASSET, 'a different binary'), + }); + try { + const expected = sha256(Buffer.from('a different binary')); + const actual = sha256(Buffer.from(FAKE_BINARY)); + await expect( + resolveBinary( + options({ env: { COMPACT_LINT_DOWNLOAD_BASE: origin.base } }), + ), + ).rejects.toThrow( + `checksum mismatch for ${ASSET}: expected ${expected}, got ${actual}; delete ${join(install, '.cache', 'compact-lint-0.1.0-x86_64-unknown-linux-gnu')} and retry`, + ); + } finally { + await origin.close(); + } + }); + + it('rejects an origin that answers with an http error', async () => { + const origin = await startOrigin({}); + try { + await expect( + resolveBinary( + options({ env: { COMPACT_LINT_DOWNLOAD_BASE: origin.base } }), + ), + ).rejects.toThrow( + `download failed for ${origin.base}/${ASSET}: HTTP 404`, + ); + } finally { + await origin.close(); + } + }); + + it('rejects an origin that cannot be reached', async () => { + await expect( + resolveBinary( + options({ + env: { COMPACT_LINT_DOWNLOAD_BASE: 'http://127.0.0.1:1/download' }, + }), + ), + ).rejects.toThrow('download failed for http://127.0.0.1:1/download/'); + }); +}); + +describe('the compact-lint bin', () => { + it('passes its arguments to the binary and forwards the exit code', () => { + const stub = join(install, 'stub-lint'); + writeFileSync(stub, '#!/bin/sh\necho "args: $*"\nexit 7\n'); + chmodSync(stub, 0o755); + + const run = spawnSync( + process.execPath, + [join(packageDir, 'src', 'compactLint.ts'), 'check', '--strict', 'src'], + { encoding: 'utf8', env: { ...process.env, COMPACT_LINT_BINARY: stub } }, + ); + + expect(run.stdout).toBe('args: check --strict src\n'); + expect(run.status).toBe(7); + }); + + it('exits 2 when no binary can be resolved', () => { + const run = spawnSync( + process.execPath, + [join(packageDir, 'src', 'compactLint.ts'), 'check'], + { + encoding: 'utf8', + env: { + ...process.env, + COMPACT_LINT_BINARY: join(install, 'not-installed'), + }, + }, + ); + + expect(run.status).toBe(2); + expect(run.stderr).toContain('compact-lint: cannot run'); + }); +}); diff --git a/packages/lint/test/version.test.ts b/packages/lint/test/version.test.ts new file mode 100644 index 00000000..75c37ae8 --- /dev/null +++ b/packages/lint/test/version.test.ts @@ -0,0 +1,22 @@ +import { readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { describe, expect, it } from 'vitest'; + +const packageDir = dirname(dirname(fileURLToPath(import.meta.url))); + +function read(...segments: string[]): string { + return readFileSync(join(packageDir, ...segments), 'utf8'); +} + +describe('the published version', () => { + it('matches the crate the package downloads', () => { + const published = (JSON.parse(read('package.json')) as { version: string }) + .version; + const crate = /^version = "(.+)"$/m.exec( + read('..', '..', 'crates', 'compact-lint', 'Cargo.toml'), + ); + + expect(crate?.[1]).toBe(published); + }); +}); diff --git a/packages/lint/tsconfig.json b/packages/lint/tsconfig.json new file mode 100644 index 00000000..f4bcef15 --- /dev/null +++ b/packages/lint/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "@tsconfig/node24/tsconfig.json", + "compilerOptions": { + "outDir": "dist", + "rootDir": "src", + "types": ["node"], + "declaration": true, + "skipLibCheck": true, + "sourceMap": true, + "rewriteRelativeImportExtensions": true, + "erasableSyntaxOnly": true, + "verbatimModuleSyntax": true + }, + "include": [ + "src/**/*" + ], + "exclude": [ + "node_modules", + "dist" + ] +} \ No newline at end of file diff --git a/packages/lint/turbo.json b/packages/lint/turbo.json new file mode 100644 index 00000000..d6710099 --- /dev/null +++ b/packages/lint/turbo.json @@ -0,0 +1,11 @@ +{ + "$schema": "https://turbo.build/schema.json", + "extends": ["//"], + "tasks": { + "build": { + "outputs": ["dist/**"], + "inputs": ["src/**/*.ts", "tsconfig.json"], + "cache": true + } + } +} diff --git a/packages/lint/vitest.config.ts b/packages/lint/vitest.config.ts new file mode 100644 index 00000000..a07a60bb --- /dev/null +++ b/packages/lint/vitest.config.ts @@ -0,0 +1,22 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + globals: true, + environment: 'node', + include: ['test/**/*.test.ts'], + reporters: 'verbose', + coverage: { + provider: 'v8', + reporter: ['text', 'html', 'json-summary'], + // The bin runs in a subprocess, which v8 coverage does not observe. + include: ['src/binary.ts'], + thresholds: { + statements: 95, + branches: 90, + functions: 100, + lines: 95, + }, + }, + }, +}); diff --git a/yarn.lock b/yarn.lock index 583cabb0..65d5c32c 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1180,6 +1180,19 @@ __metadata: languageName: unknown linkType: soft +"@openzeppelin/compact-lint@workspace:packages/lint": + version: 0.0.0-use.local + resolution: "@openzeppelin/compact-lint@workspace:packages/lint" + dependencies: + "@tsconfig/node24": "npm:^24.0.3" + "@types/node": "npm:26.1.2" + typescript: "npm:^6.0.3" + vitest: "npm:^4.1.9" + bin: + compact-lint: dist/compactLint.js + languageName: unknown + linkType: soft + "@openzeppelin/compact-simulator@workspace:packages/simulator": version: 0.0.0-use.local resolution: "@openzeppelin/compact-simulator@workspace:packages/simulator" From b3c6c8c89507d4fe861d357546413123bb83566e Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Tue, 15 Sep 2026 11:45:24 +0200 Subject: [PATCH 08/56] build(compact-linter): name the npm package compact-linter The published packages are compact-builder, compact-cli, compact-deployer and compact-simulator, so the wrapper follows the same shape as @openzeppelin/compact-linter under packages/linter, with a compact-linter bin and a compact-linter/v release tag. The crate, its binary and the release asset names stay compact-lint. --- packages/{lint => linter}/CHANGELOG.md | 0 packages/{lint => linter}/LICENSE | 0 packages/{lint => linter}/README.md | 0 packages/{lint => linter}/package.json | 0 packages/{lint => linter}/src/binary.ts | 0 packages/{lint => linter}/src/compactLint.ts | 0 packages/{lint => linter}/test/binary.test.ts | 0 packages/{lint => linter}/test/version.test.ts | 0 packages/{lint => linter}/tsconfig.json | 0 packages/{lint => linter}/turbo.json | 0 packages/{lint => linter}/vitest.config.ts | 0 11 files changed, 0 insertions(+), 0 deletions(-) rename packages/{lint => linter}/CHANGELOG.md (100%) rename packages/{lint => linter}/LICENSE (100%) rename packages/{lint => linter}/README.md (100%) rename packages/{lint => linter}/package.json (100%) rename packages/{lint => linter}/src/binary.ts (100%) rename packages/{lint => linter}/src/compactLint.ts (100%) rename packages/{lint => linter}/test/binary.test.ts (100%) rename packages/{lint => linter}/test/version.test.ts (100%) rename packages/{lint => linter}/tsconfig.json (100%) rename packages/{lint => linter}/turbo.json (100%) rename packages/{lint => linter}/vitest.config.ts (100%) diff --git a/packages/lint/CHANGELOG.md b/packages/linter/CHANGELOG.md similarity index 100% rename from packages/lint/CHANGELOG.md rename to packages/linter/CHANGELOG.md diff --git a/packages/lint/LICENSE b/packages/linter/LICENSE similarity index 100% rename from packages/lint/LICENSE rename to packages/linter/LICENSE diff --git a/packages/lint/README.md b/packages/linter/README.md similarity index 100% rename from packages/lint/README.md rename to packages/linter/README.md diff --git a/packages/lint/package.json b/packages/linter/package.json similarity index 100% rename from packages/lint/package.json rename to packages/linter/package.json diff --git a/packages/lint/src/binary.ts b/packages/linter/src/binary.ts similarity index 100% rename from packages/lint/src/binary.ts rename to packages/linter/src/binary.ts diff --git a/packages/lint/src/compactLint.ts b/packages/linter/src/compactLint.ts similarity index 100% rename from packages/lint/src/compactLint.ts rename to packages/linter/src/compactLint.ts diff --git a/packages/lint/test/binary.test.ts b/packages/linter/test/binary.test.ts similarity index 100% rename from packages/lint/test/binary.test.ts rename to packages/linter/test/binary.test.ts diff --git a/packages/lint/test/version.test.ts b/packages/linter/test/version.test.ts similarity index 100% rename from packages/lint/test/version.test.ts rename to packages/linter/test/version.test.ts diff --git a/packages/lint/tsconfig.json b/packages/linter/tsconfig.json similarity index 100% rename from packages/lint/tsconfig.json rename to packages/linter/tsconfig.json diff --git a/packages/lint/turbo.json b/packages/linter/turbo.json similarity index 100% rename from packages/lint/turbo.json rename to packages/linter/turbo.json diff --git a/packages/lint/vitest.config.ts b/packages/linter/vitest.config.ts similarity index 100% rename from packages/lint/vitest.config.ts rename to packages/linter/vitest.config.ts From 71db1e87e5af158e53c57dfd63713de3cbc5b94d Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Tue, 15 Sep 2026 11:46:27 +0200 Subject: [PATCH 09/56] build(compact-linter): finish the compact-linter rename Carries the content half of the rename: manifest name and bin, release tag path, stderr prefix, workflows, docs and the lockfile. The previous commit only moved the directory. --- .github/workflows/release-publish.yml | 22 +++++++++---------- .github/workflows/release.yml | 18 +++++++-------- .gitignore | 2 +- README.md | 6 ++--- RELEASING.md | 20 ++++++++--------- crates/compact-lint/README.md | 6 ++--- packages/linter/CHANGELOG.md | 4 ++-- packages/linter/README.md | 12 +++++----- packages/linter/package.json | 6 ++--- packages/linter/src/binary.ts | 2 +- .../src/{compactLint.ts => compactLinter.ts} | 9 +++++--- packages/linter/test/binary.test.ts | 8 +++---- yarn.lock | 6 ++--- 13 files changed, 62 insertions(+), 59 deletions(-) rename packages/linter/src/{compactLint.ts => compactLinter.ts} (89%) diff --git a/.github/workflows/release-publish.yml b/.github/workflows/release-publish.yml index 2e34bc08..af9452ee 100644 --- a/.github/workflows/release-publish.yml +++ b/.github/workflows/release-publish.yml @@ -19,7 +19,7 @@ on: - compact-builder - compact-cli - compact-deployer - - compact-lint + - compact-linter - compact-simulator jobs: @@ -68,7 +68,7 @@ jobs: compact-builder) DIR="builder" ;; compact-cli) DIR="cli" ;; compact-deployer) DIR="deployer" ;; - compact-lint) DIR="lint" ;; + compact-linter) DIR="linter" ;; compact-simulator) DIR="simulator" ;; *) echo "::error::unknown package: $PKG" @@ -88,7 +88,7 @@ jobs: builder) PKG="compact-builder" ;; cli) PKG="compact-cli" ;; deployer) PKG="compact-deployer" ;; - lint) PKG="compact-lint" ;; + linter) PKG="compact-linter" ;; simulator) PKG="compact-simulator" ;; *) echo "::error::unknown package directory: $DIR" @@ -136,12 +136,12 @@ jobs: echo "- Trigger: $EVENT" } >> $GITHUB_STEP_SUMMARY - # compact-lint ships a native binary per target, built on its own runner. The + # compact-linter ships a native binary per target, built on its own runner. The # npm package downloads them, so they must reach the GitHub release first. binaries: name: Build compact-lint for ${{ matrix.target }} needs: detect - if: needs.detect.outputs.name == 'compact-lint' + if: needs.detect.outputs.name == 'compact-linter' runs-on: ${{ matrix.runner }} permissions: @@ -200,7 +200,7 @@ jobs: publish: name: Publish merged release needs: [detect, binaries] - # `binaries` is skipped for every package but compact-lint, and a skipped + # `binaries` is skipped for every package but compact-linter, and a skipped # dependency must not skip the publish. if: >- always() && @@ -255,7 +255,7 @@ jobs: fi - name: Download the release binaries - if: needs.detect.outputs.name == 'compact-lint' + if: needs.detect.outputs.name == 'compact-linter' uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: path: dist @@ -265,7 +265,7 @@ jobs: # Asset names only: the installed package looks each digest up by the name # it downloads. - name: Write the checksums - if: needs.detect.outputs.name == 'compact-lint' + if: needs.detect.outputs.name == 'compact-linter' working-directory: dist run: | sha256sum compact-lint-* > checksums.txt @@ -274,7 +274,7 @@ jobs: # The npm package downloads these assets on first run, so the release has # to carry them before the package reaches npm. - name: Create the GitHub release - if: needs.detect.outputs.name == 'compact-lint' + if: needs.detect.outputs.name == 'compact-linter' env: GH_TOKEN: ${{ steps.gh-app-token.outputs.token }} TAG: ${{ needs.detect.outputs.name }}/v${{ needs.detect.outputs.version }} @@ -285,7 +285,7 @@ jobs: $0 ~ "^## " v "( |$)" { found = 1; next } found && /^## / { exit } found { print } - ' packages/lint/CHANGELOG.md) + ' packages/linter/CHANGELOG.md) if [[ -z "${NOTES//[[:space:]]/}" ]]; then NOTES="$TAG" fi @@ -297,7 +297,7 @@ jobs: ARGS+=(--prerelease) fi gh release create "$TAG" dist/* \ - --title "compact-lint v$VERSION" \ + --title "compact-linter v$VERSION" \ --notes "$NOTES" \ "${ARGS[@]}" fi diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 13360df6..b9522bb4 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -11,7 +11,7 @@ on: - compact-builder - compact-cli - compact-deployer - - compact-lint + - compact-linter - compact-simulator version_bump: description: "Version bump type (pre* strategies are beta-only)" @@ -90,8 +90,8 @@ jobs: "compact-deployer") echo "dir=deployer" >> $GITHUB_OUTPUT ;; - "compact-lint") - echo "dir=lint" >> $GITHUB_OUTPUT + "compact-linter") + echo "dir=linter" >> $GITHUB_OUTPUT ;; "compact-simulator") echo "dir=simulator" >> $GITHUB_OUTPUT @@ -101,10 +101,10 @@ jobs: - name: Setup Environment uses: ./.github/actions/setup - # compact-lint's version lives in the crate too, and bumping it there + # compact-linter's version lives in the crate too, and bumping it there # rewrites Cargo.lock. - name: Install the pinned toolchain - if: inputs.package == 'compact-lint' + if: inputs.package == 'compact-linter' run: | CHANNEL=$(grep -m1 '^channel' rust-toolchain.toml | cut -d'"' -f2) rustup toolchain install "$CHANNEL" --profile minimal @@ -148,7 +148,7 @@ jobs: } >> $GITHUB_STEP_SUMMARY - name: Sync the crate version - if: inputs.package == 'compact-lint' + if: inputs.package == 'compact-linter' env: NEW_VERSION: ${{ steps.version.outputs.new }} run: | @@ -183,7 +183,7 @@ jobs: fi - name: Commit version bump - if: inputs.package != 'compact-lint' + if: inputs.package != 'compact-linter' uses: iarekylew00t/verified-bot-commit@42a042b0407248f3c0acac00c389e729e3476e86 # v2.3.5 with: message: "release: ${{ inputs.package }} v${{ steps.version.outputs.new }}" @@ -193,14 +193,14 @@ jobs: packages/${{ steps.pkg.outputs.dir }}/package.json - name: Commit version bump with the crate - if: inputs.package == 'compact-lint' + if: inputs.package == 'compact-linter' uses: iarekylew00t/verified-bot-commit@42a042b0407248f3c0acac00c389e729e3476e86 # v2.3.5 with: message: "release: ${{ inputs.package }} v${{ steps.version.outputs.new }}" token: ${{ steps.gh-app-token.outputs.token }} ref: ${{ steps.version.outputs.branch }} files: | - packages/lint/package.json + packages/linter/package.json crates/compact-lint/Cargo.toml Cargo.lock diff --git a/.gitignore b/.gitignore index 757ea362..48f64fef 100644 --- a/.gitignore +++ b/.gitignore @@ -67,7 +67,7 @@ target/ .toolkit-cache/ # compact-lint's release binary, cached inside the installed npm package. -packages/lint/.cache/ +packages/linter/.cache/ coverage **/reports diff --git a/README.md b/README.md index 6ae796e2..5d39deb2 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ Tools for compiling, building, testing, and deploying Compact smart contracts. T - [`packages/builder`](./packages/builder) β€” programmatic library that drives the Compact compiler + builder - [`packages/cli`](./packages/cli) β€” thin bin wrapper around the builder and deployer libraries (`compact-compiler`, `compact-builder`, `compact-deploy`) - [`packages/deployer`](./packages/deployer) β€” deployer library that submits a compiled contract to a Midnight network. Pins one Midnight stack: see [Supported stack](./packages/deployer/README.md#supported-stack) -- [`packages/lint`](./packages/lint) β€” bin wrapper around the [`compact-lint`](./crates/compact-lint) crate, the doc-comment linter for Compact sources +- [`packages/linter`](./packages/linter) β€” bin wrapper around the [`compact-lint`](./crates/compact-lint) crate, the doc-comment linter for Compact sources - [`packages/simulator`](./packages/simulator) β€” TypeScript simulator to run and test Compact contracts locally See each package's README for usage, options, and examples. @@ -40,7 +40,7 @@ yarn add --dev @openzeppelin/compact-cli yarn add --dev @openzeppelin/compact-simulator # Linter β€” check doc comments in .compact sources -yarn add --dev @openzeppelin/compact-lint +yarn add --dev @openzeppelin/compact-linter # Deployer β€” deploy a compiled contract from TypeScript yarn add --dev @openzeppelin/compact-deployer @@ -63,7 +63,7 @@ import { createSimulator } from '@openzeppelin/compact-simulator'; ## Requirements -- Node.js >= 22 for `packages/builder` and `packages/simulator`, >= 24 for `packages/cli`, `packages/deployer` and `packages/lint` +- Node.js >= 22 for `packages/builder` and `packages/simulator`, >= 24 for `packages/cli`, `packages/deployer` and `packages/linter` - Yarn 4 (Berry) - Turbo - Optional: Midnight Compact toolchain installed and available in `PATH` diff --git a/RELEASING.md b/RELEASING.md index ed5e4965..fd3494ec 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -49,7 +49,7 @@ release notes agree. - Create a git tag. - Publish the package to npm under the channel's dist-tag. 7. Once published, go to "Releases" and create a GitHub release using the - generated tag. Mark beta tags as prereleases. `compact-lint` is the + generated tag. Mark beta tags as prereleases. `compact-linter` is the exception: the workflow creates its release itself (see below). ## Graduating a beta to stable @@ -89,7 +89,7 @@ compact-cli (bin wrapper) └─ depends on compact-deployer compact-builder (library) compact-deployer (library) -compact-lint (bin wrapper around the compact-lint crate) +compact-linter (bin wrapper around the compact-lint crate) compact-simulator (library) ``` @@ -100,22 +100,22 @@ each dependent finds its deps already on npm: 1. `compact-builder` (no internal deps) 2. `compact-simulator` (no internal deps) 3. `compact-deployer` (no internal deps) -4. `compact-lint` (no internal deps) +4. `compact-linter` (no internal deps) 5. `compact-cli` (depends on `compact-builder` and `compact-deployer`; pull `main` first so both bump commits are present locally before triggering) After the first release, the five packages version independently β€” bump any one of them in isolation without re-publishing the others. -## compact-lint +## compact-linter -`compact-lint` is a bin wrapper around the `compact-lint` crate, so its release +`compact-linter` is a bin wrapper around the `compact-lint` crate, so its release carries a native binary as well as an npm package. -- The version lives in two files: `packages/lint/package.json` and +- The version lives in two files: `packages/linter/package.json` and `crates/compact-lint/Cargo.toml`. The release workflow bumps the package, mirrors the value into the crate, refreshes `Cargo.lock`, and commits all three. A unit - test in `packages/lint` fails when the two drift. + test in `packages/linter` fails when the two drift. - The publish workflow builds four binaries before publishing, one per target, each on its own runner: @@ -126,12 +126,12 @@ carries a native binary as well as an npm package. | `x86_64-apple-darwin` | `macos-15-intel` | | `aarch64-apple-darwin` | `macos-15` | -- It then creates the GitHub release `compact-lint/v` with the four assets +- It then creates the GitHub release `compact-linter/v` with the four assets and a `checksums.txt`, and only then publishes to npm. The installed package downloads its binary from that release, so the assets must be there first. For every other package the GitHub release is still created by hand (step 7 above). -- Release notes come from the `## ` section of `packages/lint/CHANGELOG.md`, +- Release notes come from the `## ` section of `packages/linter/CHANGELOG.md`, falling back to the tag name. A `beta` dist-tag marks the release a prerelease. -- Before the first release, add `@openzeppelin/compact-lint` as a Trusted Publisher +- Before the first release, add `@openzeppelin/compact-linter` as a Trusted Publisher on npmjs.org, naming this repo and `.github/workflows/release-publish.yml`. Every new npm package needs this once, or the publish step cannot authenticate. diff --git a/crates/compact-lint/README.md b/crates/compact-lint/README.md index aa303996..434efe14 100644 --- a/crates/compact-lint/README.md +++ b/crates/compact-lint/README.md @@ -8,9 +8,9 @@ contracts and writes the measured `k` and `rows` into the annotations. ## Install -- npm, no Rust toolchain needed: `yarn add -D @openzeppelin/compact-lint`, or - `npx @openzeppelin/compact-lint check`. The package downloads the release binary for - the host on first use. See [`packages/lint`](../../packages/lint). +- npm, no Rust toolchain needed: `yarn add -D @openzeppelin/compact-linter`, or + `npx @openzeppelin/compact-linter check`. The package downloads the release binary for + the host on first use. See [`packages/linter`](../../packages/linter). - From source: `cargo install --path crates/compact-lint`. ## Usage diff --git a/packages/linter/CHANGELOG.md b/packages/linter/CHANGELOG.md index a6cdf5cf..5d886386 100644 --- a/packages/linter/CHANGELOG.md +++ b/packages/linter/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -All notable changes to `@openzeppelin/compact-lint` are documented in this +All notable changes to `@openzeppelin/compact-linter` are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), @@ -10,4 +10,4 @@ and this package adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- `compact-lint` bin, a launcher that downloads the [`compact-lint`](../../crates/compact-lint) release binary for the host, verifies its SHA-256, and runs it +- `compact-linter` bin, a launcher that downloads the [`compact-lint`](../../crates/compact-lint) release binary for the host, verifies its SHA-256, and runs it diff --git a/packages/linter/README.md b/packages/linter/README.md index 22f62d35..6bf577b0 100644 --- a/packages/linter/README.md +++ b/packages/linter/README.md @@ -1,4 +1,4 @@ -# @openzeppelin/compact-lint +# @openzeppelin/compact-linter Bin wrapper around the [`compact-lint`](../../crates/compact-lint) Rust crate, the doc-comment linter for Compact sources. The package itself is a thin launcher: it @@ -7,13 +7,13 @@ resolves the native binary for the host and runs it with your arguments. ## Install ```bash -yarn add --dev @openzeppelin/compact-lint +yarn add --dev @openzeppelin/compact-linter ``` ```bash -npx @openzeppelin/compact-lint check -yarn compact-lint check contracts/src -yarn compact-lint fix --dry-run +npx @openzeppelin/compact-linter check +yarn compact-linter check contracts/src +yarn compact-linter fix --dry-run ``` Commands, flags, exit codes and `compact-lint.toml` are documented in the @@ -21,7 +21,7 @@ Commands, flags, exit codes and `compact-lint.toml` are documented in the ## Where the binary comes from -- Prebuilt binaries are attached to the `compact-lint/v` GitHub release, one +- Prebuilt binaries are attached to the `compact-linter/v` GitHub release, one per target: `x86_64-unknown-linux-gnu`, `aarch64-unknown-linux-gnu`, `x86_64-apple-darwin`, `aarch64-apple-darwin`. - The first run downloads the one matching the host, checks its SHA-256 against the diff --git a/packages/linter/package.json b/packages/linter/package.json index d1451fa0..81cdf57b 100644 --- a/packages/linter/package.json +++ b/packages/linter/package.json @@ -1,5 +1,5 @@ { - "name": "@openzeppelin/compact-lint", + "name": "@openzeppelin/compact-linter", "description": "Doc-comment linter for Compact sources", "version": "0.1.0", "keywords": [ @@ -14,7 +14,7 @@ "repository": { "type": "git", "url": "git+https://github.com/OpenZeppelin/compact-tools.git", - "directory": "packages/lint" + "directory": "packages/linter" }, "type": "module", "files": [ @@ -26,7 +26,7 @@ "engines": { "node": ">=24" }, - "bin": "dist/compactLint.js", + "bin": "dist/compactLinter.js", "scripts": { "build": "tsc -p .", "types": "tsc -p tsconfig.json --noEmit", diff --git a/packages/linter/src/binary.ts b/packages/linter/src/binary.ts index 02cbaa86..8c73bd48 100644 --- a/packages/linter/src/binary.ts +++ b/packages/linter/src/binary.ts @@ -93,7 +93,7 @@ export async function resolveBinary(options: ResolveOptions): Promise { const asset = assetName(target); const base = options.env.COMPACT_LINT_DOWNLOAD_BASE ?? - `${RELEASE_BASE}/compact-lint/v${options.version}`; + `${RELEASE_BASE}/compact-linter/v${options.version}`; options.notify(`downloading ${asset} (v${options.version})`); const [binary, checksums] = await Promise.all([ diff --git a/packages/linter/src/compactLint.ts b/packages/linter/src/compactLinter.ts similarity index 89% rename from packages/linter/src/compactLint.ts rename to packages/linter/src/compactLinter.ts index a03ae709..33003481 100644 --- a/packages/linter/src/compactLint.ts +++ b/packages/linter/src/compactLinter.ts @@ -16,7 +16,8 @@ function packageVersion(): string { } function fail(message: string): never { - process.stderr.write(`compact-lint: ${message}\n`); + process.stderr.write(`compact-linter: ${message} +`); process.exit(2); } @@ -29,7 +30,9 @@ async function runLint(): Promise { platform: process.platform, arch: process.arch, env: process.env, - notify: (message) => process.stderr.write(`compact-lint: ${message}\n`), + notify: (message) => + process.stderr.write(`compact-linter: ${message} +`), }); } catch (error) { fail(error instanceof Error ? error.message : String(error)); @@ -37,7 +40,7 @@ async function runLint(): Promise { // argv0 keeps the cache file name out of the linter's own usage output. const result = spawnSync(binary, process.argv.slice(2), { - argv0: 'compact-lint', + argv0: 'compact-linter', stdio: 'inherit', }); if (result.error) { diff --git a/packages/linter/test/binary.test.ts b/packages/linter/test/binary.test.ts index c4673445..18de25cb 100644 --- a/packages/linter/test/binary.test.ts +++ b/packages/linter/test/binary.test.ts @@ -258,7 +258,7 @@ describe('resolveBinary', () => { }); }); -describe('the compact-lint bin', () => { +describe('the compact-linter bin', () => { it('passes its arguments to the binary and forwards the exit code', () => { const stub = join(install, 'stub-lint'); writeFileSync(stub, '#!/bin/sh\necho "args: $*"\nexit 7\n'); @@ -266,7 +266,7 @@ describe('the compact-lint bin', () => { const run = spawnSync( process.execPath, - [join(packageDir, 'src', 'compactLint.ts'), 'check', '--strict', 'src'], + [join(packageDir, 'src', 'compactLinter.ts'), 'check', '--strict', 'src'], { encoding: 'utf8', env: { ...process.env, COMPACT_LINT_BINARY: stub } }, ); @@ -277,7 +277,7 @@ describe('the compact-lint bin', () => { it('exits 2 when no binary can be resolved', () => { const run = spawnSync( process.execPath, - [join(packageDir, 'src', 'compactLint.ts'), 'check'], + [join(packageDir, 'src', 'compactLinter.ts'), 'check'], { encoding: 'utf8', env: { @@ -288,6 +288,6 @@ describe('the compact-lint bin', () => { ); expect(run.status).toBe(2); - expect(run.stderr).toContain('compact-lint: cannot run'); + expect(run.stderr).toContain('compact-linter: cannot run'); }); }); diff --git a/yarn.lock b/yarn.lock index 65d5c32c..6a5f2373 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1180,16 +1180,16 @@ __metadata: languageName: unknown linkType: soft -"@openzeppelin/compact-lint@workspace:packages/lint": +"@openzeppelin/compact-linter@workspace:packages/linter": version: 0.0.0-use.local - resolution: "@openzeppelin/compact-lint@workspace:packages/lint" + resolution: "@openzeppelin/compact-linter@workspace:packages/linter" dependencies: "@tsconfig/node24": "npm:^24.0.3" "@types/node": "npm:26.1.2" typescript: "npm:^6.0.3" vitest: "npm:^4.1.9" bin: - compact-lint: dist/compactLint.js + compact-linter: dist/compactLinter.js languageName: unknown linkType: soft From 2b058563a3e719d5753114ac6737936aca90aa33 Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Tue, 15 Sep 2026 16:34:51 +0200 Subject: [PATCH 10/56] feat(compact-lint): render biome-style diagnostics The one-line `path:line:col: rule: message` output is replaced by a Biome-shaped block per diagnostic: header with the rule name and a FIXABLE / FIXED badge, the message under a level glyph, a code frame with the span underlined, one advice line, and the fix as a line diff. * Levels: every rule reports at error, warn, info or off, set in a `[rules]` table. Placeholders and unmeasured circuits default to warn so they no longer fail a run; `--strict` promotes placeholders. Exit 1 needs an error, or a warning with `--error-on-warnings`. * Reporters: `default`, `concise` (one line per diagnostic) and `github` (workflow commands, escaped per the spec). Diagnostics go to stdout; the truncation notice and the `Checked N files in T.` summary go to stderr. `--max-diagnostics` caps what is shown at 20. * fix and fill-constraints render through the same reporter, with Safe / Unsafe fix titles and an Applied fix title after a write. --- Cargo.lock | 8 + Cargo.toml | 2 + crates/compact-lint/Cargo.toml | 2 + crates/compact-lint/README.md | 161 ++- .../examples/compact-contracts.toml | 16 + crates/compact-lint/src/check.rs | 96 +- crates/compact-lint/src/config.rs | 103 ++ crates/compact-lint/src/diagnostic.rs | 956 ++++++++++++++++++ crates/compact-lint/src/edit.rs | 79 +- crates/compact-lint/src/fill.rs | 202 ++-- crates/compact-lint/src/fix.rs | 135 ++- crates/compact-lint/src/format.rs | 33 +- crates/compact-lint/src/lib.rs | 3 +- crates/compact-lint/src/main.rs | 238 ++++- crates/compact-lint/src/model.rs | 7 + crates/compact-lint/src/report.rs | 76 +- crates/compact-lint/src/rules.rs | 257 +++-- crates/compact-lint/tests/check.rs | 163 ++- crates/compact-lint/tests/fill.rs | 63 +- crates/compact-lint/tests/fix.rs | 52 +- .../fixtures/constraints-format/expected.txt | 28 +- .../expected-strict.txt | 13 + .../constraints-placeholder/expected.txt | 14 +- .../fixtures/diagnostic-level/Mixed.compact | 16 + .../diagnostic-level/compact-lint.toml | 27 + .../fixtures/diagnostic-level/expected.txt | 17 + .../fixtures/error-on-warnings/Warned.compact | 11 + .../error-on-warnings/compact-lint.toml | 27 + .../fixtures/error-on-warnings/expected.txt | 13 + .../fixtures/fill-basic/expected-dry-run.txt | 45 + .../fixtures/fill-basic/expected-settled.txt | 13 + .../tests/fixtures/fill-basic/expected.txt | 34 +- .../fill-missing-source/expected-dry-run.txt | 11 + .../fill-missing-source/expected-settled.txt | 11 + .../fixtures/fill-missing-source/expected.txt | 12 +- .../fill-no-compile/expected-dry-run.txt | 16 + .../fill-no-compile/expected-settled.txt | 0 .../fixtures/fill-no-compile/expected.txt | 10 +- .../fill-override/expected-dry-run.txt | 16 + .../fill-override/expected-settled.txt | 0 .../tests/fixtures/fill-override/expected.txt | 10 +- .../fixtures/fill-self/expected-dry-run.txt | 32 + .../fixtures/fill-self/expected-settled.txt | 0 .../tests/fixtures/fill-self/expected.txt | 20 +- .../fix-constraints/expected-dry-run.txt | 48 + .../fixtures/fix-constraints/expected.txt | 30 +- .../fixtures/fix-crlf/expected-dry-run.txt | 49 + .../tests/fixtures/fix-crlf/expected.txt | 32 +- .../fix-missing-tag/expected-dry-run.txt | 78 ++ .../fixtures/fix-missing-tag/expected.txt | 50 +- .../fix-module-name/expected-dry-run.txt | 31 + .../fixtures/fix-module-name/expected.txt | 20 +- .../fixtures/fix-rename/expected-dry-run.txt | 32 + .../tests/fixtures/fix-rename/expected.txt | 20 +- .../fix-skeleton/expected-dry-run.txt | 139 +++ .../tests/fixtures/fix-skeleton/expected.txt | 91 +- .../fix-unfixable/expected-dry-run.txt | 0 .../tests/fixtures/forbidden-tag/expected.txt | 28 +- .../fixtures/max-diagnostics/Many.compact | 11 + .../max-diagnostics/compact-lint.toml | 27 + .../fixtures/max-diagnostics/expected.txt | 19 + .../fixtures/missing-constraints/expected.txt | 19 +- .../tests/fixtures/missing-doc/expected.txt | 62 +- .../tests/fixtures/missing-tag/expected.txt | 36 +- .../tests/fixtures/module-name/expected.txt | 18 +- .../tests/fixtures/parse/expected.txt | 12 +- .../fixtures/reporter-concise/Two.compact | 16 + .../reporter-concise/compact-lint.toml | 27 + .../fixtures/reporter-concise/expected.txt | 2 + .../fixtures/reporter-github/Two.compact | 16 + .../reporter-github/compact-lint.toml | 27 + .../fixtures/reporter-github/expected.txt | 2 + .../fixtures/rules-levels/Levels.compact | 14 + .../fixtures/rules-levels/compact-lint.toml | 32 + .../tests/fixtures/rules-levels/expected.txt | 18 + 75 files changed, 3576 insertions(+), 478 deletions(-) create mode 100644 crates/compact-lint/src/diagnostic.rs create mode 100644 crates/compact-lint/tests/fixtures/constraints-placeholder/expected-strict.txt create mode 100644 crates/compact-lint/tests/fixtures/diagnostic-level/Mixed.compact create mode 100644 crates/compact-lint/tests/fixtures/diagnostic-level/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/diagnostic-level/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/error-on-warnings/Warned.compact create mode 100644 crates/compact-lint/tests/fixtures/error-on-warnings/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/error-on-warnings/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/fill-basic/expected-dry-run.txt create mode 100644 crates/compact-lint/tests/fixtures/fill-basic/expected-settled.txt create mode 100644 crates/compact-lint/tests/fixtures/fill-missing-source/expected-dry-run.txt create mode 100644 crates/compact-lint/tests/fixtures/fill-missing-source/expected-settled.txt create mode 100644 crates/compact-lint/tests/fixtures/fill-no-compile/expected-dry-run.txt create mode 100644 crates/compact-lint/tests/fixtures/fill-no-compile/expected-settled.txt create mode 100644 crates/compact-lint/tests/fixtures/fill-override/expected-dry-run.txt create mode 100644 crates/compact-lint/tests/fixtures/fill-override/expected-settled.txt create mode 100644 crates/compact-lint/tests/fixtures/fill-self/expected-dry-run.txt create mode 100644 crates/compact-lint/tests/fixtures/fill-self/expected-settled.txt create mode 100644 crates/compact-lint/tests/fixtures/fix-constraints/expected-dry-run.txt create mode 100644 crates/compact-lint/tests/fixtures/fix-crlf/expected-dry-run.txt create mode 100644 crates/compact-lint/tests/fixtures/fix-missing-tag/expected-dry-run.txt create mode 100644 crates/compact-lint/tests/fixtures/fix-module-name/expected-dry-run.txt create mode 100644 crates/compact-lint/tests/fixtures/fix-rename/expected-dry-run.txt create mode 100644 crates/compact-lint/tests/fixtures/fix-skeleton/expected-dry-run.txt create mode 100644 crates/compact-lint/tests/fixtures/fix-unfixable/expected-dry-run.txt create mode 100644 crates/compact-lint/tests/fixtures/max-diagnostics/Many.compact create mode 100644 crates/compact-lint/tests/fixtures/max-diagnostics/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/max-diagnostics/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/reporter-concise/Two.compact create mode 100644 crates/compact-lint/tests/fixtures/reporter-concise/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/reporter-concise/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/reporter-github/Two.compact create mode 100644 crates/compact-lint/tests/fixtures/reporter-github/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/reporter-github/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/rules-levels/Levels.compact create mode 100644 crates/compact-lint/tests/fixtures/rules-levels/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/rules-levels/expected.txt diff --git a/Cargo.lock b/Cargo.lock index 778d546a..4aaaacdd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -177,6 +177,7 @@ checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" name = "compact-lint" version = "0.1.0" dependencies = [ + "anstyle", "anyhow", "assert_cmd", "clap", @@ -185,6 +186,7 @@ dependencies = [ "portable-pty", "serde", "serde_json", + "similar", "tempfile", "thiserror 2.0.20", "toml", @@ -573,6 +575,12 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "similar" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa" + [[package]] name = "streaming-iterator" version = "0.1.9" diff --git a/Cargo.toml b/Cargo.toml index a235a014..45eaeb2e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,6 +19,7 @@ codegen-units = 1 pedantic = { level = "warn", priority = -1 } [workspace.dependencies] +anstyle = "1.0" anyhow = "1.0" cc = "1" clap = { version = "4.6", features = ["derive", "env"] } @@ -26,6 +27,7 @@ globset = "0.4" portable-pty = "0.9" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" +similar = "2.7" thiserror = "2.0" toml = "1.1" tree-sitter = "0.25" diff --git a/crates/compact-lint/Cargo.toml b/crates/compact-lint/Cargo.toml index 014ed0b5..c7a65b41 100644 --- a/crates/compact-lint/Cargo.toml +++ b/crates/compact-lint/Cargo.toml @@ -19,12 +19,14 @@ name = "compact-lint" path = "src/main.rs" [dependencies] +anstyle.workspace = true anyhow.workspace = true clap.workspace = true globset.workspace = true portable-pty.workspace = true serde.workspace = true serde_json.workspace = true +similar.workspace = true tempfile.workspace = true thiserror.workspace = true toml.workspace = true diff --git a/crates/compact-lint/README.md b/crates/compact-lint/README.md index 434efe14..b562ca59 100644 --- a/crates/compact-lint/README.md +++ b/crates/compact-lint/README.md @@ -2,7 +2,7 @@ Doc-comment linter for Compact sources. It parses `.compact` files with [`compact-tree-sitter`](../compact-tree-sitter), matches every declaration against the -per-kind template in `compact-lint.toml`, and prints one finding per line. `fix` +per-kind template in `compact-lint.toml`, and prints one diagnostic per violation. `fix` rewrites the comments the repairable rules report. `fill-constraints` compiles the contracts and writes the measured `k` and `rows` into the annotations. @@ -16,9 +16,9 @@ contracts and writes the measured `k` and `rows` into the annotations. ## Usage ```sh -compact-lint check [PATHS]... [--config ] [--strict] [--no-format] [--compact-bin ] -compact-lint fix [PATHS]... [--config ] [--dry-run] -compact-lint fill-constraints [PATHS]... [--config ] [--dry-run] [--no-compile] [--compact-bin ] [--artifacts ] +compact-lint check [PATHS]... [--config ] [--strict] [--no-format] [--compact-bin ] [OUTPUT] +compact-lint fix [PATHS]... [--config ] [--dry-run] [OUTPUT] +compact-lint fill-constraints [PATHS]... [--config ] [--dry-run] [--no-compile] [--compact-bin ] [--artifacts ] [OUTPUT] ``` - `PATHS` β€” files or directories, walked recursively for `.compact`. Skipped while @@ -26,21 +26,96 @@ compact-lint fill-constraints [PATHS]... [--config ] [--dry-run] [--no-com - No `PATHS` β€” the config's `include` globs are used instead. - `--config ` β€” use this config instead of searching upward for `compact-lint.toml`. -- `--strict` β€” turn `k=?` / `rows=?` placeholders into findings. Use it on release - branches. +- `--strict` β€” report `k=?` / `rows=?` placeholders as errors instead of warnings. Use + it on release branches. - `--no-format` β€” skip the `compact format --check` pass. Required where the `compact` - binary is unavailable, CI included. + binary is unavailable, CI included. Same effect as `format = "off"` in `[rules]`. - `--compact-bin ` β€” path to the `compact` binary. Also settable with `COMPACT_LINT_COMPACT_BIN`; the flag wins. -Findings go to stdout, one per line, in `path:line:col: rule: message` form (the -rustc / eslint shape, so editors and `grep` both read it). The `N findings in M files` -summary goes to stderr, where `M` is the number of files checked. +`OUTPUT` is the same set of flags on all three subcommands: + +- `--reporter ` β€” output format, default `default`. +- `--diagnostic-level ` β€” lowest level shown, default `info`. The + summary still counts what it hides. +- `--error-on-warnings` β€” exit `1` on a run that only warned. +- `--max-diagnostics ` β€” diagnostics shown before the rest are only counted, + default `20`. +- `--colors ` β€” default: colour when stdout is a TTY and `NO_COLOR` is unset. + +## Output + +- Diagnostics go to stdout; the truncation notice and the summary go to stderr. +- `default` β€” Biome-style block per diagnostic: header, message, code frame, `i` advice, + and the fix as a line diff where one exists. +- `concise` β€” ` path:line:col: : `, one line per diagnostic. +- `github` β€” `::error|warning|notice title=…,file=…,line=…::` workflow commands. +- Glyphs: `Γ—` error, `!` warning, `i` info. +- Rule names read `lint/`, except `parse`, `format` and `fill`, which are bare. +- `FIXABLE` in a header means `fix` repairs it; `FIXED` means this run already did. +- The summary reads `Checked N files in .` plus what the run did, then + `Found N errors.` and `Found N warnings.` lines when either is non-zero. +- A clean run prints only the summary line. + +``` +Gaps.compact:6:3 lint/missing-doc FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + Γ— Ledger `_owner` has no doc comment. + + 4 β”‚ */ + 5 β”‚ export module Gaps { + > 6 β”‚ export ledger _owner: Bytes<32>; + β”‚ ^^^^^^^^^^^^^^^^^^^^ + 7 β”‚ + 8 β”‚ export enum Kind { + + i Add a doc comment above it, or run compact-lint fix. + + i Unsafe fix: Insert a doc skeleton for ledger `_owner` + + 6 β”‚ + Β·Β·/** + 7 β”‚ + Β·Β·Β·*Β·@descriptionΒ·TODO + 8 β”‚ + Β·Β·Β·*/ +``` + +with this on stderr: + +``` +Checked 1 file in 2ms. No fixes applied. +Found 3 errors. +``` + +## Diagnostic levels + +- Every rule reports at a level: `error`, `warn`, `info`, or `off`. +- `off` stops the rule running; its findings never reach the report or the counts. +- Set them in `[rules]`, keyed by rule id: + +```toml +[rules] +missing-doc = "error" +constraints-placeholder = "warn" +format = "off" +``` + +Defaults: + +| Rule | Level | +| --- | --- | +| `missing-doc`, `missing-tag`, `forbidden-tag`, `module-name` | `error` | +| `missing-constraints`, `constraints-format` | `error` | +| `parse`, `format` | `error` | +| `constraints-placeholder` | `warn` | +| `constraints-unmeasured`, `constraints-unmeasurable` | `warn` | + +- `--strict` promotes `constraints-placeholder` to `error` for that run; a rule set to + `off` stays off. +- An unknown key in `[rules]` is a config error. ## Exit codes -- `0` β€” no findings. -- `1` β€” findings. +- `0` β€” no error-level diagnostics. +- `1` β€” at least one error-level diagnostic, or a warning with `--error-on-warnings`. - `2` β€” usage, config, IO or parser error. ## Fix @@ -56,8 +131,15 @@ compact-lint fix [PATHS]... [--config ] [--dry-run] - `--dry-run` β€” report the edits and write nothing. Exit `1` when there are edits, so CI gates on it the way it gates on `cargo fmt --check`. -Edits go to stdout, one per line, in `path:line:col: fix: ` form. The -`N edits in M files` summary goes to stderr, where `M` is the number of files changed. +- One `info` diagnostic per edit goes to stdout, with the rewrite as a line diff. +- An offered fix reads `Safe fix:` when it writes a value the tool knows (`forbidden-tag` + renames, `module-name`) and `Unsafe fix:` when it writes a `TODO` or `k=?, rows=?` + placeholder a human still has to replace (`missing-doc`, `missing-tag`, + `missing-constraints`). `fill-constraints` writes measured values, so its fixes are + safe. +- A write run heads each with `FIXED`; `--dry-run` heads each with `FIXABLE` and keeps + the code frame of the unchanged file. +- The summary reads `Fixed N files.` for a write run, `No fixes applied.` for a preview. Exit codes: @@ -114,15 +196,22 @@ comment carries `constraints.tag`, whatever its value. A circuit with no annotat `fix`'s job and is left alone here. A file holding a parse defect is skipped, so `check` stays the place a syntax error is reported. -Changes go to stdout, one per line: +Each filled value is an `info` diagnostic carrying the annotation's before and after: ``` -contracts/src/access/Ownable.compact:59:6: fill: @constraints k=?, rows=? -> k=13, rows=4273 +contracts/src/access/Ownable.compact:59:6 fill FIXED ━━━━━━━━━━ + + i Circuit `transferOwnership` measures k=13, rows=4273. + + i Applied fix: Set @constraints to k=13, rows=4273 + + 59 β”‚ - Β·Β·Β·*Β·@constraintsΒ·k=?,Β·rows=? + 59 β”‚ + Β·Β·Β·*Β·@constraintsΒ·k=13,Β·rows=4273 ``` -The `N values filled in M files, U unmeasured` summary goes to stderr. `M` counts the -files that changed; `U` counts every tagged circuit left without a value, including the -ones in a file with no measurement source. +The `Filled N values in M files.` summary goes to stderr, with `Found N warnings.` under +it. `M` counts the files that changed; the warnings are the tagged circuits left without +a value, including the ones in a file with no measurement source. ### How a source is resolved @@ -160,17 +249,11 @@ A tagged circuit is *unmeasured* when its source compiled but produced no measur its name. That happens where the mock has no exported circuit of that name β€” `initialize` is called from the mock's constructor, never exported β€” or where the compiler's `contract-info.json` marks the circuit `proof: false`, which carries no constraints. The -value is left alone and the circuit is reported: - -``` -contracts/src/access/Ownable.compact:37:6: constraints-unmeasured: circuit `initialize` has no measurement in contracts/src/access/test/mocks/MockOwnable.compact -``` +value is left alone and the circuit is reported as `constraints-unmeasured`, at `warn` +by default, with the source that measures it named in the advice. -A file with no measurement source at all is reported once, with the candidates tried: - -``` -contracts/src/utils/Utils.compact:1:1: constraints-unmeasurable: no measurement source for contracts/src/utils/Utils.compact; tried contracts/src/utils/test/mocks/MockUtils.compact, contracts/src/test/mocks/MockUtils.compact -``` +A file with no measurement source at all is reported once as `constraints-unmeasurable`, +with the candidates tried named in the advice. Exit codes: @@ -193,7 +276,9 @@ the line ending, and only the annotation's own line changes. | `module-name` | `@module ` does not name the module it documents. | | `missing-constraints` | An exported non-pure circuit has no constraints tag. | | `constraints-format` | The constraints value is not `k=, rows=`. | -| `constraints-placeholder` | `--strict` only: the constraints value still holds a `?`. | +| `constraints-placeholder` | The constraints value still holds a `?`. | +| `constraints-unmeasured` | `fill-constraints` only: the source compiled but measured no circuit of that name. | +| `constraints-unmeasurable` | `fill-constraints` only: no measurement source resolves for the file. | | `parse` | The file holds a syntax defect; the first one is reported and the doc rules are skipped for that file. | | `format` | `compact format --check` reported the file. | @@ -241,6 +326,9 @@ rename = { "@return" = "@returns" } [fix] placeholder = "TODO" +[rules] +constraints-placeholder = "warn" + [kinds.module] docs = "exported" tags = ["@module", "@description"] @@ -261,6 +349,7 @@ Defaults when no config file is found: | `tags.forbid` | `[]` | | `tags.rename` | `{}` | | `fix.placeholder` | `"TODO"` | +| `rules.` | `"error"`, except the four listed under Diagnostic levels | | `kinds..docs` | `"exported"` | | `kinds..tags` | `[]` | @@ -276,6 +365,7 @@ Defaults when no config file is found: are validated like every other tag. An unmapped forbidden tag is reported, never rewritten. - `fix.placeholder` is the text `fix` writes where it has no value of its own. +- `rules` takes one key per rule id, valued `"off"`, `"info"`, `"warn"` or `"error"`. - `constraints.compiler` is passed as `+` to `compact compile`. - `constraints.sources` templates are tried in order; the first existing file wins. - `constraints.self` marks files that compile themselves, so no mock is looked for. @@ -301,13 +391,16 @@ cargo test --workspace `tests/fixtures//` holds one `check` case per rule plus a clean case: a `compact-lint.toml`, the `.compact` sources, and `expected.txt`, the exact stdout with -paths relative to the case directory. +paths relative to the case directory. A case that also runs under a flag carries the +second expectation beside it, such as `expected-strict.txt`. `tests/fixtures/fix-/` holds one `fix` case per rule: a `compact-lint.toml`, -`before/`, `after/` and `expected.txt`. The run copies `before/` into a temporary -directory, so the fixtures are never rewritten in place. +`before/`, `after/`, `expected.txt` for the write run and `expected-dry-run.txt` for the +preview. The run copies `before/` into a temporary directory, so the fixtures are never +rewritten in place. -`tests/fixtures/fill-/` holds the `fill-constraints` cases in the same shape. They +`tests/fixtures/fill-/` holds the `fill-constraints` cases in the same shape, plus +`expected-settled.txt` for what a second run still reports. They run against `tests/fixtures/fill-fake-compact/bin/compact`, a shell script that prints the compiler's progress lines for a hard-coded table and writes a matching `contract-info.json`, so the tests need no toolchain. It still runs through the pty, so diff --git a/crates/compact-lint/examples/compact-contracts.toml b/crates/compact-lint/examples/compact-contracts.toml index ef9489eb..6667f2a2 100644 --- a/crates/compact-lint/examples/compact-contracts.toml +++ b/crates/compact-lint/examples/compact-contracts.toml @@ -16,6 +16,22 @@ self = ["**/presets/**"] forbid = ["@return"] rename = { "@return" = "@returns" } +# Every rule's default level, spelled out. Set one to "off" to stop it running, or to +# "warn" / "info" to keep it out of the exit code. `check --strict` promotes +# constraints-placeholder to "error" for that run. +# [rules] +# missing-doc = "error" +# missing-tag = "error" +# forbidden-tag = "error" +# module-name = "error" +# missing-constraints = "error" +# constraints-format = "error" +# constraints-placeholder = "warn" +# constraints-unmeasured = "warn" +# constraints-unmeasurable = "warn" +# parse = "error" +# format = "error" + [kinds.module] docs = "exported" tags = ["@module", "@description"] diff --git a/crates/compact-lint/src/check.rs b/crates/compact-lint/src/check.rs index 7fbc195f..cc21f6da 100644 --- a/crates/compact-lint/src/check.rs +++ b/crates/compact-lint/src/check.rs @@ -5,8 +5,12 @@ use std::path::{Path, PathBuf}; use thiserror::Error; +use crate::config::Config; +use crate::diagnostic::{Badge, Diagnostic, FixPreview, Level}; +use crate::edit::{apply, newline_of}; +use crate::fix; use crate::format::{self, FormatError}; -use crate::report::Finding; +use crate::report::RuleId; use crate::rules::{LintError, Linter}; use crate::target::{self, TargetError}; @@ -35,23 +39,12 @@ pub struct Options { pub compact_bin: OsString, } -/// The findings, plus how many files produced them. +/// The diagnostics, plus how many files produced them. pub struct Outcome { - pub findings: Vec, + pub diagnostics: Vec, pub files_checked: usize, } -impl Outcome { - #[must_use] - pub fn summary(&self) -> String { - format!( - "{} findings in {} files", - self.findings.len(), - self.files_checked - ) - } -} - /// Runs the subcommand with `cwd` as the working directory. /// # Errors /// Returns an error when the config, the file walk, the parser or the formatter fails. @@ -59,22 +52,85 @@ pub fn run(options: &Options, cwd: &Path) -> Result { let target = target::resolve(&options.paths, options.config_path.as_deref(), cwd)?; let mut linter = Linter::new()?; - let mut findings = Vec::new(); + let mut diagnostics = Vec::new(); for path in &target.files { let text = std::fs::read_to_string(path).map_err(|source| CheckError::Read { path: path.clone(), source, })?; - findings.extend(linter.check(path, &text, &target.config, options.strict)?); + let newline = newline_of(&text); + + for issue in linter.issues(path, &text, &target.config)? { + let level = level_of(issue.rule(), &target.config, options.strict); + let diagnostic = issue.diagnostic(path, level, &target.config); + + diagnostics.push(match fix::edit_for(&issue, &target.config, newline) { + Some(edit) => { + let after = apply(&text, std::slice::from_ref(&edit), newline); + let title = fix::title(&edit, Badge::Fixable); + diagnostic.fixed_by(FixPreview::between(title, &text, &after), Badge::Fixable) + } + None => diagnostic, + }); + } } - if !options.no_format { - findings.extend(format::check(&options.compact_bin, &target.files)?); + let format_level = target.config.rules.get(RuleId::FORMAT); + if !options.no_format && format_level != Level::Off { + diagnostics.extend(format::check( + &options.compact_bin, + &target.files, + format_level, + )?); } - findings.sort_by(|left, right| left.sort_key().cmp(&right.sort_key())); + diagnostics.sort_by(|left, right| left.sort_key().cmp(&right.sort_key())); Ok(Outcome { - findings, + diagnostics, files_checked: target.files.len(), }) } + +/// `--strict` promotes a placeholder to an error; a rule turned off stays off. +fn level_of(rule: RuleId, config: &Config, strict: bool) -> Level { + let level = config.rules.get(rule); + if strict && rule == RuleId::CONSTRAINTS_PLACEHOLDER && level != Level::Off { + Level::Error + } else { + level + } +} + +#[cfg(test)] +mod tests { + use super::level_of; + use crate::config::Config; + use crate::diagnostic::Level; + use crate::report::RuleId; + + #[test] + fn strict_promotes_a_placeholder_and_leaves_the_other_rules_alone() { + let config = Config::default(); + + assert_eq!( + level_of(RuleId::CONSTRAINTS_PLACEHOLDER, &config, false), + Level::Warn + ); + assert_eq!( + level_of(RuleId::CONSTRAINTS_PLACEHOLDER, &config, true), + Level::Error + ); + assert_eq!(level_of(RuleId::MISSING_DOC, &config, true), Level::Error); + } + + #[test] + fn strict_does_not_revive_a_placeholder_rule_turned_off() { + let mut config = Config::default(); + config.rules.constraints_placeholder = Level::Off; + + assert_eq!( + level_of(RuleId::CONSTRAINTS_PLACEHOLDER, &config, true), + Level::Off + ); + } +} diff --git a/crates/compact-lint/src/config.rs b/crates/compact-lint/src/config.rs index d633c480..46d69314 100644 --- a/crates/compact-lint/src/config.rs +++ b/crates/compact-lint/src/config.rs @@ -7,8 +7,10 @@ use globset::{Glob, GlobSet, GlobSetBuilder}; use serde::Deserialize; use thiserror::Error; +use crate::diagnostic::Level; use crate::doc::Tag; use crate::model::DeclKind; +use crate::report::RuleId; /// The config file name searched for upward from the current directory. pub const CONFIG_FILE_NAME: &str = "compact-lint.toml"; @@ -143,6 +145,73 @@ impl Default for ConstraintsConfig { } } +/// The level each rule reports at; `off` stops it running. +#[derive(Clone, Debug, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields, default)] +pub struct RulesConfig { + #[serde(rename = "missing-doc")] + pub missing_doc: Level, + #[serde(rename = "missing-tag")] + pub missing_tag: Level, + #[serde(rename = "forbidden-tag")] + pub forbidden_tag: Level, + #[serde(rename = "module-name")] + pub module_name: Level, + #[serde(rename = "missing-constraints")] + pub missing_constraints: Level, + #[serde(rename = "constraints-format")] + pub constraints_format: Level, + #[serde(rename = "constraints-placeholder")] + pub constraints_placeholder: Level, + #[serde(rename = "constraints-unmeasured")] + pub constraints_unmeasured: Level, + #[serde(rename = "constraints-unmeasurable")] + pub constraints_unmeasurable: Level, + pub parse: Level, + pub format: Level, +} + +impl Default for RulesConfig { + fn default() -> Self { + Self { + missing_doc: Level::Error, + missing_tag: Level::Error, + forbidden_tag: Level::Error, + module_name: Level::Error, + missing_constraints: Level::Error, + constraints_format: Level::Error, + // A placeholder is a value waiting on a measurement, not a defect; `--strict` + // promotes it on release branches. + constraints_placeholder: Level::Warn, + constraints_unmeasured: Level::Warn, + constraints_unmeasurable: Level::Warn, + parse: Level::Error, + format: Level::Error, + } + } +} + +impl RulesConfig { + #[must_use] + pub fn get(&self, rule: RuleId) -> Level { + match rule { + RuleId::MISSING_DOC => self.missing_doc, + RuleId::MISSING_TAG => self.missing_tag, + RuleId::FORBIDDEN_TAG => self.forbidden_tag, + RuleId::MODULE_NAME => self.module_name, + RuleId::MISSING_CONSTRAINTS => self.missing_constraints, + RuleId::CONSTRAINTS_FORMAT => self.constraints_format, + RuleId::CONSTRAINTS_PLACEHOLDER => self.constraints_placeholder, + RuleId::CONSTRAINTS_UNMEASURED => self.constraints_unmeasured, + RuleId::CONSTRAINTS_UNMEASURABLE => self.constraints_unmeasurable, + RuleId::PARSE => self.parse, + RuleId::FORMAT => self.format, + // `fill` reports what changed, so it is not configurable. + _ => Level::Info, + } + } +} + /// Tags no doc comment may carry, and the replacements `fix` writes for them. #[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq)] #[serde(deny_unknown_fields, default)] @@ -178,6 +247,7 @@ pub struct Config { pub tags: TagsConfig, pub fix: FixConfig, pub kinds: KindsConfig, + pub rules: RulesConfig, } impl Default for Config { @@ -190,6 +260,7 @@ impl Default for Config { tags: TagsConfig::default(), fix: FixConfig::default(), kinds: KindsConfig::default(), + rules: RulesConfig::default(), } } } @@ -309,8 +380,40 @@ pub fn discover(start: &Path) -> Option { #[cfg(test)] mod tests { use super::{Config, DocsPolicy, SUPPORTED_VERSION}; + use crate::diagnostic::Level; use crate::doc::Tag; use crate::model::DeclKind; + use crate::report::RuleId; + + #[test] + fn every_rule_defaults_to_error_but_the_ones_awaiting_a_measurement() { + let rules = Config::default().rules; + + assert_eq!(rules.get(RuleId::MISSING_DOC), Level::Error); + assert_eq!(rules.get(RuleId::PARSE), Level::Error); + assert_eq!(rules.get(RuleId::FORMAT), Level::Error); + assert_eq!(rules.get(RuleId::CONSTRAINTS_PLACEHOLDER), Level::Warn); + assert_eq!(rules.get(RuleId::CONSTRAINTS_UNMEASURED), Level::Warn); + assert_eq!(rules.get(RuleId::CONSTRAINTS_UNMEASURABLE), Level::Warn); + } + + #[test] + fn a_rules_table_sets_only_the_rules_it_names() { + let config: Config = toml::from_str("[rules]\nmissing-doc = \"off\"\nformat = \"warn\"\n") + .expect("the snippet is valid config"); + + assert_eq!(config.rules.get(RuleId::MISSING_DOC), Level::Off); + assert_eq!(config.rules.get(RuleId::FORMAT), Level::Warn); + assert_eq!(config.rules.get(RuleId::MISSING_TAG), Level::Error); + } + + #[test] + fn an_unknown_rule_key_is_rejected() { + let error = toml::from_str::("[rules]\nmissing-docs = \"off\"\n") + .expect_err("the rule is misspelled"); + + assert!(error.to_string().contains("missing-docs"), "{error}"); + } #[test] fn defaults_require_docs_on_exported_declarations_only() { diff --git a/crates/compact-lint/src/diagnostic.rs b/crates/compact-lint/src/diagnostic.rs new file mode 100644 index 00000000..8e1b732e --- /dev/null +++ b/crates/compact-lint/src/diagnostic.rs @@ -0,0 +1,956 @@ +//! Diagnostics and the three reporters that render them. +//! +//! A [`Diagnostic`] carries everything a reporter prints: where, which rule, at which +//! [`Level`], and optionally a [`FixPreview`] rendered as a line diff. + +use std::collections::BTreeMap; +use std::fmt::Write as _; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use anstyle::{AnsiColor, Color, Style}; +use serde::Deserialize; +use similar::{ChangeTag, DiffTag, TextDiff}; + +use crate::report::{Position, RuleId}; + +/// Total width a header fills, rule glyphs included. +const HEADER_WIDTH: usize = 100; + +/// Shortest run of header rule glyphs, whatever the header's length. +const MIN_RULE_GLYPHS: usize = 10; + +/// Body indentation under a header. +const INDENT: &str = " "; + +/// Source lines shown on each side of the finding line. +const CONTEXT: usize = 2; + +/// Printed when the cap hides diagnostics. +pub const TRUNCATION_NOTICE: &str = + "The number of diagnostics exceeds the limit allowed. Use --max-diagnostics to increase it."; + +/// How loudly a rule reports, and whether it runs at all. +#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, PartialOrd, Ord)] +#[serde(rename_all = "lowercase")] +pub enum Level { + /// The rule is not run and its findings are dropped. + Off, + Info, + Warn, + #[default] + Error, +} + +impl Level { + /// The glyph the default and concise reporters print. + #[must_use] + pub const fn glyph(self) -> char { + match self { + Self::Error => '\u{d7}', + Self::Warn => '!', + Self::Off | Self::Info => 'i', + } + } + + /// The GitHub workflow-command name. + #[must_use] + pub const fn github(self) -> &'static str { + match self { + Self::Error => "error", + Self::Warn => "warning", + Self::Off | Self::Info => "notice", + } + } + + const fn color(self) -> AnsiColor { + match self { + Self::Error => AnsiColor::Red, + Self::Warn => AnsiColor::Yellow, + Self::Off | Self::Info => AnsiColor::Cyan, + } + } +} + +/// The source range a diagnostic underlines, end exclusive. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Span { + pub start: Position, + pub end: Position, +} + +impl Span { + #[must_use] + pub const fn new(start: Position, end: Position) -> Self { + Self { start, end } + } + + /// A span covering `width` columns of one line. + #[must_use] + pub const fn columns(start: Position, width: usize) -> Self { + Self { + start, + end: Position { + line: start.line, + column: start.column + width, + }, + } + } +} + +/// The line window an edit rewrites, before and after it applies. +/// +/// `first_line` is the 1-based line the window opens on. Both sides open there, because +/// the window starts at the first line the two texts differ on. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct FixPreview { + pub title: String, + pub before: String, + pub after: String, + pub first_line: usize, +} + +impl FixPreview { + /// The window two versions of one file differ over, or `None` when they match. + #[must_use] + pub fn between(title: String, before: &str, after: &str) -> Option { + let diff = TextDiff::from_lines(before, after); + let mut changed = diff.ops().iter().filter(|op| op.tag() != DiffTag::Equal); + + let first = changed.next()?; + let last = changed.next_back().unwrap_or(first); + let old = first.old_range().start..last.old_range().end; + let new = first.new_range().start..last.new_range().end; + + Some(Self { + title, + before: diff.old_slices().get(old.clone())?.concat(), + after: diff.new_slices().get(new)?.concat(), + first_line: old.start + 1, + }) + } +} + +/// Whether the run applied the fix or only offers it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Badge { + Fixable, + Fixed, +} + +impl Badge { + const fn as_str(self) -> &'static str { + match self { + Self::Fixable => "FIXABLE", + Self::Fixed => "FIXED", + } + } +} + +/// One reported problem, with everything the reporters print for it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Diagnostic { + pub path: PathBuf, + /// Absent for a whole-file diagnostic, which prints no `line:col`. + pub span: Option, + pub rule: RuleId, + pub level: Level, + pub message: String, + pub advice: Vec, + pub fix: Option, + pub badge: Option, +} + +impl Diagnostic { + pub fn new(path: impl Into, rule: RuleId, level: Level, message: String) -> Self { + Self { + path: path.into(), + span: None, + rule, + level, + message, + advice: Vec::new(), + fix: None, + badge: None, + } + } + + #[must_use] + pub const fn at(mut self, span: Span) -> Self { + self.span = Some(span); + self + } + + #[must_use] + pub fn advise(mut self, advice: impl Into) -> Self { + self.advice.push(advice.into()); + self + } + + /// Attaches the preview and the badge that names its state. + #[must_use] + pub fn fixed_by(mut self, preview: Option, badge: Badge) -> Self { + if preview.is_some() { + self.badge = Some(badge); + } + self.fix = preview; + self + } + + /// Sorts by file, then position, then rule, so output is stable across runs. + #[must_use] + pub fn sort_key(&self) -> (&Path, Position, RuleId) { + ( + self.path.as_path(), + self.span + .map_or_else(Position::file_start, |span| span.start), + self.rule, + ) + } +} + +/// The rule name in a header, a concise line and a GitHub `title`. +/// +/// Doc rules are namespaced the way Biome namespaces its lint rules; the passes that are +/// not doc rules keep their bare name. +#[must_use] +pub fn display_name(rule: RuleId) -> String { + match rule { + RuleId::PARSE | RuleId::FORMAT | RuleId::FILL => rule.as_str().to_owned(), + _ => format!("lint/{rule}"), + } +} + +/// Capitalises the first letter. +#[must_use] +pub fn capitalise(body: &str) -> String { + let mut characters = body.chars(); + match characters.next() { + Some(first) => format!("{}{}", first.to_uppercase(), characters.as_str()), + None => String::new(), + } +} + +/// Capitalises the first letter and closes the sentence with a period. +#[must_use] +pub fn sentence(body: &str) -> String { + let opened = capitalise(body); + if opened.ends_with('.') { + opened + } else { + format!("{opened}.") + } +} + +/// How many diagnostics are at error and at warning level. +#[must_use] +pub fn counts(diagnostics: &[Diagnostic]) -> (usize, usize) { + let errors = diagnostics + .iter() + .filter(|diagnostic| diagnostic.level == Level::Error) + .count(); + let warnings = diagnostics + .iter() + .filter(|diagnostic| diagnostic.level == Level::Warn) + .count(); + (errors, warnings) +} + +/// Which reporter renders a run. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, clap::ValueEnum)] +pub enum Reporter { + /// Header, code frame, advice and fix diff. + #[default] + Default, + /// One line per diagnostic. + Concise, + /// GitHub workflow commands. + Github, +} + +/// Everything the output flags resolve to. +#[derive(Clone, Copy, Debug)] +pub struct Output { + pub reporter: Reporter, + /// Lowest level shown; diagnostics below it still count in the summary. + pub level: Level, + /// Cap on shown diagnostics; `None` lifts it. + pub max: Option, + pub colors: bool, +} + +impl Default for Output { + fn default() -> Self { + Self { + reporter: Reporter::default(), + level: Level::Info, + max: Some(20), + colors: false, + } + } +} + +impl Output { + /// Writes every shown diagnostic and returns how many the cap hid. + /// # Errors + /// Returns an error when the writer fails. + pub fn render( + &self, + out: &mut impl Write, + diagnostics: &[Diagnostic], + ) -> std::io::Result { + let mut sources = Sources::default(); + let mut shown = 0; + let mut hidden = 0; + + for diagnostic in diagnostics { + if diagnostic.level < self.level || diagnostic.level == Level::Off { + continue; + } + if self.max.is_some_and(|max| shown >= max) { + hidden += 1; + continue; + } + shown += 1; + + match self.reporter { + Reporter::Default => { + out.write_all(default_block(diagnostic, &mut sources, self.colors).as_bytes())?; + } + Reporter::Concise => { + out.write_all(concise_line(diagnostic, self.colors).as_bytes())?; + } + Reporter::Github => out.write_all(github_line(diagnostic).as_bytes())?, + } + } + + out.flush()?; + Ok(hidden) + } +} + +/// The two-line notice printed when the cap hid diagnostics. +#[must_use] +pub fn truncation(hidden: usize) -> String { + format!("{TRUNCATION_NOTICE}\nDiagnostics not shown: {hidden}.") +} + +/// What a run did to the files it read, as the summary phrases it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Action { + /// `check`, and `fix --dry-run`. + NoFixes, + /// Files rewritten by `fix`. + Fixed(usize), + /// Values written by `fill-constraints`, and the files that took them. + Filled { values: usize, files: usize }, +} + +/// The stderr summary, built from a measured duration so tests can pin it. +#[derive(Clone, Copy, Debug)] +pub struct Summary { + pub files: usize, + pub duration: Duration, + pub action: Action, + pub errors: usize, + pub warnings: usize, +} + +impl Summary { + #[must_use] + pub fn render(&self) -> String { + let action = match self.action { + Action::NoFixes => " No fixes applied.".to_owned(), + Action::Fixed(files) => format!(" Fixed {}.", plural(files, "file")), + Action::Filled { values, files } => format!( + " Filled {} in {}.", + plural(values, "value"), + plural(files, "file") + ), + }; + + let mut out = format!( + "Checked {} in {}.{action}", + plural(self.files, "file"), + duration(self.duration) + ); + if self.errors > 0 { + let _ = write!(out, "\nFound {}.", plural(self.errors, "error")); + } + if self.warnings > 0 { + let _ = write!(out, "\nFound {}.", plural(self.warnings, "warning")); + } + out + } +} + +fn plural(count: usize, word: &str) -> String { + if count == 1 { + format!("{count} {word}") + } else { + format!("{count} {word}s") + } +} + +/// Sub-millisecond runs keep their microseconds; a run over a second reads in seconds. +fn duration(elapsed: Duration) -> String { + let micros = elapsed.as_micros(); + if micros < 1_000 { + format!("{micros}\u{b5}s") + } else if micros < 1_000_000 { + format!("{}ms", micros / 1_000) + } else { + format!("{:.1}s", elapsed.as_secs_f64()) + } +} + +/// File texts read for code frames, read once per file. +#[derive(Default)] +struct Sources { + texts: BTreeMap>, +} + +impl Sources { + fn get(&mut self, path: &Path) -> Option<&str> { + self.texts + .entry(path.to_owned()) + .or_insert_with(|| std::fs::read_to_string(path).ok()) + .as_deref() + } +} + +fn paint(text: &str, style: Style, colors: bool) -> String { + if colors { + format!("{}{text}{}", style.render(), style.render_reset()) + } else { + text.to_owned() + } +} + +const fn level_style(level: Level) -> Style { + Style::new().fg_color(Some(Color::Ansi(level.color()))) +} + +fn header(diagnostic: &Diagnostic, colors: bool) -> String { + let location = match diagnostic.span { + Some(span) => format!( + "{}:{}:{}", + diagnostic.path.display(), + span.start.line, + span.start.column + ), + None => diagnostic.path.display().to_string(), + }; + let name = display_name(diagnostic.rule); + + let plain = match diagnostic.badge { + Some(badge) => format!("{location} {name} {} ", badge.as_str()), + None => format!("{location} {name} "), + }; + let glyphs = HEADER_WIDTH + .saturating_sub(plain.chars().count()) + .max(MIN_RULE_GLYPHS); + + let painted = paint(&location, Style::new().bold(), colors); + format!( + "{}{}{}\n", + painted, + &plain[location.len()..], + "\u{2501}".repeat(glyphs) + ) +} + +/// Header, message, code frame, advice, fix diff; one blank line between blocks. +fn default_block(diagnostic: &Diagnostic, sources: &mut Sources, colors: bool) -> String { + let style = level_style(diagnostic.level); + let mut out = header(diagnostic, colors); + + let glyph = paint(&diagnostic.level.glyph().to_string(), style.bold(), colors); + let _ = write!(out, "\n{INDENT}{glyph} {}\n", diagnostic.message); + + // An applied fix already rewrote the file, so the diff below stands in for the frame. + if diagnostic.badge != Some(Badge::Fixed) + && let Some(span) = diagnostic.span + && let Some(source) = sources.get(&diagnostic.path) + && let Some(frame) = frame(source, span, style, colors) + { + let _ = write!(out, "\n{frame}"); + } + + let info = paint("i", level_style(Level::Info).bold(), colors); + for advice in &diagnostic.advice { + let _ = write!(out, "\n{INDENT}{info} {advice}\n"); + } + + if let Some(preview) = &diagnostic.fix { + let _ = write!(out, "\n{INDENT}{info} {}\n", preview.title); + let _ = write!(out, "\n{}", diff(preview, colors)); + } + + out.push('\n'); + out +} + +/// The finding line with up to [`CONTEXT`] lines on each side, and the underline. +fn frame(source: &str, span: Span, style: Style, colors: bool) -> Option { + let lines: Vec<&str> = source.lines().collect(); + let index = span.start.line.checked_sub(1)?; + if index >= lines.len() { + return None; + } + + let from = index.saturating_sub(CONTEXT); + let to = (index + CONTEXT).min(lines.len() - 1); + let width = (to + 1).to_string().len(); + + let mut out = String::new(); + for (number, text) in (from..=to).map(|line| (line + 1, lines[line])) { + let marker = if number == span.start.line { + "> " + } else { + " " + }; + let _ = writeln!(out, "{INDENT}{marker}{number:>width$} \u{2502} {text}"); + if number == span.start.line { + let _ = writeln!( + out, + "{INDENT} {:width$} \u{2502} {}", + "", + underline(text, span, style, colors) + ); + } + } + Some(out) +} + +/// Carets under the span, padded to its start; a multi-line span stops at the line end. +fn underline(text: &str, span: Span, style: Style, colors: bool) -> String { + let start = boundary(text, span.start.column.saturating_sub(1)); + let end = if span.end.line == span.start.line { + boundary(text, span.end.column.saturating_sub(1)).max(start) + } else { + text.len() + }; + + let pad = text[..start].chars().count(); + let carets = text[start..end].chars().count().max(1); + format!( + "{}{}", + " ".repeat(pad), + paint(&"^".repeat(carets), style.bold(), colors) + ) +} + +/// The nearest char boundary at or below `byte`, clamped to the line. +fn boundary(text: &str, byte: usize) -> usize { + let mut at = byte.min(text.len()); + while at > 0 && !text.is_char_boundary(at) { + at -= 1; + } + at +} + +/// The preview's window as a two-column line diff, spaces shown as `Β·` on changed lines. +fn diff(preview: &FixPreview, colors: bool) -> String { + let text = TextDiff::from_lines(&preview.before, &preview.after); + + let mut rows: Vec<(Option, Option, &'static str, String)> = Vec::new(); + let mut old = preview.first_line; + let mut new = preview.first_line; + + for change in text.iter_all_changes() { + let value = change.value().trim_end_matches(['\n', '\r']); + match change.tag() { + ChangeTag::Delete => { + rows.push((Some(old), None, "- ", value.replace(' ', "\u{b7}"))); + old += 1; + } + ChangeTag::Insert => { + rows.push((None, Some(new), "+ ", value.replace(' ', "\u{b7}"))); + new += 1; + } + ChangeTag::Equal => { + rows.push((Some(old), Some(new), " ", value.to_owned())); + old += 1; + new += 1; + } + } + } + + let old_width = column_width(rows.iter().filter_map(|row| row.0)); + let new_width = column_width(rows.iter().filter_map(|row| row.1)); + + let mut out = String::new(); + for (old, new, marker, text) in rows { + let style = match marker { + "- " => level_style(Level::Error), + "+ " => Style::new().fg_color(Some(Color::Ansi(AnsiColor::Green))), + _ => Style::new(), + }; + let body = paint(&format!("{marker}{text}"), style, colors); + let _ = writeln!( + out, + "{INDENT} {:>old_width$} {:>new_width$} \u{2502} {body}", + old.map_or_else(String::new, |line| line.to_string()), + new.map_or_else(String::new, |line| line.to_string()), + ); + } + out +} + +fn column_width(numbers: impl Iterator) -> usize { + numbers + .map(|number| number.to_string().len()) + .max() + .unwrap_or(1) +} + +fn concise_line(diagnostic: &Diagnostic, colors: bool) -> String { + let location = match diagnostic.span { + Some(span) => format!( + "{}:{}:{}", + diagnostic.path.display(), + span.start.line, + span.start.column + ), + None => diagnostic.path.display().to_string(), + }; + let glyph = paint( + &diagnostic.level.glyph().to_string(), + level_style(diagnostic.level).bold(), + colors, + ); + + format!( + "{glyph} {location}: {}: {}\n", + display_name(diagnostic.rule), + diagnostic.message + ) +} + +fn github_line(diagnostic: &Diagnostic) -> String { + let position = match diagnostic.span { + Some(span) => format!( + ",line={},endLine={},col={},endColumn={}", + span.start.line, span.end.line, span.start.column, span.end.column + ), + None => String::new(), + }; + + format!( + "::{} title={},file={}{position}::{}\n", + diagnostic.level.github(), + github_property(&display_name(diagnostic.rule)), + github_property(&diagnostic.path.display().to_string()), + github_message(&diagnostic.message) + ) +} + +/// A workflow command ends at a newline, so the message carries none; `%` opens an +/// escape, so it escapes itself. +fn github_message(text: &str) -> String { + text.replace('%', "%25") + .replace('\r', "%0D") + .replace('\n', "%0A") +} + +/// A property value also ends at the comma or colon that opens the next field. +fn github_property(text: &str) -> String { + github_message(text).replace(',', "%2C").replace(':', "%3A") +} + +#[cfg(test)] +mod tests { + use super::{ + Action, Badge, Diagnostic, FixPreview, Level, Output, Position, Reporter, Span, Summary, + diff, duration, frame, header, level_style, + }; + use crate::report::RuleId; + use std::time::Duration; + + fn at(line: usize, column: usize) -> Position { + Position { line, column } + } + + fn diagnostic() -> Diagnostic { + Diagnostic::new( + "Gaps.compact", + RuleId::MISSING_DOC, + Level::Error, + "Ledger `_owner` has no doc comment.".to_owned(), + ) + .at(Span::columns(at(6, 3), 20)) + } + + #[test] + fn a_frame_underlines_the_span_at_its_column() { + let source = "one\ntwo\nthree four\nfive\nsix\n"; + let rendered = frame( + source, + Span::columns(at(3, 7), 4), + level_style(Level::Error), + false, + ) + .expect("the line is in the source"); + + assert_eq!( + rendered, + concat!( + " 1 \u{2502} one\n", + " 2 \u{2502} two\n", + " > 3 \u{2502} three four\n", + " \u{2502} ^^^^\n", + " 4 \u{2502} five\n", + " 5 \u{2502} six\n", + ) + ); + } + + #[test] + fn a_span_past_the_line_end_underlines_one_column() { + let rendered = frame( + "short\n", + Span::columns(at(1, 40), 3), + level_style(Level::Error), + false, + ) + .expect("the line is in the source"); + + assert!(rendered.ends_with("\u{2502} ^\n"), "{rendered}"); + } + + #[test] + fn a_header_fills_to_one_hundred_columns() { + let rendered = header(&diagnostic(), false); + + assert_eq!(rendered.chars().count(), 101, "{rendered}"); + assert!(rendered.starts_with("Gaps.compact:6:3 lint/missing-doc \u{2501}")); + } + + #[test] + fn a_long_header_keeps_ten_rule_glyphs() { + let long = "a".repeat(140); + let rendered = header( + &Diagnostic::new(long, RuleId::FORMAT, Level::Error, String::new()), + false, + ); + + assert!(rendered.ends_with(&format!("format {}\n", "\u{2501}".repeat(10)))); + } + + #[test] + fn a_badge_sits_between_the_rule_and_the_glyphs() { + let rendered = header( + &diagnostic().fixed_by( + Some(FixPreview { + title: "Unsafe fix: Insert a doc skeleton".to_owned(), + before: String::new(), + after: String::new(), + first_line: 1, + }), + Badge::Fixable, + ), + false, + ); + + assert!( + rendered.contains("lint/missing-doc FIXABLE \u{2501}"), + "{rendered}" + ); + } + + #[test] + fn a_diff_marks_changed_lines_and_shows_their_spaces() { + let preview = FixPreview::between( + "Unsafe fix: Rename @return to @returns".to_owned(), + "/**\n * @return x\n */\n", + "/**\n * @returns x\n */\n", + ) + .expect("the texts differ"); + + assert_eq!(preview.first_line, 2); + assert_eq!( + diff(&preview, false), + concat!( + " 2 \u{2502} - \u{b7}*\u{b7}@return\u{b7}x\n", + " 2 \u{2502} + \u{b7}*\u{b7}@returns\u{b7}x\n", + ) + ); + } + + #[test] + fn an_insertion_numbers_only_the_new_side() { + let preview = FixPreview::between( + "Unsafe fix: Insert @description".to_owned(), + "a\nb\n", + "a\nnew\nb\n", + ) + .expect("the texts differ"); + + assert_eq!(preview.first_line, 2); + assert_eq!(diff(&preview, false), " 2 \u{2502} + new\n"); + } + + #[test] + fn identical_texts_have_no_preview() { + assert!(FixPreview::between(String::new(), "a\n", "a\n").is_none()); + } + + #[test] + fn colors_wrap_the_glyph_and_stay_out_of_the_plain_render() { + let mut painted = Vec::new(); + Output { + colors: true, + ..Output::default() + } + .render(&mut painted, std::slice::from_ref(&diagnostic())) + .expect("the writer accepts the render"); + + let mut plain = Vec::new(); + Output::default() + .render(&mut plain, std::slice::from_ref(&diagnostic())) + .expect("the writer accepts the render"); + + assert!(String::from_utf8_lossy(&painted).contains('\u{1b}')); + assert!(!String::from_utf8_lossy(&plain).contains('\u{1b}')); + } + + #[test] + fn the_cap_counts_what_it_hides() { + let diagnostics = [diagnostic(), diagnostic(), diagnostic()]; + let mut out = Vec::new(); + + let hidden = Output { + max: Some(1), + ..Output::default() + } + .render(&mut out, &diagnostics) + .expect("the writer accepts the render"); + + assert_eq!(hidden, 2); + } + + #[test] + fn the_level_filter_hides_the_quieter_diagnostics() { + let warning = Diagnostic::new( + "a.compact", + RuleId::CONSTRAINTS_PLACEHOLDER, + Level::Warn, + "A warning.".to_owned(), + ); + let mut out = Vec::new(); + + Output { + level: Level::Error, + reporter: Reporter::Concise, + ..Output::default() + } + .render(&mut out, &[warning]) + .expect("the writer accepts the render"); + + assert!(out.is_empty(), "{}", String::from_utf8_lossy(&out)); + } + + #[test] + fn the_concise_and_github_reporters_render_one_line_each() { + let mut concise = Vec::new(); + Output { + reporter: Reporter::Concise, + ..Output::default() + } + .render(&mut concise, std::slice::from_ref(&diagnostic())) + .expect("the writer accepts the render"); + + let mut github = Vec::new(); + Output { + reporter: Reporter::Github, + ..Output::default() + } + .render(&mut github, std::slice::from_ref(&diagnostic())) + .expect("the writer accepts the render"); + + assert_eq!( + String::from_utf8_lossy(&concise), + "\u{d7} Gaps.compact:6:3: lint/missing-doc: Ledger `_owner` has no doc comment.\n" + ); + assert_eq!( + String::from_utf8_lossy(&github), + "::error title=lint/missing-doc,file=Gaps.compact,line=6,endLine=6,col=3,endColumn=23::Ledger `_owner` has no doc comment.\n" + ); + } + + #[test] + fn the_github_reporter_escapes_what_would_end_a_field() { + let awkward = Diagnostic::new( + "src/a,b/Token.compact", + RuleId::CONSTRAINTS_FORMAT, + Level::Error, + "@constraints value `k=10%` is not `k=, rows=`.".to_owned(), + ) + .at(Span::columns(at(3, 6), 12)); + + assert_eq!( + super::github_line(&awkward), + "::error title=lint/constraints-format,file=src/a%2Cb/Token.compact,line=3,endLine=3,col=6,endColumn=18::@constraints value `k=10%25` is not `k=, rows=`.\n" + ); + } + + #[test] + fn a_whole_file_diagnostic_prints_no_line_or_column() { + let whole = Diagnostic::new( + "a.compact", + RuleId::FORMAT, + Level::Error, + "Not formatted.".to_owned(), + ); + + assert!(super::concise_line(&whole, false).starts_with("\u{d7} a.compact: format: ")); + assert_eq!( + super::github_line(&whole), + "::error title=format,file=a.compact::Not formatted.\n" + ); + } + + #[test] + fn the_summary_counts_singulars_and_plurals_apart() { + let summary = Summary { + files: 1, + duration: Duration::from_millis(5), + action: Action::NoFixes, + errors: 1, + warnings: 2, + }; + + assert_eq!( + summary.render(), + "Checked 1 file in 5ms. No fixes applied.\nFound 1 error.\nFound 2 warnings." + ); + } + + #[test] + fn a_clean_summary_names_neither_errors_nor_warnings() { + let summary = Summary { + files: 3, + duration: Duration::from_millis(4), + action: Action::Filled { + values: 1, + files: 1, + }, + errors: 0, + warnings: 0, + }; + + assert_eq!( + summary.render(), + "Checked 3 files in 4ms. Filled 1 value in 1 file." + ); + } + + #[test] + fn durations_read_in_the_unit_that_fits() { + assert_eq!(duration(Duration::from_micros(400)), "400\u{b5}s"); + assert_eq!(duration(Duration::from_millis(5)), "5ms"); + assert_eq!(duration(Duration::from_millis(1234)), "1.2s"); + } +} diff --git a/crates/compact-lint/src/edit.rs b/crates/compact-lint/src/edit.rs index 38a81397..139709d9 100644 --- a/crates/compact-lint/src/edit.rs +++ b/crates/compact-lint/src/edit.rs @@ -9,12 +9,14 @@ use std::path::{Path, PathBuf}; use thiserror::Error; -use crate::report::Position; +use crate::diagnostic::Span; +use crate::report::RuleId; -/// One repair, carrying the line `fix` prints for it. +/// One repair, carrying the rule it answers and the span its diagnostic underlines. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Edit { - pub position: Position, + pub span: Span, + pub rule: RuleId, pub message: String, pub kind: EditKind, } @@ -33,6 +35,20 @@ pub enum EditKind { }, } +impl EditKind { + /// Whether the rewrite needs no follow-up. + /// + /// An edit that writes a value the tool already knows is safe; one that writes a + /// placeholder for a human to replace is not. + #[must_use] + pub const fn is_safe(&self) -> bool { + match self { + Self::Insert { .. } => false, + Self::Doc { op, .. } => op.is_safe(), + } + } +} + /// One change to the lines of a doc comment. #[derive(Clone, Debug, PartialEq, Eq)] pub enum DocOp { @@ -68,6 +84,17 @@ pub enum DocOp { }, } +impl DocOp { + /// Whether the rewrite needs no follow-up; see [`EditKind::is_safe`]. + #[must_use] + pub const fn is_safe(&self) -> bool { + match self { + Self::RenameTag { .. } | Self::SetModuleName { .. } | Self::SetTagValue { .. } => true, + Self::InsertTag { .. } | Self::InsertConstraints(_) => false, + } + } +} + #[derive(Debug, Error)] pub enum WriteError { #[error("cannot read {path}")] @@ -394,11 +421,13 @@ mod tests { DocOp, Edit, EditKind, apply, newline_of, rename_tag, render_doc, set_module_name, set_tag_value, }; - use crate::report::Position; + use crate::diagnostic::Span; + use crate::report::{Position, RuleId}; fn doc_edit(range: std::ops::Range, indent: usize, op: DocOp) -> Edit { Edit { - position: Position::file_start(), + span: Span::columns(Position::file_start(), 1), + rule: RuleId::MISSING_TAG, message: String::new(), kind: EditKind::Doc { range, indent, op }, } @@ -417,6 +446,43 @@ mod tests { render_doc(doc, indent, "\n", &borrowed) } + #[test] + fn only_the_rewrites_that_write_a_known_value_are_safe() { + assert!( + DocOp::RenameTag { + line: 1, + from: "@return".to_owned(), + to: "@returns".to_owned(), + } + .is_safe() + ); + assert!( + DocOp::SetModuleName { + line: 1, + name: "Renamed".to_owned(), + } + .is_safe() + ); + assert!( + DocOp::SetTagValue { + line: 1, + tag: "@constraints".to_owned(), + value: "k=7, rows=74".to_owned(), + } + .is_safe() + ); + + assert!(!tag("@description TODO", &[]).is_safe()); + assert!(!DocOp::InsertConstraints("@constraints k=?, rows=?".to_owned()).is_safe()); + assert!( + !EditKind::Insert { + offset: 0, + text: "/**\n * TODO\n */\n".to_owned(), + } + .is_safe() + ); + } + #[test] fn a_tag_goes_in_at_the_top_of_the_body() { let doc = "/**\n * @constraints k=6, rows=28\n */"; @@ -570,7 +636,8 @@ mod tests { "export ledger a: Uint<8>;\n/**\n * @return x\n */\nexport circuit run(): [] { }\n"; let edits = [ Edit { - position: Position::file_start(), + span: Span::columns(Position::file_start(), 1), + rule: RuleId::MISSING_DOC, message: String::new(), kind: EditKind::Insert { offset: 0, diff --git a/crates/compact-lint/src/fill.rs b/crates/compact-lint/src/fill.rs index 5ee0dd6e..02e54d65 100644 --- a/crates/compact-lint/src/fill.rs +++ b/crates/compact-lint/src/fill.rs @@ -9,20 +9,15 @@ use std::path::{Path, PathBuf}; use thiserror::Error; -use crate::config::ConfigError; +use crate::config::{Config, ConfigError}; +use crate::diagnostic::{Badge, Diagnostic, FixPreview, Level, Span}; use crate::edit::{DocOp, Edit, EditKind, WriteError, apply, newline_of, write_atomically}; use crate::measure::{self, Compiler, Constraints, MeasureError}; -use crate::report::Position; +use crate::report::{Position, RuleId}; use crate::rules::{ConstraintSite, LintError, Linter}; use crate::source::{Resolver, Source}; use crate::target::{self, TargetError}; -/// The rule name for a tagged circuit its source does not measure. -const UNMEASURED: &str = "constraints-unmeasured"; - -/// The rule name for a file with no measurement source at all. -const UNMEASURABLE: &str = "constraints-unmeasurable"; - #[derive(Debug, Error)] pub enum FillError { #[error(transparent)] @@ -55,25 +50,17 @@ pub struct Options { pub artifacts: PathBuf, } -/// The report lines and the counts behind the summary. +/// The diagnostics and the counts behind the summary. pub struct Outcome { - /// One line per change or gap, in file order. - pub lines: Vec, + pub diagnostics: Vec, pub filled: usize, + /// Files that took a value. pub files: usize, + /// Files the run read, changed or not. + pub checked: usize, pub unmeasured: usize, } -impl Outcome { - #[must_use] - pub fn summary(&self) -> String { - format!( - "{} values filled in {} files, {} unmeasured", - self.filled, self.files, self.unmeasured - ) - } -} - /// One file's annotations and the contract they are measured through. struct Work { path: PathBuf, @@ -119,13 +106,14 @@ pub fn run(options: &Options, cwd: &Path) -> Result { )?; let mut outcome = Outcome { - lines: Vec::new(), + diagnostics: Vec::new(), filled: 0, files: 0, + checked: target.files.len(), unmeasured: 0, }; for file in &work { - fill_file(file, &measured, &tag, options, &mut outcome)?; + fill_file(file, &measured, &tag, &target.config, options, &mut outcome)?; } Ok(outcome) } @@ -185,26 +173,46 @@ fn fill_file( file: &Work, measured: &BTreeMap>, tag: &crate::doc::Tag, + config: &Config, options: &Options, outcome: &mut Outcome, ) -> Result<(), FillError> { + let badge = if options.dry_run { + Badge::Fixable + } else { + Badge::Fixed + }; + let newline = newline_of(&file.text); + let source = match &file.source { Source::Found(source) => source, Source::Missing(tried) => { - outcome.lines.push(unmeasurable_line(&file.path, tried)); - outcome.unmeasured += file.sites.len(); + let level = config.rules.get(RuleId::CONSTRAINTS_UNMEASURABLE); + if level != Level::Off { + outcome + .diagnostics + .push(unmeasurable(&file.path, tried, level)); + outcome.unmeasured += file.sites.len(); + } return Ok(()); } }; let constraints = measured.get(source); + let unmeasured_level = config.rules.get(RuleId::CONSTRAINTS_UNMEASURED); let mut edits = Vec::new(); for site in &file.sites { let Some(measurement) = constraints.and_then(|found| found.get(&site.circuit)) else { - outcome - .lines - .push(unmeasured_line(&file.path, site, source)); - outcome.unmeasured += 1; + if unmeasured_level != Level::Off { + outcome.diagnostics.push(unmeasured( + &file.path, + site, + source, + tag, + unmeasured_level, + )); + outcome.unmeasured += 1; + } continue; }; @@ -213,14 +221,10 @@ fn fill_file( continue; } - outcome.lines.push(format!( - "{}: fill: {tag} {} -> {value}", - at(&file.path, site.position), - site.value - )); - edits.push(Edit { - position: site.position, - message: String::new(), + let edit = Edit { + span: Span::columns(site.position, tag.as_str().len()), + rule: RuleId::FILL, + message: format!("set {tag} to {value}"), kind: EditKind::Doc { range: site.doc.range.clone(), indent: site.doc.indent, @@ -230,7 +234,25 @@ fn fill_file( value, }, }, - }); + }; + + let after = apply(&file.text, std::slice::from_ref(&edit), newline); + let title = crate::fix::title(&edit, badge); + outcome.diagnostics.push( + Diagnostic::new( + file.path.clone(), + RuleId::FILL, + Level::Info, + format!( + "Circuit `{}` measures {}.", + site.circuit, + measurement.value() + ), + ) + .at(edit.span) + .fixed_by(FixPreview::between(title, &file.text, &after), badge), + ); + edits.push(edit); } if edits.is_empty() { @@ -240,58 +262,110 @@ fn fill_file( outcome.filled += edits.len(); outcome.files += 1; if !options.dry_run { - let newline = newline_of(&file.text); write_atomically(&file.path, &apply(&file.text, &edits, newline))?; } Ok(()) } -fn unmeasured_line(path: &Path, site: &ConstraintSite, source: &Path) -> String { - format!( - "{}: {UNMEASURED}: circuit `{}` has no measurement in {}", - at(path, site.position), - site.circuit, - source.display() +/// A tagged circuit whose source compiled but produced no measurement for its name. +fn unmeasured( + path: &Path, + site: &ConstraintSite, + source: &Path, + tag: &crate::doc::Tag, + level: Level, +) -> Diagnostic { + Diagnostic::new( + path, + RuleId::CONSTRAINTS_UNMEASURED, + level, + format!("Circuit `{}` has no measurement.", site.circuit), ) + .at(Span::columns(site.position, tag.as_str().len())) + .advise(format!( + "It is measured through {}, which exports no circuit of that name.", + source.display() + )) } -fn unmeasurable_line(path: &Path, tried: &[PathBuf]) -> String { +/// A file no template, glob or override resolves a measurement source for. +fn unmeasurable(path: &Path, tried: &[PathBuf], level: Level) -> Diagnostic { let tried: Vec = tried .iter() .map(|path| path.display().to_string()) .collect(); - format!( - "{}: {UNMEASURABLE}: no measurement source for {}; tried {}", - at(path, Position::file_start()), - path.display(), + + Diagnostic::new( + path, + RuleId::CONSTRAINTS_UNMEASURABLE, + level, + format!("No measurement source for {}.", path.display()), + ) + .at(Span::columns(Position::file_start(), 1)) + .advise(format!( + "Tried {}; add one, or name it in constraints.overrides.", if tried.is_empty() { "nothing".to_owned() } else { tried.join(", ") } - ) -} - -fn at(path: &Path, position: Position) -> String { - format!("{}:{}:{}", path.display(), position.line, position.column) + )) } #[cfg(test)] mod tests { - use super::Outcome; + use super::{Position, unmeasurable, unmeasured}; + use crate::diagnostic::Level; + use crate::doc::Tag; + use crate::rules::{ConstraintSite, DocRef}; + use std::path::{Path, PathBuf}; #[test] - fn the_summary_counts_values_files_and_gaps() { - let outcome = Outcome { - lines: Vec::new(), - filled: 12, - files: 4, - unmeasured: 1, + fn an_unmeasured_circuit_names_the_source_in_its_advice() { + let site = ConstraintSite { + circuit: "initialize".to_owned(), + position: Position { + line: 30, + column: 6, + }, + line_offset: 2, + value: "k=?, rows=?".to_owned(), + doc: DocRef { + range: 0..1, + indent: 2, + }, }; + let diagnostic = unmeasured( + Path::new("src/access/Ownable.compact"), + &site, + Path::new("src/access/test/mocks/MockOwnable.compact"), + &Tag::new("@constraints"), + Level::Warn, + ); + + assert_eq!( + diagnostic.message, + "Circuit `initialize` has no measurement." + ); + assert!( + diagnostic.advice[0].contains("MockOwnable.compact"), + "{:?}", + diagnostic.advice + ); + } + + #[test] + fn an_unmeasurable_file_lists_every_candidate_it_tried() { + let diagnostic = unmeasurable( + Path::new("src/orphan/Orphan.compact"), + &[PathBuf::from("a.compact"), PathBuf::from("b.compact")], + Level::Warn, + ); + assert_eq!( - outcome.summary(), - "12 values filled in 4 files, 1 unmeasured" + diagnostic.advice[0], + "Tried a.compact, b.compact; add one, or name it in constraints.overrides." ); } } diff --git a/crates/compact-lint/src/fix.rs b/crates/compact-lint/src/fix.rs index 20770e87..45327e42 100644 --- a/crates/compact-lint/src/fix.rs +++ b/crates/compact-lint/src/fix.rs @@ -5,10 +5,11 @@ use std::path::{Path, PathBuf}; use thiserror::Error; use crate::config::Config; +use crate::diagnostic::{Badge, Diagnostic, FixPreview, Level, capitalise}; use crate::doc::Tag; use crate::edit::{DocOp, Edit, EditKind, WriteError, apply, newline_of, write_atomically}; use crate::model::DeclKind; -use crate::report::Position; +use crate::report::RuleId; use crate::rules::{Issue, LintError, Linter}; use crate::target::{self, TargetError}; @@ -44,26 +45,19 @@ pub struct Options { pub dry_run: bool, } -/// The edits one file took. -pub struct FileEdits { - pub path: PathBuf, - pub edits: Vec, -} - -/// Every file the run changed, in the order they were visited. +/// What the run changed, and the diagnostic for every edit. pub struct Outcome { - pub files: Vec, + pub diagnostics: Vec, + /// Files the run visited, changed or not. + pub checked: usize, + /// Files that took at least one edit. + pub changed: usize, } impl Outcome { #[must_use] pub fn edits(&self) -> usize { - self.files.iter().map(|file| file.edits.len()).sum() - } - - #[must_use] - pub fn summary(&self) -> String { - format!("{} edits in {} files", self.edits(), self.files.len()) + self.diagnostics.len() } } @@ -73,8 +67,15 @@ impl Outcome { pub fn run(options: &Options, cwd: &Path) -> Result { let target = target::resolve(&options.paths, options.config_path.as_deref(), cwd)?; + let badge = if options.dry_run { + Badge::Fixable + } else { + Badge::Fixed + }; + let mut linter = Linter::new()?; - let mut files = Vec::new(); + let mut diagnostics = Vec::new(); + let mut changed = 0; for path in &target.files { let source = std::fs::read_to_string(path).map_err(|source| FixError::Read { @@ -83,26 +84,65 @@ pub fn run(options: &Options, cwd: &Path) -> Result { })?; let newline = newline_of(&source); - let edits: Vec = linter - .issues(path, &source, &target.config, false)? + let issues = linter.issues(path, &source, &target.config)?; + let repairs: Vec<(&Issue, Edit)> = issues .iter() - .filter_map(|issue| edit_for(issue, &target.config, newline)) + .filter_map(|issue| edit_for(issue, &target.config, newline).map(|edit| (issue, edit))) .collect(); - if edits.is_empty() { + if repairs.is_empty() { continue; } + for (issue, edit) in &repairs { + diagnostics.push(diagnostic(path, issue, edit, &source, newline, badge)); + } + + let edits: Vec = repairs.into_iter().map(|(_, edit)| edit).collect(); if !options.dry_run { write_atomically(path, &apply(&source, &edits, newline))?; } - files.push(FileEdits { - path: path.clone(), - edits, - }); + changed += 1; } - Ok(Outcome { files }) + Ok(Outcome { + diagnostics, + checked: target.files.len(), + changed, + }) +} + +/// The `i` line above a fix diff: what it does, and whether it is already done. +/// +/// An offered fix that writes a placeholder is `Unsafe`, the way Biome marks a fix the +/// reader still has to finish. +#[must_use] +pub fn title(edit: &Edit, badge: Badge) -> String { + let what = capitalise(&edit.message); + match badge { + Badge::Fixed => format!("Applied fix: {what}"), + Badge::Fixable if edit.kind.is_safe() => format!("Safe fix: {what}"), + Badge::Fixable => format!("Unsafe fix: {what}"), + } +} + +/// One repair as a diagnostic: the issue states the problem, the title states the fix. +fn diagnostic( + path: &Path, + issue: &Issue, + edit: &Edit, + source: &str, + newline: &str, + badge: Badge, +) -> Diagnostic { + let after = apply(source, std::slice::from_ref(edit), newline); + + Diagnostic::new(path, edit.rule, Level::Info, issue.message()) + .at(edit.span) + .fixed_by( + FixPreview::between(title(edit, badge), source, &after), + badge, + ) } /// The repair for one issue, or `None` where the rule has no safe fix. @@ -111,18 +151,20 @@ pub fn run(options: &Options, cwd: &Path) -> Result { /// cannot invent, and `parse` and `format` are not doc-comment issues at all. #[must_use] pub fn edit_for(issue: &Issue, config: &Config, newline: &str) -> Option { + let span = issue.span(); match issue { Issue::MissingDoc { - position, subject, kind, name, offset, indent, constraints, + .. } => Some(Edit { - position: *position, - message: format!("inserted doc skeleton for {subject}"), + span, + rule: RuleId::MISSING_DOC, + message: format!("insert a doc skeleton for {subject}"), kind: EditKind::Insert { offset: *offset, text: skeleton( @@ -137,15 +179,15 @@ pub fn edit_for(issue: &Issue, config: &Config, newline: &str) -> Option { }), Issue::MissingTag { - position, kind, tag, name, doc, .. } => Some(Edit { - position: *position, - message: format!("inserted {tag}"), + span, + rule: RuleId::MISSING_TAG, + message: format!("insert {tag}"), kind: EditKind::Doc { range: doc.range.clone(), indent: doc.indent, @@ -153,11 +195,10 @@ pub fn edit_for(issue: &Issue, config: &Config, newline: &str) -> Option { }, }), - Issue::MissingConstraints { - position, tag, doc, .. - } => Some(Edit { - position: *position, - message: format!("inserted {tag} {UNMEASURED}"), + Issue::MissingConstraints { tag, doc, .. } => Some(Edit { + span, + rule: RuleId::MISSING_CONSTRAINTS, + message: format!("insert {tag} {UNMEASURED}"), kind: EditKind::Doc { range: doc.range.clone(), indent: doc.indent, @@ -166,15 +207,16 @@ pub fn edit_for(issue: &Issue, config: &Config, newline: &str) -> Option { }), Issue::ForbiddenTag { - position, tag, line_offset, doc, + .. } => { let replacement = config.rename_of(tag)?; Some(Edit { - position: *position, - message: format!("renamed {tag} to {replacement}"), + span, + rule: RuleId::FORBIDDEN_TAG, + message: format!("rename {tag} to {replacement}"), kind: EditKind::Doc { range: doc.range.clone(), indent: doc.indent, @@ -188,13 +230,13 @@ pub fn edit_for(issue: &Issue, config: &Config, newline: &str) -> Option { } Issue::ModuleName { - position, name, line_offset, doc, .. } => Some(Edit { - position: *position, + span, + rule: RuleId::MODULE_NAME, message: format!("set {MODULE_TAG} to `{name}`"), kind: EditKind::Doc { range: doc.range.clone(), @@ -282,17 +324,6 @@ fn skeleton( format!("{}{newline}{margin}", lines.join(newline)) } -/// The line `fix` prints for one edit. -#[must_use] -pub fn line(path: &Path, position: Position, message: &str) -> String { - format!( - "{}:{}:{}: fix: {message}", - path.display(), - position.line, - position.column - ) -} - #[cfg(test)] mod tests { use super::skeleton; diff --git a/crates/compact-lint/src/format.rs b/crates/compact-lint/src/format.rs index d3a0c46a..c8678830 100644 --- a/crates/compact-lint/src/format.rs +++ b/crates/compact-lint/src/format.rs @@ -6,7 +6,8 @@ use std::process::Command; use thiserror::Error; -use crate::report::{Finding, Position, RuleId}; +use crate::diagnostic::{Diagnostic, Level, sentence}; +use crate::report::RuleId; /// Environment override for the `compact` binary; the `--compact-bin` flag wins over it. pub const COMPACT_BIN_ENV: &str = "COMPACT_LINT_COMPACT_BIN"; @@ -14,7 +15,11 @@ pub const COMPACT_BIN_ENV: &str = "COMPACT_LINT_COMPACT_BIN"; /// The default binary name, resolved through `PATH`. pub const DEFAULT_COMPACT_BIN: &str = "compact"; -pub const MESSAGE: &str = "not formatted; run `compact format`"; +/// The message every reported file carries; the repair is the diagnostic's advice. +pub const MESSAGE: &str = "Not formatted."; + +/// The advice every `format` diagnostic carries. +pub const ADVICE: &str = "Run compact format to fix it."; #[derive(Debug, Error)] pub enum FormatError { @@ -28,14 +33,18 @@ pub enum FormatError { }, } -/// Runs `compact format --check` once over every file and maps its report to findings. +/// Runs `compact format --check` once over every file and maps its report to diagnostics. /// /// The formatter writes one `:` line per unformatted file to stderr, followed by -/// an indented diff. An output that holds no such line yields one finding on the first +/// an indented diff. An output that holds no such line yields one diagnostic on the first /// checked file carrying the formatter's own first line. /// # Errors /// Returns an error when the `compact` binary is missing or cannot be spawned. -pub fn check(binary: &OsStr, files: &[PathBuf]) -> Result, FormatError> { +pub fn check( + binary: &OsStr, + files: &[PathBuf], + level: Level, +) -> Result, FormatError> { if files.is_empty() { return Ok(Vec::new()); } @@ -68,23 +77,21 @@ pub fn check(binary: &OsStr, files: &[PathBuf]) -> Result, FormatEr let raw = first_line(&stderr) .or_else(|| first_line(&stdout)) .unwrap_or("compact format --check failed"); - return Ok(vec![Finding::new( - files[0].clone(), - Position::file_start(), - RuleId::FORMAT, - raw.to_owned(), - )]); + return Ok(vec![ + Diagnostic::new(files[0].clone(), RuleId::FORMAT, level, sentence(raw)).advise(ADVICE), + ]); } Ok(reported .into_iter() .map(|path| { - Finding::new( + Diagnostic::new( resolve(path, files), - Position::file_start(), RuleId::FORMAT, + level, MESSAGE.to_owned(), ) + .advise(ADVICE) }) .collect()) } diff --git a/crates/compact-lint/src/lib.rs b/crates/compact-lint/src/lib.rs index 99ade4b5..1dd7e4b0 100644 --- a/crates/compact-lint/src/lib.rs +++ b/crates/compact-lint/src/lib.rs @@ -3,7 +3,7 @@ //! The crate parses `.compact` files with the bundled tree-sitter grammar, matches each //! declaration against the per-kind doc-comment template in `compact-lint.toml`, and //! yields one [`rules::Issue`] per violation. `check` renders an issue as a -//! [`report::Finding`]; `fix` renders the repairable ones as an [`edit::Edit`]. +//! [`diagnostic::Diagnostic`]; `fix` renders the repairable ones as an [`edit::Edit`]. //! `fill-constraints` takes the other path: [`measure`] compiles a contract and //! [`fill`] writes the measured values into the annotations that already exist. @@ -11,6 +11,7 @@ pub mod check; pub mod config; +pub mod diagnostic; pub mod discover; pub mod doc; pub mod edit; diff --git a/crates/compact-lint/src/main.rs b/crates/compact-lint/src/main.rs index b264b392..0d8ddba3 100644 --- a/crates/compact-lint/src/main.rs +++ b/crates/compact-lint/src/main.rs @@ -3,24 +3,30 @@ #![forbid(unsafe_code)] use std::ffi::OsString; -use std::io::Write; +use std::io::{IsTerminal, Write}; use std::path::PathBuf; use std::process::ExitCode; +use std::str::FromStr; +use std::time::{Duration, Instant}; use anyhow::{Context, Result}; use clap::{Parser, Subcommand}; use tempfile::TempDir; -use compact_lint::check::{self, Outcome}; +use compact_lint::check; +use compact_lint::diagnostic::{Action, Diagnostic, Level, Output, Reporter, Summary, counts}; use compact_lint::format::{COMPACT_BIN_ENV, DEFAULT_COMPACT_BIN}; -use compact_lint::{fill, fix}; +use compact_lint::{diagnostic, fill, fix}; -/// Exit code for a run that produced findings, or a `--dry-run` that would edit. +/// Exit code for a run that produced errors, or a `--dry-run` that would edit. const EXIT_FINDINGS: u8 = 1; /// Exit code for a usage, config, IO or parser error. const EXIT_ERROR: u8 = 2; +/// Shown diagnostics per run, before `--max-diagnostics` changes it. +const DEFAULT_MAX_DIAGNOSTICS: &str = "20"; + #[derive(Debug, Parser)] #[command( name = "compact-lint", @@ -42,6 +48,80 @@ enum Command { FillConstraints(FillArgs), } +/// The flags every subcommand shares for what it prints and how loudly. +#[derive(Debug, clap::Args)] +struct OutputArgs { + /// Output format. + #[arg(long, value_enum, default_value_t = Reporter::Default, value_name = "NAME")] + reporter: Reporter, + + /// Lowest level shown; the summary still counts what it hides. + #[arg(long, value_enum, default_value_t = LevelArg::Info, value_name = "LEVEL")] + diagnostic_level: LevelArg, + + /// Exit 1 when the run produced warnings but no errors. + #[arg(long)] + error_on_warnings: bool, + + /// Diagnostics shown before the rest are counted instead; `none` lifts the cap. + #[arg(long, default_value = DEFAULT_MAX_DIAGNOSTICS, value_name = "NONE|N")] + max_diagnostics: MaxDiagnostics, + + /// Colour the output; the default colours a TTY with `NO_COLOR` unset. + #[arg(long, value_enum, value_name = "WHEN")] + colors: Option, +} + +/// The levels a reader can ask for; `off` is a rule setting, not a filter. +#[derive(Clone, Copy, Debug, clap::ValueEnum)] +enum LevelArg { + Info, + Warn, + Error, +} + +#[derive(Clone, Copy, Debug, clap::ValueEnum)] +enum ColorsArg { + Off, + Force, +} + +/// `--max-diagnostics`, either a cap or `none`. +#[derive(Clone, Copy, Debug)] +struct MaxDiagnostics(Option); + +impl FromStr for MaxDiagnostics { + type Err = String; + + fn from_str(text: &str) -> Result { + if text == "none" { + return Ok(Self(None)); + } + text.parse() + .map(|cap| Self(Some(cap))) + .map_err(|_| format!("expected a whole number or `none`, got {text:?}")) + } +} + +impl OutputArgs { + fn output(&self) -> Output { + Output { + reporter: self.reporter, + level: match self.diagnostic_level { + LevelArg::Info => Level::Info, + LevelArg::Warn => Level::Warn, + LevelArg::Error => Level::Error, + }, + max: self.max_diagnostics.0, + colors: match self.colors { + Some(ColorsArg::Off) => false, + Some(ColorsArg::Force) => true, + None => std::io::stdout().is_terminal() && std::env::var_os("NO_COLOR").is_none(), + }, + } + } +} + #[derive(Debug, clap::Args)] struct CheckArgs { /// Files or directories to check; defaults to the config's include globs. @@ -51,7 +131,7 @@ struct CheckArgs { #[arg(long, value_name = "FILE")] config: Option, - /// Report `k=?` / `rows=?` placeholders in the constraints tag. + /// Report `k=?` / `rows=?` placeholders as errors instead of warnings. #[arg(long)] strict: bool, @@ -62,6 +142,9 @@ struct CheckArgs { /// Path to the `compact` binary. #[arg(long, value_name = "PATH", env = COMPACT_BIN_ENV)] compact_bin: Option, + + #[command(flatten)] + output: OutputArgs, } #[derive(Debug, clap::Args)] @@ -76,6 +159,9 @@ struct FixArgs { /// Report the edits without writing them; exits 1 when there are any. #[arg(long)] dry_run: bool, + + #[command(flatten)] + output: OutputArgs, } #[derive(Debug, clap::Args)] @@ -102,6 +188,9 @@ struct FillArgs { /// Directory the compiler writes to; kept after the run when given. #[arg(long, value_name = "DIR")] artifacts: Option, + + #[command(flatten)] + output: OutputArgs, } fn main() -> ExitCode { @@ -136,14 +225,20 @@ fn run_check(args: CheckArgs, cwd: &std::path::Path) -> Result { .unwrap_or_else(|| OsString::from(DEFAULT_COMPACT_BIN)), }; + let started = Instant::now(); let outcome = check::run(&options, cwd).context("running the check")?; - emit_findings(&outcome).context("writing the report")?; - - Ok(if outcome.findings.is_empty() { - ExitCode::SUCCESS - } else { - ExitCode::from(EXIT_FINDINGS) - }) + let (errors, warnings) = emit( + &args.output, + &outcome.diagnostics, + RunFacts { + files: outcome.files_checked, + duration: started.elapsed(), + action: Action::NoFixes, + }, + ) + .context("writing the report")?; + + Ok(exit_code(errors, warnings, args.output.error_on_warnings)) } fn run_fix(args: FixArgs, cwd: &std::path::Path) -> Result { @@ -153,14 +248,28 @@ fn run_fix(args: FixArgs, cwd: &std::path::Path) -> Result { dry_run: args.dry_run, }; + let started = Instant::now(); let outcome = fix::run(&options, cwd).context("running the fix")?; - emit_edits(&outcome).context("writing the report")?; - - Ok(if options.dry_run && outcome.edits() > 0 { - ExitCode::from(EXIT_FINDINGS) + let action = if options.dry_run { + Action::NoFixes } else { - ExitCode::SUCCESS - }) + Action::Fixed(outcome.changed) + }; + let (errors, warnings) = emit( + &args.output, + &outcome.diagnostics, + RunFacts { + files: outcome.checked, + duration: started.elapsed(), + action, + }, + ) + .context("writing the report")?; + + if options.dry_run && outcome.edits() > 0 { + return Ok(ExitCode::from(EXIT_FINDINGS)); + } + Ok(exit_code(errors, warnings, args.output.error_on_warnings)) } fn run_fill(args: FillArgs, cwd: &std::path::Path) -> Result { @@ -177,15 +286,27 @@ fn run_fill(args: FillArgs, cwd: &std::path::Path) -> Result { artifacts, }; + let started = Instant::now(); let outcome = fill::run(&options, cwd).context("filling the constraints")?; - emit_lines(&outcome.lines, &outcome.summary()).context("writing the report")?; + let (errors, warnings) = emit( + &args.output, + &outcome.diagnostics, + RunFacts { + files: outcome.checked, + duration: started.elapsed(), + action: Action::Filled { + values: outcome.filled, + files: outcome.files, + }, + }, + ) + .context("writing the report")?; drop(temporary); - Ok(if outcome.unmeasured == 0 { - ExitCode::SUCCESS - } else { - ExitCode::from(EXIT_FINDINGS) - }) + if outcome.unmeasured > 0 { + return Ok(ExitCode::from(EXIT_FINDINGS)); + } + Ok(exit_code(errors, warnings, args.output.error_on_warnings)) } /// The artifacts directory, plus the temporary one to remove once the run ends. @@ -198,46 +319,53 @@ fn artifacts_dir(given: Option) -> Result<(PathBuf, Option)> { Ok((directory.path().to_owned(), Some(directory))) } -fn emit_lines(lines: &[String], summary: &str) -> std::io::Result<()> { - let stdout = std::io::stdout(); - let mut out = stdout.lock(); - for line in lines { - writeln!(out, "{line}")?; - } - out.flush()?; - - eprintln!("{summary}"); - Ok(()) +/// What a run did, everything the summary needs that the diagnostics do not carry. +#[derive(Clone, Copy, Debug)] +struct RunFacts { + files: usize, + duration: Duration, + action: Action, } -fn emit_findings(outcome: &Outcome) -> std::io::Result<()> { +/// Writes the diagnostics to stdout and the truncation notice and summary to stderr. +fn emit( + args: &OutputArgs, + diagnostics: &[Diagnostic], + facts: RunFacts, +) -> std::io::Result<(usize, usize)> { + let (errors, warnings) = counts(diagnostics); + let stdout = std::io::stdout(); let mut out = stdout.lock(); - for finding in &outcome.findings { - writeln!(out, "{finding}")?; + let hidden = args.output().render(&mut out, diagnostics)?; + + let stderr = std::io::stderr(); + let mut error_out = stderr.lock(); + if hidden > 0 { + writeln!(error_out, "{}", diagnostic::truncation(hidden))?; } - out.flush()?; + writeln!( + error_out, + "{}", + Summary { + files: facts.files, + duration: facts.duration, + action: facts.action, + errors, + warnings, + } + .render() + )?; - eprintln!("{}", outcome.summary()); - Ok(()) + Ok((errors, warnings)) } -fn emit_edits(outcome: &fix::Outcome) -> std::io::Result<()> { - let stdout = std::io::stdout(); - let mut out = stdout.lock(); - for file in &outcome.files { - for edit in &file.edits { - writeln!( - out, - "{}", - fix::line(&file.path, edit.position, &edit.message) - )?; - } +fn exit_code(errors: usize, warnings: usize, error_on_warnings: bool) -> ExitCode { + if errors > 0 || (error_on_warnings && warnings > 0) { + ExitCode::from(EXIT_FINDINGS) + } else { + ExitCode::SUCCESS } - out.flush()?; - - eprintln!("{}", outcome.summary()); - Ok(()) } /// Prints the error and every source under it, one cause per line. diff --git a/crates/compact-lint/src/model.rs b/crates/compact-lint/src/model.rs index 5634f9cd..d90131eb 100644 --- a/crates/compact-lint/src/model.rs +++ b/crates/compact-lint/src/model.rs @@ -76,6 +76,8 @@ pub struct Declaration { pub exported: bool, pub pure: bool, pub position: Position, + /// End of the name token, or of the first token where the kind has no name. + pub end: Position, /// Byte offset of the declaration's first token, where `fix` inserts a skeleton. pub offset: usize, /// The doc comment immediately preceding the declaration, if one attaches. @@ -150,6 +152,10 @@ fn declaration(kind: DeclKind, node: Node<'_>, source: &str) -> Declaration { .map(str::to_owned); let start = node.start_position(); + let end = node + .child_by_field_name("name") + .or_else(|| node.child(0)) + .map_or_else(|| node.end_position(), |token| token.end_position()); Declaration { kind, @@ -157,6 +163,7 @@ fn declaration(kind: DeclKind, node: Node<'_>, source: &str) -> Declaration { exported, pure, position: Position::from_zero_based(start.row, start.column), + end: Position::from_zero_based(end.row, end.column), offset: node.start_byte(), doc: attached_doc(node, source), } diff --git a/crates/compact-lint/src/report.rs b/crates/compact-lint/src/report.rs index b2d9f172..e27b5f42 100644 --- a/crates/compact-lint/src/report.rs +++ b/crates/compact-lint/src/report.rs @@ -1,7 +1,6 @@ -//! Findings and the one-line `path:line:col: rule: message` rendering. +//! Rule identifiers and source positions. use std::fmt; -use std::path::{Path, PathBuf}; /// A lint rule's stable identifier, as printed in the output and matched by CI greps. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] @@ -15,11 +14,16 @@ impl RuleId { pub const MISSING_CONSTRAINTS: Self = Self("missing-constraints"); pub const CONSTRAINTS_FORMAT: Self = Self("constraints-format"); pub const CONSTRAINTS_PLACEHOLDER: Self = Self("constraints-placeholder"); + pub const CONSTRAINTS_UNMEASURED: Self = Self("constraints-unmeasured"); + pub const CONSTRAINTS_UNMEASURABLE: Self = Self("constraints-unmeasurable"); pub const PARSE: Self = Self("parse"); pub const FORMAT: Self = Self("format"); - /// Every rule this build can emit, in the order the README lists them. - pub const ALL: [Self; 9] = [ + /// A value `fill-constraints` wrote. It reports what changed, so it takes no level. + pub const FILL: Self = Self("fill"); + + /// Every rule a `[rules]` table can set a level for, in the order the README lists them. + pub const ALL: [Self; 11] = [ Self::MISSING_DOC, Self::MISSING_TAG, Self::FORBIDDEN_TAG, @@ -27,6 +31,8 @@ impl RuleId { Self::MISSING_CONSTRAINTS, Self::CONSTRAINTS_FORMAT, Self::CONSTRAINTS_PLACEHOLDER, + Self::CONSTRAINTS_UNMEASURED, + Self::CONSTRAINTS_UNMEASURABLE, Self::PARSE, Self::FORMAT, ]; @@ -67,69 +73,9 @@ impl Position { } } -/// One lint violation at one source position. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Finding { - pub path: PathBuf, - pub position: Position, - pub rule: RuleId, - pub message: String, -} - -impl Finding { - pub fn new( - path: impl Into, - position: Position, - rule: RuleId, - message: String, - ) -> Self { - Self { - path: path.into(), - position, - rule, - message, - } - } - - /// Sorts findings by file, then position, then rule, so output is stable across runs. - #[must_use] - pub fn sort_key(&self) -> (&Path, Position, RuleId) { - (self.path.as_path(), self.position, self.rule) - } -} - -impl fmt::Display for Finding { - fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - formatter, - "{}:{}:{}: {}: {}", - self.path.display(), - self.position.line, - self.position.column, - self.rule, - self.message - ) - } -} - #[cfg(test)] mod tests { - use super::{Finding, Position, RuleId}; - - #[test] - fn finding_renders_as_path_line_col_rule_message() { - let finding = Finding::new( - "contracts/src/access/Ownable.compact", - Position::from_zero_based(41, 0), - RuleId::MISSING_DOC, - "circuit `assertOnlyOwner` has no doc comment".to_owned(), - ); - - assert_eq!( - finding.to_string(), - "contracts/src/access/Ownable.compact:42:1: missing-doc: circuit `assertOnlyOwner` has no doc comment" - ); - } + use super::RuleId; #[test] fn rule_ids_are_unique() { diff --git a/crates/compact-lint/src/rules.rs b/crates/compact-lint/src/rules.rs index 889b302b..4c5a30cc 100644 --- a/crates/compact-lint/src/rules.rs +++ b/crates/compact-lint/src/rules.rs @@ -1,6 +1,6 @@ //! The doc-comment rules, run over one parsed file at a time. //! -//! Detection yields [`Issue`]s. `check` renders them as [`Finding`]s and `fix` renders +//! Detection yields [`Issue`]s. `check` renders them as [`Diagnostic`]s and `fix` renders //! the fixable ones as edits, so both subcommands read the same detection pass. use std::ops::Range; @@ -10,9 +10,13 @@ use thiserror::Error; use tree_sitter::{Node, Parser}; use crate::config::{Config, DocsPolicy}; +use crate::diagnostic::{Diagnostic, Level, Span, sentence}; use crate::doc::Tag; use crate::model::{DeclKind, Declaration, declarations}; -use crate::report::{Finding, Position, RuleId}; +use crate::report::{Position, RuleId}; + +/// The tag whose value must name the module it documents. +const MODULE_TAG: &str = "@module"; #[derive(Debug, Error)] pub enum LintError { @@ -53,11 +57,13 @@ pub struct ConstraintSite { pub enum Issue { Parse { position: Position, + end: Position, node_kind: String, missing: bool, }, MissingDoc { position: Position, + end: Position, subject: String, kind: DeclKind, name: Option, @@ -70,6 +76,7 @@ pub enum Issue { }, MissingTag { position: Position, + end: Position, subject: String, kind: DeclKind, tag: Tag, @@ -94,6 +101,7 @@ pub enum Issue { }, MissingConstraints { position: Position, + end: Position, subject: String, tag: Tag, doc: DocRef, @@ -139,9 +147,10 @@ impl Issue { } } + /// The sentence a reporter prints, capitalised and closed like Biome's. #[must_use] pub fn message(&self) -> String { - match self { + let body = match self { Self::Parse { node_kind, missing, .. } => { @@ -159,19 +168,70 @@ impl Issue { Self::ForbiddenTag { tag, .. } => format!("forbidden tag {tag}"), Self::ModuleName { documented, name, .. - } => format!("@module names `{documented}`, but the module is `{name}`"), + } => format!("{MODULE_TAG} names `{documented}`, but the module is `{name}`"), Self::ConstraintsFormat { tag, value, .. } => { format!("{tag} value `{value}` is not `k=, rows=`") } Self::ConstraintsPlaceholder { tag, value, .. } => { format!("{tag} value `{value}` still holds a placeholder") } + }; + sentence(&body) + } + + /// The one-sentence `i` line telling the reader what to do about it. + #[must_use] + pub fn advice(&self, config: &Config) -> String { + match self { + Self::Parse { .. } => { + "Fix the syntax error; the doc rules are skipped for this file.".to_owned() + } + Self::MissingDoc { .. } => { + "Add a doc comment above it, or run compact-lint fix.".to_owned() + } + Self::MissingTag { tag, .. } => { + format!("Add {tag} to the doc comment, or run compact-lint fix.") + } + Self::ForbiddenTag { tag, .. } => match config.rename_of(tag) { + Some(replacement) => format!("Rename it to {replacement}."), + None => "Remove it from the doc comment.".to_owned(), + }, + Self::ModuleName { name, .. } => { + format!("Set the tag to {name}, or run compact-lint fix.") + } + Self::MissingConstraints { tag, .. } => format!( + "Run compact-lint fill-constraints after adding the tag, or add it as {tag} k=?, rows=? to fill later." + ), + Self::ConstraintsFormat { .. } => "Write the value as k=, rows=.".to_owned(), + Self::ConstraintsPlaceholder { .. } => { + "Run compact-lint fill-constraints to measure it.".to_owned() + } + } + } + + /// What a reporter underlines: the declaration head, or the tag token itself. + #[must_use] + pub fn span(&self) -> Span { + match self { + Self::Parse { position, end, .. } + | Self::MissingDoc { position, end, .. } + | Self::MissingTag { position, end, .. } + | Self::MissingConstraints { position, end, .. } => Span::new(*position, *end), + Self::ForbiddenTag { position, tag, .. } + | Self::ConstraintsFormat { position, tag, .. } + | Self::ConstraintsPlaceholder { position, tag, .. } => { + Span::columns(*position, tag.as_str().len()) + } + Self::ModuleName { position, .. } => Span::columns(*position, MODULE_TAG.len()), } } + /// The diagnostic for this issue, without the fix preview the caller attaches. #[must_use] - pub fn finding(&self, display: &Path) -> Finding { - Finding::new(display, self.position(), self.rule(), self.message()) + pub fn diagnostic(&self, display: &Path, level: Level, config: &Config) -> Diagnostic { + Diagnostic::new(display, self.rule(), level, self.message()) + .at(self.span()) + .advise(self.advice(config)) } } @@ -202,7 +262,6 @@ impl Linter { display: &Path, source: &str, config: &Config, - strict: bool, ) -> Result, LintError> { let tree = self .parser @@ -211,13 +270,18 @@ impl Linter { let root = tree.root_node(); if let Some(defect) = first_defect(root) { - return Ok(vec![defect]); + return Ok(if config.rules.get(RuleId::PARSE) == Level::Off { + Vec::new() + } else { + vec![defect] + }); } let mut issues = Vec::new(); for declaration in declarations(root, source) { - check_declaration(&declaration, config, strict, &mut issues); + check_declaration(&declaration, config, &mut issues); } + issues.retain(|issue| config.rules.get(issue.rule()) != Level::Off); issues.sort_by_key(|issue| (issue.position(), issue.rule())); Ok(issues) } @@ -249,31 +313,16 @@ impl Linter { .filter_map(|declaration| constraint_site(declaration, &config.constraints.tag)) .collect()) } - - /// Checks one file. `display` is the path printed in findings. - /// # Errors - /// Returns an error when tree-sitter produces no tree for `source`. - pub fn check( - &mut self, - display: &Path, - source: &str, - config: &Config, - strict: bool, - ) -> Result, LintError> { - Ok(self - .issues(display, source, config, strict)? - .iter() - .map(|issue| issue.finding(display)) - .collect()) - } } /// The first `ERROR` or `MISSING` node in document order. fn first_defect(node: Node<'_>) -> Option { if node.is_error() || node.is_missing() { let start = node.start_position(); + let end = node.end_position(); return Some(Issue::Parse { position: Position::from_zero_based(start.row, start.column), + end: Position::from_zero_based(end.row, end.column), node_kind: node.kind().to_owned(), missing: node.is_missing(), }); @@ -287,12 +336,7 @@ fn first_defect(node: Node<'_>) -> Option { node.children(&mut cursor).find_map(first_defect) } -fn check_declaration( - declaration: &Declaration, - config: &Config, - strict: bool, - issues: &mut Vec, -) { +fn check_declaration(declaration: &Declaration, config: &Config, issues: &mut Vec) { let kind_config = config.kinds.get(declaration.kind); let requires_docs = match kind_config.docs { DocsPolicy::All => true, @@ -304,6 +348,7 @@ fn check_declaration( if requires_docs { issues.push(Issue::MissingDoc { position: declaration.position, + end: declaration.end, subject: subject(declaration), kind: declaration.kind, name: declaration.name.clone(), @@ -346,6 +391,7 @@ fn check_declaration( if !attached.comment.has(required) { issues.push(Issue::MissingTag { position: declaration.position, + end: declaration.end, subject: subject(declaration), kind: declaration.kind, tag: required.clone(), @@ -355,12 +401,12 @@ fn check_declaration( } } - check_constraints(declaration, &doc, config, strict, issues); + check_constraints(declaration, &doc, config, issues); } /// `@module ` must name the module it documents. fn check_module_name(declaration: &Declaration, doc: &DocRef, issues: &mut Vec) { - let tag = Tag::new("@module"); + let tag = Tag::new(MODULE_TAG); let (Some(attached), Some(name)) = (declaration.doc.as_ref(), declaration.name.as_deref()) else { return; @@ -417,7 +463,6 @@ fn check_constraints( declaration: &Declaration, doc: &DocRef, config: &Config, - strict: bool, issues: &mut Vec, ) { if !takes_constraints(declaration) { @@ -431,6 +476,7 @@ fn check_constraints( let Some(occurrence) = attached.comment.first(tag) else { issues.push(Issue::MissingConstraints { position: declaration.position, + end: declaration.end, subject: subject(declaration), tag: tag.clone(), doc: doc.clone(), @@ -450,7 +496,7 @@ fn check_constraints( return; }; - if strict && placeholders { + if placeholders { issues.push(Issue::ConstraintsPlaceholder { position, tag: tag.clone(), @@ -498,16 +544,29 @@ fn subject(declaration: &Declaration) -> String { mod tests { use super::{Linter, module_name, parse_constraints}; use crate::config::{Config, DocsPolicy}; + use crate::diagnostic::Level; + use crate::diagnostic::sentence; use crate::doc::Tag; + use crate::report::RuleId; use std::path::Path; - fn findings(source: &str, config: &Config, strict: bool) -> Vec { + /// One `line:col rule message` line per issue, the fields every reporter starts from. + fn reported(source: &str, config: &Config) -> Vec { Linter::new() .expect("the bundled grammar loads") - .check(Path::new("a.compact"), source, config, strict) + .issues(Path::new("a.compact"), source, config) .expect("the source produced a tree") .iter() - .map(ToString::to_string) + .map(|issue| { + let span = issue.span(); + format!( + "{}:{} {} {}", + span.start.line, + span.start.column, + issue.rule(), + issue.message() + ) + }) .collect() } @@ -521,7 +580,7 @@ mod tests { fn a_non_exported_circuit_inside_an_exported_module_needs_no_docs() { let source = "/** @description M. */\nexport module M {\n circuit helper(): [] { }\n}\n"; - assert!(findings(source, &Config::default(), false).is_empty()); + assert!(reported(source, &Config::default()).is_empty()); } #[test] @@ -529,8 +588,8 @@ mod tests { let source = "export module M {\n}\n"; assert_eq!( - findings(source, &Config::default(), false), - ["a.compact:1:1: missing-doc: module `M` has no doc comment"] + reported(source, &Config::default()), + ["1:1 missing-doc Module `M` has no doc comment."] ); } @@ -539,8 +598,8 @@ mod tests { let source = "/** @description M. */\n// a note\nexport module M {\n}\n"; assert_eq!( - findings(source, &Config::default(), false), - ["a.compact:3:1: missing-doc: module `M` has no doc comment"] + reported(source, &Config::default()), + ["3:1 missing-doc Module `M` has no doc comment."] ); } @@ -548,7 +607,7 @@ mod tests { fn a_pure_exported_circuit_needs_no_constraints() { let source = "/** @description Adds. */\nexport pure circuit add(a: Uint<8>): Uint<8> { return a; }\n"; - assert!(findings(source, &circuit_config(), false).is_empty()); + assert!(reported(source, &circuit_config()).is_empty()); } #[test] @@ -557,25 +616,59 @@ mod tests { "/** @description Bumps. */\nexport circuit bump(): [] { count.increment(1); }\n"; assert_eq!( - findings(source, &circuit_config(), false), - ["a.compact:2:1: missing-constraints: circuit `bump` doc comment has no @constraints"] + reported(source, &circuit_config()), + ["2:1 missing-constraints Circuit `bump` doc comment has no @constraints."] ); } #[test] - fn a_placeholder_is_a_finding_only_under_strict() { + fn a_declaration_span_ends_at_its_name() { + let source = "export module M {\n}\n"; + let issues = Linter::new() + .expect("the bundled grammar loads") + .issues(Path::new("a.compact"), source, &Config::default()) + .expect("the source produced a tree"); + + assert_eq!(issues[0].span().end.column, "export module M".len() + 1); + } + + #[test] + fn a_tag_span_covers_the_tag_token() { + let source = "/**\n * @return nothing\n */\ncircuit hidden(): [] { }\n"; + let mut config = Config::default(); + config.tags.forbid = vec![Tag::new("@return")]; + + let issues = Linter::new() + .expect("the bundled grammar loads") + .issues(Path::new("a.compact"), source, &config) + .expect("the source produced a tree"); + let span = issues[0].span(); + + assert_eq!(span.start.column, 4); + assert_eq!(span.end.column, 11); + } + + #[test] + fn a_placeholder_is_reported_without_strict_too() { let source = "/**\n * @description Bumps.\n * @constraints k=?, rows=?\n */\nexport circuit bump(): [] { }\n"; - let config = circuit_config(); - assert!(findings(source, &config, false).is_empty()); assert_eq!( - findings(source, &config, true), + reported(source, &circuit_config()), [ - "a.compact:3:4: constraints-placeholder: @constraints value `k=?, rows=?` still holds a placeholder" + "3:4 constraints-placeholder @constraints value `k=?, rows=?` still holds a placeholder." ] ); } + #[test] + fn a_rule_set_to_off_produces_no_issue() { + let source = "export module M {\n}\n"; + let mut config = Config::default(); + config.rules.missing_doc = Level::Off; + + assert!(reported(source, &config).is_empty()); + } + #[test] fn a_forbidden_tag_is_reported_even_where_docs_are_optional() { let source = "/**\n * @return nothing\n */\ncircuit hidden(): [] { }\n"; @@ -583,11 +676,29 @@ mod tests { config.tags.forbid = vec![Tag::new("@return")]; assert_eq!( - findings(source, &config, false), - ["a.compact:2:4: forbidden-tag: forbidden tag @return"] + reported(source, &config), + ["2:4 forbidden-tag Forbidden tag @return."] ); } + #[test] + fn a_rename_becomes_the_advice_for_a_forbidden_tag() { + let source = "/**\n * @return nothing\n */\ncircuit hidden(): [] { }\n"; + let mut config = Config::default(); + config.tags.forbid = vec![Tag::new("@return")]; + config + .tags + .rename + .insert(Tag::new("@return"), Tag::new("@returns")); + + let issues = Linter::new() + .expect("the bundled grammar loads") + .issues(Path::new("a.compact"), source, &config) + .expect("the source produced a tree"); + + assert_eq!(issues[0].advice(&config), "Rename it to @returns."); + } + #[test] fn a_witness_under_docs_all_is_checked_without_export() { let source = "witness wit_secret(): Bytes<32>;\n"; @@ -595,8 +706,8 @@ mod tests { config.kinds.witness.docs = DocsPolicy::All; assert_eq!( - findings(source, &config, false), - ["a.compact:1:1: missing-doc: witness `wit_secret` has no doc comment"] + reported(source, &config), + ["1:1 missing-doc Witness `wit_secret` has no doc comment."] ); } @@ -604,9 +715,18 @@ mod tests { fn a_parse_defect_suppresses_the_doc_rules() { let source = "export module M {\nexport circuit\n"; - let reported = findings(source, &Config::default(), false); - assert_eq!(reported.len(), 1, "{reported:?}"); - assert!(reported[0].contains("parse error"), "{reported:?}"); + let issues = reported(source, &Config::default()); + assert_eq!(issues.len(), 1, "{issues:?}"); + assert!(issues[0].contains("Parse error"), "{issues:?}"); + } + + #[test] + fn parse_set_to_off_leaves_a_broken_file_silent() { + let source = "export module M {\nexport circuit\n"; + let mut config = Config::default(); + config.rules.parse = Level::Off; + + assert!(reported(source, &config).is_empty()); } #[test] @@ -615,7 +735,7 @@ mod tests { let mut config = circuit_config(); config.constraints.tag = Tag::new("@circuitInfo"); - assert!(findings(source, &config, false).is_empty()); + assert!(reported(source, &config).is_empty()); } #[test] @@ -633,4 +753,21 @@ mod tests { assert_eq!(module_name("Utils."), "Utils"); assert_eq!(module_name("ShieldedToken (archived)"), "ShieldedToken"); } + + #[test] + fn a_message_opens_with_a_capital_and_closes_with_one_period() { + assert_eq!(sentence("forbidden tag @return"), "Forbidden tag @return."); + assert_eq!(sentence("@module names `A`."), "@module names `A`."); + } + + #[test] + fn every_configurable_rule_has_a_level() { + let rules = Config::default().rules; + + assert!( + RuleId::ALL + .iter() + .all(|rule| rules.get(*rule) != Level::Info) + ); + } } diff --git a/crates/compact-lint/tests/check.rs b/crates/compact-lint/tests/check.rs index 452c09dc..ff96c607 100644 --- a/crates/compact-lint/tests/check.rs +++ b/crates/compact-lint/tests/check.rs @@ -1,13 +1,15 @@ //! `compact-lint check` end to end, one fixture case per rule. //! -//! Every case runs with `--no-format`, because CI has no `compact` binary. +//! Every case runs with `--no-format`, because CI has no `compact` binary, and with +//! `--colors=off`, so the expectation holds whatever the runner's terminal is. +use std::fmt::Write as _; use std::path::PathBuf; use std::process::Command; use assert_cmd::prelude::*; -/// Exit code for a run that produced findings. +/// Exit code for a run that produced errors. const EXIT_FINDINGS: i32 = 1; /// Exit code for a usage, config, IO or parser error. @@ -26,15 +28,15 @@ fn binary() -> Command { Command::cargo_bin("compact-lint").expect("the binary is built alongside this test") } -fn expected(name: &str) -> String { - std::fs::read_to_string(case(name).join("expected.txt")).expect("the case has an expectation") +fn expected(name: &str, file: &str) -> String { + std::fs::read_to_string(case(name).join(file)).expect("the case has an expectation") } -/// Runs `check` inside a case directory and returns its exit code and stdout. -fn run(name: &str, extra: &[&str]) -> (i32, String) { +/// Runs `check` inside a case directory and returns its exit code, stdout and stderr. +fn run(name: &str, extra: &[&str]) -> (i32, String, String) { let output = binary() .current_dir(case(name)) - .args(["check", "--no-format"]) + .args(["check", "--no-format", "--colors=off"]) .args(extra) .output() .expect("the binary ran"); @@ -42,19 +44,51 @@ fn run(name: &str, extra: &[&str]) -> (i32, String) { ( output.status.code().expect("the binary was not signalled"), String::from_utf8(output.stdout).expect("the report is UTF-8"), + String::from_utf8(output.stderr).expect("the summary is UTF-8"), ) } +/// Replaces the measured duration, the one part of the summary a run cannot repeat. +fn without_duration(stderr: &str) -> String { + let mut out = String::new(); + for line in stderr.lines() { + match line + .split_once(" in ") + .filter(|_| line.starts_with("Checked ")) + { + Some((head, tail)) => match tail.split_once(". ") { + Some((_, rest)) => { + let _ = write!(out, "{head} in . {rest}"); + } + None => out.push_str(line), + }, + None => out.push_str(line), + } + out.push('\n'); + } + out +} + fn assert_case(name: &str, extra: &[&str], code: i32) { - let (actual_code, stdout) = run(name, extra); + assert_expectation(name, "expected.txt", extra, code); +} - assert_eq!(stdout, expected(name), "stdout for case {name}"); +fn assert_expectation(name: &str, file: &str, extra: &[&str], code: i32) { + let (actual_code, stdout, _) = run(name, extra); + + assert_eq!(stdout, expected(name, file), "stdout for case {name}"); assert_eq!(actual_code, code, "exit code for case {name}"); } #[test] fn a_fully_documented_module_reports_nothing() { assert_case("clean", &[], 0); + + let (_, _, stderr) = run("clean", &[]); + assert_eq!( + without_duration(&stderr), + "Checked 1 file in . No fixes applied.\n" + ); } #[test] @@ -88,12 +122,17 @@ fn a_malformed_constraints_value_reports_constraints_format() { } #[test] -fn a_placeholder_reports_only_under_strict() { - let (code, stdout) = run("constraints-placeholder", &[]); - assert_eq!(stdout, ""); - assert_eq!(code, 0); +fn a_placeholder_is_a_warning_until_strict_makes_it_an_error() { + assert_case("constraints-placeholder", &[], 0); + assert_expectation( + "constraints-placeholder", + "expected-strict.txt", + &["--strict"], + EXIT_FINDINGS, + ); - assert_case("constraints-placeholder", &["--strict"], EXIT_FINDINGS); + let (_, _, stderr) = run("constraints-placeholder", &[]); + assert!(stderr.ends_with("Found 1 warning.\n"), "{stderr}"); } #[test] @@ -101,17 +140,89 @@ fn a_broken_file_reports_parse_instead_of_crashing() { assert_case("parse", &[], EXIT_FINDINGS); } +#[test] +fn a_rule_set_to_off_is_silent_and_one_set_to_warn_does_not_fail_the_run() { + assert_case("rules-levels", &[], 0); + + let (_, stdout, stderr) = run("rules-levels", &[]); + assert!(!stdout.contains("missing-doc"), "{stdout}"); + assert!(stderr.ends_with("Found 1 warning.\n"), "{stderr}"); +} + +#[test] +fn the_concise_reporter_prints_one_line_per_diagnostic() { + assert_expectation( + "reporter-concise", + "expected.txt", + &["--reporter=concise"], + EXIT_FINDINGS, + ); +} + +#[test] +fn the_github_reporter_prints_workflow_commands() { + assert_expectation( + "reporter-github", + "expected.txt", + &["--reporter=github"], + EXIT_FINDINGS, + ); +} + +#[test] +fn the_cap_shows_the_first_diagnostics_and_counts_the_rest() { + assert_expectation( + "max-diagnostics", + "expected.txt", + &["--max-diagnostics=1"], + EXIT_FINDINGS, + ); + + let (_, _, stderr) = run("max-diagnostics", &["--max-diagnostics=1"]); + assert!( + stderr.starts_with("The number of diagnostics exceeds"), + "{stderr}" + ); + assert!(stderr.contains("Diagnostics not shown: 2.\n"), "{stderr}"); + + let (_, _, lifted) = run("max-diagnostics", &["--max-diagnostics=none"]); + assert!(!lifted.contains("Diagnostics not shown"), "{lifted}"); +} + +#[test] +fn error_on_warnings_fails_a_run_that_only_warned() { + assert_case("error-on-warnings", &["--error-on-warnings"], EXIT_FINDINGS); + assert_case("error-on-warnings", &[], 0); +} + +#[test] +fn the_diagnostic_level_hides_warnings_without_dropping_them_from_the_summary() { + assert_expectation( + "diagnostic-level", + "expected.txt", + &["--diagnostic-level=error"], + EXIT_FINDINGS, + ); + + let (_, stdout, stderr) = run("diagnostic-level", &["--diagnostic-level=error"]); + assert!(!stdout.contains("constraints-placeholder"), "{stdout}"); + assert!( + stderr.ends_with("Found 1 error.\nFound 1 warning.\n"), + "{stderr}" + ); +} + #[test] fn an_explicit_path_replaces_the_include_globs() { let output = binary() .current_dir(case("missing-doc")) - .args(["check", "--no-format", "Gaps.compact"]) + .args(["check", "--no-format", "--colors=off", "Gaps.compact"]) .output() .expect("the binary ran"); assert_eq!( String::from_utf8(output.stdout).expect("the report is UTF-8"), - expected("missing-doc") + expected("missing-doc", "expected.txt") ); } @@ -120,14 +231,14 @@ fn an_explicit_config_anchors_discovery_at_the_working_directory() { let config = case("clean").join("compact-lint.toml"); let output = binary() .current_dir(case("missing-doc")) - .args(["check", "--no-format", "--config"]) + .args(["check", "--no-format", "--colors=off", "--config"]) .arg(&config) .output() .expect("the binary ran"); assert_eq!( String::from_utf8(output.stdout).expect("the report is UTF-8"), - expected("missing-doc") + expected("missing-doc", "expected.txt") ); } @@ -156,17 +267,15 @@ fn an_unreadable_config_exits_two() { } #[test] -fn the_summary_goes_to_stderr_and_the_findings_to_stdout() { - let output = binary() - .current_dir(case("module-name")) - .args(["check", "--no-format"]) - .output() - .expect("the binary ran"); +fn the_summary_goes_to_stderr_and_the_diagnostics_to_stdout() { + let (_, stdout, stderr) = run("module-name", &[]); - let stderr = String::from_utf8(output.stderr).expect("the summary is UTF-8"); - assert_eq!(stderr.trim_end(), "1 findings in 1 files"); + assert_eq!( + without_duration(&stderr), + "Checked 1 file in . No fixes applied.\nFound 1 error.\n" + ); assert!( - String::from_utf8_lossy(&output.stdout).contains("module-name"), + stdout.contains("lint/module-name"), "the rule id belongs on stdout" ); } diff --git a/crates/compact-lint/tests/fill.rs b/crates/compact-lint/tests/fill.rs index 8c8cbcba..bbf3e241 100644 --- a/crates/compact-lint/tests/fill.rs +++ b/crates/compact-lint/tests/fill.rs @@ -93,15 +93,15 @@ fn collect(root: &Path, directory: &Path, out: &mut BTreeMap>) } } -fn expected(name: &str) -> String { - std::fs::read_to_string(case(name).join("expected.txt")).expect("the case has an expectation") +fn expected(name: &str, file: &str) -> String { + std::fs::read_to_string(case(name).join(file)).expect("the case has an expectation") } /// Runs `fill-constraints` inside `directory`, pointed at the fake compiler. fn fill(directory: &Path, extra: &[&str]) -> Output { binary() .current_dir(directory) - .args(["fill-constraints", "--compact-bin"]) + .args(["fill-constraints", "--colors=off", "--compact-bin"]) .arg(fake_compact()) .args(extra) .output() @@ -120,6 +120,7 @@ fn run(directory: &Path, args: &[&str]) -> (i32, String) { let output = binary() .current_dir(directory) .args(args) + .arg("--colors=off") .output() .expect("the binary ran"); code_and_stdout(&output) @@ -127,13 +128,18 @@ fn run(directory: &Path, args: &[&str]) -> (i32, String) { /// The whole contract of a measurable case: it fills, it lands, it settles, it previews. /// -/// `settled` is what a second run still reports, which is the unmeasured circuits. -fn assert_case(name: &str, extra: &[&str], exit: i32, settled: &str) { +/// A case holds `expected.txt` for the write run, `expected-settled.txt` for what a +/// second run still reports, and `expected-dry-run.txt` for the preview. +fn assert_case(name: &str, extra: &[&str], exit: i32) { let directory = work(name); let root = directory.path(); let (code, stdout) = code_and_stdout(&fill(root, extra)); - assert_eq!(stdout, expected(name), "stdout for case {name}"); + assert_eq!( + stdout, + expected(name, "expected.txt"), + "stdout for case {name}" + ); assert_eq!(code, exit, "exit code for case {name}"); assert_eq!( sources(root), @@ -146,7 +152,11 @@ fn assert_case(name: &str, extra: &[&str], exit: i32, settled: &str) { assert_eq!(code, 0, "check exit code after filling case {name}"); let (code, stdout) = code_and_stdout(&fill(root, extra)); - assert_eq!(stdout, settled, "a second run on case {name}"); + assert_eq!( + stdout, + expected(name, "expected-settled.txt"), + "a second run on case {name}" + ); assert_eq!(code, exit, "second run exit code for case {name}"); let preview = work(name); @@ -154,7 +164,11 @@ fn assert_case(name: &str, extra: &[&str], exit: i32, settled: &str) { let mut arguments = extra.to_vec(); arguments.push("--dry-run"); let (code, stdout) = code_and_stdout(&fill(preview.path(), &arguments)); - assert_eq!(stdout, expected(name), "dry-run stdout for case {name}"); + assert_eq!( + stdout, + expected(name, "expected-dry-run.txt"), + "dry-run stdout for case {name}" + ); assert_eq!(code, exit, "dry-run exit code for case {name}"); assert_eq!( sources(preview.path()), @@ -165,28 +179,22 @@ fn assert_case(name: &str, extra: &[&str], exit: i32, settled: &str) { #[test] fn placeholders_and_stale_values_take_the_measurement() { - let unmeasured = expected("basic") - .lines() - .filter(|line| line.contains("constraints-unmeasured")) - .collect::>() - .join("\n"); - - assert_case("basic", &[], EXIT_UNMEASURED, &format!("{unmeasured}\n")); + assert_case("basic", &[], EXIT_UNMEASURED); } #[test] fn a_preset_matching_a_self_glob_compiles_itself() { - assert_case("self", &[], 0, ""); + assert_case("self", &[], 0); } #[test] fn an_override_names_the_contract_that_measures_a_file() { - assert_case("override", &[], 0, ""); + assert_case("override", &[], 0); } #[test] fn a_seeded_cache_fills_without_a_compiler() { - assert_case("no-compile", &["--no-compile"], 0, ""); + assert_case("no-compile", &["--no-compile"], 0); } #[test] @@ -195,10 +203,13 @@ fn a_circuit_the_report_marks_unproved_stays_unmeasured() { let (_, stdout) = code_and_stdout(&fill(directory.path(), &[])); assert!( - stdout.contains("circuit `initialize` has no measurement"), + stdout.contains("Circuit `initialize` has no measurement."), + "{stdout}" + ); + assert!( + !stdout.contains("Set @constraints to k=5, rows=10"), "{stdout}" ); - assert!(!stdout.contains("k=5, rows=10"), "{stdout}"); } #[test] @@ -209,7 +220,7 @@ fn a_file_with_no_measurement_source_reports_once_and_exits_one() { let (code, stdout) = code_and_stdout(&fill(root, &[])); - assert_eq!(stdout, expected("missing-source")); + assert_eq!(stdout, expected("missing-source", "expected.txt")); assert_eq!(code, EXIT_UNMEASURED); assert_eq!(sources(root), before); } @@ -258,13 +269,15 @@ fn a_compile_writes_the_cache_the_builder_shares() { fn the_summary_goes_to_stderr_and_the_changes_to_stdout() { let directory = work("basic"); let output = fill(directory.path(), &[]); + let stderr = String::from_utf8_lossy(&output.stderr); - assert_eq!( - String::from_utf8_lossy(&output.stderr).trim_end(), - "2 values filled in 1 files, 1 unmeasured" + assert!(stderr.starts_with("Checked 1 file in "), "{stderr}"); + assert!( + stderr.ends_with(". Filled 2 values in 1 file.\nFound 1 warning.\n"), + "{stderr}" ); assert!( - String::from_utf8_lossy(&output.stdout).contains(": fill: "), + String::from_utf8_lossy(&output.stdout).contains(" fill FIXED "), "the changes belong on stdout" ); } diff --git a/crates/compact-lint/tests/fix.rs b/crates/compact-lint/tests/fix.rs index fae2b524..2d4e7189 100644 --- a/crates/compact-lint/tests/fix.rs +++ b/crates/compact-lint/tests/fix.rs @@ -1,7 +1,8 @@ //! `compact-lint fix` end to end, one fixture case per rule. //! -//! A case holds `compact-lint.toml`, `before/`, `after/` and `expected.txt`. The run -//! works on a copy of `before/`, so the fixtures themselves are never rewritten. +//! A case holds `compact-lint.toml`, `before/`, `after/`, `expected.txt` for the write +//! run and `expected-dry-run.txt` for the preview. The run works on a copy of `before/`, +//! so the fixtures themselves are never rewritten. use std::collections::BTreeMap; use std::path::{Path, PathBuf}; @@ -79,8 +80,8 @@ fn collect(root: &Path, directory: &Path, out: &mut BTreeMap>) } } -fn expected(name: &str) -> String { - std::fs::read_to_string(case(name).join("expected.txt")).expect("the case has an expectation") +fn expected(name: &str, file: &str) -> String { + std::fs::read_to_string(case(name).join(file)).expect("the case has an expectation") } /// Runs a subcommand inside `directory` and returns its exit code and stdout. @@ -88,6 +89,7 @@ fn run(directory: &Path, args: &[&str]) -> (i32, String) { let output = binary() .current_dir(directory) .args(args) + .arg("--colors=off") .output() .expect("the binary ran"); @@ -103,7 +105,11 @@ fn assert_case(name: &str) { let root = directory.path(); let (code, stdout) = run(root, &["fix"]); - assert_eq!(stdout, expected(name), "stdout for case {name}"); + assert_eq!( + stdout, + expected(name, "expected.txt"), + "stdout for case {name}" + ); assert_eq!(code, 0, "exit code for case {name}"); assert_eq!( sources(root), @@ -111,7 +117,9 @@ fn assert_case(name: &str) { "rewritten sources for case {name}" ); - let (code, stdout) = run(root, &["check", "--no-format"]); + // An inserted annotation is a placeholder, which `check` warns about until it is + // measured; nothing at error level may survive the fix. + let (code, stdout) = run(root, &["check", "--no-format", "--diagnostic-level=error"]); assert_eq!(stdout, "", "check is clean after fixing case {name}"); assert_eq!(code, 0, "check exit code after fixing case {name}"); @@ -122,7 +130,11 @@ fn assert_case(name: &str) { let preview = work(name); let before = sources(preview.path()); let (code, stdout) = run(preview.path(), &["fix", "--dry-run"]); - assert_eq!(stdout, expected(name), "dry-run stdout for case {name}"); + assert_eq!( + stdout, + expected(name, "expected-dry-run.txt"), + "dry-run stdout for case {name}" + ); assert_eq!(code, EXIT_EDITS, "dry-run exit code for case {name}"); assert_eq!( sources(preview.path()), @@ -182,18 +194,34 @@ fn the_summary_goes_to_stderr_and_the_edits_to_stdout() { let directory = work("rename"); let output = binary() .current_dir(directory.path()) - .arg("fix") + .args(["fix", "--colors=off"]) .output() .expect("the binary ran"); let stderr = String::from_utf8(output.stderr).expect("the summary is UTF-8"); - assert_eq!(stderr.trim_end(), "2 edits in 1 files"); + assert!(stderr.starts_with("Checked 1 file in "), "{stderr}"); + assert!(stderr.ends_with(". Fixed 1 file.\n"), "{stderr}"); assert!( - String::from_utf8_lossy(&output.stdout).contains(": fix: "), + String::from_utf8_lossy(&output.stdout).contains(" FIXED "), "the edits belong on stdout" ); } +#[test] +fn a_concise_run_prints_one_line_per_edit() { + let directory = work("rename"); + let (code, stdout) = run(directory.path(), &["fix", "--reporter=concise"]); + + assert_eq!( + stdout, + concat!( + "i Returns.compact:9:6: lint/forbidden-tag: Forbidden tag @return.\n", + "i Returns.compact:15:6: lint/forbidden-tag: Forbidden tag @return.\n", + ) + ); + assert_eq!(code, 0); +} + #[test] fn an_explicit_config_replaces_the_one_beside_the_sources() { let directory = work("rename"); @@ -203,14 +231,14 @@ fn an_explicit_config_replaces_the_one_beside_the_sources() { let config = case("rename").join("compact-lint.toml"); let output = binary() .current_dir(directory.path()) - .args(["fix", "--config"]) + .args(["fix", "--colors=off", "--config"]) .arg(&config) .output() .expect("the binary ran"); assert_eq!( String::from_utf8(output.stdout).expect("the report is UTF-8"), - expected("rename") + expected("rename", "expected.txt") ); } diff --git a/crates/compact-lint/tests/fixtures/constraints-format/expected.txt b/crates/compact-lint/tests/fixtures/constraints-format/expected.txt index a1b1ac88..cc4ddc91 100644 --- a/crates/compact-lint/tests/fixtures/constraints-format/expected.txt +++ b/crates/compact-lint/tests/fixtures/constraints-format/expected.txt @@ -1,2 +1,26 @@ -Malformed.compact:8:6: constraints-format: @constraints value `k=10 rows=626` is not `k=, rows=` -Malformed.compact:14:6: constraints-format: @constraints value `rows=626, k=10` is not `k=, rows=` +Malformed.compact:8:6 lint/constraints-format ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + Γ— @constraints value `k=10 rows=626` is not `k=, rows=`. + + 6 β”‚ /** + 7 β”‚ * @description The comma is missing. + > 8 β”‚ * @constraints k=10 rows=626 + β”‚ ^^^^^^^^^^^^ + 9 β”‚ */ + 10 β”‚ export circuit first(): [] { } + + i Write the value as k=, rows=. + +Malformed.compact:14:6 lint/constraints-format ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + Γ— @constraints value `rows=626, k=10` is not `k=, rows=`. + + 12 β”‚ /** + 13 β”‚ * @description The fields are the wrong way round. + > 14 β”‚ * @constraints rows=626, k=10 + β”‚ ^^^^^^^^^^^^ + 15 β”‚ */ + 16 β”‚ export circuit second(): [] { } + + i Write the value as k=, rows=. + diff --git a/crates/compact-lint/tests/fixtures/constraints-placeholder/expected-strict.txt b/crates/compact-lint/tests/fixtures/constraints-placeholder/expected-strict.txt new file mode 100644 index 00000000..bbb6b7f8 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/constraints-placeholder/expected-strict.txt @@ -0,0 +1,13 @@ +Unfilled.compact:8:6 lint/constraints-placeholder ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + Γ— @constraints value `k=?, rows=?` still holds a placeholder. + + 6 β”‚ /** + 7 β”‚ * @description Not measured yet. + > 8 β”‚ * @constraints k=?, rows=? + β”‚ ^^^^^^^^^^^^ + 9 β”‚ */ + 10 β”‚ export circuit run(): [] { } + + i Run compact-lint fill-constraints to measure it. + diff --git a/crates/compact-lint/tests/fixtures/constraints-placeholder/expected.txt b/crates/compact-lint/tests/fixtures/constraints-placeholder/expected.txt index ba3214ef..44a95a66 100644 --- a/crates/compact-lint/tests/fixtures/constraints-placeholder/expected.txt +++ b/crates/compact-lint/tests/fixtures/constraints-placeholder/expected.txt @@ -1 +1,13 @@ -Unfilled.compact:8:6: constraints-placeholder: @constraints value `k=?, rows=?` still holds a placeholder +Unfilled.compact:8:6 lint/constraints-placeholder ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + ! @constraints value `k=?, rows=?` still holds a placeholder. + + 6 β”‚ /** + 7 β”‚ * @description Not measured yet. + > 8 β”‚ * @constraints k=?, rows=? + β”‚ ^^^^^^^^^^^^ + 9 β”‚ */ + 10 β”‚ export circuit run(): [] { } + + i Run compact-lint fill-constraints to measure it. + diff --git a/crates/compact-lint/tests/fixtures/diagnostic-level/Mixed.compact b/crates/compact-lint/tests/fixtures/diagnostic-level/Mixed.compact new file mode 100644 index 00000000..316ad867 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/diagnostic-level/Mixed.compact @@ -0,0 +1,16 @@ +/** + * @module Mixed + * @description A module with one warning and one error. + */ +export module Mixed { + /** + * @description Not measured yet. + * @constraints k=?, rows=? + */ + export circuit run(): [] { } + + /** + * @description Unannotated. + */ + export circuit bump(): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/diagnostic-level/compact-lint.toml b/crates/compact-lint/tests/fixtures/diagnostic-level/compact-lint.toml new file mode 100644 index 00000000..0813e24c --- /dev/null +++ b/crates/compact-lint/tests/fixtures/diagnostic-level/compact-lint.toml @@ -0,0 +1,27 @@ +version = 1 +include = ["**/*.compact"] + +[tags] +forbid = ["@return"] + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] + +[kinds.ledger] +tags = ["@description"] + +[kinds.witness] +docs = "all" +tags = ["@description"] + +[kinds.struct] +tags = ["@description"] + +[kinds.enum] +tags = ["@description"] + +[kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/diagnostic-level/expected.txt b/crates/compact-lint/tests/fixtures/diagnostic-level/expected.txt new file mode 100644 index 00000000..66526c9e --- /dev/null +++ b/crates/compact-lint/tests/fixtures/diagnostic-level/expected.txt @@ -0,0 +1,17 @@ +Mixed.compact:15:3 lint/missing-constraints FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + Γ— Circuit `bump` doc comment has no @constraints. + + 13 β”‚ * @description Unannotated. + 14 β”‚ */ + > 15 β”‚ export circuit bump(): [] { } + β”‚ ^^^^^^^^^^^^^^^^^^^ + 16 β”‚ } + + i Run compact-lint fill-constraints after adding the tag, or add it as @constraints k=?, rows=? to fill later. + + i Unsafe fix: Insert @constraints k=?, rows=? + + 14 β”‚ + Β·Β·Β·* + 15 β”‚ + Β·Β·Β·*Β·@constraintsΒ·k=?,Β·rows=? + diff --git a/crates/compact-lint/tests/fixtures/error-on-warnings/Warned.compact b/crates/compact-lint/tests/fixtures/error-on-warnings/Warned.compact new file mode 100644 index 00000000..08673d61 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/error-on-warnings/Warned.compact @@ -0,0 +1,11 @@ +/** + * @module Warned + * @description A module whose only finding is a warning. + */ +export module Warned { + /** + * @description Not measured yet. + * @constraints k=?, rows=? + */ + export circuit run(): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/error-on-warnings/compact-lint.toml b/crates/compact-lint/tests/fixtures/error-on-warnings/compact-lint.toml new file mode 100644 index 00000000..0813e24c --- /dev/null +++ b/crates/compact-lint/tests/fixtures/error-on-warnings/compact-lint.toml @@ -0,0 +1,27 @@ +version = 1 +include = ["**/*.compact"] + +[tags] +forbid = ["@return"] + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] + +[kinds.ledger] +tags = ["@description"] + +[kinds.witness] +docs = "all" +tags = ["@description"] + +[kinds.struct] +tags = ["@description"] + +[kinds.enum] +tags = ["@description"] + +[kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/error-on-warnings/expected.txt b/crates/compact-lint/tests/fixtures/error-on-warnings/expected.txt new file mode 100644 index 00000000..26aece60 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/error-on-warnings/expected.txt @@ -0,0 +1,13 @@ +Warned.compact:8:6 lint/constraints-placeholder ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + ! @constraints value `k=?, rows=?` still holds a placeholder. + + 6 β”‚ /** + 7 β”‚ * @description Not measured yet. + > 8 β”‚ * @constraints k=?, rows=? + β”‚ ^^^^^^^^^^^^ + 9 β”‚ */ + 10 β”‚ export circuit run(): [] { } + + i Run compact-lint fill-constraints to measure it. + diff --git a/crates/compact-lint/tests/fixtures/fill-basic/expected-dry-run.txt b/crates/compact-lint/tests/fixtures/fill-basic/expected-dry-run.txt new file mode 100644 index 00000000..dbeaeb3b --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-basic/expected-dry-run.txt @@ -0,0 +1,45 @@ +src/access/Ownable.compact:9:6 fill FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `owner` measures k=7, rows=74. + + 7 β”‚ * @description Returns the owner. + 8 β”‚ * + > 9 β”‚ * @constraints k=?, rows=? + β”‚ ^^^^^^^^^^^^ + 10 β”‚ */ + 11 β”‚ export circuit owner(): [] { } + + i Safe fix: Set @constraints to k=7, rows=74 + + 9 β”‚ - Β·Β·Β·*Β·@constraintsΒ·k=?,Β·rows=? + 9 β”‚ + Β·Β·Β·*Β·@constraintsΒ·k=7,Β·rows=74 + +src/access/Ownable.compact:16:6 fill FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `transferOwnership` measures k=13, rows=4871. + + 14 β”‚ * @description Transfers ownership. + 15 β”‚ * + > 16 β”‚ * @constraints k=9, rows=42 + β”‚ ^^^^^^^^^^^^ + 17 β”‚ */ + 18 β”‚ export circuit transferOwnership(): [] { } + + i Safe fix: Set @constraints to k=13, rows=4871 + + 16 β”‚ - Β·Β·Β·*Β·@constraintsΒ·k=9,Β·rows=42 + 16 β”‚ + Β·Β·Β·*Β·@constraintsΒ·k=13,Β·rows=4871 + +src/access/Ownable.compact:30:6 lint/constraints-unmeasured ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + ! Circuit `initialize` has no measurement. + + 28 β”‚ * @description Sets the first owner. + 29 β”‚ * + > 30 β”‚ * @constraints k=5, rows=10 + β”‚ ^^^^^^^^^^^^ + 31 β”‚ */ + 32 β”‚ export circuit initialize(): [] { } + + i It is measured through src/access/test/mocks/MockOwnable.compact, which exports no circuit of that name. + diff --git a/crates/compact-lint/tests/fixtures/fill-basic/expected-settled.txt b/crates/compact-lint/tests/fixtures/fill-basic/expected-settled.txt new file mode 100644 index 00000000..0808b59c --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-basic/expected-settled.txt @@ -0,0 +1,13 @@ +src/access/Ownable.compact:30:6 lint/constraints-unmeasured ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + ! Circuit `initialize` has no measurement. + + 28 β”‚ * @description Sets the first owner. + 29 β”‚ * + > 30 β”‚ * @constraints k=5, rows=10 + β”‚ ^^^^^^^^^^^^ + 31 β”‚ */ + 32 β”‚ export circuit initialize(): [] { } + + i It is measured through src/access/test/mocks/MockOwnable.compact, which exports no circuit of that name. + diff --git a/crates/compact-lint/tests/fixtures/fill-basic/expected.txt b/crates/compact-lint/tests/fixtures/fill-basic/expected.txt index a9bdabc9..15e834a1 100644 --- a/crates/compact-lint/tests/fixtures/fill-basic/expected.txt +++ b/crates/compact-lint/tests/fixtures/fill-basic/expected.txt @@ -1,3 +1,31 @@ -src/access/Ownable.compact:9:6: fill: @constraints k=?, rows=? -> k=7, rows=74 -src/access/Ownable.compact:16:6: fill: @constraints k=9, rows=42 -> k=13, rows=4871 -src/access/Ownable.compact:30:6: constraints-unmeasured: circuit `initialize` has no measurement in src/access/test/mocks/MockOwnable.compact +src/access/Ownable.compact:9:6 fill FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `owner` measures k=7, rows=74. + + i Applied fix: Set @constraints to k=7, rows=74 + + 9 β”‚ - Β·Β·Β·*Β·@constraintsΒ·k=?,Β·rows=? + 9 β”‚ + Β·Β·Β·*Β·@constraintsΒ·k=7,Β·rows=74 + +src/access/Ownable.compact:16:6 fill FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `transferOwnership` measures k=13, rows=4871. + + i Applied fix: Set @constraints to k=13, rows=4871 + + 16 β”‚ - Β·Β·Β·*Β·@constraintsΒ·k=9,Β·rows=42 + 16 β”‚ + Β·Β·Β·*Β·@constraintsΒ·k=13,Β·rows=4871 + +src/access/Ownable.compact:30:6 lint/constraints-unmeasured ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + ! Circuit `initialize` has no measurement. + + 28 β”‚ * @description Sets the first owner. + 29 β”‚ * + > 30 β”‚ * @constraints k=5, rows=10 + β”‚ ^^^^^^^^^^^^ + 31 β”‚ */ + 32 β”‚ export circuit initialize(): [] { } + + i It is measured through src/access/test/mocks/MockOwnable.compact, which exports no circuit of that name. + diff --git a/crates/compact-lint/tests/fixtures/fill-missing-source/expected-dry-run.txt b/crates/compact-lint/tests/fixtures/fill-missing-source/expected-dry-run.txt new file mode 100644 index 00000000..e4df1982 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-missing-source/expected-dry-run.txt @@ -0,0 +1,11 @@ +src/orphan/Orphan.compact:1:1 lint/constraints-unmeasurable ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + ! No measurement source for src/orphan/Orphan.compact. + + > 1 β”‚ /** + β”‚ ^ + 2 β”‚ * @module Orphan + 3 β”‚ * @description Test fixture. + + i Tried src/orphan/test/mocks/MockOrphan.compact, src/test/mocks/MockOrphan.compact; add one, or name it in constraints.overrides. + diff --git a/crates/compact-lint/tests/fixtures/fill-missing-source/expected-settled.txt b/crates/compact-lint/tests/fixtures/fill-missing-source/expected-settled.txt new file mode 100644 index 00000000..e4df1982 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-missing-source/expected-settled.txt @@ -0,0 +1,11 @@ +src/orphan/Orphan.compact:1:1 lint/constraints-unmeasurable ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + ! No measurement source for src/orphan/Orphan.compact. + + > 1 β”‚ /** + β”‚ ^ + 2 β”‚ * @module Orphan + 3 β”‚ * @description Test fixture. + + i Tried src/orphan/test/mocks/MockOrphan.compact, src/test/mocks/MockOrphan.compact; add one, or name it in constraints.overrides. + diff --git a/crates/compact-lint/tests/fixtures/fill-missing-source/expected.txt b/crates/compact-lint/tests/fixtures/fill-missing-source/expected.txt index 1a91510b..e4df1982 100644 --- a/crates/compact-lint/tests/fixtures/fill-missing-source/expected.txt +++ b/crates/compact-lint/tests/fixtures/fill-missing-source/expected.txt @@ -1 +1,11 @@ -src/orphan/Orphan.compact:1:1: constraints-unmeasurable: no measurement source for src/orphan/Orphan.compact; tried src/orphan/test/mocks/MockOrphan.compact, src/test/mocks/MockOrphan.compact +src/orphan/Orphan.compact:1:1 lint/constraints-unmeasurable ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + ! No measurement source for src/orphan/Orphan.compact. + + > 1 β”‚ /** + β”‚ ^ + 2 β”‚ * @module Orphan + 3 β”‚ * @description Test fixture. + + i Tried src/orphan/test/mocks/MockOrphan.compact, src/test/mocks/MockOrphan.compact; add one, or name it in constraints.overrides. + diff --git a/crates/compact-lint/tests/fixtures/fill-no-compile/expected-dry-run.txt b/crates/compact-lint/tests/fixtures/fill-no-compile/expected-dry-run.txt new file mode 100644 index 00000000..2af2854d --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-no-compile/expected-dry-run.txt @@ -0,0 +1,16 @@ +src/access/Ownable.compact:9:6 fill FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `owner` measures k=7, rows=74. + + 7 β”‚ * @description Returns the owner. + 8 β”‚ * + > 9 β”‚ * @constraints k=?, rows=? + β”‚ ^^^^^^^^^^^^ + 10 β”‚ */ + 11 β”‚ export circuit owner(): [] { } + + i Safe fix: Set @constraints to k=7, rows=74 + + 9 β”‚ - Β·Β·Β·*Β·@constraintsΒ·k=?,Β·rows=? + 9 β”‚ + Β·Β·Β·*Β·@constraintsΒ·k=7,Β·rows=74 + diff --git a/crates/compact-lint/tests/fixtures/fill-no-compile/expected-settled.txt b/crates/compact-lint/tests/fixtures/fill-no-compile/expected-settled.txt new file mode 100644 index 00000000..e69de29b diff --git a/crates/compact-lint/tests/fixtures/fill-no-compile/expected.txt b/crates/compact-lint/tests/fixtures/fill-no-compile/expected.txt index 0e5a1e3f..ea1b5f14 100644 --- a/crates/compact-lint/tests/fixtures/fill-no-compile/expected.txt +++ b/crates/compact-lint/tests/fixtures/fill-no-compile/expected.txt @@ -1 +1,9 @@ -src/access/Ownable.compact:9:6: fill: @constraints k=?, rows=? -> k=7, rows=74 +src/access/Ownable.compact:9:6 fill FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `owner` measures k=7, rows=74. + + i Applied fix: Set @constraints to k=7, rows=74 + + 9 β”‚ - Β·Β·Β·*Β·@constraintsΒ·k=?,Β·rows=? + 9 β”‚ + Β·Β·Β·*Β·@constraintsΒ·k=7,Β·rows=74 + diff --git a/crates/compact-lint/tests/fixtures/fill-override/expected-dry-run.txt b/crates/compact-lint/tests/fixtures/fill-override/expected-dry-run.txt new file mode 100644 index 00000000..28991319 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-override/expected-dry-run.txt @@ -0,0 +1,16 @@ +src/utils/Utils.compact:9:6 fill FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `hash` measures k=9, rows=310. + + 7 β”‚ * @description Hashes a value. + 8 β”‚ * + > 9 β”‚ * @constraints k=?, rows=? + β”‚ ^^^^^^^^^^^^ + 10 β”‚ */ + 11 β”‚ export circuit hash(): [] { } + + i Safe fix: Set @constraints to k=9, rows=310 + + 9 β”‚ - Β·Β·Β·*Β·@constraintsΒ·k=?,Β·rows=? + 9 β”‚ + Β·Β·Β·*Β·@constraintsΒ·k=9,Β·rows=310 + diff --git a/crates/compact-lint/tests/fixtures/fill-override/expected-settled.txt b/crates/compact-lint/tests/fixtures/fill-override/expected-settled.txt new file mode 100644 index 00000000..e69de29b diff --git a/crates/compact-lint/tests/fixtures/fill-override/expected.txt b/crates/compact-lint/tests/fixtures/fill-override/expected.txt index f718af96..069f732f 100644 --- a/crates/compact-lint/tests/fixtures/fill-override/expected.txt +++ b/crates/compact-lint/tests/fixtures/fill-override/expected.txt @@ -1 +1,9 @@ -src/utils/Utils.compact:9:6: fill: @constraints k=?, rows=? -> k=9, rows=310 +src/utils/Utils.compact:9:6 fill FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `hash` measures k=9, rows=310. + + i Applied fix: Set @constraints to k=9, rows=310 + + 9 β”‚ - Β·Β·Β·*Β·@constraintsΒ·k=?,Β·rows=? + 9 β”‚ + Β·Β·Β·*Β·@constraintsΒ·k=9,Β·rows=310 + diff --git a/crates/compact-lint/tests/fixtures/fill-self/expected-dry-run.txt b/crates/compact-lint/tests/fixtures/fill-self/expected-dry-run.txt new file mode 100644 index 00000000..470061e2 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-self/expected-dry-run.txt @@ -0,0 +1,32 @@ +src/multisig/presets/Vault.compact:9:6 fill FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `deposit` measures k=12, rows=2048. + + 7 β”‚ * @description Deposits a coin. + 8 β”‚ * + > 9 β”‚ * @constraints k=?, rows=? + β”‚ ^^^^^^^^^^^^ + 10 β”‚ */ + 11 β”‚ export circuit deposit(): [] { } + + i Safe fix: Set @constraints to k=12, rows=2048 + + 9 β”‚ - Β·Β·Β·*Β·@constraintsΒ·k=?,Β·rows=? + 9 β”‚ + Β·Β·Β·*Β·@constraintsΒ·k=12,Β·rows=2048 + +src/multisig/presets/Vault.compact:16:6 fill FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `withdraw` measures k=14, rows=8192. + + 14 β”‚ * @description Withdraws a coin. + 15 β”‚ * + > 16 β”‚ * @constraints k=?, rows=? + β”‚ ^^^^^^^^^^^^ + 17 β”‚ */ + 18 β”‚ export circuit withdraw(): [] { } + + i Safe fix: Set @constraints to k=14, rows=8192 + + 16 β”‚ - Β·Β·Β·*Β·@constraintsΒ·k=?,Β·rows=? + 16 β”‚ + Β·Β·Β·*Β·@constraintsΒ·k=14,Β·rows=8192 + diff --git a/crates/compact-lint/tests/fixtures/fill-self/expected-settled.txt b/crates/compact-lint/tests/fixtures/fill-self/expected-settled.txt new file mode 100644 index 00000000..e69de29b diff --git a/crates/compact-lint/tests/fixtures/fill-self/expected.txt b/crates/compact-lint/tests/fixtures/fill-self/expected.txt index 88499e9a..b6ef8af3 100644 --- a/crates/compact-lint/tests/fixtures/fill-self/expected.txt +++ b/crates/compact-lint/tests/fixtures/fill-self/expected.txt @@ -1,2 +1,18 @@ -src/multisig/presets/Vault.compact:9:6: fill: @constraints k=?, rows=? -> k=12, rows=2048 -src/multisig/presets/Vault.compact:16:6: fill: @constraints k=?, rows=? -> k=14, rows=8192 +src/multisig/presets/Vault.compact:9:6 fill FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `deposit` measures k=12, rows=2048. + + i Applied fix: Set @constraints to k=12, rows=2048 + + 9 β”‚ - Β·Β·Β·*Β·@constraintsΒ·k=?,Β·rows=? + 9 β”‚ + Β·Β·Β·*Β·@constraintsΒ·k=12,Β·rows=2048 + +src/multisig/presets/Vault.compact:16:6 fill FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `withdraw` measures k=14, rows=8192. + + i Applied fix: Set @constraints to k=14, rows=8192 + + 16 β”‚ - Β·Β·Β·*Β·@constraintsΒ·k=?,Β·rows=? + 16 β”‚ + Β·Β·Β·*Β·@constraintsΒ·k=14,Β·rows=8192 + diff --git a/crates/compact-lint/tests/fixtures/fix-constraints/expected-dry-run.txt b/crates/compact-lint/tests/fixtures/fix-constraints/expected-dry-run.txt new file mode 100644 index 00000000..8b9a4618 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-constraints/expected-dry-run.txt @@ -0,0 +1,48 @@ +Unmeasured.compact:9:3 lint/missing-constraints FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `bump` doc comment has no @constraints. + + 7 β”‚ * @description Bumps the counter. + 8 β”‚ */ + > 9 β”‚ export circuit bump(): [] { } + β”‚ ^^^^^^^^^^^^^^^^^^^ + 10 β”‚ + 11 β”‚ /** + + i Unsafe fix: Insert @constraints k=?, rows=? + + 8 β”‚ + Β·Β·Β·* + 9 β”‚ + Β·Β·Β·*Β·@constraintsΒ·k=?,Β·rows=? + +Unmeasured.compact:18:3 lint/missing-constraints FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `send` doc comment has no @constraints. + + 16 β”‚ * @returns {[]} Empty tuple. + 17 β”‚ */ + > 18 β”‚ export circuit send(to: Bytes<32>): [] { } + β”‚ ^^^^^^^^^^^^^^^^^^^ + 19 β”‚ + 20 β”‚ /** + + i Unsafe fix: Insert @constraints k=?, rows=? + + 15 β”‚ + Β·Β·Β·*Β·@constraintsΒ·k=?,Β·rows=? + 16 β”‚ + Β·Β·Β·* + +Unmeasured.compact:23:3 lint/missing-constraints FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `run` doc comment has no @constraints. + + 21 β”‚ * @notice The annotation goes to the top, since there is no description. + 22 β”‚ */ + > 23 β”‚ export circuit run(): [] { } + β”‚ ^^^^^^^^^^^^^^^^^^ + 24 β”‚ + 25 β”‚ /** + + i Unsafe fix: Insert @constraints k=?, rows=? + + 21 β”‚ + Β·Β·Β·*Β·@constraintsΒ·k=?,Β·rows=? + 22 β”‚ + Β·Β·Β·* + diff --git a/crates/compact-lint/tests/fixtures/fix-constraints/expected.txt b/crates/compact-lint/tests/fixtures/fix-constraints/expected.txt index 9b498237..cd1b0d53 100644 --- a/crates/compact-lint/tests/fixtures/fix-constraints/expected.txt +++ b/crates/compact-lint/tests/fixtures/fix-constraints/expected.txt @@ -1,3 +1,27 @@ -Unmeasured.compact:9:3: fix: inserted @constraints k=?, rows=? -Unmeasured.compact:18:3: fix: inserted @constraints k=?, rows=? -Unmeasured.compact:23:3: fix: inserted @constraints k=?, rows=? +Unmeasured.compact:9:3 lint/missing-constraints FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `bump` doc comment has no @constraints. + + i Applied fix: Insert @constraints k=?, rows=? + + 8 β”‚ + Β·Β·Β·* + 9 β”‚ + Β·Β·Β·*Β·@constraintsΒ·k=?,Β·rows=? + +Unmeasured.compact:18:3 lint/missing-constraints FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `send` doc comment has no @constraints. + + i Applied fix: Insert @constraints k=?, rows=? + + 15 β”‚ + Β·Β·Β·*Β·@constraintsΒ·k=?,Β·rows=? + 16 β”‚ + Β·Β·Β·* + +Unmeasured.compact:23:3 lint/missing-constraints FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `run` doc comment has no @constraints. + + i Applied fix: Insert @constraints k=?, rows=? + + 21 β”‚ + Β·Β·Β·*Β·@constraintsΒ·k=?,Β·rows=? + 22 β”‚ + Β·Β·Β·* + diff --git a/crates/compact-lint/tests/fixtures/fix-crlf/expected-dry-run.txt b/crates/compact-lint/tests/fixtures/fix-crlf/expected-dry-run.txt new file mode 100644 index 00000000..506bff8d --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-crlf/expected-dry-run.txt @@ -0,0 +1,49 @@ +Windows.compact:6:3 lint/missing-doc FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Ledger `_count` has no doc comment. + + 4 β”‚ */ + 5 β”‚ export module Windows { + > 6 β”‚ export ledger _count: Counter; + β”‚ ^^^^^^^^^^^^^^^^^^^^ + 7 β”‚ + 8 β”‚ /** + + i Unsafe fix: Insert a doc skeleton for ledger `_count` + + 6 β”‚ + Β·Β·/** + 7 β”‚ + Β·Β·Β·*Β·@descriptionΒ·TODO + 8 β”‚ + Β·Β·Β·*/ + +Windows.compact:10:6 lint/forbidden-tag FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Forbidden tag @return. + + 8 β”‚ /** + 9 β”‚ * @description Bumps the counter. + > 10 β”‚ * @return {[]} - Empty tuple. + β”‚ ^^^^^^^ + 11 β”‚ */ + 12 β”‚ export circuit bump(): [] { } + + i Safe fix: Rename @return to @returns + + 10 β”‚ - Β·Β·Β·*Β·@returnΒ·{[]}Β·-Β·EmptyΒ·tuple. + 10 β”‚ + Β·Β·Β·*Β·@returnsΒ·{[]}Β·-Β·EmptyΒ·tuple. + +Windows.compact:12:3 lint/missing-constraints FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `bump` doc comment has no @constraints. + + 10 β”‚ * @return {[]} - Empty tuple. + 11 β”‚ */ + > 12 β”‚ export circuit bump(): [] { } + β”‚ ^^^^^^^^^^^^^^^^^^^ + 13 β”‚ } + + i Unsafe fix: Insert @constraints k=?, rows=? + + 10 β”‚ + Β·Β·Β·* + 11 β”‚ + Β·Β·Β·*Β·@constraintsΒ·k=?,Β·rows=? + 12 β”‚ + Β·Β·Β·* + diff --git a/crates/compact-lint/tests/fixtures/fix-crlf/expected.txt b/crates/compact-lint/tests/fixtures/fix-crlf/expected.txt index 994f2b4d..84838b22 100644 --- a/crates/compact-lint/tests/fixtures/fix-crlf/expected.txt +++ b/crates/compact-lint/tests/fixtures/fix-crlf/expected.txt @@ -1,3 +1,29 @@ -Windows.compact:6:3: fix: inserted doc skeleton for ledger `_count` -Windows.compact:10:6: fix: renamed @return to @returns -Windows.compact:12:3: fix: inserted @constraints k=?, rows=? +Windows.compact:6:3 lint/missing-doc FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Ledger `_count` has no doc comment. + + i Applied fix: Insert a doc skeleton for ledger `_count` + + 6 β”‚ + Β·Β·/** + 7 β”‚ + Β·Β·Β·*Β·@descriptionΒ·TODO + 8 β”‚ + Β·Β·Β·*/ + +Windows.compact:10:6 lint/forbidden-tag FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Forbidden tag @return. + + i Applied fix: Rename @return to @returns + + 10 β”‚ - Β·Β·Β·*Β·@returnΒ·{[]}Β·-Β·EmptyΒ·tuple. + 10 β”‚ + Β·Β·Β·*Β·@returnsΒ·{[]}Β·-Β·EmptyΒ·tuple. + +Windows.compact:12:3 lint/missing-constraints FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `bump` doc comment has no @constraints. + + i Applied fix: Insert @constraints k=?, rows=? + + 10 β”‚ + Β·Β·Β·* + 11 β”‚ + Β·Β·Β·*Β·@constraintsΒ·k=?,Β·rows=? + 12 β”‚ + Β·Β·Β·* + diff --git a/crates/compact-lint/tests/fixtures/fix-missing-tag/expected-dry-run.txt b/crates/compact-lint/tests/fixtures/fix-missing-tag/expected-dry-run.txt new file mode 100644 index 00000000..67311e12 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-missing-tag/expected-dry-run.txt @@ -0,0 +1,78 @@ +Untagged.compact:4:1 lint/missing-tag FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Module `Untagged` doc comment has no @description. + + 2 β”‚ * @module Untagged + 3 β”‚ */ + > 4 β”‚ export module Untagged { + β”‚ ^^^^^^^^^^^^^^^^^^^^^^ + 5 β”‚ /** Approved accounts. Absent means not allowed. */ + 6 β”‚ export ledger _allowed: Set>; + + i Unsafe fix: Insert @description + + 3 β”‚ + Β·*Β·@descriptionΒ·TODO + +Untagged.compact:6:3 lint/missing-tag FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Ledger `_allowed` doc comment has no @description. + + 4 β”‚ export module Untagged { + 5 β”‚ /** Approved accounts. Absent means not allowed. */ + > 6 β”‚ export ledger _allowed: Set>; + β”‚ ^^^^^^^^^^^^^^^^^^^^^^ + 7 β”‚ + 8 β”‚ /** + + i Unsafe fix: Insert @description + + 5 β”‚ - Β·Β·/**Β·ApprovedΒ·accounts.Β·AbsentΒ·meansΒ·notΒ·allowed.Β·*/ + 5 β”‚ + Β·Β·/** + 6 β”‚ + Β·Β·Β·*Β·@descriptionΒ·ApprovedΒ·accounts.Β·AbsentΒ·meansΒ·notΒ·allowed. + 7 β”‚ + Β·Β·Β·*/ + +Untagged.compact:12:3 lint/missing-tag FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `run` doc comment has no @description. + + 10 β”‚ * @constraints k=6, rows=28 + 11 β”‚ */ + > 12 β”‚ export circuit run(): [] { } + β”‚ ^^^^^^^^^^^^^^^^^^ + 13 β”‚ + 14 β”‚ /** + + i Unsafe fix: Insert @description + + 9 β”‚ - Β·Β·Β·*Β·TheΒ·circuitΒ·hasΒ·noΒ·descriptionΒ·either. + 9 β”‚ + Β·Β·Β·*Β·@descriptionΒ·TheΒ·circuitΒ·hasΒ·noΒ·descriptionΒ·either. + +Untagged.compact:17:3 lint/missing-constraints FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `store` doc comment has no @constraints. + + 15 β”‚ * @param {Uint<8>} value - The value to store. + 16 β”‚ */ + > 17 β”‚ export circuit store(value: Uint<8>): [] { } + β”‚ ^^^^^^^^^^^^^^^^^^^^ + 18 β”‚ } + + i Unsafe fix: Insert @constraints k=?, rows=? + + 15 β”‚ + Β·Β·Β·*Β·@constraintsΒ·k=?,Β·rows=? + 16 β”‚ + Β·Β·Β·* + +Untagged.compact:17:3 lint/missing-tag FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `store` doc comment has no @description. + + 15 β”‚ * @param {Uint<8>} value - The value to store. + 16 β”‚ */ + > 17 β”‚ export circuit store(value: Uint<8>): [] { } + β”‚ ^^^^^^^^^^^^^^^^^^^^ + 18 β”‚ } + + i Unsafe fix: Insert @description + + 15 β”‚ + Β·Β·Β·*Β·@descriptionΒ·TODO + diff --git a/crates/compact-lint/tests/fixtures/fix-missing-tag/expected.txt b/crates/compact-lint/tests/fixtures/fix-missing-tag/expected.txt index a33b4e22..b3401a1d 100644 --- a/crates/compact-lint/tests/fixtures/fix-missing-tag/expected.txt +++ b/crates/compact-lint/tests/fixtures/fix-missing-tag/expected.txt @@ -1,5 +1,45 @@ -Untagged.compact:4:1: fix: inserted @description -Untagged.compact:6:3: fix: inserted @description -Untagged.compact:12:3: fix: inserted @description -Untagged.compact:17:3: fix: inserted @constraints k=?, rows=? -Untagged.compact:17:3: fix: inserted @description +Untagged.compact:4:1 lint/missing-tag FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Module `Untagged` doc comment has no @description. + + i Applied fix: Insert @description + + 3 β”‚ + Β·*Β·@descriptionΒ·TODO + +Untagged.compact:6:3 lint/missing-tag FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Ledger `_allowed` doc comment has no @description. + + i Applied fix: Insert @description + + 5 β”‚ - Β·Β·/**Β·ApprovedΒ·accounts.Β·AbsentΒ·meansΒ·notΒ·allowed.Β·*/ + 5 β”‚ + Β·Β·/** + 6 β”‚ + Β·Β·Β·*Β·@descriptionΒ·ApprovedΒ·accounts.Β·AbsentΒ·meansΒ·notΒ·allowed. + 7 β”‚ + Β·Β·Β·*/ + +Untagged.compact:12:3 lint/missing-tag FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `run` doc comment has no @description. + + i Applied fix: Insert @description + + 9 β”‚ - Β·Β·Β·*Β·TheΒ·circuitΒ·hasΒ·noΒ·descriptionΒ·either. + 9 β”‚ + Β·Β·Β·*Β·@descriptionΒ·TheΒ·circuitΒ·hasΒ·noΒ·descriptionΒ·either. + +Untagged.compact:17:3 lint/missing-constraints FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `store` doc comment has no @constraints. + + i Applied fix: Insert @constraints k=?, rows=? + + 15 β”‚ + Β·Β·Β·*Β·@constraintsΒ·k=?,Β·rows=? + 16 β”‚ + Β·Β·Β·* + +Untagged.compact:17:3 lint/missing-tag FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `store` doc comment has no @description. + + i Applied fix: Insert @description + + 15 β”‚ + Β·Β·Β·*Β·@descriptionΒ·TODO + diff --git a/crates/compact-lint/tests/fixtures/fix-module-name/expected-dry-run.txt b/crates/compact-lint/tests/fixtures/fix-module-name/expected-dry-run.txt new file mode 100644 index 00000000..85f96fac --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-module-name/expected-dry-run.txt @@ -0,0 +1,31 @@ +Renamed.compact:2:4 lint/module-name FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i @module names `Stale`, but the module is `Renamed`. + + 1 β”‚ /** + > 2 β”‚ * @module Stale (archived) + β”‚ ^^^^^^^ + 3 β”‚ * @description The tag still names the module's old name. + 4 β”‚ */ + + i Safe fix: Set @module to `Renamed` + + 2 β”‚ - Β·*Β·@moduleΒ·StaleΒ·(archived) + 2 β”‚ + Β·*Β·@moduleΒ·RenamedΒ·(archived) + +Renamed.compact:7:6 lint/module-name FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i @module names `Inner`, but the module is `Nested`. + + 5 β”‚ export module Renamed { + 6 β”‚ /** + > 7 β”‚ * @module Inner. + β”‚ ^^^^^^^ + 8 β”‚ * @description The inner tag names nothing that exists. + 9 β”‚ */ + + i Safe fix: Set @module to `Nested` + + 7 β”‚ - Β·Β·Β·*Β·@moduleΒ·Inner. + 7 β”‚ + Β·Β·Β·*Β·@moduleΒ·Nested + diff --git a/crates/compact-lint/tests/fixtures/fix-module-name/expected.txt b/crates/compact-lint/tests/fixtures/fix-module-name/expected.txt index 5e9811ac..f22ed9ff 100644 --- a/crates/compact-lint/tests/fixtures/fix-module-name/expected.txt +++ b/crates/compact-lint/tests/fixtures/fix-module-name/expected.txt @@ -1,2 +1,18 @@ -Renamed.compact:2:4: fix: set @module to `Renamed` -Renamed.compact:7:6: fix: set @module to `Nested` +Renamed.compact:2:4 lint/module-name FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i @module names `Stale`, but the module is `Renamed`. + + i Applied fix: Set @module to `Renamed` + + 2 β”‚ - Β·*Β·@moduleΒ·StaleΒ·(archived) + 2 β”‚ + Β·*Β·@moduleΒ·RenamedΒ·(archived) + +Renamed.compact:7:6 lint/module-name FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i @module names `Inner`, but the module is `Nested`. + + i Applied fix: Set @module to `Nested` + + 7 β”‚ - Β·Β·Β·*Β·@moduleΒ·Inner. + 7 β”‚ + Β·Β·Β·*Β·@moduleΒ·Nested + diff --git a/crates/compact-lint/tests/fixtures/fix-rename/expected-dry-run.txt b/crates/compact-lint/tests/fixtures/fix-rename/expected-dry-run.txt new file mode 100644 index 00000000..786a769b --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-rename/expected-dry-run.txt @@ -0,0 +1,32 @@ +Returns.compact:9:6 lint/forbidden-tag FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Forbidden tag @return. + + 7 β”‚ * @description Does nothing. + 8 β”‚ * @constraints k=6, rows=28 + > 9 β”‚ * @return {[]} - Empty tuple. + β”‚ ^^^^^^^ + 10 β”‚ */ + 11 β”‚ export circuit run(): [] { } + + i Safe fix: Rename @return to @returns + + 9 β”‚ - Β·Β·Β·*Β·@returnΒ·{[]}Β·-Β·EmptyΒ·tuple. + 9 β”‚ + Β·Β·Β·*Β·@returnsΒ·{[]}Β·-Β·EmptyΒ·tuple. + +Returns.compact:15:6 lint/forbidden-tag FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Forbidden tag @return. + + 13 β”‚ /** + 14 β”‚ * @description Not exported, so its docs are optional, but the tag is not. + > 15 β”‚ * @return {[]} - Empty tuple. + β”‚ ^^^^^^^ + 16 β”‚ * @returns {[]} - The new spelling is left alone. + 17 β”‚ */ + + i Safe fix: Rename @return to @returns + + 15 β”‚ - Β·Β·Β·*Β·@returnΒ·{[]}Β·-Β·EmptyΒ·tuple. + 15 β”‚ + Β·Β·Β·*Β·@returnsΒ·{[]}Β·-Β·EmptyΒ·tuple. + diff --git a/crates/compact-lint/tests/fixtures/fix-rename/expected.txt b/crates/compact-lint/tests/fixtures/fix-rename/expected.txt index 50c5c2ad..13a3e1a4 100644 --- a/crates/compact-lint/tests/fixtures/fix-rename/expected.txt +++ b/crates/compact-lint/tests/fixtures/fix-rename/expected.txt @@ -1,2 +1,18 @@ -Returns.compact:9:6: fix: renamed @return to @returns -Returns.compact:15:6: fix: renamed @return to @returns +Returns.compact:9:6 lint/forbidden-tag FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Forbidden tag @return. + + i Applied fix: Rename @return to @returns + + 9 β”‚ - Β·Β·Β·*Β·@returnΒ·{[]}Β·-Β·EmptyΒ·tuple. + 9 β”‚ + Β·Β·Β·*Β·@returnsΒ·{[]}Β·-Β·EmptyΒ·tuple. + +Returns.compact:15:6 lint/forbidden-tag FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Forbidden tag @return. + + i Applied fix: Rename @return to @returns + + 15 β”‚ - Β·Β·Β·*Β·@returnΒ·{[]}Β·-Β·EmptyΒ·tuple. + 15 β”‚ + Β·Β·Β·*Β·@returnsΒ·{[]}Β·-Β·EmptyΒ·tuple. + diff --git a/crates/compact-lint/tests/fixtures/fix-skeleton/expected-dry-run.txt b/crates/compact-lint/tests/fixtures/fix-skeleton/expected-dry-run.txt new file mode 100644 index 00000000..c0b76206 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-skeleton/expected-dry-run.txt @@ -0,0 +1,139 @@ +Bare.compact:3:1 lint/missing-doc FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Module `Bare` has no doc comment. + + 1 β”‚ pragma language_version >= 0.23.0; + 2 β”‚ + > 3 β”‚ export module Bare { + β”‚ ^^^^^^^^^^^^^^^^^^ + 4 β”‚ import CompactStandardLibrary; + 5 β”‚ + + i Unsafe fix: Insert a doc skeleton for module `Bare` + + 3 β”‚ + /** + 4 β”‚ + Β·*Β·@moduleΒ·Bare + 5 β”‚ + Β·*Β·@descriptionΒ·TODO + 6 β”‚ + Β·*/ + +Bare.compact:6:3 lint/missing-doc FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Ledger `_count` has no doc comment. + + 4 β”‚ import CompactStandardLibrary; + 5 β”‚ + > 6 β”‚ export ledger _count: Counter; + β”‚ ^^^^^^^^^^^^^^^^^^^^ + 7 β”‚ + 8 β”‚ witness wit_Secret(): Bytes<32>; + + i Unsafe fix: Insert a doc skeleton for ledger `_count` + + 6 β”‚ + Β·Β·/** + 7 β”‚ + Β·Β·Β·*Β·@descriptionΒ·TODO + 8 β”‚ + Β·Β·Β·*/ + +Bare.compact:8:3 lint/missing-doc FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Witness `wit_Secret` has no doc comment. + + 6 β”‚ export ledger _count: Counter; + 7 β”‚ + > 8 β”‚ witness wit_Secret(): Bytes<32>; + β”‚ ^^^^^^^^^^^^^^^^^^ + 9 β”‚ + 10 β”‚ export struct Reading { + + i Unsafe fix: Insert a doc skeleton for witness `wit_Secret` + + 8 β”‚ + Β·Β·/** + 9 β”‚ + Β·Β·Β·*Β·@descriptionΒ·TODO + 10 β”‚ + Β·Β·Β·*/ + +Bare.compact:10:3 lint/missing-doc FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Struct `Reading` has no doc comment. + + 8 β”‚ witness wit_Secret(): Bytes<32>; + 9 β”‚ + > 10 β”‚ export struct Reading { + β”‚ ^^^^^^^^^^^^^^^^^^^^^ + 11 β”‚ value: Uint<64> + 12 β”‚ } + + i Unsafe fix: Insert a doc skeleton for struct `Reading` + + 10 β”‚ + Β·Β·/** + 11 β”‚ + Β·Β·Β·*Β·@descriptionΒ·TODO + 12 β”‚ + Β·Β·Β·*/ + +Bare.compact:14:3 lint/missing-doc FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Enum `Direction` has no doc comment. + + 12 β”‚ } + 13 β”‚ + > 14 β”‚ export enum Direction { + β”‚ ^^^^^^^^^^^^^^^^^^^^^ + 15 β”‚ Up, + 16 β”‚ Down + + i Unsafe fix: Insert a doc skeleton for enum `Direction` + + 14 β”‚ + Β·Β·/** + 15 β”‚ + Β·Β·Β·*Β·@descriptionΒ·TODO + 16 β”‚ + Β·Β·Β·*/ + +Bare.compact:19:3 lint/missing-doc FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Type `Alias` has no doc comment. + + 17 β”‚ } + 18 β”‚ + > 19 β”‚ export type Alias = Bytes<32>; + β”‚ ^^^^^^^^^^^^^^^^^ + 20 β”‚ + 21 β”‚ constructor() { + + i Unsafe fix: Insert a doc skeleton for type `Alias` + + 19 β”‚ + Β·Β·/** + 20 β”‚ + Β·Β·Β·*Β·TODO + 21 β”‚ + Β·Β·Β·*/ + +Bare.compact:25:3 lint/missing-doc FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `double` has no doc comment. + + 23 β”‚ } + 24 β”‚ + > 25 β”‚ export pure circuit double(value: Uint<8>): Uint<16> { + β”‚ ^^^^^^^^^^^^^^^^^^^^^^^^^^ + 26 β”‚ return value as Uint<16> * 2; + 27 β”‚ } + + i Unsafe fix: Insert a doc skeleton for circuit `double` + + 25 β”‚ + Β·Β·/** + 26 β”‚ + Β·Β·Β·*Β·@descriptionΒ·TODO + 27 β”‚ + Β·Β·Β·*/ + +Bare.compact:29:3 lint/missing-doc FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `bump` has no doc comment. + + 27 β”‚ } + 28 β”‚ + > 29 β”‚ export circuit bump(): [] { + β”‚ ^^^^^^^^^^^^^^^^^^^ + 30 β”‚ _count.increment(1); + 31 β”‚ } + + i Unsafe fix: Insert a doc skeleton for circuit `bump` + + 29 β”‚ + Β·Β·/** + 30 β”‚ + Β·Β·Β·*Β·@descriptionΒ·TODO + 31 β”‚ + Β·Β·Β·* + 32 β”‚ + Β·Β·Β·*Β·@constraintsΒ·k=?,Β·rows=? + 33 β”‚ + Β·Β·Β·*/ + diff --git a/crates/compact-lint/tests/fixtures/fix-skeleton/expected.txt b/crates/compact-lint/tests/fixtures/fix-skeleton/expected.txt index 8dadb68e..f872b5e8 100644 --- a/crates/compact-lint/tests/fixtures/fix-skeleton/expected.txt +++ b/crates/compact-lint/tests/fixtures/fix-skeleton/expected.txt @@ -1,8 +1,83 @@ -Bare.compact:3:1: fix: inserted doc skeleton for module `Bare` -Bare.compact:6:3: fix: inserted doc skeleton for ledger `_count` -Bare.compact:8:3: fix: inserted doc skeleton for witness `wit_Secret` -Bare.compact:10:3: fix: inserted doc skeleton for struct `Reading` -Bare.compact:14:3: fix: inserted doc skeleton for enum `Direction` -Bare.compact:19:3: fix: inserted doc skeleton for type `Alias` -Bare.compact:25:3: fix: inserted doc skeleton for circuit `double` -Bare.compact:29:3: fix: inserted doc skeleton for circuit `bump` +Bare.compact:3:1 lint/missing-doc FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Module `Bare` has no doc comment. + + i Applied fix: Insert a doc skeleton for module `Bare` + + 3 β”‚ + /** + 4 β”‚ + Β·*Β·@moduleΒ·Bare + 5 β”‚ + Β·*Β·@descriptionΒ·TODO + 6 β”‚ + Β·*/ + +Bare.compact:6:3 lint/missing-doc FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Ledger `_count` has no doc comment. + + i Applied fix: Insert a doc skeleton for ledger `_count` + + 6 β”‚ + Β·Β·/** + 7 β”‚ + Β·Β·Β·*Β·@descriptionΒ·TODO + 8 β”‚ + Β·Β·Β·*/ + +Bare.compact:8:3 lint/missing-doc FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Witness `wit_Secret` has no doc comment. + + i Applied fix: Insert a doc skeleton for witness `wit_Secret` + + 8 β”‚ + Β·Β·/** + 9 β”‚ + Β·Β·Β·*Β·@descriptionΒ·TODO + 10 β”‚ + Β·Β·Β·*/ + +Bare.compact:10:3 lint/missing-doc FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Struct `Reading` has no doc comment. + + i Applied fix: Insert a doc skeleton for struct `Reading` + + 10 β”‚ + Β·Β·/** + 11 β”‚ + Β·Β·Β·*Β·@descriptionΒ·TODO + 12 β”‚ + Β·Β·Β·*/ + +Bare.compact:14:3 lint/missing-doc FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Enum `Direction` has no doc comment. + + i Applied fix: Insert a doc skeleton for enum `Direction` + + 14 β”‚ + Β·Β·/** + 15 β”‚ + Β·Β·Β·*Β·@descriptionΒ·TODO + 16 β”‚ + Β·Β·Β·*/ + +Bare.compact:19:3 lint/missing-doc FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Type `Alias` has no doc comment. + + i Applied fix: Insert a doc skeleton for type `Alias` + + 19 β”‚ + Β·Β·/** + 20 β”‚ + Β·Β·Β·*Β·TODO + 21 β”‚ + Β·Β·Β·*/ + +Bare.compact:25:3 lint/missing-doc FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `double` has no doc comment. + + i Applied fix: Insert a doc skeleton for circuit `double` + + 25 β”‚ + Β·Β·/** + 26 β”‚ + Β·Β·Β·*Β·@descriptionΒ·TODO + 27 β”‚ + Β·Β·Β·*/ + +Bare.compact:29:3 lint/missing-doc FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `bump` has no doc comment. + + i Applied fix: Insert a doc skeleton for circuit `bump` + + 29 β”‚ + Β·Β·/** + 30 β”‚ + Β·Β·Β·*Β·@descriptionΒ·TODO + 31 β”‚ + Β·Β·Β·* + 32 β”‚ + Β·Β·Β·*Β·@constraintsΒ·k=?,Β·rows=? + 33 β”‚ + Β·Β·Β·*/ + diff --git a/crates/compact-lint/tests/fixtures/fix-unfixable/expected-dry-run.txt b/crates/compact-lint/tests/fixtures/fix-unfixable/expected-dry-run.txt new file mode 100644 index 00000000..e69de29b diff --git a/crates/compact-lint/tests/fixtures/forbidden-tag/expected.txt b/crates/compact-lint/tests/fixtures/forbidden-tag/expected.txt index 0edaa79e..088a709a 100644 --- a/crates/compact-lint/tests/fixtures/forbidden-tag/expected.txt +++ b/crates/compact-lint/tests/fixtures/forbidden-tag/expected.txt @@ -1,2 +1,26 @@ -Returns.compact:9:6: forbidden-tag: forbidden tag @return -Returns.compact:15:6: forbidden-tag: forbidden tag @return +Returns.compact:9:6 lint/forbidden-tag ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + Γ— Forbidden tag @return. + + 7 β”‚ * @description Does nothing. + 8 β”‚ * @constraints k=6, rows=28 + > 9 β”‚ * @return {[]} - Empty tuple. + β”‚ ^^^^^^^ + 10 β”‚ */ + 11 β”‚ export circuit run(): [] { } + + i Remove it from the doc comment. + +Returns.compact:15:6 lint/forbidden-tag ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + Γ— Forbidden tag @return. + + 13 β”‚ /** + 14 β”‚ * @description Not exported, so its docs are optional, but the tag is not. + > 15 β”‚ * @return {[]} - Empty tuple. + β”‚ ^^^^^^^ + 16 β”‚ */ + 17 β”‚ circuit helper(): [] { } + + i Remove it from the doc comment. + diff --git a/crates/compact-lint/tests/fixtures/max-diagnostics/Many.compact b/crates/compact-lint/tests/fixtures/max-diagnostics/Many.compact new file mode 100644 index 00000000..86ba24aa --- /dev/null +++ b/crates/compact-lint/tests/fixtures/max-diagnostics/Many.compact @@ -0,0 +1,11 @@ +/** + * @module Many + * @description A module with more findings than the cap shows. + */ +export module Many { + export ledger _first: Bytes<32>; + + export ledger _second: Bytes<32>; + + export ledger _third: Bytes<32>; +} diff --git a/crates/compact-lint/tests/fixtures/max-diagnostics/compact-lint.toml b/crates/compact-lint/tests/fixtures/max-diagnostics/compact-lint.toml new file mode 100644 index 00000000..0813e24c --- /dev/null +++ b/crates/compact-lint/tests/fixtures/max-diagnostics/compact-lint.toml @@ -0,0 +1,27 @@ +version = 1 +include = ["**/*.compact"] + +[tags] +forbid = ["@return"] + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] + +[kinds.ledger] +tags = ["@description"] + +[kinds.witness] +docs = "all" +tags = ["@description"] + +[kinds.struct] +tags = ["@description"] + +[kinds.enum] +tags = ["@description"] + +[kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/max-diagnostics/expected.txt b/crates/compact-lint/tests/fixtures/max-diagnostics/expected.txt new file mode 100644 index 00000000..baf2938a --- /dev/null +++ b/crates/compact-lint/tests/fixtures/max-diagnostics/expected.txt @@ -0,0 +1,19 @@ +Many.compact:6:3 lint/missing-doc FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + Γ— Ledger `_first` has no doc comment. + + 4 β”‚ */ + 5 β”‚ export module Many { + > 6 β”‚ export ledger _first: Bytes<32>; + β”‚ ^^^^^^^^^^^^^^^^^^^^ + 7 β”‚ + 8 β”‚ export ledger _second: Bytes<32>; + + i Add a doc comment above it, or run compact-lint fix. + + i Unsafe fix: Insert a doc skeleton for ledger `_first` + + 6 β”‚ + Β·Β·/** + 7 β”‚ + Β·Β·Β·*Β·@descriptionΒ·TODO + 8 β”‚ + Β·Β·Β·*/ + diff --git a/crates/compact-lint/tests/fixtures/missing-constraints/expected.txt b/crates/compact-lint/tests/fixtures/missing-constraints/expected.txt index 18ec6884..d63153ce 100644 --- a/crates/compact-lint/tests/fixtures/missing-constraints/expected.txt +++ b/crates/compact-lint/tests/fixtures/missing-constraints/expected.txt @@ -1 +1,18 @@ -Unmeasured.compact:9:3: missing-constraints: circuit `run` doc comment has no @constraints +Unmeasured.compact:9:3 lint/missing-constraints FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + Γ— Circuit `run` doc comment has no @constraints. + + 7 β”‚ * @description Writes to the ledger without an annotation. + 8 β”‚ */ + > 9 β”‚ export circuit run(): [] { } + β”‚ ^^^^^^^^^^^^^^^^^^ + 10 β”‚ + 11 β”‚ /** + + i Run compact-lint fill-constraints after adding the tag, or add it as @constraints k=?, rows=? to fill later. + + i Unsafe fix: Insert @constraints k=?, rows=? + + 8 β”‚ + Β·Β·Β·* + 9 β”‚ + Β·Β·Β·*Β·@constraintsΒ·k=?,Β·rows=? + diff --git a/crates/compact-lint/tests/fixtures/missing-doc/expected.txt b/crates/compact-lint/tests/fixtures/missing-doc/expected.txt index b3649c78..0230db54 100644 --- a/crates/compact-lint/tests/fixtures/missing-doc/expected.txt +++ b/crates/compact-lint/tests/fixtures/missing-doc/expected.txt @@ -1,3 +1,59 @@ -Gaps.compact:6:3: missing-doc: ledger `_owner` has no doc comment -Gaps.compact:8:3: missing-doc: enum `Kind` has no doc comment -Gaps.compact:17:3: missing-doc: circuit `run` has no doc comment +Gaps.compact:6:3 lint/missing-doc FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + Γ— Ledger `_owner` has no doc comment. + + 4 β”‚ */ + 5 β”‚ export module Gaps { + > 6 β”‚ export ledger _owner: Bytes<32>; + β”‚ ^^^^^^^^^^^^^^^^^^^^ + 7 β”‚ + 8 β”‚ export enum Kind { + + i Add a doc comment above it, or run compact-lint fix. + + i Unsafe fix: Insert a doc skeleton for ledger `_owner` + + 6 β”‚ + Β·Β·/** + 7 β”‚ + Β·Β·Β·*Β·@descriptionΒ·TODO + 8 β”‚ + Β·Β·Β·*/ + +Gaps.compact:8:3 lint/missing-doc FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + Γ— Enum `Kind` has no doc comment. + + 6 β”‚ export ledger _owner: Bytes<32>; + 7 β”‚ + > 8 β”‚ export enum Kind { + β”‚ ^^^^^^^^^^^^^^^^ + 9 β”‚ One + 10 β”‚ } + + i Add a doc comment above it, or run compact-lint fix. + + i Unsafe fix: Insert a doc skeleton for enum `Kind` + + 8 β”‚ + Β·Β·/** + 9 β”‚ + Β·Β·Β·*Β·@descriptionΒ·TODO + 10 β”‚ + Β·Β·Β·*/ + +Gaps.compact:17:3 lint/missing-doc FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + Γ— Circuit `run` has no doc comment. + + 15 β”‚ */ + 16 β”‚ // The comment that breaks the attachment. + > 17 β”‚ export circuit run(): [] { + β”‚ ^^^^^^^^^^^^^^^^^^ + 18 β”‚ _owner = default>; + 19 β”‚ } + + i Add a doc comment above it, or run compact-lint fix. + + i Unsafe fix: Insert a doc skeleton for circuit `run` + + 17 β”‚ + Β·Β·/** + 18 β”‚ + Β·Β·Β·*Β·@descriptionΒ·TODO + 19 β”‚ + Β·Β·Β·* + 20 β”‚ + Β·Β·Β·*Β·@constraintsΒ·k=?,Β·rows=? + 21 β”‚ + Β·Β·Β·*/ + diff --git a/crates/compact-lint/tests/fixtures/missing-tag/expected.txt b/crates/compact-lint/tests/fixtures/missing-tag/expected.txt index 9fb4a3b1..8cf0d4ad 100644 --- a/crates/compact-lint/tests/fixtures/missing-tag/expected.txt +++ b/crates/compact-lint/tests/fixtures/missing-tag/expected.txt @@ -1,2 +1,34 @@ -Untagged.compact:4:1: missing-tag: module `Untagged` doc comment has no @description -Untagged.compact:9:3: missing-tag: circuit `run` doc comment has no @description +Untagged.compact:4:1 lint/missing-tag FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + Γ— Module `Untagged` doc comment has no @description. + + 2 β”‚ * @module Untagged + 3 β”‚ */ + > 4 β”‚ export module Untagged { + β”‚ ^^^^^^^^^^^^^^^^^^^^^^ + 5 β”‚ /** + 6 β”‚ * The module has no @description, and neither has this circuit. + + i Add @description to the doc comment, or run compact-lint fix. + + i Unsafe fix: Insert @description + + 3 β”‚ + Β·*Β·@descriptionΒ·TODO + +Untagged.compact:9:3 lint/missing-tag FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + Γ— Circuit `run` doc comment has no @description. + + 7 β”‚ * @constraints k=6, rows=28 + 8 β”‚ */ + > 9 β”‚ export circuit run(): [] { } + β”‚ ^^^^^^^^^^^^^^^^^^ + 10 β”‚ } + + i Add @description to the doc comment, or run compact-lint fix. + + i Unsafe fix: Insert @description + + 6 β”‚ - Β·Β·Β·*Β·TheΒ·moduleΒ·hasΒ·noΒ·@description,Β·andΒ·neitherΒ·hasΒ·thisΒ·circuit. + 6 β”‚ + Β·Β·Β·*Β·@descriptionΒ·TheΒ·moduleΒ·hasΒ·noΒ·@description,Β·andΒ·neitherΒ·hasΒ·thisΒ·circuit. + diff --git a/crates/compact-lint/tests/fixtures/module-name/expected.txt b/crates/compact-lint/tests/fixtures/module-name/expected.txt index 6d31a1ce..8370e2ff 100644 --- a/crates/compact-lint/tests/fixtures/module-name/expected.txt +++ b/crates/compact-lint/tests/fixtures/module-name/expected.txt @@ -1 +1,17 @@ -Renamed.compact:2:4: module-name: @module names `Stale`, but the module is `Renamed` +Renamed.compact:2:4 lint/module-name FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + Γ— @module names `Stale`, but the module is `Renamed`. + + 1 β”‚ /** + > 2 β”‚ * @module Stale + β”‚ ^^^^^^^ + 3 β”‚ * @description The tag still names the module's old name. + 4 β”‚ */ + + i Set the tag to Renamed, or run compact-lint fix. + + i Safe fix: Set @module to `Renamed` + + 2 β”‚ - Β·*Β·@moduleΒ·Stale + 2 β”‚ + Β·*Β·@moduleΒ·Renamed + diff --git a/crates/compact-lint/tests/fixtures/parse/expected.txt b/crates/compact-lint/tests/fixtures/parse/expected.txt index b50d9d70..0035b682 100644 --- a/crates/compact-lint/tests/fixtures/parse/expected.txt +++ b/crates/compact-lint/tests/fixtures/parse/expected.txt @@ -1 +1,11 @@ -Broken.compact:2:3: parse: parse error: unexpected ERROR +Broken.compact:2:3 parse ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + Γ— Parse error: unexpected ERROR. + + 1 β”‚ export module Broken { + > 2 β”‚ export circuit + β”‚ ^^^^^^^^^^^^^^ + 3 β”‚ } + + i Fix the syntax error; the doc rules are skipped for this file. + diff --git a/crates/compact-lint/tests/fixtures/reporter-concise/Two.compact b/crates/compact-lint/tests/fixtures/reporter-concise/Two.compact new file mode 100644 index 00000000..4ff04b68 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/reporter-concise/Two.compact @@ -0,0 +1,16 @@ +/** + * @module Two + * @description A module with one finding of each level. + */ +export module Two { + /** + * @description Not measured yet. + * @constraints k=?, rows=? + */ + export circuit run(): [] { } + + /** + * @description Unannotated. + */ + export circuit bump(): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/reporter-concise/compact-lint.toml b/crates/compact-lint/tests/fixtures/reporter-concise/compact-lint.toml new file mode 100644 index 00000000..0813e24c --- /dev/null +++ b/crates/compact-lint/tests/fixtures/reporter-concise/compact-lint.toml @@ -0,0 +1,27 @@ +version = 1 +include = ["**/*.compact"] + +[tags] +forbid = ["@return"] + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] + +[kinds.ledger] +tags = ["@description"] + +[kinds.witness] +docs = "all" +tags = ["@description"] + +[kinds.struct] +tags = ["@description"] + +[kinds.enum] +tags = ["@description"] + +[kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/reporter-concise/expected.txt b/crates/compact-lint/tests/fixtures/reporter-concise/expected.txt new file mode 100644 index 00000000..fb70c75d --- /dev/null +++ b/crates/compact-lint/tests/fixtures/reporter-concise/expected.txt @@ -0,0 +1,2 @@ +! Two.compact:8:6: lint/constraints-placeholder: @constraints value `k=?, rows=?` still holds a placeholder. +Γ— Two.compact:15:3: lint/missing-constraints: Circuit `bump` doc comment has no @constraints. diff --git a/crates/compact-lint/tests/fixtures/reporter-github/Two.compact b/crates/compact-lint/tests/fixtures/reporter-github/Two.compact new file mode 100644 index 00000000..4ff04b68 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/reporter-github/Two.compact @@ -0,0 +1,16 @@ +/** + * @module Two + * @description A module with one finding of each level. + */ +export module Two { + /** + * @description Not measured yet. + * @constraints k=?, rows=? + */ + export circuit run(): [] { } + + /** + * @description Unannotated. + */ + export circuit bump(): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/reporter-github/compact-lint.toml b/crates/compact-lint/tests/fixtures/reporter-github/compact-lint.toml new file mode 100644 index 00000000..0813e24c --- /dev/null +++ b/crates/compact-lint/tests/fixtures/reporter-github/compact-lint.toml @@ -0,0 +1,27 @@ +version = 1 +include = ["**/*.compact"] + +[tags] +forbid = ["@return"] + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] + +[kinds.ledger] +tags = ["@description"] + +[kinds.witness] +docs = "all" +tags = ["@description"] + +[kinds.struct] +tags = ["@description"] + +[kinds.enum] +tags = ["@description"] + +[kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/reporter-github/expected.txt b/crates/compact-lint/tests/fixtures/reporter-github/expected.txt new file mode 100644 index 00000000..f56af505 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/reporter-github/expected.txt @@ -0,0 +1,2 @@ +::warning title=lint/constraints-placeholder,file=Two.compact,line=8,endLine=8,col=6,endColumn=18::@constraints value `k=?, rows=?` still holds a placeholder. +::error title=lint/missing-constraints,file=Two.compact,line=15,endLine=15,col=3,endColumn=22::Circuit `bump` doc comment has no @constraints. diff --git a/crates/compact-lint/tests/fixtures/rules-levels/Levels.compact b/crates/compact-lint/tests/fixtures/rules-levels/Levels.compact new file mode 100644 index 00000000..eda738ab --- /dev/null +++ b/crates/compact-lint/tests/fixtures/rules-levels/Levels.compact @@ -0,0 +1,14 @@ +/** + * @module Levels + * @description A module whose rules are set to other levels. + */ +export module Levels { + export ledger _owner: Bytes<32>; + + /** + * @description Does nothing. + * @constraints k=6, rows=28 + * @return {[]} - Empty tuple. + */ + export circuit run(): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/rules-levels/compact-lint.toml b/crates/compact-lint/tests/fixtures/rules-levels/compact-lint.toml new file mode 100644 index 00000000..46228303 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/rules-levels/compact-lint.toml @@ -0,0 +1,32 @@ +version = 1 +include = ["**/*.compact"] + +[tags] +forbid = ["@return"] +rename = { "@return" = "@returns" } + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] + +[kinds.ledger] +tags = ["@description"] + +[kinds.witness] +docs = "all" +tags = ["@description"] + +[kinds.struct] +tags = ["@description"] + +[kinds.enum] +tags = ["@description"] + +[kinds.constructor] +docs = "none" + +[rules] +missing-doc = "off" +forbidden-tag = "warn" diff --git a/crates/compact-lint/tests/fixtures/rules-levels/expected.txt b/crates/compact-lint/tests/fixtures/rules-levels/expected.txt new file mode 100644 index 00000000..c88533c0 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/rules-levels/expected.txt @@ -0,0 +1,18 @@ +Levels.compact:11:6 lint/forbidden-tag FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + ! Forbidden tag @return. + + 9 β”‚ * @description Does nothing. + 10 β”‚ * @constraints k=6, rows=28 + > 11 β”‚ * @return {[]} - Empty tuple. + β”‚ ^^^^^^^ + 12 β”‚ */ + 13 β”‚ export circuit run(): [] { } + + i Rename it to @returns. + + i Safe fix: Rename @return to @returns + + 11 β”‚ - Β·Β·Β·*Β·@returnΒ·{[]}Β·-Β·EmptyΒ·tuple. + 11 β”‚ + Β·Β·Β·*Β·@returnsΒ·{[]}Β·-Β·EmptyΒ·tuple. + From 3f722cb9043e6494d8f025df42cb0e57ca0ce8b0 Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Tue, 15 Sep 2026 16:45:15 +0200 Subject: [PATCH 11/56] refactor(compact-lint): read the [lint] table of compact.toml One project, one config file. compact-deploy already owns `compact.toml`, so the linter moves its settings under a `[lint]` table there and `compact-lint.toml` goes away before anything ships. * The linter parses the whole document but deserialises only `lint`; every other table is another tool's and is ignored. A file with no `[lint]` table is a config error, no file at all keeps the built-in defaults. * The `version` key is dropped: tables are namespaced per tool and the deployer's file has none either. * A deployer test pins that its loader strips the `[lint]` table, so the two tools keep sharing the file without a schema change. --- crates/compact-lint/README.md | 53 +++++---- .../{compact-contracts.toml => compact.toml} | 32 +++--- crates/compact-lint/src/config.rs | 108 ++++++++++++------ crates/compact-lint/src/lib.rs | 4 +- crates/compact-lint/src/main.rs | 8 +- crates/compact-lint/tests/check.rs | 12 +- crates/compact-lint/tests/fill.rs | 4 +- crates/compact-lint/tests/fix.rs | 10 +- .../tests/fixtures/clean/compact.toml | 42 +++++++ .../compact.toml} | 18 +-- .../compact.toml} | 18 +-- .../compact.toml} | 18 +-- .../error-on-warnings/compact-lint.toml | 27 ----- .../compact.toml} | 18 +-- .../{compact-lint.toml => compact.toml} | 6 +- .../{compact-lint.toml => compact.toml} | 6 +- .../{compact-lint.toml => compact.toml} | 6 +- .../{compact-lint.toml => compact.toml} | 6 +- .../{compact-lint.toml => compact.toml} | 8 +- .../{compact-lint.toml => compact.toml} | 8 +- .../{compact-lint.toml => compact.toml} | 10 +- .../{compact-lint.toml => compact.toml} | 12 +- .../{compact-lint.toml => compact.toml} | 10 +- .../{compact-lint.toml => compact.toml} | 6 +- .../{compact-lint.toml => compact.toml} | 10 +- .../{compact-lint.toml => compact.toml} | 20 ++-- .../{compact-lint.toml => compact.toml} | 10 +- .../fixtures/forbidden-tag/compact-lint.toml | 27 ----- .../tests/fixtures/forbidden-tag/compact.toml | 27 +++++ .../max-diagnostics/compact-lint.toml | 27 ----- .../fixtures/max-diagnostics/compact.toml | 27 +++++ .../missing-constraints/compact-lint.toml | 27 ----- .../fixtures/missing-constraints/compact.toml | 27 +++++ .../fixtures/missing-doc/compact-lint.toml | 27 ----- .../tests/fixtures/missing-doc/compact.toml | 27 +++++ .../fixtures/missing-tag/compact-lint.toml | 27 ----- .../tests/fixtures/missing-tag/compact.toml | 27 +++++ .../fixtures/module-name/compact-lint.toml | 27 ----- .../tests/fixtures/module-name/compact.toml | 27 +++++ .../tests/fixtures/no-lint-table/compact.toml | 14 +++ .../parse/{compact-lint.toml => compact.toml} | 2 +- .../reporter-concise/compact-lint.toml | 27 ----- .../fixtures/reporter-concise/compact.toml | 27 +++++ .../reporter-github/compact-lint.toml | 27 ----- .../fixtures/reporter-github/compact.toml | 27 +++++ .../{compact-lint.toml => compact.toml} | 20 ++-- examples/fungible-token/compact.toml | 2 + .../src/config/compact-config.test.ts | 18 +++ packages/linter/README.md | 5 +- 49 files changed, 549 insertions(+), 434 deletions(-) rename crates/compact-lint/examples/{compact-contracts.toml => compact.toml} (70%) create mode 100644 crates/compact-lint/tests/fixtures/clean/compact.toml rename crates/compact-lint/tests/fixtures/{diagnostic-level/compact-lint.toml => constraints-format/compact.toml} (59%) rename crates/compact-lint/tests/fixtures/{clean/compact-lint.toml => constraints-placeholder/compact.toml} (59%) rename crates/compact-lint/tests/fixtures/{constraints-format/compact-lint.toml => diagnostic-level/compact.toml} (59%) delete mode 100644 crates/compact-lint/tests/fixtures/error-on-warnings/compact-lint.toml rename crates/compact-lint/tests/fixtures/{constraints-placeholder/compact-lint.toml => error-on-warnings/compact.toml} (59%) rename crates/compact-lint/tests/fixtures/fill-basic/{compact-lint.toml => compact.toml} (65%) rename crates/compact-lint/tests/fixtures/fill-compiler-fails/{compact-lint.toml => compact.toml} (65%) rename crates/compact-lint/tests/fixtures/fill-missing-source/{compact-lint.toml => compact.toml} (55%) rename crates/compact-lint/tests/fixtures/fill-no-compile/{compact-lint.toml => compact.toml} (65%) rename crates/compact-lint/tests/fixtures/fill-override/{compact-lint.toml => compact.toml} (68%) rename crates/compact-lint/tests/fixtures/fill-self/{compact-lint.toml => compact.toml} (56%) rename crates/compact-lint/tests/fixtures/fix-constraints/{compact-lint.toml => compact.toml} (52%) rename crates/compact-lint/tests/fixtures/fix-crlf/{compact-lint.toml => compact.toml} (63%) rename crates/compact-lint/tests/fixtures/fix-missing-tag/{compact-lint.toml => compact.toml} (57%) rename crates/compact-lint/tests/fixtures/fix-module-name/{compact-lint.toml => compact.toml} (60%) rename crates/compact-lint/tests/fixtures/fix-rename/{compact-lint.toml => compact.toml} (65%) rename crates/compact-lint/tests/fixtures/fix-skeleton/{compact-lint.toml => compact.toml} (62%) rename crates/compact-lint/tests/fixtures/fix-unfixable/{compact-lint.toml => compact.toml} (70%) delete mode 100644 crates/compact-lint/tests/fixtures/forbidden-tag/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/forbidden-tag/compact.toml delete mode 100644 crates/compact-lint/tests/fixtures/max-diagnostics/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/max-diagnostics/compact.toml delete mode 100644 crates/compact-lint/tests/fixtures/missing-constraints/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/missing-constraints/compact.toml delete mode 100644 crates/compact-lint/tests/fixtures/missing-doc/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/missing-doc/compact.toml delete mode 100644 crates/compact-lint/tests/fixtures/missing-tag/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/missing-tag/compact.toml delete mode 100644 crates/compact-lint/tests/fixtures/module-name/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/module-name/compact.toml create mode 100644 crates/compact-lint/tests/fixtures/no-lint-table/compact.toml rename crates/compact-lint/tests/fixtures/parse/{compact-lint.toml => compact.toml} (69%) delete mode 100644 crates/compact-lint/tests/fixtures/reporter-concise/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/reporter-concise/compact.toml delete mode 100644 crates/compact-lint/tests/fixtures/reporter-github/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/reporter-github/compact.toml rename crates/compact-lint/tests/fixtures/rules-levels/{compact-lint.toml => compact.toml} (64%) diff --git a/crates/compact-lint/README.md b/crates/compact-lint/README.md index b562ca59..813808c9 100644 --- a/crates/compact-lint/README.md +++ b/crates/compact-lint/README.md @@ -2,7 +2,7 @@ Doc-comment linter for Compact sources. It parses `.compact` files with [`compact-tree-sitter`](../compact-tree-sitter), matches every declaration against the -per-kind template in `compact-lint.toml`, and prints one diagnostic per violation. `fix` +per-kind template in `compact.toml`, and prints one diagnostic per violation. `fix` rewrites the comments the repairable rules report. `fill-constraints` compiles the contracts and writes the measured `k` and `rows` into the annotations. @@ -25,11 +25,11 @@ compact-lint fill-constraints [PATHS]... [--config ] [--dry-run] [--no-com walking: `node_modules`, `target`, `dist`, `build`, `.git`. - No `PATHS` β€” the config's `include` globs are used instead. - `--config ` β€” use this config instead of searching upward for - `compact-lint.toml`. + `compact.toml`. - `--strict` β€” report `k=?` / `rows=?` placeholders as errors instead of warnings. Use it on release branches. - `--no-format` β€” skip the `compact format --check` pass. Required where the `compact` - binary is unavailable, CI included. Same effect as `format = "off"` in `[rules]`. + binary is unavailable, CI included. Same effect as `format = "off"` in `[lint.rules]`. - `--compact-bin ` β€” path to the `compact` binary. Also settable with `COMPACT_LINT_COMPACT_BIN`; the flag wins. @@ -89,10 +89,10 @@ Found 3 errors. - Every rule reports at a level: `error`, `warn`, `info`, or `off`. - `off` stops the rule running; its findings never reach the report or the counts. -- Set them in `[rules]`, keyed by rule id: +- Set them in `[lint.rules]`, keyed by rule id: ```toml -[rules] +[lint.rules] missing-doc = "error" constraints-placeholder = "warn" format = "off" @@ -110,7 +110,7 @@ Defaults: - `--strict` promotes `constraints-placeholder` to `error` for that run; a rule set to `off` stays off. -- An unknown key in `[rules]` is a config error. +- An unknown key in `[lint.rules]` is a config error. ## Exit codes @@ -300,36 +300,45 @@ Rule detail: ## Config -`compact-lint.toml`, searched for upward from the current directory. Every field is -optional; unknown fields are rejected. A config found by walking upward anchors the -`include` globs at its own directory; a config named with `--config` is a shareable -preset, so the globs stay anchored at the current directory. +`compact.toml`, searched for upward from the current directory. The linter reads its +`[lint]` table; every key below is a key of that table. + +- The file is shared with [`compact-deploy`](../../packages/deployer), which owns + `[profile]`, `[networks.*]`, `[wallet]` and `[contracts.*]` in the same file. +- Tables the linter does not own are ignored, so a deployer-only key is never a lint + error. +- Every field under `[lint]` is optional; an unknown one is rejected. +- A `compact.toml` with no `[lint]` table is a config error, exit `2`. No `compact.toml` + anywhere up the tree is not: the run uses the built-in defaults. +- A config found by walking upward anchors the `include` globs at its own directory; a + config named with `--config` is a shareable preset, so the globs stay anchored at the + current directory. ```toml -version = 1 +[lint] include = ["contracts/src/**/*.compact"] exclude = ["**/test/mocks/**", "**/archive/**"] -[constraints] +[lint.constraints] tag = "@constraints" compiler = "0.34.0" sources = ["{dir}/test/mocks/Mock{stem}.compact", "{parent}/test/mocks/Mock{stem}.compact"] self = ["**/presets/**"] -[constraints.overrides] +[lint.constraints.overrides] "contracts/src/utils/Utils.compact" = "contracts/src/utils/test/mocks/MockUtils.compact" -[tags] +[lint.tags] forbid = ["@return"] rename = { "@return" = "@returns" } -[fix] +[lint.fix] placeholder = "TODO" -[rules] +[lint.rules] constraints-placeholder = "warn" -[kinds.module] +[lint.kinds.module] docs = "exported" tags = ["@module", "@description"] ``` @@ -338,7 +347,6 @@ Defaults when no config file is found: | Key | Default | | --- | --- | -| `version` | `1`, the only version this build accepts | | `include` | `["**/*.compact"]` | | `exclude` | `[]` | | `constraints.tag` | `"@constraints"` | @@ -372,7 +380,7 @@ Defaults when no config file is found: - `constraints.overrides` keys and values are paths relative to the config's directory, or to the current directory when the config came from `--config`. -`examples/compact-contracts.toml` is the config for OpenZeppelin/compact-contracts. +`examples/compact.toml` is the config for OpenZeppelin/compact-contracts. ## Doc-comment model @@ -390,11 +398,12 @@ cargo test --workspace ``` `tests/fixtures//` holds one `check` case per rule plus a clean case: a -`compact-lint.toml`, the `.compact` sources, and `expected.txt`, the exact stdout with +`compact.toml`, the `.compact` sources, and `expected.txt`, the exact stdout with paths relative to the case directory. A case that also runs under a flag carries the -second expectation beside it, such as `expected-strict.txt`. +second expectation beside it, such as `expected-strict.txt`. The `clean` case carries +the deployer's tables too, and `no-lint-table` carries nothing else. -`tests/fixtures/fix-/` holds one `fix` case per rule: a `compact-lint.toml`, +`tests/fixtures/fix-/` holds one `fix` case per rule: a `compact.toml`, `before/`, `after/`, `expected.txt` for the write run and `expected-dry-run.txt` for the preview. The run copies `before/` into a temporary directory, so the fixtures are never rewritten in place. diff --git a/crates/compact-lint/examples/compact-contracts.toml b/crates/compact-lint/examples/compact.toml similarity index 70% rename from crates/compact-lint/examples/compact-contracts.toml rename to crates/compact-lint/examples/compact.toml index 6667f2a2..9cf5ef5f 100644 --- a/crates/compact-lint/examples/compact-contracts.toml +++ b/crates/compact-lint/examples/compact.toml @@ -1,25 +1,29 @@ # compact-lint config for OpenZeppelin/compact-contracts. -# Copy it to the repository root as compact-lint.toml. +# Copy it to the repository root as compact.toml. +# +# One project, one config file. compact-deploy's `[profile]`, `[networks.*]`, +# `[wallet]` and `[contracts.*]` tables live in this same file and the linter +# ignores them; see examples/fungible-token/compact.toml for their shape. -version = 1 +[lint] include = ["contracts/src/**/*.compact"] exclude = ["**/test/mocks/**", "**/archive/**"] # `@constraints` is the default; set `tag` to point the rule at another annotation. -[constraints] +[lint.constraints] tag = "@constraints" # Presets are contracts, so fill-constraints compiles them directly. Everything else is # measured through the mock beside it or in its parent, the default `sources` templates. self = ["**/presets/**"] -[tags] +[lint.tags] forbid = ["@return"] rename = { "@return" = "@returns" } # Every rule's default level, spelled out. Set one to "off" to stop it running, or to # "warn" / "info" to keep it out of the exit code. `check --strict` promotes # constraints-placeholder to "error" for that run. -# [rules] +# [lint.rules] # missing-doc = "error" # missing-tag = "error" # forbidden-tag = "error" @@ -32,29 +36,29 @@ rename = { "@return" = "@returns" } # parse = "error" # format = "error" -[kinds.module] +[lint.kinds.module] docs = "exported" tags = ["@module", "@description"] -[kinds.circuit] +[lint.kinds.circuit] tags = ["@description"] -[kinds.ledger] +[lint.kinds.ledger] tags = ["@description"] -[kinds.witness] +[lint.kinds.witness] docs = "all" tags = ["@description"] -[kinds.struct] +[lint.kinds.struct] tags = ["@description"] -[kinds.enum] +[lint.kinds.enum] tags = ["@description"] -[kinds.constructor] +[lint.kinds.constructor] docs = "none" -[kinds.contract] +[lint.kinds.contract] -[kinds.type] +[lint.kinds.type] diff --git a/crates/compact-lint/src/config.rs b/crates/compact-lint/src/config.rs index 46d69314..88dc6436 100644 --- a/crates/compact-lint/src/config.rs +++ b/crates/compact-lint/src/config.rs @@ -1,4 +1,7 @@ -//! `compact-lint.toml`: discovery, parsing, and the built-in defaults. +//! `compact.toml`: discovery, parsing, and the built-in defaults. +//! +//! The file is shared with `compact-deploy`. The linter reads its `[lint]` table and +//! ignores every other one. use std::collections::BTreeMap; use std::path::{Path, PathBuf}; @@ -13,10 +16,7 @@ use crate::model::DeclKind; use crate::report::RuleId; /// The config file name searched for upward from the current directory. -pub const CONFIG_FILE_NAME: &str = "compact-lint.toml"; - -/// The only schema version this build understands. -pub const SUPPORTED_VERSION: u32 = 1; +pub const CONFIG_FILE_NAME: &str = "compact.toml"; #[derive(Debug, Error)] pub enum ConfigError { @@ -32,10 +32,8 @@ pub enum ConfigError { #[source] source: toml::de::Error, }, - #[error( - "config {path} is version {found}, but this build understands version {SUPPORTED_VERSION}" - )] - Version { path: PathBuf, found: u32 }, + #[error("{CONFIG_FILE_NAME} at {path} has no [lint] table")] + MissingLintTable { path: PathBuf }, #[error( "config {path} lists tag {tag:?}; tags are spelled with their `@`, like `@description`" )] @@ -236,11 +234,17 @@ impl Default for FixConfig { } } -/// A parsed `compact-lint.toml`, or the built-in defaults when no file was found. +/// The whole `compact.toml`. Tables other tools own are ignored, so the root rejects +/// nothing. +#[derive(Debug, Default, Deserialize)] +struct Document { + lint: Option, +} + +/// A parsed `[lint]` table, or the built-in defaults when no file was found. #[derive(Clone, Debug, Deserialize, PartialEq, Eq)] #[serde(deny_unknown_fields, default)] pub struct Config { - pub version: u32, pub include: Vec, pub exclude: Vec, pub constraints: ConstraintsConfig, @@ -253,7 +257,6 @@ pub struct Config { impl Default for Config { fn default() -> Self { Self { - version: SUPPORTED_VERSION, include: vec!["**/*.compact".to_owned()], exclude: Vec::new(), constraints: ConstraintsConfig::default(), @@ -266,26 +269,24 @@ impl Default for Config { } impl Config { - /// Parses a config file and rejects a version this build does not implement. + /// Parses a config file's `[lint]` table. /// # Errors - /// Returns an error when the file is unreadable, malformed, or a future version. + /// Returns an error when the file is unreadable or malformed, or carries no `[lint]` + /// table. pub fn load(path: &Path) -> Result { let text = std::fs::read_to_string(path).map_err(|source| ConfigError::Read { path: path.to_owned(), source, })?; - let config: Self = toml::from_str(&text).map_err(|source| ConfigError::Parse { + let document: Document = toml::from_str(&text).map_err(|source| ConfigError::Parse { path: path.to_owned(), source, })?; - if config.version != SUPPORTED_VERSION { - return Err(ConfigError::Version { - path: path.to_owned(), - found: config.version, - }); - } + let config = document.lint.ok_or_else(|| ConfigError::MissingLintTable { + path: path.to_owned(), + })?; if let Some(tag) = config.tags().find(|tag| !tag.is_well_formed()) { return Err(ConfigError::Tag { @@ -365,7 +366,7 @@ fn glob_set(patterns: &[String], path: &Path) -> Result { }) } -/// Walks up from `start` looking for `compact-lint.toml`. +/// Walks up from `start` looking for `compact.toml`. #[must_use] pub fn discover(start: &Path) -> Option { for directory in start.ancestors() { @@ -379,7 +380,7 @@ pub fn discover(start: &Path) -> Option { #[cfg(test)] mod tests { - use super::{Config, DocsPolicy, SUPPORTED_VERSION}; + use super::{Config, DocsPolicy}; use crate::diagnostic::Level; use crate::doc::Tag; use crate::model::DeclKind; @@ -419,7 +420,6 @@ mod tests { fn defaults_require_docs_on_exported_declarations_only() { let config = Config::default(); - assert_eq!(config.version, SUPPORTED_VERSION); assert_eq!(config.constraints.tag, Tag::new("@constraints")); for kind in [DeclKind::Module, DeclKind::Circuit, DeclKind::Type] { assert_eq!(config.kinds.get(kind).docs, DocsPolicy::Exported); @@ -429,7 +429,7 @@ mod tests { #[test] fn omitted_tables_fall_back_to_defaults() { - let config: Config = toml::from_str("version = 1\n[kinds.witness]\ndocs = \"all\"\n") + let config: Config = toml::from_str("[kinds.witness]\ndocs = \"all\"\n") .expect("the snippet is valid config"); assert_eq!(config.kinds.witness.docs, DocsPolicy::All); @@ -439,17 +439,17 @@ mod tests { #[test] fn an_unknown_key_is_rejected() { - let error = toml::from_str::("verison = 1\n").expect_err("the key is misspelled"); + let error = toml::from_str::("inclued = []\n").expect_err("the key is misspelled"); - assert!(error.to_string().contains("verison"), "{error}"); + assert!(error.to_string().contains("inclued"), "{error}"); } #[test] fn a_tag_without_its_at_sign_is_rejected() { let dir = std::env::temp_dir().join(format!("compact-lint-config-{}", std::process::id())); std::fs::create_dir_all(&dir).expect("the temp dir is writable"); - let path = dir.join("compact-lint.toml"); - std::fs::write(&path, "[kinds.circuit]\ntags = [\"description\"]\n") + let path = dir.join("compact.toml"); + std::fs::write(&path, "[lint.kinds.circuit]\ntags = [\"description\"]\n") .expect("the config is writable"); let error = Config::load(&path).expect_err("the tag lacks its @"); @@ -476,9 +476,12 @@ mod tests { fn a_rename_target_without_its_at_sign_is_rejected() { let dir = std::env::temp_dir().join(format!("compact-lint-rename-{}", std::process::id())); std::fs::create_dir_all(&dir).expect("the temp dir is writable"); - let path = dir.join("compact-lint.toml"); - std::fs::write(&path, "[tags]\nrename = { \"@return\" = \"returns\" }\n") - .expect("the config is writable"); + let path = dir.join("compact.toml"); + std::fs::write( + &path, + "[lint.tags]\nrename = { \"@return\" = \"returns\" }\n", + ) + .expect("the config is writable"); let error = Config::load(&path).expect_err("the replacement lacks its @"); @@ -540,4 +543,45 @@ mod tests { assert!(error.to_string().contains("circiut"), "{error}"); } + + /// Writes `text` to a `compact.toml` of its own and returns what `load` made of it. + fn load_document(name: &str, text: &str) -> Result { + let dir = std::env::temp_dir().join(format!("compact-lint-{name}-{}", std::process::id())); + std::fs::create_dir_all(&dir).expect("the temp dir is writable"); + let path = dir.join("compact.toml"); + std::fs::write(&path, text).expect("the config is writable"); + + let loaded = Config::load(&path); + + std::fs::remove_dir_all(&dir).expect("the temp dir is removable"); + loaded + } + + #[test] + fn tables_another_tool_owns_are_ignored() { + let config = load_document( + "foreign", + "[profile]\ndefault_network = \"local\"\n\n[lint]\ninclude = [\"src/**/*.compact\"]\n", + ) + .expect("the deployer's tables are not the linter's business"); + + assert_eq!(config.include, ["src/**/*.compact"]); + } + + #[test] + fn a_file_without_a_lint_table_is_an_error() { + let error = load_document("no-lint", "[profile]\ndefault_network = \"local\"\n") + .expect_err("the file carries no [lint] table"); + + assert!(error.to_string().contains("has no [lint] table"), "{error}"); + } + + #[test] + fn a_typo_under_the_lint_table_is_still_rejected() { + let error = load_document("lint-typo", "[lint]\ninclued = []\n") + .expect_err("the key is misspelled"); + let source = std::error::Error::source(&error).expect("the parser named the key"); + + assert!(source.to_string().contains("inclued"), "{source}"); + } } diff --git a/crates/compact-lint/src/lib.rs b/crates/compact-lint/src/lib.rs index 1dd7e4b0..c7302b04 100644 --- a/crates/compact-lint/src/lib.rs +++ b/crates/compact-lint/src/lib.rs @@ -1,8 +1,8 @@ //! Doc-comment linter for Compact sources. //! //! The crate parses `.compact` files with the bundled tree-sitter grammar, matches each -//! declaration against the per-kind doc-comment template in `compact-lint.toml`, and -//! yields one [`rules::Issue`] per violation. `check` renders an issue as a +//! declaration against the per-kind doc-comment template in `compact.toml`'s `[lint]` +//! table, and yields one [`rules::Issue`] per violation. `check` renders an issue as a //! [`diagnostic::Diagnostic`]; `fix` renders the repairable ones as an [`edit::Edit`]. //! `fill-constraints` takes the other path: [`measure`] compiles a contract and //! [`fill`] writes the measured values into the annotations that already exist. diff --git a/crates/compact-lint/src/main.rs b/crates/compact-lint/src/main.rs index 0d8ddba3..c3f4949c 100644 --- a/crates/compact-lint/src/main.rs +++ b/crates/compact-lint/src/main.rs @@ -40,7 +40,7 @@ struct Cli { #[derive(Debug, Subcommand)] enum Command { - /// Check doc comments against the per-kind templates in compact-lint.toml. + /// Check doc comments against the per-kind templates in compact.toml's [lint] table. Check(CheckArgs), /// Rewrite doc comments so the rules `fix` covers stop reporting. Fix(FixArgs), @@ -127,7 +127,7 @@ struct CheckArgs { /// Files or directories to check; defaults to the config's include globs. paths: Vec, - /// Config file to use instead of searching upward for compact-lint.toml. + /// Config file to use instead of searching upward for compact.toml. #[arg(long, value_name = "FILE")] config: Option, @@ -152,7 +152,7 @@ struct FixArgs { /// Files or directories to fix; defaults to the config's include globs. paths: Vec, - /// Config file to use instead of searching upward for compact-lint.toml. + /// Config file to use instead of searching upward for compact.toml. #[arg(long, value_name = "FILE")] config: Option, @@ -169,7 +169,7 @@ struct FillArgs { /// Files or directories to fill; defaults to the config's include globs. paths: Vec, - /// Config file to use instead of searching upward for compact-lint.toml. + /// Config file to use instead of searching upward for compact.toml. #[arg(long, value_name = "FILE")] config: Option, diff --git a/crates/compact-lint/tests/check.rs b/crates/compact-lint/tests/check.rs index ff96c607..230d6561 100644 --- a/crates/compact-lint/tests/check.rs +++ b/crates/compact-lint/tests/check.rs @@ -228,7 +228,7 @@ fn an_explicit_path_replaces_the_include_globs() { #[test] fn an_explicit_config_anchors_discovery_at_the_working_directory() { - let config = case("clean").join("compact-lint.toml"); + let config = case("clean").join("compact.toml"); let output = binary() .current_dir(case("missing-doc")) .args(["check", "--no-format", "--colors=off", "--config"]) @@ -255,11 +255,19 @@ fn a_missing_compact_binary_exits_two_and_names_the_escape_hatch() { assert!(stderr.contains("--no-format"), "{stderr}"); } +#[test] +fn a_config_holding_only_another_tool_tables_exits_two() { + let (code, _, stderr) = run("no-lint-table", &[]); + + assert_eq!(code, EXIT_ERROR, "{stderr}"); + assert!(stderr.contains("has no [lint] table"), "{stderr}"); +} + #[test] fn an_unreadable_config_exits_two() { let output = binary() .current_dir(case("clean")) - .args(["check", "--no-format", "--config", "compact-lint.toml.nope"]) + .args(["check", "--no-format", "--config", "compact.toml.nope"]) .output() .expect("the binary ran"); diff --git a/crates/compact-lint/tests/fill.rs b/crates/compact-lint/tests/fill.rs index bbf3e241..a36dbd77 100644 --- a/crates/compact-lint/tests/fill.rs +++ b/crates/compact-lint/tests/fill.rs @@ -45,8 +45,8 @@ fn work(name: &str) -> TempDir { let root = case(name); std::fs::copy( - root.join("compact-lint.toml"), - directory.path().join("compact-lint.toml"), + root.join("compact.toml"), + directory.path().join("compact.toml"), ) .expect("the case has a config"); copy_tree(&root.join("before"), directory.path()); diff --git a/crates/compact-lint/tests/fix.rs b/crates/compact-lint/tests/fix.rs index 2d4e7189..96c7693a 100644 --- a/crates/compact-lint/tests/fix.rs +++ b/crates/compact-lint/tests/fix.rs @@ -1,6 +1,6 @@ //! `compact-lint fix` end to end, one fixture case per rule. //! -//! A case holds `compact-lint.toml`, `before/`, `after/`, `expected.txt` for the write +//! A case holds `compact.toml`, `before/`, `after/`, `expected.txt` for the write //! run and `expected-dry-run.txt` for the preview. The run works on a copy of `before/`, //! so the fixtures themselves are never rewritten. @@ -32,8 +32,8 @@ fn work(name: &str) -> TempDir { let root = case(name); std::fs::copy( - root.join("compact-lint.toml"), - directory.path().join("compact-lint.toml"), + root.join("compact.toml"), + directory.path().join("compact.toml"), ) .expect("the case has a config"); copy_tree(&root.join("before"), directory.path()); @@ -225,10 +225,10 @@ fn a_concise_run_prints_one_line_per_edit() { #[test] fn an_explicit_config_replaces_the_one_beside_the_sources() { let directory = work("rename"); - std::fs::remove_file(directory.path().join("compact-lint.toml")) + std::fs::remove_file(directory.path().join("compact.toml")) .expect("the copied config is removable"); - let config = case("rename").join("compact-lint.toml"); + let config = case("rename").join("compact.toml"); let output = binary() .current_dir(directory.path()) .args(["fix", "--colors=off", "--config"]) diff --git a/crates/compact-lint/tests/fixtures/clean/compact.toml b/crates/compact-lint/tests/fixtures/clean/compact.toml new file mode 100644 index 00000000..b55b8bc8 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/clean/compact.toml @@ -0,0 +1,42 @@ +# compact-deploy's tables, here so the case proves the linter ignores them. +[profile] +default_network = "local" + +[networks.local] +network_id = "undeployed" +indexer = "http://127.0.0.1:8088/api/v4/graphql" +indexer_ws = "ws://127.0.0.1:8088/api/v4/graphql/ws" +node = "http://127.0.0.1:9944" +node_ws = "ws://127.0.0.1:9944" + +[contracts.Clean] +artifact = "Clean" +signing_key_file = "deploy/Clean.signingkey" + +[lint] +include = ["**/*.compact"] + +[lint.tags] +forbid = ["@return"] + +[lint.kinds.module] +tags = ["@module", "@description"] + +[lint.kinds.circuit] +tags = ["@description"] + +[lint.kinds.ledger] +tags = ["@description"] + +[lint.kinds.witness] +docs = "all" +tags = ["@description"] + +[lint.kinds.struct] +tags = ["@description"] + +[lint.kinds.enum] +tags = ["@description"] + +[lint.kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/diagnostic-level/compact-lint.toml b/crates/compact-lint/tests/fixtures/constraints-format/compact.toml similarity index 59% rename from crates/compact-lint/tests/fixtures/diagnostic-level/compact-lint.toml rename to crates/compact-lint/tests/fixtures/constraints-format/compact.toml index 0813e24c..01fa5a78 100644 --- a/crates/compact-lint/tests/fixtures/diagnostic-level/compact-lint.toml +++ b/crates/compact-lint/tests/fixtures/constraints-format/compact.toml @@ -1,27 +1,27 @@ -version = 1 +[lint] include = ["**/*.compact"] -[tags] +[lint.tags] forbid = ["@return"] -[kinds.module] +[lint.kinds.module] tags = ["@module", "@description"] -[kinds.circuit] +[lint.kinds.circuit] tags = ["@description"] -[kinds.ledger] +[lint.kinds.ledger] tags = ["@description"] -[kinds.witness] +[lint.kinds.witness] docs = "all" tags = ["@description"] -[kinds.struct] +[lint.kinds.struct] tags = ["@description"] -[kinds.enum] +[lint.kinds.enum] tags = ["@description"] -[kinds.constructor] +[lint.kinds.constructor] docs = "none" diff --git a/crates/compact-lint/tests/fixtures/clean/compact-lint.toml b/crates/compact-lint/tests/fixtures/constraints-placeholder/compact.toml similarity index 59% rename from crates/compact-lint/tests/fixtures/clean/compact-lint.toml rename to crates/compact-lint/tests/fixtures/constraints-placeholder/compact.toml index 0813e24c..01fa5a78 100644 --- a/crates/compact-lint/tests/fixtures/clean/compact-lint.toml +++ b/crates/compact-lint/tests/fixtures/constraints-placeholder/compact.toml @@ -1,27 +1,27 @@ -version = 1 +[lint] include = ["**/*.compact"] -[tags] +[lint.tags] forbid = ["@return"] -[kinds.module] +[lint.kinds.module] tags = ["@module", "@description"] -[kinds.circuit] +[lint.kinds.circuit] tags = ["@description"] -[kinds.ledger] +[lint.kinds.ledger] tags = ["@description"] -[kinds.witness] +[lint.kinds.witness] docs = "all" tags = ["@description"] -[kinds.struct] +[lint.kinds.struct] tags = ["@description"] -[kinds.enum] +[lint.kinds.enum] tags = ["@description"] -[kinds.constructor] +[lint.kinds.constructor] docs = "none" diff --git a/crates/compact-lint/tests/fixtures/constraints-format/compact-lint.toml b/crates/compact-lint/tests/fixtures/diagnostic-level/compact.toml similarity index 59% rename from crates/compact-lint/tests/fixtures/constraints-format/compact-lint.toml rename to crates/compact-lint/tests/fixtures/diagnostic-level/compact.toml index 0813e24c..01fa5a78 100644 --- a/crates/compact-lint/tests/fixtures/constraints-format/compact-lint.toml +++ b/crates/compact-lint/tests/fixtures/diagnostic-level/compact.toml @@ -1,27 +1,27 @@ -version = 1 +[lint] include = ["**/*.compact"] -[tags] +[lint.tags] forbid = ["@return"] -[kinds.module] +[lint.kinds.module] tags = ["@module", "@description"] -[kinds.circuit] +[lint.kinds.circuit] tags = ["@description"] -[kinds.ledger] +[lint.kinds.ledger] tags = ["@description"] -[kinds.witness] +[lint.kinds.witness] docs = "all" tags = ["@description"] -[kinds.struct] +[lint.kinds.struct] tags = ["@description"] -[kinds.enum] +[lint.kinds.enum] tags = ["@description"] -[kinds.constructor] +[lint.kinds.constructor] docs = "none" diff --git a/crates/compact-lint/tests/fixtures/error-on-warnings/compact-lint.toml b/crates/compact-lint/tests/fixtures/error-on-warnings/compact-lint.toml deleted file mode 100644 index 0813e24c..00000000 --- a/crates/compact-lint/tests/fixtures/error-on-warnings/compact-lint.toml +++ /dev/null @@ -1,27 +0,0 @@ -version = 1 -include = ["**/*.compact"] - -[tags] -forbid = ["@return"] - -[kinds.module] -tags = ["@module", "@description"] - -[kinds.circuit] -tags = ["@description"] - -[kinds.ledger] -tags = ["@description"] - -[kinds.witness] -docs = "all" -tags = ["@description"] - -[kinds.struct] -tags = ["@description"] - -[kinds.enum] -tags = ["@description"] - -[kinds.constructor] -docs = "none" diff --git a/crates/compact-lint/tests/fixtures/constraints-placeholder/compact-lint.toml b/crates/compact-lint/tests/fixtures/error-on-warnings/compact.toml similarity index 59% rename from crates/compact-lint/tests/fixtures/constraints-placeholder/compact-lint.toml rename to crates/compact-lint/tests/fixtures/error-on-warnings/compact.toml index 0813e24c..01fa5a78 100644 --- a/crates/compact-lint/tests/fixtures/constraints-placeholder/compact-lint.toml +++ b/crates/compact-lint/tests/fixtures/error-on-warnings/compact.toml @@ -1,27 +1,27 @@ -version = 1 +[lint] include = ["**/*.compact"] -[tags] +[lint.tags] forbid = ["@return"] -[kinds.module] +[lint.kinds.module] tags = ["@module", "@description"] -[kinds.circuit] +[lint.kinds.circuit] tags = ["@description"] -[kinds.ledger] +[lint.kinds.ledger] tags = ["@description"] -[kinds.witness] +[lint.kinds.witness] docs = "all" tags = ["@description"] -[kinds.struct] +[lint.kinds.struct] tags = ["@description"] -[kinds.enum] +[lint.kinds.enum] tags = ["@description"] -[kinds.constructor] +[lint.kinds.constructor] docs = "none" diff --git a/crates/compact-lint/tests/fixtures/fill-basic/compact-lint.toml b/crates/compact-lint/tests/fixtures/fill-basic/compact.toml similarity index 65% rename from crates/compact-lint/tests/fixtures/fill-basic/compact-lint.toml rename to crates/compact-lint/tests/fixtures/fill-basic/compact.toml index e5a81d85..2edfac92 100644 --- a/crates/compact-lint/tests/fixtures/fill-basic/compact-lint.toml +++ b/crates/compact-lint/tests/fixtures/fill-basic/compact.toml @@ -1,8 +1,8 @@ -version = 1 +[lint] exclude = ["**/test/mocks/**"] -[kinds.module] +[lint.kinds.module] tags = ["@module", "@description"] -[kinds.circuit] +[lint.kinds.circuit] tags = ["@description"] diff --git a/crates/compact-lint/tests/fixtures/fill-compiler-fails/compact-lint.toml b/crates/compact-lint/tests/fixtures/fill-compiler-fails/compact.toml similarity index 65% rename from crates/compact-lint/tests/fixtures/fill-compiler-fails/compact-lint.toml rename to crates/compact-lint/tests/fixtures/fill-compiler-fails/compact.toml index e5a81d85..2edfac92 100644 --- a/crates/compact-lint/tests/fixtures/fill-compiler-fails/compact-lint.toml +++ b/crates/compact-lint/tests/fixtures/fill-compiler-fails/compact.toml @@ -1,8 +1,8 @@ -version = 1 +[lint] exclude = ["**/test/mocks/**"] -[kinds.module] +[lint.kinds.module] tags = ["@module", "@description"] -[kinds.circuit] +[lint.kinds.circuit] tags = ["@description"] diff --git a/crates/compact-lint/tests/fixtures/fill-missing-source/compact-lint.toml b/crates/compact-lint/tests/fixtures/fill-missing-source/compact.toml similarity index 55% rename from crates/compact-lint/tests/fixtures/fill-missing-source/compact-lint.toml rename to crates/compact-lint/tests/fixtures/fill-missing-source/compact.toml index 584076c2..e1314246 100644 --- a/crates/compact-lint/tests/fixtures/fill-missing-source/compact-lint.toml +++ b/crates/compact-lint/tests/fixtures/fill-missing-source/compact.toml @@ -1,7 +1,7 @@ -version = 1 +[lint] -[kinds.module] +[lint.kinds.module] tags = ["@module", "@description"] -[kinds.circuit] +[lint.kinds.circuit] tags = ["@description"] diff --git a/crates/compact-lint/tests/fixtures/fill-no-compile/compact-lint.toml b/crates/compact-lint/tests/fixtures/fill-no-compile/compact.toml similarity index 65% rename from crates/compact-lint/tests/fixtures/fill-no-compile/compact-lint.toml rename to crates/compact-lint/tests/fixtures/fill-no-compile/compact.toml index e5a81d85..2edfac92 100644 --- a/crates/compact-lint/tests/fixtures/fill-no-compile/compact-lint.toml +++ b/crates/compact-lint/tests/fixtures/fill-no-compile/compact.toml @@ -1,8 +1,8 @@ -version = 1 +[lint] exclude = ["**/test/mocks/**"] -[kinds.module] +[lint.kinds.module] tags = ["@module", "@description"] -[kinds.circuit] +[lint.kinds.circuit] tags = ["@description"] diff --git a/crates/compact-lint/tests/fixtures/fill-override/compact-lint.toml b/crates/compact-lint/tests/fixtures/fill-override/compact.toml similarity index 68% rename from crates/compact-lint/tests/fixtures/fill-override/compact-lint.toml rename to crates/compact-lint/tests/fixtures/fill-override/compact.toml index 4f16f104..a9032949 100644 --- a/crates/compact-lint/tests/fixtures/fill-override/compact-lint.toml +++ b/crates/compact-lint/tests/fixtures/fill-override/compact.toml @@ -1,11 +1,11 @@ -version = 1 +[lint] exclude = ["**/test/mocks/**"] -[constraints.overrides] +[lint.constraints.overrides] "src/utils/Utils.compact" = "src/utils/test/mocks/MockUtilities.compact" -[kinds.module] +[lint.kinds.module] tags = ["@module", "@description"] -[kinds.circuit] +[lint.kinds.circuit] tags = ["@description"] diff --git a/crates/compact-lint/tests/fixtures/fill-self/compact-lint.toml b/crates/compact-lint/tests/fixtures/fill-self/compact.toml similarity index 56% rename from crates/compact-lint/tests/fixtures/fill-self/compact-lint.toml rename to crates/compact-lint/tests/fixtures/fill-self/compact.toml index 85451328..d4c9f2f0 100644 --- a/crates/compact-lint/tests/fixtures/fill-self/compact-lint.toml +++ b/crates/compact-lint/tests/fixtures/fill-self/compact.toml @@ -1,10 +1,10 @@ -version = 1 +[lint] -[constraints] +[lint.constraints] self = ["**/presets/**"] -[kinds.module] +[lint.kinds.module] tags = ["@module", "@description"] -[kinds.circuit] +[lint.kinds.circuit] tags = ["@description"] diff --git a/crates/compact-lint/tests/fixtures/fix-constraints/compact-lint.toml b/crates/compact-lint/tests/fixtures/fix-constraints/compact.toml similarity index 52% rename from crates/compact-lint/tests/fixtures/fix-constraints/compact-lint.toml rename to crates/compact-lint/tests/fixtures/fix-constraints/compact.toml index 832f4ee6..0a6450ac 100644 --- a/crates/compact-lint/tests/fixtures/fix-constraints/compact-lint.toml +++ b/crates/compact-lint/tests/fixtures/fix-constraints/compact.toml @@ -1,13 +1,13 @@ -version = 1 +[lint] include = ["**/*.compact"] -[constraints] +[lint.constraints] tag = "@constraints" -[kinds.module] +[lint.kinds.module] tags = ["@module", "@description"] -[kinds.circuit] +[lint.kinds.circuit] -[kinds.constructor] +[lint.kinds.constructor] docs = "none" diff --git a/crates/compact-lint/tests/fixtures/fix-crlf/compact-lint.toml b/crates/compact-lint/tests/fixtures/fix-crlf/compact.toml similarity index 63% rename from crates/compact-lint/tests/fixtures/fix-crlf/compact-lint.toml rename to crates/compact-lint/tests/fixtures/fix-crlf/compact.toml index 5e3068c1..de1e9488 100644 --- a/crates/compact-lint/tests/fixtures/fix-crlf/compact-lint.toml +++ b/crates/compact-lint/tests/fixtures/fix-crlf/compact.toml @@ -1,18 +1,18 @@ -version = 1 +[lint] include = ["**/*.compact"] -[tags] +[lint.tags] forbid = ["@return"] rename = { "@return" = "@returns" } -[kinds.module] +[lint.kinds.module] tags = ["@module", "@description"] -[kinds.circuit] +[lint.kinds.circuit] tags = ["@description"] -[kinds.ledger] +[lint.kinds.ledger] tags = ["@description"] -[kinds.constructor] +[lint.kinds.constructor] docs = "none" diff --git a/crates/compact-lint/tests/fixtures/fix-missing-tag/compact-lint.toml b/crates/compact-lint/tests/fixtures/fix-missing-tag/compact.toml similarity index 57% rename from crates/compact-lint/tests/fixtures/fix-missing-tag/compact-lint.toml rename to crates/compact-lint/tests/fixtures/fix-missing-tag/compact.toml index 3af7b212..a8f7e9a2 100644 --- a/crates/compact-lint/tests/fixtures/fix-missing-tag/compact-lint.toml +++ b/crates/compact-lint/tests/fixtures/fix-missing-tag/compact.toml @@ -1,14 +1,14 @@ -version = 1 +[lint] include = ["**/*.compact"] -[kinds.module] +[lint.kinds.module] tags = ["@module", "@description"] -[kinds.circuit] +[lint.kinds.circuit] tags = ["@description"] -[kinds.ledger] +[lint.kinds.ledger] tags = ["@description"] -[kinds.constructor] +[lint.kinds.constructor] docs = "none" diff --git a/crates/compact-lint/tests/fixtures/fix-module-name/compact-lint.toml b/crates/compact-lint/tests/fixtures/fix-module-name/compact.toml similarity index 60% rename from crates/compact-lint/tests/fixtures/fix-module-name/compact-lint.toml rename to crates/compact-lint/tests/fixtures/fix-module-name/compact.toml index d404f250..bbc83387 100644 --- a/crates/compact-lint/tests/fixtures/fix-module-name/compact-lint.toml +++ b/crates/compact-lint/tests/fixtures/fix-module-name/compact.toml @@ -1,8 +1,8 @@ -version = 1 +[lint] include = ["**/*.compact"] -[kinds.module] +[lint.kinds.module] tags = ["@module", "@description"] -[kinds.constructor] +[lint.kinds.constructor] docs = "none" diff --git a/crates/compact-lint/tests/fixtures/fix-rename/compact-lint.toml b/crates/compact-lint/tests/fixtures/fix-rename/compact.toml similarity index 65% rename from crates/compact-lint/tests/fixtures/fix-rename/compact-lint.toml rename to crates/compact-lint/tests/fixtures/fix-rename/compact.toml index ad6ecc55..05f63b37 100644 --- a/crates/compact-lint/tests/fixtures/fix-rename/compact-lint.toml +++ b/crates/compact-lint/tests/fixtures/fix-rename/compact.toml @@ -1,15 +1,15 @@ -version = 1 +[lint] include = ["**/*.compact"] -[tags] +[lint.tags] forbid = ["@return"] rename = { "@return" = "@returns" } -[kinds.module] +[lint.kinds.module] tags = ["@module", "@description"] -[kinds.circuit] +[lint.kinds.circuit] tags = ["@description"] -[kinds.constructor] +[lint.kinds.constructor] docs = "none" diff --git a/crates/compact-lint/tests/fixtures/fix-skeleton/compact-lint.toml b/crates/compact-lint/tests/fixtures/fix-skeleton/compact.toml similarity index 62% rename from crates/compact-lint/tests/fixtures/fix-skeleton/compact-lint.toml rename to crates/compact-lint/tests/fixtures/fix-skeleton/compact.toml index 5fd3408d..234ff29f 100644 --- a/crates/compact-lint/tests/fixtures/fix-skeleton/compact-lint.toml +++ b/crates/compact-lint/tests/fixtures/fix-skeleton/compact.toml @@ -1,31 +1,31 @@ -version = 1 +[lint] include = ["**/*.compact"] -[fix] +[lint.fix] placeholder = "TODO" -[tags] +[lint.tags] forbid = ["@return"] rename = { "@return" = "@returns" } -[kinds.module] +[lint.kinds.module] tags = ["@module", "@description"] -[kinds.circuit] +[lint.kinds.circuit] tags = ["@description"] -[kinds.ledger] +[lint.kinds.ledger] tags = ["@description"] -[kinds.witness] +[lint.kinds.witness] docs = "all" tags = ["@description"] -[kinds.struct] +[lint.kinds.struct] tags = ["@description"] -[kinds.enum] +[lint.kinds.enum] tags = ["@description"] -[kinds.constructor] +[lint.kinds.constructor] docs = "none" diff --git a/crates/compact-lint/tests/fixtures/fix-unfixable/compact-lint.toml b/crates/compact-lint/tests/fixtures/fix-unfixable/compact.toml similarity index 70% rename from crates/compact-lint/tests/fixtures/fix-unfixable/compact-lint.toml rename to crates/compact-lint/tests/fixtures/fix-unfixable/compact.toml index 9bb3ab8f..3e20ce9e 100644 --- a/crates/compact-lint/tests/fixtures/fix-unfixable/compact-lint.toml +++ b/crates/compact-lint/tests/fixtures/fix-unfixable/compact.toml @@ -1,15 +1,15 @@ -version = 1 +[lint] include = ["**/*.compact"] # `@throws` is forbidden but has no replacement, so `fix` leaves it where it is. -[tags] +[lint.tags] forbid = ["@throws"] -[kinds.module] +[lint.kinds.module] tags = ["@module", "@description"] -[kinds.circuit] +[lint.kinds.circuit] tags = ["@description"] -[kinds.constructor] +[lint.kinds.constructor] docs = "none" diff --git a/crates/compact-lint/tests/fixtures/forbidden-tag/compact-lint.toml b/crates/compact-lint/tests/fixtures/forbidden-tag/compact-lint.toml deleted file mode 100644 index 0813e24c..00000000 --- a/crates/compact-lint/tests/fixtures/forbidden-tag/compact-lint.toml +++ /dev/null @@ -1,27 +0,0 @@ -version = 1 -include = ["**/*.compact"] - -[tags] -forbid = ["@return"] - -[kinds.module] -tags = ["@module", "@description"] - -[kinds.circuit] -tags = ["@description"] - -[kinds.ledger] -tags = ["@description"] - -[kinds.witness] -docs = "all" -tags = ["@description"] - -[kinds.struct] -tags = ["@description"] - -[kinds.enum] -tags = ["@description"] - -[kinds.constructor] -docs = "none" diff --git a/crates/compact-lint/tests/fixtures/forbidden-tag/compact.toml b/crates/compact-lint/tests/fixtures/forbidden-tag/compact.toml new file mode 100644 index 00000000..01fa5a78 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/forbidden-tag/compact.toml @@ -0,0 +1,27 @@ +[lint] +include = ["**/*.compact"] + +[lint.tags] +forbid = ["@return"] + +[lint.kinds.module] +tags = ["@module", "@description"] + +[lint.kinds.circuit] +tags = ["@description"] + +[lint.kinds.ledger] +tags = ["@description"] + +[lint.kinds.witness] +docs = "all" +tags = ["@description"] + +[lint.kinds.struct] +tags = ["@description"] + +[lint.kinds.enum] +tags = ["@description"] + +[lint.kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/max-diagnostics/compact-lint.toml b/crates/compact-lint/tests/fixtures/max-diagnostics/compact-lint.toml deleted file mode 100644 index 0813e24c..00000000 --- a/crates/compact-lint/tests/fixtures/max-diagnostics/compact-lint.toml +++ /dev/null @@ -1,27 +0,0 @@ -version = 1 -include = ["**/*.compact"] - -[tags] -forbid = ["@return"] - -[kinds.module] -tags = ["@module", "@description"] - -[kinds.circuit] -tags = ["@description"] - -[kinds.ledger] -tags = ["@description"] - -[kinds.witness] -docs = "all" -tags = ["@description"] - -[kinds.struct] -tags = ["@description"] - -[kinds.enum] -tags = ["@description"] - -[kinds.constructor] -docs = "none" diff --git a/crates/compact-lint/tests/fixtures/max-diagnostics/compact.toml b/crates/compact-lint/tests/fixtures/max-diagnostics/compact.toml new file mode 100644 index 00000000..01fa5a78 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/max-diagnostics/compact.toml @@ -0,0 +1,27 @@ +[lint] +include = ["**/*.compact"] + +[lint.tags] +forbid = ["@return"] + +[lint.kinds.module] +tags = ["@module", "@description"] + +[lint.kinds.circuit] +tags = ["@description"] + +[lint.kinds.ledger] +tags = ["@description"] + +[lint.kinds.witness] +docs = "all" +tags = ["@description"] + +[lint.kinds.struct] +tags = ["@description"] + +[lint.kinds.enum] +tags = ["@description"] + +[lint.kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/missing-constraints/compact-lint.toml b/crates/compact-lint/tests/fixtures/missing-constraints/compact-lint.toml deleted file mode 100644 index 0813e24c..00000000 --- a/crates/compact-lint/tests/fixtures/missing-constraints/compact-lint.toml +++ /dev/null @@ -1,27 +0,0 @@ -version = 1 -include = ["**/*.compact"] - -[tags] -forbid = ["@return"] - -[kinds.module] -tags = ["@module", "@description"] - -[kinds.circuit] -tags = ["@description"] - -[kinds.ledger] -tags = ["@description"] - -[kinds.witness] -docs = "all" -tags = ["@description"] - -[kinds.struct] -tags = ["@description"] - -[kinds.enum] -tags = ["@description"] - -[kinds.constructor] -docs = "none" diff --git a/crates/compact-lint/tests/fixtures/missing-constraints/compact.toml b/crates/compact-lint/tests/fixtures/missing-constraints/compact.toml new file mode 100644 index 00000000..01fa5a78 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/missing-constraints/compact.toml @@ -0,0 +1,27 @@ +[lint] +include = ["**/*.compact"] + +[lint.tags] +forbid = ["@return"] + +[lint.kinds.module] +tags = ["@module", "@description"] + +[lint.kinds.circuit] +tags = ["@description"] + +[lint.kinds.ledger] +tags = ["@description"] + +[lint.kinds.witness] +docs = "all" +tags = ["@description"] + +[lint.kinds.struct] +tags = ["@description"] + +[lint.kinds.enum] +tags = ["@description"] + +[lint.kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/missing-doc/compact-lint.toml b/crates/compact-lint/tests/fixtures/missing-doc/compact-lint.toml deleted file mode 100644 index 0813e24c..00000000 --- a/crates/compact-lint/tests/fixtures/missing-doc/compact-lint.toml +++ /dev/null @@ -1,27 +0,0 @@ -version = 1 -include = ["**/*.compact"] - -[tags] -forbid = ["@return"] - -[kinds.module] -tags = ["@module", "@description"] - -[kinds.circuit] -tags = ["@description"] - -[kinds.ledger] -tags = ["@description"] - -[kinds.witness] -docs = "all" -tags = ["@description"] - -[kinds.struct] -tags = ["@description"] - -[kinds.enum] -tags = ["@description"] - -[kinds.constructor] -docs = "none" diff --git a/crates/compact-lint/tests/fixtures/missing-doc/compact.toml b/crates/compact-lint/tests/fixtures/missing-doc/compact.toml new file mode 100644 index 00000000..01fa5a78 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/missing-doc/compact.toml @@ -0,0 +1,27 @@ +[lint] +include = ["**/*.compact"] + +[lint.tags] +forbid = ["@return"] + +[lint.kinds.module] +tags = ["@module", "@description"] + +[lint.kinds.circuit] +tags = ["@description"] + +[lint.kinds.ledger] +tags = ["@description"] + +[lint.kinds.witness] +docs = "all" +tags = ["@description"] + +[lint.kinds.struct] +tags = ["@description"] + +[lint.kinds.enum] +tags = ["@description"] + +[lint.kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/missing-tag/compact-lint.toml b/crates/compact-lint/tests/fixtures/missing-tag/compact-lint.toml deleted file mode 100644 index 0813e24c..00000000 --- a/crates/compact-lint/tests/fixtures/missing-tag/compact-lint.toml +++ /dev/null @@ -1,27 +0,0 @@ -version = 1 -include = ["**/*.compact"] - -[tags] -forbid = ["@return"] - -[kinds.module] -tags = ["@module", "@description"] - -[kinds.circuit] -tags = ["@description"] - -[kinds.ledger] -tags = ["@description"] - -[kinds.witness] -docs = "all" -tags = ["@description"] - -[kinds.struct] -tags = ["@description"] - -[kinds.enum] -tags = ["@description"] - -[kinds.constructor] -docs = "none" diff --git a/crates/compact-lint/tests/fixtures/missing-tag/compact.toml b/crates/compact-lint/tests/fixtures/missing-tag/compact.toml new file mode 100644 index 00000000..01fa5a78 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/missing-tag/compact.toml @@ -0,0 +1,27 @@ +[lint] +include = ["**/*.compact"] + +[lint.tags] +forbid = ["@return"] + +[lint.kinds.module] +tags = ["@module", "@description"] + +[lint.kinds.circuit] +tags = ["@description"] + +[lint.kinds.ledger] +tags = ["@description"] + +[lint.kinds.witness] +docs = "all" +tags = ["@description"] + +[lint.kinds.struct] +tags = ["@description"] + +[lint.kinds.enum] +tags = ["@description"] + +[lint.kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/module-name/compact-lint.toml b/crates/compact-lint/tests/fixtures/module-name/compact-lint.toml deleted file mode 100644 index 0813e24c..00000000 --- a/crates/compact-lint/tests/fixtures/module-name/compact-lint.toml +++ /dev/null @@ -1,27 +0,0 @@ -version = 1 -include = ["**/*.compact"] - -[tags] -forbid = ["@return"] - -[kinds.module] -tags = ["@module", "@description"] - -[kinds.circuit] -tags = ["@description"] - -[kinds.ledger] -tags = ["@description"] - -[kinds.witness] -docs = "all" -tags = ["@description"] - -[kinds.struct] -tags = ["@description"] - -[kinds.enum] -tags = ["@description"] - -[kinds.constructor] -docs = "none" diff --git a/crates/compact-lint/tests/fixtures/module-name/compact.toml b/crates/compact-lint/tests/fixtures/module-name/compact.toml new file mode 100644 index 00000000..01fa5a78 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/module-name/compact.toml @@ -0,0 +1,27 @@ +[lint] +include = ["**/*.compact"] + +[lint.tags] +forbid = ["@return"] + +[lint.kinds.module] +tags = ["@module", "@description"] + +[lint.kinds.circuit] +tags = ["@description"] + +[lint.kinds.ledger] +tags = ["@description"] + +[lint.kinds.witness] +docs = "all" +tags = ["@description"] + +[lint.kinds.struct] +tags = ["@description"] + +[lint.kinds.enum] +tags = ["@description"] + +[lint.kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/no-lint-table/compact.toml b/crates/compact-lint/tests/fixtures/no-lint-table/compact.toml new file mode 100644 index 00000000..e7d243dc --- /dev/null +++ b/crates/compact-lint/tests/fixtures/no-lint-table/compact.toml @@ -0,0 +1,14 @@ +# compact-deploy's tables only: the file exists, the linter's table does not. +[profile] +default_network = "local" + +[networks.local] +network_id = "undeployed" +indexer = "http://127.0.0.1:8088/api/v4/graphql" +indexer_ws = "ws://127.0.0.1:8088/api/v4/graphql/ws" +node = "http://127.0.0.1:9944" +node_ws = "ws://127.0.0.1:9944" + +[contracts.Token] +artifact = "Token" +signing_key_file = "deploy/Token.signingkey" diff --git a/crates/compact-lint/tests/fixtures/parse/compact-lint.toml b/crates/compact-lint/tests/fixtures/parse/compact.toml similarity index 69% rename from crates/compact-lint/tests/fixtures/parse/compact-lint.toml rename to crates/compact-lint/tests/fixtures/parse/compact.toml index 56ee774e..e7401e9b 100644 --- a/crates/compact-lint/tests/fixtures/parse/compact-lint.toml +++ b/crates/compact-lint/tests/fixtures/parse/compact.toml @@ -1,2 +1,2 @@ -version = 1 +[lint] include = ["**/*.compact"] diff --git a/crates/compact-lint/tests/fixtures/reporter-concise/compact-lint.toml b/crates/compact-lint/tests/fixtures/reporter-concise/compact-lint.toml deleted file mode 100644 index 0813e24c..00000000 --- a/crates/compact-lint/tests/fixtures/reporter-concise/compact-lint.toml +++ /dev/null @@ -1,27 +0,0 @@ -version = 1 -include = ["**/*.compact"] - -[tags] -forbid = ["@return"] - -[kinds.module] -tags = ["@module", "@description"] - -[kinds.circuit] -tags = ["@description"] - -[kinds.ledger] -tags = ["@description"] - -[kinds.witness] -docs = "all" -tags = ["@description"] - -[kinds.struct] -tags = ["@description"] - -[kinds.enum] -tags = ["@description"] - -[kinds.constructor] -docs = "none" diff --git a/crates/compact-lint/tests/fixtures/reporter-concise/compact.toml b/crates/compact-lint/tests/fixtures/reporter-concise/compact.toml new file mode 100644 index 00000000..01fa5a78 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/reporter-concise/compact.toml @@ -0,0 +1,27 @@ +[lint] +include = ["**/*.compact"] + +[lint.tags] +forbid = ["@return"] + +[lint.kinds.module] +tags = ["@module", "@description"] + +[lint.kinds.circuit] +tags = ["@description"] + +[lint.kinds.ledger] +tags = ["@description"] + +[lint.kinds.witness] +docs = "all" +tags = ["@description"] + +[lint.kinds.struct] +tags = ["@description"] + +[lint.kinds.enum] +tags = ["@description"] + +[lint.kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/reporter-github/compact-lint.toml b/crates/compact-lint/tests/fixtures/reporter-github/compact-lint.toml deleted file mode 100644 index 0813e24c..00000000 --- a/crates/compact-lint/tests/fixtures/reporter-github/compact-lint.toml +++ /dev/null @@ -1,27 +0,0 @@ -version = 1 -include = ["**/*.compact"] - -[tags] -forbid = ["@return"] - -[kinds.module] -tags = ["@module", "@description"] - -[kinds.circuit] -tags = ["@description"] - -[kinds.ledger] -tags = ["@description"] - -[kinds.witness] -docs = "all" -tags = ["@description"] - -[kinds.struct] -tags = ["@description"] - -[kinds.enum] -tags = ["@description"] - -[kinds.constructor] -docs = "none" diff --git a/crates/compact-lint/tests/fixtures/reporter-github/compact.toml b/crates/compact-lint/tests/fixtures/reporter-github/compact.toml new file mode 100644 index 00000000..01fa5a78 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/reporter-github/compact.toml @@ -0,0 +1,27 @@ +[lint] +include = ["**/*.compact"] + +[lint.tags] +forbid = ["@return"] + +[lint.kinds.module] +tags = ["@module", "@description"] + +[lint.kinds.circuit] +tags = ["@description"] + +[lint.kinds.ledger] +tags = ["@description"] + +[lint.kinds.witness] +docs = "all" +tags = ["@description"] + +[lint.kinds.struct] +tags = ["@description"] + +[lint.kinds.enum] +tags = ["@description"] + +[lint.kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/rules-levels/compact-lint.toml b/crates/compact-lint/tests/fixtures/rules-levels/compact.toml similarity index 64% rename from crates/compact-lint/tests/fixtures/rules-levels/compact-lint.toml rename to crates/compact-lint/tests/fixtures/rules-levels/compact.toml index 46228303..02a0b350 100644 --- a/crates/compact-lint/tests/fixtures/rules-levels/compact-lint.toml +++ b/crates/compact-lint/tests/fixtures/rules-levels/compact.toml @@ -1,32 +1,32 @@ -version = 1 +[lint] include = ["**/*.compact"] -[tags] +[lint.tags] forbid = ["@return"] rename = { "@return" = "@returns" } -[kinds.module] +[lint.kinds.module] tags = ["@module", "@description"] -[kinds.circuit] +[lint.kinds.circuit] tags = ["@description"] -[kinds.ledger] +[lint.kinds.ledger] tags = ["@description"] -[kinds.witness] +[lint.kinds.witness] docs = "all" tags = ["@description"] -[kinds.struct] +[lint.kinds.struct] tags = ["@description"] -[kinds.enum] +[lint.kinds.enum] tags = ["@description"] -[kinds.constructor] +[lint.kinds.constructor] docs = "none" -[rules] +[lint.rules] missing-doc = "off" forbidden-tag = "warn" diff --git a/examples/fungible-token/compact.toml b/examples/fungible-token/compact.toml index 672d90a8..85a6f576 100644 --- a/examples/fungible-token/compact.toml +++ b/examples/fungible-token/compact.toml @@ -46,3 +46,5 @@ signing_key_file = "deploy/TokenExample.signingkey" # them from here. The programmatic flow (`yarn deploy:*`) overrides # them inline via the `args:` field on `runDeploy()`. args = { module = "./deploy/TokenExample.args.mjs", export = "args" } + +# compact-lint reads a [lint] table from this same file; see crates/compact-lint/examples/compact.toml. diff --git a/packages/deployer/src/config/compact-config.test.ts b/packages/deployer/src/config/compact-config.test.ts index 2ef37c65..25d4a621 100644 --- a/packages/deployer/src/config/compact-config.test.ts +++ b/packages/deployer/src/config/compact-config.test.ts @@ -38,6 +38,24 @@ describe('CompactConfig', () => { expect(config.contract('Token').artifact).toBe('src/artifacts/Token/Token'); }); + it('ignores the [lint] table that compact-lint owns', async () => { + const dir = tmpRepo(`${MIN_VALID} +[lint] +include = ["contracts/src/**/*.compact"] + +[lint.rules] +missing-doc = "error" + +[lint.kinds.module] +docs = "exported" +tags = ["@module", "@description"] +`); + const config = await CompactConfig.load(undefined, dir); + expect(config.defaultNetwork).toBe('local'); + expect(config.network('local').network_id).toBe('undeployed'); + expect(config.contract('Token').artifact).toBe('src/artifacts/Token/Token'); + }); + it('should throw with the available set when a lookup misses', async () => { const dir = tmpRepo(MIN_VALID); const config = await CompactConfig.load(undefined, dir); diff --git a/packages/linter/README.md b/packages/linter/README.md index 6bf577b0..226b4821 100644 --- a/packages/linter/README.md +++ b/packages/linter/README.md @@ -16,8 +16,9 @@ yarn compact-linter check contracts/src yarn compact-linter fix --dry-run ``` -Commands, flags, exit codes and `compact-lint.toml` are documented in the -[crate README](../../crates/compact-lint/README.md). +Commands, flags, exit codes and the `[lint]` table of `compact.toml` are documented in +the [crate README](../../crates/compact-lint/README.md). `compact.toml` is the project's +one config file, shared with `compact-deploy`. ## Where the binary comes from From 0ce9b338053e64f8ea29e15d45f97ddb893dc3a9 Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Tue, 15 Sep 2026 17:14:47 +0200 Subject: [PATCH 12/56] feat(compact-lint): lint doc sections against a template MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Module headers in compact-contracts are a sequence of named sections (`@notice Privacy:`, `@dev Performance:`, …). A bare `@notice` entry cannot tell them apart, so a config entry may now carry a heading. * `kinds..tags` entries read `@tag` or `@tag Heading`; a headed entry matches only the occurrence whose value opens `Heading:`. `kinds..sections` lists every allowed section in template order and, when set, is the order `tags` entries must also appear in. * `unknown-section` (warn) reports a heading the template does not list, gated per tag so free-form tags stay untouched. `tag-order` (error) reports the first block out of template order; its fix reorders the listed blocks and leaves unlisted ones in their slots. * `fix` inserts a missing section as `@tag Heading:` plus a placeholder line, after its nearest present predecessor in the order. * The linter ships no section list. The example config carries a starting point for compact-contracts. --- crates/compact-lint/README.md | 41 +++- crates/compact-lint/examples/compact.toml | 34 ++- crates/compact-lint/src/config.rs | 214 +++++++++++++++-- crates/compact-lint/src/doc.rs | 178 +++++++++++++- crates/compact-lint/src/edit.rs | 188 +++++++++++++-- crates/compact-lint/src/fix.rs | 155 ++++++++----- crates/compact-lint/src/report.rs | 6 +- crates/compact-lint/src/rules.rs | 217 +++++++++++++++++- crates/compact-lint/tests/check.rs | 24 ++ crates/compact-lint/tests/fix.rs | 21 ++ .../fix-sections/after/Missing.compact | 16 ++ .../fixtures/fix-sections/after/Order.compact | 16 ++ .../fix-sections/after/Skeleton.compact | 12 + .../fix-sections/before/Missing.compact | 14 ++ .../fix-sections/before/Order.compact | 16 ++ .../fix-sections/before/Skeleton.compact | 4 + .../tests/fixtures/fix-sections/compact.toml | 16 ++ .../fix-sections/expected-dry-run.txt | 61 +++++ .../tests/fixtures/fix-sections/expected.txt | 42 ++++ .../sections-missing/Sections.compact | 14 ++ .../fixtures/sections-missing/compact.toml | 13 ++ .../fixtures/sections-missing/expected.txt | 17 ++ .../tests/fixtures/tag-order/Ordered.compact | 14 ++ .../tests/fixtures/tag-order/compact.toml | 13 ++ .../tests/fixtures/tag-order/expected.txt | 24 ++ .../fixtures/template-clean/Template.compact | 51 ++++ .../fixtures/template-clean/compact.toml | 57 +++++ .../fixtures/template-clean/expected.txt | 0 .../fixtures/unknown-section/Headings.compact | 23 ++ .../fixtures/unknown-section/compact.toml | 11 + .../fixtures/unknown-section/expected.txt | 13 ++ 31 files changed, 1408 insertions(+), 117 deletions(-) create mode 100644 crates/compact-lint/tests/fixtures/fix-sections/after/Missing.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-sections/after/Order.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-sections/after/Skeleton.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-sections/before/Missing.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-sections/before/Order.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-sections/before/Skeleton.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-sections/compact.toml create mode 100644 crates/compact-lint/tests/fixtures/fix-sections/expected-dry-run.txt create mode 100644 crates/compact-lint/tests/fixtures/fix-sections/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/sections-missing/Sections.compact create mode 100644 crates/compact-lint/tests/fixtures/sections-missing/compact.toml create mode 100644 crates/compact-lint/tests/fixtures/sections-missing/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/tag-order/Ordered.compact create mode 100644 crates/compact-lint/tests/fixtures/tag-order/compact.toml create mode 100644 crates/compact-lint/tests/fixtures/tag-order/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/template-clean/Template.compact create mode 100644 crates/compact-lint/tests/fixtures/template-clean/compact.toml create mode 100644 crates/compact-lint/tests/fixtures/template-clean/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/unknown-section/Headings.compact create mode 100644 crates/compact-lint/tests/fixtures/unknown-section/compact.toml create mode 100644 crates/compact-lint/tests/fixtures/unknown-section/expected.txt diff --git a/crates/compact-lint/README.md b/crates/compact-lint/README.md index 813808c9..cb1b218b 100644 --- a/crates/compact-lint/README.md +++ b/crates/compact-lint/README.md @@ -103,8 +103,10 @@ Defaults: | Rule | Level | | --- | --- | | `missing-doc`, `missing-tag`, `forbidden-tag`, `module-name` | `error` | +| `tag-order` | `error` | | `missing-constraints`, `constraints-format` | `error` | | `parse`, `format` | `error` | +| `unknown-section` | `warn` | | `constraints-placeholder` | `warn` | | `constraints-unmeasured`, `constraints-unmeasurable` | `warn` | @@ -151,14 +153,17 @@ What each rule's fix does: | Rule | Fix | | --- | --- | -| `missing-doc` | Inserts a doc skeleton above the declaration, indented to it. Body lines come from `kinds..tags` in config order; `@module` takes the declaration's name, every other tag takes `fix.placeholder`. Exported non-pure circuits also get the constraints line. A kind with neither gets a single placeholder line. | -| `missing-tag` | Inserts each missing tag after the block of the last tag that precedes it in `kinds..tags`, else at the top of the body. A missing `@description` adopts untagged prose that opens the body instead of writing a placeholder. A `/** … */` one-liner expands to the multi-line form first. | +| `missing-doc` | Inserts a doc skeleton above the declaration, indented to it. Body lines come from `kinds..tags` in config order; `@module` takes the declaration's name, a headed entry becomes a `@tag Heading:` line with `fix.placeholder` under it, every other tag takes `fix.placeholder`. Exported non-pure circuits also get the constraints line. A kind with neither gets a single placeholder line. | +| `missing-tag` | Inserts each missing entry after the block of the last entry that precedes it in the template order, optional ones included, else at the top of the body. A headed entry goes in as a two-line section block; the predecessor's block is found by heading, not by bare tag. A missing bare `@description` adopts untagged prose that opens the body instead of writing a placeholder. A `/** … */` one-liner expands to the multi-line form first. | +| `tag-order` | Splits the comment body into one block per tag, sorts the blocks matching a listed entry into config order, and writes them back into the same slots. Prose before the first tag, unlisted blocks and the blank lines separating slots stay put, so a second run reports nothing. | | `missing-constraints` | Inserts ` k=?, rows=?` after the `@description` block, with a blank ` *` line before it and, where prose follows, one after. Without a `@description` it opens the body. | | `forbidden-tag` | Renames the tag in place, and only where `tags.rename` maps it. | | `module-name` | Replaces the first word of the `@module` value with the module's name, keeping what follows. | Not fixed: +- `unknown-section` β€” the heading is either a section the config should list or prose to + fold into one, and only a human picks. - `constraints-format` β€” a human wrote a measurement the rule cannot parse; guessing at it would lose the value. - `constraints-placeholder` β€” filling `k=?` needs a real measurement. @@ -166,7 +171,8 @@ Not fixed: - `format` β€” that is `compact format`'s job. - A forbidden tag with no `tags.rename` entry stays a `check` finding. -Existing lines are never reordered or reflowed. Edits are computed against the original +Lines are never reflowed, and only `tag-order` moves them, whole blocks at a time. Edits +are computed against the original text and applied from the highest offset down; several edits on one comment merge into a single replacement of it. Files are rewritten through a sibling `.tmp` file and renamed into place, keeping the file's line ending and its trailing newline, or lack of one. @@ -271,7 +277,9 @@ the line ending, and only the annotation's own line changes. | Rule | Meaning | | --- | --- | | `missing-doc` | The declaration needs docs per `kinds..docs` and has no doc comment attached. | -| `missing-tag` | A tag listed in `kinds..tags` is absent from the doc comment. | +| `missing-tag` | An entry listed in `kinds..tags` is absent from the doc comment. | +| `unknown-section` | A section heading neither `kinds..tags` nor `kinds..sections` lists for that tag. | +| `tag-order` | Listed entries appear in an order the template order does not have. | | `forbidden-tag` | A tag listed in `tags.forbid` is present. | | `module-name` | `@module ` does not name the module it documents. | | `missing-constraints` | An exported non-pure circuit has no constraints tag. | @@ -297,6 +305,11 @@ Rule detail: `module Signer` and `@module Utils.` matches `module Utils`. - **`forbidden-tag`.** It fires on any doc comment attached to a checked declaration, including declarations whose docs are optional. +- **`unknown-section`.** Gated per tag: a kind that lists no headed entry for `@description` + never gets the rule on `@description`. It is not fixable. +- **`tag-order`.** The order is `kinds..sections` where the kind has one, else + `kinds..tags`. Occurrences of tags no entry lists are ignored, and one doc comment + yields one finding, at the first occurrence that breaks the order. ## Config @@ -340,7 +353,8 @@ constraints-placeholder = "warn" [lint.kinds.module] docs = "exported" -tags = ["@module", "@description"] +tags = ["@module", "@description", "@notice Privacy", "@notice Security"] +sections = ["@module", "@description", "@dev Notation", "@notice Privacy", "@notice Security"] ``` Defaults when no config file is found: @@ -360,11 +374,26 @@ Defaults when no config file is found: | `rules.` | `"error"`, except the four listed under Diagnostic levels | | `kinds..docs` | `"exported"` | | `kinds..tags` | `[]` | +| `kinds..sections` | `[]` | - `kinds` takes one table per kind: `module`, `circuit`, `ledger`, `witness`, `constructor`, `struct`, `enum`, `contract`, `type`. `pragma`, `import`, `include`, `export { … }` and `contract implements` are never checked. - `docs` is `"all"`, `"exported"` or `"none"`. +- A `tags` or `sections` entry is `"@tag"` or `"@tag Heading"`, split at the first space. +- `tags` is what every doc comment of the kind must carry. +- `sections`, when non-empty, is the kind's complete template: every allowed section, in + the order a header writes them, required and optional alike. +- A required entry must also appear in `sections`; a `tags` entry missing from a non-empty + `sections` is a config error. +- `tag-order` and the `fix` insert point read `sections` where the kind has one, else + `tags`. +- A headed entry matches the occurrence of its tag whose value opens `Heading:`, matched + exactly and case-sensitively; what follows the colon is free. A bare entry matches any + occurrence of its tag. +- A heading is non-empty, carries no `:`, and appears once per list. +- The linter ships no section list of its own; a kind with no headed entry never reports + `unknown-section` or orders sections. - `constructor` carries no `export` token, so `"exported"` means "never" for it. Use `"all"` or `"none"` there. - `exclude` filters files found by walking a directory. A file named on the command @@ -389,6 +418,8 @@ Defaults when no config file is found: - A tag's value is the rest of its line plus every following line until the next tag or a blank line. - Repeated tags are kept in source order; `@param` normally repeats. +- A value whose first line reads `Heading:` opens a section; the heading is letters, + digits, spaces and hyphens, and anything else reads as prose. - `@param {Type} name - text` is not parsed further. ## Tests diff --git a/crates/compact-lint/examples/compact.toml b/crates/compact-lint/examples/compact.toml index 9cf5ef5f..164f889e 100644 --- a/crates/compact-lint/examples/compact.toml +++ b/crates/compact-lint/examples/compact.toml @@ -26,6 +26,8 @@ rename = { "@return" = "@returns" } # [lint.rules] # missing-doc = "error" # missing-tag = "error" +# unknown-section = "warn" +# tag-order = "error" # forbidden-tag = "error" # module-name = "error" # missing-constraints = "error" @@ -36,9 +38,37 @@ rename = { "@return" = "@returns" } # parse = "error" # format = "error" +# The module header template. `tags` is what every header must carry, `sections` is every +# allowed section in template order, and a required entry also appears in `sections`. Both +# lists are a starting point: moving an entry into `tags` makes it required, and a heading +# `sections` does not name is reported as unknown-section. [lint.kinds.module] -docs = "exported" -tags = ["@module", "@description"] +docs = "all" +tags = [ + "@module", + "@description", + "@notice Privacy", + "@notice Security", + "@notice Concurrency", + "@notice Scope", + "@dev Performance", +] +sections = [ + "@module", + "@description", + "@dev Notation", + "@dev Derivations", + "@dev Parameterization", + "@dev Compatibility", + "@notice Privacy", + "@notice Security", + "@notice Concurrency", + "@notice Scope", + "@notice Client-side duties", + "@notice Scalability", + "@dev Performance", + "@dev Composition", +] [lint.kinds.circuit] tags = ["@description"] diff --git a/crates/compact-lint/src/config.rs b/crates/compact-lint/src/config.rs index 88dc6436..77150d50 100644 --- a/crates/compact-lint/src/config.rs +++ b/crates/compact-lint/src/config.rs @@ -11,7 +11,7 @@ use serde::Deserialize; use thiserror::Error; use crate::diagnostic::Level; -use crate::doc::Tag; +use crate::doc::{Tag, TagSpec}; use crate::model::DeclKind; use crate::report::RuleId; @@ -38,6 +38,26 @@ pub enum ConfigError { "config {path} lists tag {tag:?}; tags are spelled with their `@`, like `@description`" )] Tag { path: PathBuf, tag: String }, + #[error("config {path}: kinds.{kind}.tags lists {entry}, but kinds.{kind}.sections does not")] + NotInSections { + path: PathBuf, + kind: &'static str, + entry: String, + }, + #[error( + "config {path} lists {entry:?} under kinds.{kind}; a heading is non-empty and carries no `:`" + )] + Heading { + path: PathBuf, + kind: &'static str, + entry: String, + }, + #[error("config {path} lists {entry:?} twice under kinds.{kind}")] + DuplicateEntry { + path: PathBuf, + kind: &'static str, + entry: String, + }, #[error("config {path} has an invalid glob {pattern:?}")] Glob { path: PathBuf, @@ -65,7 +85,21 @@ pub enum DocsPolicy { #[serde(deny_unknown_fields, default)] pub struct KindConfig { pub docs: DocsPolicy, - pub tags: Vec, + /// Entries every doc comment of the kind carries; each one also appears in `sections`. + pub tags: Vec, + /// Every section the template allows, in template order; empty leaves `tags` the order. + pub sections: Vec, +} + +impl KindConfig { + /// The ordered template: `sections` where the kind has one, else the required entries. + pub fn entries(&self) -> impl Iterator { + if self.sections.is_empty() { + self.tags.iter() + } else { + self.sections.iter() + } + } } /// One table per checked declaration kind. @@ -87,6 +121,22 @@ pub struct KindsConfig { } impl KindsConfig { + /// Every kind table, keyed by the name its config section uses. + #[must_use] + pub fn all(&self) -> [(&'static str, &KindConfig); 9] { + [ + ("module", &self.module), + ("circuit", &self.circuit), + ("ledger", &self.ledger), + ("witness", &self.witness), + ("constructor", &self.constructor), + ("struct", &self.struct_), + ("enum", &self.enum_), + ("contract", &self.contract), + ("type", &self.type_), + ] + } + #[must_use] pub fn get(&self, kind: DeclKind) -> &KindConfig { match kind { @@ -151,6 +201,10 @@ pub struct RulesConfig { pub missing_doc: Level, #[serde(rename = "missing-tag")] pub missing_tag: Level, + #[serde(rename = "unknown-section")] + pub unknown_section: Level, + #[serde(rename = "tag-order")] + pub tag_order: Level, #[serde(rename = "forbidden-tag")] pub forbidden_tag: Level, #[serde(rename = "module-name")] @@ -174,6 +228,9 @@ impl Default for RulesConfig { Self { missing_doc: Level::Error, missing_tag: Level::Error, + // A heading the template does not list is a candidate for it, not a defect. + unknown_section: Level::Warn, + tag_order: Level::Error, forbidden_tag: Level::Error, module_name: Level::Error, missing_constraints: Level::Error, @@ -195,6 +252,8 @@ impl RulesConfig { match rule { RuleId::MISSING_DOC => self.missing_doc, RuleId::MISSING_TAG => self.missing_tag, + RuleId::UNKNOWN_SECTION => self.unknown_section, + RuleId::TAG_ORDER => self.tag_order, RuleId::FORBIDDEN_TAG => self.forbidden_tag, RuleId::MODULE_NAME => self.module_name, RuleId::MISSING_CONSTRAINTS => self.missing_constraints, @@ -294,25 +353,64 @@ impl Config { tag: tag.to_string(), }); } + config.validate_entries(path)?; Ok(config) } - /// Every tag the config mentions: required per kind, forbidden, and the constraints tag. + /// A heading is well formed, no list repeats an entry, and a required entry takes its + /// place in the section order. + fn validate_entries(&self, path: &Path) -> Result<(), ConfigError> { + for (kind, config) in self.kinds.all() { + for list in [&config.tags, &config.sections] { + let mut seen: Vec = Vec::new(); + for entry in list { + if !entry.has_well_formed_heading() { + return Err(ConfigError::Heading { + path: path.to_owned(), + kind, + entry: entry.to_string(), + }); + } + let spelling = entry.to_string(); + if seen.contains(&spelling) { + return Err(ConfigError::DuplicateEntry { + path: path.to_owned(), + kind, + entry: spelling, + }); + } + seen.push(spelling); + } + } + + if config.sections.is_empty() { + continue; + } + if let Some(entry) = config + .tags + .iter() + .find(|required| !config.sections.contains(required)) + { + return Err(ConfigError::NotInSections { + path: path.to_owned(), + kind, + entry: entry.to_string(), + }); + } + } + Ok(()) + } + + /// Every tag the config mentions: the kind templates, the forbidden set, and the + /// constraints tag. fn tags(&self) -> impl Iterator { - let per_kind = [ - &self.kinds.module, - &self.kinds.circuit, - &self.kinds.ledger, - &self.kinds.witness, - &self.kinds.constructor, - &self.kinds.struct_, - &self.kinds.enum_, - &self.kinds.contract, - &self.kinds.type_, - ] - .into_iter() - .flat_map(|kind| kind.tags.iter()); + let per_kind = self.kinds.all().into_iter().flat_map(|(_, kind)| { + kind.tags + .iter() + .chain(kind.sections.iter()) + .map(|entry| &entry.tag) + }); per_kind .chain(self.tags.forbid.iter()) @@ -382,7 +480,7 @@ pub fn discover(start: &Path) -> Option { mod tests { use super::{Config, DocsPolicy}; use crate::diagnostic::Level; - use crate::doc::Tag; + use crate::doc::{Tag, TagSpec}; use crate::model::DeclKind; use crate::report::RuleId; @@ -393,6 +491,8 @@ mod tests { assert_eq!(rules.get(RuleId::MISSING_DOC), Level::Error); assert_eq!(rules.get(RuleId::PARSE), Level::Error); assert_eq!(rules.get(RuleId::FORMAT), Level::Error); + assert_eq!(rules.get(RuleId::TAG_ORDER), Level::Error); + assert_eq!(rules.get(RuleId::UNKNOWN_SECTION), Level::Warn); assert_eq!(rules.get(RuleId::CONSTRAINTS_PLACEHOLDER), Level::Warn); assert_eq!(rules.get(RuleId::CONSTRAINTS_UNMEASURED), Level::Warn); assert_eq!(rules.get(RuleId::CONSTRAINTS_UNMEASURABLE), Level::Warn); @@ -458,6 +558,86 @@ mod tests { std::fs::remove_dir_all(&dir).expect("the temp dir is removable"); } + #[test] + fn a_tag_entry_keeps_the_heading_after_its_tag() { + let config: Config = toml::from_str( + "[kinds.module]\ntags = [\"@module\", \"@notice Privacy\"]\nsections = [\"@dev Notation\"]\n", + ) + .expect("the snippet is valid config"); + + assert_eq!(config.kinds.module.tags[0], TagSpec::parse("@module")); + assert_eq!( + config.kinds.module.tags[1].heading.as_deref(), + Some("Privacy") + ); + assert_eq!(config.kinds.module.sections[0].tag, Tag::new("@dev")); + assert!(config.kinds.circuit.sections.is_empty()); + } + + #[test] + fn a_required_entry_missing_from_the_section_order_is_rejected() { + let error = load_document( + "not-in-sections", + "[lint.kinds.module]\ntags = [\"@module\", \"@notice Privacy\"]\nsections = [\"@module\", \"@dev Notation\"]\n", + ) + .expect_err("a required entry takes its place in the section order"); + + assert!( + error.to_string().contains( + "kinds.module.tags lists @notice Privacy, but kinds.module.sections does not" + ), + "{error}" + ); + } + + #[test] + fn the_section_order_replaces_the_tag_order_where_the_kind_has_one() { + let bare: Config = + toml::from_str("[kinds.module]\ntags = [\"@module\", \"@description\"]\n") + .expect("the snippet is valid config"); + let ordered: Config = toml::from_str( + "[kinds.module]\ntags = [\"@module\", \"@notice Privacy\"]\nsections = [\"@module\", \"@dev Notation\", \"@notice Privacy\"]\n", + ) + .expect("the snippet is valid config"); + + let spelled = |config: &Config| -> Vec { + config + .kinds + .module + .entries() + .map(ToString::to_string) + .collect() + }; + + assert_eq!(spelled(&bare), ["@module", "@description"]); + assert_eq!( + spelled(&ordered), + ["@module", "@dev Notation", "@notice Privacy"] + ); + } + + #[test] + fn a_heading_carrying_a_colon_is_rejected() { + let error = load_document( + "colon-heading", + "[lint.kinds.module]\ntags = [\"@notice Privacy:\"]\n", + ) + .expect_err("the occurrence writes the colon, not the config"); + + assert!(error.to_string().contains("@notice Privacy:"), "{error}"); + } + + #[test] + fn an_entry_listed_twice_in_one_list_is_rejected() { + let error = load_document( + "duplicate-entry", + "[lint.kinds.module]\nsections = [\"@notice Privacy\", \"@notice Privacy\"]\n", + ) + .expect_err("a list names an entry once"); + + assert!(error.to_string().contains("twice"), "{error}"); + } + #[test] fn a_rename_maps_a_forbidden_tag_to_its_replacement() { let config: Config = toml::from_str( diff --git a/crates/compact-lint/src/doc.rs b/crates/compact-lint/src/doc.rs index 685007f1..6ec4f705 100644 --- a/crates/compact-lint/src/doc.rs +++ b/crates/compact-lint/src/doc.rs @@ -34,6 +34,90 @@ impl fmt::Display for Tag { } } +/// A config tag entry: a tag, optionally narrowed to one named section of the template. +/// +/// `@notice` matches every `@notice`; `@notice Security` matches only the occurrence whose +/// value opens `Security:`. +#[derive(Clone, Debug, Deserialize, PartialEq, Eq)] +#[serde(from = "String")] +pub struct TagSpec { + pub tag: Tag, + pub heading: Option, +} + +impl TagSpec { + #[must_use] + pub const fn bare(tag: Tag) -> Self { + Self { tag, heading: None } + } + + /// Splits `@tag Heading` at its first space; the heading is the rest, trimmed. + #[must_use] + pub fn parse(entry: &str) -> Self { + match entry.split_once(' ') { + Some((tag, heading)) => Self { + tag: Tag::new(tag), + heading: Some(heading.trim().to_owned()), + }, + None => Self::bare(Tag::new(entry)), + } + } + + /// A heading is non-empty and carries no `:`, which the occurrence writes itself. + #[must_use] + pub fn has_well_formed_heading(&self) -> bool { + self.heading + .as_ref() + .is_none_or(|heading| !heading.is_empty() && !heading.contains(':')) + } + + /// The name the entry goes by in prose: its heading, or its tag when it has none. + #[must_use] + pub fn label(&self) -> &str { + self.heading.as_deref().unwrap_or_else(|| self.tag.as_str()) + } + + /// Whether `occurrence` is this entry: the same tag, and for a headed entry a value + /// opening `Heading:`. + #[must_use] + pub fn matches(&self, occurrence: &TagOccurrence) -> bool { + occurrence.tag == self.tag + && self.opens_with_heading(occurrence.value.lines().next().unwrap_or_default()) + } + + /// Whether a gutter-stripped comment line opens this entry's block. + #[must_use] + pub fn matches_line(&self, content: &str) -> bool { + split_tag(content) + .is_some_and(|(tag, value)| tag == self.tag && self.opens_with_heading(value)) + } + + fn opens_with_heading(&self, value: &str) -> bool { + match &self.heading { + None => true, + Some(heading) => value + .trim() + .strip_prefix(heading.as_str()) + .is_some_and(|rest| rest.starts_with(':')), + } + } +} + +impl From for TagSpec { + fn from(entry: String) -> Self { + Self::parse(&entry) + } +} + +impl fmt::Display for TagSpec { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + match &self.heading { + Some(heading) => write!(formatter, "{} {heading}", self.tag), + None => formatter.write_str(self.tag.as_str()), + } + } +} + /// One tag occurrence: its name, its value, and where it sits inside the comment. #[derive(Clone, Debug, PartialEq, Eq)] pub struct TagOccurrence { @@ -45,6 +129,20 @@ pub struct TagOccurrence { pub column_offset: usize, } +impl TagOccurrence { + /// The section heading the value opens with: the text before its first `:`, where + /// that prefix is letters, digits, spaces and hyphens. + #[must_use] + pub fn heading(&self) -> Option<&str> { + let (prefix, _) = self.value.lines().next()?.split_once(':')?; + let spelled = !prefix.is_empty() + && prefix.chars().all(|character| { + character.is_ascii_alphanumeric() || matches!(character, ' ' | '-') + }); + spelled.then_some(prefix) + } +} + /// A parsed doc comment. Repeated tags (`@param`) are kept in source order. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct DocComment { @@ -143,7 +241,7 @@ fn split_tag(content: &str) -> Option<(Tag, &str)> { #[cfg(test)] mod tests { - use super::{DocComment, Tag}; + use super::{DocComment, Tag, TagSpec}; #[test] fn gutter_and_delimiters_are_stripped() { @@ -200,6 +298,84 @@ mod tests { assert!(doc.tags().is_empty()); } + #[test] + fn an_entry_splits_into_a_tag_and_the_heading_after_its_first_space() { + assert_eq!( + TagSpec::parse("@module"), + TagSpec::bare(Tag::new("@module")) + ); + assert_eq!( + TagSpec::parse("@notice Client-side duties"), + TagSpec { + tag: Tag::new("@notice"), + heading: Some("Client-side duties".to_owned()), + } + ); + assert_eq!( + TagSpec::parse("@dev Notation ").heading.as_deref(), + Some("Notation") + ); + assert_eq!( + TagSpec::parse("@notice Security").to_string(), + "@notice Security" + ); + } + + #[test] + fn a_heading_is_well_formed_when_it_is_non_empty_and_carries_no_colon() { + assert!(TagSpec::parse("@module").has_well_formed_heading()); + assert!(TagSpec::parse("@notice Security").has_well_formed_heading()); + assert!(!TagSpec::parse("@notice ").has_well_formed_heading()); + assert!(!TagSpec::parse("@notice Security:").has_well_formed_heading()); + } + + #[test] + fn a_headed_entry_matches_only_the_occurrence_opening_with_its_heading() { + let doc = DocComment::parse( + "/**\n * @notice Privacy:\n * - Public, per tx.\n * @notice Security:\n * - Nonces.\n */", + ); + let privacy = TagSpec::parse("@notice Privacy"); + let gotchas = TagSpec::parse("@notice Gotchas"); + let bare = TagSpec::parse("@notice"); + + let matched: Vec = doc.tags().iter().map(|one| privacy.matches(one)).collect(); + assert_eq!(matched, [true, false]); + assert!(!doc.tags().iter().any(|one| gotchas.matches(one))); + assert!(doc.tags().iter().all(|one| bare.matches(one))); + } + + #[test] + fn an_entry_matches_the_comment_line_that_opens_its_block() { + let security = TagSpec::parse("@notice Security"); + + assert!(security.matches_line("@notice Security: nonces are spend-critical.")); + assert!(!security.matches_line("@notice Securityish: no.")); + assert!(!security.matches_line("@dev Security: wrong tag.")); + assert!(TagSpec::parse("@description").matches_line("@description Anything.")); + } + + #[test] + fn a_heading_is_the_value_up_to_its_first_colon() { + let doc = DocComment::parse( + "/**\n * @dev Notation:\n * @notice Client-side duties:\n * @param {T} a - A.\n * @description A note-based token: amounts\n */", + ); + let headings: Vec> = doc + .tags() + .iter() + .map(super::TagOccurrence::heading) + .collect(); + + assert_eq!( + headings, + [ + Some("Notation"), + Some("Client-side duties"), + None, + Some("A note-based token"), + ] + ); + } + #[test] fn a_single_line_comment_parses() { let doc = DocComment::parse("/** @description One liner. */"); diff --git a/crates/compact-lint/src/edit.rs b/crates/compact-lint/src/edit.rs index 139709d9..89e4d0a9 100644 --- a/crates/compact-lint/src/edit.rs +++ b/crates/compact-lint/src/edit.rs @@ -10,8 +10,12 @@ use std::path::{Path, PathBuf}; use thiserror::Error; use crate::diagnostic::Span; +use crate::doc::{Tag, TagSpec}; use crate::report::RuleId; +/// The tag the constraints annotation anchors itself on. +const DESCRIPTION_TAG: &str = "@description"; + /// One repair, carrying the rule it answers and the span its diagnostic underlines. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Edit { @@ -52,11 +56,12 @@ impl EditKind { /// One change to the lines of a doc comment. #[derive(Clone, Debug, PartialEq, Eq)] pub enum DocOp { - /// A `@tag value` line added after the last of `after` present, else at the top of the body. + /// A tag block added after the last of `after` present, else at the top of the body. InsertTag { - line: String, - /// Tags that precede this one in config order. - after: Vec, + /// The block's lines: a `@tag value` line, plus a placeholder line for a section. + lines: Vec, + /// Entries that precede this one in config order. + after: Vec, /// Untagged prose opening the body becomes this tag's value instead of the placeholder. adopts_prose: bool, }, @@ -82,6 +87,12 @@ pub enum DocOp { tag: String, value: String, }, + /// The tag blocks that match a listed entry, written back into their slots in config + /// order. + ReorderBlocks { + /// The template, required entries first, in the order it lists them. + entries: Vec, + }, } impl DocOp { @@ -89,7 +100,10 @@ impl DocOp { #[must_use] pub const fn is_safe(&self) -> bool { match self { - Self::RenameTag { .. } | Self::SetModuleName { .. } | Self::SetTagValue { .. } => true, + Self::RenameTag { .. } + | Self::SetModuleName { .. } + | Self::SetTagValue { .. } + | Self::ReorderBlocks { .. } => true, Self::InsertTag { .. } | Self::InsertConstraints(_) => false, } } @@ -234,12 +248,12 @@ fn render_doc(doc: &str, indent: usize, newline: &str, ops: &[&DocOp]) -> String for op in ops { if let DocOp::InsertTag { - line, + lines: inserted, after, adopts_prose, } = op { - insert_tag(&mut lines, &gutter, line, after, *adopts_prose); + insert_tag(&mut lines, &gutter, inserted, after, *adopts_prose); } } @@ -249,6 +263,14 @@ fn render_doc(doc: &str, indent: usize, newline: &str, ops: &[&DocOp]) -> String } } + // The order the template wants is decided on the finished comment, so a reorder runs + // over the lines every other op already wrote. + for op in ops { + if let DocOp::ReorderBlocks { entries } = op { + reorder_blocks(&mut lines, entries); + } + } + lines.join(newline) } @@ -267,14 +289,14 @@ fn expand(single: &str, margin: &str, gutter: &str) -> Vec { ] } -/// A tag line lands after the block of the last tag in `after` that is present, else at +/// A tag block lands after the block of the last entry in `after` that is present, else at /// the top of the body. With `adopts_prose`, untagged prose opening the body takes the /// tag instead of a new line going in. fn insert_tag( lines: &mut Vec, gutter: &str, - line: &str, - after: &[String], + inserted: &[String], + after: &[TagSpec], adopts_prose: bool, ) { let closer = lines.len().saturating_sub(1); @@ -282,14 +304,77 @@ fn insert_tag( if adopts_prose && let Some(first) = (1..closer).find(|index| !is_blank(&lines[*index])) && !starts_tag(content(&lines[first])) - && let Some((tag, _)) = line.split_once(' ') + && let Some((tag, _)) = inserted.first().and_then(|line| line.split_once(' ')) { lines[first] = format!("{gutter}{tag} {}", content(&lines[first])); return; } let at = tag_block_end(lines, closer, after).map_or(1.min(closer), |end| end + 1); - lines.insert(at, format!("{gutter}{line}")); + for (offset, line) in inserted.iter().enumerate() { + lines.insert(at + offset, format!("{gutter}{line}")); + } +} + +/// Blocks matching a listed entry are written back into their slots in config order. +/// Prose before the first tag, blocks no entry lists, and the blank lines separating the +/// slots all stay where they are. +fn reorder_blocks(lines: &mut Vec, entries: &[TagSpec]) { + let closer = lines.len().saturating_sub(1); + if closer < 2 { + return; + } + + let prose_end = (1..closer) + .find(|index| starts_tag(content(&lines[*index]))) + .unwrap_or(closer); + + // A block runs from its tag line over its continuations; the blank lines under it + // separate slots rather than belonging to what fills one. + let mut blocks: Vec> = Vec::new(); + let mut separators: Vec> = Vec::new(); + for line in lines.iter().take(closer).skip(prose_end) { + if starts_tag(content(line)) { + blocks.push(Vec::new()); + separators.push(Vec::new()); + } + match separators.last_mut() { + Some(separator) if is_blank(line) => separator.push(line.clone()), + _ => { + if let (Some(block), Some(separator)) = (blocks.last_mut(), separators.last_mut()) { + block.append(separator); + block.push(line.clone()); + } + } + } + } + + let mut slots: Vec = Vec::new(); + let mut listed: Vec<(usize, Vec)> = Vec::new(); + for (slot, block) in blocks.iter().enumerate() { + let position = block.first().and_then(|line| { + entries + .iter() + .position(|entry| entry.matches_line(content(line))) + }); + if let Some(position) = position { + slots.push(slot); + listed.push((position, block.clone())); + } + } + listed.sort_by_key(|(position, _)| *position); + + for (slot, (_, block)) in slots.iter().zip(listed) { + blocks[*slot] = block; + } + + let mut rebuilt: Vec = lines[..prose_end].to_vec(); + for (block, separator) in blocks.into_iter().zip(separators) { + rebuilt.extend(block); + rebuilt.extend(separator); + } + rebuilt.extend_from_slice(&lines[closer..]); + *lines = rebuilt; } /// The constraints line follows the `@description` block, or opens the body without one. @@ -315,17 +400,14 @@ fn insert_constraints(lines: &mut Vec, margin: &str, gutter: &str, body: /// The last line of the `@description` block: its tag line plus every continuation. fn description_end(lines: &[String], closer: usize) -> Option { - tag_block_end(lines, closer, &["@description".to_owned()]) + tag_block_end(lines, closer, &[TagSpec::bare(Tag::new(DESCRIPTION_TAG))]) } -/// The last line of the block opened by the last occurrence of any tag in `tags`. -fn tag_block_end(lines: &[String], closer: usize, tags: &[String]) -> Option { +/// The last line of the block opened by the last occurrence of any entry in `entries`. +fn tag_block_end(lines: &[String], closer: usize, entries: &[TagSpec]) -> Option { let start = (1..closer).rev().find(|index| { let text = content(&lines[*index]); - tags.iter().any(|tag| { - text.strip_prefix(tag.as_str()) - .is_some_and(|rest| rest.is_empty() || rest.starts_with(char::is_whitespace)) - }) + entries.iter().any(|entry| entry.matches_line(text)) })?; let mut end = start; @@ -422,6 +504,7 @@ mod tests { set_tag_value, }; use crate::diagnostic::Span; + use crate::doc::TagSpec; use crate::report::{Position, RuleId}; fn doc_edit(range: std::ops::Range, indent: usize, op: DocOp) -> Edit { @@ -435,12 +518,26 @@ mod tests { fn tag(line: &str, after: &[&str]) -> DocOp { DocOp::InsertTag { - line: line.to_owned(), - after: after.iter().map(ToString::to_string).collect(), + lines: vec![line.to_owned()], + after: after.iter().map(|entry| TagSpec::parse(entry)).collect(), adopts_prose: line.starts_with("@description"), } } + fn section(heading: &str, after: &[&str]) -> DocOp { + DocOp::InsertTag { + lines: vec![format!("{heading}:"), "TODO".to_owned()], + after: after.iter().map(|entry| TagSpec::parse(entry)).collect(), + adopts_prose: false, + } + } + + fn reorder(entries: &[&str]) -> DocOp { + DocOp::ReorderBlocks { + entries: entries.iter().map(|entry| TagSpec::parse(entry)).collect(), + } + } + fn rendered(doc: &str, indent: usize, ops: &[DocOp]) -> String { let borrowed: Vec<&DocOp> = ops.iter().collect(); render_doc(doc, indent, "\n", &borrowed) @@ -535,6 +632,55 @@ mod tests { ); } + #[test] + fn a_section_goes_in_as_a_heading_line_and_a_placeholder_under_it() { + let doc = "/**\n * @notice Privacy:\n * - Amounts stay private.\n * @dev Notation:\n * - `H(...)`: the digest.\n */"; + + assert_eq!( + rendered(doc, 0, &[section("@notice Security", &["@notice Privacy"])]), + "/**\n * @notice Privacy:\n * - Amounts stay private.\n * @notice Security:\n * TODO\n * @dev Notation:\n * - `H(...)`: the digest.\n */" + ); + } + + #[test] + fn a_section_lands_after_the_block_its_heading_names_not_the_last_of_its_tag() { + let doc = + "/**\n * @notice Privacy:\n * - Amounts.\n * @notice Scope:\n * - Notes only.\n */"; + + assert_eq!( + rendered(doc, 0, &[section("@notice Security", &["@notice Privacy"])]), + "/**\n * @notice Privacy:\n * - Amounts.\n * @notice Security:\n * TODO\n * @notice Scope:\n * - Notes only.\n */" + ); + } + + #[test] + fn listed_blocks_move_into_config_order_and_unlisted_ones_hold_their_slot() { + let doc = "/**\n * Prose first.\n * @notice Security:\n * - Nonces.\n *\n * @param {T} a - A.\n * @module Token\n * @notice Privacy:\n * - Amounts.\n */"; + + assert_eq!( + rendered( + doc, + 0, + &[reorder(&["@module", "@notice Privacy", "@notice Security"])] + ), + "/**\n * Prose first.\n * @module Token\n *\n * @param {T} a - A.\n * @notice Privacy:\n * - Amounts.\n * @notice Security:\n * - Nonces.\n */" + ); + } + + #[test] + fn a_comment_already_in_order_comes_back_unchanged() { + let doc = "/**\n * @module Token\n * @notice Privacy:\n * - Amounts.\n * @notice Security:\n * - Nonces.\n */"; + + assert_eq!( + rendered( + doc, + 0, + &[reorder(&["@module", "@notice Privacy", "@notice Security"])] + ), + doc + ); + } + #[test] fn a_single_line_doc_expands_before_a_tag_goes_in() { let doc = "/** @description Approved accounts. */"; diff --git a/crates/compact-lint/src/fix.rs b/crates/compact-lint/src/fix.rs index 45327e42..e220f5c3 100644 --- a/crates/compact-lint/src/fix.rs +++ b/crates/compact-lint/src/fix.rs @@ -5,12 +5,12 @@ use std::path::{Path, PathBuf}; use thiserror::Error; use crate::config::Config; -use crate::diagnostic::{Badge, Diagnostic, FixPreview, Level, capitalise}; -use crate::doc::Tag; +use crate::diagnostic::{Badge, Diagnostic, FixPreview, Level, Span, capitalise}; +use crate::doc::TagSpec; use crate::edit::{DocOp, Edit, EditKind, WriteError, apply, newline_of, write_atomically}; use crate::model::DeclKind; use crate::report::RuleId; -use crate::rules::{Issue, LintError, Linter}; +use crate::rules::{DocRef, Issue, LintError, Linter}; use crate::target::{self, TargetError}; /// The value written into an inserted constraints annotation. @@ -180,31 +180,35 @@ pub fn edit_for(issue: &Issue, config: &Config, newline: &str) -> Option { Issue::MissingTag { kind, - tag, + entry, name, doc, .. - } => Some(Edit { + } => Some(doc_edit( span, - rule: RuleId::MISSING_TAG, - message: format!("insert {tag}"), - kind: EditKind::Doc { - range: doc.range.clone(), - indent: doc.indent, - op: missing_tag_op(*kind, tag, name.as_deref(), config), - }, - }), + RuleId::MISSING_TAG, + format!("insert {entry}"), + doc, + missing_tag_op(*kind, entry, name.as_deref(), config), + )), - Issue::MissingConstraints { tag, doc, .. } => Some(Edit { + Issue::TagOrder { kind, doc, .. } => Some(doc_edit( span, - rule: RuleId::MISSING_CONSTRAINTS, - message: format!("insert {tag} {UNMEASURED}"), - kind: EditKind::Doc { - range: doc.range.clone(), - indent: doc.indent, - op: DocOp::InsertConstraints(format!("{tag} {UNMEASURED}")), + RuleId::TAG_ORDER, + "reorder the doc comment blocks".to_owned(), + doc, + DocOp::ReorderBlocks { + entries: config.kinds.get(*kind).entries().cloned().collect(), }, - }), + )), + + Issue::MissingConstraints { tag, doc, .. } => Some(doc_edit( + span, + RuleId::MISSING_CONSTRAINTS, + format!("insert {tag} {UNMEASURED}"), + doc, + DocOp::InsertConstraints(format!("{tag} {UNMEASURED}")), + )), Issue::ForbiddenTag { tag, @@ -213,20 +217,17 @@ pub fn edit_for(issue: &Issue, config: &Config, newline: &str) -> Option { .. } => { let replacement = config.rename_of(tag)?; - Some(Edit { + Some(doc_edit( span, - rule: RuleId::FORBIDDEN_TAG, - message: format!("rename {tag} to {replacement}"), - kind: EditKind::Doc { - range: doc.range.clone(), - indent: doc.indent, - op: DocOp::RenameTag { - line: *line_offset, - from: tag.to_string(), - to: replacement.to_string(), - }, + RuleId::FORBIDDEN_TAG, + format!("rename {tag} to {replacement}"), + doc, + DocOp::RenameTag { + line: *line_offset, + from: tag.to_string(), + to: replacement.to_string(), }, - }) + )) } Issue::ModuleName { @@ -234,48 +235,67 @@ pub fn edit_for(issue: &Issue, config: &Config, newline: &str) -> Option { line_offset, doc, .. - } => Some(Edit { + } => Some(doc_edit( span, - rule: RuleId::MODULE_NAME, - message: format!("set {MODULE_TAG} to `{name}`"), - kind: EditKind::Doc { - range: doc.range.clone(), - indent: doc.indent, - op: DocOp::SetModuleName { - line: *line_offset, - name: name.clone(), - }, + RuleId::MODULE_NAME, + format!("set {MODULE_TAG} to `{name}`"), + doc, + DocOp::SetModuleName { + line: *line_offset, + name: name.clone(), }, - }), + )), Issue::Parse { .. } + | Issue::UnknownSection { .. } | Issue::ConstraintsFormat { .. } | Issue::ConstraintsPlaceholder { .. } => None, } } -/// The tag line lands after the tags that precede it in config order; `@description` +/// One rewrite of the doc comment the issue points at. +fn doc_edit(span: Span, rule: RuleId, message: String, doc: &DocRef, op: DocOp) -> Edit { + Edit { + span, + rule, + message, + kind: EditKind::Doc { + range: doc.range.clone(), + indent: doc.indent, + op, + }, + } +} + +/// The block lands after the entries that precede it in template order, optional ones +/// included, so it follows whichever neighbour the comment carries; a bare `@description` /// adopts prose that opens the body. -fn missing_tag_op(kind: DeclKind, tag: &Tag, name: Option<&str>, config: &Config) -> DocOp { +fn missing_tag_op(kind: DeclKind, entry: &TagSpec, name: Option<&str>, config: &Config) -> DocOp { DocOp::InsertTag { - line: tag_line(tag, name, config), + lines: entry_lines(entry, name, config), after: config .kinds .get(kind) - .tags - .iter() - .take_while(|required| *required != tag) - .map(ToString::to_string) + .entries() + .take_while(|listed| *listed != entry) + .cloned() .collect(), - adopts_prose: tag.as_str() == DESCRIPTION_TAG, + adopts_prose: entry.heading.is_none() && entry.tag.as_str() == DESCRIPTION_TAG, } } +/// A section opens its own block, with the placeholder on the line under its heading. /// `@module` takes the declaration's own name; every other tag takes the placeholder. -fn tag_line(tag: &Tag, name: Option<&str>, config: &Config) -> String { - match name { - Some(name) if tag.as_str() == MODULE_TAG => format!("{tag} {name}"), - _ => format!("{tag} {}", config.fix.placeholder), +fn entry_lines(entry: &TagSpec, name: Option<&str>, config: &Config) -> Vec { + match (&entry.heading, name) { + (Some(heading), _) => vec![ + format!("{} {heading}:", entry.tag), + config.fix.placeholder.clone(), + ], + (None, Some(name)) if entry.tag.as_str() == MODULE_TAG => { + vec![format!("{} {name}", entry.tag)] + } + (None, _) => vec![format!("{} {}", entry.tag, config.fix.placeholder)], } } @@ -296,7 +316,7 @@ fn skeleton( .get(kind) .tags .iter() - .map(|tag| tag_line(tag, name, config)) + .flat_map(|entry| entry_lines(entry, name, config)) .collect(); if constraints { @@ -328,13 +348,13 @@ fn skeleton( mod tests { use super::skeleton; use crate::config::Config; - use crate::doc::Tag; + use crate::doc::TagSpec; use crate::model::DeclKind; fn config() -> Config { let mut config = Config::default(); - config.kinds.module.tags = vec![Tag::new("@module"), Tag::new("@description")]; - config.kinds.circuit.tags = vec![Tag::new("@description")]; + config.kinds.module.tags = vec![TagSpec::parse("@module"), TagSpec::parse("@description")]; + config.kinds.circuit.tags = vec![TagSpec::parse("@description")]; config } @@ -346,6 +366,21 @@ mod tests { ); } + #[test] + fn a_skeleton_gives_every_section_a_heading_line_and_a_placeholder_under_it() { + let mut config = config(); + config + .kinds + .module + .tags + .push(TagSpec::parse("@notice Privacy")); + + assert_eq!( + skeleton(DeclKind::Module, Some("Token"), false, &config, 0, "\n"), + "/**\n * @module Token\n * @description TODO\n * @notice Privacy:\n * TODO\n */\n" + ); + } + #[test] fn an_exported_circuit_skeleton_carries_the_constraints_line() { assert_eq!( diff --git a/crates/compact-lint/src/report.rs b/crates/compact-lint/src/report.rs index e27b5f42..9073ce51 100644 --- a/crates/compact-lint/src/report.rs +++ b/crates/compact-lint/src/report.rs @@ -9,6 +9,8 @@ pub struct RuleId(&'static str); impl RuleId { pub const MISSING_DOC: Self = Self("missing-doc"); pub const MISSING_TAG: Self = Self("missing-tag"); + pub const UNKNOWN_SECTION: Self = Self("unknown-section"); + pub const TAG_ORDER: Self = Self("tag-order"); pub const FORBIDDEN_TAG: Self = Self("forbidden-tag"); pub const MODULE_NAME: Self = Self("module-name"); pub const MISSING_CONSTRAINTS: Self = Self("missing-constraints"); @@ -23,9 +25,11 @@ impl RuleId { pub const FILL: Self = Self("fill"); /// Every rule a `[rules]` table can set a level for, in the order the README lists them. - pub const ALL: [Self; 11] = [ + pub const ALL: [Self; 13] = [ Self::MISSING_DOC, Self::MISSING_TAG, + Self::UNKNOWN_SECTION, + Self::TAG_ORDER, Self::FORBIDDEN_TAG, Self::MODULE_NAME, Self::MISSING_CONSTRAINTS, diff --git a/crates/compact-lint/src/rules.rs b/crates/compact-lint/src/rules.rs index 4c5a30cc..1fe0561b 100644 --- a/crates/compact-lint/src/rules.rs +++ b/crates/compact-lint/src/rules.rs @@ -11,7 +11,7 @@ use tree_sitter::{Node, Parser}; use crate::config::{Config, DocsPolicy}; use crate::diagnostic::{Diagnostic, Level, Span, sentence}; -use crate::doc::Tag; +use crate::doc::{Tag, TagSpec}; use crate::model::{DeclKind, Declaration, declarations}; use crate::report::{Position, RuleId}; @@ -79,11 +79,26 @@ pub enum Issue { end: Position, subject: String, kind: DeclKind, - tag: Tag, + entry: TagSpec, /// The declaration's name, which `@module` takes as its value. name: Option, doc: DocRef, }, + UnknownSection { + position: Position, + kind: DeclKind, + tag: Tag, + heading: String, + }, + TagOrder { + position: Position, + kind: DeclKind, + /// The entry at the occurrence that breaks the order. + entry: TagSpec, + /// The entry the template orders after it, seen earlier in the comment. + previous: TagSpec, + doc: DocRef, + }, ForbiddenTag { position: Position, tag: Tag, @@ -125,6 +140,8 @@ impl Issue { Self::Parse { position, .. } | Self::MissingDoc { position, .. } | Self::MissingTag { position, .. } + | Self::UnknownSection { position, .. } + | Self::TagOrder { position, .. } | Self::ForbiddenTag { position, .. } | Self::ModuleName { position, .. } | Self::MissingConstraints { position, .. } @@ -139,6 +156,8 @@ impl Issue { Self::Parse { .. } => RuleId::PARSE, Self::MissingDoc { .. } => RuleId::MISSING_DOC, Self::MissingTag { .. } => RuleId::MISSING_TAG, + Self::UnknownSection { .. } => RuleId::UNKNOWN_SECTION, + Self::TagOrder { .. } => RuleId::TAG_ORDER, Self::ForbiddenTag { .. } => RuleId::FORBIDDEN_TAG, Self::ModuleName { .. } => RuleId::MODULE_NAME, Self::MissingConstraints { .. } => RuleId::MISSING_CONSTRAINTS, @@ -161,10 +180,22 @@ impl Issue { } } Self::MissingDoc { subject, .. } => format!("{subject} has no doc comment"), - Self::MissingTag { subject, tag, .. } - | Self::MissingConstraints { subject, tag, .. } => { + Self::MissingTag { subject, entry, .. } => match entry.heading { + Some(_) => format!("{subject} doc comment has no `{entry}` section"), + None => format!("{subject} doc comment has no {entry}"), + }, + Self::MissingConstraints { subject, tag, .. } => { format!("{subject} doc comment has no {tag}") } + Self::UnknownSection { tag, heading, .. } => { + format!("`{tag} {heading}` is not a section the template lists") + } + Self::TagOrder { + entry, previous, .. + } => format!( + "`{previous}` comes before `{entry}`; the template orders {} first", + entry.label() + ), Self::ForbiddenTag { tag, .. } => format!("forbidden tag {tag}"), Self::ModuleName { documented, name, .. @@ -189,9 +220,17 @@ impl Issue { Self::MissingDoc { .. } => { "Add a doc comment above it, or run compact-lint fix.".to_owned() } - Self::MissingTag { tag, .. } => { - format!("Add {tag} to the doc comment, or run compact-lint fix.") + Self::MissingTag { entry, .. } => match &entry.heading { + Some(heading) => format!( + "Add a {} {heading}: section, or run compact-lint fix.", + entry.tag + ), + None => format!("Add {entry} to the doc comment, or run compact-lint fix."), + }, + Self::UnknownSection { kind, .. } => { + format!("Add it to kinds.{kind}.sections, or fold it into a listed section.") } + Self::TagOrder { .. } => "Run compact-lint fix to reorder the blocks.".to_owned(), Self::ForbiddenTag { tag, .. } => match config.rename_of(tag) { Some(replacement) => format!("Rename it to {replacement}."), None => "Remove it from the doc comment.".to_owned(), @@ -222,6 +261,18 @@ impl Issue { | Self::ConstraintsPlaceholder { position, tag, .. } => { Span::columns(*position, tag.as_str().len()) } + Self::UnknownSection { + position, + tag, + heading, + .. + } => Span::columns(*position, heading_width(tag, Some(heading))), + Self::TagOrder { + position, entry, .. + } => Span::columns( + *position, + heading_width(&entry.tag, entry.heading.as_deref()), + ), Self::ModuleName { position, .. } => Span::columns(*position, MODULE_TAG.len()), } } @@ -235,6 +286,14 @@ impl Issue { } } +/// The tag token, and for a section the heading and the colon closing it. +fn heading_width(tag: &Tag, heading: Option<&str>) -> usize { + match heading { + Some(heading) => tag.as_str().len() + " ".len() + heading.len() + ":".len(), + None => tag.as_str().len(), + } +} + /// A reusable parser plus the rules that run over its trees. pub struct Linter { parser: Parser, @@ -388,22 +447,92 @@ fn check_declaration(declaration: &Declaration, config: &Config, issues: &mut Ve } for required in &kind_config.tags { - if !attached.comment.has(required) { + if !attached + .comment + .tags() + .iter() + .any(|occurrence| required.matches(occurrence)) + { issues.push(Issue::MissingTag { position: declaration.position, end: declaration.end, subject: subject(declaration), kind: declaration.kind, - tag: required.clone(), + entry: required.clone(), name: declaration.name.clone(), doc: doc.clone(), }); } } + check_sections(declaration, &doc, config, issues); check_constraints(declaration, &doc, config, issues); } +/// Headings the template does not list, and the order the listed entries appear in. +fn check_sections( + declaration: &Declaration, + doc: &DocRef, + config: &Config, + issues: &mut Vec, +) { + let Some(attached) = declaration.doc.as_ref() else { + return; + }; + let kind_config = config.kinds.get(declaration.kind); + let template: Vec<&TagSpec> = kind_config.entries().collect(); + + for occurrence in attached.comment.tags() { + let Some(heading) = occurrence.heading() else { + continue; + }; + // The rule is gated per tag: a tag the config heads nowhere is left alone. + let mut headed = kind_config + .tags + .iter() + .chain(kind_config.sections.iter()) + .filter(|entry| entry.tag == occurrence.tag && entry.heading.is_some()) + .peekable(); + if headed.peek().is_none() || headed.any(|entry| entry.label() == heading) { + continue; + } + + issues.push(Issue::UnknownSection { + position: attached.tag_position(occurrence), + kind: declaration.kind, + tag: occurrence.tag.clone(), + heading: heading.to_owned(), + }); + } + + let mut highest: Option<(usize, &TagSpec)> = None; + for occurrence in attached.comment.tags() { + let Some((index, entry)) = template + .iter() + .copied() + .enumerate() + .find(|(_, entry)| entry.matches(occurrence)) + else { + continue; + }; + + match highest { + Some((top, previous)) if index < top => { + issues.push(Issue::TagOrder { + position: attached.tag_position(occurrence), + kind: declaration.kind, + entry: entry.clone(), + previous: previous.clone(), + doc: doc.clone(), + }); + return; + } + Some((top, _)) if index == top => {} + _ => highest = Some((index, entry)), + } + } +} + /// `@module ` must name the module it documents. fn check_module_name(declaration: &Declaration, doc: &DocRef, issues: &mut Vec) { let tag = Tag::new(MODULE_TAG); @@ -546,7 +675,7 @@ mod tests { use crate::config::{Config, DocsPolicy}; use crate::diagnostic::Level; use crate::diagnostic::sentence; - use crate::doc::Tag; + use crate::doc::{Tag, TagSpec}; use crate::report::RuleId; use std::path::Path; @@ -572,7 +701,25 @@ mod tests { fn circuit_config() -> Config { let mut config = Config::default(); - config.kinds.circuit.tags = vec![Tag::new("@description")]; + config.kinds.circuit.tags = vec![TagSpec::parse("@description")]; + config + } + + /// A module template of two required sections, with an optional one between them. + fn template_config() -> Config { + let mut config = Config::default(); + config.kinds.module.docs = DocsPolicy::All; + config.kinds.module.tags = vec![ + TagSpec::parse("@module"), + TagSpec::parse("@notice Privacy"), + TagSpec::parse("@notice Security"), + ]; + config.kinds.module.sections = vec![ + TagSpec::parse("@module"), + TagSpec::parse("@notice Privacy"), + TagSpec::parse("@dev Notation"), + TagSpec::parse("@notice Security"), + ]; config } @@ -621,6 +768,56 @@ mod tests { ); } + #[test] + fn a_headed_entry_absent_from_the_comment_reports_the_section() { + let source = "/**\n * @module M\n * @notice Privacy:\n * - Amounts.\n */\nmodule M {\n}\n"; + + assert_eq!( + reported(source, &template_config()), + ["6:1 missing-tag Module `M` doc comment has no `@notice Security` section."] + ); + } + + #[test] + fn a_heading_the_template_does_not_list_reports_unknown_section() { + let source = "/**\n * @module M\n * @notice Privacy:\n * - Amounts.\n * @notice Security:\n * - Nonces.\n * @notice Gotchas:\n * - None.\n */\nmodule M {\n}\n"; + + assert_eq!( + reported(source, &template_config()), + ["7:4 unknown-section `@notice Gotchas` is not a section the template lists."] + ); + } + + #[test] + fn a_heading_on_a_tag_the_template_heads_nowhere_is_left_alone() { + let mut config = template_config(); + config.kinds.module.tags = vec![TagSpec::parse("@description")]; + config.kinds.module.sections = Vec::new(); + let source = + "/**\n * @description A note-based token: amounts stay private.\n */\nmodule M {\n}\n"; + + assert!(reported(source, &config).is_empty()); + } + + #[test] + fn listed_entries_out_of_config_order_report_tag_order_once() { + let source = "/**\n * @module M\n * @notice Security:\n * - Nonces.\n * @notice Privacy:\n * - Amounts.\n * @dev Notation:\n * - `H`.\n */\nmodule M {\n}\n"; + + assert_eq!( + reported(source, &template_config()), + [ + "5:4 tag-order `@notice Security` comes before `@notice Privacy`; the template orders Privacy first." + ] + ); + } + + #[test] + fn a_tag_no_entry_lists_is_ignored_by_the_order_check() { + let source = "/**\n * @module M\n * @notice Privacy:\n * - Amounts.\n * @param {T} a - A.\n * @notice Security:\n * - Nonces.\n */\nmodule M {\n}\n"; + + assert!(reported(source, &template_config()).is_empty()); + } + #[test] fn a_declaration_span_ends_at_its_name() { let source = "export module M {\n}\n"; diff --git a/crates/compact-lint/tests/check.rs b/crates/compact-lint/tests/check.rs index 230d6561..422f88a3 100644 --- a/crates/compact-lint/tests/check.rs +++ b/crates/compact-lint/tests/check.rs @@ -101,6 +101,30 @@ fn a_doc_comment_without_a_required_tag_reports_missing_tag() { assert_case("missing-tag", &[], EXIT_FINDINGS); } +#[test] +fn a_doc_comment_without_a_required_section_names_it_in_the_finding() { + assert_case("sections-missing", &[], EXIT_FINDINGS); +} + +#[test] +fn a_heading_the_template_does_not_list_warns_only_where_the_tag_has_headings() { + assert_case("unknown-section", &[], 0); + + let (_, stdout, stderr) = run("unknown-section", &[]); + assert!(!stdout.contains("@description"), "{stdout}"); + assert!(stderr.ends_with("Found 1 warning.\n"), "{stderr}"); +} + +#[test] +fn listed_entries_out_of_template_order_report_tag_order() { + assert_case("tag-order", &[], EXIT_FINDINGS); +} + +#[test] +fn a_module_following_the_example_template_reports_nothing() { + assert_case("template-clean", &[], 0); +} + #[test] fn a_forbidden_tag_reports_wherever_it_appears() { assert_case("forbidden-tag", &[], EXIT_FINDINGS); diff --git a/crates/compact-lint/tests/fix.rs b/crates/compact-lint/tests/fix.rs index 96c7693a..e5e382c5 100644 --- a/crates/compact-lint/tests/fix.rs +++ b/crates/compact-lint/tests/fix.rs @@ -153,6 +153,11 @@ fn a_required_tag_goes_into_the_comment_that_lacks_it() { assert_case("missing-tag"); } +#[test] +fn sections_are_inserted_by_heading_and_the_blocks_come_back_in_template_order() { + assert_case("sections"); +} + #[test] fn the_constraints_annotation_follows_the_description_block() { assert_case("constraints"); @@ -173,6 +178,22 @@ fn a_crlf_source_keeps_its_line_endings() { assert_case("crlf"); } +#[test] +fn a_second_fix_leaves_the_reordered_sections_byte_for_byte() { + let directory = work("sections"); + let root = directory.path(); + + let (_, _) = run(root, &["fix"]); + let once = sources(root); + + let (code, stdout) = run(root, &["fix"]); + + assert_eq!(stdout, ""); + assert_eq!(code, 0); + assert_eq!(sources(root), once); + assert_eq!(once, sources(&case("sections").join("after"))); +} + #[test] fn nothing_fixable_writes_nothing_and_exits_zero() { let directory = work("unfixable"); diff --git a/crates/compact-lint/tests/fixtures/fix-sections/after/Missing.compact b/crates/compact-lint/tests/fixtures/fix-sections/after/Missing.compact new file mode 100644 index 00000000..d8087b39 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-sections/after/Missing.compact @@ -0,0 +1,16 @@ +pragma language_version >= 0.23.0; + +/** + * @module Missing + * @description A module whose header stops before its security section. + * + * @notice Privacy: + * - Amounts stay private. + * + * @dev Notation: + * - `H(...)`: a `Bytes<32>` digest. + * @notice Security: + * TODO + */ +export module Missing { +} diff --git a/crates/compact-lint/tests/fixtures/fix-sections/after/Order.compact b/crates/compact-lint/tests/fixtures/fix-sections/after/Order.compact new file mode 100644 index 00000000..cabe8099 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-sections/after/Order.compact @@ -0,0 +1,16 @@ +pragma language_version >= 0.23.0; + +/** + * @module Order + * @description A module whose sections run out of template order. + * + * @notice Privacy: + * - Amounts stay private. + * + * @see The compatibility suite pins the wire format. + * + * @notice Security: + * - Nonces are spend-critical. + */ +export module Order { +} diff --git a/crates/compact-lint/tests/fixtures/fix-sections/after/Skeleton.compact b/crates/compact-lint/tests/fixtures/fix-sections/after/Skeleton.compact new file mode 100644 index 00000000..13c6f809 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-sections/after/Skeleton.compact @@ -0,0 +1,12 @@ +pragma language_version >= 0.23.0; + +/** + * @module Skeleton + * @description TODO + * @notice Privacy: + * TODO + * @notice Security: + * TODO + */ +export module Skeleton { +} diff --git a/crates/compact-lint/tests/fixtures/fix-sections/before/Missing.compact b/crates/compact-lint/tests/fixtures/fix-sections/before/Missing.compact new file mode 100644 index 00000000..3eccd42e --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-sections/before/Missing.compact @@ -0,0 +1,14 @@ +pragma language_version >= 0.23.0; + +/** + * @module Missing + * @description A module whose header stops before its security section. + * + * @notice Privacy: + * - Amounts stay private. + * + * @dev Notation: + * - `H(...)`: a `Bytes<32>` digest. + */ +export module Missing { +} diff --git a/crates/compact-lint/tests/fixtures/fix-sections/before/Order.compact b/crates/compact-lint/tests/fixtures/fix-sections/before/Order.compact new file mode 100644 index 00000000..ab6f1592 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-sections/before/Order.compact @@ -0,0 +1,16 @@ +pragma language_version >= 0.23.0; + +/** + * @module Order + * @description A module whose sections run out of template order. + * + * @notice Security: + * - Nonces are spend-critical. + * + * @see The compatibility suite pins the wire format. + * + * @notice Privacy: + * - Amounts stay private. + */ +export module Order { +} diff --git a/crates/compact-lint/tests/fixtures/fix-sections/before/Skeleton.compact b/crates/compact-lint/tests/fixtures/fix-sections/before/Skeleton.compact new file mode 100644 index 00000000..7e9d2563 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-sections/before/Skeleton.compact @@ -0,0 +1,4 @@ +pragma language_version >= 0.23.0; + +export module Skeleton { +} diff --git a/crates/compact-lint/tests/fixtures/fix-sections/compact.toml b/crates/compact-lint/tests/fixtures/fix-sections/compact.toml new file mode 100644 index 00000000..110df547 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-sections/compact.toml @@ -0,0 +1,16 @@ +[lint] +include = ["**/*.compact"] + +[lint.kinds.module] +docs = "all" +tags = ["@module", "@description", "@notice Privacy", "@notice Security"] +sections = [ + "@module", + "@description", + "@notice Privacy", + "@dev Notation", + "@notice Security", +] + +[lint.kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/fix-sections/expected-dry-run.txt b/crates/compact-lint/tests/fixtures/fix-sections/expected-dry-run.txt new file mode 100644 index 00000000..f86ba901 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-sections/expected-dry-run.txt @@ -0,0 +1,61 @@ +Missing.compact:13:1 lint/missing-tag FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Module `Missing` doc comment has no `@notice Security` section. + + 11 β”‚ * - `H(...)`: a `Bytes<32>` digest. + 12 β”‚ */ + > 13 β”‚ export module Missing { + β”‚ ^^^^^^^^^^^^^^^^^^^^^ + 14 β”‚ } + + i Unsafe fix: Insert @notice Security + + 12 β”‚ + Β·*Β·@noticeΒ·Security: + 13 β”‚ + Β·*Β·TODO + +Order.compact:12:4 lint/tag-order FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i `@notice Security` comes before `@notice Privacy`; the template orders Privacy first. + + 10 β”‚ * @see The compatibility suite pins the wire format. + 11 β”‚ * + > 12 β”‚ * @notice Privacy: + β”‚ ^^^^^^^^^^^^^^^^ + 13 β”‚ * - Amounts stay private. + 14 β”‚ */ + + i Safe fix: Reorder the doc comment blocks + + 7 β”‚ - Β·*Β·@noticeΒ·Security: + 8 β”‚ - Β·*Β·-Β·NoncesΒ·areΒ·spend-critical. + 7 β”‚ + Β·*Β·@noticeΒ·Privacy: + 8 β”‚ + Β·*Β·-Β·AmountsΒ·stayΒ·private. + 9 9 β”‚ * + 10 10 β”‚ * @see The compatibility suite pins the wire format. + 11 11 β”‚ * + 12 β”‚ - Β·*Β·@noticeΒ·Privacy: + 13 β”‚ - Β·*Β·-Β·AmountsΒ·stayΒ·private. + 12 β”‚ + Β·*Β·@noticeΒ·Security: + 13 β”‚ + Β·*Β·-Β·NoncesΒ·areΒ·spend-critical. + +Skeleton.compact:3:1 lint/missing-doc FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Module `Skeleton` has no doc comment. + + 1 β”‚ pragma language_version >= 0.23.0; + 2 β”‚ + > 3 β”‚ export module Skeleton { + β”‚ ^^^^^^^^^^^^^^^^^^^^^^ + 4 β”‚ } + + i Unsafe fix: Insert a doc skeleton for module `Skeleton` + + 3 β”‚ + /** + 4 β”‚ + Β·*Β·@moduleΒ·Skeleton + 5 β”‚ + Β·*Β·@descriptionΒ·TODO + 6 β”‚ + Β·*Β·@noticeΒ·Privacy: + 7 β”‚ + Β·*Β·TODO + 8 β”‚ + Β·*Β·@noticeΒ·Security: + 9 β”‚ + Β·*Β·TODO + 10 β”‚ + Β·*/ + diff --git a/crates/compact-lint/tests/fixtures/fix-sections/expected.txt b/crates/compact-lint/tests/fixtures/fix-sections/expected.txt new file mode 100644 index 00000000..a0327340 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-sections/expected.txt @@ -0,0 +1,42 @@ +Missing.compact:13:1 lint/missing-tag FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Module `Missing` doc comment has no `@notice Security` section. + + i Applied fix: Insert @notice Security + + 12 β”‚ + Β·*Β·@noticeΒ·Security: + 13 β”‚ + Β·*Β·TODO + +Order.compact:12:4 lint/tag-order FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i `@notice Security` comes before `@notice Privacy`; the template orders Privacy first. + + i Applied fix: Reorder the doc comment blocks + + 7 β”‚ - Β·*Β·@noticeΒ·Security: + 8 β”‚ - Β·*Β·-Β·NoncesΒ·areΒ·spend-critical. + 7 β”‚ + Β·*Β·@noticeΒ·Privacy: + 8 β”‚ + Β·*Β·-Β·AmountsΒ·stayΒ·private. + 9 9 β”‚ * + 10 10 β”‚ * @see The compatibility suite pins the wire format. + 11 11 β”‚ * + 12 β”‚ - Β·*Β·@noticeΒ·Privacy: + 13 β”‚ - Β·*Β·-Β·AmountsΒ·stayΒ·private. + 12 β”‚ + Β·*Β·@noticeΒ·Security: + 13 β”‚ + Β·*Β·-Β·NoncesΒ·areΒ·spend-critical. + +Skeleton.compact:3:1 lint/missing-doc FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Module `Skeleton` has no doc comment. + + i Applied fix: Insert a doc skeleton for module `Skeleton` + + 3 β”‚ + /** + 4 β”‚ + Β·*Β·@moduleΒ·Skeleton + 5 β”‚ + Β·*Β·@descriptionΒ·TODO + 6 β”‚ + Β·*Β·@noticeΒ·Privacy: + 7 β”‚ + Β·*Β·TODO + 8 β”‚ + Β·*Β·@noticeΒ·Security: + 9 β”‚ + Β·*Β·TODO + 10 β”‚ + Β·*/ + diff --git a/crates/compact-lint/tests/fixtures/sections-missing/Sections.compact b/crates/compact-lint/tests/fixtures/sections-missing/Sections.compact new file mode 100644 index 00000000..69b4da13 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/sections-missing/Sections.compact @@ -0,0 +1,14 @@ +pragma language_version >= 0.23.0; + +/** + * @module Sections + * @description A module whose header stops before its security section. + * + * @notice Privacy: + * - Amounts stay private. + * + * @dev Notation: + * - `H(...)`: a `Bytes<32>` digest. + */ +export module Sections { +} diff --git a/crates/compact-lint/tests/fixtures/sections-missing/compact.toml b/crates/compact-lint/tests/fixtures/sections-missing/compact.toml new file mode 100644 index 00000000..3432db9c --- /dev/null +++ b/crates/compact-lint/tests/fixtures/sections-missing/compact.toml @@ -0,0 +1,13 @@ +[lint] +include = ["**/*.compact"] + +[lint.kinds.module] +docs = "all" +tags = ["@module", "@description", "@notice Privacy", "@notice Security"] +sections = [ + "@module", + "@description", + "@notice Privacy", + "@dev Notation", + "@notice Security", +] diff --git a/crates/compact-lint/tests/fixtures/sections-missing/expected.txt b/crates/compact-lint/tests/fixtures/sections-missing/expected.txt new file mode 100644 index 00000000..288e525b --- /dev/null +++ b/crates/compact-lint/tests/fixtures/sections-missing/expected.txt @@ -0,0 +1,17 @@ +Sections.compact:13:1 lint/missing-tag FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + Γ— Module `Sections` doc comment has no `@notice Security` section. + + 11 β”‚ * - `H(...)`: a `Bytes<32>` digest. + 12 β”‚ */ + > 13 β”‚ export module Sections { + β”‚ ^^^^^^^^^^^^^^^^^^^^^^ + 14 β”‚ } + + i Add a @notice Security: section, or run compact-lint fix. + + i Unsafe fix: Insert @notice Security + + 12 β”‚ + Β·*Β·@noticeΒ·Security: + 13 β”‚ + Β·*Β·TODO + diff --git a/crates/compact-lint/tests/fixtures/tag-order/Ordered.compact b/crates/compact-lint/tests/fixtures/tag-order/Ordered.compact new file mode 100644 index 00000000..bbfb946e --- /dev/null +++ b/crates/compact-lint/tests/fixtures/tag-order/Ordered.compact @@ -0,0 +1,14 @@ +pragma language_version >= 0.23.0; + +/** + * @module Ordered + * @description A module whose security section runs ahead of its privacy one. + * + * @notice Security: + * - Nonces are spend-critical. + * + * @notice Privacy: + * - Amounts stay private. + */ +export module Ordered { +} diff --git a/crates/compact-lint/tests/fixtures/tag-order/compact.toml b/crates/compact-lint/tests/fixtures/tag-order/compact.toml new file mode 100644 index 00000000..3432db9c --- /dev/null +++ b/crates/compact-lint/tests/fixtures/tag-order/compact.toml @@ -0,0 +1,13 @@ +[lint] +include = ["**/*.compact"] + +[lint.kinds.module] +docs = "all" +tags = ["@module", "@description", "@notice Privacy", "@notice Security"] +sections = [ + "@module", + "@description", + "@notice Privacy", + "@dev Notation", + "@notice Security", +] diff --git a/crates/compact-lint/tests/fixtures/tag-order/expected.txt b/crates/compact-lint/tests/fixtures/tag-order/expected.txt new file mode 100644 index 00000000..4083b3b7 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/tag-order/expected.txt @@ -0,0 +1,24 @@ +Ordered.compact:10:4 lint/tag-order FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + Γ— `@notice Security` comes before `@notice Privacy`; the template orders Privacy first. + + 8 β”‚ * - Nonces are spend-critical. + 9 β”‚ * + > 10 β”‚ * @notice Privacy: + β”‚ ^^^^^^^^^^^^^^^^ + 11 β”‚ * - Amounts stay private. + 12 β”‚ */ + + i Run compact-lint fix to reorder the blocks. + + i Safe fix: Reorder the doc comment blocks + + 7 β”‚ + Β·*Β·@noticeΒ·Privacy: + 8 β”‚ + Β·*Β·-Β·AmountsΒ·stayΒ·private. + 9 β”‚ + Β·* + 7 10 β”‚ * @notice Security: + 8 11 β”‚ * - Nonces are spend-critical. + 9 β”‚ - Β·* + 10 β”‚ - Β·*Β·@noticeΒ·Privacy: + 11 β”‚ - Β·*Β·-Β·AmountsΒ·stayΒ·private. + diff --git a/crates/compact-lint/tests/fixtures/template-clean/Template.compact b/crates/compact-lint/tests/fixtures/template-clean/Template.compact new file mode 100644 index 00000000..84298076 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/template-clean/Template.compact @@ -0,0 +1,51 @@ +pragma language_version >= 0.23.0; + +/** + * @module Template + * @description + * A tally kept as one public counter, with the caller hidden. + * + * @dev Notation: + * - `tally`: the public counter this module owns. + * + * @dev Compatibility: + * The wire format is the counter alone; nothing here is versioned. + * + * @notice Privacy: + * - Public: the entry point, and the counter itself. + * - Private: which account called, and how often. + * + * @notice Security: + * - `bump` is ungated: re-exporting it is a permissionless write. + * - A failed assert rejects the whole tx and the caller pays no fee. + * + * @notice Concurrency: + * - `increment` commutes, so two calls in one block both land. + * + * @notice Scope: + * Counting only: no roles, no initialization, no supply. + * + * @notice Scalability: + * - State growth is one counter, whatever the number of calls. + * + * @dev Performance: + * - Cost is one counter write per call; per-circuit `k` and rows are on each + * `@constraints` line. + */ +export module Template { + import CompactStandardLibrary; + + /** + * @description The number of bumps the module has seen. + */ + export ledger tally: Counter; + + /** + * @description Adds one to the tally. + * @constraints k=10, rows=626 + * @returns {[]} Empty tuple. + */ + export circuit bump(): [] { + tally.increment(1); + } +} diff --git a/crates/compact-lint/tests/fixtures/template-clean/compact.toml b/crates/compact-lint/tests/fixtures/template-clean/compact.toml new file mode 100644 index 00000000..6c3bc72b --- /dev/null +++ b/crates/compact-lint/tests/fixtures/template-clean/compact.toml @@ -0,0 +1,57 @@ +# The kind tables of examples/compact.toml, with the include glob pointed at the case. +[lint] +include = ["**/*.compact"] + +[lint.constraints] +tag = "@constraints" + +[lint.tags] +forbid = ["@return"] +rename = { "@return" = "@returns" } + +[lint.kinds.module] +docs = "all" +tags = [ + "@module", + "@description", + "@notice Privacy", + "@notice Security", + "@notice Concurrency", + "@notice Scope", + "@dev Performance", +] +sections = [ + "@module", + "@description", + "@dev Notation", + "@dev Derivations", + "@dev Parameterization", + "@dev Compatibility", + "@notice Privacy", + "@notice Security", + "@notice Concurrency", + "@notice Scope", + "@notice Client-side duties", + "@notice Scalability", + "@dev Performance", + "@dev Composition", +] + +[lint.kinds.circuit] +tags = ["@description"] + +[lint.kinds.ledger] +tags = ["@description"] + +[lint.kinds.witness] +docs = "all" +tags = ["@description"] + +[lint.kinds.struct] +tags = ["@description"] + +[lint.kinds.enum] +tags = ["@description"] + +[lint.kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/template-clean/expected.txt b/crates/compact-lint/tests/fixtures/template-clean/expected.txt new file mode 100644 index 00000000..e69de29b diff --git a/crates/compact-lint/tests/fixtures/unknown-section/Headings.compact b/crates/compact-lint/tests/fixtures/unknown-section/Headings.compact new file mode 100644 index 00000000..21571cdf --- /dev/null +++ b/crates/compact-lint/tests/fixtures/unknown-section/Headings.compact @@ -0,0 +1,23 @@ +pragma language_version >= 0.23.0; + +/** + * @module Headings + * @description A module carrying one section the template does not list. + * + * @notice Privacy: + * - Amounts stay private. + * + * @notice Gotchas: + * - The nonce is spend-critical. + * + * @dev Notation: + * - `H(...)`: a `Bytes<32>` digest. + */ +export module Headings { + /** + * @description A helper: it doubles its argument. + */ + export pure circuit double(value: Uint<8>): Uint<16> { + return value as Uint<16> * 2; + } +} diff --git a/crates/compact-lint/tests/fixtures/unknown-section/compact.toml b/crates/compact-lint/tests/fixtures/unknown-section/compact.toml new file mode 100644 index 00000000..e17a6b57 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/unknown-section/compact.toml @@ -0,0 +1,11 @@ +[lint] +include = ["**/*.compact"] + +[lint.kinds.module] +docs = "all" +tags = ["@module", "@description", "@notice Privacy"] +sections = ["@module", "@description", "@notice Privacy", "@dev Notation"] + +# No headed `@description` entry, so a heading on that tag is nobody's business. +[lint.kinds.circuit] +tags = ["@description"] diff --git a/crates/compact-lint/tests/fixtures/unknown-section/expected.txt b/crates/compact-lint/tests/fixtures/unknown-section/expected.txt new file mode 100644 index 00000000..63418c41 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/unknown-section/expected.txt @@ -0,0 +1,13 @@ +Headings.compact:10:4 lint/unknown-section ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + ! `@notice Gotchas` is not a section the template lists. + + 8 β”‚ * - Amounts stay private. + 9 β”‚ * + > 10 β”‚ * @notice Gotchas: + β”‚ ^^^^^^^^^^^^^^^^ + 11 β”‚ * - The nonce is spend-critical. + 12 β”‚ * + + i Add it to kinds.module.sections, or fold it into a listed section. + From fbf050ad883404484643d79eac9e8249d8e1e71b Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Tue, 15 Sep 2026 17:28:49 +0200 Subject: [PATCH 13/56] feat(compact-lint): add --timings phase breakdown A run on 39 files takes about 3 s, and nothing in the output said that 97% of it is the `compact format --check` subprocess. `--timings` prints a per-phase wall-clock table on stderr after the summary, longest phase first with a detail column naming what it worked on, so a slow run points at its own cause. Phases are recorded unconditionally and printed only under the flag. The total is the sum of the phases, not the run's wall clock. --- crates/compact-lint/README.md | 23 +++ crates/compact-lint/src/check.rs | 72 +++++++-- crates/compact-lint/src/diagnostic.rs | 29 +++- crates/compact-lint/src/fill.rs | 21 ++- crates/compact-lint/src/fix.rs | 32 +++- crates/compact-lint/src/lib.rs | 1 + crates/compact-lint/src/main.rs | 75 +++++++-- crates/compact-lint/src/timing.rs | 217 ++++++++++++++++++++++++++ crates/compact-lint/tests/check.rs | 11 ++ 9 files changed, 444 insertions(+), 37 deletions(-) create mode 100644 crates/compact-lint/src/timing.rs diff --git a/crates/compact-lint/README.md b/crates/compact-lint/README.md index cb1b218b..5eb62af8 100644 --- a/crates/compact-lint/README.md +++ b/crates/compact-lint/README.md @@ -42,6 +42,7 @@ compact-lint fill-constraints [PATHS]... [--config ] [--dry-run] [--no-com - `--max-diagnostics ` β€” diagnostics shown before the rest are only counted, default `20`. - `--colors ` β€” default: colour when stdout is a TTY and `NO_COLOR` is unset. +- `--timings` β€” print a per-phase wall-clock breakdown under the summary. ## Output @@ -85,6 +86,28 @@ Checked 1 file in 2ms. No fixes applied. Found 3 errors. ``` +## Performance + +- The lint pass is tens of milliseconds for a repo of a few dozen files. +- `compact format --check` dominates a full run; the cost is the compiler's, not the + linter's. +- `--timings` prints the breakdown that shows it, longest phase first. +- `--no-format`, or `format = "off"` in `[lint.rules]`, drops that phase. + +``` +Timings + format check 2.7s 98.4% compact format --check, 39 files, 1 process + fix previews 30ms 1.1% 481 previews + parse and rules 9ms 0.4% 39 files, 516 issues + config and walk 1ms 0.0% 39 files matched + render 518Β΅s 0.0% 20 diagnostics shown + total 2.7s +``` + +- The total is the sum of the phases, not the run's wall clock. +- `fix` reports `edits` and `write`, `dry run` for a preview; `fill-constraints` reports + one `compile` row per source, named in the detail column. + ## Diagnostic levels - Every rule reports at a level: `error`, `warn`, `info`, or `off`. diff --git a/crates/compact-lint/src/check.rs b/crates/compact-lint/src/check.rs index cc21f6da..ad222f92 100644 --- a/crates/compact-lint/src/check.rs +++ b/crates/compact-lint/src/check.rs @@ -2,6 +2,7 @@ use std::ffi::OsString; use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; use thiserror::Error; @@ -13,6 +14,7 @@ use crate::format::{self, FormatError}; use crate::report::RuleId; use crate::rules::{LintError, Linter}; use crate::target::{self, TargetError}; +use crate::timing::{Phase, Timings}; #[derive(Debug, Error)] pub enum CheckError { @@ -48,40 +50,75 @@ pub struct Outcome { /// Runs the subcommand with `cwd` as the working directory. /// # Errors /// Returns an error when the config, the file walk, the parser or the formatter fails. -pub fn run(options: &Options, cwd: &Path) -> Result { +pub fn run(options: &Options, cwd: &Path, timings: &mut Timings) -> Result { + let walk = Phase::start("config and walk"); let target = target::resolve(&options.paths, options.config_path.as_deref(), cwd)?; + walk.stop(timings, format!("{} files matched", target.files.len())); let mut linter = Linter::new()?; let mut diagnostics = Vec::new(); + let mut parsing = Duration::ZERO; + let mut previewing = Duration::ZERO; + let mut issue_count = 0; + let mut preview_count = 0; + for path in &target.files { + let started = Instant::now(); let text = std::fs::read_to_string(path).map_err(|source| CheckError::Read { path: path.clone(), source, })?; let newline = newline_of(&text); + let issues = linter.issues(path, &text, &target.config)?; + parsing += started.elapsed(); + issue_count += issues.len(); - for issue in linter.issues(path, &text, &target.config)? { + for issue in issues { let level = level_of(issue.rule(), &target.config, options.strict); let diagnostic = issue.diagnostic(path, level, &target.config); - diagnostics.push(match fix::edit_for(&issue, &target.config, newline) { - Some(edit) => { - let after = apply(&text, std::slice::from_ref(&edit), newline); - let title = fix::title(&edit, Badge::Fixable); - diagnostic.fixed_by(FixPreview::between(title, &text, &after), Badge::Fixable) + let started = Instant::now(); + let preview = fix::edit_for(&issue, &target.config, newline).map(|edit| { + let after = apply(&text, std::slice::from_ref(&edit), newline); + FixPreview::between(fix::title(&edit, Badge::Fixable), &text, &after) + }); + previewing += started.elapsed(); + + diagnostics.push(match preview { + Some(preview) => { + preview_count += 1; + diagnostic.fixed_by(preview, Badge::Fixable) } None => diagnostic, }); } } + timings.record( + "parse and rules", + parsing, + format!("{} files, {issue_count} issues", target.files.len()), + ); + timings.record( + "fix previews", + previewing, + format!("{preview_count} previews"), + ); + let format_level = target.config.rules.get(RuleId::FORMAT); - if !options.no_format && format_level != Level::Off { - diagnostics.extend(format::check( - &options.compact_bin, - &target.files, - format_level, - )?); + if options.no_format || format_level == Level::Off { + timings.record("format check", Duration::ZERO, skipped(options.no_format)); + } else { + let phase = Phase::start("format check"); + let found = format::check(&options.compact_bin, &target.files, format_level)?; + phase.stop( + timings, + format!( + "compact format --check, {} files, 1 process", + target.files.len() + ), + ); + diagnostics.extend(found); } diagnostics.sort_by(|left, right| left.sort_key().cmp(&right.sort_key())); @@ -91,6 +128,15 @@ pub fn run(options: &Options, cwd: &Path) -> Result { }) } +/// Why the format pass did not run, for its timing row. +fn skipped(no_format: bool) -> &'static str { + if no_format { + "skipped by --no-format" + } else { + "skipped by format = \"off\"" + } +} + /// `--strict` promotes a placeholder to an error; a rule turned off stays off. fn level_of(rule: RuleId, config: &Config, strict: bool) -> Level { let level = config.rules.get(rule); diff --git a/crates/compact-lint/src/diagnostic.rs b/crates/compact-lint/src/diagnostic.rs index 8e1b732e..b9a1a03a 100644 --- a/crates/compact-lint/src/diagnostic.rs +++ b/crates/compact-lint/src/diagnostic.rs @@ -292,14 +292,14 @@ impl Default for Output { } impl Output { - /// Writes every shown diagnostic and returns how many the cap hid. + /// Writes every shown diagnostic and reports what it printed. /// # Errors /// Returns an error when the writer fails. pub fn render( &self, out: &mut impl Write, diagnostics: &[Diagnostic], - ) -> std::io::Result { + ) -> std::io::Result { let mut sources = Sources::default(); let mut shown = 0; let mut hidden = 0; @@ -326,10 +326,17 @@ impl Output { } out.flush()?; - Ok(hidden) + Ok(Rendered { shown, hidden }) } } +/// What one render printed, and what the cap held back. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Rendered { + pub shown: usize, + pub hidden: usize, +} + /// The two-line notice printed when the cap hid diagnostics. #[must_use] pub fn truncation(hidden: usize) -> String { @@ -394,7 +401,7 @@ fn plural(count: usize, word: &str) -> String { } /// Sub-millisecond runs keep their microseconds; a run over a second reads in seconds. -fn duration(elapsed: Duration) -> String { +pub(crate) fn duration(elapsed: Duration) -> String { let micros = elapsed.as_micros(); if micros < 1_000 { format!("{micros}\u{b5}s") @@ -663,8 +670,8 @@ fn github_property(text: &str) -> String { #[cfg(test)] mod tests { use super::{ - Action, Badge, Diagnostic, FixPreview, Level, Output, Position, Reporter, Span, Summary, - diff, duration, frame, header, level_style, + Action, Badge, Diagnostic, FixPreview, Level, Output, Position, Rendered, Reporter, Span, + Summary, diff, duration, frame, header, level_style, }; use crate::report::RuleId; use std::time::Duration; @@ -821,14 +828,20 @@ mod tests { let diagnostics = [diagnostic(), diagnostic(), diagnostic()]; let mut out = Vec::new(); - let hidden = Output { + let rendered = Output { max: Some(1), ..Output::default() } .render(&mut out, &diagnostics) .expect("the writer accepts the render"); - assert_eq!(hidden, 2); + assert_eq!( + rendered, + Rendered { + shown: 1, + hidden: 2 + } + ); } #[test] diff --git a/crates/compact-lint/src/fill.rs b/crates/compact-lint/src/fill.rs index 02e54d65..a1c6a351 100644 --- a/crates/compact-lint/src/fill.rs +++ b/crates/compact-lint/src/fill.rs @@ -17,6 +17,7 @@ use crate::report::{Position, RuleId}; use crate::rules::{ConstraintSite, LintError, Linter}; use crate::source::{Resolver, Source}; use crate::target::{self, TargetError}; +use crate::timing::{Phase, Timings}; #[derive(Debug, Error)] pub enum FillError { @@ -73,11 +74,14 @@ struct Work { /// # Errors /// Returns an error when the config, the file walk, the parser, the compiler or a write /// fails. -pub fn run(options: &Options, cwd: &Path) -> Result { +pub fn run(options: &Options, cwd: &Path, timings: &mut Timings) -> Result { + let walk = Phase::start("config and walk"); let target = target::resolve(&options.paths, options.config_path.as_deref(), cwd)?; let resolver = Resolver::new(&target.config, &target.base, cwd)?; + walk.stop(timings, format!("{} files matched", target.files.len())); let tag = target.config.constraints.tag.clone(); + let sources = Phase::start("resolve sources"); let mut linter = Linter::new()?; let mut work = Vec::new(); for path in &target.files { @@ -98,13 +102,17 @@ pub fn run(options: &Options, cwd: &Path) -> Result { }); } + sources.stop(timings, format!("{} files with annotations", work.len())); + let measured = measure_sources( &work, options, target.config.constraints.compiler.as_ref(), cwd, + timings, )?; + let rewrite = Phase::start("parse and rewrite"); let mut outcome = Outcome { diagnostics: Vec::new(), filled: 0, @@ -115,6 +123,10 @@ pub fn run(options: &Options, cwd: &Path) -> Result { for file in &work { fill_file(file, &measured, &tag, &target.config, options, &mut outcome)?; } + rewrite.stop( + timings, + format!("{} values in {} files", outcome.filled, outcome.files), + ); Ok(outcome) } @@ -124,6 +136,7 @@ fn measure_sources( options: &Options, version: Option<&String>, cwd: &Path, + timings: &mut Timings, ) -> Result>, FillError> { let mut sources: Vec<&PathBuf> = work .iter() @@ -144,6 +157,11 @@ fn measure_sources( let mut measured = BTreeMap::new(); for source in sources { + let phase = Phase::start(if options.no_compile { + "read cache" + } else { + "compile" + }); let list = if options.no_compile { measure::read_cache(source)?.ok_or_else(|| MeasureError::CacheMiss { path: measure::cache_path(source), @@ -157,6 +175,7 @@ fn measure_sources( } list }; + phase.stop(timings, source.display().to_string()); measured.insert( source.clone(), diff --git a/crates/compact-lint/src/fix.rs b/crates/compact-lint/src/fix.rs index e220f5c3..40480cd0 100644 --- a/crates/compact-lint/src/fix.rs +++ b/crates/compact-lint/src/fix.rs @@ -1,6 +1,7 @@ //! The `fix` subcommand: turn the fixable issues into edits and rewrite the files. use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; use thiserror::Error; @@ -12,6 +13,7 @@ use crate::model::DeclKind; use crate::report::RuleId; use crate::rules::{DocRef, Issue, LintError, Linter}; use crate::target::{self, TargetError}; +use crate::timing::{Phase, Timings}; /// The value written into an inserted constraints annotation. const UNMEASURED: &str = "k=?, rows=?"; @@ -64,8 +66,10 @@ impl Outcome { /// Runs the subcommand with `cwd` as the working directory. /// # Errors /// Returns an error when the config, the file walk, the parser or a write fails. -pub fn run(options: &Options, cwd: &Path) -> Result { +pub fn run(options: &Options, cwd: &Path, timings: &mut Timings) -> Result { + let walk = Phase::start("config and walk"); let target = target::resolve(&options.paths, options.config_path.as_deref(), cwd)?; + walk.stop(timings, format!("{} files matched", target.files.len())); let badge = if options.dry_run { Badge::Fixable @@ -76,8 +80,13 @@ pub fn run(options: &Options, cwd: &Path) -> Result { let mut linter = Linter::new()?; let mut diagnostics = Vec::new(); let mut changed = 0; + let mut parsing = Duration::ZERO; + let mut editing = Duration::ZERO; + let mut writing = Duration::ZERO; + let mut issue_count = 0; for path in &target.files { + let started = Instant::now(); let source = std::fs::read_to_string(path).map_err(|source| FixError::Read { path: path.clone(), source, @@ -85,12 +94,17 @@ pub fn run(options: &Options, cwd: &Path) -> Result { let newline = newline_of(&source); let issues = linter.issues(path, &source, &target.config)?; + parsing += started.elapsed(); + issue_count += issues.len(); + + let started = Instant::now(); let repairs: Vec<(&Issue, Edit)> = issues .iter() .filter_map(|issue| edit_for(issue, &target.config, newline).map(|edit| (issue, edit))) .collect(); if repairs.is_empty() { + editing += started.elapsed(); continue; } @@ -99,12 +113,28 @@ pub fn run(options: &Options, cwd: &Path) -> Result { } let edits: Vec = repairs.into_iter().map(|(_, edit)| edit).collect(); + editing += started.elapsed(); + + let started = Instant::now(); if !options.dry_run { write_atomically(path, &apply(&source, &edits, newline))?; } + writing += started.elapsed(); changed += 1; } + timings.record( + "parse and rules", + parsing, + format!("{} files, {issue_count} issues", target.files.len()), + ); + timings.record("edits", editing, format!("{} edits", diagnostics.len())); + if options.dry_run { + timings.record("dry run", writing, format!("{changed} files would change")); + } else { + timings.record("write", writing, format!("{changed} files")); + } + Ok(Outcome { diagnostics, checked: target.files.len(), diff --git a/crates/compact-lint/src/lib.rs b/crates/compact-lint/src/lib.rs index c7302b04..965645b3 100644 --- a/crates/compact-lint/src/lib.rs +++ b/crates/compact-lint/src/lib.rs @@ -24,3 +24,4 @@ pub mod report; pub mod rules; pub mod source; pub mod target; +pub mod timing; diff --git a/crates/compact-lint/src/main.rs b/crates/compact-lint/src/main.rs index c3f4949c..995a102c 100644 --- a/crates/compact-lint/src/main.rs +++ b/crates/compact-lint/src/main.rs @@ -16,6 +16,7 @@ use tempfile::TempDir; use compact_lint::check; use compact_lint::diagnostic::{Action, Diagnostic, Level, Output, Reporter, Summary, counts}; use compact_lint::format::{COMPACT_BIN_ENV, DEFAULT_COMPACT_BIN}; +use compact_lint::timing::{Phase, Timings}; use compact_lint::{diagnostic, fill, fix}; /// Exit code for a run that produced errors, or a `--dry-run` that would edit. @@ -70,6 +71,10 @@ struct OutputArgs { /// Colour the output; the default colours a TTY with `NO_COLOR` unset. #[arg(long, value_enum, value_name = "WHEN")] colors: Option, + + /// Print a per-phase wall-clock breakdown under the summary. + #[arg(long)] + timings: bool, } /// The levels a reader can ask for; `off` is a rule setting, not a filter. @@ -225,9 +230,10 @@ fn run_check(args: CheckArgs, cwd: &std::path::Path) -> Result { .unwrap_or_else(|| OsString::from(DEFAULT_COMPACT_BIN)), }; + let mut timings = Timings::default(); let started = Instant::now(); - let outcome = check::run(&options, cwd).context("running the check")?; - let (errors, warnings) = emit( + let outcome = check::run(&options, cwd, &mut timings).context("running the check")?; + let printed = report( &args.output, &outcome.diagnostics, RunFacts { @@ -235,10 +241,15 @@ fn run_check(args: CheckArgs, cwd: &std::path::Path) -> Result { duration: started.elapsed(), action: Action::NoFixes, }, + &mut timings, ) .context("writing the report")?; - Ok(exit_code(errors, warnings, args.output.error_on_warnings)) + Ok(exit_code( + printed.errors, + printed.warnings, + args.output.error_on_warnings, + )) } fn run_fix(args: FixArgs, cwd: &std::path::Path) -> Result { @@ -248,14 +259,15 @@ fn run_fix(args: FixArgs, cwd: &std::path::Path) -> Result { dry_run: args.dry_run, }; + let mut timings = Timings::default(); let started = Instant::now(); - let outcome = fix::run(&options, cwd).context("running the fix")?; + let outcome = fix::run(&options, cwd, &mut timings).context("running the fix")?; let action = if options.dry_run { Action::NoFixes } else { Action::Fixed(outcome.changed) }; - let (errors, warnings) = emit( + let printed = report( &args.output, &outcome.diagnostics, RunFacts { @@ -263,13 +275,18 @@ fn run_fix(args: FixArgs, cwd: &std::path::Path) -> Result { duration: started.elapsed(), action, }, + &mut timings, ) .context("writing the report")?; if options.dry_run && outcome.edits() > 0 { return Ok(ExitCode::from(EXIT_FINDINGS)); } - Ok(exit_code(errors, warnings, args.output.error_on_warnings)) + Ok(exit_code( + printed.errors, + printed.warnings, + args.output.error_on_warnings, + )) } fn run_fill(args: FillArgs, cwd: &std::path::Path) -> Result { @@ -286,9 +303,10 @@ fn run_fill(args: FillArgs, cwd: &std::path::Path) -> Result { artifacts, }; + let mut timings = Timings::default(); let started = Instant::now(); - let outcome = fill::run(&options, cwd).context("filling the constraints")?; - let (errors, warnings) = emit( + let outcome = fill::run(&options, cwd, &mut timings).context("filling the constraints")?; + let printed = report( &args.output, &outcome.diagnostics, RunFacts { @@ -299,6 +317,7 @@ fn run_fill(args: FillArgs, cwd: &std::path::Path) -> Result { files: outcome.files, }, }, + &mut timings, ) .context("writing the report")?; @@ -306,7 +325,11 @@ fn run_fill(args: FillArgs, cwd: &std::path::Path) -> Result { if outcome.unmeasured > 0 { return Ok(ExitCode::from(EXIT_FINDINGS)); } - Ok(exit_code(errors, warnings, args.output.error_on_warnings)) + Ok(exit_code( + printed.errors, + printed.warnings, + args.output.error_on_warnings, + )) } /// The artifacts directory, plus the temporary one to remove once the run ends. @@ -327,22 +350,46 @@ struct RunFacts { action: Action, } +/// What the report counted, for the exit code. +#[derive(Clone, Copy, Debug)] +struct Printed { + errors: usize, + warnings: usize, +} + +/// Emits the report as its own timed phase, then the breakdown when `--timings` is set. +fn report( + args: &OutputArgs, + diagnostics: &[Diagnostic], + facts: RunFacts, + timings: &mut Timings, +) -> std::io::Result { + let phase = Phase::start("render"); + let (printed, shown) = emit(args, diagnostics, facts)?; + phase.stop(timings, format!("{shown} diagnostics shown")); + + if args.timings { + writeln!(std::io::stderr().lock(), "{}", timings.render())?; + } + Ok(printed) +} + /// Writes the diagnostics to stdout and the truncation notice and summary to stderr. fn emit( args: &OutputArgs, diagnostics: &[Diagnostic], facts: RunFacts, -) -> std::io::Result<(usize, usize)> { +) -> std::io::Result<(Printed, usize)> { let (errors, warnings) = counts(diagnostics); let stdout = std::io::stdout(); let mut out = stdout.lock(); - let hidden = args.output().render(&mut out, diagnostics)?; + let rendered = args.output().render(&mut out, diagnostics)?; let stderr = std::io::stderr(); let mut error_out = stderr.lock(); - if hidden > 0 { - writeln!(error_out, "{}", diagnostic::truncation(hidden))?; + if rendered.hidden > 0 { + writeln!(error_out, "{}", diagnostic::truncation(rendered.hidden))?; } writeln!( error_out, @@ -357,7 +404,7 @@ fn emit( .render() )?; - Ok((errors, warnings)) + Ok((Printed { errors, warnings }, rendered.shown)) } fn exit_code(errors: usize, warnings: usize, error_on_warnings: bool) -> ExitCode { diff --git a/crates/compact-lint/src/timing.rs b/crates/compact-lint/src/timing.rs new file mode 100644 index 00000000..e24e1088 --- /dev/null +++ b/crates/compact-lint/src/timing.rs @@ -0,0 +1,217 @@ +//! The per-phase wall-clock breakdown `--timings` prints. +//! +//! A phase is one span of a run the reader can act on: the file walk, the rules, the +//! `compact format --check` subprocess. Each carries a detail column naming what it +//! worked on, so a slow phase says why it was slow. + +use std::fmt::Write as _; +use std::time::{Duration, Instant}; + +use crate::diagnostic::duration; + +/// The block's first line. +const HEADING: &str = "Timings"; + +/// The name of the closing row. +const TOTAL: &str = "total"; + +/// Indentation under the heading. +const INDENT: &str = " "; + +/// Separator between columns. +const GAP: &str = " "; + +/// Width of the share column, sized for `100.0%`. +const SHARE_WIDTH: usize = 6; + +/// A phase being measured, recorded where it ends. +#[derive(Debug)] +pub struct Phase { + name: &'static str, + started: Instant, +} + +impl Phase { + /// Opens a phase named `name`. + #[must_use] + pub fn start(name: &'static str) -> Self { + Self { + name, + started: Instant::now(), + } + } + + /// Ends the phase now and records it. + pub fn stop(self, timings: &mut Timings, detail: impl Into) { + timings.record(self.name, self.started.elapsed(), detail); + } +} + +/// One recorded phase. +#[derive(Debug)] +struct Measured { + name: &'static str, + elapsed: Duration, + detail: String, +} + +/// Every phase of one run, in the order it was recorded. +#[derive(Debug, Default)] +pub struct Timings { + phases: Vec, +} + +impl Timings { + /// Records a phase the caller timed itself, for work spread over a loop. + pub fn record(&mut self, name: &'static str, elapsed: Duration, detail: impl Into) { + self.phases.push(Measured { + name, + elapsed, + detail: detail.into(), + }); + } + + /// Renders the block, longest phase first and the total last. + /// + /// The total is the sum of the phases, not the run's wall clock, so a phase nobody + /// measured is missing from both. + #[must_use] + pub fn render(&self) -> String { + let total: Duration = self.phases.iter().map(|phase| phase.elapsed).sum(); + + let mut rows: Vec<(&Measured, String)> = self + .phases + .iter() + .map(|phase| (phase, duration(phase.elapsed))) + .collect(); + // Sorting is stable, so phases of equal length stay in the order they ran. + rows.sort_by_key(|(phase, _)| std::cmp::Reverse(phase.elapsed)); + + let total_elapsed = duration(total); + let name_width = rows + .iter() + .map(|(phase, _)| phase.name.len()) + .chain([TOTAL.len()]) + .max() + .unwrap_or_default(); + // Padding counts characters, so a microsecond figure must be measured the same way. + let elapsed_width = rows + .iter() + .map(|(_, elapsed)| elapsed.chars().count()) + .chain([total_elapsed.chars().count()]) + .max() + .unwrap_or_default(); + + let mut out = HEADING.to_owned(); + for (phase, elapsed) in &rows { + let line = format!( + "{INDENT}{name:elapsed_width$}{GAP}{share:>SHARE_WIDTH$}{GAP}{detail}", + name = phase.name, + share = share(phase.elapsed, total), + detail = phase.detail, + ); + let _ = write!(out, "\n{}", line.trim_end()); + } + let _ = write!( + out, + "\n{INDENT}{TOTAL:elapsed_width$}" + ); + out + } +} + +/// A phase's share of the total, `0.0%` for a run that measured nothing. +fn share(elapsed: Duration, total: Duration) -> String { + let share = if total.is_zero() { + 0.0 + } else { + elapsed.as_secs_f64() / total.as_secs_f64() * 100.0 + }; + format!("{share:.1}%") +} + +#[cfg(test)] +mod tests { + use super::{Phase, Timings}; + use std::time::Duration; + + fn timings() -> Timings { + let mut timings = Timings::default(); + timings.record( + "config and walk", + Duration::from_millis(1), + "39 files matched", + ); + timings.record( + "parse and rules", + Duration::from_millis(40), + "39 files, 512 issues", + ); + timings.record( + "format check", + Duration::from_millis(3_200), + "compact format --check, 39 files, 1 process", + ); + timings + } + + #[test] + fn phases_render_longest_first_with_the_total_last() { + let rendered = timings().render(); + + let names: Vec<&str> = rendered + .lines() + .skip(1) + .filter_map(|line| line.split_whitespace().next()) + .collect(); + assert_eq!(names, ["format", "parse", "config", "total"]); + } + + #[test] + fn the_columns_line_up_and_the_shares_sum_to_the_whole() { + assert_eq!( + timings().render(), + "Timings\n\ + \x20 format check 3.2s 98.7% compact format --check, 39 files, 1 process\n\ + \x20 parse and rules 40ms 1.2% 39 files, 512 issues\n\ + \x20 config and walk 1ms 0.0% 39 files matched\n\ + \x20 total 3.2s" + ); + } + + #[test] + fn a_microsecond_phase_keeps_the_columns_aligned() { + let mut timings = Timings::default(); + timings.record("parse and rules", Duration::from_millis(52), "39 files"); + timings.record("render", Duration::from_micros(299), "20 diagnostics shown"); + + assert_eq!( + timings.render(), + "Timings\n\ + \x20 parse and rules 52ms 99.4% 39 files\n\ + \x20 render 299\u{b5}s 0.6% 20 diagnostics shown\n\ + \x20 total 52ms" + ); + } + + #[test] + fn a_phase_without_a_detail_leaves_no_trailing_space() { + let mut timings = Timings::default(); + timings.record("render", Duration::from_millis(2), ""); + + assert_eq!( + timings.render(), + "Timings\n render 2ms 100.0%\n total 2ms" + ); + } + + #[test] + fn a_run_that_measured_nothing_renders_a_zero_total() { + let mut timings = Timings::default(); + Phase::start("config and walk").stop(&mut timings, "0 files matched"); + + let rendered = timings.render(); + assert!(rendered.starts_with("Timings\n"), "{rendered}"); + assert!(rendered.contains("0 files matched"), "{rendered}"); + } +} diff --git a/crates/compact-lint/tests/check.rs b/crates/compact-lint/tests/check.rs index 422f88a3..3f3c5c87 100644 --- a/crates/compact-lint/tests/check.rs +++ b/crates/compact-lint/tests/check.rs @@ -213,6 +213,17 @@ fn the_cap_shows_the_first_diagnostics_and_counts_the_rest() { assert!(!lifted.contains("Diagnostics not shown"), "{lifted}"); } +#[test] +fn timings_print_a_phase_breakdown_under_the_summary_only_when_asked() { + let (_, _, stderr) = run("clean", &["--timings"]); + assert!(stderr.contains("\nTimings\n"), "{stderr}"); + assert!(stderr.contains("parse and rules"), "{stderr}"); + assert!(stderr.contains("\n total"), "{stderr}"); + + let (_, _, quiet) = run("clean", &[]); + assert!(!quiet.contains("Timings"), "{quiet}"); +} + #[test] fn error_on_warnings_fails_a_run_that_only_warned() { assert_case("error-on-warnings", &["--error-on-warnings"], EXIT_FINDINGS); From c69476d008f2d913e7e30c115f950efb6053732d Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Wed, 16 Sep 2026 05:49:19 +0200 Subject: [PATCH 14/56] feat(compact-lint): read measurements from the artifact dir The builder now writes `//circuit-info.json` beside the compiler's own output instead of a hidden per-directory sidecar in the source tree. `fill-constraints` follows: `--no-compile` reads that file, and the linter's own compiles write it to the same place, so a full ZK `yarn compile` in CI is all the fill step needs. * `[lint.constraints] artifacts` names the tree, relative to compact.toml; `--artifacts` overrides it. The temp-dir default is gone, compiler output is kept where the builder keeps it. * Lookup is `//` first, then a walk for a hierarchical tree; two hits for one stem is an error. * `.gitignore` drops the sidecar block; the fixture moves under `artifacts/` with an exception for the test tree. --- .gitignore | 7 +- crates/compact-lint/README.md | 37 ++- crates/compact-lint/examples/compact.toml | 3 + crates/compact-lint/src/config.rs | 13 +- crates/compact-lint/src/fill.rs | 70 ++++- crates/compact-lint/src/main.rs | 20 +- crates/compact-lint/src/measure.rs | 257 +++++++++++++----- crates/compact-lint/tests/fill.rs | 74 ++++- .../artifacts/MockOwnable/circuit-info.json | 11 + .../src/access/test/mocks/.circuit-info.json | 12 - 10 files changed, 354 insertions(+), 150 deletions(-) create mode 100644 crates/compact-lint/tests/fixtures/fill-no-compile/before/artifacts/MockOwnable/circuit-info.json delete mode 100644 crates/compact-lint/tests/fixtures/fill-no-compile/before/src/access/test/mocks/.circuit-info.json diff --git a/.gitignore b/.gitignore index 48f64fef..569a4a27 100644 --- a/.gitignore +++ b/.gitignore @@ -33,11 +33,8 @@ managed/ # never gets committed β€” including under examples/, where the walkthrough # expects you to compile the contract yourself before deploying. artifacts/ -# compact-compiler's per-source circuit-info cache, written next to the -# .compact sources it measures. -.circuit-info.json -# Except the seeded cache the fill-constraints tests read. -!crates/compact-lint/tests/fixtures/**/.circuit-info.json +# Except the seeded artifacts the fill-constraints tests read. +!crates/compact-lint/tests/fixtures/**/artifacts/ midnight-level-db compactc diff --git a/crates/compact-lint/README.md b/crates/compact-lint/README.md index 5eb62af8..5dfdc024 100644 --- a/crates/compact-lint/README.md +++ b/crates/compact-lint/README.md @@ -212,13 +212,13 @@ compact-lint fill-constraints [PATHS]... [--config ] [--dry-run] [--no-com ``` - `PATHS` and `--config` resolve exactly as they do for `check`. -- `--dry-run` β€” report the changes and write nothing, the measurement cache included. -- `--no-compile` β€” read the `.circuit-info.json` caches instead of compiling. A source - with no cached entry is an error. +- `--dry-run` β€” report the changes and write nothing, the artifact file included. +- `--no-compile` β€” read each contract's `circuit-info.json` instead of compiling. A source + with no artifact file is an error. - `--compact-bin ` β€” path to the `compact` binary, as for `check`. Also settable with `COMPACT_LINT_COMPACT_BIN`. -- `--artifacts ` β€” where the compiler writes. Without it a temporary directory is - used and removed at the end. +- `--artifacts ` β€” the artifacts tree to read and write, overriding + `constraints.artifacts`. Scope is the annotations that already exist: every exported non-pure circuit whose doc comment carries `constraints.tag`, whatever its value. A circuit with no annotation is @@ -254,23 +254,30 @@ mock contract that exports the same circuit names. For each file, in order: Each distinct source is compiled once per run, whatever the number of files it measures. -### The cache +### The artifact file -After a compile, the measurements are merged into `.circuit-info.json` beside the source, -keyed by the source's file name. It is the file the TypeScript builder in -`packages/builder` writes, in the same shape, so the two tools share it: +Each compiled contract carries its measurements in `circuit-info.json`, beside the +compiler's own `compiler/contract-info.json` in its artifact directory. It is the file the +TypeScript builder in `packages/builder` writes, in the same shape, so the two tools share +it: ```json { "generatedAt": "2026-09-15T08:38:49.000Z", - "files": { - "MockOwnable.compact": [{ "name": "owner", "k": 7, "rows": 74 }] - } + "source": "contracts/src/access/test/mocks/MockOwnable.compact", + "circuits": [{ "name": "owner", "k": 7, "rows": 74 }] } ``` -Other files' entries are kept and `generatedAt` is refreshed. `--no-compile` reads this -file instead of running the compiler. +- `constraints.artifacts` names the tree, relative to the `compact.toml` directory, and + defaults to `artifacts`. `--artifacts ` overrides it. +- A compile writes `//circuit-info.json`, replacing what was there, with + `source` relative to the `compact.toml` directory. +- `--no-compile` reads `//circuit-info.json`, and where that is absent + searches the tree for one `/circuit-info.json`, which is where a hierarchical + build puts it. Two directories of one stem is an error. +- In compact-contracts a full ZK `yarn compile` writes the file `--no-compile` reads, so + the linter never recompiles what the builder already measured. ### Unmeasured @@ -288,7 +295,7 @@ Exit codes: - `0` β€” every tagged circuit was measured, whether or not a value changed. - `1` β€” at least one circuit is unmeasured or unmeasurable. -- `2` β€” usage, config, IO, compiler or missing-cache error. A failed compile prints the +- `2` β€” usage, config, IO, compiler or missing-artifact error. A failed compile prints the source and the last 20 lines of the compiler's cleaned output; the raw pty stream is never printed. diff --git a/crates/compact-lint/examples/compact.toml b/crates/compact-lint/examples/compact.toml index 164f889e..84442340 100644 --- a/crates/compact-lint/examples/compact.toml +++ b/crates/compact-lint/examples/compact.toml @@ -12,6 +12,9 @@ exclude = ["**/test/mocks/**", "**/archive/**"] # `@constraints` is the default; set `tag` to point the rule at another annotation. [lint.constraints] tag = "@constraints" +# Where the builder and fill-constraints write `/circuit-info.json`, relative to +# this file. `--artifacts ` overrides it. +artifacts = "contracts/artifacts" # Presets are contracts, so fill-constraints compiles them directly. Everything else is # measured through the mock beside it or in its parent, the default `sources` templates. self = ["**/presets/**"] diff --git a/crates/compact-lint/src/config.rs b/crates/compact-lint/src/config.rs index 77150d50..4f720191 100644 --- a/crates/compact-lint/src/config.rs +++ b/crates/compact-lint/src/config.rs @@ -162,6 +162,9 @@ pub const DEFAULT_SOURCES: [&str; 2] = [ "{parent}/test/mocks/Mock{stem}.compact", ]; +/// Where the compiler writes, and where `fill-constraints` reads a measurement from. +pub const DEFAULT_ARTIFACTS: &str = "artifacts"; + /// The circuit constraints annotation, and how `fill-constraints` measures it. #[derive(Clone, Debug, Deserialize, PartialEq, Eq)] #[serde(deny_unknown_fields, default)] @@ -169,6 +172,8 @@ pub struct ConstraintsConfig { pub tag: Tag, /// Toolchain version passed as `+`; none leaves `compact` on its default. pub compiler: Option, + /// Artifacts tree, relative to this file's directory; `--artifacts` overrides it. + pub artifacts: PathBuf, /// Measurement-source templates, first existing file wins. pub sources: Vec, /// Globs for files that are contracts and compile themselves. @@ -183,6 +188,7 @@ impl Default for ConstraintsConfig { Self { tag: Tag::new("@constraints"), compiler: None, + artifacts: PathBuf::from(DEFAULT_ARTIFACTS), sources: DEFAULT_SOURCES .iter() .map(|&template| template.to_owned()) @@ -683,6 +689,7 @@ mod tests { let constraints = Config::default().constraints; assert_eq!(constraints.compiler, None); + assert_eq!(constraints.artifacts, std::path::Path::new("artifacts")); assert_eq!(constraints.sources, super::DEFAULT_SOURCES); assert!(constraints.own.is_empty()); assert!(constraints.overrides.is_empty()); @@ -691,11 +698,15 @@ mod tests { #[test] fn a_constraints_table_keeps_the_templates_it_does_not_name() { let config: Config = toml::from_str( - "[constraints]\ncompiler = \"0.34.0\"\nself = [\"**/presets/**\"]\n[constraints.overrides]\n\"a.compact\" = \"b.compact\"\n", + "[constraints]\ncompiler = \"0.34.0\"\nartifacts = \"contracts/artifacts\"\nself = [\"**/presets/**\"]\n[constraints.overrides]\n\"a.compact\" = \"b.compact\"\n", ) .expect("the snippet is valid config"); assert_eq!(config.constraints.compiler.as_deref(), Some("0.34.0")); + assert_eq!( + config.constraints.artifacts, + std::path::Path::new("contracts/artifacts") + ); assert_eq!(config.constraints.own, ["**/presets/**"]); assert_eq!(config.constraints.sources, super::DEFAULT_SOURCES); assert_eq!( diff --git a/crates/compact-lint/src/fill.rs b/crates/compact-lint/src/fill.rs index a1c6a351..95273524 100644 --- a/crates/compact-lint/src/fill.rs +++ b/crates/compact-lint/src/fill.rs @@ -44,11 +44,38 @@ pub struct Options { pub paths: Vec, pub config_path: Option, pub dry_run: bool, - /// Read the `.circuit-info.json` caches instead of compiling. + /// Read each contract's `circuit-info.json` instead of compiling. pub no_compile: bool, pub compact_bin: OsString, - /// Where the compiler writes; a run without one uses a temporary directory. - pub artifacts: PathBuf, + /// `--artifacts`; none takes `constraints.artifacts` under the config's directory. + pub artifacts: Option, +} + +/// The artifacts tree, and how a file written into it spells the source it measured. +struct Artifacts { + directory: PathBuf, + /// The config's directory, which a recorded source path is relative to. + base: PathBuf, +} + +impl Artifacts { + /// The compiled file as its artifact records it: relative to the config's directory, + /// with forward slashes. + fn recorded(&self, source: &Path, cwd: &Path) -> String { + let absolute = if source.is_absolute() { + source.to_owned() + } else { + cwd.join(source) + }; + + absolute + .strip_prefix(&self.base) + .unwrap_or(&absolute) + .components() + .map(|part| part.as_os_str().to_string_lossy()) + .collect::>() + .join("/") + } } /// The diagnostics and the counts behind the summary. @@ -104,11 +131,19 @@ pub fn run(options: &Options, cwd: &Path, timings: &mut Timings) -> Result Result, cwd: &Path, + artifacts: &Artifacts, timings: &mut Timings, ) -> Result>, FillError> { let mut sources: Vec<&PathBuf> = work @@ -151,31 +187,35 @@ fn measure_sources( let compiler = Compiler { binary: options.compact_bin.clone(), version: version.cloned(), - artifacts: options.artifacts.clone(), + artifacts: artifacts.directory.clone(), cwd: cwd.to_owned(), }; let mut measured = BTreeMap::new(); for source in sources { let phase = Phase::start(if options.no_compile { - "read cache" + "read artifact" } else { "compile" }); - let list = if options.no_compile { - measure::read_cache(source)?.ok_or_else(|| MeasureError::CacheMiss { - path: measure::cache_path(source), - name: source.display().to_string(), - })? + let (list, detail) = if options.no_compile { + let path = measure::locate(&artifacts.directory, source)?; + let list = measure::read_artifact(&path)?; + (list, path.display().to_string()) } else { let list = compiler.measure(source)?; - // A preview writes nothing, the cache included. + // A preview writes nothing, the artifact included. if !options.dry_run { - measure::write_cache(source, &list)?; + measure::write_artifact( + &artifacts.directory, + source, + &artifacts.recorded(source, cwd), + &list, + )?; } - list + (list, source.display().to_string()) }; - phase.stop(timings, source.display().to_string()); + phase.stop(timings, detail); measured.insert( source.clone(), diff --git a/crates/compact-lint/src/main.rs b/crates/compact-lint/src/main.rs index 995a102c..bd8dd19a 100644 --- a/crates/compact-lint/src/main.rs +++ b/crates/compact-lint/src/main.rs @@ -11,7 +11,6 @@ use std::time::{Duration, Instant}; use anyhow::{Context, Result}; use clap::{Parser, Subcommand}; -use tempfile::TempDir; use compact_lint::check; use compact_lint::diagnostic::{Action, Diagnostic, Level, Output, Reporter, Summary, counts}; @@ -182,7 +181,7 @@ struct FillArgs { #[arg(long)] dry_run: bool, - /// Read the .circuit-info.json caches instead of compiling. + /// Read each contract's circuit-info.json instead of compiling. #[arg(long)] no_compile: bool, @@ -190,7 +189,7 @@ struct FillArgs { #[arg(long, value_name = "PATH", env = COMPACT_BIN_ENV)] compact_bin: Option, - /// Directory the compiler writes to; kept after the run when given. + /// Artifacts tree to read and write; overrides constraints.artifacts. #[arg(long, value_name = "DIR")] artifacts: Option, @@ -290,8 +289,6 @@ fn run_fix(args: FixArgs, cwd: &std::path::Path) -> Result { } fn run_fill(args: FillArgs, cwd: &std::path::Path) -> Result { - let (artifacts, temporary) = artifacts_dir(args.artifacts)?; - let options = fill::Options { paths: args.paths, config_path: args.config, @@ -300,7 +297,7 @@ fn run_fill(args: FillArgs, cwd: &std::path::Path) -> Result { compact_bin: args .compact_bin .unwrap_or_else(|| OsString::from(DEFAULT_COMPACT_BIN)), - artifacts, + artifacts: args.artifacts, }; let mut timings = Timings::default(); @@ -321,7 +318,6 @@ fn run_fill(args: FillArgs, cwd: &std::path::Path) -> Result { ) .context("writing the report")?; - drop(temporary); if outcome.unmeasured > 0 { return Ok(ExitCode::from(EXIT_FINDINGS)); } @@ -332,16 +328,6 @@ fn run_fill(args: FillArgs, cwd: &std::path::Path) -> Result { )) } -/// The artifacts directory, plus the temporary one to remove once the run ends. -fn artifacts_dir(given: Option) -> Result<(PathBuf, Option)> { - if let Some(path) = given { - return Ok((path, None)); - } - - let directory = tempfile::tempdir().context("creating the artifacts directory")?; - Ok((directory.path().to_owned(), Some(directory))) -} - /// What a run did, everything the summary needs that the diagnostics do not carry. #[derive(Clone, Copy, Debug)] struct RunFacts { diff --git a/crates/compact-lint/src/measure.rs b/crates/compact-lint/src/measure.rs index 954bc137..51104486 100644 --- a/crates/compact-lint/src/measure.rs +++ b/crates/compact-lint/src/measure.rs @@ -1,8 +1,8 @@ //! Measuring a circuit's proving key size and row count with `compact compile`. //! //! `k` and `rows` reach only the compiler's terminal progress output, so the compile runs -//! under a pty and the transcript is parsed. Results are cached in the -//! `.circuit-info.json` file the TypeScript builder writes, in the same shape. +//! under a pty and the transcript is parsed. Results go to the `circuit-info.json` the +//! TypeScript builder writes in a contract's artifact directory, in the same shape. use std::collections::BTreeMap; use std::ffi::{OsStr, OsString}; @@ -13,13 +13,17 @@ use std::time::{SystemTime, UNIX_EPOCH}; use portable_pty::{CommandBuilder, PtySize, native_pty_system}; use serde::{Deserialize, Serialize}; use thiserror::Error; +use walkdir::WalkDir; -/// The measurement cache, written beside the compiled source. -pub const CACHE_FILE_NAME: &str = ".circuit-info.json"; +/// One contract's measurements, beside the compiler's own output in its artifact directory. +pub const ARTIFACT_FILE_NAME: &str = "circuit-info.json"; /// The compiler's own report of the circuits it built, under the artifacts directory. const CONTRACT_INFO_PATH: [&str; 2] = ["compiler", "contract-info.json"]; +/// A dependency tree carries its own artifacts, so the search never descends into one. +const SKIPPED_DIR: &str = "node_modules"; + /// Compiler-output lines kept in a failure report. const TAIL_LINES: usize = 20; @@ -65,8 +69,21 @@ pub enum MeasureError { #[source] source: serde_json::Error, }, - #[error("{path} has no cached measurement for {name}; drop --no-compile to compile it")] - CacheMiss { path: PathBuf, name: String }, + #[error( + "no measurement for {file} at {path}; compile it, or run fill-constraints without --no-compile" + )] + CacheMiss { file: PathBuf, path: PathBuf }, + #[error("several artifact directories are named {stem}: {}", list(paths))] + AmbiguousArtifact { stem: String, paths: Vec }, +} + +/// Paths as one comma-separated line, for an error message. +fn list(paths: &[PathBuf]) -> String { + paths + .iter() + .map(|path| path.display().to_string()) + .collect::>() + .join(", ") } /// One circuit's measured constraints. @@ -84,7 +101,7 @@ impl Constraints { } } -/// One entry of the `.circuit-info.json` cache. +/// One circuit of the `circuit-info.json` list. #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] pub struct Measurement { pub name: String, @@ -102,12 +119,16 @@ impl Measurement { } } -/// The `.circuit-info.json` shape, shared with the TypeScript builder. +/// The `circuit-info.json` shape, shared with the TypeScript builder. #[derive(Clone, Debug, Default, Deserialize, Serialize)] struct CircuitInfo { #[serde(rename = "generatedAt")] generated_at: String, - files: BTreeMap>, + /// The compiled file, as its writer spelled it; the directory, not this, locates a source. + #[serde(default)] + source: String, + #[serde(default)] + circuits: Vec, } /// The compiler's circuit list; only `proof` circuits carry constraints. @@ -146,11 +167,7 @@ impl Compiler { /// Returns an error when the binary cannot run, the compile fails, or the /// artifacts cannot be read. pub fn measure(&self, source: &Path) -> Result, MeasureError> { - let stem = source - .file_stem() - .unwrap_or_else(|| OsStr::new("contract")) - .to_owned(); - let output = self.artifacts.join(&stem); + let output = self.artifacts.join(stem(source)); std::fs::create_dir_all(&output).map_err(|cause| MeasureError::Write { path: output.clone(), source: cause, @@ -250,33 +267,89 @@ fn proved_circuits(output: &Path) -> Result>, MeasureError> { )) } -/// Reads a source's entry from the cache beside it. +/// A source's artifact file, in the directory the compiler writes for it. +#[must_use] +pub fn artifact_path(artifacts: &Path, source: &Path) -> PathBuf { + artifacts.join(stem(source)).join(ARTIFACT_FILE_NAME) +} + +/// Finds a source's artifact file: its own directory first, then a search of the tree. +/// +/// A hierarchical build nests the contract directory under the subdirectory it was +/// compiled from. /// # Errors -/// Returns an error when the cache is unreadable or malformed. -pub fn read_cache(source: &Path) -> Result>, MeasureError> { - let path = cache_path(source); - if !path.is_file() { - return Ok(None); +/// Returns an error when no directory under `artifacts` holds the file, or several do. +pub fn locate(artifacts: &Path, source: &Path) -> Result { + let flat = artifact_path(artifacts, source); + if flat.is_file() { + return Ok(flat); + } + + let mut nested = search(artifacts, &stem(source)); + if nested.len() > 1 { + return Err(MeasureError::AmbiguousArtifact { + stem: stem(source), + paths: nested, + }); } + nested.pop().ok_or_else(|| MeasureError::CacheMiss { + file: source.to_owned(), + path: flat, + }) +} - let info = load_cache(&path)?; - Ok(info.files.get(&file_key(source)).cloned()) +/// Every artifact file under `artifacts` whose contract directory is named `stem`. +fn search(artifacts: &Path, stem: &str) -> Vec { + WalkDir::new(artifacts) + .follow_links(false) + .sort_by_file_name() + .into_iter() + .filter_entry(|entry| entry.depth() == 0 || entry.file_name() != SKIPPED_DIR) + .filter_map(Result::ok) + .filter(|entry| entry.file_type().is_dir() && entry.file_name() == OsStr::new(stem)) + .map(|entry| entry.path().join(ARTIFACT_FILE_NAME)) + .filter(|path| path.is_file()) + .collect() } -/// Writes a source's entry into the cache beside it, keeping every other entry. +/// Reads one contract's measurements from its artifact file. /// # Errors -/// Returns an error when the cache is unreadable, malformed or unwritable. -pub fn write_cache(source: &Path, measured: &[Measurement]) -> Result { - let path = cache_path(source); - let mut info = if path.is_file() { - load_cache(&path)? - } else { - CircuitInfo::default() - }; +/// Returns an error when the file is unreadable or malformed. +pub fn read_artifact(path: &Path) -> Result, MeasureError> { + let text = std::fs::read_to_string(path).map_err(|source| MeasureError::Read { + path: path.to_owned(), + source, + })?; + let info: CircuitInfo = serde_json::from_str(&text).map_err(|source| MeasureError::Parse { + path: path.to_owned(), + source, + })?; + Ok(info.circuits) +} - info.generated_at = timestamp(SystemTime::now()); - info.files.insert(file_key(source), measured.to_vec()); +/// Writes one contract's measurements, replacing whatever the file held. +/// +/// `recorded` is the compiled file's path as the artifact spells it. +/// # Errors +/// Returns an error when the directory or the file cannot be written. +pub fn write_artifact( + artifacts: &Path, + source: &Path, + recorded: &str, + measured: &[Measurement], +) -> Result { + let path = artifact_path(artifacts, source); + let directory = path.parent().unwrap_or_else(|| Path::new(".")); + std::fs::create_dir_all(directory).map_err(|source| MeasureError::Write { + path: directory.to_owned(), + source, + })?; + let info = CircuitInfo { + generated_at: timestamp(SystemTime::now()), + source: recorded.to_owned(), + circuits: measured.to_vec(), + }; let mut text = serde_json::to_string_pretty(&info).map_err(|source| MeasureError::Parse { path: path.clone(), source, @@ -289,31 +362,11 @@ pub fn write_cache(source: &Path, measured: &[Measurement]) -> Result Result { - let text = std::fs::read_to_string(path).map_err(|source| MeasureError::Read { - path: path.to_owned(), - source, - })?; - serde_json::from_str(&text).map_err(|source| MeasureError::Parse { - path: path.to_owned(), - source, - }) -} - -/// The cache sits in the source's own directory. -#[must_use] -pub fn cache_path(source: &Path) -> PathBuf { - source - .parent() - .unwrap_or_else(|| Path::new(".")) - .join(CACHE_FILE_NAME) -} - -/// Entries are keyed by the source's file name, not its path. -fn file_key(source: &Path) -> String { +/// The contract directory's name: the source's file stem. +fn stem(source: &Path) -> String { source - .file_name() - .unwrap_or_default() + .file_stem() + .unwrap_or_else(|| OsStr::new("contract")) .to_string_lossy() .into_owned() } @@ -490,8 +543,8 @@ fn civil_date(days: i64) -> (i64, i64, i64) { #[cfg(test)] mod tests { use super::{ - CACHE_FILE_NAME, Measurement, civil_date, clean, parse, read_cache, tail, timestamp, - write_cache, + ARTIFACT_FILE_NAME, MeasureError, Measurement, civil_date, clean, locate, parse, + read_artifact, tail, timestamp, write_artifact, }; use std::path::Path; use std::time::{Duration, UNIX_EPOCH}; @@ -559,36 +612,90 @@ mod tests { assert_eq!(tail(cleaned, 20), "one\ntwo\nthree\nfour"); } - #[test] - fn a_cache_write_keeps_the_entries_of_other_sources() { - let directory = tempfile::tempdir().expect("a temporary directory is available"); - let source = directory.path().join("MockOwnable.compact"); + /// Seeds `//circuit-info.json` with one measured circuit. + fn seed(artifacts: &Path, directory: &str) { + let target = artifacts.join(directory); + std::fs::create_dir_all(&target).expect("the tree is writable"); std::fs::write( - directory.path().join(CACHE_FILE_NAME), - "{\n \"generatedAt\": \"2026-01-01T00:00:00.000Z\",\n \"files\": {\n \"Other.compact\": [{ \"name\": \"run\", \"k\": 3, \"rows\": 4 }]\n }\n}\n", + target.join(ARTIFACT_FILE_NAME), + "{\n \"generatedAt\": \"2026-01-01T00:00:00.000Z\",\n \"source\": \"src/MockOwnable.compact\",\n \"circuits\": [{ \"name\": \"owner\", \"k\": 7, \"rows\": 74 }]\n}\n", ) - .expect("the cache is writable"); + .expect("the artifact is writable"); + } + #[test] + fn a_written_artifact_reads_back_with_the_source_it_records() { + let directory = tempfile::tempdir().expect("a temporary directory is available"); + let source = Path::new("src/access/test/mocks/MockOwnable.compact"); let written = [measurement("owner", 7, 74)]; - write_cache(&source, &written).expect("the cache is writable"); - assert_eq!( - read_cache(&source).expect("the cache is readable"), - Some(written.to_vec()) + let path = write_artifact( + directory.path(), + source, + "src/access/test/mocks/MockOwnable.compact", + &written, + ) + .expect("the artifact is writable"); + let text = std::fs::read_to_string(&path).expect("the artifact is readable"); + + assert_eq!(path, directory.path().join("MockOwnable/circuit-info.json")); + assert!( + text.contains("\"source\": \"src/access/test/mocks/MockOwnable.compact\""), + "{text}" ); assert_eq!( - read_cache(&directory.path().join("Other.compact")).expect("the cache is readable"), - Some(vec![measurement("run", 3, 4)]) + read_artifact(&path).expect("the artifact parses"), + written.to_vec() ); } #[test] - fn a_source_with_no_cache_entry_reads_as_absent() { + fn a_nested_contract_directory_is_found_by_its_stem() { let directory = tempfile::tempdir().expect("a temporary directory is available"); + seed(directory.path(), "access/MockOwnable"); + + let found = locate( + directory.path(), + Path::new("src/access/test/mocks/MockOwnable.compact"), + ) + .expect("the nested artifact is found"); assert_eq!( - read_cache(&directory.path().join("Gone.compact")).expect("the cache is readable"), - None + found, + directory + .path() + .join("access/MockOwnable/circuit-info.json") + ); + } + + #[test] + fn two_contract_directories_of_one_stem_are_ambiguous() { + let directory = tempfile::tempdir().expect("a temporary directory is available"); + seed(directory.path(), "access/MockOwnable"); + seed(directory.path(), "token/MockOwnable"); + + let error = locate(directory.path(), Path::new("MockOwnable.compact")) + .expect_err("the stem names two directories"); + + assert!( + matches!(error, MeasureError::AmbiguousArtifact { ref stem, ref paths } + if stem == "MockOwnable" && paths.len() == 2), + "{error}" + ); + } + + #[test] + fn a_source_with_no_artifact_names_the_path_it_tried() { + let directory = tempfile::tempdir().expect("a temporary directory is available"); + + let error = locate(directory.path(), Path::new("src/Gone.compact")) + .expect_err("nothing was compiled"); + + assert!( + error + .to_string() + .contains("Gone/circuit-info.json; compile it"), + "{error}" ); } diff --git a/crates/compact-lint/tests/fill.rs b/crates/compact-lint/tests/fill.rs index a36dbd77..0ba93ba0 100644 --- a/crates/compact-lint/tests/fill.rs +++ b/crates/compact-lint/tests/fill.rs @@ -193,7 +193,7 @@ fn an_override_names_the_contract_that_measures_a_file() { } #[test] -fn a_seeded_cache_fills_without_a_compiler() { +fn a_seeded_artifact_fills_without_a_compiler() { assert_case("no-compile", &["--no-compile"], 0); } @@ -238,31 +238,85 @@ fn a_failed_compile_exits_two_with_the_output_tail() { } #[test] -fn a_missing_cache_entry_exits_two_and_names_the_flag() { +fn a_missing_artifact_exits_two_and_names_the_flag() { let directory = work("basic"); let output = fill(directory.path(), &["--no-compile"]); let stderr = String::from_utf8_lossy(&output.stderr); assert_eq!(output.status.code(), Some(EXIT_ERROR)); - assert!(stderr.contains(".circuit-info.json"), "{stderr}"); + assert!( + stderr.contains("artifacts/MockOwnable/circuit-info.json"), + "{stderr}" + ); assert!(stderr.contains("--no-compile"), "{stderr}"); } #[test] -fn a_compile_writes_the_cache_the_builder_shares() { +fn a_compile_writes_the_artifact_circuit_info() { let directory = work("override"); fill(directory.path(), &[]); - let cache = std::fs::read_to_string( + let artifact = std::fs::read_to_string( directory .path() - .join("src/utils/test/mocks/.circuit-info.json"), + .join("artifacts/MockUtilities/circuit-info.json"), + ) + .expect("the artifact was written"); + + assert!(artifact.contains("\"generatedAt\""), "{artifact}"); + assert!( + artifact.contains("\"source\": \"src/utils/test/mocks/MockUtilities.compact\""), + "{artifact}" + ); + assert!(artifact.contains("\"rows\": 310"), "{artifact}"); + assert!( + directory + .path() + .join("artifacts/MockUtilities/compiler/contract-info.json") + .is_file(), + "the compiler's own report sits beside it" + ); +} + +#[test] +fn a_hierarchical_artifact_tree_is_found_by_stem() { + let directory = work("no-compile"); + let artifacts = directory.path().join("artifacts"); + std::fs::create_dir_all(artifacts.join("access")).expect("the tree is writable"); + std::fs::rename( + artifacts.join("MockOwnable"), + artifacts.join("access/MockOwnable"), ) - .expect("the cache was written"); + .expect("the contract directory is movable"); - assert!(cache.contains("\"generatedAt\""), "{cache}"); - assert!(cache.contains("\"MockUtilities.compact\""), "{cache}"); - assert!(cache.contains("\"rows\": 310"), "{cache}"); + let (code, stdout) = code_and_stdout(&fill(directory.path(), &["--no-compile"])); + + assert_eq!(stdout, expected("no-compile", "expected.txt")); + assert_eq!(code, 0); +} + +#[test] +fn two_artifacts_with_one_stem_are_an_error() { + let directory = work("no-compile"); + let artifacts = directory.path().join("artifacts"); + for subdirectory in ["access", "token"] { + let target = artifacts.join(subdirectory).join("MockOwnable"); + std::fs::create_dir_all(&target).expect("the tree is writable"); + std::fs::copy( + artifacts.join("MockOwnable/circuit-info.json"), + target.join("circuit-info.json"), + ) + .expect("the artifact is copyable"); + } + std::fs::remove_dir_all(artifacts.join("MockOwnable")).expect("the tree is writable"); + + let output = fill(directory.path(), &["--no-compile"]); + let stderr = String::from_utf8_lossy(&output.stderr); + + assert_eq!(output.status.code(), Some(EXIT_ERROR)); + assert!(stderr.contains("named MockOwnable"), "{stderr}"); + assert!(stderr.contains("access/MockOwnable"), "{stderr}"); + assert!(stderr.contains("token/MockOwnable"), "{stderr}"); } #[test] diff --git a/crates/compact-lint/tests/fixtures/fill-no-compile/before/artifacts/MockOwnable/circuit-info.json b/crates/compact-lint/tests/fixtures/fill-no-compile/before/artifacts/MockOwnable/circuit-info.json new file mode 100644 index 00000000..5eef4050 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-no-compile/before/artifacts/MockOwnable/circuit-info.json @@ -0,0 +1,11 @@ +{ + "generatedAt": "2026-01-01T00:00:00.000Z", + "source": "src/access/test/mocks/MockOwnable.compact", + "circuits": [ + { + "name": "owner", + "k": 7, + "rows": 74 + } + ] +} diff --git a/crates/compact-lint/tests/fixtures/fill-no-compile/before/src/access/test/mocks/.circuit-info.json b/crates/compact-lint/tests/fixtures/fill-no-compile/before/src/access/test/mocks/.circuit-info.json deleted file mode 100644 index 0c0fa8e7..00000000 --- a/crates/compact-lint/tests/fixtures/fill-no-compile/before/src/access/test/mocks/.circuit-info.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "generatedAt": "2026-01-01T00:00:00.000Z", - "files": { - "MockOwnable.compact": [ - { - "name": "owner", - "k": 7, - "rows": 74 - } - ] - } -} From 46ef29a12ffb52bdbee32ffd7eb60270a790898a Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Wed, 16 Sep 2026 06:36:45 +0200 Subject: [PATCH 15/56] ci(rust): stop persisting checkout credentials The default checkout leaves the job's GITHUB_TOKEN in .git/config, so any later step or build script in the job can read and reuse it. Nothing in this workflow talks to the remote after checkout, so opt out. --- .github/workflows/rust.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index a3f227ab..4775a024 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -23,6 +23,8 @@ jobs: - name: Check out code uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - name: Install the pinned toolchain run: | From f06882b5a19ac08c8aa7d0921be47a4ab7279da3 Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Wed, 16 Sep 2026 06:37:25 +0200 Subject: [PATCH 16/56] docs(compact-tree-sitter): correct the name field claim Both the grammar header and the README said every declaration node carries a `name` field. Four do not, and a consumer that reads `name` unconditionally gets nothing back for them. --- crates/compact-tree-sitter/README.md | 15 +++++++++------ crates/compact-tree-sitter/grammar.js | 7 +++++-- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/crates/compact-tree-sitter/README.md b/crates/compact-tree-sitter/README.md index 50f0d706..f07c988d 100644 --- a/crates/compact-tree-sitter/README.md +++ b/crates/compact-tree-sitter/README.md @@ -8,12 +8,15 @@ leaves everything else opaque. ## What it covers -- Every top-level and module-level declaration is a named node with a `name` - field: `pragma_declaration`, `include_declaration`, `import_declaration`, - `export_declaration`, `module_declaration`, `struct_declaration`, - `enum_declaration`, `contract_declaration`, `implements_declaration`, - `type_declaration`, `ledger_declaration`, `witness_declaration`, - `constructor_declaration`, `circuit_declaration`. +- Every top-level and module-level declaration is a named node, but the fields + differ per declaration. These carry a `name` field: `pragma_declaration`, + `import_declaration`, `module_declaration`, `struct_declaration`, + `enum_declaration`, `contract_declaration`, `type_declaration`, + `ledger_declaration`, `witness_declaration`, `circuit_declaration`. +- The exceptions: `include_declaration` carries `path`, + `implements_declaration` carries `type`, `constructor_declaration` has no + identifier, and `export_declaration` holds its exported names as bare + `identifier` children with no field. - `module_declaration` recurses: a `module_body` holds the same declarations. - Comments are named nodes in `extras`: `line_comment`, `block_comment`, `doc_comment`. diff --git a/crates/compact-tree-sitter/grammar.js b/crates/compact-tree-sitter/grammar.js index 55c2d258..2ffb9015 100644 --- a/crates/compact-tree-sitter/grammar.js +++ b/crates/compact-tree-sitter/grammar.js @@ -2,8 +2,11 @@ // @ts-check // Declaration-level grammar for Compact (Midnight), language version 0.26. -// Every top-level and module-level declaration is a named node carrying a `name` -// field; bodies, parameter lists and statements stay opaque brace-balanced runs. +// Every top-level and module-level declaration is a named node, but the fields +// vary: most carry `name`, while `include_declaration` carries `path`, +// `implements_declaration` carries `type`, `constructor_declaration` has no +// identifier at all, and `export_declaration` holds bare `identifier` children. +// Bodies, parameter lists and statements stay opaque brace-balanced runs. /** * Comma-separated list with an optional trailing comma. From e2b329d69f8e31dac0772edc871d91b67f5e37bb Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Wed, 16 Sep 2026 06:38:16 +0200 Subject: [PATCH 17/56] test(compact-tree-sitter): skip symlinks in the corpus walk A symlinked directory inside the corpus makes the recursion loop, and a symlinked file is walked twice. Skip both. --- crates/compact-tree-sitter/tests/corpus.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/compact-tree-sitter/tests/corpus.rs b/crates/compact-tree-sitter/tests/corpus.rs index 7ff16ed6..f2ab924e 100644 --- a/crates/compact-tree-sitter/tests/corpus.rs +++ b/crates/compact-tree-sitter/tests/corpus.rs @@ -41,6 +41,11 @@ fn collect_compact_files(dir: &Path, out: &mut Vec) { let path = entry.path(); let name = entry.file_name(); + // A symlinked directory can point back up the tree and loop forever. + if path.is_symlink() { + continue; + } + if path.is_dir() { if !SKIPPED_DIRS.iter().any(|skipped| name == *skipped) { collect_compact_files(&path, out); From 334b4a98a8440e290f2dad8ee1b60efe5722939a Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Wed, 16 Sep 2026 06:40:49 +0200 Subject: [PATCH 18/56] fix(compact-lint): resolve explicit paths against cwd Discovery matches exclude globs against paths relative to the config's directory, but an explicit CLI path stayed relative to the process cwd. Running `check archive` from a subdirectory produced `archive/X.compact`, which never matched an exclude written as `contracts/archive/**`, so excluded files were silently linted. Anchor relative CLI paths at cwd first; the display step still strips cwd, so the report is unchanged. --- crates/compact-lint/src/check.rs | 38 ++++++++++++++++++- crates/compact-lint/tests/check.rs | 15 ++++++++ .../exclude-explicit-dir/compact-lint.toml | 9 +++++ .../contracts/archive/Old.compact | 7 ++++ .../contracts/live/Live.compact | 7 ++++ .../exclude-explicit-dir/expected.txt | 1 + 6 files changed, 76 insertions(+), 1 deletion(-) create mode 100644 crates/compact-lint/tests/fixtures/exclude-explicit-dir/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/exclude-explicit-dir/contracts/archive/Old.compact create mode 100644 crates/compact-lint/tests/fixtures/exclude-explicit-dir/contracts/live/Live.compact create mode 100644 crates/compact-lint/tests/fixtures/exclude-explicit-dir/expected.txt diff --git a/crates/compact-lint/src/check.rs b/crates/compact-lint/src/check.rs index 2f2d2a88..76ee393c 100644 --- a/crates/compact-lint/src/check.rs +++ b/crates/compact-lint/src/check.rs @@ -67,7 +67,8 @@ pub fn run(options: &Options, cwd: &Path) -> Result { let include = config.include_set(source)?; discover::from_globs(&base, &include, &exclude)? } else { - discover::from_paths(&options.paths, &base, &exclude)? + let paths = absolute_paths(&options.paths, cwd); + discover::from_paths(&paths, &base, &exclude)? }; let files: Vec = files.iter().map(|path| display_path(path, cwd)).collect(); @@ -111,7 +112,42 @@ fn resolve_config( } } +/// Discovery matches the exclude globs against paths relative to the config's +/// directory, so a CLI path has to be anchored at `cwd` first: a bare `archive` +/// given from a subdirectory would otherwise never match `contracts/archive/**`. +fn absolute_paths(paths: &[PathBuf], cwd: &Path) -> Vec { + paths + .iter() + .map(|path| { + if path.is_absolute() { + path.clone() + } else { + cwd.join(path) + } + }) + .collect() +} + /// Paths under the working directory print relative to it; anything else prints as is. fn display_path(path: &Path, cwd: &Path) -> PathBuf { path.strip_prefix(cwd).unwrap_or(path).to_owned() } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_relative_path_is_anchored_at_the_working_directory() { + let resolved = absolute_paths(&[PathBuf::from("archive")], Path::new("/repo/contracts")); + + assert_eq!(resolved, vec![PathBuf::from("/repo/contracts/archive")]); + } + + #[test] + fn an_absolute_path_is_left_alone() { + let resolved = absolute_paths(&[PathBuf::from("/elsewhere/X.compact")], Path::new("/repo")); + + assert_eq!(resolved, vec![PathBuf::from("/elsewhere/X.compact")]); + } +} diff --git a/crates/compact-lint/tests/check.rs b/crates/compact-lint/tests/check.rs index 452c09dc..c4fc99f9 100644 --- a/crates/compact-lint/tests/check.rs +++ b/crates/compact-lint/tests/check.rs @@ -115,6 +115,21 @@ fn an_explicit_path_replaces_the_include_globs() { ); } +#[test] +fn an_exclude_glob_applies_to_an_explicit_path_given_from_a_subdirectory() { + let output = binary() + .current_dir(case("exclude-explicit-dir").join("contracts")) + .args(["check", "--no-format", "live", "archive"]) + .output() + .expect("the binary ran"); + + assert_eq!( + String::from_utf8(output.stdout).expect("the report is UTF-8"), + expected("exclude-explicit-dir") + ); + assert_eq!(output.status.code(), Some(EXIT_FINDINGS)); +} + #[test] fn an_explicit_config_anchors_discovery_at_the_working_directory() { let config = case("clean").join("compact-lint.toml"); diff --git a/crates/compact-lint/tests/fixtures/exclude-explicit-dir/compact-lint.toml b/crates/compact-lint/tests/fixtures/exclude-explicit-dir/compact-lint.toml new file mode 100644 index 00000000..02f0d72f --- /dev/null +++ b/crates/compact-lint/tests/fixtures/exclude-explicit-dir/compact-lint.toml @@ -0,0 +1,9 @@ +version = 1 +include = ["contracts/**/*.compact"] +exclude = ["contracts/archive/**"] + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.ledger] +tags = ["@description"] diff --git a/crates/compact-lint/tests/fixtures/exclude-explicit-dir/contracts/archive/Old.compact b/crates/compact-lint/tests/fixtures/exclude-explicit-dir/contracts/archive/Old.compact new file mode 100644 index 00000000..57a9386d --- /dev/null +++ b/crates/compact-lint/tests/fixtures/exclude-explicit-dir/contracts/archive/Old.compact @@ -0,0 +1,7 @@ +/** + * @module Old + * @description A retired module the config excludes. + */ +export module Old { + export ledger _owner: Bytes<32>; +} diff --git a/crates/compact-lint/tests/fixtures/exclude-explicit-dir/contracts/live/Live.compact b/crates/compact-lint/tests/fixtures/exclude-explicit-dir/contracts/live/Live.compact new file mode 100644 index 00000000..10781e5c --- /dev/null +++ b/crates/compact-lint/tests/fixtures/exclude-explicit-dir/contracts/live/Live.compact @@ -0,0 +1,7 @@ +/** + * @module Live + * @description A maintained module. + */ +export module Live { + export ledger _owner: Bytes<32>; +} diff --git a/crates/compact-lint/tests/fixtures/exclude-explicit-dir/expected.txt b/crates/compact-lint/tests/fixtures/exclude-explicit-dir/expected.txt new file mode 100644 index 00000000..31799ef6 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/exclude-explicit-dir/expected.txt @@ -0,0 +1 @@ +live/Live.compact:6:3: missing-doc: ledger `_owner` has no doc comment From 93448137ec298676f483cf6fd806dede58b0e5ea Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Wed, 16 Sep 2026 06:41:17 +0200 Subject: [PATCH 19/56] refactor(compact-lint): mark Tag::new must_use A constructor with no side effects; matches the rest of Tag. --- crates/compact-lint/src/doc.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/compact-lint/src/doc.rs b/crates/compact-lint/src/doc.rs index 685007f1..4da32002 100644 --- a/crates/compact-lint/src/doc.rs +++ b/crates/compact-lint/src/doc.rs @@ -10,6 +10,7 @@ use serde::Deserialize; pub struct Tag(String); impl Tag { + #[must_use] pub fn new(name: impl Into) -> Self { Self(name.into()) } From 3ade154d446b26eaf9d9fb40e832404ef881bce7 Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Wed, 16 Sep 2026 06:42:15 +0200 Subject: [PATCH 20/56] fix(compact-lint): check constraints under docs = none The constraints rule ran after the per-kind docs gate, so kinds.circuit.docs = "none" silently disabled it. The rule is fixed rather than configurable, so it now runs before the gate; only the required-tag loop stays behind it. --- crates/compact-lint/src/rules.rs | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/crates/compact-lint/src/rules.rs b/crates/compact-lint/src/rules.rs index 9bc0bf7a..4e8cefc8 100644 --- a/crates/compact-lint/src/rules.rs +++ b/crates/compact-lint/src/rules.rs @@ -146,6 +146,9 @@ fn check_declaration( check_module_name(declaration, display, findings); } + // The constraints rule is fixed, so it stays outside the per-kind docs policy. + check_constraints(declaration, display, config, strict, findings); + if !requires_docs { return; } @@ -160,8 +163,6 @@ fn check_declaration( )); } } - - check_constraints(declaration, display, config, strict, findings); } /// `@module ` must name the module it documents. @@ -341,6 +342,19 @@ mod tests { ); } + #[test] + fn the_constraints_rule_survives_docs_none() { + let source = + "/** @description Bumps. */\nexport circuit bump(): [] { count.increment(1); }\n"; + let mut config = circuit_config(); + config.kinds.circuit.docs = DocsPolicy::None; + + assert_eq!( + findings(source, &config, false), + ["a.compact:2:1: missing-constraints: circuit `bump` doc comment has no @constraints"] + ); + } + #[test] fn a_placeholder_is_a_finding_only_under_strict() { let source = "/**\n * @description Bumps.\n * @constraints k=?, rows=?\n */\nexport circuit bump(): [] { }\n"; From 0acfa84bb211bece6ff194329ba1569811aeae57 Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Wed, 16 Sep 2026 06:45:39 +0200 Subject: [PATCH 21/56] fix(compact-lint): skip inserting a tag a rename supplies A config that forbids @return, renames it to @returns and requires @returns produced both a rename edit and an insert edit on the same doc comment, so fix left the comment with @returns twice. Drop the insert when a rename in that comment already yields the missing tag. --- crates/compact-lint/src/fix.rs | 26 +++++++++++++++++-- crates/compact-lint/tests/fix.rs | 12 +++++++++ .../after/Supplied.compact | 12 +++++++++ .../before/Supplied.compact | 12 +++++++++ .../fix-rename-supplies-tag/compact-lint.toml | 12 +++++++++ .../fix-rename-supplies-tag/expected.txt | 1 + 6 files changed, 73 insertions(+), 2 deletions(-) create mode 100644 crates/compact-lint/tests/fixtures/fix-rename-supplies-tag/after/Supplied.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-rename-supplies-tag/before/Supplied.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-rename-supplies-tag/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/fix-rename-supplies-tag/expected.txt diff --git a/crates/compact-lint/src/fix.rs b/crates/compact-lint/src/fix.rs index 88e42bd7..a2d21c10 100644 --- a/crates/compact-lint/src/fix.rs +++ b/crates/compact-lint/src/fix.rs @@ -87,9 +87,10 @@ pub fn run(options: &Options, cwd: &Path) -> Result { })?; let newline = newline_of(&source); - let edits: Vec = linter - .issues(path, &source, &target.config, false)? + let issues = linter.issues(path, &source, &target.config, false)?; + let edits: Vec = issues .iter() + .filter(|issue| !supplied_by_a_rename(issue, &issues, &target.config)) .filter_map(|issue| edit_for(issue, &target.config, newline)) .collect(); @@ -109,6 +110,27 @@ pub fn run(options: &Options, cwd: &Path) -> Result { Ok(Outcome { files }) } +/// Whether a forbidden tag in the same doc comment is renamed to the tag this +/// `missing-tag` issue reports. +/// +/// Inserting it as well would leave the comment carrying the tag twice. +fn supplied_by_a_rename(issue: &Issue, issues: &[Issue], config: &Config) -> bool { + let Issue::MissingTag { tag, doc, .. } = issue else { + return false; + }; + + issues.iter().any(|other| { + matches!( + other, + Issue::ForbiddenTag { + tag: forbidden, + doc: other_doc, + .. + } if other_doc == doc && config.rename_of(forbidden) == Some(tag) + ) + }) +} + /// The repair for one issue, or `None` where the rule has no safe fix. /// /// `constraints-format` and `constraints-placeholder` need a measurement a rewrite diff --git a/crates/compact-lint/tests/fix.rs b/crates/compact-lint/tests/fix.rs index fae2b524..c8b5d9e3 100644 --- a/crates/compact-lint/tests/fix.rs +++ b/crates/compact-lint/tests/fix.rs @@ -151,6 +151,18 @@ fn a_forbidden_tag_with_a_replacement_is_renamed_in_place() { assert_case("rename"); } +#[test] +fn a_rename_that_supplies_a_required_tag_suppresses_the_insert() { + assert_case("rename-supplies-tag"); + + let directory = work("rename-supplies-tag"); + run(directory.path(), &["fix"]); + let fixed = std::fs::read_to_string(directory.path().join("Supplied.compact")) + .expect("the fixed source is readable"); + + assert_eq!(fixed.matches("@returns").count(), 1, "{fixed}"); +} + #[test] fn a_stale_module_tag_takes_the_module_name() { assert_case("module-name"); diff --git a/crates/compact-lint/tests/fixtures/fix-rename-supplies-tag/after/Supplied.compact b/crates/compact-lint/tests/fixtures/fix-rename-supplies-tag/after/Supplied.compact new file mode 100644 index 00000000..a405a3bb --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-rename-supplies-tag/after/Supplied.compact @@ -0,0 +1,12 @@ +/** + * @module Supplied + * @description A module whose circuit still uses the old return tag. + */ +export module Supplied { + /** + * @description Does nothing. + * @constraints k=6, rows=28 + * @returns {[]} - Empty tuple. + */ + export circuit run(): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/fix-rename-supplies-tag/before/Supplied.compact b/crates/compact-lint/tests/fixtures/fix-rename-supplies-tag/before/Supplied.compact new file mode 100644 index 00000000..fa377d5a --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-rename-supplies-tag/before/Supplied.compact @@ -0,0 +1,12 @@ +/** + * @module Supplied + * @description A module whose circuit still uses the old return tag. + */ +export module Supplied { + /** + * @description Does nothing. + * @constraints k=6, rows=28 + * @return {[]} - Empty tuple. + */ + export circuit run(): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/fix-rename-supplies-tag/compact-lint.toml b/crates/compact-lint/tests/fixtures/fix-rename-supplies-tag/compact-lint.toml new file mode 100644 index 00000000..815000c7 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-rename-supplies-tag/compact-lint.toml @@ -0,0 +1,12 @@ +version = 1 +include = ["**/*.compact"] + +[tags] +forbid = ["@return"] +rename = { "@return" = "@returns" } + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description", "@returns"] diff --git a/crates/compact-lint/tests/fixtures/fix-rename-supplies-tag/expected.txt b/crates/compact-lint/tests/fixtures/fix-rename-supplies-tag/expected.txt new file mode 100644 index 00000000..9a3fad0e --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-rename-supplies-tag/expected.txt @@ -0,0 +1 @@ +Supplied.compact:9:6: fix: renamed @return to @returns From e64fef967070e64e874321ccce9473cdebd0dbff Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Wed, 16 Sep 2026 06:46:59 +0200 Subject: [PATCH 22/56] fix(compact-lint): validate the fix placeholder The placeholder is written onto a `*` line of a generated doc comment. An empty one produced a blank tag line, a multi-line one broke the comment layout, and one containing `*/` closed the comment early and corrupted the source. Reject all three at load time instead. --- crates/compact-lint/src/config.rs | 63 ++++++++++++++++++++++++++++++- 1 file changed, 62 insertions(+), 1 deletion(-) diff --git a/crates/compact-lint/src/config.rs b/crates/compact-lint/src/config.rs index 002c6d13..6b68d947 100644 --- a/crates/compact-lint/src/config.rs +++ b/crates/compact-lint/src/config.rs @@ -38,6 +38,12 @@ pub enum ConfigError { "config {path} lists tag {tag:?}; tags are spelled with their `@`, like `@description`" )] Tag { path: PathBuf, tag: String }, + #[error("config {path} has an invalid fix.placeholder {placeholder:?}: {reason}")] + Placeholder { + path: PathBuf, + placeholder: String, + reason: &'static str, + }, #[error("config {path} has an invalid glob {pattern:?}")] Glob { path: PathBuf, @@ -198,6 +204,14 @@ impl Config { }); } + if let Some(reason) = placeholder_defect(&config.fix.placeholder) { + return Err(ConfigError::Placeholder { + path: path.to_owned(), + placeholder: config.fix.placeholder.clone(), + reason, + }); + } + Ok(config) } @@ -245,6 +259,20 @@ impl Config { } } +/// Why a placeholder cannot go on a `*` line of a doc comment, or `None` when it can. +fn placeholder_defect(placeholder: &str) -> Option<&'static str> { + if placeholder.trim().is_empty() { + return Some("it is empty"); + } + if placeholder.contains(['\n', '\r']) { + return Some("it spans more than one line"); + } + if placeholder.contains("*/") { + return Some("`*/` would close the comment early"); + } + None +} + fn glob_set(patterns: &[String], path: &Path) -> Result { let mut builder = GlobSetBuilder::new(); for pattern in patterns { @@ -276,9 +304,21 @@ pub fn discover(start: &Path) -> Option { #[cfg(test)] mod tests { - use super::{Config, DocsPolicy, SUPPORTED_VERSION}; + use super::{CONFIG_FILE_NAME, Config, DocsPolicy, SUPPORTED_VERSION}; use crate::doc::Tag; use crate::model::DeclKind; + use tempfile::TempDir; + + /// Loads `snippet` as a config file and returns the rejection it produced. + fn rejection(snippet: &str) -> String { + let directory = TempDir::new().expect("a temporary directory is available"); + let path = directory.path().join(CONFIG_FILE_NAME); + std::fs::write(&path, snippet).expect("the config is writable"); + + Config::load(&path) + .expect_err("the config is invalid") + .to_string() + } #[test] fn defaults_require_docs_on_exported_declarations_only() { @@ -360,6 +400,27 @@ mod tests { assert_eq!(config.fix.placeholder, "FIXME"); } + #[test] + fn an_empty_fix_placeholder_is_rejected() { + let error = rejection("[fix]\nplaceholder = \" \"\n"); + + assert!(error.contains("is empty"), "{error}"); + } + + #[test] + fn a_multi_line_fix_placeholder_is_rejected() { + let error = rejection("[fix]\nplaceholder = \"TO\\nDO\"\n"); + + assert!(error.contains("more than one line"), "{error}"); + } + + #[test] + fn a_fix_placeholder_closing_the_comment_is_rejected() { + let error = rejection("[fix]\nplaceholder = \"TODO */\"\n"); + + assert!(error.contains("close the comment"), "{error}"); + } + #[test] fn an_unknown_kind_is_rejected() { let error = From c4737e6b95bbd5ccc9e4b6dfd1d3f09a2d011f77 Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Wed, 16 Sep 2026 06:48:02 +0200 Subject: [PATCH 23/56] fix(compact-lint): validate rename against forbid A rename only fires from a forbidden-tag finding, so a key that tags.forbid does not list is dead config the author expects to work. A value that tags.forbid does list makes fix rewrite one finding into another, so a second run reports the replacement. Reject both at load time. --- crates/compact-lint/README.md | 7 +++--- crates/compact-lint/src/config.rs | 41 +++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 3 deletions(-) diff --git a/crates/compact-lint/README.md b/crates/compact-lint/README.md index 0c4f3b2e..5f2cfd6a 100644 --- a/crates/compact-lint/README.md +++ b/crates/compact-lint/README.md @@ -159,9 +159,10 @@ Defaults when no config file is found: `"all"` or `"none"` there. - `exclude` filters files found by walking a directory. A file named on the command line is always checked. -- `tags.rename` maps a forbidden tag to the tag `fix` writes in its place. Both spellings - are validated like every other tag. An unmapped forbidden tag is reported, never - rewritten. +- `tags.rename` maps a forbidden tag to the tag `fix` writes in its place. Every key + must appear in `tags.forbid` and no value may, or the config is rejected. Both + spellings are validated like every other tag. An unmapped forbidden tag is reported, + never rewritten. - `fix.placeholder` is the text `fix` writes where it has no value of its own. `examples/compact-contracts.toml` is the config for OpenZeppelin/compact-contracts. diff --git a/crates/compact-lint/src/config.rs b/crates/compact-lint/src/config.rs index 6b68d947..3bddff24 100644 --- a/crates/compact-lint/src/config.rs +++ b/crates/compact-lint/src/config.rs @@ -38,6 +38,14 @@ pub enum ConfigError { "config {path} lists tag {tag:?}; tags are spelled with their `@`, like `@description`" )] Tag { path: PathBuf, tag: String }, + #[error("config {path} renames {tag}, which tags.forbid does not list")] + RenameUnforbidden { path: PathBuf, tag: String }, + #[error("config {path} renames {from} to {to}, which tags.forbid also lists")] + RenameToForbidden { + path: PathBuf, + from: String, + to: String, + }, #[error("config {path} has an invalid fix.placeholder {placeholder:?}: {reason}")] Placeholder { path: PathBuf, @@ -204,6 +212,22 @@ impl Config { }); } + for (from, to) in &config.tags.rename { + if !config.tags.forbid.contains(from) { + return Err(ConfigError::RenameUnforbidden { + path: path.to_owned(), + tag: from.to_string(), + }); + } + if config.tags.forbid.contains(to) { + return Err(ConfigError::RenameToForbidden { + path: path.to_owned(), + from: from.to_string(), + to: to.to_string(), + }); + } + } + if let Some(reason) = placeholder_defect(&config.fix.placeholder) { return Err(ConfigError::Placeholder { path: path.to_owned(), @@ -400,6 +424,23 @@ mod tests { assert_eq!(config.fix.placeholder, "FIXME"); } + #[test] + fn a_rename_of_a_tag_that_is_not_forbidden_is_rejected() { + let error = rejection("[tags]\nrename = { \"@return\" = \"@returns\" }\n"); + + assert!(error.contains("@return"), "{error}"); + assert!(error.contains("tags.forbid does not list"), "{error}"); + } + + #[test] + fn a_rename_onto_a_forbidden_tag_is_rejected() { + let error = rejection( + "[tags]\nforbid = [\"@return\", \"@returns\"]\nrename = { \"@return\" = \"@returns\" }\n", + ); + + assert!(error.contains("tags.forbid also lists"), "{error}"); + } + #[test] fn an_empty_fix_placeholder_is_rejected() { let error = rejection("[fix]\nplaceholder = \" \"\n"); From aa06bbdcab7d57964f2fb70608351f86ca01cbc4 Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Wed, 16 Sep 2026 06:49:23 +0200 Subject: [PATCH 24/56] fix(compact-lint): write through a unique temp file The staging file was `.compact.tmp` beside the source and written with fs::write, so a pre-existing file of that name was truncated, and the predictable name let anything else with write access to the directory plant one. Create a sibling `....tmp` exclusively instead, write through the handle, and remove it when a later step fails. --- crates/compact-lint/src/fix.rs | 77 +++++++++++++++++++++++++------- crates/compact-lint/tests/fix.rs | 15 +++++++ 2 files changed, 76 insertions(+), 16 deletions(-) diff --git a/crates/compact-lint/src/fix.rs b/crates/compact-lint/src/fix.rs index a2d21c10..4e44f5f1 100644 --- a/crates/compact-lint/src/fix.rs +++ b/crates/compact-lint/src/fix.rs @@ -1,6 +1,10 @@ //! The `fix` subcommand: turn the fixable issues into edits and rewrite the files. +use std::ffi::{OsStr, OsString}; +use std::fs::{File, OpenOptions}; +use std::io::{ErrorKind, Write}; use std::path::{Path, PathBuf}; +use std::time::{SystemTime, UNIX_EPOCH}; use thiserror::Error; @@ -308,27 +312,68 @@ fn skeleton( format!("{}{newline}{margin}", lines.join(newline)) } +/// How many unique names to try before giving up on the temporary file. +const TEMPORARY_ATTEMPTS: u32 = 8; + /// Writes through a sibling temporary file, so a failed write never truncates the source. fn write_atomically(path: &Path, text: &str) -> Result<(), FixError> { - let temporary = path.with_extension("compact.tmp"); - - std::fs::write(&temporary, text).map_err(|source| FixError::Write { - path: temporary.clone(), - source, - })?; - let permissions = std::fs::metadata(path) - .map_err(|source| FixError::Read { + let (temporary, mut handle) = create_temporary(path)?; + + let write = handle + .write_all(text.as_bytes()) + .and_then(|()| handle.sync_all()) + .and_then(|()| std::fs::metadata(path)) + .and_then(|metadata| std::fs::set_permissions(&temporary, metadata.permissions())) + .and_then(|()| std::fs::rename(&temporary, path)); + + write.map_err(|source| { + // The rename never happened, so the temporary file is ours to clean up. + let _ = std::fs::remove_file(&temporary); + FixError::Write { path: path.to_owned(), source, - })? - .permissions(); - std::fs::set_permissions(&temporary, permissions).map_err(|source| FixError::Write { - path: temporary.clone(), - source, - })?; - std::fs::rename(&temporary, path).map_err(|source| FixError::Write { + } + }) +} + +/// Creates a sibling temporary file under a name nothing else holds. +/// +/// A predictable name lets another process plant a file the write would truncate, so +/// the name carries the pid and a timestamp and the file is created exclusively. +fn create_temporary(path: &Path) -> Result<(PathBuf, File), FixError> { + let directory = path.parent().unwrap_or(Path::new(".")); + let stem = path.file_name().unwrap_or(OsStr::new("source")); + let pid = std::process::id(); + + let mut last = None; + for attempt in 0..TEMPORARY_ATTEMPTS { + let nanos = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |since| since.subsec_nanos()); + let mut name = OsString::from("."); + name.push(stem); + name.push(format!(".{pid}.{nanos}.{attempt}.tmp")); + let candidate = directory.join(name); + + match OpenOptions::new() + .write(true) + .create_new(true) + .open(&candidate) + { + Ok(handle) => return Ok((candidate, handle)), + Err(error) if error.kind() == ErrorKind::AlreadyExists => last = Some(error), + Err(source) => { + return Err(FixError::Write { + path: path.to_owned(), + source, + }); + } + } + } + + Err(FixError::Write { path: path.to_owned(), - source, + source: last.unwrap_or_else(|| ErrorKind::AlreadyExists.into()), }) } diff --git a/crates/compact-lint/tests/fix.rs b/crates/compact-lint/tests/fix.rs index c8b5d9e3..a92aa1f7 100644 --- a/crates/compact-lint/tests/fix.rs +++ b/crates/compact-lint/tests/fix.rs @@ -226,6 +226,21 @@ fn an_explicit_config_replaces_the_one_beside_the_sources() { ); } +#[test] +fn a_file_named_like_the_old_temporary_survives_a_fix() { + let directory = work("rename"); + let planted = directory.path().join("Returns.compact.tmp"); + std::fs::write(&planted, "not mine to truncate\n").expect("the plant is writable"); + + let (code, _) = run(directory.path(), &["fix"]); + + assert_eq!(code, 0); + assert_eq!( + std::fs::read_to_string(&planted).expect("the plant is still there"), + "not mine to truncate\n" + ); +} + #[test] fn a_missing_path_exits_two() { let directory = work("rename"); From f5b467ede0681d93c80aef3dbbc8369e5dee07b2 Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Wed, 16 Sep 2026 06:52:16 +0200 Subject: [PATCH 25/56] docs(compact-lint): tag output fences as text Bare fences trip markdownlint MD040 and give the renderer nothing to go on. --- crates/compact-lint/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/compact-lint/README.md b/crates/compact-lint/README.md index b729b3f3..9deeb0b8 100644 --- a/crates/compact-lint/README.md +++ b/crates/compact-lint/README.md @@ -109,7 +109,7 @@ stays the place a syntax error is reported. Changes go to stdout, one per line: -``` +```text contracts/src/access/Ownable.compact:59:6: fill: @constraints k=?, rows=? -> k=13, rows=4273 ``` @@ -155,13 +155,13 @@ is called from the mock's constructor, never exported β€” or where the compiler' `contract-info.json` marks the circuit `proof: false`, which carries no constraints. The value is left alone and the circuit is reported: -``` +```text contracts/src/access/Ownable.compact:37:6: constraints-unmeasured: circuit `initialize` has no measurement in contracts/src/access/test/mocks/MockOwnable.compact ``` A file with no measurement source at all is reported once, with the candidates tried: -``` +```text contracts/src/utils/Utils.compact:1:1: constraints-unmeasurable: no measurement source for contracts/src/utils/Utils.compact; tried contracts/src/utils/test/mocks/MockUtils.compact, contracts/src/test/mocks/MockUtils.compact ``` From c42ba9b7e89fa96a23b70f7157d53c4b1f7f0ab6 Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Wed, 16 Sep 2026 06:53:30 +0200 Subject: [PATCH 26/56] fix(compact-lint): keep leading parent components normalize popped on every `..`, so a parent-relative constraints template or CLI path lost its leading `..` and first_existing probed a path under the working directory instead of beside it. Only cancel a `..` that has a real component to cancel. --- crates/compact-lint/src/source.rs | 42 ++++++++++++++++++++++++++++--- 1 file changed, 39 insertions(+), 3 deletions(-) diff --git a/crates/compact-lint/src/source.rs b/crates/compact-lint/src/source.rs index 2a5c3944..3e486b0d 100644 --- a/crates/compact-lint/src/source.rs +++ b/crates/compact-lint/src/source.rs @@ -132,14 +132,21 @@ fn display(path: &Path) -> String { } /// Resolves `.` and `..` lexically, so two spellings of one path compare equal. +/// +/// A `..` with nothing to cancel is kept, so a relative path that climbs out of its own +/// directory still points where it did. fn normalize(path: &Path) -> PathBuf { let mut out = PathBuf::new(); for component in path.components() { match component { Component::CurDir => {} - Component::ParentDir => { - out.pop(); - } + Component::ParentDir => match out.components().next_back() { + Some(Component::Normal(_)) => { + out.pop(); + } + Some(Component::RootDir | Component::Prefix(_)) => {} + _ => out.push(Component::ParentDir), + }, other => out.push(other), } } @@ -234,6 +241,35 @@ mod tests { ); } + #[test] + fn a_parent_relative_template_resolves_outside_the_working_directory() { + let tree = tempfile::tempdir().expect("a temporary directory is available"); + for relative in ["work/Ownable.compact", "mocks/Ownable.compact"] { + let path = tree.path().join(relative); + std::fs::create_dir_all(path.parent().expect("the path has a directory")) + .expect("the tree is writable"); + std::fs::write(&path, "").expect("the source is writable"); + } + + let mut config = Config::default(); + config.constraints.sources = vec!["../mocks/{stem}.compact".to_owned()]; + let work = tree.path().join("work"); + + assert_eq!( + resolve(&config, &work, "Ownable.compact"), + Source::Found(PathBuf::from("../mocks/Ownable.compact")) + ); + } + + #[test] + fn normalize_keeps_a_parent_it_cannot_cancel() { + assert_eq!( + super::normalize(Path::new("../mocks/./Ownable.compact")), + PathBuf::from("../mocks/Ownable.compact") + ); + assert_eq!(super::normalize(Path::new("/..")), PathBuf::from("/")); + } + #[test] fn a_file_with_no_candidate_reports_the_paths_it_tried() { let tree = tree(); From 676a2cbe2e96b7b80310ee13afe52a1acd39fe40 Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Wed, 16 Sep 2026 07:00:16 +0200 Subject: [PATCH 27/56] docs(compact-lint): tag output fences as text Bare fences trip markdownlint MD040 and give the renderer nothing to go on. --- crates/compact-lint/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/compact-lint/README.md b/crates/compact-lint/README.md index 933402a1..71fa3055 100644 --- a/crates/compact-lint/README.md +++ b/crates/compact-lint/README.md @@ -58,7 +58,7 @@ compact-lint fill-constraints [PATHS]... [--config ] [--dry-run] [--no-com `Found N errors.` and `Found N warnings.` lines when either is non-zero. - A clean run prints only the summary line. -``` +```text Gaps.compact:6:3 lint/missing-doc FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Γ— Ledger `_owner` has no doc comment. @@ -81,7 +81,7 @@ Gaps.compact:6:3 lint/missing-doc FIXABLE ━━━━━━━━━━━━ with this on stderr: -``` +```text Checked 1 file in 2ms. No fixes applied. Found 3 errors. ``` @@ -94,7 +94,7 @@ Found 3 errors. - `--timings` prints the breakdown that shows it, longest phase first. - `--no-format`, or `format = "off"` in `[lint.rules]`, drops that phase. -``` +```text Timings format check 2.7s 98.4% compact format --check, 39 files, 1 process fix previews 30ms 1.1% 481 previews @@ -227,7 +227,7 @@ stays the place a syntax error is reported. Each filled value is an `info` diagnostic carrying the annotation's before and after: -``` +```text contracts/src/access/Ownable.compact:59:6 fill FIXED ━━━━━━━━━━ i Circuit `transferOwnership` measures k=13, rows=4273. From be4634e71fc20f299c13eb8326b88c4ada0f43bc Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Wed, 16 Sep 2026 07:04:37 +0200 Subject: [PATCH 28/56] fix(compact-lint): keep section entries out of the rename skip A rename writes a bare tag, so it cannot supply a headed entry such as `@notice Security`; skipping the insert left the section missing and a second check still reported it. --- crates/compact-lint/src/fix.rs | 51 ++++++++++++++++++++++++++++++++-- 1 file changed, 48 insertions(+), 3 deletions(-) diff --git a/crates/compact-lint/src/fix.rs b/crates/compact-lint/src/fix.rs index 008061cf..aee4599f 100644 --- a/crates/compact-lint/src/fix.rs +++ b/crates/compact-lint/src/fix.rs @@ -179,11 +179,15 @@ fn diagnostic( /// Whether a forbidden tag in the same doc comment is renamed to the tag this /// `missing-tag` issue reports. /// -/// Inserting it as well would leave the comment carrying the tag twice. +/// Inserting it as well would leave the comment carrying the tag twice. A headed entry +/// is exempt: a rename writes a bare tag, which is not the section that is missing. fn supplied_by_a_rename(issue: &Issue, issues: &[Issue], config: &Config) -> bool { let Issue::MissingTag { entry, doc, .. } = issue else { return false; }; + if entry.heading.is_some() { + return false; + } issues.iter().any(|other| { matches!( @@ -398,10 +402,26 @@ fn skeleton( #[cfg(test)] mod tests { - use super::skeleton; + use super::{skeleton, supplied_by_a_rename}; use crate::config::Config; - use crate::doc::TagSpec; + use crate::doc::{Tag, TagSpec}; use crate::model::DeclKind; + use crate::rules::{Issue, Linter}; + use std::path::Path; + + /// The messages of the issues that still become edits after the rename filter. + fn kept(source: &str, config: &Config) -> Vec { + let issues = Linter::new() + .expect("the bundled grammar loads") + .issues(Path::new("a.compact"), source, config) + .expect("the source produced a tree"); + + issues + .iter() + .filter(|issue| !supplied_by_a_rename(issue, &issues, config)) + .map(Issue::message) + .collect() + } fn config() -> Config { let mut config = Config::default(); @@ -410,6 +430,31 @@ mod tests { config } + #[test] + fn a_rename_supplies_the_bare_tag_but_not_the_section_of_the_same_name() { + let source = "/**\n * @note Something.\n */\nexport circuit run(): [] { }\n"; + let mut config = Config::default(); + config.tags.forbid = vec![Tag::new("@note")]; + config + .tags + .rename + .insert(Tag::new("@note"), Tag::new("@notice")); + config.kinds.circuit.tags = vec![ + TagSpec::parse("@notice"), + TagSpec::parse("@notice Security"), + ]; + + // The bare `@notice` is gone: the rename writes it. The section is not. + assert_eq!( + kept(source, &config), + [ + "Forbidden tag @note.", + "Circuit `run` doc comment has no @constraints.", + "Circuit `run` doc comment has no `@notice Security` section.", + ] + ); + } + #[test] fn a_module_skeleton_names_the_module() { assert_eq!( From 7b74838826f66fcf24d771e16c4184a7f7d98ee5 Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Tue, 15 Sep 2026 09:43:29 +0200 Subject: [PATCH 29/56] feat(compact-lint): add the check command Adds the compact-lint CLI with one subcommand, check, that enforces per-declaration-kind doc-comment templates from compact-lint.toml and optionally runs compact format --check. Findings print one per line as path:line:col: rule: message on stdout; exit 1 on findings, 2 on any error. fix and fill-constraints come later and only add tables to the same toml. * doc: tags parsed into an ordered list with line and column, so a finding points at the @ of the offending tag. * rules: missing-doc, missing-tag, forbidden-tag, module-name, missing-constraints, constraints-format, constraints-placeholder (--strict), parse, format. Constraints apply to exported non-pure circuits only. * config: every field optional, unknown keys and tags without their @ rejected; an explicit --config is a preset anchored at the cwd. * tests: one fixture case per rule through the binary, plus unit tests per module. --- Cargo.lock | 365 +++++++++++++++ Cargo.toml | 10 + crates/compact-lint/Cargo.toml | 33 ++ crates/compact-lint/README.md | 128 ++++++ .../examples/compact-contracts.toml | 40 ++ crates/compact-lint/src/check.rs | 117 +++++ crates/compact-lint/src/config.rs | 305 +++++++++++++ crates/compact-lint/src/discover.rs | 114 +++++ crates/compact-lint/src/doc.rs | 211 +++++++++ crates/compact-lint/src/format.rs | 156 +++++++ crates/compact-lint/src/lib.rs | 16 + crates/compact-lint/src/main.rs | 114 +++++ crates/compact-lint/src/model.rs | 177 ++++++++ crates/compact-lint/src/report.rs | 142 ++++++ crates/compact-lint/src/rules.rs | 415 ++++++++++++++++++ crates/compact-lint/tests/check.rs | 172 ++++++++ .../tests/fixtures/clean/Clean.compact | 56 +++ .../tests/fixtures/clean/compact-lint.toml | 27 ++ .../tests/fixtures/clean/expected.txt | 0 .../constraints-format/Malformed.compact | 17 + .../constraints-format/compact-lint.toml | 27 ++ .../fixtures/constraints-format/expected.txt | 2 + .../constraints-placeholder/Unfilled.compact | 11 + .../constraints-placeholder/compact-lint.toml | 27 ++ .../constraints-placeholder/expected.txt | 1 + .../fixtures/forbidden-tag/Returns.compact | 18 + .../fixtures/forbidden-tag/compact-lint.toml | 27 ++ .../tests/fixtures/forbidden-tag/expected.txt | 2 + .../missing-constraints/Unmeasured.compact | 17 + .../missing-constraints/compact-lint.toml | 27 ++ .../fixtures/missing-constraints/expected.txt | 1 + .../tests/fixtures/missing-doc/Gaps.compact | 20 + .../fixtures/missing-doc/compact-lint.toml | 27 ++ .../tests/fixtures/missing-doc/expected.txt | 3 + .../fixtures/missing-tag/Untagged.compact | 10 + .../fixtures/missing-tag/compact-lint.toml | 27 ++ .../tests/fixtures/missing-tag/expected.txt | 2 + .../fixtures/module-name/Renamed.compact | 6 + .../fixtures/module-name/compact-lint.toml | 27 ++ .../tests/fixtures/module-name/expected.txt | 1 + .../tests/fixtures/parse/Broken.compact | 3 + .../tests/fixtures/parse/compact-lint.toml | 2 + .../tests/fixtures/parse/expected.txt | 1 + 43 files changed, 2904 insertions(+) create mode 100644 crates/compact-lint/Cargo.toml create mode 100644 crates/compact-lint/README.md create mode 100644 crates/compact-lint/examples/compact-contracts.toml create mode 100644 crates/compact-lint/src/check.rs create mode 100644 crates/compact-lint/src/config.rs create mode 100644 crates/compact-lint/src/discover.rs create mode 100644 crates/compact-lint/src/doc.rs create mode 100644 crates/compact-lint/src/format.rs create mode 100644 crates/compact-lint/src/lib.rs create mode 100644 crates/compact-lint/src/main.rs create mode 100644 crates/compact-lint/src/model.rs create mode 100644 crates/compact-lint/src/report.rs create mode 100644 crates/compact-lint/src/rules.rs create mode 100644 crates/compact-lint/tests/check.rs create mode 100644 crates/compact-lint/tests/fixtures/clean/Clean.compact create mode 100644 crates/compact-lint/tests/fixtures/clean/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/clean/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/constraints-format/Malformed.compact create mode 100644 crates/compact-lint/tests/fixtures/constraints-format/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/constraints-format/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/constraints-placeholder/Unfilled.compact create mode 100644 crates/compact-lint/tests/fixtures/constraints-placeholder/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/constraints-placeholder/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/forbidden-tag/Returns.compact create mode 100644 crates/compact-lint/tests/fixtures/forbidden-tag/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/forbidden-tag/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/missing-constraints/Unmeasured.compact create mode 100644 crates/compact-lint/tests/fixtures/missing-constraints/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/missing-constraints/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/missing-doc/Gaps.compact create mode 100644 crates/compact-lint/tests/fixtures/missing-doc/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/missing-doc/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/missing-tag/Untagged.compact create mode 100644 crates/compact-lint/tests/fixtures/missing-tag/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/missing-tag/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/module-name/Renamed.compact create mode 100644 crates/compact-lint/tests/fixtures/module-name/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/module-name/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/parse/Broken.compact create mode 100644 crates/compact-lint/tests/fixtures/parse/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/parse/expected.txt diff --git a/Cargo.lock b/Cargo.lock index f1a04064..80f353a8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -11,6 +11,88 @@ dependencies = [ "memchr", ] +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "assert_cmd" +version = "2.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2aa3a22042e45de04255c7bf3626e239f450200fd0493c1e382263544b20aea6" +dependencies = [ + "anstyle", + "bstr", + "libc", + "predicates", + "predicates-core", + "predicates-tree", + "wait-timeout", +] + +[[package]] +name = "bstr" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f" +dependencies = [ + "memchr", + "regex-automata", + "serde_core", +] + [[package]] name = "cc" version = "1.4.6" @@ -21,6 +103,68 @@ dependencies = [ "shlex", ] +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "compact-lint" +version = "0.1.0" +dependencies = [ + "anyhow", + "assert_cmd", + "clap", + "compact-tree-sitter", + "globset", + "serde", + "thiserror", + "toml", + "tree-sitter", + "walkdir", +] + [[package]] name = "compact-tree-sitter" version = "0.1.0" @@ -30,6 +174,12 @@ dependencies = [ "tree-sitter-language", ] +[[package]] +name = "difflib" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8" + [[package]] name = "equivalent" version = "1.0.2" @@ -42,12 +192,31 @@ version = "0.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3e0f1c7c3a72c66fd80abe965175f7523475c0489a87d3ff9d6e8c87d87a9d2d" +[[package]] +name = "globset" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07c34a9410465b45bd9787443bc7370f37735bad04b0f0cd57ff1a3186c98988" +dependencies = [ + "aho-corasick", + "bstr", + "log", + "regex-automata", + "regex-syntax", +] + [[package]] name = "hashbrown" version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + [[package]] name = "indexmap" version = "2.14.2" @@ -58,18 +227,69 @@ dependencies = [ "hashbrown", ] +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + [[package]] name = "itoa" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + [[package]] name = "memchr" version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "predicates" +version = "3.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ada8f2932f28a27ee7b70dd6c1c39ea0675c55a36879ab92f3a715eaa1e63cfe" +dependencies = [ + "anstyle", + "difflib", + "predicates-core", +] + +[[package]] +name = "predicates-core" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cad38746f3166b4031b1a0d39ad9f954dd291e7854fcc0eed52ee41a0b50d144" + +[[package]] +name = "predicates-tree" +version = "1.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0de1b847b39c8131db0467e9df1ff60e6d0562ab8e9a16e568ad0fdb372e2f2" +dependencies = [ + "predicates-core", + "termtree", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -117,6 +337,15 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + [[package]] name = "serde" version = "1.0.229" @@ -124,6 +353,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" dependencies = [ "serde_core", + "serde_derive", ] [[package]] @@ -160,6 +390,15 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_spanned" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" +dependencies = [ + "serde_core", +] + [[package]] name = "shlex" version = "2.0.1" @@ -172,6 +411,12 @@ version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b2231b7c3057d5e4ad0156fb3dc807d900806020c5ffa3ee6ff2c8c76fb8520" +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + [[package]] name = "syn" version = "3.0.5" @@ -183,6 +428,71 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "termtree" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683" + +[[package]] +name = "thiserror" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc04cd3e1236dd4a98afca4569f2deb3f120e5422a4023be2cb683f8486292af" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "toml" +version = "1.1.6+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "920602543f0911ab71da12c50d59701da54c196d1a2bf5cb4b75667f137a406a" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.1+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2" + [[package]] name = "tree-sitter" version = "0.25.10" @@ -209,6 +519,61 @@ version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "wait-timeout" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" +dependencies = [ + "libc", +] + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" + [[package]] name = "zmij" version = "1.0.23" diff --git a/Cargo.toml b/Cargo.toml index af074357..5e096be2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,16 @@ rust-version = "1.96" pedantic = { level = "warn", priority = -1 } [workspace.dependencies] +anyhow = "1.0" cc = "1" +clap = { version = "4.6", features = ["derive", "env"] } +globset = "0.4" +serde = { version = "1.0", features = ["derive"] } +thiserror = "2.0" +toml = "1.1" tree-sitter = "0.25" +compact-tree-sitter = { version = "0.1.0", path = "crates/compact-tree-sitter" } tree-sitter-language = "0.1" +walkdir = "2.5" + +assert_cmd = "2.2" diff --git a/crates/compact-lint/Cargo.toml b/crates/compact-lint/Cargo.toml new file mode 100644 index 00000000..09834756 --- /dev/null +++ b/crates/compact-lint/Cargo.toml @@ -0,0 +1,33 @@ +[package] +name = "compact-lint" +version = "0.1.0" +description = "Doc-comment linter for Compact sources" +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true + +[lints] +workspace = true + +[lib] +name = "compact_lint" +path = "src/lib.rs" + +[[bin]] +name = "compact-lint" +path = "src/main.rs" + +[dependencies] +anyhow.workspace = true +clap.workspace = true +globset.workspace = true +serde.workspace = true +thiserror.workspace = true +toml.workspace = true +tree-sitter.workspace = true +compact-tree-sitter.workspace = true +walkdir.workspace = true + +[dev-dependencies] +assert_cmd.workspace = true diff --git a/crates/compact-lint/README.md b/crates/compact-lint/README.md new file mode 100644 index 00000000..28bd6284 --- /dev/null +++ b/crates/compact-lint/README.md @@ -0,0 +1,128 @@ +# compact-lint + +Doc-comment linter for Compact sources. It parses `.compact` files with +[`compact-tree-sitter`](../compact-tree-sitter), matches every declaration against the +per-kind template in `compact-lint.toml`, and prints one finding per line. + +## Usage + +```sh +compact-lint check [PATHS]... [--config ] [--strict] [--no-format] [--compact-bin ] +``` + +- `PATHS` β€” files or directories, walked recursively for `.compact`. Skipped while + walking: `node_modules`, `target`, `dist`, `build`, `.git`. +- No `PATHS` β€” the config's `include` globs are used instead. +- `--config ` β€” use this config instead of searching upward for + `compact-lint.toml`. +- `--strict` β€” turn `k=?` / `rows=?` placeholders into findings. Use it on release + branches. +- `--no-format` β€” skip the `compact format --check` pass. Required where the `compact` + binary is unavailable, CI included. +- `--compact-bin ` β€” path to the `compact` binary. Also settable with + `COMPACT_LINT_COMPACT_BIN`; the flag wins. + +Findings go to stdout, one per line, in `path:line:col: rule: message` form (the +rustc / eslint shape, so editors and `grep` both read it). The `N findings in M files` +summary goes to stderr, where `M` is the number of files checked. + +## Exit codes + +- `0` β€” no findings. +- `1` β€” findings. +- `2` β€” usage, config, IO or parser error. + +## Rules + +| Rule | Meaning | +| --- | --- | +| `missing-doc` | The declaration needs docs per `kinds..docs` and has no doc comment attached. | +| `missing-tag` | A tag listed in `kinds..tags` is absent from the doc comment. | +| `forbidden-tag` | A tag listed in `tags.forbid` is present. | +| `module-name` | `@module ` does not name the module it documents. | +| `missing-constraints` | An exported non-pure circuit has no constraints tag. | +| `constraints-format` | The constraints value is not `k=, rows=`. | +| `constraints-placeholder` | `--strict` only: the constraints value still holds a `?`. | +| `parse` | The file holds a syntax defect; the first one is reported and the doc rules are skipped for that file. | +| `format` | `compact format --check` reported the file. | + +Rule detail: + +- **Attachment.** A doc comment counts as attached only when it is the declaration's + immediately preceding *named* sibling. A `//` or `/* */` comment between the two + breaks the attachment and the declaration reads as undocumented. +- **Export.** "Exported" means the declaration carries the `export` token itself. A + non-exported circuit inside an exported module is not exported. +- **Constraints.** The rule applies to exported non-pure circuits only, and that is + fixed, not configurable. A missing doc comment reports as `missing-doc`, not + `missing-constraints`. +- **`module-name`.** The documented name is the first word of the `@module` value, + without its generic arguments or trailing punctuation, so `@module Signer` matches + `module Signer` and `@module Utils.` matches `module Utils`. +- **`forbidden-tag`.** It fires on any doc comment attached to a checked declaration, + including declarations whose docs are optional. + +## Config + +`compact-lint.toml`, searched for upward from the current directory. Every field is +optional; unknown fields are rejected. A config found by walking upward anchors the +`include` globs at its own directory; a config named with `--config` is a shareable +preset, so the globs stay anchored at the current directory. + +```toml +version = 1 +include = ["contracts/src/**/*.compact"] +exclude = ["**/test/mocks/**", "**/archive/**"] + +[constraints] +tag = "@constraints" + +[tags] +forbid = ["@return"] + +[kinds.module] +docs = "exported" +tags = ["@module", "@description"] +``` + +Defaults when no config file is found: + +| Key | Default | +| --- | --- | +| `version` | `1`, the only version this build accepts | +| `include` | `["**/*.compact"]` | +| `exclude` | `[]` | +| `constraints.tag` | `"@constraints"` | +| `tags.forbid` | `[]` | +| `kinds..docs` | `"exported"` | +| `kinds..tags` | `[]` | + +- `kinds` takes one table per kind: `module`, `circuit`, `ledger`, `witness`, + `constructor`, `struct`, `enum`, `contract`, `type`. `pragma`, `import`, `include`, + `export { … }` and `contract implements` are never checked. +- `docs` is `"all"`, `"exported"` or `"none"`. +- `constructor` carries no `export` token, so `"exported"` means "never" for it. Use + `"all"` or `"none"` there. +- `exclude` filters files found by walking a directory. A file named on the command + line is always checked. + +`examples/compact-contracts.toml` is the config for OpenZeppelin/compact-contracts. + +## Doc-comment model + +- `/**`, `*/` and the leading ` * ` gutter are stripped. +- A tag line's first non-blank token is `@` followed by one or more ASCII letters. +- A tag's value is the rest of its line plus every following line until the next tag or + a blank line. +- Repeated tags are kept in source order; `@param` normally repeats. +- `@param {Type} name - text` is not parsed further. + +## Tests + +```sh +cargo test --workspace +``` + +`tests/fixtures//` holds one case per rule plus a clean case: a +`compact-lint.toml`, the `.compact` sources, and `expected.txt`, the exact stdout with +paths relative to the case directory. diff --git a/crates/compact-lint/examples/compact-contracts.toml b/crates/compact-lint/examples/compact-contracts.toml new file mode 100644 index 00000000..402186d0 --- /dev/null +++ b/crates/compact-lint/examples/compact-contracts.toml @@ -0,0 +1,40 @@ +# compact-lint config for OpenZeppelin/compact-contracts. +# Copy it to the repository root as compact-lint.toml. + +version = 1 +include = ["contracts/src/**/*.compact"] +exclude = ["**/test/mocks/**", "**/archive/**"] + +# `@constraints` is the default; set `tag` to point the rule at another annotation. +[constraints] +tag = "@constraints" + +[tags] +forbid = ["@return"] + +[kinds.module] +docs = "exported" +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] + +[kinds.ledger] +tags = ["@description"] + +[kinds.witness] +docs = "all" +tags = ["@description"] + +[kinds.struct] +tags = ["@description"] + +[kinds.enum] +tags = ["@description"] + +[kinds.constructor] +docs = "none" + +[kinds.contract] + +[kinds.type] diff --git a/crates/compact-lint/src/check.rs b/crates/compact-lint/src/check.rs new file mode 100644 index 00000000..2f2d2a88 --- /dev/null +++ b/crates/compact-lint/src/check.rs @@ -0,0 +1,117 @@ +//! The `check` subcommand: resolve config, collect files, run the rules. + +use std::ffi::OsString; +use std::path::{Path, PathBuf}; + +use thiserror::Error; + +use crate::config::{Config, ConfigError, discover as discover_config}; +use crate::discover::{self, DiscoverError}; +use crate::format::{self, FormatError}; +use crate::report::Finding; +use crate::rules::{LintError, Linter}; + +#[derive(Debug, Error)] +pub enum CheckError { + #[error(transparent)] + Config(#[from] ConfigError), + #[error(transparent)] + Discover(#[from] DiscoverError), + #[error(transparent)] + Lint(#[from] LintError), + #[error(transparent)] + Format(#[from] FormatError), + #[error("cannot read {path}")] + Read { + path: PathBuf, + #[source] + source: std::io::Error, + }, +} + +/// Everything the `check` subcommand needs, already resolved from flags and env. +pub struct Options { + pub paths: Vec, + pub config_path: Option, + pub strict: bool, + pub no_format: bool, + pub compact_bin: OsString, +} + +/// The findings, plus how many files produced them. +pub struct Outcome { + pub findings: Vec, + pub files_checked: usize, +} + +impl Outcome { + #[must_use] + pub fn summary(&self) -> String { + format!( + "{} findings in {} files", + self.findings.len(), + self.files_checked + ) + } +} + +/// Runs the subcommand with `cwd` as the working directory. +/// # Errors +/// Returns an error when the config, the file walk, the parser or the formatter fails. +pub fn run(options: &Options, cwd: &Path) -> Result { + let (config, config_path, base) = resolve_config(options, cwd)?; + let source = config_path.as_deref().unwrap_or(Path::new("")); + + let exclude = config.exclude_set(source)?; + let files = if options.paths.is_empty() { + let include = config.include_set(source)?; + discover::from_globs(&base, &include, &exclude)? + } else { + discover::from_paths(&options.paths, &base, &exclude)? + }; + let files: Vec = files.iter().map(|path| display_path(path, cwd)).collect(); + + let mut linter = Linter::new()?; + let mut findings = Vec::new(); + for path in &files { + let text = std::fs::read_to_string(path).map_err(|source| CheckError::Read { + path: path.clone(), + source, + })?; + findings.extend(linter.check(path, &text, &config, options.strict)?); + } + + if !options.no_format { + findings.extend(format::check(&options.compact_bin, &files)?); + } + + findings.sort_by(|left, right| left.sort_key().cmp(&right.sort_key())); + Ok(Outcome { + findings, + files_checked: files.len(), + }) +} + +/// An explicit `--config` is a shareable preset, so glob discovery stays anchored at +/// `cwd`; a config found by walking upward anchors discovery at its own directory. +fn resolve_config( + options: &Options, + cwd: &Path, +) -> Result<(Config, Option, PathBuf), ConfigError> { + if let Some(path) = options.config_path.as_deref() { + return Ok((Config::load(path)?, Some(path.to_owned()), cwd.to_owned())); + } + + match discover_config(cwd) { + Some(path) => { + let base = path.parent().unwrap_or(cwd).to_owned(); + Ok((Config::load(&path)?, Some(path), base)) + } + None => Ok((Config::default(), None, cwd.to_owned())), + } +} + +/// Paths under the working directory print relative to it; anything else prints as is. +fn display_path(path: &Path, cwd: &Path) -> PathBuf { + path.strip_prefix(cwd).unwrap_or(path).to_owned() +} diff --git a/crates/compact-lint/src/config.rs b/crates/compact-lint/src/config.rs new file mode 100644 index 00000000..0d7ae2ba --- /dev/null +++ b/crates/compact-lint/src/config.rs @@ -0,0 +1,305 @@ +//! `compact-lint.toml`: discovery, parsing, and the built-in defaults. + +use std::path::{Path, PathBuf}; + +use globset::{Glob, GlobSet, GlobSetBuilder}; +use serde::Deserialize; +use thiserror::Error; + +use crate::doc::Tag; +use crate::model::DeclKind; + +/// The config file name searched for upward from the current directory. +pub const CONFIG_FILE_NAME: &str = "compact-lint.toml"; + +/// The only schema version this build understands. +pub const SUPPORTED_VERSION: u32 = 1; + +#[derive(Debug, Error)] +pub enum ConfigError { + #[error("cannot read config {path}")] + Read { + path: PathBuf, + #[source] + source: std::io::Error, + }, + #[error("cannot parse config {path}")] + Parse { + path: PathBuf, + #[source] + source: toml::de::Error, + }, + #[error( + "config {path} is version {found}, but this build understands version {SUPPORTED_VERSION}" + )] + Version { path: PathBuf, found: u32 }, + #[error( + "config {path} lists tag {tag:?}; tags are spelled with their `@`, like `@description`" + )] + Tag { path: PathBuf, tag: String }, + #[error("config {path} has an invalid glob {pattern:?}")] + Glob { + path: PathBuf, + pattern: String, + #[source] + source: globset::Error, + }, +} + +/// How much of a kind needs documenting. +#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "lowercase")] +pub enum DocsPolicy { + /// Every declaration of the kind. + All, + /// Only declarations carrying the `export` token. + #[default] + Exported, + /// The kind is not checked for docs. + None, +} + +/// Per-kind requirements. +#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields, default)] +pub struct KindConfig { + pub docs: DocsPolicy, + pub tags: Vec, +} + +/// One table per checked declaration kind. +#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields, default)] +pub struct KindsConfig { + pub module: KindConfig, + pub circuit: KindConfig, + pub ledger: KindConfig, + pub witness: KindConfig, + pub constructor: KindConfig, + #[serde(rename = "struct")] + pub struct_: KindConfig, + #[serde(rename = "enum")] + pub enum_: KindConfig, + pub contract: KindConfig, + #[serde(rename = "type")] + pub type_: KindConfig, +} + +impl KindsConfig { + #[must_use] + pub fn get(&self, kind: DeclKind) -> &KindConfig { + match kind { + DeclKind::Module => &self.module, + DeclKind::Circuit => &self.circuit, + DeclKind::Ledger => &self.ledger, + DeclKind::Witness => &self.witness, + DeclKind::Constructor => &self.constructor, + DeclKind::Struct => &self.struct_, + DeclKind::Enum => &self.enum_, + DeclKind::Contract => &self.contract, + DeclKind::Type => &self.type_, + } + } +} + +/// The circuit constraints annotation. +#[derive(Clone, Debug, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields, default)] +pub struct ConstraintsConfig { + pub tag: Tag, +} + +impl Default for ConstraintsConfig { + fn default() -> Self { + Self { + tag: Tag::new("@constraints"), + } + } +} + +/// Tags no doc comment may carry. +#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields, default)] +pub struct TagsConfig { + pub forbid: Vec, +} + +/// A parsed `compact-lint.toml`, or the built-in defaults when no file was found. +#[derive(Clone, Debug, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields, default)] +pub struct Config { + pub version: u32, + pub include: Vec, + pub exclude: Vec, + pub constraints: ConstraintsConfig, + pub tags: TagsConfig, + pub kinds: KindsConfig, +} + +impl Default for Config { + fn default() -> Self { + Self { + version: SUPPORTED_VERSION, + include: vec!["**/*.compact".to_owned()], + exclude: Vec::new(), + constraints: ConstraintsConfig::default(), + tags: TagsConfig::default(), + kinds: KindsConfig::default(), + } + } +} + +impl Config { + /// Parses a config file and rejects a version this build does not implement. + /// # Errors + /// Returns an error when the file is unreadable, malformed, or a future version. + pub fn load(path: &Path) -> Result { + let text = std::fs::read_to_string(path).map_err(|source| ConfigError::Read { + path: path.to_owned(), + source, + })?; + + let config: Self = toml::from_str(&text).map_err(|source| ConfigError::Parse { + path: path.to_owned(), + source, + })?; + + if config.version != SUPPORTED_VERSION { + return Err(ConfigError::Version { + path: path.to_owned(), + found: config.version, + }); + } + + if let Some(tag) = config.tags().find(|tag| !tag.is_well_formed()) { + return Err(ConfigError::Tag { + path: path.to_owned(), + tag: tag.to_string(), + }); + } + + Ok(config) + } + + /// Every tag the config mentions: required per kind, forbidden, and the constraints tag. + fn tags(&self) -> impl Iterator { + let per_kind = [ + &self.kinds.module, + &self.kinds.circuit, + &self.kinds.ledger, + &self.kinds.witness, + &self.kinds.constructor, + &self.kinds.struct_, + &self.kinds.enum_, + &self.kinds.contract, + &self.kinds.type_, + ] + .into_iter() + .flat_map(|kind| kind.tags.iter()); + + per_kind + .chain(self.tags.forbid.iter()) + .chain(std::iter::once(&self.constraints.tag)) + } + + /// Compiles the `include` globs. + /// # Errors + /// Returns an error when a pattern is not a valid glob. + pub fn include_set(&self, path: &Path) -> Result { + glob_set(&self.include, path) + } + + /// Compiles the `exclude` globs; an empty set matches nothing. + /// # Errors + /// Returns an error when a pattern is not a valid glob. + pub fn exclude_set(&self, path: &Path) -> Result { + glob_set(&self.exclude, path) + } +} + +fn glob_set(patterns: &[String], path: &Path) -> Result { + let mut builder = GlobSetBuilder::new(); + for pattern in patterns { + let glob = Glob::new(pattern).map_err(|source| ConfigError::Glob { + path: path.to_owned(), + pattern: pattern.clone(), + source, + })?; + builder.add(glob); + } + builder.build().map_err(|source| ConfigError::Glob { + path: path.to_owned(), + pattern: String::new(), + source, + }) +} + +/// Walks up from `start` looking for `compact-lint.toml`. +#[must_use] +pub fn discover(start: &Path) -> Option { + for directory in start.ancestors() { + let candidate = directory.join(CONFIG_FILE_NAME); + if candidate.is_file() { + return Some(candidate); + } + } + None +} + +#[cfg(test)] +mod tests { + use super::{Config, DocsPolicy, SUPPORTED_VERSION}; + use crate::doc::Tag; + use crate::model::DeclKind; + + #[test] + fn defaults_require_docs_on_exported_declarations_only() { + let config = Config::default(); + + assert_eq!(config.version, SUPPORTED_VERSION); + assert_eq!(config.constraints.tag, Tag::new("@constraints")); + for kind in [DeclKind::Module, DeclKind::Circuit, DeclKind::Type] { + assert_eq!(config.kinds.get(kind).docs, DocsPolicy::Exported); + assert!(config.kinds.get(kind).tags.is_empty()); + } + } + + #[test] + fn omitted_tables_fall_back_to_defaults() { + let config: Config = toml::from_str("version = 1\n[kinds.witness]\ndocs = \"all\"\n") + .expect("the snippet is valid config"); + + assert_eq!(config.kinds.witness.docs, DocsPolicy::All); + assert_eq!(config.kinds.circuit.docs, DocsPolicy::Exported); + assert_eq!(config.include, ["**/*.compact"]); + } + + #[test] + fn an_unknown_key_is_rejected() { + let error = toml::from_str::("verison = 1\n").expect_err("the key is misspelled"); + + assert!(error.to_string().contains("verison"), "{error}"); + } + + #[test] + fn a_tag_without_its_at_sign_is_rejected() { + let dir = std::env::temp_dir().join(format!("compact-lint-config-{}", std::process::id())); + std::fs::create_dir_all(&dir).expect("the temp dir is writable"); + let path = dir.join("compact-lint.toml"); + std::fs::write(&path, "[kinds.circuit]\ntags = [\"description\"]\n") + .expect("the config is writable"); + + let error = Config::load(&path).expect_err("the tag lacks its @"); + + assert!(error.to_string().contains("\"description\""), "{error}"); + std::fs::remove_dir_all(&dir).expect("the temp dir is removable"); + } + + #[test] + fn an_unknown_kind_is_rejected() { + let error = + toml::from_str::("[kinds.circiut]\n").expect_err("the kind is misspelled"); + + assert!(error.to_string().contains("circiut"), "{error}"); + } +} diff --git a/crates/compact-lint/src/discover.rs b/crates/compact-lint/src/discover.rs new file mode 100644 index 00000000..f647c9f1 --- /dev/null +++ b/crates/compact-lint/src/discover.rs @@ -0,0 +1,114 @@ +//! Turning CLI paths and config globs into the list of files to check. + +use std::path::{Path, PathBuf}; + +use globset::GlobSet; +use thiserror::Error; +use walkdir::WalkDir; + +/// Directories that never hold first-party Compact sources. +const SKIPPED_DIRS: [&str; 5] = ["node_modules", "target", "dist", "build", ".git"]; + +const COMPACT_EXTENSION: &str = "compact"; + +#[derive(Debug, Error)] +pub enum DiscoverError { + #[error("cannot walk {path}")] + Walk { + path: PathBuf, + #[source] + source: walkdir::Error, + }, + #[error("path {0} does not exist")] + Missing(PathBuf), +} + +/// Collects the `.compact` files under the given paths. +/// +/// A path named on the command line is always checked, even when `exclude` matches +/// it; files found by walking a directory are filtered by `exclude`. +/// # Errors +/// Returns an error when a path does not exist or a directory cannot be walked. +pub fn from_paths( + paths: &[PathBuf], + base: &Path, + exclude: &GlobSet, +) -> Result, DiscoverError> { + let mut files = Vec::new(); + + for path in paths { + if path.is_file() { + files.push(path.clone()); + } else if path.is_dir() { + walk(path, base, exclude, None, &mut files)?; + } else { + return Err(DiscoverError::Missing(path.clone())); + } + } + + Ok(sorted(files)) +} + +/// Collects the `.compact` files under `base` that `include` matches and `exclude` does not. +/// # Errors +/// Returns an error when `base` cannot be walked. +pub fn from_globs( + base: &Path, + include: &GlobSet, + exclude: &GlobSet, +) -> Result, DiscoverError> { + let mut files = Vec::new(); + walk(base, base, exclude, Some(include), &mut files)?; + Ok(sorted(files)) +} + +fn walk( + root: &Path, + base: &Path, + exclude: &GlobSet, + include: Option<&GlobSet>, + out: &mut Vec, +) -> Result<(), DiscoverError> { + let walker = WalkDir::new(root) + .follow_links(false) + .into_iter() + .filter_entry(|entry| entry.depth() == 0 || !is_skipped_dir(entry.file_name())); + + for entry in walker { + let entry = entry.map_err(|source| DiscoverError::Walk { + path: root.to_owned(), + source, + })?; + + if !entry.file_type().is_file() { + continue; + } + + let path = entry.path(); + if path + .extension() + .is_none_or(|extension| extension != COMPACT_EXTENSION) + { + continue; + } + + let relative = path.strip_prefix(base).unwrap_or(path); + if include.is_some_and(|set| !set.is_match(relative)) || exclude.is_match(relative) { + continue; + } + + out.push(path.to_owned()); + } + + Ok(()) +} + +fn is_skipped_dir(name: &std::ffi::OsStr) -> bool { + SKIPPED_DIRS.iter().any(|skipped| name == *skipped) +} + +fn sorted(mut files: Vec) -> Vec { + files.sort(); + files.dedup(); + files +} diff --git a/crates/compact-lint/src/doc.rs b/crates/compact-lint/src/doc.rs new file mode 100644 index 00000000..685007f1 --- /dev/null +++ b/crates/compact-lint/src/doc.rs @@ -0,0 +1,211 @@ +//! Parsing of `/** … */` doc comments into an ordered tag list. + +use std::fmt; + +use serde::Deserialize; + +/// A doc-comment tag name, stored with its leading `@` (`@description`). +#[derive(Clone, Debug, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[serde(transparent)] +pub struct Tag(String); + +impl Tag { + pub fn new(name: impl Into) -> Self { + Self(name.into()) + } + + #[must_use] + pub fn as_str(&self) -> &str { + &self.0 + } + + /// `@` followed by at least one ASCII letter, the same shape the parser recognises. + #[must_use] + pub fn is_well_formed(&self) -> bool { + self.0.strip_prefix('@').is_some_and(|name| { + !name.is_empty() && name.bytes().all(|byte| byte.is_ascii_alphabetic()) + }) + } +} + +impl fmt::Display for Tag { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(&self.0) + } +} + +/// One tag occurrence: its name, its value, and where it sits inside the comment. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct TagOccurrence { + pub tag: Tag, + pub value: String, + /// 0-based line index inside the doc comment, counted from the `/**` line. + pub line_offset: usize, + /// 0-based byte offset of the `@` in its line; on the first line, counted after `/**`. + pub column_offset: usize, +} + +/// A parsed doc comment. Repeated tags (`@param`) are kept in source order. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct DocComment { + tags: Vec, +} + +impl DocComment { + /// Parses the raw `/** … */` text, stripping the delimiters and the ` * ` gutter. + #[must_use] + pub fn parse(raw: &str) -> Self { + let opened = raw.strip_prefix("/**").unwrap_or(raw); + let inner = opened.strip_suffix("*/").unwrap_or(opened); + + let mut tags: Vec = Vec::new(); + let mut open: Option = None; + + for (line_offset, line) in inner.lines().enumerate() { + let content = strip_gutter(line).trim(); + + if content.is_empty() { + open = None; + continue; + } + + if let Some((tag, value)) = split_tag(content) { + tags.push(TagOccurrence { + tag, + value: value.to_owned(), + line_offset, + column_offset: line.find('@').unwrap_or(0), + }); + open = Some(tags.len() - 1); + continue; + } + + // A non-blank, non-tag line continues the tag above it. + if let Some(index) = open + && let Some(occurrence) = tags.get_mut(index) + { + if !occurrence.value.is_empty() { + occurrence.value.push('\n'); + } + occurrence.value.push_str(content); + } + } + + Self { tags } + } + + /// Every tag occurrence, in source order. + #[must_use] + pub fn tags(&self) -> &[TagOccurrence] { + &self.tags + } + + #[must_use] + pub fn has(&self, tag: &Tag) -> bool { + self.tags.iter().any(|occurrence| &occurrence.tag == tag) + } + + /// The first occurrence of `tag`, which is the one every rule reads. + #[must_use] + pub fn first(&self, tag: &Tag) -> Option<&TagOccurrence> { + self.tags.iter().find(|occurrence| &occurrence.tag == tag) + } + + /// The value of the first occurrence of `tag`. + #[must_use] + pub fn value(&self, tag: &Tag) -> Option<&str> { + self.first(tag).map(|occurrence| occurrence.value.as_str()) + } +} + +/// Removes the leading whitespace, one `*`, and one following space from a comment line. +fn strip_gutter(line: &str) -> &str { + let trimmed = line.trim_start(); + match trimmed.strip_prefix('*') { + Some(rest) => rest.strip_prefix(' ').unwrap_or(rest), + None => trimmed, + } +} + +/// A tag line starts with `@` followed by at least one ASCII letter. +fn split_tag(content: &str) -> Option<(Tag, &str)> { + let rest = content.strip_prefix('@')?; + let name_len = rest + .find(|character: char| !character.is_ascii_alphabetic()) + .unwrap_or(rest.len()); + if name_len == 0 { + return None; + } + + let (name, value) = rest.split_at(name_len); + Some((Tag::new(format!("@{name}")), value.trim())) +} + +#[cfg(test)] +mod tests { + use super::{DocComment, Tag}; + + #[test] + fn gutter_and_delimiters_are_stripped() { + let doc = DocComment::parse("/**\n * @description Adds two numbers.\n */"); + + assert_eq!(doc.tags().len(), 1); + assert_eq!(doc.tags()[0].tag, Tag::new("@description")); + assert_eq!(doc.tags()[0].value, "Adds two numbers."); + assert_eq!(doc.tags()[0].line_offset, 1); + assert_eq!(doc.tags()[0].column_offset, 3); + } + + #[test] + fn a_blank_line_ends_a_value() { + let doc = DocComment::parse("/**\n * @notice first\n *\n * loose prose\n */"); + + assert_eq!(doc.value(&Tag::new("@notice")), Some("first")); + } + + #[test] + fn a_non_tag_line_continues_the_tag_above_it() { + let doc = DocComment::parse("/**\n * @notice first\n * second\n */"); + + assert_eq!(doc.value(&Tag::new("@notice")), Some("first\nsecond")); + } + + #[test] + fn repeated_tags_keep_source_order() { + let doc = DocComment::parse( + "/**\n * @param {Uint<8>} a - left\n * @param {Uint<8>} b - right\n */", + ); + + let params: Vec<&str> = doc + .tags() + .iter() + .filter(|occurrence| occurrence.tag == Tag::new("@param")) + .map(|occurrence| occurrence.value.as_str()) + .collect(); + assert_eq!(params, ["{Uint<8>} a - left", "{Uint<8>} b - right"]); + } + + #[test] + fn return_and_returns_are_distinct_tags() { + let doc = DocComment::parse("/**\n * @returns The sum.\n */"); + + assert!(doc.has(&Tag::new("@returns"))); + assert!(!doc.has(&Tag::new("@return"))); + } + + #[test] + fn an_at_sign_without_letters_is_not_a_tag() { + let doc = DocComment::parse("/**\n * @1234 not a tag\n * mail@example.com\n */"); + + assert!(doc.tags().is_empty()); + } + + #[test] + fn a_single_line_comment_parses() { + let doc = DocComment::parse("/** @description One liner. */"); + + assert_eq!(doc.value(&Tag::new("@description")), Some("One liner.")); + assert_eq!(doc.tags()[0].line_offset, 0); + assert_eq!(doc.tags()[0].column_offset, 1); + } +} diff --git a/crates/compact-lint/src/format.rs b/crates/compact-lint/src/format.rs new file mode 100644 index 00000000..d3a0c46a --- /dev/null +++ b/crates/compact-lint/src/format.rs @@ -0,0 +1,156 @@ +//! The optional `compact format --check` pass. + +use std::ffi::OsStr; +use std::path::{Path, PathBuf}; +use std::process::Command; + +use thiserror::Error; + +use crate::report::{Finding, Position, RuleId}; + +/// Environment override for the `compact` binary; the `--compact-bin` flag wins over it. +pub const COMPACT_BIN_ENV: &str = "COMPACT_LINT_COMPACT_BIN"; + +/// The default binary name, resolved through `PATH`. +pub const DEFAULT_COMPACT_BIN: &str = "compact"; + +pub const MESSAGE: &str = "not formatted; run `compact format`"; + +#[derive(Debug, Error)] +pub enum FormatError { + #[error("cannot run `{binary}`; pass --no-format to skip the format check")] + BinaryMissing { binary: String }, + #[error("cannot run `{binary}`")] + Spawn { + binary: String, + #[source] + source: std::io::Error, + }, +} + +/// Runs `compact format --check` once over every file and maps its report to findings. +/// +/// The formatter writes one `:` line per unformatted file to stderr, followed by +/// an indented diff. An output that holds no such line yields one finding on the first +/// checked file carrying the formatter's own first line. +/// # Errors +/// Returns an error when the `compact` binary is missing or cannot be spawned. +pub fn check(binary: &OsStr, files: &[PathBuf]) -> Result, FormatError> { + if files.is_empty() { + return Ok(Vec::new()); + } + + let output = Command::new(binary) + .arg("format") + .arg("--check") + .args(files) + .output() + .map_err(|source| { + let binary = binary.to_string_lossy().into_owned(); + if source.kind() == std::io::ErrorKind::NotFound { + FormatError::BinaryMissing { binary } + } else { + FormatError::Spawn { binary, source } + } + })?; + + if output.status.success() { + return Ok(Vec::new()); + } + + let stderr = String::from_utf8_lossy(&output.stderr); + let stdout = String::from_utf8_lossy(&output.stdout); + let reported: Vec<&str> = reported_paths(&stderr) + .chain(reported_paths(&stdout)) + .collect(); + + if reported.is_empty() { + let raw = first_line(&stderr) + .or_else(|| first_line(&stdout)) + .unwrap_or("compact format --check failed"); + return Ok(vec![Finding::new( + files[0].clone(), + Position::file_start(), + RuleId::FORMAT, + raw.to_owned(), + )]); + } + + Ok(reported + .into_iter() + .map(|path| { + Finding::new( + resolve(path, files), + Position::file_start(), + RuleId::FORMAT, + MESSAGE.to_owned(), + ) + }) + .collect()) +} + +/// Unformatted files are announced as a flush-left `:` line. +fn reported_paths(output: &str) -> impl Iterator { + output.lines().filter_map(|line| { + let path = line.strip_suffix(':')?; + (!path.is_empty() && !path.starts_with(char::is_whitespace) && path.ends_with(".compact")) + .then_some(path) + }) +} + +/// Prefers the path spelling the caller passed in, so output stays consistent. +/// Matching is by whole path components, so `Token.compact` never claims `NativeToken.compact`. +fn resolve(reported: &str, files: &[PathBuf]) -> PathBuf { + let reported = Path::new(reported); + files + .iter() + .find(|file| reported.ends_with(file) || file.ends_with(reported)) + .cloned() + .unwrap_or_else(|| reported.to_owned()) +} + +fn first_line(output: &str) -> Option<&str> { + output.lines().map(str::trim).find(|line| !line.is_empty()) +} + +#[cfg(test)] +mod tests { + use super::{reported_paths, resolve}; + use std::path::PathBuf; + + const SAMPLE: &str = "/tmp/bad.compact:\n 18 | export ledger round: Counter;\n- 21 | - round.increment(1);\n+ 21 | + round.increment(1);\n\nError: formatting failed\n"; + + #[test] + fn flush_left_path_lines_become_findings() { + let paths: Vec<&str> = reported_paths(SAMPLE).collect(); + + assert_eq!(paths, ["/tmp/bad.compact"]); + } + + #[test] + fn indented_diff_lines_are_not_paths() { + let paths: Vec<&str> = reported_paths(" a.compact:\n\ttrailing:\n").collect(); + + assert!(paths.is_empty()); + } + + #[test] + fn an_absolute_report_maps_back_to_the_relative_path_passed_in() { + let files = [PathBuf::from("contracts/src/Token.compact")]; + + assert_eq!( + resolve("/work/contracts/src/Token.compact", &files), + PathBuf::from("contracts/src/Token.compact") + ); + } + + #[test] + fn a_shorter_file_name_with_the_same_suffix_is_not_a_match() { + let files = [PathBuf::from("Token.compact")]; + + assert_eq!( + resolve("/work/NativeToken.compact", &files), + PathBuf::from("/work/NativeToken.compact") + ); + } +} diff --git a/crates/compact-lint/src/lib.rs b/crates/compact-lint/src/lib.rs new file mode 100644 index 00000000..fdaf6e9d --- /dev/null +++ b/crates/compact-lint/src/lib.rs @@ -0,0 +1,16 @@ +//! Doc-comment linter for Compact sources. +//! +//! The crate parses `.compact` files with the bundled tree-sitter grammar, matches each +//! declaration against the per-kind doc-comment template in `compact-lint.toml`, and +//! reports one [`report::Finding`] per violation. + +#![forbid(unsafe_code)] + +pub mod check; +pub mod config; +pub mod discover; +pub mod doc; +pub mod format; +pub mod model; +pub mod report; +pub mod rules; diff --git a/crates/compact-lint/src/main.rs b/crates/compact-lint/src/main.rs new file mode 100644 index 00000000..dc4d3640 --- /dev/null +++ b/crates/compact-lint/src/main.rs @@ -0,0 +1,114 @@ +//! `compact-lint` command line entry point. + +#![forbid(unsafe_code)] + +use std::ffi::OsString; +use std::io::Write; +use std::path::PathBuf; +use std::process::ExitCode; + +use anyhow::{Context, Result}; +use clap::{Parser, Subcommand}; + +use compact_lint::check::{self, Options, Outcome}; +use compact_lint::format::{COMPACT_BIN_ENV, DEFAULT_COMPACT_BIN}; + +/// Exit code for a run that produced findings. +const EXIT_FINDINGS: u8 = 1; + +/// Exit code for a usage, config, IO or parser error. +const EXIT_ERROR: u8 = 2; + +#[derive(Debug, Parser)] +#[command( + name = "compact-lint", + version, + about = "Doc-comment linter for Compact sources" +)] +struct Cli { + #[command(subcommand)] + command: Command, +} + +#[derive(Debug, Subcommand)] +enum Command { + /// Check doc comments against the per-kind templates in compact-lint.toml. + Check(CheckArgs), +} + +#[derive(Debug, clap::Args)] +struct CheckArgs { + /// Files or directories to check; defaults to the config's include globs. + paths: Vec, + + /// Config file to use instead of searching upward for compact-lint.toml. + #[arg(long, value_name = "FILE")] + config: Option, + + /// Report `k=?` / `rows=?` placeholders in the constraints tag. + #[arg(long)] + strict: bool, + + /// Skip the `compact format --check` pass. + #[arg(long)] + no_format: bool, + + /// Path to the `compact` binary. + #[arg(long, value_name = "PATH", env = COMPACT_BIN_ENV)] + compact_bin: Option, +} + +fn main() -> ExitCode { + match run() { + Ok(code) => code, + Err(error) => { + report_error(&error); + ExitCode::from(EXIT_ERROR) + } + } +} + +fn run() -> Result { + let cli = Cli::parse(); + let Command::Check(args) = cli.command; + + let cwd = std::env::current_dir().context("reading the current directory")?; + let options = Options { + paths: args.paths, + config_path: args.config, + strict: args.strict, + no_format: args.no_format, + compact_bin: args + .compact_bin + .unwrap_or_else(|| OsString::from(DEFAULT_COMPACT_BIN)), + }; + + let outcome = check::run(&options, &cwd).context("running the check")?; + emit(&outcome).context("writing the report")?; + + Ok(if outcome.findings.is_empty() { + ExitCode::SUCCESS + } else { + ExitCode::from(EXIT_FINDINGS) + }) +} + +fn emit(outcome: &Outcome) -> std::io::Result<()> { + let stdout = std::io::stdout(); + let mut out = stdout.lock(); + for finding in &outcome.findings { + writeln!(out, "{finding}")?; + } + out.flush()?; + + eprintln!("{}", outcome.summary()); + Ok(()) +} + +/// Prints the error and every source under it, one cause per line. +fn report_error(error: &anyhow::Error) { + eprintln!("compact-lint: {error}"); + for cause in error.chain().skip(1) { + eprintln!(" caused by: {cause}"); + } +} diff --git a/crates/compact-lint/src/model.rs b/crates/compact-lint/src/model.rs new file mode 100644 index 00000000..968eee81 --- /dev/null +++ b/crates/compact-lint/src/model.rs @@ -0,0 +1,177 @@ +//! Declarations the linter checks, lifted out of the tree-sitter tree. + +use std::fmt; + +use tree_sitter::Node; + +use crate::doc::{DocComment, TagOccurrence}; +use crate::report::Position; + +/// The declaration kinds the linter has rules for. +/// +/// `pragma`, `include`, `import`, `export { … }` and `contract implements` are +/// never checked, so they have no variant here. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum DeclKind { + Module, + Circuit, + Ledger, + Witness, + Constructor, + Struct, + Enum, + Contract, + Type, +} + +impl DeclKind { + /// Maps a tree-sitter node kind, returning `None` for unchecked declarations. + #[must_use] + pub fn from_node_kind(node_kind: &str) -> Option { + match node_kind { + "module_declaration" => Some(Self::Module), + "circuit_declaration" => Some(Self::Circuit), + "ledger_declaration" => Some(Self::Ledger), + "witness_declaration" => Some(Self::Witness), + "constructor_declaration" => Some(Self::Constructor), + "struct_declaration" => Some(Self::Struct), + "enum_declaration" => Some(Self::Enum), + "contract_declaration" => Some(Self::Contract), + "type_declaration" => Some(Self::Type), + _ => None, + } + } + + /// The name used in config keys and messages. + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::Module => "module", + Self::Circuit => "circuit", + Self::Ledger => "ledger", + Self::Witness => "witness", + Self::Constructor => "constructor", + Self::Struct => "struct", + Self::Enum => "enum", + Self::Contract => "contract", + Self::Type => "type", + } + } +} + +impl fmt::Display for DeclKind { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(self.as_str()) + } +} + +/// One declaration with the facts the rules need. +#[derive(Clone, Debug)] +pub struct Declaration { + pub kind: DeclKind, + /// The `name` field; `constructor` has none. + pub name: Option, + /// The declaration carries the `export` token itself; nesting never grants it. + pub exported: bool, + pub pure: bool, + pub position: Position, + /// The doc comment immediately preceding the declaration, if one attaches. + pub doc: Option, +} + +/// A doc comment bound to a declaration, with the source line it starts on. +#[derive(Clone, Debug)] +pub struct AttachedDoc { + pub comment: DocComment, + /// 0-based row of the `/**` line, for turning a tag's offset into a position. + pub start_row: usize, + pub start_column: usize, +} + +impl AttachedDoc { + /// The position of a tag's `@`; a first-line offset is counted after the `/**`. + #[must_use] + pub const fn tag_position(&self, occurrence: &TagOccurrence) -> Position { + let column = if occurrence.line_offset == 0 { + self.start_column + "/**".len() + occurrence.column_offset + } else { + occurrence.column_offset + }; + Position::from_zero_based(self.start_row + occurrence.line_offset, column) + } +} + +/// Collects every checked declaration, descending into module bodies. +#[must_use] +pub fn declarations(root: Node<'_>, source: &str) -> Vec { + let mut found = Vec::new(); + collect(root, source, &mut found); + found +} + +fn collect(parent: Node<'_>, source: &str, out: &mut Vec) { + let mut cursor = parent.walk(); + for node in parent.named_children(&mut cursor) { + let Some(kind) = DeclKind::from_node_kind(node.kind()) else { + continue; + }; + + out.push(declaration(kind, node, source)); + + // Only modules nest; every other body is an opaque token run. + if kind == DeclKind::Module + && let Some(body) = node.child_by_field_name("body") + { + collect(body, source, out); + } + } +} + +fn declaration(kind: DeclKind, node: Node<'_>, source: &str) -> Declaration { + let mut cursor = node.walk(); + let mut exported = false; + let mut pure = false; + for child in node.children(&mut cursor) { + match child.kind() { + "export" => exported = true, + "pure" => pure = true, + _ => {} + } + } + + let name = node + .child_by_field_name("name") + .and_then(|name| text(name, source)) + .map(str::to_owned); + + let start = node.start_position(); + + Declaration { + kind, + name, + exported, + pure, + position: Position::from_zero_based(start.row, start.column), + doc: attached_doc(node, source), + } +} + +/// A doc comment attaches only as the immediately preceding named sibling; a line +/// or block comment in between breaks the attachment. +fn attached_doc(node: Node<'_>, source: &str) -> Option { + let previous = node.prev_named_sibling()?; + if previous.kind() != "doc_comment" { + return None; + } + + let start = previous.start_position(); + Some(AttachedDoc { + comment: DocComment::parse(text(previous, source)?), + start_row: start.row, + start_column: start.column, + }) +} + +fn text<'a>(node: Node<'_>, source: &'a str) -> Option<&'a str> { + source.get(node.start_byte()..node.end_byte()) +} diff --git a/crates/compact-lint/src/report.rs b/crates/compact-lint/src/report.rs new file mode 100644 index 00000000..b2d9f172 --- /dev/null +++ b/crates/compact-lint/src/report.rs @@ -0,0 +1,142 @@ +//! Findings and the one-line `path:line:col: rule: message` rendering. + +use std::fmt; +use std::path::{Path, PathBuf}; + +/// A lint rule's stable identifier, as printed in the output and matched by CI greps. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct RuleId(&'static str); + +impl RuleId { + pub const MISSING_DOC: Self = Self("missing-doc"); + pub const MISSING_TAG: Self = Self("missing-tag"); + pub const FORBIDDEN_TAG: Self = Self("forbidden-tag"); + pub const MODULE_NAME: Self = Self("module-name"); + pub const MISSING_CONSTRAINTS: Self = Self("missing-constraints"); + pub const CONSTRAINTS_FORMAT: Self = Self("constraints-format"); + pub const CONSTRAINTS_PLACEHOLDER: Self = Self("constraints-placeholder"); + pub const PARSE: Self = Self("parse"); + pub const FORMAT: Self = Self("format"); + + /// Every rule this build can emit, in the order the README lists them. + pub const ALL: [Self; 9] = [ + Self::MISSING_DOC, + Self::MISSING_TAG, + Self::FORBIDDEN_TAG, + Self::MODULE_NAME, + Self::MISSING_CONSTRAINTS, + Self::CONSTRAINTS_FORMAT, + Self::CONSTRAINTS_PLACEHOLDER, + Self::PARSE, + Self::FORMAT, + ]; + + #[must_use] + pub const fn as_str(self) -> &'static str { + self.0 + } +} + +impl fmt::Display for RuleId { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(self.0) + } +} + +/// A 1-based source position; column 1 is the first byte of a line. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct Position { + pub line: usize, + pub column: usize, +} + +impl Position { + /// Converts a tree-sitter 0-based row/column pair. + #[must_use] + pub const fn from_zero_based(row: usize, column: usize) -> Self { + Self { + line: row + 1, + column: column + 1, + } + } + + /// The start of a file, used by whole-file findings. + #[must_use] + pub const fn file_start() -> Self { + Self { line: 1, column: 1 } + } +} + +/// One lint violation at one source position. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Finding { + pub path: PathBuf, + pub position: Position, + pub rule: RuleId, + pub message: String, +} + +impl Finding { + pub fn new( + path: impl Into, + position: Position, + rule: RuleId, + message: String, + ) -> Self { + Self { + path: path.into(), + position, + rule, + message, + } + } + + /// Sorts findings by file, then position, then rule, so output is stable across runs. + #[must_use] + pub fn sort_key(&self) -> (&Path, Position, RuleId) { + (self.path.as_path(), self.position, self.rule) + } +} + +impl fmt::Display for Finding { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + formatter, + "{}:{}:{}: {}: {}", + self.path.display(), + self.position.line, + self.position.column, + self.rule, + self.message + ) + } +} + +#[cfg(test)] +mod tests { + use super::{Finding, Position, RuleId}; + + #[test] + fn finding_renders_as_path_line_col_rule_message() { + let finding = Finding::new( + "contracts/src/access/Ownable.compact", + Position::from_zero_based(41, 0), + RuleId::MISSING_DOC, + "circuit `assertOnlyOwner` has no doc comment".to_owned(), + ); + + assert_eq!( + finding.to_string(), + "contracts/src/access/Ownable.compact:42:1: missing-doc: circuit `assertOnlyOwner` has no doc comment" + ); + } + + #[test] + fn rule_ids_are_unique() { + let mut ids: Vec<&str> = RuleId::ALL.iter().map(|rule| rule.as_str()).collect(); + ids.sort_unstable(); + let count = ids.len(); + ids.dedup(); + assert_eq!(ids.len(), count); + } +} diff --git a/crates/compact-lint/src/rules.rs b/crates/compact-lint/src/rules.rs new file mode 100644 index 00000000..9bc0bf7a --- /dev/null +++ b/crates/compact-lint/src/rules.rs @@ -0,0 +1,415 @@ +//! The doc-comment rules, run over one parsed file at a time. + +use std::path::{Path, PathBuf}; + +use thiserror::Error; +use tree_sitter::{Node, Parser}; + +use crate::config::{Config, DocsPolicy}; +use crate::doc::Tag; +use crate::model::{DeclKind, Declaration, declarations}; +use crate::report::{Finding, Position, RuleId}; + +#[derive(Debug, Error)] +pub enum LintError { + #[error("the bundled Compact grammar does not match the linked tree-sitter ABI")] + Language(#[source] tree_sitter::LanguageError), + #[error("tree-sitter returned no parse tree for {0}")] + NoTree(PathBuf), +} + +/// A reusable parser plus the rules that run over its trees. +pub struct Linter { + parser: Parser, +} + +impl Linter { + /// # Errors + /// Returns an error when the bundled grammar does not match the linked ABI. + pub fn new() -> Result { + let mut parser = Parser::new(); + parser + .set_language(&compact_tree_sitter::LANGUAGE.into()) + .map_err(LintError::Language)?; + Ok(Self { parser }) + } + + /// Checks one file. `display` is the path printed in findings. + /// + /// A tree holding an `ERROR` or `MISSING` node yields a single `parse` finding and + /// no doc findings, because declarations around the defect are not trustworthy. + /// # Errors + /// Returns an error when tree-sitter produces no tree for `source`. + pub fn check( + &mut self, + display: &Path, + source: &str, + config: &Config, + strict: bool, + ) -> Result, LintError> { + let tree = self + .parser + .parse(source, None) + .ok_or_else(|| LintError::NoTree(display.to_owned()))?; + let root = tree.root_node(); + + if let Some(defect) = first_defect(root) { + return Ok(vec![defect.finding(display)]); + } + + let mut findings = Vec::new(); + for declaration in declarations(root, source) { + check_declaration(&declaration, display, config, strict, &mut findings); + } + findings.sort_by(|left, right| left.sort_key().cmp(&right.sort_key())); + Ok(findings) + } +} + +struct Defect { + position: Position, + kind: String, + missing: bool, +} + +impl Defect { + fn finding(&self, display: &Path) -> Finding { + let message = if self.missing { + format!("parse error: missing {}", self.kind) + } else { + format!("parse error: unexpected {}", self.kind) + }; + Finding::new(display, self.position, RuleId::PARSE, message) + } +} + +/// The first `ERROR` or `MISSING` node in document order. +fn first_defect(node: Node<'_>) -> Option { + if node.is_error() || node.is_missing() { + let start = node.start_position(); + return Some(Defect { + position: Position::from_zero_based(start.row, start.column), + kind: node.kind().to_owned(), + missing: node.is_missing(), + }); + } + + if !node.has_error() { + return None; + } + + let mut cursor = node.walk(); + node.children(&mut cursor).find_map(first_defect) +} + +fn check_declaration( + declaration: &Declaration, + display: &Path, + config: &Config, + strict: bool, + findings: &mut Vec, +) { + let kind_config = config.kinds.get(declaration.kind); + let requires_docs = match kind_config.docs { + DocsPolicy::All => true, + DocsPolicy::Exported => declaration.exported, + DocsPolicy::None => false, + }; + + let Some(attached) = declaration.doc.as_ref() else { + if requires_docs { + findings.push(Finding::new( + display, + declaration.position, + RuleId::MISSING_DOC, + format!("{} has no doc comment", subject(declaration)), + )); + } + return; + }; + + // A forbidden tag is a finding wherever it appears, documented or not. + for forbidden in &config.tags.forbid { + for occurrence in attached.comment.tags() { + if &occurrence.tag == forbidden { + findings.push(Finding::new( + display, + attached.tag_position(occurrence), + RuleId::FORBIDDEN_TAG, + format!("forbidden tag {forbidden}"), + )); + } + } + } + + if declaration.kind == DeclKind::Module { + check_module_name(declaration, display, findings); + } + + if !requires_docs { + return; + } + + for required in &kind_config.tags { + if !attached.comment.has(required) { + findings.push(Finding::new( + display, + declaration.position, + RuleId::MISSING_TAG, + format!("{} doc comment has no {required}", subject(declaration)), + )); + } + } + + check_constraints(declaration, display, config, strict, findings); +} + +/// `@module ` must name the module it documents. +fn check_module_name(declaration: &Declaration, display: &Path, findings: &mut Vec) { + let tag = Tag::new("@module"); + let (Some(attached), Some(name)) = (declaration.doc.as_ref(), declaration.name.as_deref()) + else { + return; + }; + let Some(occurrence) = attached.comment.first(&tag) else { + return; + }; + + let documented = module_name(&occurrence.value); + if documented != name { + findings.push(Finding::new( + display, + attached.tag_position(occurrence), + RuleId::MODULE_NAME, + format!("@module names `{documented}`, but the module is `{name}`"), + )); + } +} + +/// The documented name is the first word, without generic arguments or trailing punctuation. +fn module_name(value: &str) -> &str { + let first = value.split_whitespace().next().unwrap_or_default(); + let without_generics = first.split('<').next().unwrap_or(first); + without_generics.trim_end_matches(['.', ',', ':', ';']) +} + +/// Exported non-pure circuits carry the constraints annotation. +fn check_constraints( + declaration: &Declaration, + display: &Path, + config: &Config, + strict: bool, + findings: &mut Vec, +) { + if declaration.kind != DeclKind::Circuit || !declaration.exported || declaration.pure { + return; + } + let Some(attached) = declaration.doc.as_ref() else { + return; + }; + let tag = &config.constraints.tag; + + let Some(occurrence) = attached.comment.first(tag) else { + findings.push(Finding::new( + display, + declaration.position, + RuleId::MISSING_CONSTRAINTS, + format!("{} doc comment has no {tag}", subject(declaration)), + )); + return; + }; + + // The annotation is one line; anything below it is prose, not part of the value. + let value = occurrence.value.lines().next().unwrap_or_default().trim(); + let position = attached.tag_position(occurrence); + + let Some(placeholders) = parse_constraints(value) else { + findings.push(Finding::new( + display, + position, + RuleId::CONSTRAINTS_FORMAT, + format!("{tag} value `{value}` is not `k=, rows=`"), + )); + return; + }; + + if strict && placeholders { + findings.push(Finding::new( + display, + position, + RuleId::CONSTRAINTS_PLACEHOLDER, + format!("{tag} value `{value}` still holds a placeholder"), + )); + } +} + +/// Matches `k=,*rows=`; returns whether either field is a `?` placeholder. +fn parse_constraints(value: &str) -> Option { + let rest = value.strip_prefix("k=")?; + let (k, rest) = rest.split_once(',')?; + let rows = rest.trim_start().strip_prefix("rows=")?; + + let k_placeholder = is_placeholder(k)?; + let rows_placeholder = is_placeholder(rows)?; + Some(k_placeholder || rows_placeholder) +} + +/// A constraints field is either a decimal count or a `?` placeholder. +fn is_placeholder(field: &str) -> Option { + match field { + "?" => Some(true), + digits if !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit()) => { + Some(false) + } + _ => None, + } +} + +/// The kind plus the backquoted name, or a bare kind when the declaration has no name. +fn subject(declaration: &Declaration) -> String { + match declaration.name.as_deref() { + Some(name) => format!("{} `{name}`", declaration.kind), + None => declaration.kind.to_string(), + } +} + +#[cfg(test)] +mod tests { + use super::{Linter, module_name, parse_constraints}; + use crate::config::{Config, DocsPolicy}; + use crate::doc::Tag; + use std::path::Path; + + fn findings(source: &str, config: &Config, strict: bool) -> Vec { + Linter::new() + .expect("the bundled grammar loads") + .check(Path::new("a.compact"), source, config, strict) + .expect("the source produced a tree") + .iter() + .map(ToString::to_string) + .collect() + } + + fn circuit_config() -> Config { + let mut config = Config::default(); + config.kinds.circuit.tags = vec![Tag::new("@description")]; + config + } + + #[test] + fn a_non_exported_circuit_inside_an_exported_module_needs_no_docs() { + let source = "/** @description M. */\nexport module M {\n circuit helper(): [] { }\n}\n"; + + assert!(findings(source, &Config::default(), false).is_empty()); + } + + #[test] + fn an_exported_module_without_a_doc_comment_is_reported() { + let source = "export module M {\n}\n"; + + assert_eq!( + findings(source, &Config::default(), false), + ["a.compact:1:1: missing-doc: module `M` has no doc comment"] + ); + } + + #[test] + fn a_line_comment_between_the_doc_and_the_declaration_breaks_attachment() { + let source = "/** @description M. */\n// a note\nexport module M {\n}\n"; + + assert_eq!( + findings(source, &Config::default(), false), + ["a.compact:3:1: missing-doc: module `M` has no doc comment"] + ); + } + + #[test] + fn a_pure_exported_circuit_needs_no_constraints() { + let source = "/** @description Adds. */\nexport pure circuit add(a: Uint<8>): Uint<8> { return a; }\n"; + + assert!(findings(source, &circuit_config(), false).is_empty()); + } + + #[test] + fn an_exported_circuit_without_constraints_is_reported() { + let source = + "/** @description Bumps. */\nexport circuit bump(): [] { count.increment(1); }\n"; + + assert_eq!( + findings(source, &circuit_config(), false), + ["a.compact:2:1: missing-constraints: circuit `bump` doc comment has no @constraints"] + ); + } + + #[test] + fn a_placeholder_is_a_finding_only_under_strict() { + let source = "/**\n * @description Bumps.\n * @constraints k=?, rows=?\n */\nexport circuit bump(): [] { }\n"; + let config = circuit_config(); + + assert!(findings(source, &config, false).is_empty()); + assert_eq!( + findings(source, &config, true), + [ + "a.compact:3:4: constraints-placeholder: @constraints value `k=?, rows=?` still holds a placeholder" + ] + ); + } + + #[test] + fn a_forbidden_tag_is_reported_even_where_docs_are_optional() { + let source = "/**\n * @return nothing\n */\ncircuit hidden(): [] { }\n"; + let mut config = Config::default(); + config.tags.forbid = vec![Tag::new("@return")]; + + assert_eq!( + findings(source, &config, false), + ["a.compact:2:4: forbidden-tag: forbidden tag @return"] + ); + } + + #[test] + fn a_witness_under_docs_all_is_checked_without_export() { + let source = "witness wit_secret(): Bytes<32>;\n"; + let mut config = Config::default(); + config.kinds.witness.docs = DocsPolicy::All; + + assert_eq!( + findings(source, &config, false), + ["a.compact:1:1: missing-doc: witness `wit_secret` has no doc comment"] + ); + } + + #[test] + fn a_parse_defect_suppresses_the_doc_rules() { + let source = "export module M {\nexport circuit\n"; + + let reported = findings(source, &Config::default(), false); + assert_eq!(reported.len(), 1, "{reported:?}"); + assert!(reported[0].contains("parse error"), "{reported:?}"); + } + + #[test] + fn the_constraints_tag_is_configurable() { + let source = "/**\n * @description Bumps.\n * @circuitInfo k=6, rows=28\n */\nexport circuit bump(): [] { }\n"; + let mut config = circuit_config(); + config.constraints.tag = Tag::new("@circuitInfo"); + + assert!(findings(source, &config, false).is_empty()); + } + + #[test] + fn constraints_accept_flexible_spacing_after_the_comma() { + assert_eq!(parse_constraints("k=10, rows=626"), Some(false)); + assert_eq!(parse_constraints("k=10,rows=626"), Some(false)); + assert_eq!(parse_constraints("k=?, rows=626"), Some(true)); + assert_eq!(parse_constraints("k=10, rows=626 (approx)"), None); + assert_eq!(parse_constraints("rows=626, k=10"), None); + } + + #[test] + fn a_documented_module_name_drops_generics_and_trailing_punctuation() { + assert_eq!(module_name("Signer"), "Signer"); + assert_eq!(module_name("Utils."), "Utils"); + assert_eq!(module_name("ShieldedToken (archived)"), "ShieldedToken"); + } +} diff --git a/crates/compact-lint/tests/check.rs b/crates/compact-lint/tests/check.rs new file mode 100644 index 00000000..452c09dc --- /dev/null +++ b/crates/compact-lint/tests/check.rs @@ -0,0 +1,172 @@ +//! `compact-lint check` end to end, one fixture case per rule. +//! +//! Every case runs with `--no-format`, because CI has no `compact` binary. + +use std::path::PathBuf; +use std::process::Command; + +use assert_cmd::prelude::*; + +/// Exit code for a run that produced findings. +const EXIT_FINDINGS: i32 = 1; + +/// Exit code for a usage, config, IO or parser error. +const EXIT_ERROR: i32 = 2; + +fn case(name: &str) -> PathBuf { + // The child reports its working directory resolved, so the expectation must be too. + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures") + .join(name) + .canonicalize() + .expect("the fixture case exists") +} + +fn binary() -> Command { + Command::cargo_bin("compact-lint").expect("the binary is built alongside this test") +} + +fn expected(name: &str) -> String { + std::fs::read_to_string(case(name).join("expected.txt")).expect("the case has an expectation") +} + +/// Runs `check` inside a case directory and returns its exit code and stdout. +fn run(name: &str, extra: &[&str]) -> (i32, String) { + let output = binary() + .current_dir(case(name)) + .args(["check", "--no-format"]) + .args(extra) + .output() + .expect("the binary ran"); + + ( + output.status.code().expect("the binary was not signalled"), + String::from_utf8(output.stdout).expect("the report is UTF-8"), + ) +} + +fn assert_case(name: &str, extra: &[&str], code: i32) { + let (actual_code, stdout) = run(name, extra); + + assert_eq!(stdout, expected(name), "stdout for case {name}"); + assert_eq!(actual_code, code, "exit code for case {name}"); +} + +#[test] +fn a_fully_documented_module_reports_nothing() { + assert_case("clean", &[], 0); +} + +#[test] +fn undocumented_declarations_and_detached_docs_report_missing_doc() { + assert_case("missing-doc", &[], EXIT_FINDINGS); +} + +#[test] +fn a_doc_comment_without_a_required_tag_reports_missing_tag() { + assert_case("missing-tag", &[], EXIT_FINDINGS); +} + +#[test] +fn a_forbidden_tag_reports_wherever_it_appears() { + assert_case("forbidden-tag", &[], EXIT_FINDINGS); +} + +#[test] +fn a_module_tag_naming_another_module_reports_module_name() { + assert_case("module-name", &[], EXIT_FINDINGS); +} + +#[test] +fn an_unannotated_exported_circuit_reports_missing_constraints() { + assert_case("missing-constraints", &[], EXIT_FINDINGS); +} + +#[test] +fn a_malformed_constraints_value_reports_constraints_format() { + assert_case("constraints-format", &[], EXIT_FINDINGS); +} + +#[test] +fn a_placeholder_reports_only_under_strict() { + let (code, stdout) = run("constraints-placeholder", &[]); + assert_eq!(stdout, ""); + assert_eq!(code, 0); + + assert_case("constraints-placeholder", &["--strict"], EXIT_FINDINGS); +} + +#[test] +fn a_broken_file_reports_parse_instead_of_crashing() { + assert_case("parse", &[], EXIT_FINDINGS); +} + +#[test] +fn an_explicit_path_replaces_the_include_globs() { + let output = binary() + .current_dir(case("missing-doc")) + .args(["check", "--no-format", "Gaps.compact"]) + .output() + .expect("the binary ran"); + + assert_eq!( + String::from_utf8(output.stdout).expect("the report is UTF-8"), + expected("missing-doc") + ); +} + +#[test] +fn an_explicit_config_anchors_discovery_at_the_working_directory() { + let config = case("clean").join("compact-lint.toml"); + let output = binary() + .current_dir(case("missing-doc")) + .args(["check", "--no-format", "--config"]) + .arg(&config) + .output() + .expect("the binary ran"); + + assert_eq!( + String::from_utf8(output.stdout).expect("the report is UTF-8"), + expected("missing-doc") + ); +} + +#[test] +fn a_missing_compact_binary_exits_two_and_names_the_escape_hatch() { + let output = binary() + .current_dir(case("clean")) + .args(["check", "--compact-bin", "compact-lint-no-such-binary"]) + .output() + .expect("the binary ran"); + + let stderr = String::from_utf8(output.stderr).expect("the error is UTF-8"); + assert_eq!(output.status.code(), Some(EXIT_ERROR), "{stderr}"); + assert!(stderr.contains("--no-format"), "{stderr}"); +} + +#[test] +fn an_unreadable_config_exits_two() { + let output = binary() + .current_dir(case("clean")) + .args(["check", "--no-format", "--config", "compact-lint.toml.nope"]) + .output() + .expect("the binary ran"); + + assert_eq!(output.status.code(), Some(EXIT_ERROR)); +} + +#[test] +fn the_summary_goes_to_stderr_and_the_findings_to_stdout() { + let output = binary() + .current_dir(case("module-name")) + .args(["check", "--no-format"]) + .output() + .expect("the binary ran"); + + let stderr = String::from_utf8(output.stderr).expect("the summary is UTF-8"); + assert_eq!(stderr.trim_end(), "1 findings in 1 files"); + assert!( + String::from_utf8_lossy(&output.stdout).contains("module-name"), + "the rule id belongs on stdout" + ); +} diff --git a/crates/compact-lint/tests/fixtures/clean/Clean.compact b/crates/compact-lint/tests/fixtures/clean/Clean.compact new file mode 100644 index 00000000..030f7857 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/clean/Clean.compact @@ -0,0 +1,56 @@ +pragma language_version >= 0.23.0; + +/** + * @module Clean + * @description A module that satisfies every rule. + */ +export module Clean { + import CompactStandardLibrary; + + /** + * @description Whether the module is initialized. + */ + export ledger _isInitialized: Boolean; + + /** + * @description The caller's secret key. + */ + witness wit_Secret(): Bytes<32>; + + /** + * @description A single counter reading. + */ + export struct Reading { + value: Uint<64> + } + + /** + * @description The directions a counter moves in. + */ + export enum Direction { + Up, + Down + } + + constructor() { + _isInitialized = false; + } + + /** + * @description Doubles its argument. + * @param {Uint<8>} value - The value to double. + * @returns {Uint<16>} The doubled value. + */ + export pure circuit double(value: Uint<8>): Uint<16> { + return value as Uint<16> * 2; + } + + /** + * @description Marks the module initialized. + * @constraints k=10, rows=626 + * @returns {[]} Empty tuple. + */ + export circuit initialize(): [] { + _isInitialized = true; + } +} diff --git a/crates/compact-lint/tests/fixtures/clean/compact-lint.toml b/crates/compact-lint/tests/fixtures/clean/compact-lint.toml new file mode 100644 index 00000000..0813e24c --- /dev/null +++ b/crates/compact-lint/tests/fixtures/clean/compact-lint.toml @@ -0,0 +1,27 @@ +version = 1 +include = ["**/*.compact"] + +[tags] +forbid = ["@return"] + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] + +[kinds.ledger] +tags = ["@description"] + +[kinds.witness] +docs = "all" +tags = ["@description"] + +[kinds.struct] +tags = ["@description"] + +[kinds.enum] +tags = ["@description"] + +[kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/clean/expected.txt b/crates/compact-lint/tests/fixtures/clean/expected.txt new file mode 100644 index 00000000..e69de29b diff --git a/crates/compact-lint/tests/fixtures/constraints-format/Malformed.compact b/crates/compact-lint/tests/fixtures/constraints-format/Malformed.compact new file mode 100644 index 00000000..9e2365ae --- /dev/null +++ b/crates/compact-lint/tests/fixtures/constraints-format/Malformed.compact @@ -0,0 +1,17 @@ +/** + * @module Malformed + * @description A module whose annotations do not parse. + */ +export module Malformed { + /** + * @description The comma is missing. + * @constraints k=10 rows=626 + */ + export circuit first(): [] { } + + /** + * @description The fields are the wrong way round. + * @constraints rows=626, k=10 + */ + export circuit second(): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/constraints-format/compact-lint.toml b/crates/compact-lint/tests/fixtures/constraints-format/compact-lint.toml new file mode 100644 index 00000000..0813e24c --- /dev/null +++ b/crates/compact-lint/tests/fixtures/constraints-format/compact-lint.toml @@ -0,0 +1,27 @@ +version = 1 +include = ["**/*.compact"] + +[tags] +forbid = ["@return"] + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] + +[kinds.ledger] +tags = ["@description"] + +[kinds.witness] +docs = "all" +tags = ["@description"] + +[kinds.struct] +tags = ["@description"] + +[kinds.enum] +tags = ["@description"] + +[kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/constraints-format/expected.txt b/crates/compact-lint/tests/fixtures/constraints-format/expected.txt new file mode 100644 index 00000000..a1b1ac88 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/constraints-format/expected.txt @@ -0,0 +1,2 @@ +Malformed.compact:8:6: constraints-format: @constraints value `k=10 rows=626` is not `k=, rows=` +Malformed.compact:14:6: constraints-format: @constraints value `rows=626, k=10` is not `k=, rows=` diff --git a/crates/compact-lint/tests/fixtures/constraints-placeholder/Unfilled.compact b/crates/compact-lint/tests/fixtures/constraints-placeholder/Unfilled.compact new file mode 100644 index 00000000..4b12883c --- /dev/null +++ b/crates/compact-lint/tests/fixtures/constraints-placeholder/Unfilled.compact @@ -0,0 +1,11 @@ +/** + * @module Unfilled + * @description A module whose annotation is still a placeholder. + */ +export module Unfilled { + /** + * @description Not measured yet. + * @constraints k=?, rows=? + */ + export circuit run(): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/constraints-placeholder/compact-lint.toml b/crates/compact-lint/tests/fixtures/constraints-placeholder/compact-lint.toml new file mode 100644 index 00000000..0813e24c --- /dev/null +++ b/crates/compact-lint/tests/fixtures/constraints-placeholder/compact-lint.toml @@ -0,0 +1,27 @@ +version = 1 +include = ["**/*.compact"] + +[tags] +forbid = ["@return"] + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] + +[kinds.ledger] +tags = ["@description"] + +[kinds.witness] +docs = "all" +tags = ["@description"] + +[kinds.struct] +tags = ["@description"] + +[kinds.enum] +tags = ["@description"] + +[kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/constraints-placeholder/expected.txt b/crates/compact-lint/tests/fixtures/constraints-placeholder/expected.txt new file mode 100644 index 00000000..ba3214ef --- /dev/null +++ b/crates/compact-lint/tests/fixtures/constraints-placeholder/expected.txt @@ -0,0 +1 @@ +Unfilled.compact:8:6: constraints-placeholder: @constraints value `k=?, rows=?` still holds a placeholder diff --git a/crates/compact-lint/tests/fixtures/forbidden-tag/Returns.compact b/crates/compact-lint/tests/fixtures/forbidden-tag/Returns.compact new file mode 100644 index 00000000..61836afc --- /dev/null +++ b/crates/compact-lint/tests/fixtures/forbidden-tag/Returns.compact @@ -0,0 +1,18 @@ +/** + * @module Returns + * @description A module that still uses the old return tag. + */ +export module Returns { + /** + * @description Does nothing. + * @constraints k=6, rows=28 + * @return {[]} - Empty tuple. + */ + export circuit run(): [] { } + + /** + * @description Not exported, so its docs are optional, but the tag is not. + * @return {[]} - Empty tuple. + */ + circuit helper(): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/forbidden-tag/compact-lint.toml b/crates/compact-lint/tests/fixtures/forbidden-tag/compact-lint.toml new file mode 100644 index 00000000..0813e24c --- /dev/null +++ b/crates/compact-lint/tests/fixtures/forbidden-tag/compact-lint.toml @@ -0,0 +1,27 @@ +version = 1 +include = ["**/*.compact"] + +[tags] +forbid = ["@return"] + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] + +[kinds.ledger] +tags = ["@description"] + +[kinds.witness] +docs = "all" +tags = ["@description"] + +[kinds.struct] +tags = ["@description"] + +[kinds.enum] +tags = ["@description"] + +[kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/forbidden-tag/expected.txt b/crates/compact-lint/tests/fixtures/forbidden-tag/expected.txt new file mode 100644 index 00000000..0edaa79e --- /dev/null +++ b/crates/compact-lint/tests/fixtures/forbidden-tag/expected.txt @@ -0,0 +1,2 @@ +Returns.compact:9:6: forbidden-tag: forbidden tag @return +Returns.compact:15:6: forbidden-tag: forbidden tag @return diff --git a/crates/compact-lint/tests/fixtures/missing-constraints/Unmeasured.compact b/crates/compact-lint/tests/fixtures/missing-constraints/Unmeasured.compact new file mode 100644 index 00000000..f8e0a628 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/missing-constraints/Unmeasured.compact @@ -0,0 +1,17 @@ +/** + * @module Unmeasured + * @description A module whose exported circuit is unmeasured. + */ +export module Unmeasured { + /** + * @description Writes to the ledger without an annotation. + */ + export circuit run(): [] { } + + /** + * @description Pure circuits are never annotated. + */ + export pure circuit double(value: Uint<8>): Uint<16> { + return value as Uint<16> * 2; + } +} diff --git a/crates/compact-lint/tests/fixtures/missing-constraints/compact-lint.toml b/crates/compact-lint/tests/fixtures/missing-constraints/compact-lint.toml new file mode 100644 index 00000000..0813e24c --- /dev/null +++ b/crates/compact-lint/tests/fixtures/missing-constraints/compact-lint.toml @@ -0,0 +1,27 @@ +version = 1 +include = ["**/*.compact"] + +[tags] +forbid = ["@return"] + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] + +[kinds.ledger] +tags = ["@description"] + +[kinds.witness] +docs = "all" +tags = ["@description"] + +[kinds.struct] +tags = ["@description"] + +[kinds.enum] +tags = ["@description"] + +[kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/missing-constraints/expected.txt b/crates/compact-lint/tests/fixtures/missing-constraints/expected.txt new file mode 100644 index 00000000..18ec6884 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/missing-constraints/expected.txt @@ -0,0 +1 @@ +Unmeasured.compact:9:3: missing-constraints: circuit `run` doc comment has no @constraints diff --git a/crates/compact-lint/tests/fixtures/missing-doc/Gaps.compact b/crates/compact-lint/tests/fixtures/missing-doc/Gaps.compact new file mode 100644 index 00000000..13a4d3e9 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/missing-doc/Gaps.compact @@ -0,0 +1,20 @@ +/** + * @module Gaps + * @description A module whose members are undocumented. + */ +export module Gaps { + export ledger _owner: Bytes<32>; + + export enum Kind { + One + } + + /** + * @description Detached by the line comment below it. + * @constraints k=6, rows=28 + */ + // The comment that breaks the attachment. + export circuit run(): [] { + _owner = default>; + } +} diff --git a/crates/compact-lint/tests/fixtures/missing-doc/compact-lint.toml b/crates/compact-lint/tests/fixtures/missing-doc/compact-lint.toml new file mode 100644 index 00000000..0813e24c --- /dev/null +++ b/crates/compact-lint/tests/fixtures/missing-doc/compact-lint.toml @@ -0,0 +1,27 @@ +version = 1 +include = ["**/*.compact"] + +[tags] +forbid = ["@return"] + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] + +[kinds.ledger] +tags = ["@description"] + +[kinds.witness] +docs = "all" +tags = ["@description"] + +[kinds.struct] +tags = ["@description"] + +[kinds.enum] +tags = ["@description"] + +[kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/missing-doc/expected.txt b/crates/compact-lint/tests/fixtures/missing-doc/expected.txt new file mode 100644 index 00000000..b3649c78 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/missing-doc/expected.txt @@ -0,0 +1,3 @@ +Gaps.compact:6:3: missing-doc: ledger `_owner` has no doc comment +Gaps.compact:8:3: missing-doc: enum `Kind` has no doc comment +Gaps.compact:17:3: missing-doc: circuit `run` has no doc comment diff --git a/crates/compact-lint/tests/fixtures/missing-tag/Untagged.compact b/crates/compact-lint/tests/fixtures/missing-tag/Untagged.compact new file mode 100644 index 00000000..98d81164 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/missing-tag/Untagged.compact @@ -0,0 +1,10 @@ +/** + * @module Untagged + */ +export module Untagged { + /** + * The module has no @description, and neither has this circuit. + * @constraints k=6, rows=28 + */ + export circuit run(): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/missing-tag/compact-lint.toml b/crates/compact-lint/tests/fixtures/missing-tag/compact-lint.toml new file mode 100644 index 00000000..0813e24c --- /dev/null +++ b/crates/compact-lint/tests/fixtures/missing-tag/compact-lint.toml @@ -0,0 +1,27 @@ +version = 1 +include = ["**/*.compact"] + +[tags] +forbid = ["@return"] + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] + +[kinds.ledger] +tags = ["@description"] + +[kinds.witness] +docs = "all" +tags = ["@description"] + +[kinds.struct] +tags = ["@description"] + +[kinds.enum] +tags = ["@description"] + +[kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/missing-tag/expected.txt b/crates/compact-lint/tests/fixtures/missing-tag/expected.txt new file mode 100644 index 00000000..9fb4a3b1 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/missing-tag/expected.txt @@ -0,0 +1,2 @@ +Untagged.compact:4:1: missing-tag: module `Untagged` doc comment has no @description +Untagged.compact:9:3: missing-tag: circuit `run` doc comment has no @description diff --git a/crates/compact-lint/tests/fixtures/module-name/Renamed.compact b/crates/compact-lint/tests/fixtures/module-name/Renamed.compact new file mode 100644 index 00000000..8ea00b64 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/module-name/Renamed.compact @@ -0,0 +1,6 @@ +/** + * @module Stale + * @description The tag still names the module's old name. + */ +export module Renamed { +} diff --git a/crates/compact-lint/tests/fixtures/module-name/compact-lint.toml b/crates/compact-lint/tests/fixtures/module-name/compact-lint.toml new file mode 100644 index 00000000..0813e24c --- /dev/null +++ b/crates/compact-lint/tests/fixtures/module-name/compact-lint.toml @@ -0,0 +1,27 @@ +version = 1 +include = ["**/*.compact"] + +[tags] +forbid = ["@return"] + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] + +[kinds.ledger] +tags = ["@description"] + +[kinds.witness] +docs = "all" +tags = ["@description"] + +[kinds.struct] +tags = ["@description"] + +[kinds.enum] +tags = ["@description"] + +[kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/module-name/expected.txt b/crates/compact-lint/tests/fixtures/module-name/expected.txt new file mode 100644 index 00000000..6d31a1ce --- /dev/null +++ b/crates/compact-lint/tests/fixtures/module-name/expected.txt @@ -0,0 +1 @@ +Renamed.compact:2:4: module-name: @module names `Stale`, but the module is `Renamed` diff --git a/crates/compact-lint/tests/fixtures/parse/Broken.compact b/crates/compact-lint/tests/fixtures/parse/Broken.compact new file mode 100644 index 00000000..c21593b4 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/parse/Broken.compact @@ -0,0 +1,3 @@ +export module Broken { + export circuit +} diff --git a/crates/compact-lint/tests/fixtures/parse/compact-lint.toml b/crates/compact-lint/tests/fixtures/parse/compact-lint.toml new file mode 100644 index 00000000..56ee774e --- /dev/null +++ b/crates/compact-lint/tests/fixtures/parse/compact-lint.toml @@ -0,0 +1,2 @@ +version = 1 +include = ["**/*.compact"] diff --git a/crates/compact-lint/tests/fixtures/parse/expected.txt b/crates/compact-lint/tests/fixtures/parse/expected.txt new file mode 100644 index 00000000..b50d9d70 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/parse/expected.txt @@ -0,0 +1 @@ +Broken.compact:2:3: parse: parse error: unexpected ERROR From 68baa98be3a9c08c279ab5a3b278118e9d56d3ec Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Wed, 16 Sep 2026 06:40:49 +0200 Subject: [PATCH 30/56] fix(compact-lint): resolve explicit paths against cwd Discovery matches exclude globs against paths relative to the config's directory, but an explicit CLI path stayed relative to the process cwd. Running `check archive` from a subdirectory produced `archive/X.compact`, which never matched an exclude written as `contracts/archive/**`, so excluded files were silently linted. Anchor relative CLI paths at cwd first; the display step still strips cwd, so the report is unchanged. --- crates/compact-lint/src/check.rs | 38 ++++++++++++++++++- crates/compact-lint/tests/check.rs | 15 ++++++++ .../exclude-explicit-dir/compact-lint.toml | 9 +++++ .../contracts/archive/Old.compact | 7 ++++ .../contracts/live/Live.compact | 7 ++++ .../exclude-explicit-dir/expected.txt | 1 + 6 files changed, 76 insertions(+), 1 deletion(-) create mode 100644 crates/compact-lint/tests/fixtures/exclude-explicit-dir/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/exclude-explicit-dir/contracts/archive/Old.compact create mode 100644 crates/compact-lint/tests/fixtures/exclude-explicit-dir/contracts/live/Live.compact create mode 100644 crates/compact-lint/tests/fixtures/exclude-explicit-dir/expected.txt diff --git a/crates/compact-lint/src/check.rs b/crates/compact-lint/src/check.rs index 2f2d2a88..76ee393c 100644 --- a/crates/compact-lint/src/check.rs +++ b/crates/compact-lint/src/check.rs @@ -67,7 +67,8 @@ pub fn run(options: &Options, cwd: &Path) -> Result { let include = config.include_set(source)?; discover::from_globs(&base, &include, &exclude)? } else { - discover::from_paths(&options.paths, &base, &exclude)? + let paths = absolute_paths(&options.paths, cwd); + discover::from_paths(&paths, &base, &exclude)? }; let files: Vec = files.iter().map(|path| display_path(path, cwd)).collect(); @@ -111,7 +112,42 @@ fn resolve_config( } } +/// Discovery matches the exclude globs against paths relative to the config's +/// directory, so a CLI path has to be anchored at `cwd` first: a bare `archive` +/// given from a subdirectory would otherwise never match `contracts/archive/**`. +fn absolute_paths(paths: &[PathBuf], cwd: &Path) -> Vec { + paths + .iter() + .map(|path| { + if path.is_absolute() { + path.clone() + } else { + cwd.join(path) + } + }) + .collect() +} + /// Paths under the working directory print relative to it; anything else prints as is. fn display_path(path: &Path, cwd: &Path) -> PathBuf { path.strip_prefix(cwd).unwrap_or(path).to_owned() } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_relative_path_is_anchored_at_the_working_directory() { + let resolved = absolute_paths(&[PathBuf::from("archive")], Path::new("/repo/contracts")); + + assert_eq!(resolved, vec![PathBuf::from("/repo/contracts/archive")]); + } + + #[test] + fn an_absolute_path_is_left_alone() { + let resolved = absolute_paths(&[PathBuf::from("/elsewhere/X.compact")], Path::new("/repo")); + + assert_eq!(resolved, vec![PathBuf::from("/elsewhere/X.compact")]); + } +} diff --git a/crates/compact-lint/tests/check.rs b/crates/compact-lint/tests/check.rs index 452c09dc..c4fc99f9 100644 --- a/crates/compact-lint/tests/check.rs +++ b/crates/compact-lint/tests/check.rs @@ -115,6 +115,21 @@ fn an_explicit_path_replaces_the_include_globs() { ); } +#[test] +fn an_exclude_glob_applies_to_an_explicit_path_given_from_a_subdirectory() { + let output = binary() + .current_dir(case("exclude-explicit-dir").join("contracts")) + .args(["check", "--no-format", "live", "archive"]) + .output() + .expect("the binary ran"); + + assert_eq!( + String::from_utf8(output.stdout).expect("the report is UTF-8"), + expected("exclude-explicit-dir") + ); + assert_eq!(output.status.code(), Some(EXIT_FINDINGS)); +} + #[test] fn an_explicit_config_anchors_discovery_at_the_working_directory() { let config = case("clean").join("compact-lint.toml"); diff --git a/crates/compact-lint/tests/fixtures/exclude-explicit-dir/compact-lint.toml b/crates/compact-lint/tests/fixtures/exclude-explicit-dir/compact-lint.toml new file mode 100644 index 00000000..02f0d72f --- /dev/null +++ b/crates/compact-lint/tests/fixtures/exclude-explicit-dir/compact-lint.toml @@ -0,0 +1,9 @@ +version = 1 +include = ["contracts/**/*.compact"] +exclude = ["contracts/archive/**"] + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.ledger] +tags = ["@description"] diff --git a/crates/compact-lint/tests/fixtures/exclude-explicit-dir/contracts/archive/Old.compact b/crates/compact-lint/tests/fixtures/exclude-explicit-dir/contracts/archive/Old.compact new file mode 100644 index 00000000..57a9386d --- /dev/null +++ b/crates/compact-lint/tests/fixtures/exclude-explicit-dir/contracts/archive/Old.compact @@ -0,0 +1,7 @@ +/** + * @module Old + * @description A retired module the config excludes. + */ +export module Old { + export ledger _owner: Bytes<32>; +} diff --git a/crates/compact-lint/tests/fixtures/exclude-explicit-dir/contracts/live/Live.compact b/crates/compact-lint/tests/fixtures/exclude-explicit-dir/contracts/live/Live.compact new file mode 100644 index 00000000..10781e5c --- /dev/null +++ b/crates/compact-lint/tests/fixtures/exclude-explicit-dir/contracts/live/Live.compact @@ -0,0 +1,7 @@ +/** + * @module Live + * @description A maintained module. + */ +export module Live { + export ledger _owner: Bytes<32>; +} diff --git a/crates/compact-lint/tests/fixtures/exclude-explicit-dir/expected.txt b/crates/compact-lint/tests/fixtures/exclude-explicit-dir/expected.txt new file mode 100644 index 00000000..31799ef6 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/exclude-explicit-dir/expected.txt @@ -0,0 +1 @@ +live/Live.compact:6:3: missing-doc: ledger `_owner` has no doc comment From 5ec15844e94eec845297c615531c8aa38b2a11e9 Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Wed, 16 Sep 2026 06:41:17 +0200 Subject: [PATCH 31/56] refactor(compact-lint): mark Tag::new must_use A constructor with no side effects; matches the rest of Tag. --- crates/compact-lint/src/doc.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/compact-lint/src/doc.rs b/crates/compact-lint/src/doc.rs index 685007f1..4da32002 100644 --- a/crates/compact-lint/src/doc.rs +++ b/crates/compact-lint/src/doc.rs @@ -10,6 +10,7 @@ use serde::Deserialize; pub struct Tag(String); impl Tag { + #[must_use] pub fn new(name: impl Into) -> Self { Self(name.into()) } From 3423bd66efcc24b134ce939680ff434e6a526b9f Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Wed, 16 Sep 2026 06:42:15 +0200 Subject: [PATCH 32/56] fix(compact-lint): check constraints under docs = none The constraints rule ran after the per-kind docs gate, so kinds.circuit.docs = "none" silently disabled it. The rule is fixed rather than configurable, so it now runs before the gate; only the required-tag loop stays behind it. --- crates/compact-lint/src/rules.rs | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/crates/compact-lint/src/rules.rs b/crates/compact-lint/src/rules.rs index 9bc0bf7a..4e8cefc8 100644 --- a/crates/compact-lint/src/rules.rs +++ b/crates/compact-lint/src/rules.rs @@ -146,6 +146,9 @@ fn check_declaration( check_module_name(declaration, display, findings); } + // The constraints rule is fixed, so it stays outside the per-kind docs policy. + check_constraints(declaration, display, config, strict, findings); + if !requires_docs { return; } @@ -160,8 +163,6 @@ fn check_declaration( )); } } - - check_constraints(declaration, display, config, strict, findings); } /// `@module ` must name the module it documents. @@ -341,6 +342,19 @@ mod tests { ); } + #[test] + fn the_constraints_rule_survives_docs_none() { + let source = + "/** @description Bumps. */\nexport circuit bump(): [] { count.increment(1); }\n"; + let mut config = circuit_config(); + config.kinds.circuit.docs = DocsPolicy::None; + + assert_eq!( + findings(source, &config, false), + ["a.compact:2:1: missing-constraints: circuit `bump` doc comment has no @constraints"] + ); + } + #[test] fn a_placeholder_is_a_finding_only_under_strict() { let source = "/**\n * @description Bumps.\n * @constraints k=?, rows=?\n */\nexport circuit bump(): [] { }\n"; From a907f8604d8adbe539001fd3b5e68d14bd6f96c0 Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Tue, 17 Nov 2026 13:26:08 +0100 Subject: [PATCH 33/56] fix(compact-lint): keep the closing */ on a module-name fix set_module_name replaced the first word after @module, which swallowed a `*/` sharing that word or standing alone after the tag, so the comment ran on and turned the module into comment text. Split the terminator off before the rewrite. As a backstop, fix reparses the rewritten text and refuses to write when its declarations change. --- crates/compact-lint/README.md | 5 +- crates/compact-lint/src/edit.rs | 54 +++++++++++++++---- crates/compact-lint/src/fix.rs | 35 +++++++++++- crates/compact-lint/src/rules.rs | 24 +++++++++ crates/compact-lint/tests/fix.rs | 5 ++ .../after/Terminators.compact | 12 +++++ .../before/Terminators.compact | 12 +++++ .../compact-lint.toml | 6 +++ .../fix-module-name-terminator/expected.txt | 3 ++ 9 files changed, 144 insertions(+), 12 deletions(-) create mode 100644 crates/compact-lint/tests/fixtures/fix-module-name-terminator/after/Terminators.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-module-name-terminator/before/Terminators.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-module-name-terminator/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/fix-module-name-terminator/expected.txt diff --git a/crates/compact-lint/README.md b/crates/compact-lint/README.md index 89f9ad09..2f3e1789 100644 --- a/crates/compact-lint/README.md +++ b/crates/compact-lint/README.md @@ -64,7 +64,7 @@ What each rule's fix does: | `missing-tag` | Inserts each missing tag after the block of the last tag that precedes it in `kinds..tags`, else at the top of the body. A missing `@description` adopts untagged prose that opens the body instead of writing a placeholder. A `/** … */` one-liner expands to the multi-line form first. | | `missing-constraints` | Inserts ` k=?, rows=?` after the `@description` block, with a blank ` *` line before it and, where prose follows, one after. Without a `@description` it opens the body. On a circuit with no doc comment, it inserts a doc comment holding only that line. | | `forbidden-tag` | Renames the tag in place, and only where `tags.rename` maps it. | -| `module-name` | Replaces the first word of the `@module` value with the module's name, keeping what follows. | +| `module-name` | Replaces the first word of the `@module` value with the module's name, keeping what follows. A `*/` on the same line stays in place. | Not fixed: @@ -75,6 +75,9 @@ Not fixed: - `format` β€” that is `compact format`'s job. - A forbidden tag with no `tags.rename` entry stays a `check` finding. +Before writing, `fix` parses the rewritten file and refuses it, exiting `2`, when its +declarations differ from the original's: a doc edit never should change them. + Existing lines are never reordered or reflowed. Edits are computed against the original text and applied from the highest offset down; several edits on one comment merge into a single replacement of it. Files are rewritten through a sibling `.tmp` file and renamed diff --git a/crates/compact-lint/src/edit.rs b/crates/compact-lint/src/edit.rs index 281d859a..861c9fed 100644 --- a/crates/compact-lint/src/edit.rs +++ b/crates/compact-lint/src/edit.rs @@ -289,8 +289,10 @@ fn rename_tag(line: &str, from: &str, to: &str) -> Option { None } -/// Replaces the first word after `@module`, keeping whatever follows it. +/// Replaces the first word after `@module`, keeping whatever follows it. A `*/` closing +/// the comment on the same line is never part of the value. fn set_module_name(line: &str, name: &str) -> Option { + let (line, terminator) = split_terminator(line); let tag = "@module"; let start = line.find(tag)?; let after = start + tag.len(); @@ -302,15 +304,33 @@ fn set_module_name(line: &str, name: &str) -> Option { .find(char::is_whitespace) .map_or(value.len(), |index| index); - if value.is_empty() { - return Some(format!("{line} {name}")); + let renamed = if value.is_empty() { + format!("{line} {name}") + } else { + format!( + "{}{}{name}{}", + &line[..after], + &rest[..spaces], + &value[word..] + ) + }; + + if terminator.is_empty() || terminator.starts_with(char::is_whitespace) { + Some(format!("{renamed}{terminator}")) + } else { + Some(format!("{renamed} {terminator}")) + } +} + +/// Splits a trailing `*/`, with the whitespace before it, off a comment line. +fn split_terminator(line: &str) -> (&str, &str) { + match line.trim_end().strip_suffix("*/") { + Some(body) => { + let kept = body.trim_end(); + (kept, &line[kept.len()..]) + } + None => (line, ""), } - Some(format!( - "{}{}{name}{}", - &line[..after], - &rest[..spaces], - &value[word..] - )) } #[cfg(test)] @@ -543,6 +563,22 @@ mod tests { ); } + #[test] + fn a_module_rewrite_keeps_the_closing_delimiter() { + assert_eq!( + set_module_name("/** @module */", "Access"), + Some("/** @module Access */".to_owned()) + ); + assert_eq!( + set_module_name("/** @module Ownable*/", "Access"), + Some("/** @module Access */".to_owned()) + ); + assert_eq!( + set_module_name(" * @module Old */", "Access"), + Some(" * @module Access */".to_owned()) + ); + } + #[test] fn crlf_sources_keep_their_line_ending() { let source = "/**\r\n * @description Bumps.\r\n */\r\n"; diff --git a/crates/compact-lint/src/fix.rs b/crates/compact-lint/src/fix.rs index 33d9ed3c..94f124bb 100644 --- a/crates/compact-lint/src/fix.rs +++ b/crates/compact-lint/src/fix.rs @@ -43,6 +43,8 @@ pub enum FixError { #[source] source: std::io::Error, }, + #[error("refusing to write {path}: the edits would change its declarations")] + Unsafe { path: PathBuf }, } /// Everything the `fix` subcommand needs, already resolved from flags. @@ -102,8 +104,12 @@ pub fn run(options: &Options, cwd: &Path) -> Result { continue; } + let fixed = apply(&source, &edits, newline); + if changes_declarations(&mut linter, path, &source, &fixed)? { + return Err(FixError::Unsafe { path: path.clone() }); + } if !options.dry_run { - write_atomically(path, &apply(&source, &edits, newline))?; + write_atomically(path, &fixed)?; } files.push(FileEdits { path: path.clone(), @@ -114,6 +120,17 @@ pub fn run(options: &Options, cwd: &Path) -> Result { Ok(Outcome { files }) } +/// Whether `after` parses into other declarations than `before`. Doc edits never should, +/// so a difference means an edit broke a comment delimiter. +fn changes_declarations( + linter: &mut Linter, + path: &Path, + before: &str, + after: &str, +) -> Result { + Ok(linter.outline(path, before)? != linter.outline(path, after)?) +} + /// Whether a forbidden tag in the same doc comment is renamed to the tag this /// `missing-tag` issue reports. /// @@ -414,10 +431,12 @@ pub fn line(path: &Path, position: Position, message: &str) -> String { #[cfg(test)] mod tests { - use super::skeleton; + use super::{changes_declarations, skeleton}; use crate::config::Config; use crate::doc::Tag; use crate::model::DeclKind; + use crate::rules::Linter; + use std::path::Path; fn config() -> Config { let mut config = Config::default(); @@ -458,6 +477,18 @@ mod tests { ); } + #[test] + fn an_unterminated_comment_counts_as_a_declaration_change() { + let mut linter = Linter::new().expect("the bundled grammar loads"); + let path = Path::new("a.compact"); + let before = "/** @module Old */\nmodule Access {\n}\n"; + + let closed = "/** @module Access */\nmodule Access {\n}\n"; + let unclosed = "/** @module Access\nmodule Access {\n}\n"; + assert!(!changes_declarations(&mut linter, path, before, closed).expect("parses")); + assert!(changes_declarations(&mut linter, path, before, unclosed).expect("parses")); + } + #[test] fn a_crlf_skeleton_uses_the_file_line_ending() { assert_eq!( diff --git a/crates/compact-lint/src/rules.rs b/crates/compact-lint/src/rules.rs index 59f1c6ef..276cf406 100644 --- a/crates/compact-lint/src/rules.rs +++ b/crates/compact-lint/src/rules.rs @@ -175,6 +175,9 @@ impl Issue { } } +/// Each declaration's kind and name, in source order. +pub type Outline = Vec<(DeclKind, Option)>; + /// A reusable parser plus the rules that run over its trees. pub struct Linter { parser: Parser, @@ -238,6 +241,27 @@ impl Linter { .map(|issue| issue.finding(display)) .collect()) } + + /// The declarations `source` parses into, or `None` when it holds a parse defect. + /// # Errors + /// Returns an error when tree-sitter produces no tree for `source`. + pub fn outline(&mut self, display: &Path, source: &str) -> Result, LintError> { + let tree = self + .parser + .parse(source, None) + .ok_or_else(|| LintError::NoTree(display.to_owned()))?; + let root = tree.root_node(); + + if first_defect(root).is_some() { + return Ok(None); + } + Ok(Some( + declarations(root, source) + .into_iter() + .map(|declaration| (declaration.kind, declaration.name)) + .collect(), + )) + } } /// The first `ERROR` or `MISSING` node in document order. diff --git a/crates/compact-lint/tests/fix.rs b/crates/compact-lint/tests/fix.rs index 3f1877fd..9d53f20f 100644 --- a/crates/compact-lint/tests/fix.rs +++ b/crates/compact-lint/tests/fix.rs @@ -173,6 +173,11 @@ fn a_stale_module_tag_takes_the_module_name() { assert_case("module-name"); } +#[test] +fn a_module_name_rewrite_keeps_a_closing_delimiter_on_its_line() { + assert_case("module-name-terminator"); +} + #[test] fn a_crlf_source_keeps_its_line_endings() { assert_case("crlf"); diff --git a/crates/compact-lint/tests/fixtures/fix-module-name-terminator/after/Terminators.compact b/crates/compact-lint/tests/fixtures/fix-module-name-terminator/after/Terminators.compact new file mode 100644 index 00000000..2298c582 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-module-name-terminator/after/Terminators.compact @@ -0,0 +1,12 @@ +/** @module Empty */ +module Empty { +} + +/** @module Glued */ +module Glued { +} + +/** + * @module Spaced */ +module Spaced { +} diff --git a/crates/compact-lint/tests/fixtures/fix-module-name-terminator/before/Terminators.compact b/crates/compact-lint/tests/fixtures/fix-module-name-terminator/before/Terminators.compact new file mode 100644 index 00000000..dac64266 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-module-name-terminator/before/Terminators.compact @@ -0,0 +1,12 @@ +/** @module */ +module Empty { +} + +/** @module Old*/ +module Glued { +} + +/** + * @module Old */ +module Spaced { +} diff --git a/crates/compact-lint/tests/fixtures/fix-module-name-terminator/compact-lint.toml b/crates/compact-lint/tests/fixtures/fix-module-name-terminator/compact-lint.toml new file mode 100644 index 00000000..59bd4d1c --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-module-name-terminator/compact-lint.toml @@ -0,0 +1,6 @@ +version = 1 +include = ["**/*.compact"] + +[kinds.module] +docs = "all" +tags = ["@module"] diff --git a/crates/compact-lint/tests/fixtures/fix-module-name-terminator/expected.txt b/crates/compact-lint/tests/fixtures/fix-module-name-terminator/expected.txt new file mode 100644 index 00000000..7bd8d286 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-module-name-terminator/expected.txt @@ -0,0 +1,3 @@ +Terminators.compact:1:5: fix: set @module to `Empty` +Terminators.compact:5:5: fix: set @module to `Glued` +Terminators.compact:10:4: fix: set @module to `Spaced` From 8a940eda47cac7697d799168b9c872980da186f6 Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Tue, 17 Nov 2026 13:27:31 +0100 Subject: [PATCH 34/56] fix(compact-lint): move delimiter-line text before inserting Tag and prose searches covered only the lines between `/**` and `*/`, so a tag or prose sharing either delimiter line was missed: an insertion split a tag from its continuation and opening prose was never adopted. Before any insertion, move that text onto a body line of its own, as the one-liner expansion already did. --- crates/compact-lint/README.md | 2 +- crates/compact-lint/src/edit.rs | 108 ++++++++++++++++-- crates/compact-lint/tests/fix.rs | 5 + .../after/Delimiters.compact | 21 ++++ .../before/Delimiters.compact | 14 +++ .../fix-delimiter-text/compact-lint.toml | 8 ++ .../fixtures/fix-delimiter-text/expected.txt | 3 + 7 files changed, 151 insertions(+), 10 deletions(-) create mode 100644 crates/compact-lint/tests/fixtures/fix-delimiter-text/after/Delimiters.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-delimiter-text/before/Delimiters.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-delimiter-text/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/fix-delimiter-text/expected.txt diff --git a/crates/compact-lint/README.md b/crates/compact-lint/README.md index 2f3e1789..2b2ebd26 100644 --- a/crates/compact-lint/README.md +++ b/crates/compact-lint/README.md @@ -61,7 +61,7 @@ What each rule's fix does: | Rule | Fix | | --- | --- | | `missing-doc` | Inserts a doc skeleton above the declaration, indented to it. Body lines come from `kinds..tags` in config order; `@module` takes the declaration's name, every other tag takes `fix.placeholder`. Exported non-pure circuits also get the constraints line. A kind with neither gets a single placeholder line. | -| `missing-tag` | Inserts each missing tag after the block of the last tag that precedes it in `kinds..tags`, else at the top of the body. A missing `@description` adopts untagged prose that opens the body instead of writing a placeholder. A `/** … */` one-liner expands to the multi-line form first. | +| `missing-tag` | Inserts each missing tag after the block of the last tag that precedes it in `kinds..tags`, else at the top of the body. A missing `@description` adopts untagged prose that opens the body instead of writing a placeholder. Text on the `/**` or `*/` line moves onto its own body line first, so a `/** … */` one-liner expands to the multi-line form. | | `missing-constraints` | Inserts ` k=?, rows=?` after the `@description` block, with a blank ` *` line before it and, where prose follows, one after. Without a `@description` it opens the body. On a circuit with no doc comment, it inserts a doc comment holding only that line. | | `forbidden-tag` | Renames the tag in place, and only where `tags.rename` maps it. | | `module-name` | Replaces the first word of the `@module` value with the module's name, keeping what follows. A `*/` on the same line stays in place. | diff --git a/crates/compact-lint/src/edit.rs b/crates/compact-lint/src/edit.rs index 861c9fed..55ab7ca6 100644 --- a/crates/compact-lint/src/edit.rs +++ b/crates/compact-lint/src/edit.rs @@ -114,15 +114,15 @@ fn render_doc(doc: &str, indent: usize, newline: &str, ops: &[&DocOp]) -> String let margin = " ".repeat(indent); let gutter = format!("{margin} * "); - // An insertion needs a body, so a `/** … */` one-liner expands first. - let expands = lines.len() == 1 - && ops - .iter() - .any(|op| matches!(op, DocOp::InsertTag { .. } | DocOp::InsertConstraints(_))); - let shift = usize::from(expands); - if expands { - lines = expand(&lines[0], &margin, &gutter); - } + // Insertions search the body only, so text on the `/**` or `*/` line moves first. + let inserts = ops + .iter() + .any(|op| matches!(op, DocOp::InsertTag { .. } | DocOp::InsertConstraints(_))); + let shift = if inserts { + isolate_delimiters(&mut lines, &margin, &gutter) + } else { + 0 + }; // In-place ops address the original lines, so they run before any insertion moves // them; tags precede the constraints line, which anchors itself on `@description`. @@ -166,6 +166,36 @@ fn render_doc(doc: &str, indent: usize, newline: &str, ops: &[&DocOp]) -> String lines.join(newline) } +/// Moves text sharing a line with `/**` or `*/` onto a body line of its own. Returns how +/// many lines the original lines moved down. +fn isolate_delimiters(lines: &mut Vec, margin: &str, gutter: &str) -> usize { + if lines.len() == 1 { + *lines = expand(&lines[0], margin, gutter); + return 1; + } + + let closer = lines.len() - 1; + if let Some(body) = lines[closer].trim_end().strip_suffix("*/") { + let text = content(body).to_owned(); + if !text.is_empty() { + lines[closer] = format!("{gutter}{text}"); + lines.push(format!("{margin} */")); + } + } + + let text = lines[0] + .strip_prefix("/**") + .unwrap_or_default() + .trim() + .to_owned(); + if text.is_empty() { + return 0; + } + lines[0].truncate("/**".len()); + lines.insert(1, format!("{gutter}{text}")); + 1 +} + /// Splits `/** text */` into the three-line form, keeping the comment's indentation. fn expand(single: &str, margin: &str, gutter: &str) -> Vec { let inner = single @@ -423,6 +453,66 @@ mod tests { ); } + #[test] + fn a_tag_on_the_opening_line_keeps_its_continuation() { + let doc = "/** @description First line\n * continuation\n */"; + + assert_eq!( + rendered( + doc, + 0, + &[DocOp::InsertConstraints( + "@constraints k=?, rows=?".to_owned() + )] + ), + "/**\n * @description First line\n * continuation\n *\n * @constraints k=?, rows=?\n */" + ); + } + + #[test] + fn prose_on_the_opening_line_is_adopted() { + let doc = "/** Approved accounts\n * @param {T} a - A.\n */"; + + assert_eq!( + rendered(doc, 0, &[tag("@description TODO", &[])]), + "/**\n * @description Approved accounts\n * @param {T} a - A.\n */" + ); + } + + #[test] + fn text_before_the_closer_moves_onto_its_own_line() { + let doc = "/**\n * @description Runs\n * and returns. */"; + + assert_eq!( + rendered( + doc, + 0, + &[DocOp::InsertConstraints( + "@constraints k=?, rows=?".to_owned() + )] + ), + "/**\n * @description Runs\n * and returns.\n *\n * @constraints k=?, rows=?\n */" + ); + } + + #[test] + fn an_in_place_edit_follows_text_moved_off_the_opening_line() { + let doc = "/** @return x\n */"; + let ops = [ + DocOp::RenameTag { + line: 0, + from: "@return".to_owned(), + to: "@returns".to_owned(), + }, + tag("@description TODO", &[]), + ]; + + assert_eq!( + rendered(doc, 0, &ops), + "/**\n * @description TODO\n * @returns x\n */" + ); + } + #[test] fn constraints_follow_the_description_and_its_continuation_lines() { let doc = "/**\n * @description Sends a coin\n * to the recipient.\n * @param {Coin} coin - The coin.\n */"; diff --git a/crates/compact-lint/tests/fix.rs b/crates/compact-lint/tests/fix.rs index 9d53f20f..92e091f5 100644 --- a/crates/compact-lint/tests/fix.rs +++ b/crates/compact-lint/tests/fix.rs @@ -178,6 +178,11 @@ fn a_module_name_rewrite_keeps_a_closing_delimiter_on_its_line() { assert_case("module-name-terminator"); } +#[test] +fn text_on_a_delimiter_line_moves_before_an_insertion() { + assert_case("delimiter-text"); +} + #[test] fn a_crlf_source_keeps_its_line_endings() { assert_case("crlf"); diff --git a/crates/compact-lint/tests/fixtures/fix-delimiter-text/after/Delimiters.compact b/crates/compact-lint/tests/fixtures/fix-delimiter-text/after/Delimiters.compact new file mode 100644 index 00000000..1a09856a --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-delimiter-text/after/Delimiters.compact @@ -0,0 +1,21 @@ +/** + * @description First line + * continuation + * + * @constraints k=?, rows=? + */ +export circuit run(): [] { } + +/** + * @description Approved accounts + * across every shard. + */ +export ledger accounts: Uint<64>; + +/** + * @description Sends + * and returns. + * + * @constraints k=?, rows=? + */ +export circuit send(): [] { } diff --git a/crates/compact-lint/tests/fixtures/fix-delimiter-text/before/Delimiters.compact b/crates/compact-lint/tests/fixtures/fix-delimiter-text/before/Delimiters.compact new file mode 100644 index 00000000..772a774e --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-delimiter-text/before/Delimiters.compact @@ -0,0 +1,14 @@ +/** @description First line + * continuation + */ +export circuit run(): [] { } + +/** Approved accounts + * across every shard. + */ +export ledger accounts: Uint<64>; + +/** + * @description Sends + * and returns. */ +export circuit send(): [] { } diff --git a/crates/compact-lint/tests/fixtures/fix-delimiter-text/compact-lint.toml b/crates/compact-lint/tests/fixtures/fix-delimiter-text/compact-lint.toml new file mode 100644 index 00000000..a9da287b --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-delimiter-text/compact-lint.toml @@ -0,0 +1,8 @@ +version = 1 +include = ["**/*.compact"] + +[kinds.circuit] +tags = ["@description"] + +[kinds.ledger] +tags = ["@description"] diff --git a/crates/compact-lint/tests/fixtures/fix-delimiter-text/expected.txt b/crates/compact-lint/tests/fixtures/fix-delimiter-text/expected.txt new file mode 100644 index 00000000..c7248b9e --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-delimiter-text/expected.txt @@ -0,0 +1,3 @@ +Delimiters.compact:4:1: fix: inserted @constraints k=?, rows=? +Delimiters.compact:9:1: fix: inserted @description +Delimiters.compact:14:1: fix: inserted @constraints k=?, rows=? From 8b14e94db27a924ed30c8985213c0721e351543b Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Tue, 17 Nov 2026 13:28:41 +0100 Subject: [PATCH 35/56] fix(compact-lint): write the constraints tag only once A rename to the constraints tag still let missing-constraints insert a `k=?, rows=?` line above the renamed one, and that placeholder hid the measured value. Listing the constraints tag in kinds.circuit.tags duplicated it the same way, through the skeleton and through missing-tag. Skip those inserts when another edit on the same comment already writes the tag. --- crates/compact-lint/README.md | 2 +- crates/compact-lint/src/fix.rs | 47 +++++++++++++------ crates/compact-lint/tests/fix.rs | 5 ++ .../fix-constraints-once/after/Once.compact | 19 ++++++++ .../fix-constraints-once/before/Once.compact | 12 +++++ .../fix-constraints-once/compact-lint.toml | 9 ++++ .../fix-constraints-once/expected.txt | 3 ++ 7 files changed, 81 insertions(+), 16 deletions(-) create mode 100644 crates/compact-lint/tests/fixtures/fix-constraints-once/after/Once.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-constraints-once/before/Once.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-constraints-once/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/fix-constraints-once/expected.txt diff --git a/crates/compact-lint/README.md b/crates/compact-lint/README.md index 2b2ebd26..5992bedf 100644 --- a/crates/compact-lint/README.md +++ b/crates/compact-lint/README.md @@ -62,7 +62,7 @@ What each rule's fix does: | --- | --- | | `missing-doc` | Inserts a doc skeleton above the declaration, indented to it. Body lines come from `kinds..tags` in config order; `@module` takes the declaration's name, every other tag takes `fix.placeholder`. Exported non-pure circuits also get the constraints line. A kind with neither gets a single placeholder line. | | `missing-tag` | Inserts each missing tag after the block of the last tag that precedes it in `kinds..tags`, else at the top of the body. A missing `@description` adopts untagged prose that opens the body instead of writing a placeholder. Text on the `/**` or `*/` line moves onto its own body line first, so a `/** … */` one-liner expands to the multi-line form. | -| `missing-constraints` | Inserts ` k=?, rows=?` after the `@description` block, with a blank ` *` line before it and, where prose follows, one after. Without a `@description` it opens the body. On a circuit with no doc comment, it inserts a doc comment holding only that line. | +| `missing-constraints` | Inserts ` k=?, rows=?` after the `@description` block, with a blank ` *` line before it and, where prose follows, one after. Without a `@description` it opens the body. On a circuit with no doc comment, it inserts a doc comment holding only that line. Nothing is inserted when a `tags.rename` entry renames another tag in the comment to the constraints tag, and a circuit never gets the constraints tag twice, even when `kinds.circuit.tags` lists it. | | `forbidden-tag` | Renames the tag in place, and only where `tags.rename` maps it. | | `module-name` | Replaces the first word of the `@module` value with the module's name, keeping what follows. A `*/` on the same line stays in place. | diff --git a/crates/compact-lint/src/fix.rs b/crates/compact-lint/src/fix.rs index 94f124bb..ad487459 100644 --- a/crates/compact-lint/src/fix.rs +++ b/crates/compact-lint/src/fix.rs @@ -96,7 +96,7 @@ pub fn run(options: &Options, cwd: &Path) -> Result { let issues = linter.issues(path, &source, &target.config, false)?; let edits: Vec = issues .iter() - .filter(|issue| !supplied_by_a_rename(issue, &issues, &target.config)) + .filter(|issue| !supplied_elsewhere(issue, &issues, &target.config)) .filter_map(|issue| edit_for(issue, &target.config, newline)) .collect(); @@ -131,24 +131,28 @@ fn changes_declarations( Ok(linter.outline(path, before)? != linter.outline(path, after)?) } -/// Whether a forbidden tag in the same doc comment is renamed to the tag this -/// `missing-tag` issue reports. +/// Whether another edit on the same doc comment already writes the tag this +/// `missing-tag` or `missing-constraints` issue would insert: a rename to it, or, for +/// the constraints tag, the constraints line. /// /// Inserting it as well would leave the comment carrying the tag twice. -fn supplied_by_a_rename(issue: &Issue, issues: &[Issue], config: &Config) -> bool { - let Issue::MissingTag { tag, doc, .. } = issue else { +fn supplied_elsewhere(issue: &Issue, issues: &[Issue], config: &Config) -> bool { + let (Issue::MissingTag { tag, doc, .. } | Issue::MissingConstraints { tag, doc, .. }) = issue + else { return false; }; + let inserts_tag = matches!(issue, Issue::MissingTag { .. }); - issues.iter().any(|other| { - matches!( - other, - Issue::ForbiddenTag { - tag: forbidden, - doc: other_doc, - .. - } if other_doc == doc && config.rename_of(forbidden) == Some(tag) - ) + issues.iter().any(|other| match other { + Issue::ForbiddenTag { + tag: forbidden, + doc: other_doc, + .. + } => other_doc == doc && config.rename_of(forbidden) == Some(tag), + Issue::MissingConstraints { doc: other_doc, .. } => { + inserts_tag && other_doc == doc && *tag == config.constraints.tag + } + _ => false, }) } @@ -306,7 +310,8 @@ fn tag_line(tag: &Tag, name: Option<&str>, config: &Config) -> String { /// The doc comment `fix` writes above an undocumented declaration. /// /// Body lines come from `kinds..tags` in config order, then the constraints -/// annotation where the declaration takes one. +/// annotation where the declaration takes one. That annotation is the only line the +/// constraints tag gets, even when `kinds..tags` lists it. fn skeleton( kind: DeclKind, name: Option<&str>, @@ -320,6 +325,7 @@ fn skeleton( .get(kind) .tags .iter() + .filter(|tag| !constraints || **tag != config.constraints.tag) .map(|tag| tag_line(tag, name, config)) .collect(); @@ -461,6 +467,17 @@ mod tests { ); } + #[test] + fn a_required_constraints_tag_is_written_once() { + let mut config = config(); + config.kinds.circuit.tags = vec![Tag::new("@description"), Tag::new("@constraints")]; + + assert_eq!( + skeleton(DeclKind::Circuit, Some("run"), true, &config, 0, "\n"), + "/**\n * @description TODO\n *\n * @constraints k=?, rows=?\n */\n" + ); + } + #[test] fn a_pure_circuit_skeleton_stops_at_the_tag_lines() { assert_eq!( diff --git a/crates/compact-lint/tests/fix.rs b/crates/compact-lint/tests/fix.rs index 92e091f5..1798e292 100644 --- a/crates/compact-lint/tests/fix.rs +++ b/crates/compact-lint/tests/fix.rs @@ -146,6 +146,11 @@ fn the_constraints_annotation_follows_the_description_block() { assert_case("constraints"); } +#[test] +fn a_circuit_ends_with_one_constraints_annotation() { + assert_case("constraints-once"); +} + #[test] fn an_undocumented_circuit_under_docs_none_takes_a_constraints_only_comment() { assert_case("constraints-undocumented"); diff --git a/crates/compact-lint/tests/fixtures/fix-constraints-once/after/Once.compact b/crates/compact-lint/tests/fixtures/fix-constraints-once/after/Once.compact new file mode 100644 index 00000000..1fe3f085 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-constraints-once/after/Once.compact @@ -0,0 +1,19 @@ +/** + * @description Runs. + * @constraints k=7, rows=74 + */ +export circuit run(): [] { } + +/** + * @description TODO + * + * @constraints k=?, rows=? + */ +export circuit bump(): [] { } + +/** + * @description Sends. + * + * @constraints k=?, rows=? + */ +export circuit send(): [] { } diff --git a/crates/compact-lint/tests/fixtures/fix-constraints-once/before/Once.compact b/crates/compact-lint/tests/fixtures/fix-constraints-once/before/Once.compact new file mode 100644 index 00000000..1a76a8f8 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-constraints-once/before/Once.compact @@ -0,0 +1,12 @@ +/** + * @description Runs. + * @circuitInfo k=7, rows=74 + */ +export circuit run(): [] { } + +export circuit bump(): [] { } + +/** + * @description Sends. + */ +export circuit send(): [] { } diff --git a/crates/compact-lint/tests/fixtures/fix-constraints-once/compact-lint.toml b/crates/compact-lint/tests/fixtures/fix-constraints-once/compact-lint.toml new file mode 100644 index 00000000..7bd908cc --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-constraints-once/compact-lint.toml @@ -0,0 +1,9 @@ +version = 1 +include = ["**/*.compact"] + +[tags] +forbid = ["@circuitInfo"] +rename = { "@circuitInfo" = "@constraints" } + +[kinds.circuit] +tags = ["@description", "@constraints"] diff --git a/crates/compact-lint/tests/fixtures/fix-constraints-once/expected.txt b/crates/compact-lint/tests/fixtures/fix-constraints-once/expected.txt new file mode 100644 index 00000000..963c3510 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-constraints-once/expected.txt @@ -0,0 +1,3 @@ +Once.compact:3:4: fix: renamed @circuitInfo to @constraints +Once.compact:7:1: fix: inserted doc skeleton for circuit `bump` +Once.compact:12:1: fix: inserted @constraints k=?, rows=? From 87569ed6b7685f8acc087bce67acf714511ab75b Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Tue, 17 Nov 2026 14:58:09 +0100 Subject: [PATCH 36/56] fix(compact-lint): keep a note when k/rows match fill-constraints compared the whole first line, so a current value with a note such as `(zkir-v3)` read as stale and was rewritten without it. Compare only the k/rows part; a changed value still drops the note. --- crates/compact-lint/README.md | 3 +++ crates/compact-lint/src/fill.rs | 2 +- crates/compact-lint/src/rules.rs | 13 +++++++++++++ crates/compact-lint/tests/fill.rs | 5 +++++ .../after/src/access/Ownable.compact | 19 +++++++++++++++++++ .../src/access/test/mocks/MockOwnable.compact | 6 ++++++ .../before/src/access/Ownable.compact | 19 +++++++++++++++++++ .../src/access/test/mocks/.circuit-info.json | 17 +++++++++++++++++ .../src/access/test/mocks/MockOwnable.compact | 6 ++++++ .../fixtures/fill-note/compact-lint.toml | 8 ++++++++ .../tests/fixtures/fill-note/expected.txt | 1 + 11 files changed, 98 insertions(+), 1 deletion(-) create mode 100644 crates/compact-lint/tests/fixtures/fill-note/after/src/access/Ownable.compact create mode 100644 crates/compact-lint/tests/fixtures/fill-note/after/src/access/test/mocks/MockOwnable.compact create mode 100644 crates/compact-lint/tests/fixtures/fill-note/before/src/access/Ownable.compact create mode 100644 crates/compact-lint/tests/fixtures/fill-note/before/src/access/test/mocks/.circuit-info.json create mode 100644 crates/compact-lint/tests/fixtures/fill-note/before/src/access/test/mocks/MockOwnable.compact create mode 100644 crates/compact-lint/tests/fixtures/fill-note/compact-lint.toml create mode 100644 crates/compact-lint/tests/fixtures/fill-note/expected.txt diff --git a/crates/compact-lint/README.md b/crates/compact-lint/README.md index 1acc7dd6..d3510cd2 100644 --- a/crates/compact-lint/README.md +++ b/crates/compact-lint/README.md @@ -110,6 +110,9 @@ comment carries `constraints.tag`, whatever its value. A circuit with no annotat `fix`'s job and is left alone here. A file holding a parse defect is skipped, so `check` stays the place a syntax error is reported. +A note after the value, such as `(zkir-v3)`, stays while the measurement matches and is +dropped when the value changes. + Changes go to stdout, one per line: ```text diff --git a/crates/compact-lint/src/fill.rs b/crates/compact-lint/src/fill.rs index 5ee0dd6e..c22dc395 100644 --- a/crates/compact-lint/src/fill.rs +++ b/crates/compact-lint/src/fill.rs @@ -209,7 +209,7 @@ fn fill_file( }; let value = measurement.value(); - if value == site.value { + if value == site.measurement() { continue; } diff --git a/crates/compact-lint/src/rules.rs b/crates/compact-lint/src/rules.rs index b025004f..bddbfc5d 100644 --- a/crates/compact-lint/src/rules.rs +++ b/crates/compact-lint/src/rules.rs @@ -48,6 +48,19 @@ pub struct ConstraintSite { pub doc: DocRef, } +impl ConstraintSite { + /// The value without a trailing note such as `(zkir-v3)`. + #[must_use] + pub fn measurement(&self) -> &str { + let Some(rows) = self.value.find("rows=") else { + return &self.value; + }; + self.value[rows..] + .find(char::is_whitespace) + .map_or(&self.value, |end| &self.value[..rows + end]) + } +} + /// One rule violation, carrying what `check` prints and what `fix` needs to repair it. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Issue { diff --git a/crates/compact-lint/tests/fill.rs b/crates/compact-lint/tests/fill.rs index 8c8cbcba..1b3ad494 100644 --- a/crates/compact-lint/tests/fill.rs +++ b/crates/compact-lint/tests/fill.rs @@ -189,6 +189,11 @@ fn a_seeded_cache_fills_without_a_compiler() { assert_case("no-compile", &["--no-compile"], 0, ""); } +#[test] +fn a_note_stays_while_the_measurement_matches() { + assert_case("note", &["--no-compile"], 0, ""); +} + #[test] fn a_circuit_the_report_marks_unproved_stays_unmeasured() { let directory = work("basic"); diff --git a/crates/compact-lint/tests/fixtures/fill-note/after/src/access/Ownable.compact b/crates/compact-lint/tests/fixtures/fill-note/after/src/access/Ownable.compact new file mode 100644 index 00000000..30c6e420 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-note/after/src/access/Ownable.compact @@ -0,0 +1,19 @@ +/** + * @module Ownable + * @description Test fixture. + */ +export module Ownable { + /** + * @description Returns the owner. + * + * @constraints k=7, rows=74 (zkir-v3) + */ + export circuit owner(): [] { } + + /** + * @description Transfers ownership. + * + * @constraints k=13, rows=4871 + */ + export circuit transferOwnership(): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/fill-note/after/src/access/test/mocks/MockOwnable.compact b/crates/compact-lint/tests/fixtures/fill-note/after/src/access/test/mocks/MockOwnable.compact new file mode 100644 index 00000000..bbb1510e --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-note/after/src/access/test/mocks/MockOwnable.compact @@ -0,0 +1,6 @@ +/** + * @module MockStub + * @description Compiled by the fake compiler, never read by it. + */ +export module MockStub { +} diff --git a/crates/compact-lint/tests/fixtures/fill-note/before/src/access/Ownable.compact b/crates/compact-lint/tests/fixtures/fill-note/before/src/access/Ownable.compact new file mode 100644 index 00000000..62247b51 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-note/before/src/access/Ownable.compact @@ -0,0 +1,19 @@ +/** + * @module Ownable + * @description Test fixture. + */ +export module Ownable { + /** + * @description Returns the owner. + * + * @constraints k=7, rows=74 (zkir-v3) + */ + export circuit owner(): [] { } + + /** + * @description Transfers ownership. + * + * @constraints k=9, rows=42 (zkir-v3) + */ + export circuit transferOwnership(): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/fill-note/before/src/access/test/mocks/.circuit-info.json b/crates/compact-lint/tests/fixtures/fill-note/before/src/access/test/mocks/.circuit-info.json new file mode 100644 index 00000000..ac7097a7 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-note/before/src/access/test/mocks/.circuit-info.json @@ -0,0 +1,17 @@ +{ + "generatedAt": "2026-01-01T00:00:00.000Z", + "files": { + "MockOwnable.compact": [ + { + "name": "owner", + "k": 7, + "rows": 74 + }, + { + "name": "transferOwnership", + "k": 13, + "rows": 4871 + } + ] + } +} diff --git a/crates/compact-lint/tests/fixtures/fill-note/before/src/access/test/mocks/MockOwnable.compact b/crates/compact-lint/tests/fixtures/fill-note/before/src/access/test/mocks/MockOwnable.compact new file mode 100644 index 00000000..bbb1510e --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-note/before/src/access/test/mocks/MockOwnable.compact @@ -0,0 +1,6 @@ +/** + * @module MockStub + * @description Compiled by the fake compiler, never read by it. + */ +export module MockStub { +} diff --git a/crates/compact-lint/tests/fixtures/fill-note/compact-lint.toml b/crates/compact-lint/tests/fixtures/fill-note/compact-lint.toml new file mode 100644 index 00000000..e5a81d85 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-note/compact-lint.toml @@ -0,0 +1,8 @@ +version = 1 +exclude = ["**/test/mocks/**"] + +[kinds.module] +tags = ["@module", "@description"] + +[kinds.circuit] +tags = ["@description"] diff --git a/crates/compact-lint/tests/fixtures/fill-note/expected.txt b/crates/compact-lint/tests/fixtures/fill-note/expected.txt new file mode 100644 index 00000000..c371f22f --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-note/expected.txt @@ -0,0 +1 @@ +src/access/Ownable.compact:16:6: fill: @constraints k=9, rows=42 (zkir-v3) -> k=13, rows=4871 From 948fc681cea92bfac4c296cfa5a9c59c3ad68afb Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Tue, 17 Nov 2026 14:58:16 +0100 Subject: [PATCH 37/56] docs(compact-lint): drop the shared-cache claim Since #191 the builder writes circuit-info.json into the artifact directory, so the `.circuit-info.json` beside a source is compact-lint's own cache. --- .gitignore | 4 ++-- crates/compact-lint/README.md | 3 +-- crates/compact-lint/src/measure.rs | 8 ++++---- crates/compact-lint/tests/fill.rs | 2 +- 4 files changed, 8 insertions(+), 9 deletions(-) diff --git a/.gitignore b/.gitignore index a66d7c3e..6dd9a8b6 100644 --- a/.gitignore +++ b/.gitignore @@ -33,8 +33,8 @@ managed/ # never gets committed β€” including under examples/, where the walkthrough # expects you to compile the contract yourself before deploying. artifacts/ -# compact-compiler's per-source circuit-info cache, written next to the -# .compact sources it measures. +# compact-lint's measurement cache, written next to the .compact sources +# it measures. .circuit-info.json # Except the seeded cache the fill-constraints tests read. !crates/compact-lint/tests/fixtures/**/.circuit-info.json diff --git a/crates/compact-lint/README.md b/crates/compact-lint/README.md index d3510cd2..ece28551 100644 --- a/crates/compact-lint/README.md +++ b/crates/compact-lint/README.md @@ -138,8 +138,7 @@ Each distinct source is compiled once per run, whatever the number of files it m ### The cache After a compile, the measurements are merged into `.circuit-info.json` beside the source, -keyed by the source's file name. It is the file the TypeScript builder in -`packages/builder` writes, in the same shape, so the two tools share it: +keyed by the source's file name: ```json { diff --git a/crates/compact-lint/src/measure.rs b/crates/compact-lint/src/measure.rs index 954bc137..d943b67e 100644 --- a/crates/compact-lint/src/measure.rs +++ b/crates/compact-lint/src/measure.rs @@ -1,8 +1,8 @@ //! Measuring a circuit's proving key size and row count with `compact compile`. //! //! `k` and `rows` reach only the compiler's terminal progress output, so the compile runs -//! under a pty and the transcript is parsed. Results are cached in the -//! `.circuit-info.json` file the TypeScript builder writes, in the same shape. +//! under a pty and the transcript is parsed. Results are cached in a +//! `.circuit-info.json` file beside the compiled source. use std::collections::BTreeMap; use std::ffi::{OsStr, OsString}; @@ -102,7 +102,7 @@ impl Measurement { } } -/// The `.circuit-info.json` shape, shared with the TypeScript builder. +/// The `.circuit-info.json` cache: each source file name's measurements. #[derive(Clone, Debug, Default, Deserialize, Serialize)] struct CircuitInfo { #[serde(rename = "generatedAt")] @@ -451,7 +451,7 @@ pub fn tail(cleaned: &str, keep: usize) -> String { lines[start..].join("\n") } -/// An RFC 3339 UTC timestamp, the spelling the TypeScript builder writes. +/// An RFC 3339 UTC timestamp. fn timestamp(now: SystemTime) -> String { let seconds = now .duration_since(UNIX_EPOCH) diff --git a/crates/compact-lint/tests/fill.rs b/crates/compact-lint/tests/fill.rs index 1b3ad494..3380c0bf 100644 --- a/crates/compact-lint/tests/fill.rs +++ b/crates/compact-lint/tests/fill.rs @@ -243,7 +243,7 @@ fn a_missing_cache_entry_exits_two_and_names_the_flag() { } #[test] -fn a_compile_writes_the_cache_the_builder_shares() { +fn a_compile_writes_the_measurement_cache() { let directory = work("override"); fill(directory.path(), &[]); From d4789034ab5e610175ef8cd41eb67266436a43db Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Tue, 17 Nov 2026 15:03:37 +0100 Subject: [PATCH 38/56] fix(compact-lint): keep edits saved during a fill fill-constraints read every source before compiling and wrote the old text back afterwards, so a change saved during a compile was lost. Each file is now read again before the first write, and a changed one stops the run with nothing written. --- crates/compact-lint/README.md | 4 +- crates/compact-lint/src/fill.rs | 49 ++++++++++++++----- crates/compact-lint/tests/fill.rs | 26 ++++++++++ .../fixtures/fill-fake-compact/bin/compact | 5 ++ 4 files changed, 71 insertions(+), 13 deletions(-) diff --git a/crates/compact-lint/README.md b/crates/compact-lint/README.md index ece28551..db6dc28f 100644 --- a/crates/compact-lint/README.md +++ b/crates/compact-lint/README.md @@ -179,7 +179,9 @@ Exit codes: never printed. Files are rewritten exactly as `fix` rewrites them: through a sibling `.tmp` file, keeping -the line ending, and only the annotation's own line changes. +the line ending, and only the annotation's own line changes. Before the first write every +file is read again, and a file saved during the run makes it exit `2` with nothing +written. ## Rules diff --git a/crates/compact-lint/src/fill.rs b/crates/compact-lint/src/fill.rs index c22dc395..b659e326 100644 --- a/crates/compact-lint/src/fill.rs +++ b/crates/compact-lint/src/fill.rs @@ -41,6 +41,8 @@ pub enum FillError { #[source] source: std::io::Error, }, + #[error("refusing to write {path}: it changed during the run")] + Changed { path: PathBuf }, } /// Everything the subcommand needs, already resolved from flags and env. @@ -124,12 +126,39 @@ pub fn run(options: &Options, cwd: &Path) -> Result { files: 0, unmeasured: 0, }; - for file in &work { - fill_file(file, &measured, &tag, options, &mut outcome)?; + let writes: Vec<(&Work, String)> = work + .iter() + .filter_map(|file| { + fill_file(file, &measured, &tag, &mut outcome).map(|fixed| (file, fixed)) + }) + .collect(); + + if !options.dry_run { + // A compile can run for minutes; every file is checked before the first write. + for (file, _) in &writes { + ensure_unchanged(file)?; + } + for (file, fixed) in &writes { + write_atomically(&file.path, fixed)?; + } } Ok(outcome) } +fn ensure_unchanged(file: &Work) -> Result<(), FillError> { + let current = std::fs::read_to_string(&file.path).map_err(|source| FillError::Read { + path: file.path.clone(), + source, + })?; + if current == file.text { + Ok(()) + } else { + Err(FillError::Changed { + path: file.path.clone(), + }) + } +} + /// Compiles each distinct source once, or reads its cache under `--no-compile`. fn measure_sources( work: &[Work], @@ -180,20 +209,20 @@ fn measure_sources( Ok(measured) } -/// Rewrites one file's annotations and records what changed and what could not be measured. +/// Records what changed and what could not be measured, and returns the rewritten text +/// when an annotation changed. fn fill_file( file: &Work, measured: &BTreeMap>, tag: &crate::doc::Tag, - options: &Options, outcome: &mut Outcome, -) -> Result<(), FillError> { +) -> Option { let source = match &file.source { Source::Found(source) => source, Source::Missing(tried) => { outcome.lines.push(unmeasurable_line(&file.path, tried)); outcome.unmeasured += file.sites.len(); - return Ok(()); + return None; } }; let constraints = measured.get(source); @@ -234,16 +263,12 @@ fn fill_file( } if edits.is_empty() { - return Ok(()); + return None; } outcome.filled += edits.len(); outcome.files += 1; - if !options.dry_run { - let newline = newline_of(&file.text); - write_atomically(&file.path, &apply(&file.text, &edits, newline))?; - } - Ok(()) + Some(apply(&file.text, &edits, newline_of(&file.text))) } fn unmeasured_line(path: &Path, site: &ConstraintSite, source: &Path) -> String { diff --git a/crates/compact-lint/tests/fill.rs b/crates/compact-lint/tests/fill.rs index 3380c0bf..c86a32a9 100644 --- a/crates/compact-lint/tests/fill.rs +++ b/crates/compact-lint/tests/fill.rs @@ -99,11 +99,16 @@ fn expected(name: &str) -> String { /// Runs `fill-constraints` inside `directory`, pointed at the fake compiler. fn fill(directory: &Path, extra: &[&str]) -> Output { + fill_with_env(directory, extra, &[]) +} + +fn fill_with_env(directory: &Path, extra: &[&str], env: &[(&str, &str)]) -> Output { binary() .current_dir(directory) .args(["fill-constraints", "--compact-bin"]) .arg(fake_compact()) .args(extra) + .envs(env.iter().copied()) .output() .expect("the binary ran") } @@ -231,6 +236,27 @@ fn a_failed_compile_exits_two_with_the_output_tail() { assert!(!stderr.contains('\u{1b}'), "the raw pty stream leaked"); } +#[test] +fn a_source_saved_during_the_compile_is_not_overwritten() { + let directory = work("basic"); + let file = directory.path().join("src/access/Ownable.compact"); + let output = fill_with_env( + directory.path(), + &[], + &[( + "FAKE_COMPACT_EDIT", + file.to_str().expect("the path is UTF-8"), + )], + ); + let stderr = String::from_utf8_lossy(&output.stderr); + let text = std::fs::read_to_string(&file).expect("the source is readable"); + + assert_eq!(output.status.code(), Some(EXIT_ERROR)); + assert!(stderr.contains("Ownable.compact"), "{stderr}"); + assert!(text.ends_with("// saved during the compile\n"), "{text}"); + assert!(text.contains("@constraints k=?, rows=?"), "{text}"); +} + #[test] fn a_missing_cache_entry_exits_two_and_names_the_flag() { let directory = work("basic"); diff --git a/crates/compact-lint/tests/fixtures/fill-fake-compact/bin/compact b/crates/compact-lint/tests/fixtures/fill-fake-compact/bin/compact index b975fe04..90785113 100755 --- a/crates/compact-lint/tests/fixtures/fill-fake-compact/bin/compact +++ b/crates/compact-lint/tests/fixtures/fill-fake-compact/bin/compact @@ -19,6 +19,11 @@ source=$1 output=$2 name=$(basename "$source") +# A save to the named file while the compile runs. +if [ -n "$FAKE_COMPACT_EDIT" ]; then + echo "// saved during the compile" >> "$FAKE_COMPACT_EDIT" +fi + # name k rows proof case "$name" in MockOwnable.compact) From 8a3f1d39dbce329ad9dd2110abd225e8e2f5c375 Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Tue, 17 Nov 2026 15:04:29 +0100 Subject: [PATCH 39/56] fix(compact-lint): measure under NO_COLOR Compiler 0.34.0 prints no progress lines when NO_COLOR is set, so every circuit read as unmeasured and the empty list replaced the cache entry. The compiler no longer inherits NO_COLOR, and a compile that proves a circuit without printing its measurement is an error that leaves the cache alone. --- crates/compact-lint/README.md | 3 +- crates/compact-lint/src/measure.rs | 19 ++++++++++++ crates/compact-lint/tests/fill.rs | 30 +++++++++++++++++++ .../fixtures/fill-fake-compact/bin/compact | 9 +++++- 4 files changed, 59 insertions(+), 2 deletions(-) diff --git a/crates/compact-lint/README.md b/crates/compact-lint/README.md index db6dc28f..229f0f48 100644 --- a/crates/compact-lint/README.md +++ b/crates/compact-lint/README.md @@ -176,7 +176,8 @@ Exit codes: - `1` β€” at least one circuit is unmeasured or unmeasurable. - `2` β€” usage, config, IO, compiler or missing-cache error. A failed compile prints the source and the last 20 lines of the compiler's cleaned output; the raw pty stream is - never printed. + never printed. A compile that proves a circuit but prints no measurement for it is an + error too, and leaves the cache as it was. Files are rewritten exactly as `fix` rewrites them: through a sibling `.tmp` file, keeping the line ending, and only the annotation's own line changes. Before the first write every diff --git a/crates/compact-lint/src/measure.rs b/crates/compact-lint/src/measure.rs index d943b67e..910d67d4 100644 --- a/crates/compact-lint/src/measure.rs +++ b/crates/compact-lint/src/measure.rs @@ -47,6 +47,8 @@ pub enum MeasureError { }, #[error("compiling {file} failed:\n{tail}")] Compile { file: PathBuf, tail: String }, + #[error("compiling {file} printed no measurement for {circuits}")] + Silent { file: PathBuf, circuits: String }, #[error("cannot read {path}")] Read { path: PathBuf, @@ -167,6 +169,21 @@ impl Compiler { let mut measured = parse(&cleaned); if let Some(proved) = proved_circuits(&output)? { + let silent: Vec<&str> = proved + .iter() + .filter(|name| { + !measured + .iter() + .any(|measurement| &measurement.name == *name) + }) + .map(String::as_str) + .collect(); + if !silent.is_empty() { + return Err(MeasureError::Silent { + file: source.to_owned(), + circuits: silent.join(", "), + }); + } measured.retain(|measurement| proved.contains(&measurement.name)); } Ok(measured) @@ -187,6 +204,8 @@ impl Compiler { command.arg(source); command.arg(output); command.env("TERM", "xterm-256color"); + // Under `NO_COLOR` the compiler prints no progress lines, so nothing is measured. + command.env_remove("NO_COLOR"); command.cwd(&self.cwd); let mut child = pair diff --git a/crates/compact-lint/tests/fill.rs b/crates/compact-lint/tests/fill.rs index c86a32a9..fae51f09 100644 --- a/crates/compact-lint/tests/fill.rs +++ b/crates/compact-lint/tests/fill.rs @@ -257,6 +257,36 @@ fn a_source_saved_during_the_compile_is_not_overwritten() { assert!(text.contains("@constraints k=?, rows=?"), "{text}"); } +#[test] +fn no_color_in_the_environment_still_measures() { + let directory = work("basic"); + let (code, stdout) = + code_and_stdout(&fill_with_env(directory.path(), &[], &[("NO_COLOR", "1")])); + + assert_eq!(stdout, expected("basic")); + assert_eq!(code, EXIT_UNMEASURED); +} + +#[test] +fn a_compile_with_no_progress_lines_exits_two_and_keeps_the_cache() { + let directory = work("no-compile"); + let cache = directory + .path() + .join("src/access/test/mocks/.circuit-info.json"); + let before = std::fs::read(&cache).expect("the seeded cache is readable"); + + let output = fill_with_env(directory.path(), &[], &[("FAKE_COMPACT_SILENT", "1")]); + let stderr = String::from_utf8_lossy(&output.stderr); + + assert_eq!(output.status.code(), Some(EXIT_ERROR)); + assert!(stderr.contains("MockOwnable.compact"), "{stderr}"); + assert!(stderr.contains("owner"), "{stderr}"); + assert_eq!( + std::fs::read(&cache).expect("the cache is still readable"), + before + ); +} + #[test] fn a_missing_cache_entry_exits_two_and_names_the_flag() { let directory = work("basic"); diff --git a/crates/compact-lint/tests/fixtures/fill-fake-compact/bin/compact b/crates/compact-lint/tests/fixtures/fill-fake-compact/bin/compact index 90785113..c889a1f3 100755 --- a/crates/compact-lint/tests/fixtures/fill-fake-compact/bin/compact +++ b/crates/compact-lint/tests/fixtures/fill-fake-compact/bin/compact @@ -55,7 +55,14 @@ esac count=$(echo "$table" | wc -l | tr -d ' ') echo "Compiling $count circuits:" -echo "$table" | while read -r circuit k rows proof; do +# Like compiler 0.34.0, print no progress lines when `NO_COLOR` is set at all. +if [ -n "${NO_COLOR+set}" ] || [ -n "$FAKE_COMPACT_SILENT" ]; then + table_lines="" +else + table_lines=$table +fi + +echo "$table_lines" | while read -r circuit k rows proof; do [ -n "$circuit" ] || continue # The real compiler redraws the line, so the same circuit appears without rows first. printf ' circuit "%s" (k=%s)\n' "$circuit" "$k" From fe318a214d5badb3065308125e5355056c7c2bb5 Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Tue, 17 Nov 2026 15:15:10 +0100 Subject: [PATCH 40/56] refactor(compact-lint): share one path normalize --- crates/compact-lint/src/source.rs | 34 ++----------------------------- crates/compact-lint/src/target.rs | 2 +- 2 files changed, 3 insertions(+), 33 deletions(-) diff --git a/crates/compact-lint/src/source.rs b/crates/compact-lint/src/source.rs index 3e486b0d..4f8216c1 100644 --- a/crates/compact-lint/src/source.rs +++ b/crates/compact-lint/src/source.rs @@ -3,9 +3,10 @@ //! A library module does not compile on its own, so its constraints are measured through //! the mock contract that exports the same circuit names. -use std::path::{Component, Path, PathBuf}; +use std::path::{Path, PathBuf}; use crate::config::{Config, ConfigError}; +use crate::target::normalize; /// Where a file's measurements come from. #[derive(Clone, Debug, PartialEq, Eq)] @@ -131,28 +132,6 @@ fn display(path: &Path) -> String { } } -/// Resolves `.` and `..` lexically, so two spellings of one path compare equal. -/// -/// A `..` with nothing to cancel is kept, so a relative path that climbs out of its own -/// directory still points where it did. -fn normalize(path: &Path) -> PathBuf { - let mut out = PathBuf::new(); - for component in path.components() { - match component { - Component::CurDir => {} - Component::ParentDir => match out.components().next_back() { - Some(Component::Normal(_)) => { - out.pop(); - } - Some(Component::RootDir | Component::Prefix(_)) => {} - _ => out.push(Component::ParentDir), - }, - other => out.push(other), - } - } - out -} - #[cfg(test)] mod tests { use super::{Resolver, Source}; @@ -261,15 +240,6 @@ mod tests { ); } - #[test] - fn normalize_keeps_a_parent_it_cannot_cancel() { - assert_eq!( - super::normalize(Path::new("../mocks/./Ownable.compact")), - PathBuf::from("../mocks/Ownable.compact") - ); - assert_eq!(super::normalize(Path::new("/..")), PathBuf::from("/")); - } - #[test] fn a_file_with_no_candidate_reports_the_paths_it_tried() { let tree = tree(); diff --git a/crates/compact-lint/src/target.rs b/crates/compact-lint/src/target.rs index ab6a4ca1..ed05f742 100644 --- a/crates/compact-lint/src/target.rs +++ b/crates/compact-lint/src/target.rs @@ -81,7 +81,7 @@ fn absolute_paths(paths: &[PathBuf], cwd: &Path) -> Vec { /// /// A `..` with nothing to cancel is kept, so a relative path that climbs out of its own /// directory still points where it did. -fn normalize(path: &Path) -> PathBuf { +pub(crate) fn normalize(path: &Path) -> PathBuf { let mut out = PathBuf::new(); for component in path.components() { match component { From f9d25561f69448be525971ad91d835d6f70356d6 Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Tue, 17 Nov 2026 15:15:29 +0100 Subject: [PATCH 41/56] fix(compact-lint): measure up to 500 circuits per compile The compiler prints only as many circuit lines as the pty has rows. At 60 rows a larger contract lost lines, which now fails the compile. --- crates/compact-lint/src/measure.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/compact-lint/src/measure.rs b/crates/compact-lint/src/measure.rs index 910d67d4..0aea19da 100644 --- a/crates/compact-lint/src/measure.rs +++ b/crates/compact-lint/src/measure.rs @@ -23,9 +23,10 @@ const CONTRACT_INFO_PATH: [&str; 2] = ["compiler", "contract-info.json"]; /// Compiler-output lines kept in a failure report. const TAIL_LINES: usize = 20; -/// Terminal geometry for the compile; a wide row keeps a progress line off the wrap. +/// Terminal geometry for the compile. The compiler prints only as many circuit lines as +/// the terminal has rows, and a wide row keeps a progress line off the wrap. const PTY_SIZE: PtySize = PtySize { - rows: 60, + rows: 500, cols: 200, pixel_width: 0, pixel_height: 0, From 070f457f70c6f2eef7b8ab587e1b9d48bb58df37 Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Tue, 17 Nov 2026 15:45:31 +0100 Subject: [PATCH 42/56] fix(compact-linter): cache the binary per user The binary was cached under `.cache/` inside the installed package, which is read-only under Yarn Plug'n'Play and in global or container installs, so the first run failed with EROFS or EACCES. It now goes to `$XDG_CACHE_HOME` or `~/.cache` on Linux and `~/Library/Caches` on macOS. --- .gitignore | 3 --- packages/linter/README.md | 8 ++++--- packages/linter/src/binary.ts | 33 +++++++++++++++++++++++----- packages/linter/src/compactLinter.ts | 5 +++-- packages/linter/test/binary.test.ts | 29 ++++++++++++++++++++++-- 5 files changed, 63 insertions(+), 15 deletions(-) diff --git a/.gitignore b/.gitignore index 713ea587..6dd9a8b6 100644 --- a/.gitignore +++ b/.gitignore @@ -66,9 +66,6 @@ vendor/ target/ .toolkit-cache/ -# compact-lint's release binary, cached inside the installed npm package. -packages/linter/.cache/ - coverage **/reports diff --git a/packages/linter/README.md b/packages/linter/README.md index 6bf577b0..212ee941 100644 --- a/packages/linter/README.md +++ b/packages/linter/README.md @@ -25,9 +25,11 @@ Commands, flags, exit codes and `compact-lint.toml` are documented in the per target: `x86_64-unknown-linux-gnu`, `aarch64-unknown-linux-gnu`, `x86_64-apple-darwin`, `aarch64-apple-darwin`. - The first run downloads the one matching the host, checks its SHA-256 against the - release's `checksums.txt`, and caches it at `.cache/compact-lint--` - inside the installed package. Later runs print nothing and start it directly. -- Uninstalling the package removes the cache with it. + release's `checksums.txt`, and caches it as `compact-lint--` in a + per-user directory: `$XDG_CACHE_HOME/compact-linter` or `~/.cache/compact-linter` on + Linux, `~/Library/Caches/compact-linter` on macOS. Later runs print nothing and start + it directly. The installed package is never written to, so read-only installs and + Yarn Plug'n'Play work. - No prebuilt binary for the host is a hard error: build the crate with `cargo install --path crates/compact-lint` and point `COMPACT_LINT_BINARY` at it. diff --git a/packages/linter/src/binary.ts b/packages/linter/src/binary.ts index 8c73bd48..5e73b10e 100644 --- a/packages/linter/src/binary.ts +++ b/packages/linter/src/binary.ts @@ -6,7 +6,7 @@ import { renameSync, writeFileSync, } from 'node:fs'; -import { join } from 'node:path'; +import { isAbsolute, join } from 'node:path'; /** npm `platform-arch` pair to the Rust target triple the release assets are named after. */ const TARGETS: Record = { @@ -24,8 +24,9 @@ const DOWNLOAD_TIMEOUT_MS = 120_000; /** Where the binary is fetched from and cached, and who is told about a download. */ export interface ResolveOptions { - /** Root of the installed package; the cache lives under `.cache/` inside it. */ packageDir: string; + /** Per-user directory the binary is cached in, never inside the installed package. */ + cacheDir: string; version: string; platform: string; arch: string; @@ -34,6 +35,26 @@ export interface ResolveOptions { notify: (message: string) => void; } +/** + * `compact-linter` under the user's cache: `~/Library/Caches` on macOS, `$XDG_CACHE_HOME` + * or `~/.cache` elsewhere. The installed package can be read-only (Yarn Plug'n'Play, a + * global install). + */ +export function userCacheDir( + platform: string, + env: Record, + home: string, +): string { + if (platform === 'darwin') { + return join(home, 'Library', 'Caches', 'compact-linter'); + } + const xdg = env.XDG_CACHE_HOME; + return join( + xdg && isAbsolute(xdg) ? xdg : join(home, '.cache'), + 'compact-linter', + ); +} + export function resolveTarget(platform: string, arch: string): string | null { return TARGETS[`${platform}-${arch}`] ?? null; } @@ -84,8 +105,10 @@ export async function resolveBinary(options: ResolveOptions): Promise { ); } - const cacheDir = join(options.packageDir, '.cache'); - const cached = join(cacheDir, `compact-lint-${options.version}-${target}`); + const cached = join( + options.cacheDir, + `compact-lint-${options.version}-${target}`, + ); if (existsSync(cached)) { return cached; } @@ -110,7 +133,7 @@ export async function resolveBinary(options: ResolveOptions): Promise { } // Staged under a unique name so concurrent runs never read a half-written file. - mkdirSync(cacheDir, { recursive: true }); + mkdirSync(options.cacheDir, { recursive: true }); const staged = `${cached}.${randomUUID()}.tmp`; writeFileSync(staged, binary); chmodSync(staged, 0o755); diff --git a/packages/linter/src/compactLinter.ts b/packages/linter/src/compactLinter.ts index 33003481..fc6f83f5 100644 --- a/packages/linter/src/compactLinter.ts +++ b/packages/linter/src/compactLinter.ts @@ -2,10 +2,10 @@ import { spawnSync } from 'node:child_process'; import { readFileSync } from 'node:fs'; -import { constants } from 'node:os'; +import { constants, homedir } from 'node:os'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; -import { resolveBinary } from './binary.ts'; +import { resolveBinary, userCacheDir } from './binary.ts'; // One level up from src/ and from dist/ alike, so both entry points find the manifest. const packageDir = dirname(dirname(fileURLToPath(import.meta.url))); @@ -26,6 +26,7 @@ async function runLint(): Promise { try { binary = await resolveBinary({ packageDir, + cacheDir: userCacheDir(process.platform, process.env, homedir()), version: packageVersion(), platform: process.platform, arch: process.arch, diff --git a/packages/linter/test/binary.test.ts b/packages/linter/test/binary.test.ts index 18de25cb..c1b8369f 100644 --- a/packages/linter/test/binary.test.ts +++ b/packages/linter/test/binary.test.ts @@ -19,6 +19,7 @@ import { resolveBinary, resolveTarget, sha256, + userCacheDir, } from '../src/binary.ts'; const packageDir = dirname(dirname(fileURLToPath(import.meta.url))); @@ -73,6 +74,7 @@ function options( ): Parameters[0] { return { packageDir: install, + cacheDir: join(install, 'cache'), version: '0.1.0', platform: 'linux', arch: 'x64', @@ -105,6 +107,29 @@ describe('resolveTarget', () => { }); }); +describe('userCacheDir', () => { + it('uses XDG_CACHE_HOME on linux when it is absolute', () => { + expect(userCacheDir('linux', { XDG_CACHE_HOME: '/xdg' }, '/home/dev')).toBe( + '/xdg/compact-linter', + ); + }); + + it('falls back to ~/.cache on linux', () => { + expect(userCacheDir('linux', {}, '/home/dev')).toBe( + '/home/dev/.cache/compact-linter', + ); + expect( + userCacheDir('linux', { XDG_CACHE_HOME: 'relative' }, '/home/dev'), + ).toBe('/home/dev/.cache/compact-linter'); + }); + + it('uses ~/Library/Caches on macos', () => { + expect( + userCacheDir('darwin', { XDG_CACHE_HOME: '/xdg' }, '/Users/dev'), + ).toBe('/Users/dev/Library/Caches/compact-linter'); + }); +}); + describe('parseChecksums', () => { it('reads every entry of a multi-asset file', () => { const digests = parseChecksums(checksumsFor(ASSET, FAKE_BINARY)); @@ -174,7 +199,7 @@ describe('resolveBinary', () => { options({ env: { COMPACT_LINT_DOWNLOAD_BASE: origin.base } }), ); expect(binary).toBe( - join(install, '.cache', 'compact-lint-0.1.0-x86_64-unknown-linux-gnu'), + join(install, 'cache', 'compact-lint-0.1.0-x86_64-unknown-linux-gnu'), ); expect(statSync(binary).mode & 0o777).toBe(0o755); expect(spawnSync(binary, ['check'], { encoding: 'utf8' }).stdout).toBe( @@ -225,7 +250,7 @@ describe('resolveBinary', () => { options({ env: { COMPACT_LINT_DOWNLOAD_BASE: origin.base } }), ), ).rejects.toThrow( - `checksum mismatch for ${ASSET}: expected ${expected}, got ${actual}; delete ${join(install, '.cache', 'compact-lint-0.1.0-x86_64-unknown-linux-gnu')} and retry`, + `checksum mismatch for ${ASSET}: expected ${expected}, got ${actual}; delete ${join(install, 'cache', 'compact-lint-0.1.0-x86_64-unknown-linux-gnu')} and retry`, ); } finally { await origin.close(); From d034e0f2f6def721502f5ee4a1abe777880fc116 Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Tue, 17 Nov 2026 15:48:09 +0100 Subject: [PATCH 43/56] fix(compact-linter): never replace published release assets A manual re-run from a later commit could rebuild the binaries and --clobber them, with checksums.txt, onto the old tag's release. New installs then verified the replaced binary against the replaced checksums. * The detect job fails when the version's tag names another commit, and every job checks out the commit detect checked. * An existing release keeps its assets; the re-run ships its checksums.txt instead of uploading. * The npm package carries checksums.txt, and the launcher verifies downloads against it, never the release's copy. --- .github/workflows/release-publish.yml | 37 ++++++++++++-- .gitignore | 3 ++ RELEASING.md | 6 +++ packages/linter/README.md | 4 +- packages/linter/package.json | 1 + packages/linter/src/binary.ts | 30 ++++++----- packages/linter/test/binary.test.ts | 71 ++++++++++++++++++++------- 7 files changed, 117 insertions(+), 35 deletions(-) diff --git a/.github/workflows/release-publish.yml b/.github/workflows/release-publish.yml index 1e9c4948..1c015746 100644 --- a/.github/workflows/release-publish.yml +++ b/.github/workflows/release-publish.yml @@ -46,6 +46,7 @@ jobs: name: ${{ steps.pkg.outputs.name }} version: ${{ steps.pkg.outputs.version }} dist_tag: ${{ steps.pkg.outputs.dist_tag }} + sha: ${{ steps.pkg.outputs.sha }} steps: # For pull_request runs: checkout the merge commit (deterministic view of @@ -132,6 +133,7 @@ jobs: echo "name=$PKG" echo "version=$VERSION" echo "dist_tag=$DIST_TAG" + echo "sha=$(git rev-parse HEAD)" } >> $GITHUB_OUTPUT { echo "### Publishing" @@ -141,6 +143,21 @@ jobs: echo "- Trigger: $EVENT" } >> $GITHUB_STEP_SUMMARY + # A re-run from a later commit must not publish or attach assets under a tag + # that names another commit. An annotated tag is compared by its peeled commit. + - name: Check an existing tag + env: + TAG: ${{ steps.pkg.outputs.name }}/v${{ steps.pkg.outputs.version }} + run: | + PEELED=$(git ls-remote origin "refs/tags/$TAG^{}" | cut -f1) + DIRECT=$(git ls-remote origin "refs/tags/$TAG" | cut -f1) + TAGGED=${PEELED:-$DIRECT} + HEAD_SHA=$(git rev-parse HEAD) + if [[ -n "$TAGGED" && "$TAGGED" != "$HEAD_SHA" ]]; then + echo "::error::tag $TAG points to $TAGGED, not $HEAD_SHA; dispatch the run from the tag" + exit 1 + fi + # compact-linter ships a native binary per target, built on its own runner. The # npm package downloads them, so they must reach the GitHub release first. binaries: @@ -174,7 +191,7 @@ jobs: - name: Check out target ref uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.merge_commit_sha || github.ref }} + ref: ${{ needs.detect.outputs.sha }} - name: Install the pinned toolchain run: | @@ -230,7 +247,7 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.merge_commit_sha || github.ref }} + ref: ${{ needs.detect.outputs.sha }} token: ${{ steps.gh-app-token.outputs.token }} - name: Setup Node.js @@ -295,7 +312,15 @@ jobs: NOTES="$TAG" fi if gh release view "$TAG" >/dev/null 2>&1; then - gh release upload "$TAG" dist/* --clobber + # A re-run keeps the published assets and ships their checksums. + ASSETS=$(gh release view "$TAG" --json assets --jq '.assets[].name') + for NAME in checksums.txt $(cd dist && ls compact-lint-*); do + if ! grep -qx "$NAME" <<< "$ASSETS"; then + echo "::error::release $TAG has no $NAME; delete the release and re-run" + exit 1 + fi + done + gh release download "$TAG" --pattern checksums.txt --dir dist --clobber else ARGS=() if [[ "$DIST_TAG" == "beta" ]]; then @@ -307,6 +332,12 @@ jobs: "${ARGS[@]}" fi + # The launcher verifies a download against the digests it was published with, + # so a release asset replaced later fails the check. + - name: Add the checksums to the package + if: needs.detect.outputs.name == 'compact-linter' + run: cp dist/checksums.txt packages/linter/checksums.txt + # Anything but a clean 200 or 404 fails the run, so a flaky registry can # never read as "new package" and quietly downgrade an existing package # from OIDC to token auth. diff --git a/.gitignore b/.gitignore index 6dd9a8b6..f2a25f0c 100644 --- a/.gitignore +++ b/.gitignore @@ -66,6 +66,9 @@ vendor/ target/ .toolkit-cache/ +# Written by the release workflow, published inside the compact-linter package. +packages/linter/checksums.txt + coverage **/reports diff --git a/RELEASING.md b/RELEASING.md index d1a33aee..49fa06bd 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -137,6 +137,12 @@ carries a native binary as well as an npm package. and a `checksums.txt`, and only then publishes to npm. The installed package downloads its binary from that release, so the assets must be there first. For every other package the GitHub release is still created by hand (step 7 above). +- The npm package carries the same `checksums.txt` and checks every download against + it, so a release asset replaced later fails on install. +- A re-run never replaces assets. It fails when the version's tag names another + commit. When the release already exists, it keeps the release's assets and ships + their `checksums.txt`. A release missing an asset has to be deleted before the + re-run. - Release notes come from the `## ` section of `packages/linter/CHANGELOG.md`, falling back to the tag name. A `beta` dist-tag marks the release a prerelease. - Its first publish takes the `NPM_TOKEN` path above. Right after it, add diff --git a/packages/linter/README.md b/packages/linter/README.md index 212ee941..33673ca3 100644 --- a/packages/linter/README.md +++ b/packages/linter/README.md @@ -25,7 +25,7 @@ Commands, flags, exit codes and `compact-lint.toml` are documented in the per target: `x86_64-unknown-linux-gnu`, `aarch64-unknown-linux-gnu`, `x86_64-apple-darwin`, `aarch64-apple-darwin`. - The first run downloads the one matching the host, checks its SHA-256 against the - release's `checksums.txt`, and caches it as `compact-lint--` in a + `checksums.txt` published inside this package, and caches it as `compact-lint--` in a per-user directory: `$XDG_CACHE_HOME/compact-linter` or `~/.cache/compact-linter` on Linux, `~/Library/Caches/compact-linter` on macOS. Later runs print nothing and start it directly. The installed package is never written to, so read-only installs and @@ -38,7 +38,7 @@ Commands, flags, exit codes and `compact-lint.toml` are documented in the | Variable | Effect | | --- | --- | | `COMPACT_LINT_BINARY` | Run this executable and skip the download. For local crate builds and air-gapped CI. | -| `COMPACT_LINT_DOWNLOAD_BASE` | Fetch the asset and `checksums.txt` from this base URL instead of the GitHub release. | +| `COMPACT_LINT_DOWNLOAD_BASE` | Fetch the asset from this base URL instead of the GitHub release. It is still checked against the package's `checksums.txt`. | | `COMPACT_LINT_COMPACT_BIN` | Read by the linter itself: path to the `compact` binary. | ## Requirements diff --git a/packages/linter/package.json b/packages/linter/package.json index 81cdf57b..e54f6057 100644 --- a/packages/linter/package.json +++ b/packages/linter/package.json @@ -19,6 +19,7 @@ "type": "module", "files": [ "dist", + "checksums.txt", "README.md", "CHANGELOG.md", "LICENSE" diff --git a/packages/linter/src/binary.ts b/packages/linter/src/binary.ts index 5e73b10e..cc22291e 100644 --- a/packages/linter/src/binary.ts +++ b/packages/linter/src/binary.ts @@ -3,6 +3,7 @@ import { chmodSync, existsSync, mkdirSync, + readFileSync, renameSync, writeFileSync, } from 'node:fs'; @@ -24,6 +25,7 @@ const DOWNLOAD_TIMEOUT_MS = 120_000; /** Where the binary is fetched from and cached, and who is told about a download. */ export interface ResolveOptions { + /** Root of the installed package, which carries the release's `checksums.txt`. */ packageDir: string; /** Per-user directory the binary is cached in, never inside the installed package. */ cacheDir: string; @@ -113,22 +115,22 @@ export async function resolveBinary(options: ResolveOptions): Promise { return cached; } + // Digests come from the package, never the release, so a replaced asset fails here. const asset = assetName(target); + const expected = expectedChecksum( + packagedChecksums(options.packageDir), + asset, + ); const base = options.env.COMPACT_LINT_DOWNLOAD_BASE ?? `${RELEASE_BASE}/compact-linter/v${options.version}`; options.notify(`downloading ${asset} (v${options.version})`); - const [binary, checksums] = await Promise.all([ - fetchBytes(`${base}/${asset}`), - fetchText(`${base}/checksums.txt`), - ]); - - const expected = expectedChecksum(checksums, asset); + const binary = await fetchBytes(`${base}/${asset}`); const actual = sha256(binary); if (actual !== expected) { throw new Error( - `checksum mismatch for ${asset}: expected ${expected}, got ${actual}; delete ${cached} and retry`, + `checksum mismatch for ${asset}: expected ${expected}, got ${actual}`, ); } @@ -141,6 +143,16 @@ export async function resolveBinary(options: ResolveOptions): Promise { return cached; } +function packagedChecksums(packageDir: string): string { + const path = join(packageDir, 'checksums.txt'); + if (!existsSync(path)) { + throw new Error( + `${path} is missing, so a download cannot be verified; set COMPACT_LINT_BINARY`, + ); + } + return readFileSync(path, 'utf8'); +} + async function fetchOk(url: string): Promise { let response: Response; try { @@ -160,7 +172,3 @@ async function fetchOk(url: string): Promise { async function fetchBytes(url: string): Promise { return new Uint8Array(await (await fetchOk(url)).arrayBuffer()); } - -async function fetchText(url: string): Promise { - return (await fetchOk(url)).text(); -} diff --git a/packages/linter/test/binary.test.ts b/packages/linter/test/binary.test.ts index c1b8369f..35811386 100644 --- a/packages/linter/test/binary.test.ts +++ b/packages/linter/test/binary.test.ts @@ -69,6 +69,11 @@ function checksumsFor(asset: string, body: string): string { let install: string; let notices: string[]; +/** The `checksums.txt` the installed package was published with. */ +function packageChecksums(body: string): void { + writeFileSync(join(install, 'checksums.txt'), checksumsFor(ASSET, body)); +} + function options( overrides: Partial[0]> = {}, ): Parameters[0] { @@ -190,10 +195,8 @@ describe('resolveBinary', () => { }); it('downloads, verifies and caches the release asset', async () => { - const origin = await startOrigin({ - [ASSET]: FAKE_BINARY, - 'checksums.txt': checksumsFor(ASSET, FAKE_BINARY), - }); + packageChecksums(FAKE_BINARY); + const origin = await startOrigin({ [ASSET]: FAKE_BINARY }); try { const binary = await resolveBinary( options({ env: { COMPACT_LINT_DOWNLOAD_BASE: origin.base } }), @@ -205,10 +208,7 @@ describe('resolveBinary', () => { expect(spawnSync(binary, ['check'], { encoding: 'utf8' }).stdout).toBe( 'fake-lint check\n', ); - expect(origin.requests.toSorted()).toStrictEqual([ - 'checksums.txt', - ASSET, - ]); + expect(origin.requests).toStrictEqual([ASSET]); expect(notices).toStrictEqual([ 'downloading compact-lint-x86_64-unknown-linux-gnu (v0.1.0)', ]); @@ -218,10 +218,8 @@ describe('resolveBinary', () => { }); it('serves a second run from the cache', async () => { - const origin = await startOrigin({ - [ASSET]: FAKE_BINARY, - 'checksums.txt': checksumsFor(ASSET, FAKE_BINARY), - }); + packageChecksums(FAKE_BINARY); + const origin = await startOrigin({ [ASSET]: FAKE_BINARY }); try { const first = await resolveBinary( options({ env: { COMPACT_LINT_DOWNLOAD_BASE: origin.base } }), @@ -230,18 +228,16 @@ describe('resolveBinary', () => { options({ env: { COMPACT_LINT_DOWNLOAD_BASE: origin.base } }), ); expect(second).toBe(first); - expect(origin.requests).toHaveLength(2); + expect(origin.requests).toHaveLength(1); expect(notices).toHaveLength(1); } finally { await origin.close(); } }); - it('rejects an asset whose digest does not match checksums.txt', async () => { - const origin = await startOrigin({ - [ASSET]: FAKE_BINARY, - 'checksums.txt': checksumsFor(ASSET, 'a different binary'), - }); + it('rejects an asset whose digest does not match the package checksums', async () => { + packageChecksums('a different binary'); + const origin = await startOrigin({ [ASSET]: FAKE_BINARY }); try { const expected = sha256(Buffer.from('a different binary')); const actual = sha256(Buffer.from(FAKE_BINARY)); @@ -250,14 +246,50 @@ describe('resolveBinary', () => { options({ env: { COMPACT_LINT_DOWNLOAD_BASE: origin.base } }), ), ).rejects.toThrow( - `checksum mismatch for ${ASSET}: expected ${expected}, got ${actual}; delete ${join(install, 'cache', 'compact-lint-0.1.0-x86_64-unknown-linux-gnu')} and retry`, + `checksum mismatch for ${ASSET}: expected ${expected}, got ${actual}`, + ); + } finally { + await origin.close(); + } + }); + + it('ignores a checksums.txt replaced on the release', async () => { + packageChecksums(FAKE_BINARY); + const replaced = '#!/bin/sh\necho replaced\n'; + const origin = await startOrigin({ + [ASSET]: replaced, + 'checksums.txt': checksumsFor(ASSET, replaced), + }); + try { + await expect( + resolveBinary( + options({ env: { COMPACT_LINT_DOWNLOAD_BASE: origin.base } }), + ), + ).rejects.toThrow(`checksum mismatch for ${ASSET}`); + expect(origin.requests).toStrictEqual([ASSET]); + } finally { + await origin.close(); + } + }); + + it('refuses to download without the package checksums', async () => { + const origin = await startOrigin({ [ASSET]: FAKE_BINARY }); + try { + await expect( + resolveBinary( + options({ env: { COMPACT_LINT_DOWNLOAD_BASE: origin.base } }), + ), + ).rejects.toThrow( + `${join(install, 'checksums.txt')} is missing, so a download cannot be verified; set COMPACT_LINT_BINARY`, ); + expect(origin.requests).toStrictEqual([]); } finally { await origin.close(); } }); it('rejects an origin that answers with an http error', async () => { + packageChecksums(FAKE_BINARY); const origin = await startOrigin({}); try { await expect( @@ -273,6 +305,7 @@ describe('resolveBinary', () => { }); it('rejects an origin that cannot be reached', async () => { + packageChecksums(FAKE_BINARY); await expect( resolveBinary( options({ From 551d97f7b75e7b3963485cdccd67bf08f4586cf3 Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Tue, 17 Nov 2026 15:48:53 +0100 Subject: [PATCH 44/56] fix(compact-linter): reject musl hosts Node reports linux on musl systems such as Alpine, so the launcher downloaded a glibc binary that cannot start there. A musl host now fails with a message pointing at a source build and COMPACT_LINT_BINARY. --- packages/linter/README.md | 7 ++++--- packages/linter/src/binary.ts | 10 +++++++++- packages/linter/src/compactLinter.ts | 12 ++++++++++++ packages/linter/test/binary.test.ts | 17 +++++++++++++++++ 4 files changed, 42 insertions(+), 4 deletions(-) diff --git a/packages/linter/README.md b/packages/linter/README.md index 33673ca3..b681989a 100644 --- a/packages/linter/README.md +++ b/packages/linter/README.md @@ -30,8 +30,9 @@ Commands, flags, exit codes and `compact-lint.toml` are documented in the Linux, `~/Library/Caches/compact-linter` on macOS. Later runs print nothing and start it directly. The installed package is never written to, so read-only installs and Yarn Plug'n'Play work. -- No prebuilt binary for the host is a hard error: build the crate with - `cargo install --path crates/compact-lint` and point `COMPACT_LINT_BINARY` at it. +- No prebuilt binary for the host is a hard error, and that includes musl Linux such as + Alpine: build the crate with `cargo install --path crates/compact-lint` and point + `COMPACT_LINT_BINARY` at it. ## Environment @@ -44,4 +45,4 @@ Commands, flags, exit codes and `compact-lint.toml` are documented in the ## Requirements - Node.js >= 24 -- Linux or macOS, x86_64 or aarch64 +- Linux with glibc, or macOS; x86_64 or aarch64 diff --git a/packages/linter/src/binary.ts b/packages/linter/src/binary.ts index cc22291e..1b0e893a 100644 --- a/packages/linter/src/binary.ts +++ b/packages/linter/src/binary.ts @@ -32,6 +32,8 @@ export interface ResolveOptions { version: string; platform: string; arch: string; + /** Whether the host's C library is musl; every Linux asset links glibc. */ + musl: boolean; env: Record; /** Called once, before the first download of a run. */ notify: (message: string) => void; @@ -90,7 +92,7 @@ export function expectedChecksum(text: string, asset: string): string { } /** - * Path to the `compact-lint` executable, downloading it into the package cache when missing. + * Path to the `compact-lint` executable, downloading it into the user cache when missing. * * Messages carry no `compact-lint:` prefix; the bin adds it. */ @@ -100,6 +102,12 @@ export async function resolveBinary(options: ResolveOptions): Promise { return override; } + if (options.platform === 'linux' && options.musl) { + throw new Error( + 'no prebuilt binary for musl Linux, the release binaries need glibc; build from source with cargo (crates/compact-lint) and set COMPACT_LINT_BINARY', + ); + } + const target = resolveTarget(options.platform, options.arch); if (target === null) { throw new Error( diff --git a/packages/linter/src/compactLinter.ts b/packages/linter/src/compactLinter.ts index fc6f83f5..8be5c33c 100644 --- a/packages/linter/src/compactLinter.ts +++ b/packages/linter/src/compactLinter.ts @@ -15,6 +15,17 @@ function packageVersion(): string { return (JSON.parse(manifest) as { version: string }).version; } +/** Node reports a glibc version only when it runs on glibc. */ +function isMusl(): boolean { + if (process.platform !== 'linux') { + return false; + } + const report = process.report.getReport() as { + header?: { glibcVersionRuntime?: string }; + }; + return report.header?.glibcVersionRuntime === undefined; +} + function fail(message: string): never { process.stderr.write(`compact-linter: ${message} `); @@ -30,6 +41,7 @@ async function runLint(): Promise { version: packageVersion(), platform: process.platform, arch: process.arch, + musl: isMusl(), env: process.env, notify: (message) => process.stderr.write(`compact-linter: ${message} diff --git a/packages/linter/test/binary.test.ts b/packages/linter/test/binary.test.ts index 35811386..38efb9b5 100644 --- a/packages/linter/test/binary.test.ts +++ b/packages/linter/test/binary.test.ts @@ -83,6 +83,7 @@ function options( version: '0.1.0', platform: 'linux', arch: 'x64', + musl: false, env: {}, notify: (message) => notices.push(message), ...overrides, @@ -175,6 +176,22 @@ describe('resolveBinary', () => { ); }); + it('reports a musl linux host', async () => { + await expect(resolveBinary(options({ musl: true }))).rejects.toThrow( + 'no prebuilt binary for musl Linux, the release binaries need glibc; build from source with cargo (crates/compact-lint) and set COMPACT_LINT_BINARY', + ); + }); + + it('runs COMPACT_LINT_BINARY on a musl host', async () => { + const binary = await resolveBinary( + options({ + musl: true, + env: { COMPACT_LINT_BINARY: '/opt/compact-lint' }, + }), + ); + expect(binary).toBe('/opt/compact-lint'); + }); + it('returns COMPACT_LINT_BINARY without contacting the origin', async () => { const origin = await startOrigin({}); try { From 6b0bfd5a56fefd22725ac2bf981fe951563c75c4 Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Tue, 17 Nov 2026 15:49:07 +0100 Subject: [PATCH 45/56] ci(compact-linter): keep the binary build token-free --- .github/workflows/release-publish.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/release-publish.yml b/.github/workflows/release-publish.yml index 1c015746..71f05648 100644 --- a/.github/workflows/release-publish.yml +++ b/.github/workflows/release-publish.yml @@ -188,10 +188,12 @@ jobs: with: egress-policy: audit + # Cargo runs build scripts, so no token stays in .git/config. - name: Check out target ref uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ needs.detect.outputs.sha }} + persist-credentials: false - name: Install the pinned toolchain run: | From d3fdb7946e42631a0129a2be3f393ff7adc02700 Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Tue, 17 Nov 2026 15:49:07 +0100 Subject: [PATCH 46/56] docs: describe the release dependency graph --- RELEASING.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/RELEASING.md b/RELEASING.md index 49fa06bd..599b5680 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -82,7 +82,8 @@ breaking change. After that, only `prerelease` moves the counter. Running ## First-release order -There's a one-step dependency chain across the five published packages: +`compact-cli` depends on `compact-builder` and `compact-deployer`. The other +published packages have no internal dependencies: ```text compact-cli (bin wrapper) From 6c2aedbf7c69610821128d613a7c91e756067651 Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Tue, 17 Nov 2026 15:55:06 +0100 Subject: [PATCH 47/56] ci(compact-linter): check the commit after checkout CodeQL reads a checkout of another job's output as untrusted code. Check out the dispatched ref as before, and fail when it is not the commit the detect job checked. --- .github/workflows/release-publish.yml | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/.github/workflows/release-publish.yml b/.github/workflows/release-publish.yml index 71f05648..8d40cdb8 100644 --- a/.github/workflows/release-publish.yml +++ b/.github/workflows/release-publish.yml @@ -192,9 +192,20 @@ jobs: - name: Check out target ref uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - ref: ${{ needs.detect.outputs.sha }} + ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.merge_commit_sha || github.ref }} persist-credentials: false + # A dispatched branch can move after detect ran; build only the commit it checked. + - name: Check the commit + env: + DETECTED: ${{ needs.detect.outputs.sha }} + run: | + HEAD_SHA=$(git rev-parse HEAD) + if [[ "$HEAD_SHA" != "$DETECTED" ]]; then + echo "::error::checked out $HEAD_SHA, but detect checked $DETECTED; re-run all jobs" + exit 1 + fi + - name: Install the pinned toolchain run: | CHANNEL=$(grep -m1 '^channel' rust-toolchain.toml | cut -d'"' -f2) @@ -249,9 +260,20 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - ref: ${{ needs.detect.outputs.sha }} + ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.merge_commit_sha || github.ref }} token: ${{ steps.gh-app-token.outputs.token }} + # A dispatched branch can move after detect ran; build only the commit it checked. + - name: Check the commit + env: + DETECTED: ${{ needs.detect.outputs.sha }} + run: | + HEAD_SHA=$(git rev-parse HEAD) + if [[ "$HEAD_SHA" != "$DETECTED" ]]; then + echo "::error::checked out $HEAD_SHA, but detect checked $DETECTED; re-run all jobs" + exit 1 + fi + - name: Setup Node.js uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 with: From b6ab46cc6e4b2fdaf019135dadc454021fb7dbbf Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Tue, 17 Nov 2026 21:21:37 +0100 Subject: [PATCH 48/56] fix(compact-lint): insert a section below every paragraph An inserted tag or section landed after the first paragraph of the block before it, so the later paragraphs of a multi-paragraph @description moved under the new section. Insertion now anchors on the last non-blank line before the next tag. The constraints line keeps its first-paragraph anchor. --- crates/compact-lint/README.md | 2 +- crates/compact-lint/src/edit.rs | 44 +++++++++++++++---- crates/compact-lint/tests/fix.rs | 5 +++ .../after/Paragraphs.compact | 15 +++++++ .../before/Paragraphs.compact | 13 ++++++ .../fix-sections-paragraphs/compact.toml | 7 +++ .../expected-dry-run.txt | 15 +++++++ .../fix-sections-paragraphs/expected.txt | 9 ++++ 8 files changed, 101 insertions(+), 9 deletions(-) create mode 100644 crates/compact-lint/tests/fixtures/fix-sections-paragraphs/after/Paragraphs.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-sections-paragraphs/before/Paragraphs.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-sections-paragraphs/compact.toml create mode 100644 crates/compact-lint/tests/fixtures/fix-sections-paragraphs/expected-dry-run.txt create mode 100644 crates/compact-lint/tests/fixtures/fix-sections-paragraphs/expected.txt diff --git a/crates/compact-lint/README.md b/crates/compact-lint/README.md index 9583b2fd..07cdb184 100644 --- a/crates/compact-lint/README.md +++ b/crates/compact-lint/README.md @@ -177,7 +177,7 @@ What each rule's fix does: | Rule | Fix | | --- | --- | | `missing-doc` | Inserts a doc skeleton above the declaration, indented to it. Body lines come from `kinds..tags` in config order; `@module` takes the declaration's name, a headed entry becomes a `@tag Heading:` line with `fix.placeholder` under it, every other tag takes `fix.placeholder`. Exported non-pure circuits also get the constraints line. A kind with neither gets a single placeholder line. | -| `missing-tag` | Inserts each missing entry after the block of the last entry that precedes it in the template order, optional ones included, else at the top of the body. A headed entry goes in as a two-line section block; the predecessor's block is found by heading, not by bare tag. A missing bare `@description` adopts untagged prose that opens the body instead of writing a placeholder. Text on the `/**` or `*/` line moves onto its own body line first, so a `/** … */` one-liner expands to the multi-line form. | +| `missing-tag` | Inserts each missing entry after the block of the last entry that precedes it in the template order, optional ones included, below every paragraph of that block, else at the top of the body. A headed entry goes in as a two-line section block; the predecessor's block is found by heading, not by bare tag. A missing bare `@description` adopts untagged prose that opens the body instead of writing a placeholder. Text on the `/**` or `*/` line moves onto its own body line first, so a `/** … */` one-liner expands to the multi-line form. | | `tag-order` | Splits the comment body into one block per tag, sorts the blocks matching a listed entry into config order, and writes them back into the same slots. Prose before the first tag, unlisted blocks and the blank lines separating slots stay put, so a second run reports nothing. | | `missing-constraints` | Inserts ` k=?, rows=?` after the `@description` block, with a blank ` *` line before it and, where prose follows, one after. Without a `@description` it opens the body. On a circuit with no doc comment, it inserts a doc comment holding only that line. Nothing is inserted when a `tags.rename` entry renames another tag in the comment to the constraints tag, and a circuit never gets the constraints tag twice, even when `kinds.circuit.tags` lists it. | | `forbidden-tag` | Renames the tag in place, and only where `tags.rename` maps it. | diff --git a/crates/compact-lint/src/edit.rs b/crates/compact-lint/src/edit.rs index 8744922e..a6e28dc9 100644 --- a/crates/compact-lint/src/edit.rs +++ b/crates/compact-lint/src/edit.rs @@ -365,9 +365,9 @@ fn expand(single: &str, margin: &str, gutter: &str) -> Vec { ] } -/// A tag block lands after the block of the last entry in `after` that is present, else at -/// the top of the body. With `adopts_prose`, untagged prose opening the body takes the -/// tag instead of a new line going in. +/// A tag block lands after the block of the last entry in `after` that is present, every +/// paragraph of it included, else at the top of the body. With `adopts_prose`, untagged +/// prose opening the body takes the tag instead of a new line going in. fn insert_tag( lines: &mut Vec, gutter: &str, @@ -386,7 +386,7 @@ fn insert_tag( return; } - let at = tag_block_end(lines, closer, after).map_or(1.min(closer), |end| end + 1); + let at = paragraphs_end(lines, closer, after).map_or(1.min(closer), |end| end + 1); for (offset, line) in inserted.iter().enumerate() { lines.insert(at + offset, format!("{gutter}{line}")); } @@ -479,12 +479,30 @@ fn description_end(lines: &[String], closer: usize) -> Option { tag_block_end(lines, closer, &[TagSpec::bare(Tag::new(DESCRIPTION_TAG))]) } -/// The last line of the block opened by the last occurrence of any entry in `entries`. -fn tag_block_end(lines: &[String], closer: usize, entries: &[TagSpec]) -> Option { - let start = (1..closer).rev().find(|index| { +/// The line holding the last occurrence of any entry in `entries`. +fn last_occurrence(lines: &[String], closer: usize, entries: &[TagSpec]) -> Option { + (1..closer).rev().find(|index| { let text = content(&lines[*index]); entries.iter().any(|entry| entry.matches_line(text)) - })?; + }) +} + +/// The last non-blank line before the tag that follows the last occurrence of any entry in +/// `entries`, so a block's later paragraphs count as part of it. +fn paragraphs_end(lines: &[String], closer: usize, entries: &[TagSpec]) -> Option { + let start = last_occurrence(lines, closer, entries)?; + let next_tag = (start + 1..closer) + .find(|index| starts_tag(content(&lines[*index]))) + .unwrap_or(closer); + (start..next_tag) + .rev() + .find(|index| !is_blank(&lines[*index])) +} + +/// The last line of the first paragraph of the block opened by the last occurrence of any +/// entry in `entries`. +fn tag_block_end(lines: &[String], closer: usize, entries: &[TagSpec]) -> Option { + let start = last_occurrence(lines, closer, entries)?; let mut end = start; while end + 1 < closer { @@ -749,6 +767,16 @@ mod tests { ); } + #[test] + fn a_section_lands_after_every_paragraph_of_the_block_before_it() { + let doc = "/**\n * @description First paragraph.\n *\n * Second paragraph.\n *\n * @notice Security:\n * - Nonces.\n */"; + + assert_eq!( + rendered(doc, 0, &[section("@notice Privacy", &["@description"])]), + "/**\n * @description First paragraph.\n *\n * Second paragraph.\n * @notice Privacy:\n * TODO\n *\n * @notice Security:\n * - Nonces.\n */" + ); + } + #[test] fn listed_blocks_move_into_config_order_and_unlisted_ones_hold_their_slot() { let doc = "/**\n * Prose first.\n * @notice Security:\n * - Nonces.\n *\n * @param {T} a - A.\n * @module Token\n * @notice Privacy:\n * - Amounts.\n */"; diff --git a/crates/compact-lint/tests/fix.rs b/crates/compact-lint/tests/fix.rs index 1f3cbdfd..ffdf48b1 100644 --- a/crates/compact-lint/tests/fix.rs +++ b/crates/compact-lint/tests/fix.rs @@ -158,6 +158,11 @@ fn sections_are_inserted_by_heading_and_the_blocks_come_back_in_template_order() assert_case("sections"); } +#[test] +fn a_section_goes_in_below_every_paragraph_of_the_block_before_it() { + assert_case("sections-paragraphs"); +} + #[test] fn the_constraints_annotation_follows_the_description_block() { assert_case("constraints"); diff --git a/crates/compact-lint/tests/fixtures/fix-sections-paragraphs/after/Paragraphs.compact b/crates/compact-lint/tests/fixtures/fix-sections-paragraphs/after/Paragraphs.compact new file mode 100644 index 00000000..ab924145 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-sections-paragraphs/after/Paragraphs.compact @@ -0,0 +1,15 @@ +pragma language_version >= 0.23.0; + +/** + * @module Paragraphs + * @description A module whose description runs over two paragraphs. + * + * The second paragraph still describes the module. + * @notice Privacy: + * TODO + * + * @notice Security: + * - Nonces are spend-critical. + */ +export module Paragraphs { +} diff --git a/crates/compact-lint/tests/fixtures/fix-sections-paragraphs/before/Paragraphs.compact b/crates/compact-lint/tests/fixtures/fix-sections-paragraphs/before/Paragraphs.compact new file mode 100644 index 00000000..762bb2e8 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-sections-paragraphs/before/Paragraphs.compact @@ -0,0 +1,13 @@ +pragma language_version >= 0.23.0; + +/** + * @module Paragraphs + * @description A module whose description runs over two paragraphs. + * + * The second paragraph still describes the module. + * + * @notice Security: + * - Nonces are spend-critical. + */ +export module Paragraphs { +} diff --git a/crates/compact-lint/tests/fixtures/fix-sections-paragraphs/compact.toml b/crates/compact-lint/tests/fixtures/fix-sections-paragraphs/compact.toml new file mode 100644 index 00000000..5967e3f6 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-sections-paragraphs/compact.toml @@ -0,0 +1,7 @@ +[lint] +include = ["**/*.compact"] + +[lint.kinds.module] +docs = "all" +tags = ["@module", "@description", "@notice Privacy", "@notice Security"] +sections = ["@module", "@description", "@notice Privacy", "@notice Security"] diff --git a/crates/compact-lint/tests/fixtures/fix-sections-paragraphs/expected-dry-run.txt b/crates/compact-lint/tests/fixtures/fix-sections-paragraphs/expected-dry-run.txt new file mode 100644 index 00000000..998449e7 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-sections-paragraphs/expected-dry-run.txt @@ -0,0 +1,15 @@ +Paragraphs.compact:12:1 lint/missing-tag FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Module `Paragraphs` doc comment has no `@notice Privacy` section. + + 10 β”‚ * - Nonces are spend-critical. + 11 β”‚ */ + > 12 β”‚ export module Paragraphs { + β”‚ ^^^^^^^^^^^^^^^^^^^^^^^^ + 13 β”‚ } + + i Unsafe fix: Insert @notice Privacy + + 8 β”‚ + Β·*Β·@noticeΒ·Privacy: + 9 β”‚ + Β·*Β·TODO + diff --git a/crates/compact-lint/tests/fixtures/fix-sections-paragraphs/expected.txt b/crates/compact-lint/tests/fixtures/fix-sections-paragraphs/expected.txt new file mode 100644 index 00000000..41b99e84 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-sections-paragraphs/expected.txt @@ -0,0 +1,9 @@ +Paragraphs.compact:12:1 lint/missing-tag FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Module `Paragraphs` doc comment has no `@notice Privacy` section. + + i Applied fix: Insert @notice Privacy + + 8 β”‚ + Β·*Β·@noticeΒ·Privacy: + 9 β”‚ + Β·*Β·TODO + From 388fb68121db877af2dafe4b38a7c8ecabfc91f6 Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Tue, 17 Nov 2026 21:21:44 +0100 Subject: [PATCH 49/56] fix(compact-lint): move delimiter text before a reorder The tag-order fix permuted only the body lines, so text on the /** or */ line stayed put while the blocks around it moved, landing a statement under another section. A reorder now moves that text onto its own body line first, as an insertion already does. An edit that leaves the text unchanged is no longer reported or counted as a fix. --- crates/compact-lint/README.md | 2 +- crates/compact-lint/src/edit.rs | 14 +++--- crates/compact-lint/src/fix.rs | 19 ++++---- crates/compact-lint/tests/fix.rs | 5 +++ .../after/Closer.compact | 11 +++++ .../after/Opener.compact | 11 +++++ .../before/Closer.compact | 10 +++++ .../before/Opener.compact | 10 +++++ .../fix-tag-order-delimiters/compact.toml | 7 +++ .../expected-dry-run.txt | 43 +++++++++++++++++++ .../fix-tag-order-delimiters/expected.txt | 29 +++++++++++++ 11 files changed, 147 insertions(+), 14 deletions(-) create mode 100644 crates/compact-lint/tests/fixtures/fix-tag-order-delimiters/after/Closer.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-tag-order-delimiters/after/Opener.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-tag-order-delimiters/before/Closer.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-tag-order-delimiters/before/Opener.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-tag-order-delimiters/compact.toml create mode 100644 crates/compact-lint/tests/fixtures/fix-tag-order-delimiters/expected-dry-run.txt create mode 100644 crates/compact-lint/tests/fixtures/fix-tag-order-delimiters/expected.txt diff --git a/crates/compact-lint/README.md b/crates/compact-lint/README.md index 07cdb184..6df11f7f 100644 --- a/crates/compact-lint/README.md +++ b/crates/compact-lint/README.md @@ -178,7 +178,7 @@ What each rule's fix does: | --- | --- | | `missing-doc` | Inserts a doc skeleton above the declaration, indented to it. Body lines come from `kinds..tags` in config order; `@module` takes the declaration's name, a headed entry becomes a `@tag Heading:` line with `fix.placeholder` under it, every other tag takes `fix.placeholder`. Exported non-pure circuits also get the constraints line. A kind with neither gets a single placeholder line. | | `missing-tag` | Inserts each missing entry after the block of the last entry that precedes it in the template order, optional ones included, below every paragraph of that block, else at the top of the body. A headed entry goes in as a two-line section block; the predecessor's block is found by heading, not by bare tag. A missing bare `@description` adopts untagged prose that opens the body instead of writing a placeholder. Text on the `/**` or `*/` line moves onto its own body line first, so a `/** … */` one-liner expands to the multi-line form. | -| `tag-order` | Splits the comment body into one block per tag, sorts the blocks matching a listed entry into config order, and writes them back into the same slots. Prose before the first tag, unlisted blocks and the blank lines separating slots stay put, so a second run reports nothing. | +| `tag-order` | Splits the comment body into one block per tag, sorts the blocks matching a listed entry into config order, and writes them back into the same slots. Text on the `/**` or `*/` line moves onto its own body line first, so it travels with its block. Prose before the first tag, unlisted blocks and the blank lines separating slots stay put, so a second run reports nothing. | | `missing-constraints` | Inserts ` k=?, rows=?` after the `@description` block, with a blank ` *` line before it and, where prose follows, one after. Without a `@description` it opens the body. On a circuit with no doc comment, it inserts a doc comment holding only that line. Nothing is inserted when a `tags.rename` entry renames another tag in the comment to the constraints tag, and a circuit never gets the constraints tag twice, even when `kinds.circuit.tags` lists it. | | `forbidden-tag` | Renames the tag in place, and only where `tags.rename` maps it. | | `module-name` | Replaces the first word of the `@module` value with the module's name, keeping what follows. A `*/` on the same line stays in place. | diff --git a/crates/compact-lint/src/edit.rs b/crates/compact-lint/src/edit.rs index a6e28dc9..2725a48d 100644 --- a/crates/compact-lint/src/edit.rs +++ b/crates/compact-lint/src/edit.rs @@ -253,11 +253,15 @@ fn render_doc(doc: &str, indent: usize, newline: &str, ops: &[&DocOp]) -> String let margin = " ".repeat(indent); let gutter = format!("{margin} * "); - // Insertions search the body only, so text on the `/**` or `*/` line moves first. - let inserts = ops - .iter() - .any(|op| matches!(op, DocOp::InsertTag { .. } | DocOp::InsertConstraints(_))); - let shift = if inserts { + // Insertions and reorders work on the body only, so text on the `/**` or `*/` line + // moves first. + let restructures = ops.iter().any(|op| { + matches!( + op, + DocOp::InsertTag { .. } | DocOp::InsertConstraints(_) | DocOp::ReorderBlocks { .. } + ) + }); + let shift = if restructures { isolate_delimiters(&mut lines, &margin, &gutter) } else { 0 diff --git a/crates/compact-lint/src/fix.rs b/crates/compact-lint/src/fix.rs index afbd32d6..6bdba1ab 100644 --- a/crates/compact-lint/src/fix.rs +++ b/crates/compact-lint/src/fix.rs @@ -100,10 +100,15 @@ pub fn run(options: &Options, cwd: &Path, timings: &mut Timings) -> Result = issues + // An edit that leaves the text as it was repairs nothing, so it is not reported. + let repairs: Vec<(&Issue, Edit, String)> = issues .iter() .filter(|issue| !supplied_elsewhere(issue, &issues, &target.config)) .filter_map(|issue| edit_for(issue, &target.config, newline).map(|edit| (issue, edit))) + .filter_map(|(issue, edit)| { + let after = apply(&source, std::slice::from_ref(&edit), newline); + (after != source).then_some((issue, edit, after)) + }) .collect(); if repairs.is_empty() { @@ -111,11 +116,11 @@ pub fn run(options: &Options, cwd: &Path, timings: &mut Timings) -> Result = repairs.into_iter().map(|(_, edit)| edit).collect(); + let edits: Vec = repairs.into_iter().map(|(_, edit, _)| edit).collect(); let fixed = apply(&source, &edits, newline); if changes_declarations(&mut linter, path, &source, &fixed)? { return Err(FixError::Unsafe { path: path.clone() }); @@ -169,15 +174,13 @@ fn diagnostic( issue: &Issue, edit: &Edit, source: &str, - newline: &str, + after: &str, badge: Badge, ) -> Diagnostic { - let after = apply(source, std::slice::from_ref(edit), newline); - Diagnostic::new(path, edit.rule, Level::Info, issue.message()) .at(edit.span) .fixed_by( - FixPreview::between(title(edit, badge), source, &after), + FixPreview::between(title(edit, badge), source, after), badge, ) } diff --git a/crates/compact-lint/tests/fix.rs b/crates/compact-lint/tests/fix.rs index ffdf48b1..ca2ef9fe 100644 --- a/crates/compact-lint/tests/fix.rs +++ b/crates/compact-lint/tests/fix.rs @@ -163,6 +163,11 @@ fn a_section_goes_in_below_every_paragraph_of_the_block_before_it() { assert_case("sections-paragraphs"); } +#[test] +fn a_reorder_moves_text_off_the_delimiter_lines_with_its_section() { + assert_case("tag-order-delimiters"); +} + #[test] fn the_constraints_annotation_follows_the_description_block() { assert_case("constraints"); diff --git a/crates/compact-lint/tests/fixtures/fix-tag-order-delimiters/after/Closer.compact b/crates/compact-lint/tests/fixtures/fix-tag-order-delimiters/after/Closer.compact new file mode 100644 index 00000000..ba955e27 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-tag-order-delimiters/after/Closer.compact @@ -0,0 +1,11 @@ +pragma language_version >= 0.23.0; + +/** + * @module Closer + * @notice Privacy: + * - Amounts are public. + * @notice Security: + * - Nonces are spend-critical. + */ +module Closer { +} diff --git a/crates/compact-lint/tests/fixtures/fix-tag-order-delimiters/after/Opener.compact b/crates/compact-lint/tests/fixtures/fix-tag-order-delimiters/after/Opener.compact new file mode 100644 index 00000000..88eef6f6 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-tag-order-delimiters/after/Opener.compact @@ -0,0 +1,11 @@ +pragma language_version >= 0.23.0; + +/** + * @module Opener + * @notice Privacy: + * - Amounts are public. + * @notice Security: + * - Nonces are spend-critical. + */ +module Opener { +} diff --git a/crates/compact-lint/tests/fixtures/fix-tag-order-delimiters/before/Closer.compact b/crates/compact-lint/tests/fixtures/fix-tag-order-delimiters/before/Closer.compact new file mode 100644 index 00000000..26619d28 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-tag-order-delimiters/before/Closer.compact @@ -0,0 +1,10 @@ +pragma language_version >= 0.23.0; + +/** + * @module Closer + * @notice Security: + * - Nonces are spend-critical. + * @notice Privacy: + * - Amounts are public. */ +module Closer { +} diff --git a/crates/compact-lint/tests/fixtures/fix-tag-order-delimiters/before/Opener.compact b/crates/compact-lint/tests/fixtures/fix-tag-order-delimiters/before/Opener.compact new file mode 100644 index 00000000..d288d467 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-tag-order-delimiters/before/Opener.compact @@ -0,0 +1,10 @@ +pragma language_version >= 0.23.0; + +/** @notice Security: + * - Nonces are spend-critical. + * @module Opener + * @notice Privacy: + * - Amounts are public. + */ +module Opener { +} diff --git a/crates/compact-lint/tests/fixtures/fix-tag-order-delimiters/compact.toml b/crates/compact-lint/tests/fixtures/fix-tag-order-delimiters/compact.toml new file mode 100644 index 00000000..07334bd2 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-tag-order-delimiters/compact.toml @@ -0,0 +1,7 @@ +[lint] +include = ["**/*.compact"] + +[lint.kinds.module] +docs = "all" +tags = ["@module", "@notice Privacy", "@notice Security"] +sections = ["@module", "@notice Privacy", "@notice Security"] diff --git a/crates/compact-lint/tests/fixtures/fix-tag-order-delimiters/expected-dry-run.txt b/crates/compact-lint/tests/fixtures/fix-tag-order-delimiters/expected-dry-run.txt new file mode 100644 index 00000000..cf439de2 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-tag-order-delimiters/expected-dry-run.txt @@ -0,0 +1,43 @@ +Closer.compact:7:4 lint/tag-order FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i `@notice Security` comes before `@notice Privacy`; the template orders Privacy first. + + 5 β”‚ * @notice Security: + 6 β”‚ * - Nonces are spend-critical. + > 7 β”‚ * @notice Privacy: + β”‚ ^^^^^^^^^^^^^^^^ + 8 β”‚ * - Amounts are public. */ + 9 β”‚ module Closer { + + i Safe fix: Reorder the doc comment blocks + + 5 β”‚ + Β·*Β·@noticeΒ·Privacy: + 6 β”‚ + Β·*Β·-Β·AmountsΒ·areΒ·public. + 5 7 β”‚ * @notice Security: + 6 8 β”‚ * - Nonces are spend-critical. + 7 β”‚ - Β·*Β·@noticeΒ·Privacy: + 8 β”‚ - Β·*Β·-Β·AmountsΒ·areΒ·public.Β·*/ + 9 β”‚ + Β·*/ + +Opener.compact:5:4 lint/tag-order FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i `@notice Security` comes before `@module`; the template orders @module first. + + 3 β”‚ /** @notice Security: + 4 β”‚ * - Nonces are spend-critical. + > 5 β”‚ * @module Opener + β”‚ ^^^^^^^ + 6 β”‚ * @notice Privacy: + 7 β”‚ * - Amounts are public. + + i Safe fix: Reorder the doc comment blocks + + 3 β”‚ - /**Β·@noticeΒ·Security: + 4 β”‚ - Β·*Β·-Β·NoncesΒ·areΒ·spend-critical. + 3 β”‚ + /** + 5 4 β”‚ * @module Opener + 6 5 β”‚ * @notice Privacy: + 7 6 β”‚ * - Amounts are public. + 7 β”‚ + Β·*Β·@noticeΒ·Security: + 8 β”‚ + Β·*Β·-Β·NoncesΒ·areΒ·spend-critical. + diff --git a/crates/compact-lint/tests/fixtures/fix-tag-order-delimiters/expected.txt b/crates/compact-lint/tests/fixtures/fix-tag-order-delimiters/expected.txt new file mode 100644 index 00000000..a156dd68 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-tag-order-delimiters/expected.txt @@ -0,0 +1,29 @@ +Closer.compact:7:4 lint/tag-order FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i `@notice Security` comes before `@notice Privacy`; the template orders Privacy first. + + i Applied fix: Reorder the doc comment blocks + + 5 β”‚ + Β·*Β·@noticeΒ·Privacy: + 6 β”‚ + Β·*Β·-Β·AmountsΒ·areΒ·public. + 5 7 β”‚ * @notice Security: + 6 8 β”‚ * - Nonces are spend-critical. + 7 β”‚ - Β·*Β·@noticeΒ·Privacy: + 8 β”‚ - Β·*Β·-Β·AmountsΒ·areΒ·public.Β·*/ + 9 β”‚ + Β·*/ + +Opener.compact:5:4 lint/tag-order FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i `@notice Security` comes before `@module`; the template orders @module first. + + i Applied fix: Reorder the doc comment blocks + + 3 β”‚ - /**Β·@noticeΒ·Security: + 4 β”‚ - Β·*Β·-Β·NoncesΒ·areΒ·spend-critical. + 3 β”‚ + /** + 5 4 β”‚ * @module Opener + 6 5 β”‚ * @notice Privacy: + 7 6 β”‚ * - Amounts are public. + 7 β”‚ + Β·*Β·@noticeΒ·Security: + 8 β”‚ + Β·*Β·-Β·NoncesΒ·areΒ·spend-critical. + From 87f9a211c1a64125f453a51226f4f8b80968be5b Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Tue, 17 Nov 2026 21:21:51 +0100 Subject: [PATCH 50/56] fix(compact-lint): compile a fill dry run into a temp dir A dry run compiled into the configured artifacts tree, so a preview replaced the builder's compiler output for each contract it measured. It now compiles into a temporary directory removed after each compile; --no-compile still reads the configured tree. The fill tests compare the whole tree after a dry run. --- crates/compact-lint/README.md | 3 ++- crates/compact-lint/src/fill.rs | 26 ++++++++++++++---------- crates/compact-lint/tests/fill.rs | 33 ++++++++++++++++++++----------- 3 files changed, 39 insertions(+), 23 deletions(-) diff --git a/crates/compact-lint/README.md b/crates/compact-lint/README.md index 6df11f7f..d4ba80f1 100644 --- a/crates/compact-lint/README.md +++ b/crates/compact-lint/README.md @@ -215,7 +215,8 @@ compact-lint fill-constraints [PATHS]... [--config ] [--dry-run] [--no-com ``` - `PATHS` and `--config` resolve exactly as they do for `check`. -- `--dry-run` β€” report the changes and write nothing, the artifact file included. +- `--dry-run` β€” report the changes and write nothing to the project. A compile goes to a + temporary directory, removed when it ends, so the artifacts tree is left alone. - `--no-compile` β€” read each contract's `circuit-info.json` instead of compiling. A source with no artifact file is an error. - `--compact-bin ` β€” path to the `compact` binary, as for `check`. Also settable diff --git a/crates/compact-lint/src/fill.rs b/crates/compact-lint/src/fill.rs index d3e4cc26..aa5240f8 100644 --- a/crates/compact-lint/src/fill.rs +++ b/crates/compact-lint/src/fill.rs @@ -39,6 +39,8 @@ pub enum FillError { }, #[error("refusing to write {path}: it changed during the run")] Changed { path: PathBuf }, + #[error("cannot create a temporary directory for the dry-run compile")] + Scratch(#[source] std::io::Error), } /// Everything the subcommand needs, already resolved from flags and env. @@ -214,7 +216,7 @@ fn measure_sources( sources.sort(); sources.dedup(); - let compiler = Compiler { + let mut compiler = Compiler { binary: options.compact_bin.clone(), version: version.cloned(), artifacts: artifacts.directory.clone(), @@ -232,17 +234,21 @@ fn measure_sources( let path = measure::locate(&artifacts.directory, source)?; let list = measure::read_artifact(&path)?; (list, path.display().to_string()) + } else if options.dry_run { + // A preview writes nothing to the project, so it compiles into a directory that + // is removed once the compile ends. + let scratch = tempfile::tempdir().map_err(FillError::Scratch)?; + scratch.path().clone_into(&mut compiler.artifacts); + let list = compiler.measure(source)?; + (list, source.display().to_string()) } else { let list = compiler.measure(source)?; - // A preview writes nothing, the artifact included. - if !options.dry_run { - measure::write_artifact( - &artifacts.directory, - source, - &artifacts.recorded(source, cwd), - &list, - )?; - } + measure::write_artifact( + &artifacts.directory, + source, + &artifacts.recorded(source, cwd), + &list, + )?; (list, source.display().to_string()) }; phase.stop(timings, detail); diff --git a/crates/compact-lint/tests/fill.rs b/crates/compact-lint/tests/fill.rs index 3dc80557..e97826db 100644 --- a/crates/compact-lint/tests/fill.rs +++ b/crates/compact-lint/tests/fill.rs @@ -70,19 +70,32 @@ fn copy_tree(from: &Path, to: &Path) { /// Every `.compact` file under `root`, keyed by its path relative to it. fn sources(root: &Path) -> BTreeMap> { let mut found = BTreeMap::new(); - collect(root, root, &mut found); + collect(root, root, true, &mut found); found } -fn collect(root: &Path, directory: &Path, out: &mut BTreeMap>) { +/// Every file under `root`, artifacts included, keyed by its path relative to it. +fn tree(root: &Path) -> BTreeMap> { + let mut found = BTreeMap::new(); + collect(root, root, false, &mut found); + found +} + +fn collect( + root: &Path, + directory: &Path, + only_sources: bool, + out: &mut BTreeMap>, +) { for entry in std::fs::read_dir(directory).expect("the tree is readable") { let entry = entry.expect("the entry is readable"); let path = entry.path(); if path.is_dir() { - collect(root, &path, out); - } else if path - .extension() - .is_some_and(|extension| extension == "compact") + collect(root, &path, only_sources, out); + } else if !only_sources + || path + .extension() + .is_some_and(|extension| extension == "compact") { let relative = path.strip_prefix(root).expect("the path is under the root"); out.insert( @@ -165,7 +178,7 @@ fn assert_case(name: &str, extra: &[&str], exit: i32) { assert_eq!(code, exit, "second run exit code for case {name}"); let preview = work(name); - let before = sources(preview.path()); + let before = tree(preview.path()); let mut arguments = extra.to_vec(); arguments.push("--dry-run"); let (code, stdout) = code_and_stdout(&fill(preview.path(), &arguments)); @@ -175,11 +188,7 @@ fn assert_case(name: &str, extra: &[&str], exit: i32) { "dry-run stdout for case {name}" ); assert_eq!(code, exit, "dry-run exit code for case {name}"); - assert_eq!( - sources(preview.path()), - before, - "dry-run wrote to case {name}" - ); + assert_eq!(tree(preview.path()), before, "dry-run wrote to case {name}"); } #[test] From ce49b5e31a1827126e999401d5ceea6542613064 Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Tue, 17 Nov 2026 21:21:57 +0100 Subject: [PATCH 51/56] fix(compact-lint): take the fill exit code from rule levels fill-constraints exited 1 for any unmeasured circuit at every level but off, unlike check and fix. In compact-contracts the module initialize circuits cannot be measured, so a CI step running it failed every time. The exit code now follows the diagnostic levels and --error-on-warnings. --- crates/compact-lint/README.md | 5 +++-- crates/compact-lint/src/fill.rs | 4 ---- crates/compact-lint/src/main.rs | 3 --- crates/compact-lint/tests/fill.rs | 30 ++++++++++++++++++++++++------ 4 files changed, 27 insertions(+), 15 deletions(-) diff --git a/crates/compact-lint/README.md b/crates/compact-lint/README.md index d4ba80f1..55b7cae2 100644 --- a/crates/compact-lint/README.md +++ b/crates/compact-lint/README.md @@ -300,8 +300,9 @@ with the candidates tried named in the advice. Exit codes: -- `0` β€” every tagged circuit was measured, whether or not a value changed. -- `1` β€” at least one circuit is unmeasured or unmeasurable. +- `0` β€” no error-level diagnostics, whether or not a value changed. Unmeasured and + unmeasurable circuits are `warn` by default, so they leave the exit code alone. +- `1` β€” at least one error-level diagnostic, or a warning with `--error-on-warnings`. - `2` β€” usage, config, IO, compiler or missing-artifact error. A failed compile prints the source and the last 20 lines of the compiler's cleaned output; the raw pty stream is never printed. A compile that proves a circuit but prints no measurement for it is an diff --git a/crates/compact-lint/src/fill.rs b/crates/compact-lint/src/fill.rs index aa5240f8..062b4d2c 100644 --- a/crates/compact-lint/src/fill.rs +++ b/crates/compact-lint/src/fill.rs @@ -90,7 +90,6 @@ pub struct Outcome { pub files: usize, /// Files the run read, changed or not. pub checked: usize, - pub unmeasured: usize, } /// One file's annotations and the contract they are measured through. @@ -157,7 +156,6 @@ pub fn run(options: &Options, cwd: &Path, timings: &mut Timings) -> Result = work .iter() @@ -288,7 +286,6 @@ fn fill_file( outcome .diagnostics .push(unmeasurable(&file.path, tried, level)); - outcome.unmeasured += file.sites.len(); } return None; } @@ -307,7 +304,6 @@ fn fill_file( tag, unmeasured_level, )); - outcome.unmeasured += 1; } continue; }; diff --git a/crates/compact-lint/src/main.rs b/crates/compact-lint/src/main.rs index bd8dd19a..4e3e5af3 100644 --- a/crates/compact-lint/src/main.rs +++ b/crates/compact-lint/src/main.rs @@ -318,9 +318,6 @@ fn run_fill(args: FillArgs, cwd: &std::path::Path) -> Result { ) .context("writing the report")?; - if outcome.unmeasured > 0 { - return Ok(ExitCode::from(EXIT_FINDINGS)); - } Ok(exit_code( printed.errors, printed.warnings, diff --git a/crates/compact-lint/tests/fill.rs b/crates/compact-lint/tests/fill.rs index e97826db..7372def1 100644 --- a/crates/compact-lint/tests/fill.rs +++ b/crates/compact-lint/tests/fill.rs @@ -11,8 +11,8 @@ use std::process::{Command, Output}; use assert_cmd::prelude::*; use tempfile::TempDir; -/// Exit code for a run that left a tagged circuit unmeasured. -const EXIT_UNMEASURED: i32 = 1; +/// Exit code for an error-level diagnostic, or a warning under `--error-on-warnings`. +const EXIT_FINDINGS: i32 = 1; /// Exit code for a config, IO or compiler error. const EXIT_ERROR: i32 = 2; @@ -193,7 +193,7 @@ fn assert_case(name: &str, extra: &[&str], exit: i32) { #[test] fn placeholders_and_stale_values_take_the_measurement() { - assert_case("basic", &[], EXIT_UNMEASURED); + assert_case("basic", &[], 0); } #[test] @@ -232,7 +232,7 @@ fn a_circuit_the_report_marks_unproved_stays_unmeasured() { } #[test] -fn a_file_with_no_measurement_source_reports_once_and_exits_one() { +fn a_file_with_no_measurement_source_reports_once() { let directory = work("missing-source"); let root = directory.path(); let before = sources(root); @@ -240,10 +240,28 @@ fn a_file_with_no_measurement_source_reports_once_and_exits_one() { let (code, stdout) = code_and_stdout(&fill(root, &[])); assert_eq!(stdout, expected("missing-source", "expected.txt")); - assert_eq!(code, EXIT_UNMEASURED); + assert_eq!(code, 0); assert_eq!(sources(root), before); } +#[test] +fn an_unmeasured_circuit_fails_the_run_only_at_error_level_or_with_error_on_warnings() { + let directory = work("basic"); + let root = directory.path(); + let (code, _) = code_and_stdout(&fill(root, &["--dry-run"])); + assert_eq!(code, 0, "at the default warn level"); + + let (code, _) = code_and_stdout(&fill(root, &["--dry-run", "--error-on-warnings"])); + assert_eq!(code, EXIT_FINDINGS, "with --error-on-warnings"); + + let config = root.join("compact.toml"); + let mut text = std::fs::read_to_string(&config).expect("the config is readable"); + text.push_str("\n[lint.rules]\nconstraints-unmeasured = \"error\"\n"); + std::fs::write(&config, text).expect("the config is writable"); + let (code, _) = code_and_stdout(&fill(root, &["--dry-run"])); + assert_eq!(code, EXIT_FINDINGS, "at the error level"); +} + #[test] fn a_failed_compile_exits_two_with_the_output_tail() { let directory = work("compiler-fails"); @@ -284,7 +302,7 @@ fn no_color_in_the_environment_still_measures() { code_and_stdout(&fill_with_env(directory.path(), &[], &[("NO_COLOR", "1")])); assert_eq!(stdout, expected("basic", "expected.txt")); - assert_eq!(code, EXIT_UNMEASURED); + assert_eq!(code, 0); } #[test] From 1e707bf1a28a8d6040bc8dd5851057a6854a8718 Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Tue, 17 Nov 2026 21:21:57 +0100 Subject: [PATCH 52/56] docs(compact-lint): drop the kept-artifact claim compactc replaces a contract's output directory when it compiles, so a compile that prints no measurement cannot promise the old artifact survives. What holds is that no circuit-info.json is written. --- crates/compact-lint/README.md | 2 +- crates/compact-lint/tests/fill.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/compact-lint/README.md b/crates/compact-lint/README.md index 55b7cae2..968d9515 100644 --- a/crates/compact-lint/README.md +++ b/crates/compact-lint/README.md @@ -306,7 +306,7 @@ Exit codes: - `2` β€” usage, config, IO, compiler or missing-artifact error. A failed compile prints the source and the last 20 lines of the compiler's cleaned output; the raw pty stream is never printed. A compile that proves a circuit but prints no measurement for it is an - error too, and leaves the artifact as it was. + error too, and writes no `circuit-info.json`. Files are rewritten exactly as `fix` rewrites them: through a sibling `.tmp` file, keeping the line ending, and only the annotation's own line changes. Before the first write every diff --git a/crates/compact-lint/tests/fill.rs b/crates/compact-lint/tests/fill.rs index 7372def1..d5790bba 100644 --- a/crates/compact-lint/tests/fill.rs +++ b/crates/compact-lint/tests/fill.rs @@ -306,7 +306,7 @@ fn no_color_in_the_environment_still_measures() { } #[test] -fn a_compile_with_no_progress_lines_exits_two_and_keeps_the_artifact() { +fn a_compile_with_no_progress_lines_exits_two_without_writing_circuit_info() { let directory = work("no-compile"); let artifact = directory .path() From c7345f62da926a5b38eb21f9e3345936ca523a1e Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Wed, 18 Nov 2026 09:52:55 +0100 Subject: [PATCH 53/56] fix(compact-lint): parse every row on a line compactc 0.36.0 pads each progress row to the terminal width and leaves the line break to the terminal, so every row of a compile shares one line. The parser read one row per line, so a contract with two or more circuits failed with "printed no measurement". * a line now yields every `circuit "" (k=, rows=)` on it, and a row still missing a field no longer hides the rows after it * the fake compiler draws its rows that way under FAKE_COMPACT_WRAP, so the pty path is covered end to end * a 0.36.0 transcript of a two-circuit mock joins the fixtures --- crates/compact-lint/src/measure.rs | 47 ++++++++++++++++--- crates/compact-lint/tests/fill.rs | 13 +++++ .../fixtures/fill-fake-compact/bin/compact | 12 ++++- .../fixtures/fill-transcript/pty-0.36.0.txt | 2 + 4 files changed, 66 insertions(+), 8 deletions(-) create mode 100644 crates/compact-lint/tests/fixtures/fill-transcript/pty-0.36.0.txt diff --git a/crates/compact-lint/src/measure.rs b/crates/compact-lint/src/measure.rs index 478343de..1cd65698 100644 --- a/crates/compact-lint/src/measure.rs +++ b/crates/compact-lint/src/measure.rs @@ -24,6 +24,9 @@ const CONTRACT_INFO_PATH: [&str; 2] = ["compiler", "contract-info.json"]; /// A dependency tree carries its own artifacts, so the search never descends into one. const SKIPPED_DIR: &str = "node_modules"; +/// Opens the compiler's per-circuit progress row, `circuit "" (k=, rows=)`. +const ROW_MARKER: &str = "circuit "; + /// Compiler-output lines kept in a failure report. const TAIL_LINES: usize = 20; @@ -472,22 +475,28 @@ fn strip_escapes(raw: &str) -> String { out } -/// Every measured circuit in a cleaned transcript; the last line for a name wins. +/// Every measured circuit in a cleaned transcript; the last row for a name wins. #[must_use] pub fn parse(cleaned: &str) -> Vec { let mut found: BTreeMap = BTreeMap::new(); for line in cleaned.lines() { - if let Some(measurement) = parse_line(line) { + for measurement in parse_line(line) { found.insert(measurement.name.clone(), measurement); } } found.into_values().collect() } -/// Matches `circuit "" (k=, rows=)`, the compiler's per-circuit progress line. -fn parse_line(line: &str) -> Option { - let after = line.split_once("circuit ")?.1.trim_start(); - let (name, rest) = after.strip_prefix('"')?.split_once('"')?; +/// Every progress row on a line. A compiler that pads a row to the terminal width in +/// place of ending it puts all its rows on one line. +fn parse_line(line: &str) -> impl Iterator + '_ { + line.match_indices(ROW_MARKER) + .filter_map(|(start, marker)| parse_row(&line[start + marker.len()..])) +} + +/// Matches `"" (k=, rows=)`, the rest of a row after [`ROW_MARKER`]. +fn parse_row(after: &str) -> Option { + let (name, rest) = after.trim_start().strip_prefix('"')?.split_once('"')?; let fields = rest.trim_start().strip_prefix('(')?.split_once(')')?.0; let (k, rows) = fields.split_once(',')?; @@ -603,6 +612,32 @@ mod tests { ); } + #[test] + fn rows_sharing_one_line_each_yield_a_measurement() { + let wrapped = std::fs::read_to_string( + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures/fill-transcript/pty-0.36.0.txt"), + ) + .expect("the captured transcript is readable"); + let cleaned = clean(&wrapped); + + assert_eq!(cleaned.lines().count(), 2, "{cleaned}"); + assert_eq!( + parse(&cleaned), + [measurement("bump", 6, 31), measurement("read", 6, 34)] + ); + } + + #[test] + fn a_row_still_missing_a_field_does_not_hide_the_rows_after_it() { + let line = "circuit \"bump\" (k=6) circuit \"read\" (k=6, rows=34) circuit \"bump\" (k=6, rows=31)"; + + assert_eq!( + parse(line), + [measurement("bump", 6, 31), measurement("read", 6, 34)] + ); + } + #[test] fn the_last_line_for_a_name_wins_over_the_partial_frames_above_it() { let frames = " circuit \"owner\" (k=7)\n circuit \"owner\" (k=7, rows=9999)\n circuit \"owner\" (k=7, rows=74)\n"; diff --git a/crates/compact-lint/tests/fill.rs b/crates/compact-lint/tests/fill.rs index d5790bba..53049a30 100644 --- a/crates/compact-lint/tests/fill.rs +++ b/crates/compact-lint/tests/fill.rs @@ -305,6 +305,19 @@ fn no_color_in_the_environment_still_measures() { assert_eq!(code, 0); } +#[test] +fn rows_the_compiler_wraps_onto_one_line_are_all_measured() { + let directory = work("basic"); + let (code, stdout) = code_and_stdout(&fill_with_env( + directory.path(), + &[], + &[("FAKE_COMPACT_WRAP", "1")], + )); + + assert_eq!(stdout, expected("basic", "expected.txt")); + assert_eq!(code, 0); +} + #[test] fn a_compile_with_no_progress_lines_exits_two_without_writing_circuit_info() { let directory = work("no-compile"); diff --git a/crates/compact-lint/tests/fixtures/fill-fake-compact/bin/compact b/crates/compact-lint/tests/fixtures/fill-fake-compact/bin/compact index c889a1f3..1dc3060a 100755 --- a/crates/compact-lint/tests/fixtures/fill-fake-compact/bin/compact +++ b/crates/compact-lint/tests/fixtures/fill-fake-compact/bin/compact @@ -62,11 +62,19 @@ else table_lines=$table fi +# With FAKE_COMPACT_WRAP, pad a row to the terminal width in place of ending it, the way +# a compiler that leaves the line break to the terminal does. +if [ -n "$FAKE_COMPACT_WRAP" ]; then + row='%-200s' +else + row='%s\n' +fi + echo "$table_lines" | while read -r circuit k rows proof; do [ -n "$circuit" ] || continue # The real compiler redraws the line, so the same circuit appears without rows first. - printf ' circuit "%s" (k=%s)\n' "$circuit" "$k" - printf ' circuit "%s" (k=%s, rows=%s)\n' "$circuit" "$k" "$rows" + printf "$row" " circuit \"$circuit\" (k=$k)" + printf "$row" " circuit \"$circuit\" (k=$k, rows=$rows)" done mkdir -p "$output/compiler" diff --git a/crates/compact-lint/tests/fixtures/fill-transcript/pty-0.36.0.txt b/crates/compact-lint/tests/fixtures/fill-transcript/pty-0.36.0.txt new file mode 100644 index 00000000..b8d3e546 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fill-transcript/pty-0.36.0.txt @@ -0,0 +1,2 @@ +Compiling 2 circuits: + circuit "bump" |  circuit "bump" (k=6) |  circuit "bump" (k=6, rows=31) |  circuit "bump" (k=6, rows=31) | circuit "read" |    circuit "bump" (k=6, rows=31) | circuit "read" (k=6) |    circuit "bump" (k=6, rows=31) | circuit "read" (k=6, rows=34) |    circuit "bump" (k=6, rows=31) | circuit "read" (k=6, rows=34) | Overall progress [ ]     circuit "bump" (k=6, rows=31)   circuit "read" (k=6, rows=34)   Overall progress [====================] 2/2 \ No newline at end of file From 336421d1cf3ed8f5e2cc69499caad793f793c3c7 Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Wed, 18 Nov 2026 09:55:59 +0100 Subject: [PATCH 54/56] fix(compact-lint): keep missing-constraints at its level An exported non-pure circuit with no doc comment reported only `missing-doc`, so `missing-doc = "off"` or `"warn"` also dropped or downgraded the missing constraints, whatever level `missing-constraints` was set to. * such a circuit now reports `missing-constraints` beside `missing-doc`, each at its own level * `fix` still writes one comment: the constraints-only insert is skipped where the skeleton already carries the line --- crates/compact-lint/README.md | 9 ++-- crates/compact-lint/src/fix.rs | 15 ++++-- crates/compact-lint/src/rules.rs | 26 ++++++++-- crates/compact-lint/tests/check.rs | 17 ++++++ crates/compact-lint/tests/fix.rs | 5 ++ .../after/Undocumented.compact | 7 +++ .../before/Undocumented.compact | 4 ++ .../fix-constraints-doc-off/compact.toml | 5 ++ .../expected-dry-run.txt | 15 ++++++ .../fix-constraints-doc-off/expected.txt | 10 ++++ .../missing-doc-level/Undocumented.compact | 4 ++ .../fixtures/missing-doc-level/compact.toml | 5 ++ .../missing-doc-level/expected-warn.txt | 52 +++++++++++++++++++ .../fixtures/missing-doc-level/expected.txt | 17 ++++++ .../fixtures/missing-doc-level/warn.toml | 5 ++ .../tests/fixtures/missing-doc/expected.txt | 19 +++++++ 16 files changed, 203 insertions(+), 12 deletions(-) create mode 100644 crates/compact-lint/tests/fixtures/fix-constraints-doc-off/after/Undocumented.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-constraints-doc-off/before/Undocumented.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-constraints-doc-off/compact.toml create mode 100644 crates/compact-lint/tests/fixtures/fix-constraints-doc-off/expected-dry-run.txt create mode 100644 crates/compact-lint/tests/fixtures/fix-constraints-doc-off/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/missing-doc-level/Undocumented.compact create mode 100644 crates/compact-lint/tests/fixtures/missing-doc-level/compact.toml create mode 100644 crates/compact-lint/tests/fixtures/missing-doc-level/expected-warn.txt create mode 100644 crates/compact-lint/tests/fixtures/missing-doc-level/expected.txt create mode 100644 crates/compact-lint/tests/fixtures/missing-doc-level/warn.toml diff --git a/crates/compact-lint/README.md b/crates/compact-lint/README.md index 968d9515..b158cda5 100644 --- a/crates/compact-lint/README.md +++ b/crates/compact-lint/README.md @@ -83,7 +83,7 @@ with this on stderr: ```text Checked 1 file in 2ms. No fixes applied. -Found 3 errors. +Found 4 errors. ``` ## Performance @@ -179,7 +179,7 @@ What each rule's fix does: | `missing-doc` | Inserts a doc skeleton above the declaration, indented to it. Body lines come from `kinds..tags` in config order; `@module` takes the declaration's name, a headed entry becomes a `@tag Heading:` line with `fix.placeholder` under it, every other tag takes `fix.placeholder`. Exported non-pure circuits also get the constraints line. A kind with neither gets a single placeholder line. | | `missing-tag` | Inserts each missing entry after the block of the last entry that precedes it in the template order, optional ones included, below every paragraph of that block, else at the top of the body. A headed entry goes in as a two-line section block; the predecessor's block is found by heading, not by bare tag. A missing bare `@description` adopts untagged prose that opens the body instead of writing a placeholder. Text on the `/**` or `*/` line moves onto its own body line first, so a `/** … */` one-liner expands to the multi-line form. | | `tag-order` | Splits the comment body into one block per tag, sorts the blocks matching a listed entry into config order, and writes them back into the same slots. Text on the `/**` or `*/` line moves onto its own body line first, so it travels with its block. Prose before the first tag, unlisted blocks and the blank lines separating slots stay put, so a second run reports nothing. | -| `missing-constraints` | Inserts ` k=?, rows=?` after the `@description` block, with a blank ` *` line before it and, where prose follows, one after. Without a `@description` it opens the body. On a circuit with no doc comment, it inserts a doc comment holding only that line. Nothing is inserted when a `tags.rename` entry renames another tag in the comment to the constraints tag, and a circuit never gets the constraints tag twice, even when `kinds.circuit.tags` lists it. | +| `missing-constraints` | Inserts ` k=?, rows=?` after the `@description` block, with a blank ` *` line before it and, where prose follows, one after. Without a `@description` it opens the body. On a circuit with no doc comment, it inserts a doc comment holding only that line, unless the `missing-doc` skeleton already carries it. Nothing is inserted when a `tags.rename` entry renames another tag in the comment to the constraints tag, and a circuit never gets the constraints tag twice, even when `kinds.circuit.tags` lists it. | | `forbidden-tag` | Renames the tag in place, and only where `tags.rename` maps it. | | `module-name` | Replaces the first word of the `@module` value with the module's name, keeping what follows. A `*/` on the same line stays in place. | @@ -339,8 +339,9 @@ Rule detail: - **Export.** "Exported" means the declaration carries the `export` token itself. A non-exported circuit inside an exported module is not exported. - **Constraints.** The rule applies to exported non-pure circuits only, and that is - fixed, not configurable. A missing doc comment reports as `missing-doc` when the - kind's `docs` policy requires one, and as `missing-constraints` when it does not. + fixed, not configurable. Such a circuit with no doc comment reports + `missing-constraints` whatever its `docs` policy, beside `missing-doc` when the policy + requires one, so each rule keeps its own level. - **`module-name`.** The documented name is the first word of the `@module` value, without its generic arguments or trailing punctuation, so `@module Signer` matches `module Signer` and `@module Utils.` matches `module Utils`. diff --git a/crates/compact-lint/src/fix.rs b/crates/compact-lint/src/fix.rs index 6bdba1ab..a4b2c293 100644 --- a/crates/compact-lint/src/fix.rs +++ b/crates/compact-lint/src/fix.rs @@ -196,13 +196,22 @@ fn changes_declarations( Ok(linter.outline(path, before)? != linter.outline(path, after)?) } -/// Whether another edit on the same doc comment already writes the tag this -/// `missing-tag` or `missing-constraints` issue would insert: a rename to it, or, for -/// the constraints tag, the constraints line. +/// Whether another edit already writes the tag this `missing-tag` or +/// `missing-constraints` issue would insert: a rename to it, the constraints line, or, +/// for a circuit with no doc comment, the skeleton carrying that line. /// /// Inserting it as well would leave the comment carrying the tag twice. A headed entry /// is exempt: a rename writes a bare tag, which is not the section that is missing. fn supplied_elsewhere(issue: &Issue, issues: &[Issue], config: &Config) -> bool { + if let Issue::UndocumentedConstraints { offset, .. } = issue { + return issues.iter().any(|other| { + matches!( + other, + Issue::MissingDoc { offset: skeleton, constraints: true, .. } if skeleton == offset + ) + }); + } + let (tag, doc, inserts_tag) = match issue { Issue::MissingTag { entry, doc, .. } if entry.heading.is_none() => (&entry.tag, doc, true), Issue::MissingConstraints { tag, doc, .. } => (tag, doc, false), diff --git a/crates/compact-lint/src/rules.rs b/crates/compact-lint/src/rules.rs index 987bc7bf..f3085c99 100644 --- a/crates/compact-lint/src/rules.rs +++ b/crates/compact-lint/src/rules.rs @@ -134,8 +134,7 @@ pub enum Issue { tag: Tag, doc: DocRef, }, - /// `missing-constraints` on a circuit with no doc comment, where the docs policy - /// does not ask for one. + /// `missing-constraints` on a circuit with no doc comment. UndocumentedConstraints { position: Position, end: Position, @@ -476,7 +475,9 @@ fn check_declaration(declaration: &Declaration, config: &Config, issues: &mut Ve indent: declaration.position.column - 1, constraints: takes_constraints(declaration), }); - } else if takes_constraints(declaration) { + } + // Reported beside `missing-doc`, so each rule keeps its own level. + if takes_constraints(declaration) { issues.push(Issue::UndocumentedConstraints { position: declaration.position, end: declaration.end, @@ -863,12 +864,27 @@ mod tests { } #[test] - fn an_undocumented_circuit_reports_only_missing_doc_when_docs_are_required() { + fn an_undocumented_circuit_reports_missing_constraints_beside_missing_doc() { let source = "export circuit bump(): [] { count.increment(1); }\n"; assert_eq!( reported(source, &circuit_config()), - ["1:1 missing-doc Circuit `bump` has no doc comment."] + [ + "1:1 missing-constraints Circuit `bump` has no doc comment, so no @constraints.", + "1:1 missing-doc Circuit `bump` has no doc comment." + ] + ); + } + + #[test] + fn missing_doc_turned_off_leaves_missing_constraints_on_an_undocumented_circuit() { + let source = "export circuit bump(): [] { count.increment(1); }\n"; + let mut config = circuit_config(); + config.rules.missing_doc = Level::Off; + + assert_eq!( + reported(source, &config), + ["1:1 missing-constraints Circuit `bump` has no doc comment, so no @constraints."] ); } diff --git a/crates/compact-lint/tests/check.rs b/crates/compact-lint/tests/check.rs index 802d0a7e..f5b3054c 100644 --- a/crates/compact-lint/tests/check.rs +++ b/crates/compact-lint/tests/check.rs @@ -140,6 +140,23 @@ fn an_unannotated_exported_circuit_reports_missing_constraints() { assert_case("missing-constraints", &[], EXIT_FINDINGS); } +#[test] +fn an_undocumented_circuit_fails_on_missing_constraints_whatever_the_missing_doc_level() { + assert_case("missing-doc-level", &["--strict"], EXIT_FINDINGS); + assert_expectation( + "missing-doc-level", + "expected-warn.txt", + &["--strict", "--config", "warn.toml"], + EXIT_FINDINGS, + ); + + let (_, _, stderr) = run("missing-doc-level", &["--config", "warn.toml"]); + assert!( + stderr.ends_with("Found 1 error.\nFound 2 warnings.\n"), + "{stderr}" + ); +} + #[test] fn a_malformed_constraints_value_reports_constraints_format() { assert_case("constraints-format", &[], EXIT_FINDINGS); diff --git a/crates/compact-lint/tests/fix.rs b/crates/compact-lint/tests/fix.rs index ca2ef9fe..bd6a228d 100644 --- a/crates/compact-lint/tests/fix.rs +++ b/crates/compact-lint/tests/fix.rs @@ -183,6 +183,11 @@ fn an_undocumented_circuit_under_docs_none_takes_a_constraints_only_comment() { assert_case("constraints-undocumented"); } +#[test] +fn an_undocumented_circuit_with_missing_doc_off_takes_a_constraints_only_comment() { + assert_case("constraints-doc-off"); +} + #[test] fn a_forbidden_tag_with_a_replacement_is_renamed_in_place() { assert_case("rename"); diff --git a/crates/compact-lint/tests/fixtures/fix-constraints-doc-off/after/Undocumented.compact b/crates/compact-lint/tests/fixtures/fix-constraints-doc-off/after/Undocumented.compact new file mode 100644 index 00000000..17cfc8f2 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-constraints-doc-off/after/Undocumented.compact @@ -0,0 +1,7 @@ +pragma language_version >= 0.22.0; +import CompactStandardLibrary; +export ledger n: Counter; +/** + * @constraints k=?, rows=? + */ +export circuit deposit(): [] { n.increment(1); } diff --git a/crates/compact-lint/tests/fixtures/fix-constraints-doc-off/before/Undocumented.compact b/crates/compact-lint/tests/fixtures/fix-constraints-doc-off/before/Undocumented.compact new file mode 100644 index 00000000..6ade2e97 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-constraints-doc-off/before/Undocumented.compact @@ -0,0 +1,4 @@ +pragma language_version >= 0.22.0; +import CompactStandardLibrary; +export ledger n: Counter; +export circuit deposit(): [] { n.increment(1); } diff --git a/crates/compact-lint/tests/fixtures/fix-constraints-doc-off/compact.toml b/crates/compact-lint/tests/fixtures/fix-constraints-doc-off/compact.toml new file mode 100644 index 00000000..9de5c1ec --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-constraints-doc-off/compact.toml @@ -0,0 +1,5 @@ +[lint] +include = ["**/*.compact"] + +[lint.rules] +missing-doc = "off" diff --git a/crates/compact-lint/tests/fixtures/fix-constraints-doc-off/expected-dry-run.txt b/crates/compact-lint/tests/fixtures/fix-constraints-doc-off/expected-dry-run.txt new file mode 100644 index 00000000..9eccb266 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-constraints-doc-off/expected-dry-run.txt @@ -0,0 +1,15 @@ +Undocumented.compact:4:1 lint/missing-constraints FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `deposit` has no doc comment, so no @constraints. + + 2 β”‚ import CompactStandardLibrary; + 3 β”‚ export ledger n: Counter; + > 4 β”‚ export circuit deposit(): [] { n.increment(1); } + β”‚ ^^^^^^^^^^^^^^^^^^^^^^ + + i Unsafe fix: Insert @constraints k=?, rows=? + + 4 β”‚ + /** + 5 β”‚ + Β·*Β·@constraintsΒ·k=?,Β·rows=? + 6 β”‚ + Β·*/ + diff --git a/crates/compact-lint/tests/fixtures/fix-constraints-doc-off/expected.txt b/crates/compact-lint/tests/fixtures/fix-constraints-doc-off/expected.txt new file mode 100644 index 00000000..9ad93402 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-constraints-doc-off/expected.txt @@ -0,0 +1,10 @@ +Undocumented.compact:4:1 lint/missing-constraints FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `deposit` has no doc comment, so no @constraints. + + i Applied fix: Insert @constraints k=?, rows=? + + 4 β”‚ + /** + 5 β”‚ + Β·*Β·@constraintsΒ·k=?,Β·rows=? + 6 β”‚ + Β·*/ + diff --git a/crates/compact-lint/tests/fixtures/missing-doc-level/Undocumented.compact b/crates/compact-lint/tests/fixtures/missing-doc-level/Undocumented.compact new file mode 100644 index 00000000..6ade2e97 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/missing-doc-level/Undocumented.compact @@ -0,0 +1,4 @@ +pragma language_version >= 0.22.0; +import CompactStandardLibrary; +export ledger n: Counter; +export circuit deposit(): [] { n.increment(1); } diff --git a/crates/compact-lint/tests/fixtures/missing-doc-level/compact.toml b/crates/compact-lint/tests/fixtures/missing-doc-level/compact.toml new file mode 100644 index 00000000..53245f48 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/missing-doc-level/compact.toml @@ -0,0 +1,5 @@ +[lint] + +[lint.rules] +missing-doc = "off" +missing-constraints = "error" diff --git a/crates/compact-lint/tests/fixtures/missing-doc-level/expected-warn.txt b/crates/compact-lint/tests/fixtures/missing-doc-level/expected-warn.txt new file mode 100644 index 00000000..221cdfef --- /dev/null +++ b/crates/compact-lint/tests/fixtures/missing-doc-level/expected-warn.txt @@ -0,0 +1,52 @@ +Undocumented.compact:3:1 lint/missing-doc FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + ! Ledger `n` has no doc comment. + + 1 β”‚ pragma language_version >= 0.22.0; + 2 β”‚ import CompactStandardLibrary; + > 3 β”‚ export ledger n: Counter; + β”‚ ^^^^^^^^^^^^^^^ + 4 β”‚ export circuit deposit(): [] { n.increment(1); } + + i Add a doc comment above it, or run compact-lint fix. + + i Unsafe fix: Insert a doc skeleton for ledger `n` + + 3 β”‚ + /** + 4 β”‚ + Β·*Β·TODO + 5 β”‚ + Β·*/ + +Undocumented.compact:4:1 lint/missing-constraints FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + Γ— Circuit `deposit` has no doc comment, so no @constraints. + + 2 β”‚ import CompactStandardLibrary; + 3 β”‚ export ledger n: Counter; + > 4 β”‚ export circuit deposit(): [] { n.increment(1); } + β”‚ ^^^^^^^^^^^^^^^^^^^^^^ + + i Add a doc comment holding @constraints k=?, rows=?, or run compact-lint fix. + + i Unsafe fix: Insert @constraints k=?, rows=? + + 4 β”‚ + /** + 5 β”‚ + Β·*Β·@constraintsΒ·k=?,Β·rows=? + 6 β”‚ + Β·*/ + +Undocumented.compact:4:1 lint/missing-doc FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + ! Circuit `deposit` has no doc comment. + + 2 β”‚ import CompactStandardLibrary; + 3 β”‚ export ledger n: Counter; + > 4 β”‚ export circuit deposit(): [] { n.increment(1); } + β”‚ ^^^^^^^^^^^^^^^^^^^^^^ + + i Add a doc comment above it, or run compact-lint fix. + + i Unsafe fix: Insert a doc skeleton for circuit `deposit` + + 4 β”‚ + /** + 5 β”‚ + Β·*Β·@constraintsΒ·k=?,Β·rows=? + 6 β”‚ + Β·*/ + diff --git a/crates/compact-lint/tests/fixtures/missing-doc-level/expected.txt b/crates/compact-lint/tests/fixtures/missing-doc-level/expected.txt new file mode 100644 index 00000000..7ee0f16b --- /dev/null +++ b/crates/compact-lint/tests/fixtures/missing-doc-level/expected.txt @@ -0,0 +1,17 @@ +Undocumented.compact:4:1 lint/missing-constraints FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + Γ— Circuit `deposit` has no doc comment, so no @constraints. + + 2 β”‚ import CompactStandardLibrary; + 3 β”‚ export ledger n: Counter; + > 4 β”‚ export circuit deposit(): [] { n.increment(1); } + β”‚ ^^^^^^^^^^^^^^^^^^^^^^ + + i Add a doc comment holding @constraints k=?, rows=?, or run compact-lint fix. + + i Unsafe fix: Insert @constraints k=?, rows=? + + 4 β”‚ + /** + 5 β”‚ + Β·*Β·@constraintsΒ·k=?,Β·rows=? + 6 β”‚ + Β·*/ + diff --git a/crates/compact-lint/tests/fixtures/missing-doc-level/warn.toml b/crates/compact-lint/tests/fixtures/missing-doc-level/warn.toml new file mode 100644 index 00000000..d5644928 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/missing-doc-level/warn.toml @@ -0,0 +1,5 @@ +[lint] + +[lint.rules] +missing-doc = "warn" +missing-constraints = "error" diff --git a/crates/compact-lint/tests/fixtures/missing-doc/expected.txt b/crates/compact-lint/tests/fixtures/missing-doc/expected.txt index 0230db54..0143a37f 100644 --- a/crates/compact-lint/tests/fixtures/missing-doc/expected.txt +++ b/crates/compact-lint/tests/fixtures/missing-doc/expected.txt @@ -36,6 +36,25 @@ Gaps.compact:8:3 lint/missing-doc FIXABLE ━━━━━━━━━━━━ 9 β”‚ + Β·Β·Β·*Β·@descriptionΒ·TODO 10 β”‚ + Β·Β·Β·*/ +Gaps.compact:17:3 lint/missing-constraints FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + Γ— Circuit `run` has no doc comment, so no @constraints. + + 15 β”‚ */ + 16 β”‚ // The comment that breaks the attachment. + > 17 β”‚ export circuit run(): [] { + β”‚ ^^^^^^^^^^^^^^^^^^ + 18 β”‚ _owner = default>; + 19 β”‚ } + + i Add a doc comment holding @constraints k=?, rows=?, or run compact-lint fix. + + i Unsafe fix: Insert @constraints k=?, rows=? + + 17 β”‚ + Β·Β·/** + 18 β”‚ + Β·Β·Β·*Β·@constraintsΒ·k=?,Β·rows=? + 19 β”‚ + Β·Β·Β·*/ + Gaps.compact:17:3 lint/missing-doc FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Γ— Circuit `run` has no doc comment. From 4822aed673e971212acdcfc474156a2592e74942 Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Wed, 18 Nov 2026 09:58:27 +0100 Subject: [PATCH 55/56] fix(compact-lint): keep a description whole on insert An inserted constraints line went below the first paragraph of `@description`, so the later paragraphs read as part of the annotation. It now goes below every paragraph of the block, but above one that opens with a label such as `Requirements:`, where compact-contracts keeps the annotation. --- crates/compact-lint/README.md | 2 +- crates/compact-lint/src/edit.rs | 87 +++++++++++++++---- crates/compact-lint/tests/fix.rs | 5 ++ .../after/Paragraphs.compact | 31 +++++++ .../before/Paragraphs.compact | 27 ++++++ .../fix-constraints-paragraphs/compact.toml | 13 +++ .../expected-dry-run.txt | 31 +++++++ .../fix-constraints-paragraphs/expected.txt | 18 ++++ 8 files changed, 194 insertions(+), 20 deletions(-) create mode 100644 crates/compact-lint/tests/fixtures/fix-constraints-paragraphs/after/Paragraphs.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-constraints-paragraphs/before/Paragraphs.compact create mode 100644 crates/compact-lint/tests/fixtures/fix-constraints-paragraphs/compact.toml create mode 100644 crates/compact-lint/tests/fixtures/fix-constraints-paragraphs/expected-dry-run.txt create mode 100644 crates/compact-lint/tests/fixtures/fix-constraints-paragraphs/expected.txt diff --git a/crates/compact-lint/README.md b/crates/compact-lint/README.md index b158cda5..70be5095 100644 --- a/crates/compact-lint/README.md +++ b/crates/compact-lint/README.md @@ -179,7 +179,7 @@ What each rule's fix does: | `missing-doc` | Inserts a doc skeleton above the declaration, indented to it. Body lines come from `kinds..tags` in config order; `@module` takes the declaration's name, a headed entry becomes a `@tag Heading:` line with `fix.placeholder` under it, every other tag takes `fix.placeholder`. Exported non-pure circuits also get the constraints line. A kind with neither gets a single placeholder line. | | `missing-tag` | Inserts each missing entry after the block of the last entry that precedes it in the template order, optional ones included, below every paragraph of that block, else at the top of the body. A headed entry goes in as a two-line section block; the predecessor's block is found by heading, not by bare tag. A missing bare `@description` adopts untagged prose that opens the body instead of writing a placeholder. Text on the `/**` or `*/` line moves onto its own body line first, so a `/** … */` one-liner expands to the multi-line form. | | `tag-order` | Splits the comment body into one block per tag, sorts the blocks matching a listed entry into config order, and writes them back into the same slots. Text on the `/**` or `*/` line moves onto its own body line first, so it travels with its block. Prose before the first tag, unlisted blocks and the blank lines separating slots stay put, so a second run reports nothing. | -| `missing-constraints` | Inserts ` k=?, rows=?` after the `@description` block, with a blank ` *` line before it and, where prose follows, one after. Without a `@description` it opens the body. On a circuit with no doc comment, it inserts a doc comment holding only that line, unless the `missing-doc` skeleton already carries it. Nothing is inserted when a `tags.rename` entry renames another tag in the comment to the constraints tag, and a circuit never gets the constraints tag twice, even when `kinds.circuit.tags` lists it. | +| `missing-constraints` | Inserts ` k=?, rows=?` below every paragraph of the `@description` block, but above a paragraph that opens with a label, a line ending in a colon such as `Requirements:`. A blank ` *` line goes before it and, where prose follows, one after. Without a `@description` it opens the body. On a circuit with no doc comment, it inserts a doc comment holding only that line, unless the `missing-doc` skeleton already carries it. Nothing is inserted when a `tags.rename` entry renames another tag in the comment to the constraints tag, and a circuit never gets the constraints tag twice, even when `kinds.circuit.tags` lists it. | | `forbidden-tag` | Renames the tag in place, and only where `tags.rename` maps it. | | `module-name` | Replaces the first word of the `@module` value with the module's name, keeping what follows. A `*/` on the same line stays in place. | diff --git a/crates/compact-lint/src/edit.rs b/crates/compact-lint/src/edit.rs index 2725a48d..b23cc700 100644 --- a/crates/compact-lint/src/edit.rs +++ b/crates/compact-lint/src/edit.rs @@ -457,7 +457,8 @@ fn reorder_blocks(lines: &mut Vec, entries: &[TagSpec]) { *lines = rebuilt; } -/// The constraints line follows the `@description` block, or opens the body without one. +/// The constraints line follows the `@description` block, above a labelled list such as +/// `Requirements:`, or opens the body without a `@description`. fn insert_constraints(lines: &mut Vec, margin: &str, gutter: &str, body: &str) { let closer = lines.len().saturating_sub(1); let blank = format!("{margin} *"); @@ -478,9 +479,24 @@ fn insert_constraints(lines: &mut Vec, margin: &str, gutter: &str, body: } } -/// The last line of the `@description` block: its tag line plus every continuation. +/// The last line of the `@description` block that the constraints line goes under: every +/// paragraph up to one opening with a label, a line that ends in a colon. fn description_end(lines: &[String], closer: usize) -> Option { - tag_block_end(lines, closer, &[TagSpec::bare(Tag::new(DESCRIPTION_TAG))]) + let start = last_occurrence(lines, closer, &[TagSpec::bare(Tag::new(DESCRIPTION_TAG))])?; + + let mut end = start; + let mut opens_paragraph = false; + for (index, line) in lines.iter().enumerate().take(closer).skip(start + 1) { + let text = content(line); + if starts_tag(text) || (opens_paragraph && text.ends_with(':')) { + break; + } + opens_paragraph = text.is_empty(); + if !opens_paragraph { + end = index; + } + } + Some(end) } /// The line holding the last occurrence of any entry in `entries`. @@ -503,22 +519,6 @@ fn paragraphs_end(lines: &[String], closer: usize, entries: &[TagSpec]) -> Optio .find(|index| !is_blank(&lines[*index])) } -/// The last line of the first paragraph of the block opened by the last occurrence of any -/// entry in `entries`. -fn tag_block_end(lines: &[String], closer: usize, entries: &[TagSpec]) -> Option { - let start = last_occurrence(lines, closer, entries)?; - - let mut end = start; - while end + 1 < closer { - let next = content(&lines[end + 1]); - if next.is_empty() || starts_tag(next) { - break; - } - end += 1; - } - Some(end) -} - /// A comment line without its indentation, its `*` and the space after it. fn content(line: &str) -> &str { let trimmed = line.trim_start(); @@ -895,6 +895,55 @@ mod tests { ); } + #[test] + fn constraints_follow_every_paragraph_of_the_description() { + let doc = + "/**\n * @description First paragraph.\n *\n * Second paragraph about privacy.\n */"; + + assert_eq!( + rendered( + doc, + 0, + &[DocOp::InsertConstraints( + "@constraints k=?, rows=?".to_owned() + )] + ), + "/**\n * @description First paragraph.\n *\n * Second paragraph about privacy.\n *\n * @constraints k=?, rows=?\n */" + ); + } + + #[test] + fn constraints_stay_above_a_labelled_list() { + let doc = "/**\n * @description First paragraph.\n *\n * Second paragraph.\n *\n * Requirements:\n *\n * - Caller is the owner.\n *\n * @param {T} a - A.\n */"; + + assert_eq!( + rendered( + doc, + 0, + &[DocOp::InsertConstraints( + "@constraints k=?, rows=?".to_owned() + )] + ), + "/**\n * @description First paragraph.\n *\n * Second paragraph.\n *\n * @constraints k=?, rows=?\n *\n * Requirements:\n *\n * - Caller is the owner.\n *\n * @param {T} a - A.\n */" + ); + } + + #[test] + fn a_colon_closing_a_line_inside_a_paragraph_is_not_a_label() { + let doc = "/**\n * @description Transfers ownership. Two cases:\n * the owner calls, or nobody does.\n */"; + + assert_eq!( + rendered( + doc, + 0, + &[DocOp::InsertConstraints( + "@constraints k=?, rows=?".to_owned() + )] + ), + "/**\n * @description Transfers ownership. Two cases:\n * the owner calls, or nobody does.\n *\n * @constraints k=?, rows=?\n */" + ); + } + #[test] fn constraints_need_no_trailing_blank_before_the_closer() { let doc = "/**\n * @description Bumps.\n */"; diff --git a/crates/compact-lint/tests/fix.rs b/crates/compact-lint/tests/fix.rs index bd6a228d..691fd275 100644 --- a/crates/compact-lint/tests/fix.rs +++ b/crates/compact-lint/tests/fix.rs @@ -173,6 +173,11 @@ fn the_constraints_annotation_follows_the_description_block() { assert_case("constraints"); } +#[test] +fn the_constraints_annotation_follows_every_paragraph_but_a_labelled_list() { + assert_case("constraints-paragraphs"); +} + #[test] fn a_circuit_ends_with_one_constraints_annotation() { assert_case("constraints-once"); diff --git a/crates/compact-lint/tests/fixtures/fix-constraints-paragraphs/after/Paragraphs.compact b/crates/compact-lint/tests/fixtures/fix-constraints-paragraphs/after/Paragraphs.compact new file mode 100644 index 00000000..41f5693d --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-constraints-paragraphs/after/Paragraphs.compact @@ -0,0 +1,31 @@ +/** + * @module Paragraphs + * @description A module whose circuit descriptions run over several paragraphs. + */ +export module Paragraphs { + /** + * @description Deposits a coin. + * + * The amount stays public. + * + * @constraints k=?, rows=? + */ + export circuit deposit(): [] { } + + /** + * @description Transfers ownership to `newOwner`. + * + * The previous owner keeps no rights. + * + * @constraints k=?, rows=? + * + * Requirements: + * + * - The caller is the owner. + * - `newOwner` is not the zero address. + * + * @param {Bytes<32>} newOwner - The new owner. + * @returns {[]} Empty tuple. + */ + export circuit transfer(newOwner: Bytes<32>): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/fix-constraints-paragraphs/before/Paragraphs.compact b/crates/compact-lint/tests/fixtures/fix-constraints-paragraphs/before/Paragraphs.compact new file mode 100644 index 00000000..35834bf4 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-constraints-paragraphs/before/Paragraphs.compact @@ -0,0 +1,27 @@ +/** + * @module Paragraphs + * @description A module whose circuit descriptions run over several paragraphs. + */ +export module Paragraphs { + /** + * @description Deposits a coin. + * + * The amount stays public. + */ + export circuit deposit(): [] { } + + /** + * @description Transfers ownership to `newOwner`. + * + * The previous owner keeps no rights. + * + * Requirements: + * + * - The caller is the owner. + * - `newOwner` is not the zero address. + * + * @param {Bytes<32>} newOwner - The new owner. + * @returns {[]} Empty tuple. + */ + export circuit transfer(newOwner: Bytes<32>): [] { } +} diff --git a/crates/compact-lint/tests/fixtures/fix-constraints-paragraphs/compact.toml b/crates/compact-lint/tests/fixtures/fix-constraints-paragraphs/compact.toml new file mode 100644 index 00000000..0a6450ac --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-constraints-paragraphs/compact.toml @@ -0,0 +1,13 @@ +[lint] +include = ["**/*.compact"] + +[lint.constraints] +tag = "@constraints" + +[lint.kinds.module] +tags = ["@module", "@description"] + +[lint.kinds.circuit] + +[lint.kinds.constructor] +docs = "none" diff --git a/crates/compact-lint/tests/fixtures/fix-constraints-paragraphs/expected-dry-run.txt b/crates/compact-lint/tests/fixtures/fix-constraints-paragraphs/expected-dry-run.txt new file mode 100644 index 00000000..4983b1f2 --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-constraints-paragraphs/expected-dry-run.txt @@ -0,0 +1,31 @@ +Paragraphs.compact:11:3 lint/missing-constraints FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `deposit` doc comment has no @constraints. + + 9 β”‚ * The amount stays public. + 10 β”‚ */ + > 11 β”‚ export circuit deposit(): [] { } + β”‚ ^^^^^^^^^^^^^^^^^^^^^^ + 12 β”‚ + 13 β”‚ /** + + i Unsafe fix: Insert @constraints k=?, rows=? + + 10 β”‚ + Β·Β·Β·* + 11 β”‚ + Β·Β·Β·*Β·@constraintsΒ·k=?,Β·rows=? + +Paragraphs.compact:26:3 lint/missing-constraints FIXABLE ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `transfer` doc comment has no @constraints. + + 24 β”‚ * @returns {[]} Empty tuple. + 25 β”‚ */ + > 26 β”‚ export circuit transfer(newOwner: Bytes<32>): [] { } + β”‚ ^^^^^^^^^^^^^^^^^^^^^^^ + 27 β”‚ } + + i Unsafe fix: Insert @constraints k=?, rows=? + + 18 β”‚ + Β·Β·Β·*Β·@constraintsΒ·k=?,Β·rows=? + 19 β”‚ + Β·Β·Β·* + diff --git a/crates/compact-lint/tests/fixtures/fix-constraints-paragraphs/expected.txt b/crates/compact-lint/tests/fixtures/fix-constraints-paragraphs/expected.txt new file mode 100644 index 00000000..035cffdb --- /dev/null +++ b/crates/compact-lint/tests/fixtures/fix-constraints-paragraphs/expected.txt @@ -0,0 +1,18 @@ +Paragraphs.compact:11:3 lint/missing-constraints FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `deposit` doc comment has no @constraints. + + i Applied fix: Insert @constraints k=?, rows=? + + 10 β”‚ + Β·Β·Β·* + 11 β”‚ + Β·Β·Β·*Β·@constraintsΒ·k=?,Β·rows=? + +Paragraphs.compact:26:3 lint/missing-constraints FIXED ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + + i Circuit `transfer` doc comment has no @constraints. + + i Applied fix: Insert @constraints k=?, rows=? + + 18 β”‚ + Β·Β·Β·*Β·@constraintsΒ·k=?,Β·rows=? + 19 β”‚ + Β·Β·Β·* + From 5f366533f98f132460f5738416d978997b711d63 Mon Sep 17 00:00:00 2001 From: 0xisk <0xisk@proton.me> Date: Wed, 18 Nov 2026 10:14:37 +0100 Subject: [PATCH 56/56] docs(compact-linter): roll the changelog to 0.1.0 The first publish takes its GitHub release notes from the `## 0.1.0` section, which so far listed only the launcher. It now names the three commands and the config and output added since, and links the crate by URL, since a relative link does not resolve in the release notes. --- packages/linter/CHANGELOG.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/packages/linter/CHANGELOG.md b/packages/linter/CHANGELOG.md index 5d886386..70ac179f 100644 --- a/packages/linter/CHANGELOG.md +++ b/packages/linter/CHANGELOG.md @@ -8,6 +8,14 @@ and this package adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## Unreleased +## 0.1.0 (2026-11-18) + ### Added -- `compact-linter` bin, a launcher that downloads the [`compact-lint`](../../crates/compact-lint) release binary for the host, verifies its SHA-256, and runs it +- `compact-linter` bin, a launcher that downloads the [`compact-lint`](https://github.com/OpenZeppelin/compact-tools/tree/main/crates/compact-lint) release binary for the host, verifies its SHA-256, and runs it (#186) +- `check` reports doc-comment issues in Compact sources: a missing doc comment, a missing or forbidden tag, a `@module` name that differs from the module, and a missing or malformed `@constraints` annotation on an exported non-pure circuit (#182) +- `fix` writes the repairs `check` marks fixable: doc skeletons, missing tags and sections, tag renames, block order and `@constraints k=?, rows=?` placeholders. `--dry-run` previews them (#184) +- `fill-constraints` compiles each contract and writes every circuit's measured `k` and `rows` into its `@constraints` annotation and into `//circuit-info.json`, the file `compact-builder` writes (#185, #189) +- Config in the `[lint]` table of `compact.toml`, with a level per rule (`error`, `warn`, `info`, `off`) under `[lint.rules]` (#189) +- Section entries such as `@notice Privacy` in `kinds..tags` and `sections`, with the `unknown-section` and `tag-order` rules (#189) +- `--reporter concise|github`, `--diagnostic-level`, `--error-on-warnings`, `--max-diagnostics`, `--colors` and `--timings` on every command (#189)