diff --git a/Cargo.lock b/Cargo.lock index d8c5954..80f686b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -287,6 +287,7 @@ dependencies = [ "codeint-git", "codeint-lang-dart", "codeint-lang-php", + "codeint-lang-python", "codeint-lang-rust", "codeint-lang-ts", "codeint-model", @@ -343,6 +344,15 @@ dependencies = [ "serde_json", ] +[[package]] +name = "codeint-lang-python" +version = "0.4.0" +dependencies = [ + "codeint-model", + "globset", + "toml", +] + [[package]] name = "codeint-lang-rust" version = "0.4.0" @@ -394,6 +404,7 @@ dependencies = [ "codeint-config", "codeint-lang-dart", "codeint-lang-php", + "codeint-lang-python", "codeint-lang-rust", "codeint-lang-ts", "codeint-model", diff --git a/Cargo.toml b/Cargo.toml index c15a4a5..ffafda2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,6 +14,7 @@ codeint-config = { path = "crates/config" } codeint-git = { path = "crates/git" } codeint-lang-dart = { path = "plugins/languages/dart" } codeint-lang-php = { path = "plugins/languages/php" } +codeint-lang-python = { path = "plugins/languages/python" } codeint-lang-rust = { path = "plugins/languages/rust" } codeint-lang-ts = { path = "plugins/languages/ts" } codeint-metrics = { path = "crates/metrics" } diff --git a/README.md b/README.md index 6742041..cdafa53 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ Each pull request can pass tests and linters while quietly adding copied blocks, Over dozens of changes, that structural drag compounds until both humans and agents slow down. codeint measures **Software entropy** directly from the shape of source code so you see it grow before it compounds. -It ships with built-in Language plugins for TypeScript/JavaScript, Rust, PHP, and Dart, plus sandboxed WebAssembly Plugins for other languages and custom Metrics. +It ships with built-in Language plugins for TypeScript/JavaScript, Rust, PHP, Dart, and Python, plus sandboxed WebAssembly Plugins for other languages and custom Metrics. ## How it works @@ -58,7 +58,7 @@ Read [docs/guide/philosophy-and-architecture.md](./docs/guide/philosophy-and-arc ## Calibrated Reference ranges -10th to 90th percentile across 20 pre-2023 open-source repositories per language ([ADR 0008](./docs/adr/0008-typescript-reference-ranges.md), [ADR 0010](./docs/adr/0010-rust-reference-ranges.md), [ADR 0011](./docs/adr/0011-php-reference-ranges.md), [ADR 0012](./docs/adr/0012-dart-reference-ranges.md)): +10th to 90th percentile across 20 pre-2023 open-source repositories per language ([ADR 0008](./docs/adr/0008-typescript-reference-ranges.md), [ADR 0010](./docs/adr/0010-rust-reference-ranges.md), [ADR 0011](./docs/adr/0011-php-reference-ranges.md), [ADR 0012](./docs/adr/0012-dart-reference-ranges.md), [ADR 0013](./docs/adr/0013-python-reference-ranges.md)): | Language | Erosion | Duplication | Verbosity | Import cycles | | -------- | ------- | ----------- | --------- | ------------- | @@ -66,6 +66,7 @@ Read [docs/guide/philosophy-and-architecture.md](./docs/guide/philosophy-and-arc | Rust | 38.0% to 64.2% | 5.0% to 32.5% | 6.0% to 32.9% | 2.1% to 50.6% | | PHP | 5.5% to 67.7% | 4.1% to 29.0% | 4.2% to 29.2% | 0.0% to 10.7% | | Dart | 4.7% to 41.9% | 7.3% to 25.6% | 8.0% to 25.9% | 7.3% to 52.4% | +| Python | 14.4% to 62.4% | 1.2% to 20.1% | 1.4% to 20.4% | 0.0% to 32.1% | See [docs/guide/languages.md](./docs/guide/languages.md) for per-language rules and sample repository timings. diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index 95addd8..2ed143e 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -14,6 +14,7 @@ codeint-config = { workspace = true } codeint-git = { workspace = true } codeint-lang-dart = { workspace = true } codeint-lang-php = { workspace = true } +codeint-lang-python = { workspace = true } codeint-lang-rust = { workspace = true } codeint-lang-ts = { workspace = true } codeint-model = { workspace = true } diff --git a/crates/cli/src/check.rs b/crates/cli/src/check.rs index b3d9ef3..727bdf7 100644 --- a/crates/cli/src/check.rs +++ b/crates/cli/src/check.rs @@ -9,6 +9,7 @@ use codeint_config::{ use codeint_git::{GitError, Repository, Snapshot}; use codeint_lang_dart::Dart; use codeint_lang_php::Php; +use codeint_lang_python::Python; use codeint_lang_rust::Rust; use codeint_lang_ts::TypeScriptAndJavaScript; use codeint_model::{ @@ -72,7 +73,7 @@ pub(crate) struct NamedLanguagePlugin<'plugin> { pub(crate) plugin: &'plugin dyn LanguagePlugin, } -pub(crate) const BUILT_IN_LANGUAGE_PLUGINS: [NamedLanguagePlugin<'static>; 4] = [ +pub(crate) const BUILT_IN_LANGUAGE_PLUGINS: [NamedLanguagePlugin<'static>; 5] = [ NamedLanguagePlugin { name: "typescript-javascript", plugin: &TypeScriptAndJavaScript, @@ -89,6 +90,10 @@ pub(crate) const BUILT_IN_LANGUAGE_PLUGINS: [NamedLanguagePlugin<'static>; 4] = name: "dart", plugin: &Dart, }, + NamedLanguagePlugin { + name: "python", + plugin: &Python, + }, ]; pub(crate) struct LoadedPlugins { diff --git a/crates/cli/tests/check.rs b/crates/cli/tests/check.rs index 016afae..91c8522 100644 --- a/crates/cli/tests/check.rs +++ b/crates/cli/tests/check.rs @@ -386,7 +386,7 @@ fn every_typescript_and_javascript_extension_is_measured_and_other_files_are_not } repository.write("README.md", "# Fixture\n"); repository.write("src/data.json", "{\"one\": 1}\n"); - repository.write("scripts/tool.py", "print('codeint')\n"); + repository.write("scripts/tool.cob", "DISPLAY 'codeint'.\n"); repository.commit_all(); let output = repository.codeint(&["check"]); @@ -2872,10 +2872,10 @@ fn a_languages_entry_that_names_an_unknown_language_plugin_names_it_and_exits_2( assert_codeint_json_is_rejected( r#"{ "languages": [ { "plugin": "typescript-javascript", "include": ["web"] }, - { "plugin": "python", "include": ["scripts"] } + { "plugin": "cobol", "include": ["scripts"] } ] }"#, - "codeint.json names an unknown Language plugin python at languages[1].plugin; \ - the Language plugins are typescript-javascript, rust, php, dart", + "codeint.json names an unknown Language plugin cobol at languages[1].plugin; \ + the Language plugins are typescript-javascript, rust, php, dart, python", "Name one of the Language plugins listed, or remove the entry from languages.", ); } diff --git a/crates/plugin-host/Cargo.toml b/crates/plugin-host/Cargo.toml index 2026c98..6f8488a 100644 --- a/crates/plugin-host/Cargo.toml +++ b/crates/plugin-host/Cargo.toml @@ -14,6 +14,7 @@ wasmtime = { workspace = true } [dev-dependencies] codeint-lang-dart = { workspace = true } codeint-lang-php = { workspace = true } +codeint-lang-python = { workspace = true } codeint-lang-rust = { workspace = true } codeint-lang-ts = { workspace = true } diff --git a/crates/plugin-host/tests/conformance.rs b/crates/plugin-host/tests/conformance.rs index 3d158b6..2c0b11e 100644 --- a/crates/plugin-host/tests/conformance.rs +++ b/crates/plugin-host/tests/conformance.rs @@ -5,6 +5,7 @@ use std::path::Path; use codeint_config::PluginHostConfig; use codeint_lang_dart::Dart; use codeint_lang_php::Php; +use codeint_lang_python::Python; use codeint_lang_rust::Rust; use codeint_lang_ts::TypeScriptAndJavaScript; use codeint_model::language::{ImportRequest, Resolution}; @@ -512,3 +513,45 @@ fn built_in_dart_plugin_passes_seam_2_conformance() { }, ); } + +#[test] +fn built_in_python_plugin_passes_seam_2_conformance() { + let prod = "from app.helper import value\n\n# comment\ndef run(flag):\n if flag:\n return value()\n else:\n return 0\n"; + let prod_crlf = prod.replace('\n', "\r\n"); + let fixture = ConformanceFixture { + expected_resolved_target: "packages/app/src/app/helper.py", + import_requests: &[ + ("packages/app/src/app/main.py", "app.helper"), + ("packages/app/src/app/main.py", "os"), + ("packages/app/src/app/main.py", ".missing"), + ], + invalid_manifest_text: "[tool.uv.workspace\n", + expected_workspace_package: "packages/app", + valid_manifests: &[ + ( + "pyproject.toml", + "[tool.uv.workspace]\nmembers = [\"packages/*\"]\n", + ), + ("packages/app/pyproject.toml", "[project]\nname = \"app\"\n"), + ], + expected_manifest_path: "pyproject.toml", + repository_paths: &[ + "pyproject.toml", + "packages/app/pyproject.toml", + "packages/app/src/app/main.py", + "packages/app/src/app/helper.py", + ], + unsupported_path: "scripts/tool.unknown", + unparsable_source: "def broken():\n s = 'unclosed\n", + unparsable_path: "packages/app/src/app/broken.py", + declaration_only: None, + empty_path: "packages/app/src/app/empty.py", + test_source: "def check():\n return 1\n", + test_path: "packages/app/tests/test_main.py", + production_source_crlf: &prod_crlf, + production_source: prod, + production_path: "packages/app/src/app/main.py", + name: "python", + }; + assert_seam_2_conformance(&Python, &fixture); +} diff --git a/docs/adr/0013-python-reference-ranges.md b/docs/adr/0013-python-reference-ranges.md new file mode 100644 index 0000000..94c4dfc --- /dev/null +++ b/docs/adr/0013-python-reference-ranges.md @@ -0,0 +1,118 @@ +--- +status: accepted +--- + +# Python Reference ranges come from a panel of 20 public repositories + +The Owner approved running the calibrated Python panel on 2026-11-22 using the pre-2023 human-written selection rule established in [ADR 0008](./0008-typescript-reference-ranges.md). + +## Context + +A Reference range must describe human-written code, or it cannot show how far agent-written code drifts from it. +This record applies the same selection rule and measurement method as ADR 0008 to 20 public Python repositories. + +### Selection rule and run + +- Query on 2026-11-22: `language:Python created:<2022-01-01 fork:false archived:false`, sorted by stars descending. +- Take the first 20 repositories passing the ADR 0008 exclusions (no forks/archived/lists/tutorials/books/collections, >= 5,000 Production source lines, Generated + Vendored <= Production, and `codeint check` exits 0). +- Pin each repository at the last commit on its default branch dated before `2023-01-01`. +- Measured with `codeint 0.4.0` release build (default clone size 75 tokens, filter 14 distinct normalized tokens) on Apple Silicon. +- Run time across the 20 repositories: 0.010s to 0.851s per repository (4.40s total, 0 unparsable Python files). + +### Exclusions + +- `public-apis/public-apis`: topic/description (list of). +- `EbookFoundation/free-programming-books`: topic/description (book). +- `donnemartin/system-design-primer`: topic/description (interview). +- `vinta/awesome-python`: topic/description (awesome). +- `practical-tutorials/project-based-learning`: topic/description (list of). +- `TheAlgorithms/Python`: topic/description (interview). +- `521xueweihan/HelloGitHub`: topic/description (awesome). +- `sherlock-project/sherlock`: 1140 Production lines (< 5,000). +- `bregman-arie/devops-exercises`: topic/description (interview). +- `fighting41love/funNLP`: topic/description (awesome). +- `swisskyrepo/PayloadsAllTheThings`: topic/description (list of). +- `d2l-ai/d2l-zh`: topic/description (book). +- `Z4nzu/hackingtool`: 1967 Production lines (< 5,000). +- `Asabeneh/30-Days-Of-Python`: topic/description (100 days). +- `josephmisiti/awesome-machine-learning`: topic/description (awesome). +- `labmlai/annotated_deep_learning_paper_implementations`: topic/description (tutorial). + +### Panel + +| Repository | Stars band | Pinned commit | Production lines | +| ---------- | ---------- | ------------- | ---------------- | +| `yt-dlp/yt-dlp` | over 100k | `2fb0f858686c46abc50a0e253245afe750746775` | 173,655 | +| `huggingface/transformers` | over 100k | `375801d5e65457d2ef86e6b269703c5f9ad67252` | 580,324 | +| `ytdl-org/youtube-dl` | over 100k | `195f22f679330549882a8234e7234942893a4902` | 131,379 | +| `pytorch/pytorch` | over 100k | `39d49dbe4546c9f4d153ec748f62371e4546158a` | 471,422 | +| `fastapi/fastapi` | over 100k | `efc12c5cdbede6922a033a5234c70cb22c4d204a` | 12,611 | +| `nvbn/thefuck` | 50k to 100k | `ceeaeab94b5df5a4fe9d94d61e4f6b0bbea96378` | 5,049 | +| `3b1b/manim` | 50k to 100k | `a31c4ae3c23f060a34f3a4f5062c1d67fc4c268a` | 17,579 | +| `PaddlePaddle/PaddleOCR` | 50k to 100k | `4f735dbde167684cce5dcd14c035e9f67b4d187d` | 66,093 | +| `home-assistant/core` | 50k to 100k | `6d4489e82207916a811e936be00246c5cbc10545` | 671,942 | +| `django/django` | 50k to 100k | `c179ad9fe7e82dcb80261aa016f2fe18c8fcc181` | 116,838 | +| `python/cpython` | 50k to 100k | `baf234971f20e5e6c7438f46889e9c8f172cc25e` | 291,724 | +| `tensorflow/models` | 50k to 100k | `755617b99ca8b647367d806cad30d463693da02b` | 319,102 | +| `openbq-org/OpenBB` | 50k to 100k | `21247ac302dfa98e187ec70b832b76eb46e9c9e8` | 148,307 | +| `apache/superset` | 50k to 100k | `734d423ca094746ee1c2f2c1e72138ed9e69cdee` | 83,725 | +| `pallets/flask` | 50k to 100k | `74e5263c88e51bb442879ab863a5d03292fc0a33` | 7,935 | +| `ansible/ansible` | 50k to 100k | `45df14a2e05573e6213ce789aa3278f4f30fa54f` | 93,017 | +| `scikit-learn/scikit-learn` | 50k to 100k | `96a0bc861ad2ba3c63db0326b42b41ddabeb2aff` | 189,155 | +| `scrapy/scrapy` | 50k to 100k | `deaf1fb6cf513db8119acfe70fd3e08f761f7ede` | 16,683 | +| `keras-team/keras` | 50k to 100k | `ed99e34f279a2d2d6a44af87ee64f8fc98c7e8b9` | 131,710 | +| `commaai/openpilot` | 50k to 100k | `6c8aca245ae78433a4f8e4acf3b1e5270fcb8768` | 34,524 | + +## Measurements + +### Per Metric, over the 20 repositories + +| Metric | Mean | Median | Standard deviation | 10th percentile | 90th percentile | Lowest | Highest | +| ------ | ---- | ------ | ------------------ | --------------- | --------------- | ------ | ------- | +| Erosion | 0.396 | 0.406 | 0.182 | 0.144 | 0.624 | 0.012 | 0.681 | +| Verbosity | 0.084 | 0.043 | 0.094 | 0.014 | 0.204 | 0.007 | 0.406 | +| Duplication | 0.078 | 0.035 | 0.095 | 0.012 | 0.201 | 0.002 | 0.403 | +| Import cycles | 0.106 | 0.032 | 0.130 | 0.000 | 0.321 | 0.000 | 0.456 | + +### Per repository, in the Production Source set + +| Repository | Erosion | Verbosity | Duplication | Import cycles | +| ---------- | ------- | --------- | ----------- | ------------- | +| `yt-dlp/yt-dlp` | 0.590 | 0.031 | 0.028 | 0.006 | +| `huggingface/transformers` | 0.621 | 0.406 | 0.403 | 0.011 | +| `ytdl-org/youtube-dl` | 0.649 | 0.034 | 0.031 | 0.011 | +| `pytorch/pytorch` | 0.395 | 0.059 | 0.048 | 0.332 | +| `fastapi/fastapi` | 0.382 | 0.207 | 0.201 | 0.021 | +| `nvbn/thefuck` | 0.012 | 0.038 | 0.015 | 0.047 | +| `3b1b/manim` | 0.151 | 0.007 | 0.002 | 0.108 | +| `PaddlePaddle/PaddleOCR` | 0.359 | 0.140 | 0.134 | 0.016 | +| `home-assistant/core` | 0.234 | 0.083 | 0.082 | 0.026 | +| `django/django` | 0.423 | 0.029 | 0.018 | 0.186 | +| `python/cpython` | 0.450 | 0.048 | 0.040 | 0.031 | +| `tensorflow/models` | 0.315 | 0.120 | 0.116 | 0.034 | +| `openbq-org/OpenBB` | 0.317 | 0.204 | 0.204 | 0.000 | +| `apache/superset` | 0.417 | 0.085 | 0.084 | 0.320 | +| `pallets/flask` | 0.251 | 0.023 | 0.020 | 0.188 | +| `ansible/ansible` | 0.681 | 0.031 | 0.023 | 0.000 | +| `scikit-learn/scikit-learn` | 0.502 | 0.025 | 0.019 | 0.199 | +| `scrapy/scrapy` | 0.089 | 0.009 | 0.008 | 0.136 | +| `keras-team/keras` | 0.478 | 0.086 | 0.076 | 0.456 | +| `commaai/openpilot` | 0.597 | 0.015 | 0.012 | 0.000 | + +## Decision + +**The Python Language plugin shows, for each Metric, the 10th to 90th percentile of this panel as its Reference range.** +The source label reads `codeint panel of 20 Python repositories, ADR 0013, codeint 0.4.0`. + +| Metric | Reference range | +| ------ | --------------- | +| Erosion | 0.144 to 0.624 | +| Verbosity | 0.014 to 0.204 | +| Duplication | 0.012 to 0.201 | +| Import cycles | 0.000 to 0.321 | + +## Consequences + +- Python reports show a Reference range next to each Metric with the source label above. +- No code, fixture, or text of a panel repository enters codeint; this record holds only names, commits, and numbers. +- Any future change to default Metric rules or Source set rules requires re-measuring the panel and amending this record. diff --git a/docs/guide/README.md b/docs/guide/README.md index b9dda1b..1bb6423 100644 --- a/docs/guide/README.md +++ b/docs/guide/README.md @@ -8,7 +8,7 @@ Each page below focuses on one topic and links to [docs/reference.md](../referen 1. [Philosophy and Architecture](./philosophy-and-architecture.md): why codeint measures Software entropy, how the four Metrics work, and how the codebase is structured. 2. [Getting Started](./getting-started.md): install codeint, initialize `codeint.json`, and run your first `check`, `diff`, and `trend`. 3. [Configuration (`codeint.json`)](./configuration.md): set Budgets, Regression limits, Source-set globs, and multi-language folders. -4. [Built-in Languages](./languages.md): how TypeScript/JavaScript, Rust, PHP, and Dart are measured, plus their calibrated Reference ranges. +4. [Built-in Languages](./languages.md): how TypeScript/JavaScript, Rust, PHP, Dart, and Python are measured, plus their calibrated Reference ranges. 5. [CI and GitHub Actions](./ci-and-github-actions.md): gate pull requests with `codeint diff` and upload SARIF findings to GitHub code scanning. 6. [Programmatic API](../programmatic.md): call codeint from JavaScript, TypeScript, or Rust. 7. [Plugins](../plugins.md): build, hash, declare, and test external WebAssembly Language and Metric plugins. diff --git a/docs/guide/configuration.md b/docs/guide/configuration.md index 3015998..9ed8fb0 100644 --- a/docs/guide/configuration.md +++ b/docs/guide/configuration.md @@ -32,7 +32,8 @@ When you upgrade via `codeint update`, codeint updates that `$schema` tag automa { "plugin": "typescript-javascript", "include": ["web"], "exclude": ["web/dist"] }, { "plugin": "rust", "include": ["crates"], "exclude": [] }, { "plugin": "php", "include": ["app", "src"], "exclude": [] }, - { "plugin": "dart", "include": ["lib"], "exclude": [] } + { "plugin": "dart", "include": ["lib"], "exclude": [] }, + { "plugin": "python", "include": ["services"], "exclude": [] } ] } ``` diff --git a/docs/guide/languages.md b/docs/guide/languages.md index 55659c1..160edf9 100644 --- a/docs/guide/languages.md +++ b/docs/guide/languages.md @@ -1,6 +1,6 @@ # Built-in Languages -codeint ships four built-in Language plugins in pure, safe Rust (`#![forbid(unsafe_code)]`). +codeint ships five built-in Language plugins in pure, safe Rust (`#![forbid(unsafe_code)]`). Each plugin parses the modern superset of its language family with no language-version pin needed in `codeint.json`. ## Summary @@ -11,6 +11,7 @@ Each plugin parses the modern superset of its language family with no language-v | `rust` | `.rs` | `Cargo.toml` | `tests/`, `benches/`, `examples/`, `tests.rs`, `*_test.rs`, `*_tests.rs`; inline `#[cfg(test)]` excluded from Production | | `php` | `.php` | `composer.json` (`repositories` of type `path`) | `tests/`, `test/`, `*Test.php`, `*.test.php` | | `dart` | `.dart` | `pubspec.yaml` (`workspace`) | `test/`, `tests/`, `integration_test/`, `*_test.dart`; `*.g.dart`, `*.freezed.dart`, `*.gr.dart`, `*.mocks.dart`, `*.pb*.dart` -> Generated | +| `python` | `.py` | `pyproject.toml` (`[tool.uv.workspace].members`) | `test/`, `tests/`, `test_*.py`, `*_test.py`, `conftest.py`; `*_pb2.py`, `*_pb2_grpc.py` -> Generated; `if TYPE_CHECKING:` imports excluded from Import cycles | Core rules also classify files under `vendor/` or `third_party/` as `vendored` and files with generated-file header comments (`@generated`, `GENERATED CODE`, `DO NOT EDIT`) as `generated`. @@ -24,6 +25,7 @@ Measured across 20 pre-2023 public repositories per language (10th to 90th perce | Rust | 38.0% to 64.2% | 5.0% to 32.5% | 6.0% to 32.9% | 2.1% to 50.6% | [ADR 0010](../adr/0010-rust-reference-ranges.md) | | PHP | 5.5% to 67.7% | 4.1% to 29.0% | 4.2% to 29.2% | 0.0% to 10.7% | [ADR 0011](../adr/0011-php-reference-ranges.md) | | Dart | 4.7% to 41.9% | 7.3% to 25.6% | 8.0% to 25.9% | 7.3% to 52.4% | [ADR 0012](../adr/0012-dart-reference-ranges.md) | +| Python | 14.4% to 62.4% | 1.2% to 20.1% | 1.4% to 20.4% | 0.0% to 32.1% | [ADR 0013](../adr/0013-python-reference-ranges.md) | To add another language as an external WebAssembly plugin, see [docs/plugins.md](../plugins.md). @@ -41,3 +43,5 @@ Sample Production measurements from `codeint check` (release build, Apple Silico | PHP | `laravel/framework` | 3,208 | 132,791 | 16.9% | 8.1% | 8.2% | 4.4% | 0.47s | | Dart | `dart-lang/pub` | 547 | 26,170 | 44.4% | 0.5% | 1.7% | 78.6% | 0.88s | | Dart | `flutter/packages` | 4,137 | 434,407 | 45.9% | 23.1% | 23.3% | 18.5% | 3.68s | +| Python | `django/django` | 865 | 116,838 | 42.3% | 1.8% | 2.9% | 18.6% | 0.33s | +| Python | `home-assistant/core` | 5,592 | 671,942 | 23.4% | 8.2% | 8.3% | 2.6% | 0.73s | diff --git a/docs/guide/philosophy-and-architecture.md b/docs/guide/philosophy-and-architecture.md index d48ff3c..2316c31 100644 --- a/docs/guide/philosophy-and-architecture.md +++ b/docs/guide/philosophy-and-architecture.md @@ -33,7 +33,7 @@ Test fixtures, generated code (`*.g.dart`, `*.pb.dart`, `@generated`), and third ### 3. Pre-2023 human-written Reference ranges Raw ratios are hard to interpret without context. -For each built-in language, codeint measures a panel of 20 public repositories pinned before `2023-01-01` (predating widespread coding-agent adoption) and publishes the 10th to 90th percentile as its **Reference range** ([ADR 0008](../adr/0008-typescript-reference-ranges.md), [ADR 0010](../adr/0010-rust-reference-ranges.md), [ADR 0011](../adr/0011-php-reference-ranges.md), [ADR 0012](../adr/0012-dart-reference-ranges.md)). +For each built-in language, codeint measures a panel of 20 public repositories pinned before `2023-01-01` (predating widespread coding-agent adoption) and publishes the 10th to 90th percentile as its **Reference range** ([ADR 0008](../adr/0008-typescript-reference-ranges.md), [ADR 0010](../adr/0010-rust-reference-ranges.md), [ADR 0011](../adr/0011-php-reference-ranges.md), [ADR 0012](../adr/0012-dart-reference-ranges.md), [ADR 0013](../adr/0013-python-reference-ranges.md)). ### 4. Budgets and Regressions @@ -65,6 +65,6 @@ CLI + Rust SDK (crates/cli) & JS/TS SDK (npm/codeint) - **Git-native measurement (`crates/git`)**: reads tracked working-tree files and historical commits directly from Git objects via `gix`, never modifying the working tree during `diff` or `trend`, with a content-addressed result cache for fast repeated runs. - **Language plugins (`plugins/languages/*`)**: own every language-specific rule (parsing, functions, decision points, tokens, Flagged lines, imports, workspaces, Source-set defaults) and lower files into the language-neutral **Code model** (`crates/model`). - TypeScript/JavaScript uses `oxc_parser`; Rust uses `syn` and `proc-macro2`; PHP and Dart use pure-Rust zero-FFI lexers sharing common helpers in `crates/model/src/scan.rs`. + TypeScript/JavaScript uses `oxc_parser`; Rust uses `syn` and `proc-macro2`; PHP, Dart, and Python use pure-Rust zero-FFI lexers sharing common helpers in `crates/model/src/scan.rs`. - **WebAssembly plugin host (`crates/plugin-host`)**: loads third-party Language and Metric plugins as WebAssembly components ([ADR 0002](../adr/0002-plugins-as-wasm-components.md)) with mandatory SHA-256 verification, zero host capabilities (no filesystem, network, env, or clock access), and configurable memory/timeout caps. - **Zero-duplication programmatic surfaces**: `crates/cli/src/lib.rs` exposes the Rust library API directly, and `npm/codeint` wraps the bundled native binary with zero-dependency ESM, CommonJS, and TypeScript declarations. diff --git a/docs/reference.md b/docs/reference.md index 45a1d53..343bbcc 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -687,7 +687,8 @@ In a multi-language repository, list each built-in Language plugin with its own { "plugin": "typescript-javascript", "include": ["web"], "exclude": ["web/dist"] }, { "plugin": "rust", "include": ["crates"], "exclude": [] }, { "plugin": "php", "include": ["app", "src"], "exclude": [] }, - { "plugin": "dart", "include": ["lib"], "exclude": [] } + { "plugin": "dart", "include": ["lib"], "exclude": [] }, + { "plugin": "python", "include": ["services"], "exclude": [] } ] } ``` diff --git a/llms.txt b/llms.txt index 16822f5..c6dd8bd 100644 --- a/llms.txt +++ b/llms.txt @@ -1,6 +1,6 @@ # codeint -> codeint is a command-line tool and programmatic SDK (JavaScript/TypeScript and Rust) that measures Software entropy (Erosion, Duplication, Verbosity, and Import cycles) across TypeScript/JavaScript, Rust, PHP, Dart, and external WebAssembly Language and Metric plugins. +> codeint is a command-line tool and programmatic SDK (JavaScript/TypeScript and Rust) that measures Software entropy (Erosion, Duplication, Verbosity, and Import cycles) across TypeScript/JavaScript, Rust, PHP, Dart, Python, and external WebAssembly Language and Metric plugins. ## Guide @@ -8,7 +8,7 @@ - [Philosophy and Architecture](docs/guide/philosophy-and-architecture.md): why Software entropy matters, how the four Metrics work, and how the codebase is structured. - [Getting Started](docs/guide/getting-started.md): install codeint, initialize `codeint.json`, and run `check`, `diff`, `trend`, and `update`. - [Configuration](docs/guide/configuration.md): configure `codeint.json` Budgets, Regression limits, Source sets, and multi-language folders. -- [Built-in Languages](docs/guide/languages.md): TypeScript/JavaScript, Rust, PHP, and Dart rules and calibrated Reference ranges. +- [Built-in Languages](docs/guide/languages.md): TypeScript/JavaScript, Rust, PHP, Dart, and Python rules and calibrated Reference ranges. - [CI and GitHub Actions](docs/guide/ci-and-github-actions.md): pull-request diff gating and SARIF code scanning setup. ## Reference and APIs @@ -30,3 +30,4 @@ - [ADR 0010: Rust Reference ranges](docs/adr/0010-rust-reference-ranges.md) - [ADR 0011: PHP Reference ranges](docs/adr/0011-php-reference-ranges.md) - [ADR 0012: Dart Reference ranges](docs/adr/0012-dart-reference-ranges.md) +- [ADR 0013: Python Reference ranges](docs/adr/0013-python-reference-ranges.md) diff --git a/plugins/languages/python/Cargo.toml b/plugins/languages/python/Cargo.toml new file mode 100644 index 0000000..159bc41 --- /dev/null +++ b/plugins/languages/python/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "codeint-lang-python" +version.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true + +[lints] +workspace = true + +[dependencies] +codeint-model = { workspace = true } +globset = { workspace = true } +toml = { workspace = true } diff --git a/plugins/languages/python/HOW-TO.md b/plugins/languages/python/HOW-TO.md new file mode 100644 index 0000000..eaf4e41 --- /dev/null +++ b/plugins/languages/python/HOW-TO.md @@ -0,0 +1,25 @@ +# How to change the rules of the Python Language plugin + +## Overview + +`plugins/languages/python` (`codeint-lang-python`, plugin name `python`) is a built-in Language plugin that lowers `.py` files into the language-neutral Code model using a pure-Rust `#![forbid(unsafe_code)]` indentation-aware lexer and structural analyzer targeting the modern Python 3 superset. + +## Source sets and workspaces + +- `src/source_set.rs` classifies a `.py` file as `Generated` when its filename ends with `_pb2.py` or `_pb2_grpc.py` or when a leading comment contains a generated-file marker, `Test` when its path is under `test/` or `tests/` or its filename is `conftest.py`, starts with `test_`, or ends with `_test.py`, and `Production` otherwise (`vendor/` and `third_party/` are settled by the core). +- `src/workspaces.rs` reads `[tool.uv.workspace].members` and `exclude` from the root `pyproject.toml` to report Workspace packages. + +## Functions, tokens, and Flagged lines + +- `src/functions.rs` extracts `def`, `async def`, and `lambda` functions and counts decision points (`if`, `elif`, `for`, `while`, `except`, non-wildcard `case` arms, `and`, and `or`). +- `src/imports.rs` marks `import` and `from ... import` statements as `TokenKind::ImportOrExport`. +- `src/rules.rs` implements five zero-false-positive structural Flagged-line rules: `conditional-yields-boolean`, `else-after-return`, `except-only-reraises`, `if-else-returns-boolean`, and `trailing-bare-return`. + +## Imports and module resolution + +- `src/imports.rs` and `src/resolution.rs` extract runtime imports while ignoring imports inside `if TYPE_CHECKING:` (or `if typing.TYPE_CHECKING:`) guard blocks and `from __future__ import` directives. +- Relative imports (`.foo`, `..bar`) and repository-root or `src/`-layout package imports resolve to repository `.py` files, while standard-library and third-party modules are classified as `External`. + +## Reference ranges + +- `reference_ranges` returns the 10th to 90th percentile bands from the 20-repository pre-2023 Python panel recorded in [ADR 0013](../../../docs/adr/0013-python-reference-ranges.md). diff --git a/plugins/languages/python/src/functions.rs b/plugins/languages/python/src/functions.rs new file mode 100644 index 0000000..7c96f44 --- /dev/null +++ b/plugins/languages/python/src/functions.rs @@ -0,0 +1,175 @@ +use std::collections::BTreeSet; + +use codeint_model::language::Function; +use codeint_model::scan::score_function_spans; + +use crate::lexer::{LogicalLine, PyToken}; + +pub(crate) fn extract( + tokens: &[PyToken], + logical_lines: &[LogicalLine], + code_lines: &BTreeSet, +) -> Vec { + let mut spans = Vec::new(); + let case_indices = collect_decision_case_indices(tokens, logical_lines); + for (line_idx, line) in logical_lines.iter().enumerate() { + if let Some(span) = extract_def_span(tokens, logical_lines, line_idx) { + spans.push(span); + } + collect_lambda_spans(tokens, line, &mut spans); + } + score_function_spans(tokens, code_lines, &spans, |toks, idx| { + decision_weight(toks, idx, &case_indices) + }) +} + +pub(crate) fn is_def_header(slice: &[PyToken]) -> bool { + slice.first().is_some_and(|t| t.is_kw("def")) + || (slice.first().is_some_and(|t| t.is_kw("async")) + && slice.get(1).is_some_and(|t| t.is_kw("def"))) +} + +fn extract_def_span( + tokens: &[PyToken], + logical_lines: &[LogicalLine], + line_idx: usize, +) -> Option<(usize, usize, u32, u32)> { + let line = &logical_lines[line_idx]; + if !is_def_header(&tokens[line.tokens.clone()]) { + return None; + } + let colon_idx = find_header_colon(tokens, line.tokens.start, line.tokens.end)?; + let block_end = block_end_line(logical_lines, line_idx); + let end_logical = &logical_lines[block_end]; + let body_start = colon_idx + 1; + let body_end = end_logical.tokens.end.saturating_sub(1); + (body_start <= body_end).then_some(( + body_start, + body_end, + line.start_line, + end_logical.end_line, + )) +} + +fn find_header_colon(tokens: &[PyToken], start: usize, end: usize) -> Option { + let mut depth = 0usize; + let mut saw_params = false; + for (idx, tok) in tokens.iter().enumerate().take(end).skip(start) { + match tok.text.as_str() { + "(" | "[" | "{" => { + saw_params |= tok.text == "(" && depth == 0; + depth += 1; + } + ")" | "]" | "}" => depth = depth.saturating_sub(1), + ":" if depth == 0 && saw_params => return Some(idx), + _ => {} + } + } + None +} + +pub(crate) fn block_end_line(logical_lines: &[LogicalLine], header_idx: usize) -> usize { + let base_indent = logical_lines[header_idx].indent; + let mut end = header_idx; + while let Some(next) = logical_lines.get(end + 1) { + if next.indent > base_indent { + end += 1; + } else { + break; + } + } + end +} + +fn collect_lambda_spans( + tokens: &[PyToken], + line: &LogicalLine, + spans: &mut Vec<(usize, usize, u32, u32)>, +) { + for idx in line.tokens.clone() { + if !tokens[idx].is_kw("lambda") { + continue; + } + let Some(colon_idx) = find_lambda_colon(tokens, idx + 1, line.tokens.end) else { + continue; + }; + let body_start = colon_idx + 1; + if body_start >= line.tokens.end { + continue; + } + let body_end = find_lambda_body_end(tokens, body_start, line.tokens.end); + if body_start <= body_end { + spans.push(( + body_start, + body_end, + tokens[idx].line, + tokens[body_end].line, + )); + } + } +} + +fn find_lambda_colon(tokens: &[PyToken], start: usize, end: usize) -> Option { + let mut depth = 0usize; + for (idx, tok) in tokens.iter().enumerate().take(end).skip(start) { + match tok.text.as_str() { + "(" | "[" | "{" => depth += 1, + ")" | "]" | "}" if depth == 0 => return None, + ")" | "]" | "}" => depth -= 1, + ":" if depth == 0 => return Some(idx), + _ => {} + } + } + None +} + +fn find_lambda_body_end(tokens: &[PyToken], start: usize, end: usize) -> usize { + let mut depth = 0usize; + for (idx, tok) in tokens.iter().enumerate().take(end).skip(start) { + match tok.text.as_str() { + "(" | "[" | "{" => depth += 1, + ")" | "]" | "}" if depth == 0 => return idx.saturating_sub(1), + ")" | "]" | "}" => depth -= 1, + "," | ";" if depth == 0 => return idx.saturating_sub(1), + _ => {} + } + } + end.saturating_sub(1) +} + +fn collect_decision_case_indices( + tokens: &[PyToken], + logical_lines: &[LogicalLine], +) -> BTreeSet { + let mut out = BTreeSet::new(); + for line in logical_lines { + let slice = &tokens[line.tokens.clone()]; + if slice + .first() + .is_some_and(|t| t.is_ident() && t.text == "case") + && slice.last().is_some_and(|t| t.text == ":") + && !is_wildcard_case(slice) + { + out.insert(line.tokens.start); + } + } + out +} + +fn is_wildcard_case(slice: &[PyToken]) -> bool { + slice.len() == 3 && slice[1].is_ident() && slice[1].text == "_" +} + +fn decision_weight(tokens: &[PyToken], idx: usize, case_indices: &BTreeSet) -> u32 { + if case_indices.contains(&idx) { + return 1; + } + let tok = &tokens[idx]; + if !tok.is_kw { + return 0; + } + match tok.text.as_str() { + "if" | "elif" | "for" | "while" | "except" | "and" | "or" => 1, + _ => 0, + } +} diff --git a/plugins/languages/python/src/imports.rs b/plugins/languages/python/src/imports.rs new file mode 100644 index 0000000..688f283 --- /dev/null +++ b/plugins/languages/python/src/imports.rs @@ -0,0 +1,153 @@ +use std::collections::BTreeSet; + +use crate::lexer::{LogicalLine, PyToken}; + +pub(crate) fn scan_imports( + tokens: &[PyToken], + logical_lines: &[LogicalLine], +) -> (Vec, BTreeSet) { + let mut runtime_imports = BTreeSet::new(); + let mut marked_indices = BTreeSet::new(); + let mut type_checking_indent: Option = None; + + for line in logical_lines { + if type_checking_indent.is_some_and(|tc| line.indent <= tc) { + type_checking_indent = None; + } + let slice = &tokens[line.tokens.clone()]; + if is_type_checking_guard(slice) { + type_checking_indent = Some(line.indent); + continue; + } + process_import_line( + line, + slice, + type_checking_indent.is_none(), + &mut marked_indices, + &mut runtime_imports, + ); + } + + (runtime_imports.into_iter().collect(), marked_indices) +} + +fn process_import_line( + line: &LogicalLine, + slice: &[PyToken], + is_runtime: bool, + marked_indices: &mut BTreeSet, + runtime_imports: &mut BTreeSet, +) { + let Some(first) = slice.first() else { + return; + }; + if first.is_kw("import") { + marked_indices.extend(line.tokens.clone()); + if is_runtime { + parse_import_stmt(&slice[1..], runtime_imports); + } + } else if first.is_kw("from") { + marked_indices.extend(line.tokens.clone()); + if is_runtime { + parse_from_import_stmt(&slice[1..], runtime_imports); + } + } +} + +fn is_type_checking_guard(slice: &[PyToken]) -> bool { + let Some(first) = slice.first() else { + return false; + }; + if !(first.is_kw("if") || first.is_kw("elif")) || slice.last().is_none_or(|t| t.text != ":") { + return false; + } + match &slice[1..slice.len() - 1] { + [t] => t.is_ident() && t.text == "TYPE_CHECKING", + [a, dot, b] => a.is_ident() && dot.text == "." && b.is_ident() && b.text == "TYPE_CHECKING", + _ => false, + } +} + +fn parse_import_stmt(slice: &[PyToken], out: &mut BTreeSet) { + let mut idx = 0usize; + while idx < slice.len() { + let mut module = String::new(); + while let Some(tok) = slice.get(idx) { + if tok.is_ident() || tok.text == "." { + module.push_str(&tok.text); + idx += 1; + } else { + break; + } + } + if !module.is_empty() { + out.insert(module); + } + while let Some(tok) = slice.get(idx) { + idx += 1; + if tok.text == "," { + break; + } + } + } +} + +fn parse_from_import_stmt(slice: &[PyToken], out: &mut BTreeSet) { + let Some(import_pos) = slice.iter().position(|t| t.is_kw("import")) else { + return; + }; + let (dots, after_dots) = consume_leading_dots(&slice[..import_pos]); + let module = collect_dotted_module(&slice[after_dots..import_pos]); + if dots.is_empty() && module == "__future__" { + return; + } + if !module.is_empty() { + out.insert(format!("{dots}{module}")); + return; + } + if !dots.is_empty() { + parse_relative_imported_names(&slice[import_pos + 1..], &dots, out); + } +} + +fn consume_leading_dots(prefix: &[PyToken]) -> (String, usize) { + let mut dots = String::new(); + let mut idx = 0usize; + while let Some(tok) = prefix.get(idx) { + match tok.text.as_str() { + "." | "..." => { + dots.push_str(&tok.text); + idx += 1; + } + _ => break, + } + } + (dots, idx) +} + +fn collect_dotted_module(tokens: &[PyToken]) -> String { + let mut module = String::new(); + for tok in tokens { + if tok.is_ident() || tok.text == "." { + module.push_str(&tok.text); + } + } + module +} + +fn parse_relative_imported_names(slice: &[PyToken], dots: &str, out: &mut BTreeSet) { + let mut idx = 0usize; + while idx < slice.len() { + let tok = &slice[idx]; + if tok.is_ident() { + out.insert(format!("{dots}{}", tok.text)); + idx += if slice.get(idx + 1).is_some_and(|t| t.is_kw("as")) { + 3 + } else { + 1 + }; + } else { + idx += 1; + } + } +} diff --git a/plugins/languages/python/src/lexer.rs b/plugins/languages/python/src/lexer.rs new file mode 100644 index 0000000..2ff5b7e --- /dev/null +++ b/plugins/languages/python/src/lexer.rs @@ -0,0 +1,451 @@ +use std::collections::BTreeSet; +use std::ops::Range; + +use codeint_model::language::{LowerError, TokenKind}; +use codeint_model::scan::{ScanToken, track_delim}; + +#[derive(Debug, Clone)] +pub(crate) struct PyToken { + pub(crate) line: u32, + pub(crate) text: String, + pub(crate) token_kind: TokenKind, + pub(crate) is_kw: bool, +} + +impl PyToken { + pub(crate) fn is_ident(&self) -> bool { + self.token_kind == TokenKind::Identifier + } + + pub(crate) fn is_kw(&self, kw: &str) -> bool { + self.is_kw && self.text == kw + } +} + +impl ScanToken for PyToken { + fn text(&self) -> &str { + &self.text + } + + fn is_keyword(&self, kw: &str) -> bool { + self.is_kw(kw) + } + + fn line(&self) -> u32 { + self.line + } +} + +#[derive(Debug, Clone)] +pub(crate) struct LogicalLine { + pub(crate) indent: usize, + pub(crate) start_line: u32, + pub(crate) end_line: u32, + pub(crate) tokens: Range, +} + +pub(crate) struct LexResult { + pub(crate) tokens: Vec, + pub(crate) logical_lines: Vec, + pub(crate) code_lines: BTreeSet, + pub(crate) header_comments: Vec, +} + +const KEYWORDS: &[&str] = &[ + "False", "None", "True", "and", "as", "assert", "async", "await", "break", "class", "continue", + "def", "del", "elif", "else", "except", "finally", "for", "from", "global", "if", "import", + "in", "is", "lambda", "nonlocal", "not", "or", "pass", "raise", "return", "try", "while", + "with", "yield", +]; + +const THREE_CHAR_OPS: &[&str] = &["...", "//=", "**=", "<<=", ">>="]; + +const TWO_CHAR_OPS: &[&str] = &[ + "==", "!=", "<=", ">=", "//", "**", "<<", ">>", ":=", "->", "+=", "-=", "*=", "/=", "%=", "&=", + "|=", "^=", "@=", +]; + +pub(crate) fn scan(text: &str) -> Result { + let mut state = Scanner::new(text); + state.run()?; + state.finish() +} + +struct Scanner<'a> { + bytes: &'a [u8], + src: &'a str, + pos: usize, + line: u32, + tokens: Vec, + logical_lines: Vec, + code_lines: BTreeSet, + header_comments: Vec, + delims: Vec<(u8, u32)>, + at_physical_line_start: bool, + current_line_indent: usize, + pending_line_start: Option<(usize, u32, usize)>, +} + +impl<'a> Scanner<'a> { + fn new(src: &'a str) -> Self { + let pos = if src.starts_with('\u{feff}') { 3 } else { 0 }; + Self { + bytes: src.as_bytes(), + src, + pos, + line: 1, + tokens: Vec::new(), + logical_lines: Vec::new(), + code_lines: BTreeSet::new(), + header_comments: Vec::new(), + delims: Vec::new(), + at_physical_line_start: true, + current_line_indent: 0, + pending_line_start: None, + } + } + + fn run(&mut self) -> Result<(), LowerError> { + while self.pos < self.bytes.len() { + if self.at_physical_line_start { + self.consume_indent(); + if self.pos >= self.bytes.len() { + break; + } + } + self.step()?; + } + self.flush_logical_line(); + if let Some((open, open_line)) = self.delims.pop() { + return Err(LowerError::Unparsable(format!( + "unclosed {:?} opened at line {open_line}", + open as char + ))); + } + Ok(()) + } + + fn finish(self) -> Result { + reject_python2_print(&self.tokens, &self.logical_lines)?; + Ok(LexResult { + tokens: self.tokens, + logical_lines: self.logical_lines, + code_lines: self.code_lines, + header_comments: self.header_comments, + }) + } + + fn consume_indent(&mut self) { + let mut indent = 0usize; + while let Some(&b) = self.bytes.get(self.pos) { + match b { + b' ' => { + indent += 1; + self.pos += 1; + } + b'\t' => { + indent += 8 - (indent % 8); + self.pos += 1; + } + b'\x0c' => self.pos += 1, + _ => break, + } + } + self.current_line_indent = indent; + self.at_physical_line_start = false; + } + + fn step(&mut self) -> Result<(), LowerError> { + let b = self.bytes[self.pos]; + if matches!(b, b' ' | b'\t' | b'\r' | b'\x0c') { + self.pos += 1; + return Ok(()); + } + if b == b'\n' { + self.pos += 1; + if self.delims.is_empty() { + self.flush_logical_line(); + } + self.line += 1; + self.at_physical_line_start = true; + return Ok(()); + } + if b == b'\\' { + return self.consume_line_continuation(); + } + if b == b'#' { + self.consume_comment(); + return Ok(()); + } + self.step_code_token(b) + } + + fn step_code_token(&mut self, b: u8) -> Result<(), LowerError> { + if matches!(b, b'\'' | b'"') { + return self.consume_string(self.pos); + } + if b.is_ascii_digit() + || (b == b'.' && self.bytes.get(self.pos + 1).is_some_and(u8::is_ascii_digit)) + { + self.consume_number(); + return Ok(()); + } + if is_ident_start(b) { + return self.consume_ident_or_prefixed_string(); + } + self.consume_punct() + } + + fn consume_line_continuation(&mut self) -> Result<(), LowerError> { + self.pos += 1; + while matches!(self.bytes.get(self.pos), Some(b' ' | b'\t' | b'\r')) { + self.pos += 1; + } + if self.bytes.get(self.pos) == Some(&b'\n') { + self.pos += 1; + self.line += 1; + self.at_physical_line_start = true; + return Ok(()); + } + Err(LowerError::Unparsable(format!( + "unexpected backslash at line {}", + self.line + ))) + } + + fn consume_comment(&mut self) { + let start = self.pos; + while let Some(&b) = self.bytes.get(self.pos) { + if b == b'\n' { + break; + } + self.pos += 1; + } + if self.tokens.is_empty() { + self.header_comments + .push(self.src[start..self.pos].to_owned()); + } + } + + fn consume_ident_or_prefixed_string(&mut self) -> Result<(), LowerError> { + if let Some(quote_pos) = string_prefix_end(self.bytes, self.pos) { + return self.consume_string(quote_pos); + } + let start = self.pos; + self.pos += 1; + while let Some(&b) = self.bytes.get(self.pos) { + if is_ident_continue(b) { + self.pos += 1; + } else { + break; + } + } + let word = &self.src[start..self.pos]; + let is_kw = KEYWORDS.contains(&word); + let token_kind = if is_kw { + TokenKind::Other + } else { + TokenKind::Identifier + }; + self.push_token(token_kind, is_kw, word.to_owned(), self.line); + Ok(()) + } + + fn consume_string(&mut self, quote_pos: usize) -> Result<(), LowerError> { + let start = self.pos; + let start_line = self.line; + let quote = self.bytes[quote_pos]; + let is_triple = self.bytes.get(quote_pos + 1) == Some("e) + && self.bytes.get(quote_pos + 2) == Some("e); + self.pos = quote_pos + if is_triple { 3 } else { 1 }; + if !self.scan_string_body(quote, is_triple) { + return Err(LowerError::Unparsable(format!( + "unterminated string at line {start_line}" + ))); + } + for line in start_line..=self.line { + self.code_lines.insert(line); + } + let text = self.src[start..self.pos].to_owned(); + self.push_token(TokenKind::Literal, false, text, start_line); + Ok(()) + } + + fn scan_string_body(&mut self, quote: u8, triple: bool) -> bool { + while self.pos < self.bytes.len() { + let b = self.bytes[self.pos]; + if b == b'\\' { + if self.bytes.get(self.pos + 1) == Some(&b'\n') { + self.line += 1; + } + self.pos = (self.pos + 2).min(self.bytes.len()); + continue; + } + if b == b'\n' { + if !triple { + return false; + } + self.line += 1; + self.pos += 1; + continue; + } + if b == quote && self.try_close_quote(quote, triple) { + return true; + } + self.pos += 1; + } + false + } + + fn try_close_quote(&mut self, quote: u8, triple: bool) -> bool { + if !triple { + self.pos += 1; + return true; + } + if self.bytes.get(self.pos + 1) == Some("e) + && self.bytes.get(self.pos + 2) == Some("e) + { + self.pos += 3; + return true; + } + false + } + + fn consume_number(&mut self) { + let start = self.pos; + let line = self.line; + while let Some(&b) = self.bytes.get(self.pos) { + let is_exp_sign = matches!(b, b'+' | b'-') + && self.pos > start + && matches!(self.bytes[self.pos - 1], b'e' | b'E'); + if b.is_ascii_alphanumeric() || b == b'_' || b == b'.' || is_exp_sign { + self.pos += 1; + } else { + break; + } + } + self.push_token( + TokenKind::Literal, + false, + self.src[start..self.pos].to_owned(), + line, + ); + } + + fn consume_punct(&mut self) -> Result<(), LowerError> { + let rest = &self.src[self.pos..]; + if rest.starts_with("<>") { + return Err(LowerError::Unparsable(format!( + "Python 2 '<>' operator at line {}", + self.line + ))); + } + let op = match_operator(rest); + self.pos += op.len(); + track_delim(&mut self.delims, op, self.line)?; + self.push_token(TokenKind::Other, false, op.to_owned(), self.line); + if op == ";" && self.delims.is_empty() { + self.flush_logical_line(); + } + Ok(()) + } + + fn push_token(&mut self, token_kind: TokenKind, is_kw: bool, text: String, line: u32) { + if self.pending_line_start.is_none() { + self.pending_line_start = Some((self.current_line_indent, line, self.tokens.len())); + } + self.code_lines.insert(line); + self.tokens.push(PyToken { + line, + text, + token_kind, + is_kw, + }); + } + + fn flush_logical_line(&mut self) { + let Some((indent, start_line, start_idx)) = self.pending_line_start.take() else { + return; + }; + if start_idx < self.tokens.len() { + let end_line = self.tokens[self.tokens.len() - 1].line; + self.logical_lines.push(LogicalLine { + indent, + start_line, + end_line, + tokens: start_idx..self.tokens.len(), + }); + } + } +} + +fn match_operator(rest: &str) -> &str { + for &op in THREE_CHAR_OPS { + if rest.starts_with(op) { + return op; + } + } + for &op in TWO_CHAR_OPS { + if rest.starts_with(op) { + return op; + } + } + let ch = rest.chars().next().map_or(1, char::len_utf8); + &rest[..ch] +} + +fn string_prefix_end(bytes: &[u8], pos: usize) -> Option { + let b0 = *bytes.get(pos)?; + if !is_string_prefix_char(b0) { + return None; + } + let b1 = *bytes.get(pos + 1)?; + if b1 == b'\'' || b1 == b'"' { + return Some(pos + 1); + } + if is_string_prefix_char(b1) && matches!(bytes.get(pos + 2), Some(b'\'' | b'"')) { + return Some(pos + 2); + } + None +} + +fn is_string_prefix_char(b: u8) -> bool { + matches!(b, b'r' | b'R' | b'u' | b'U' | b'b' | b'B' | b'f' | b'F') +} + +fn is_ident_start(b: u8) -> bool { + b.is_ascii_alphabetic() || b == b'_' || b >= 0x80 +} + +fn is_ident_continue(b: u8) -> bool { + b.is_ascii_alphanumeric() || b == b'_' || b >= 0x80 +} + +fn reject_python2_print( + tokens: &[PyToken], + logical_lines: &[LogicalLine], +) -> Result<(), LowerError> { + for line in logical_lines { + let slice = &tokens[line.tokens.clone()]; + let Some(first) = slice.first() else { + continue; + }; + if !first.is_ident() || first.text != "print" { + continue; + } + let Some(second) = slice.get(1) else { + continue; + }; + let is_py2_arg = matches!( + second.token_kind, + TokenKind::Literal | TokenKind::Identifier + ) || second.text == ">>"; + if is_py2_arg { + return Err(LowerError::Unparsable(format!( + "Python 2 print statement at line {}", + first.line + ))); + } + } + Ok(()) +} diff --git a/plugins/languages/python/src/lib.rs b/plugins/languages/python/src/lib.rs new file mode 100644 index 0000000..b061293 --- /dev/null +++ b/plugins/languages/python/src/lib.rs @@ -0,0 +1,89 @@ +#![forbid(unsafe_code)] + +mod functions; +mod imports; +mod lexer; +mod resolution; +mod rules; +mod source_set; +mod workspaces; + +use codeint_model::language::{ + FileModel, Guest, ImportRequest, LowerError, Manifest, ReferenceRange, Resolution, Token, + TokenKind, WorkspaceError, +}; +use codeint_model::scan::build_reference_ranges; +use codeint_model::token_text_hash; + +pub use rules::flagged_line_rules; + +pub struct Python; + +impl Guest for Python { + fn extensions() -> Vec { + vec!["py".to_owned()] + } + + fn reference_ranges() -> Vec { + build_reference_ranges( + "codeint panel of 20 Python repositories, ADR 0013, codeint 0.4.0", + [ + ("erosion", 0.144, 0.624), + ("verbosity", 0.014, 0.204), + ("duplication", 0.012, 0.201), + ("import_cycles", 0.000, 0.321), + ], + ) + } + + fn manifest_paths(repository_paths: Vec) -> Vec { + resolution::find_pyprojects(&repository_paths) + } + + fn workspace_packages(manifests: Vec) -> Result, WorkspaceError> { + workspaces::discover(&manifests) + } + + fn resolve_imports( + repository_paths: Vec, + manifests: Vec, + requests: Vec, + ) -> Vec { + resolution::resolve_all(&repository_paths, &manifests, &requests) + } + + fn lower(path: String, text: String) -> Result { + if !path.ends_with(".py") { + return Err(LowerError::UnsupportedFile(format!( + "{path} is not a Python source file" + ))); + } + let lexed = lexer::scan(&text)?; + let (runtime_imports, import_indices) = + imports::scan_imports(&lexed.tokens, &lexed.logical_lines); + let tokens = lexed + .tokens + .iter() + .enumerate() + .map(|(idx, tok)| Token { + kind: if import_indices.contains(&idx) { + TokenKind::ImportOrExport + } else { + tok.token_kind + }, + text_hash: token_text_hash(&tok.text), + line: tok.line, + }) + .collect(); + let source_lines = + u32::try_from(lexed.code_lines.len()).map_err(|_| LowerError::TooLarge)?; + Ok(FileModel { + functions: functions::extract(&lexed.tokens, &lexed.logical_lines, &lexed.code_lines), + flagged_lines: rules::evaluate(&lexed.tokens, &lexed.logical_lines, &lexed.code_lines), + source_set: source_set::classify(&path, &lexed.header_comments), + runtime_imports, + tokens, + source_lines, + }) + } +} diff --git a/plugins/languages/python/src/resolution.rs b/plugins/languages/python/src/resolution.rs new file mode 100644 index 0000000..62a3d46 --- /dev/null +++ b/plugins/languages/python/src/resolution.rs @@ -0,0 +1,118 @@ +use std::collections::{HashMap, HashSet}; + +use codeint_model::language::{ImportRequest, Manifest, Resolution}; +use codeint_model::scan::find_manifests; + +pub(crate) fn find_pyprojects(repository_paths: &[String]) -> Vec { + find_manifests(repository_paths, "pyproject.toml") +} + +pub(crate) fn resolve_all( + repository_paths: &[String], + manifests: &[Manifest], + requests: &[ImportRequest], +) -> Vec { + let py_files: HashSet = repository_paths + .iter() + .filter(|path| path.ends_with(".py")) + .cloned() + .collect(); + let module_map = build_module_map(&py_files, manifests); + requests + .iter() + .map(|req| resolve_one(&py_files, &module_map, &req.importer, &req.specifier)) + .collect() +} + +fn build_module_map(py_files: &HashSet, manifests: &[Manifest]) -> HashMap { + let mut roots = vec![String::new(), "src".to_owned()]; + for manifest in manifests { + if let Some(dir) = manifest.path.strip_suffix("/pyproject.toml") { + roots.push(dir.to_owned()); + roots.push(format!("{dir}/src")); + } + } + let mut sorted_files: Vec<&String> = py_files.iter().collect(); + sorted_files.sort(); + let mut map = HashMap::new(); + for root in &roots { + let prefix = if root.is_empty() { + String::new() + } else { + format!("{root}/") + }; + for file in &sorted_files { + let Some(rel) = file.strip_prefix(&prefix) else { + continue; + }; + if let Some(module) = path_to_module(rel) { + map.entry(module).or_insert_with(|| (*file).clone()); + } + } + } + map +} + +fn path_to_module(rel: &str) -> Option { + if rel == "__init__.py" { + return None; + } + if let Some(pkg) = rel.strip_suffix("/__init__.py") { + return Some(pkg.replace('/', ".")); + } + rel.strip_suffix(".py").map(|stem| stem.replace('/', ".")) +} + +fn resolve_one( + py_files: &HashSet, + module_map: &HashMap, + importer: &str, + specifier: &str, +) -> Resolution { + if specifier.starts_with('.') { + return resolve_relative(py_files, importer, specifier); + } + if let Some(target) = module_map.get(specifier) { + if target == importer { + return Resolution::External; + } + return Resolution::Resolved(target.clone()); + } + Resolution::External +} + +fn resolve_relative(py_files: &HashSet, importer: &str, specifier: &str) -> Resolution { + let dots = specifier.bytes().take_while(|&b| b == b'.').count(); + let remainder = &specifier[dots..]; + let parent = importer.rsplit_once('/').map_or("", |(dir, _)| dir); + let mut segments: Vec<&str> = if parent.is_empty() { + Vec::new() + } else { + parent.split('/').collect() + }; + let climbs = dots.saturating_sub(1); + if climbs > segments.len() { + return Resolution::Unresolved(format!("{specifier:?} climbs outside the repository")); + } + segments.truncate(segments.len() - climbs); + if !remainder.is_empty() { + segments.extend(remainder.split('.').filter(|s| !s.is_empty())); + } + let base = segments.join("/"); + let candidates = if base.is_empty() { + vec!["__init__.py".to_owned()] + } else { + vec![format!("{base}.py"), format!("{base}/__init__.py")] + }; + for candidate in candidates { + if py_files.contains(&candidate) { + if candidate == importer { + return Resolution::External; + } + return Resolution::Resolved(candidate); + } + } + Resolution::Unresolved(format!( + "no Python module in the repository matches {specifier:?}" + )) +} diff --git a/plugins/languages/python/src/rules.rs b/plugins/languages/python/src/rules.rs new file mode 100644 index 0000000..94d9176 --- /dev/null +++ b/plugins/languages/python/src/rules.rs @@ -0,0 +1,273 @@ +use std::collections::BTreeSet; + +use codeint_model::language::FlaggedLine; +use codeint_model::scan::{finalize_flagged, flag_range}; + +use crate::functions::{block_end_line, is_def_header}; +use crate::lexer::{LogicalLine, PyToken}; + +const RULES: &[&str] = &[ + "conditional-yields-boolean", + "else-after-return", + "except-only-reraises", + "if-else-returns-boolean", + "trailing-bare-return", +]; + +pub fn flagged_line_rules() -> impl Iterator { + RULES.iter().copied() +} + +pub(crate) fn evaluate( + tokens: &[PyToken], + logical_lines: &[LogicalLine], + code_lines: &BTreeSet, +) -> Vec { + let mut out = BTreeSet::new(); + for (idx, line) in logical_lines.iter().enumerate() { + let slice = &tokens[line.tokens.clone()]; + if slice + .first() + .is_some_and(|t| t.is_kw("if") || t.is_kw("elif")) + { + check_if_else(tokens, logical_lines, idx, code_lines, &mut out); + } else if slice.first().is_some_and(|t| t.is_kw("except")) { + check_except_only_reraises(tokens, logical_lines, idx, code_lines, &mut out); + } else if is_def_header(slice) { + check_trailing_bare_return(tokens, logical_lines, idx, code_lines, &mut out); + } + check_conditional_bool(slice, code_lines, &mut out); + } + finalize_flagged(out) +} + +fn check_if_else( + tokens: &[PyToken], + logical_lines: &[LogicalLine], + if_idx: usize, + code_lines: &BTreeSet, + out: &mut BTreeSet<(u32, &'static str)>, +) { + let then_end = block_end_line(logical_lines, if_idx); + if then_end == if_idx { + return; + } + let else_idx = then_end + 1; + let Some(else_line) = logical_lines.get(else_idx) else { + return; + }; + if else_line.indent != logical_lines[if_idx].indent + || !tokens[else_line.tokens.clone()] + .first() + .is_some_and(|t| t.is_kw("else")) + { + return; + } + let else_end = block_end_line(logical_lines, else_idx); + if else_end == else_idx { + return; + } + if tokens[logical_lines[if_idx].tokens.start].is_kw("if") + && let (Some(a), Some(b)) = ( + single_bool_return(tokens, logical_lines, if_idx + 1, then_end), + single_bool_return(tokens, logical_lines, else_idx + 1, else_end), + ) + && a != b + { + flag_range( + logical_lines[if_idx].start_line, + logical_lines[else_end].end_line, + "if-else-returns-boolean", + code_lines, + out, + ); + return; + } + if ends_with_unconditional_exit(tokens, logical_lines, if_idx + 1, then_end) { + flag_range( + else_line.start_line, + logical_lines[else_end].end_line, + "else-after-return", + code_lines, + out, + ); + } +} + +fn single_bool_return( + tokens: &[PyToken], + logical_lines: &[LogicalLine], + start_idx: usize, + end_idx: usize, +) -> Option { + if start_idx != end_idx { + return None; + } + let slice = trim_trailing_semi(&tokens[logical_lines[start_idx].tokens.clone()]); + if slice.len() == 2 && slice[0].is_kw("return") { + bool_literal(&slice[1]) + } else { + None + } +} + +fn ends_with_unconditional_exit( + tokens: &[PyToken], + logical_lines: &[LogicalLine], + start_idx: usize, + end_idx: usize, +) -> bool { + let body_indent = logical_lines[start_idx].indent; + let Some(last) = logical_lines[start_idx..=end_idx] + .iter() + .rev() + .find(|line| line.indent == body_indent) + else { + return false; + }; + tokens[last.tokens.clone()] + .first() + .is_some_and(|t| t.is_kw("return") || t.is_kw("raise")) +} + +fn check_except_only_reraises( + tokens: &[PyToken], + logical_lines: &[LogicalLine], + except_idx: usize, + code_lines: &BTreeSet, + out: &mut BTreeSet<(u32, &'static str)>, +) { + let body_end = block_end_line(logical_lines, except_idx); + if body_end != except_idx + 1 { + return; + } + let caught_var = extract_caught_var(&tokens[logical_lines[except_idx].tokens.clone()]); + let body = trim_trailing_semi(&tokens[logical_lines[body_end].tokens.clone()]); + if is_reraise_stmt(body, caught_var) { + flag_range( + logical_lines[except_idx].start_line, + logical_lines[body_end].end_line, + "except-only-reraises", + code_lines, + out, + ); + } +} + +fn extract_caught_var(header: &[PyToken]) -> Option<&str> { + header + .iter() + .position(|t| t.is_kw("as")) + .and_then(|pos| header.get(pos + 1)) + .filter(|t| t.is_ident()) + .map(|t| t.text.as_str()) +} + +fn is_reraise_stmt(body: &[PyToken], caught_var: Option<&str>) -> bool { + if !body.first().is_some_and(|t| t.is_kw("raise")) { + return false; + } + match body.len() { + 1 => true, + 2 => caught_var.is_some_and(|name| body[1].is_ident() && body[1].text == name), + _ => false, + } +} + +fn check_trailing_bare_return( + tokens: &[PyToken], + logical_lines: &[LogicalLine], + def_idx: usize, + code_lines: &BTreeSet, + out: &mut BTreeSet<(u32, &'static str)>, +) { + let body_end = block_end_line(logical_lines, def_idx); + if body_end <= def_idx + 1 { + return; + } + let body_indent = logical_lines[def_idx + 1].indent; + let last = &logical_lines[body_end]; + if last.indent != body_indent { + return; + } + let slice = trim_trailing_semi(&tokens[last.tokens.clone()]); + if is_bare_or_none_return(slice) { + flag_range( + last.start_line, + last.end_line, + "trailing-bare-return", + code_lines, + out, + ); + } +} + +fn is_bare_or_none_return(slice: &[PyToken]) -> bool { + if !slice.first().is_some_and(|t| t.is_kw("return")) { + return false; + } + slice.len() == 1 || (slice.len() == 2 && slice[1].is_kw("None")) +} + +fn check_conditional_bool( + slice: &[PyToken], + code_lines: &BTreeSet, + out: &mut BTreeSet<(u32, &'static str)>, +) { + for (idx, tok) in slice.iter().enumerate() { + let Some(first_bool) = bool_literal(tok) else { + continue; + }; + if !slice.get(idx + 1).is_some_and(|t| t.is_kw("if")) { + continue; + } + let Some(else_pos) = find_matching_inline_else(slice, idx + 2) else { + continue; + }; + let Some(second) = slice.get(else_pos + 1) else { + continue; + }; + if bool_literal(second).is_some_and(|second_bool| second_bool != first_bool) { + flag_range( + tok.line, + second.line, + "conditional-yields-boolean", + code_lines, + out, + ); + } + } +} + +fn find_matching_inline_else(slice: &[PyToken], start: usize) -> Option { + let mut depth = 0usize; + for (idx, tok) in slice.iter().enumerate().skip(start) { + match tok.text.as_str() { + "(" | "[" | "{" => depth += 1, + ")" | "]" | "}" if depth == 0 => return None, + ")" | "]" | "}" => depth -= 1, + _ if depth == 0 && tok.is_kw("else") => return Some(idx), + _ => {} + } + } + None +} + +fn bool_literal(tok: &PyToken) -> Option { + if !tok.is_kw { + return None; + } + match tok.text.as_str() { + "True" => Some(true), + "False" => Some(false), + _ => None, + } +} + +fn trim_trailing_semi(slice: &[PyToken]) -> &[PyToken] { + if slice.last().is_some_and(|t| t.text == ";") { + &slice[..slice.len() - 1] + } else { + slice + } +} diff --git a/plugins/languages/python/src/source_set.rs b/plugins/languages/python/src/source_set.rs new file mode 100644 index 0000000..0a099ae --- /dev/null +++ b/plugins/languages/python/src/source_set.rs @@ -0,0 +1,44 @@ +use codeint_model::language::SourceSet; + +const GENERATED_MARKERS: &[&str] = &[ + "@generated", + "generated code", + "do not edit", + "auto-generated", +]; + +pub(crate) fn classify(path: &str, header_comments: &[String]) -> SourceSet { + let filename = path.rsplit('/').next().unwrap_or(path); + if is_generated_filename(filename) || has_generated_header(header_comments) { + return SourceSet::Generated; + } + if is_test_path(path, filename) { + return SourceSet::Test; + } + SourceSet::Production +} + +fn is_generated_filename(filename: &str) -> bool { + filename.ends_with("_pb2.py") || filename.ends_with("_pb2_grpc.py") +} + +fn has_generated_header(header_comments: &[String]) -> bool { + header_comments.iter().any(|line| { + let lower = line.to_ascii_lowercase(); + GENERATED_MARKERS + .iter() + .any(|marker| lower.contains(marker)) + }) +} + +fn is_test_path(path: &str, filename: &str) -> bool { + if path + .split('/') + .any(|segment| matches!(segment, "test" | "tests")) + { + return true; + } + filename == "conftest.py" + || (filename.starts_with("test_") && filename.ends_with(".py")) + || filename.ends_with("_test.py") +} diff --git a/plugins/languages/python/src/workspaces.rs b/plugins/languages/python/src/workspaces.rs new file mode 100644 index 0000000..3fb5d47 --- /dev/null +++ b/plugins/languages/python/src/workspaces.rs @@ -0,0 +1,66 @@ +use std::collections::BTreeSet; + +use codeint_model::language::{Manifest, WorkspaceError}; +use globset::{Glob, GlobSet, GlobSetBuilder}; + +pub(crate) fn discover(manifests: &[Manifest]) -> Result, WorkspaceError> { + let Some(root) = manifests.iter().find(|m| m.path == "pyproject.toml") else { + return Ok(Vec::new()); + }; + let doc: toml::Value = toml::from_str(&root.text).map_err(|err| WorkspaceError { + path: root.path.clone(), + message: err.to_string(), + })?; + let Some(workspace) = doc + .get("tool") + .and_then(|v| v.get("uv")) + .and_then(|v| v.get("workspace")) + else { + return Ok(Vec::new()); + }; + let members_list = read_string_array(workspace.get("members")); + if members_list.is_empty() { + return Ok(Vec::new()); + } + let members = compile_globs(&members_list, &root.path)?; + let excludes = compile_globs(&read_string_array(workspace.get("exclude")), &root.path)?; + let mut found = BTreeSet::new(); + for manifest in manifests { + if let Some(dir) = manifest.path.strip_suffix("/pyproject.toml") + && members.is_match(dir) + && !excludes.is_match(dir) + { + found.insert(dir.to_owned()); + } + } + Ok(found.into_iter().collect()) +} + +fn read_string_array(value: Option<&toml::Value>) -> Vec { + value + .and_then(toml::Value::as_array) + .map(|items| { + items + .iter() + .filter_map(toml::Value::as_str) + .map(str::to_owned) + .collect() + }) + .unwrap_or_default() +} + +fn compile_globs(patterns: &[String], manifest_path: &str) -> Result { + let mut builder = GlobSetBuilder::new(); + for raw in patterns { + let normalized = raw.trim_start_matches("./").trim_end_matches('/'); + let glob = Glob::new(normalized).map_err(|err| WorkspaceError { + path: manifest_path.to_owned(), + message: err.to_string(), + })?; + builder.add(glob); + } + builder.build().map_err(|err| WorkspaceError { + path: manifest_path.to_owned(), + message: err.to_string(), + }) +} diff --git a/plugins/languages/python/tests/conformance.rs b/plugins/languages/python/tests/conformance.rs new file mode 100644 index 0000000..5ccd9ed --- /dev/null +++ b/plugins/languages/python/tests/conformance.rs @@ -0,0 +1,215 @@ +use codeint_lang_python::{Python, flagged_line_rules}; +use codeint_model::language::{Function, ImportRequest, Resolution}; +use codeint_model::{LanguagePlugin, LowerError, Manifest, RepoPath, SourceSet, TokenKind}; + +#[test] +fn python_plugin_contract_and_python2_rejection() { + assert_eq!(Python.extensions(), ["py"]); + let ranges = Python.reference_ranges().unwrap(); + for metric in ["erosion", "verbosity", "duplication", "import_cycles"] { + assert!(ranges.for_metric(metric).is_some(), "missing {metric}"); + } + let bad_cases = [ + ("a.pyi", "def f() -> int: ...\n", true), + ("a.py", "def f():\n s = 'unterminated\n", false), + ("legacy.py", "print 'hello'\n", false), + ("legacy_op.py", "if a <> b:\n pass\n", false), + ]; + for (path, src, expect_unsupported) in bad_cases { + let res = Python.lower(&RepoPath::new(path).unwrap(), src); + if expect_unsupported { + assert!(matches!(res, Err(LowerError::UnsupportedFile { .. }))); + } else { + assert!(matches!(res, Err(LowerError::Unparsable { .. }))); + } + } + let empty = Python + .lower(&RepoPath::new("empty.py").unwrap(), "") + .unwrap(); + assert_eq!(empty.source_set, SourceSet::Production); + assert_eq!(empty.source_lines, 0); +} + +#[test] +fn python_functions_decisions_and_source_sets() { + let src = [ + "async def evaluate(x):", + " if x is not None and x > 0:", + " for i in range(x):", + " x += i", + " f = lambda v: v if v > 0 else 0", + " match x:", + " case 0:", + " return f(0)", + " case _:", + " return f(x)", + ] + .join("\n"); + let model = Python + .lower(&RepoPath::new("src/app/eval.py").unwrap(), &src) + .unwrap(); + assert_eq!(model.functions.len(), 2); + assert_eq!( + model.functions[0], + Function { + line: 1, + end_line: 10, + decision_points: 4, + source_lines: 10, + } + ); + assert_eq!(model.functions[1].decision_points, 1); + + for (path, body, expected) in [ + ("tests/test_app.py", "x = 1\n", SourceSet::Test), + ("pkg/conftest.py", "x = 1\n", SourceSet::Test), + ("pkg/api_pb2.py", "x = 1\n", SourceSet::Generated), + ("pkg/gen.py", "# @generated\nx = 1\n", SourceSet::Generated), + ] { + let m = Python.lower(&RepoPath::new(path).unwrap(), body).unwrap(); + assert_eq!(m.source_set, expected, "wrong source set for {path}"); + } +} + +#[test] +fn python_imports_type_checking_resolution_and_workspaces() { + let src = [ + "from __future__ import annotations", + "from typing import TYPE_CHECKING", + "import os", + "from . import helpers", + "from demo.utils import run", + "if TYPE_CHECKING:", + " from demo.types import Widget", + "def entry():", + " return run(helpers)", + ] + .join("\n"); + let model = Python + .lower(&RepoPath::new("src/demo/main.py").unwrap(), &src) + .unwrap(); + assert_eq!( + model.runtime_imports, + [".helpers", "demo.utils", "os", "typing"] + ); + assert!( + model + .tokens + .iter() + .filter(|t| t.line <= 5 || t.line == 7) + .all(|t| t.kind == TokenKind::ImportOrExport) + ); + + let repo: Vec = [ + "pyproject.toml", + "src/demo/__init__.py", + "src/demo/main.py", + "src/demo/helpers.py", + "src/demo/utils.py", + ] + .into_iter() + .map(|p| RepoPath::new(p).unwrap()) + .collect(); + let resolutions = Python.resolve_imports( + &repo, + vec![Manifest { + path: "pyproject.toml".into(), + text: "[project]\nname = \"demo\"\n".into(), + }], + vec![ + ImportRequest { + importer: "src/demo/main.py".into(), + specifier: ".helpers".into(), + }, + ImportRequest { + importer: "src/demo/main.py".into(), + specifier: "demo.utils".into(), + }, + ImportRequest { + importer: "src/demo/main.py".into(), + specifier: "os".into(), + }, + ImportRequest { + importer: "src/demo/main.py".into(), + specifier: ".missing".into(), + }, + ], + ); + assert_eq!( + resolutions[0], + Resolution::Resolved("src/demo/helpers.py".into()) + ); + assert_eq!( + resolutions[1], + Resolution::Resolved("src/demo/utils.py".into()) + ); + assert_eq!(resolutions[2], Resolution::External); + assert!(matches!(resolutions[3], Resolution::Unresolved(_))); + + let packages = Python + .workspace_packages(vec![ + Manifest { + path: "pyproject.toml".into(), + text: "[tool.uv.workspace]\nmembers = [\"packages/*\"]\nexclude = [\"packages/ignored\"]\n".into(), + }, + Manifest { + path: "packages/core/pyproject.toml".into(), + text: "[project]\nname = \"core\"\n".into(), + }, + Manifest { + path: "packages/ignored/pyproject.toml".into(), + text: "[project]\nname = \"ignored\"\n".into(), + }, + ]) + .unwrap(); + assert_eq!(packages, [RepoPath::new("packages/core").unwrap()]); +} + +#[test] +fn python_verbosity_rules() { + let mut ids: Vec<_> = flagged_line_rules().collect(); + ids.sort_unstable(); + assert_eq!( + ids, + [ + "conditional-yields-boolean", + "else-after-return", + "except-only-reraises", + "if-else-returns-boolean", + "trailing-bare-return", + ] + ); + let cases = [ + ( + "else-after-return", + "def f(x):\n if x > 0:\n return 1\n else:\n return 2\n", + "def f(x):\n if x > 0:\n y = 1\n else:\n y = 2\n return y\n", + ), + ( + "if-else-returns-boolean", + "def f(x):\n if x > 0:\n return True\n else:\n return False\n", + "def f(x):\n if x > 0:\n return 1\n else:\n return 0\n", + ), + ( + "conditional-yields-boolean", + "def f(x):\n return True if x > 0 else False\n", + "def f(x):\n return 'a' if x > 0 else 'b'\n", + ), + ( + "except-only-reraises", + "def f():\n try:\n work()\n except ValueError as err:\n raise err\n", + "def f():\n try:\n work()\n except ValueError as err:\n log(err)\n raise\n", + ), + ( + "trailing-bare-return", + "def f():\n work()\n return None\n", + "def f(x):\n if x:\n return\n work()\n", + ), + ]; + for (rule, bad, good) in cases { + let bad_model = Python.lower(&RepoPath::new("a.py").unwrap(), bad).unwrap(); + let good_model = Python.lower(&RepoPath::new("b.py").unwrap(), good).unwrap(); + assert!(bad_model.flagged_lines.iter().any(|l| l.rule == rule)); + assert!(!good_model.flagged_lines.iter().any(|l| l.rule == rule)); + } +}